text
stringlengths
4
4.46M
id
stringlengths
13
126
metadata
dict
__index_level_0__
int64
0
415
-- mods/default/item_entity.lua local builtin_item = minetest.registered_entities["__builtin:item"] local item = { set_item = function(self, itemstring) builtin_item.set_item(self, itemstring) local stack = ItemStack(itemstring) local itemdef = minetest.registered_items[stack:get_name()] if itemdef and itemdef.groups.flammable ~= 0 then self.flammable = itemdef.groups.flammable end end, burn_up = function(self) -- disappear in a smoke puff self.object:remove() local p = self.object:get_pos() minetest.sound_play("default_item_smoke", { pos = p, max_hear_distance = 8, }) minetest.add_particlespawner({ amount = 3, time = 0.1, minpos = {x = p.x - 0.1, y = p.y + 0.1, z = p.z - 0.1 }, maxpos = {x = p.x + 0.1, y = p.y + 0.2, z = p.z + 0.1 }, minvel = {x = 0, y = 2.5, z = 0}, maxvel = {x = 0, y = 2.5, z = 0}, minacc = {x = -0.15, y = -0.02, z = -0.15}, maxacc = {x = 0.15, y = -0.01, z = 0.15}, minexptime = 4, maxexptime = 6, minsize = 5, maxsize = 5, collisiondetection = true, texture = "default_item_smoke.png" }) end, on_step = function(self, dtime, ...) builtin_item.on_step(self, dtime, ...) if self.flammable then -- flammable, check for igniters self.ignite_timer = (self.ignite_timer or 0) + dtime if self.ignite_timer > 10 then self.ignite_timer = 0 local node = minetest.get_node_or_nil(self.object:get_pos()) if not node then return end -- Immediately burn up flammable items in lava if minetest.get_item_group(node.name, "lava") > 0 then self:burn_up() else -- otherwise there'll be a chance based on its igniter value local burn_chance = self.flammable * minetest.get_item_group(node.name, "igniter") if burn_chance > 0 and math.random(0, burn_chance) ~= 0 then self:burn_up() end end end end end, } -- set defined item as new __builtin:item, with the old one as fallback table setmetatable(item, builtin_item) minetest.register_entity(":__builtin:item", item)
QiskitBlocks/qiskitblocks/mods/default/item_entity.lua/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/default/item_entity.lua", "repo_id": "QiskitBlocks", "token_count": 920 }
0
-- mods/default/tools.lua -- The hand minetest.register_item(":", { type = "none", wield_image = "wieldhand.png", wield_scale = {x=1,y=1,z=2.5}, tool_capabilities = { full_punch_interval = 0.9, max_drop_level = 0, groupcaps = { crumbly = {times={[2]=3.00, [3]=0.70}, uses=0, maxlevel=1}, snappy = {times={[3]=0.40}, uses=0, maxlevel=1}, oddly_breakable_by_hand = {times={[1]=3.50,[2]=2.00,[3]=0.70}, uses=0} }, damage_groups = {fleshy=1}, } }) -- -- Picks -- minetest.register_tool("default:pick_wood", { description = "Wooden Pickaxe", inventory_image = "default_tool_woodpick.png", tool_capabilities = { full_punch_interval = 1.2, max_drop_level=0, groupcaps={ cracky = {times={[3]=1.60}, uses=10, maxlevel=1}, }, damage_groups = {fleshy=2}, }, groups = {flammable = 2}, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:pick_stone", { description = "Stone Pickaxe", inventory_image = "default_tool_stonepick.png", tool_capabilities = { full_punch_interval = 1.3, max_drop_level=0, groupcaps={ cracky = {times={[2]=2.0, [3]=1.00}, uses=20, maxlevel=1}, }, damage_groups = {fleshy=3}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:pick_bronze", { description = "Bronze Pickaxe", inventory_image = "default_tool_bronzepick.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ cracky = {times={[1]=4.50, [2]=1.80, [3]=0.90}, uses=20, maxlevel=2}, }, damage_groups = {fleshy=4}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:pick_steel", { description = "Steel Pickaxe", inventory_image = "default_tool_steelpick.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ cracky = {times={[1]=4.00, [2]=1.60, [3]=0.80}, uses=20, maxlevel=2}, }, damage_groups = {fleshy=4}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:pick_mese", { description = "Mese Pickaxe", inventory_image = "default_tool_mesepick.png", tool_capabilities = { full_punch_interval = 0.9, max_drop_level=3, groupcaps={ cracky = {times={[1]=2.4, [2]=1.2, [3]=0.60}, uses=20, maxlevel=3}, }, damage_groups = {fleshy=5}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:pick_diamond", { description = "Diamond Pickaxe", inventory_image = "default_tool_diamondpick.png", tool_capabilities = { full_punch_interval = 0.9, max_drop_level=3, groupcaps={ cracky = {times={[1]=2.0, [2]=1.0, [3]=0.50}, uses=30, maxlevel=3}, }, damage_groups = {fleshy=5}, }, sound = {breaks = "default_tool_breaks"}, }) -- -- Shovels -- minetest.register_tool("default:shovel_wood", { description = "Wooden Shovel", inventory_image = "default_tool_woodshovel.png", wield_image = "default_tool_woodshovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.2, max_drop_level=0, groupcaps={ crumbly = {times={[1]=3.00, [2]=1.60, [3]=0.60}, uses=10, maxlevel=1}, }, damage_groups = {fleshy=2}, }, groups = {flammable = 2}, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:shovel_stone", { description = "Stone Shovel", inventory_image = "default_tool_stoneshovel.png", wield_image = "default_tool_stoneshovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.4, max_drop_level=0, groupcaps={ crumbly = {times={[1]=1.80, [2]=1.20, [3]=0.50}, uses=20, maxlevel=1}, }, damage_groups = {fleshy=2}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:shovel_bronze", { description = "Bronze Shovel", inventory_image = "default_tool_bronzeshovel.png", wield_image = "default_tool_bronzeshovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.1, max_drop_level=1, groupcaps={ crumbly = {times={[1]=1.65, [2]=1.05, [3]=0.45}, uses=25, maxlevel=2}, }, damage_groups = {fleshy=3}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:shovel_steel", { description = "Steel Shovel", inventory_image = "default_tool_steelshovel.png", wield_image = "default_tool_steelshovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.1, max_drop_level=1, groupcaps={ crumbly = {times={[1]=1.50, [2]=0.90, [3]=0.40}, uses=30, maxlevel=2}, }, damage_groups = {fleshy=3}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:shovel_mese", { description = "Mese Shovel", inventory_image = "default_tool_meseshovel.png", wield_image = "default_tool_meseshovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=3, groupcaps={ crumbly = {times={[1]=1.20, [2]=0.60, [3]=0.30}, uses=20, maxlevel=3}, }, damage_groups = {fleshy=4}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:shovel_diamond", { description = "Diamond Shovel", inventory_image = "default_tool_diamondshovel.png", wield_image = "default_tool_diamondshovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ crumbly = {times={[1]=1.10, [2]=0.50, [3]=0.30}, uses=30, maxlevel=3}, }, damage_groups = {fleshy=4}, }, sound = {breaks = "default_tool_breaks"}, }) -- -- Axes -- minetest.register_tool("default:axe_wood", { description = "Wooden Axe", inventory_image = "default_tool_woodaxe.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=0, groupcaps={ choppy = {times={[2]=3.00, [3]=1.60}, uses=10, maxlevel=1}, }, damage_groups = {fleshy=2}, }, groups = {flammable = 2}, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:axe_stone", { description = "Stone Axe", inventory_image = "default_tool_stoneaxe.png", tool_capabilities = { full_punch_interval = 1.2, max_drop_level=0, groupcaps={ choppy={times={[1]=3.00, [2]=2.00, [3]=1.30}, uses=20, maxlevel=1}, }, damage_groups = {fleshy=3}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:axe_bronze", { description = "Bronze Axe", inventory_image = "default_tool_bronzeaxe.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ choppy={times={[1]=2.75, [2]=1.70, [3]=1.15}, uses=20, maxlevel=2}, }, damage_groups = {fleshy=4}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:axe_steel", { description = "Steel Axe", inventory_image = "default_tool_steelaxe.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ choppy={times={[1]=2.50, [2]=1.40, [3]=1.00}, uses=20, maxlevel=2}, }, damage_groups = {fleshy=4}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:axe_mese", { description = "Mese Axe", inventory_image = "default_tool_meseaxe.png", tool_capabilities = { full_punch_interval = 0.9, max_drop_level=1, groupcaps={ choppy={times={[1]=2.20, [2]=1.00, [3]=0.60}, uses=20, maxlevel=3}, }, damage_groups = {fleshy=6}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:axe_diamond", { description = "Diamond Axe", inventory_image = "default_tool_diamondaxe.png", tool_capabilities = { full_punch_interval = 0.9, max_drop_level=1, groupcaps={ choppy={times={[1]=2.10, [2]=0.90, [3]=0.50}, uses=30, maxlevel=3}, }, damage_groups = {fleshy=7}, }, sound = {breaks = "default_tool_breaks"}, }) -- -- Swords -- minetest.register_tool("default:sword_wood", { description = "Wooden Sword", inventory_image = "default_tool_woodsword.png", tool_capabilities = { full_punch_interval = 1, max_drop_level=0, groupcaps={ snappy={times={[2]=1.6, [3]=0.40}, uses=10, maxlevel=1}, }, damage_groups = {fleshy=2}, }, groups = {flammable = 2}, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:sword_stone", { description = "Stone Sword", inventory_image = "default_tool_stonesword.png", tool_capabilities = { full_punch_interval = 1.2, max_drop_level=0, groupcaps={ snappy={times={[2]=1.4, [3]=0.40}, uses=20, maxlevel=1}, }, damage_groups = {fleshy=4}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:sword_bronze", { description = "Bronze Sword", inventory_image = "default_tool_bronzesword.png", tool_capabilities = { full_punch_interval = 0.8, max_drop_level=1, groupcaps={ snappy={times={[1]=2.75, [2]=1.30, [3]=0.375}, uses=25, maxlevel=2}, }, damage_groups = {fleshy=6}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:sword_steel", { description = "Steel Sword", inventory_image = "default_tool_steelsword.png", tool_capabilities = { full_punch_interval = 0.8, max_drop_level=1, groupcaps={ snappy={times={[1]=2.5, [2]=1.20, [3]=0.35}, uses=30, maxlevel=2}, }, damage_groups = {fleshy=6}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:sword_mese", { description = "Mese Sword", inventory_image = "default_tool_mesesword.png", tool_capabilities = { full_punch_interval = 0.7, max_drop_level=1, groupcaps={ snappy={times={[1]=2.0, [2]=1.00, [3]=0.35}, uses=30, maxlevel=3}, }, damage_groups = {fleshy=7}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:sword_diamond", { description = "Diamond Sword", inventory_image = "default_tool_diamondsword.png", tool_capabilities = { full_punch_interval = 0.7, max_drop_level=1, groupcaps={ snappy={times={[1]=1.90, [2]=0.90, [3]=0.30}, uses=40, maxlevel=3}, }, damage_groups = {fleshy=8}, }, sound = {breaks = "default_tool_breaks"}, }) minetest.register_tool("default:key", { description = "Key", inventory_image = "default_key.png", groups = {key = 1, not_in_creative_inventory = 1}, stack_max = 1, on_place = function(itemstack, placer, pointed_thing) local under = pointed_thing.under local node = minetest.get_node(under) local def = minetest.registered_nodes[node.name] if def and def.on_rightclick and not (placer and placer:is_player() and placer:get_player_control().sneak) then return def.on_rightclick(under, node, placer, itemstack, pointed_thing) or itemstack end if pointed_thing.type ~= "node" then return itemstack end local pos = pointed_thing.under node = minetest.get_node(pos) if not node or node.name == "ignore" then return itemstack end local ndef = minetest.registered_nodes[node.name] if not ndef then return itemstack end local on_key_use = ndef.on_key_use if on_key_use then on_key_use(pos, placer) end return nil end })
QiskitBlocks/qiskitblocks/mods/default/tools.lua/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/default/tools.lua", "repo_id": "QiskitBlocks", "token_count": 4671 }
1
# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-07-29 09:13+0200\n" "PO-Revision-Date: 2017-07-29 09:20+0200\n" "Language-Team: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: Poedit 1.8.12\n" "Last-Translator: fat115 <[email protected]>\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" "Language: fr\n" #: api.lua msgid "** Peaceful Mode Active - No Monsters Will Spawn" msgstr "** Mode pacifique activé - Aucun monstre ne sera généré" #: api.lua msgid "Mob has been protected!" msgstr "L'animal a été protégé !" #: api.lua msgid "@1 (Tamed)" msgstr "@1 (apprivoisé)" #: api.lua msgid "Not tamed!" msgstr "Non-apprivoisé !" #: api.lua msgid "@1 is owner!" msgstr "Appartient à @1 !" #: api.lua msgid "Missed!" msgstr "Raté !" #: api.lua msgid "Already protected!" msgstr "Déjà protégé !" #: api.lua msgid "@1 at full health (@2)" msgstr "@1 est en pleine forme (@2) " #: api.lua msgid "@1 has been tamed!" msgstr "@1 a été apprivoisé ! " #: api.lua msgid "Enter name:" msgstr "Saisissez un nom :" #: api.lua msgid "Rename" msgstr "Renommer" #: crafts.lua msgid "Name Tag" msgstr "Étiquette pour collier" #: crafts.lua msgid "Leather" msgstr "Cuir" #: crafts.lua msgid "Raw Meat" msgstr "Viande crue" #: crafts.lua msgid "Meat" msgstr "Viande" #: crafts.lua msgid "Lasso (right-click animal to put in inventory)" msgstr "Lasso (clic droit sur l'animal pour le mettre dans l'inventaire)" #: crafts.lua msgid "Net (right-click animal to put in inventory)" msgstr "Filet (clic droit sur l'animal pour le mettre dans l'inventaire)" #: crafts.lua msgid "Steel Shears (right-click to shear)" msgstr "Ciseaux à laine (clic droit pour tondre)" #: crafts.lua msgid "Mob Protection Rune" msgstr "Rune de protection des animaux" #: crafts.lua msgid "Saddle" msgstr "Selle" #: crafts.lua msgid "Mob Fence" msgstr "Clôture à animaux" #: spawner.lua msgid "Mob Spawner" msgstr "Générateur de mob" #: spawner.lua msgid "Mob MinLight MaxLight Amount PlayerDist" msgstr "Mob MinLumière MaxLumière Quantité DistanceJoueur" #: spawner.lua msgid "Spawner Not Active (enter settings)" msgstr "Générateur non actif (entrez les paramètres)" #: spawner.lua msgid "Spawner Active (@1)" msgstr "Générateur actif (@1)" #: spawner.lua msgid "Mob Spawner settings failed!" msgstr "Echec des paramètres du générateur" #: spawner.lua msgid "" "Syntax: “name min_light[0-14] max_light[0-14] max_mobs_in_area[0 to disable] " "distance[1-20] y_offset[-10 to 10]”" msgstr "Syntaxe : “nom min_lumière[0-14] max_lumière[0-14] max_mobs_dans_zone[0 pour désactiver] distance[1-20] décalage_y[-10 à 10]“"
QiskitBlocks/qiskitblocks/mods/mobs_redo/locale/fr.po/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/mobs_redo/locale/fr.po", "repo_id": "QiskitBlocks", "token_count": 1209 }
2
local S = mobs.intllib -- mob spawner local spawner_default = "mobs_animal:pumba 10 15 0 0" minetest.register_node("mobs:spawner", { tiles = {"mob_spawner.png"}, drawtype = "glasslike", paramtype = "light", walkable = true, description = S("Mob Spawner"), groups = {cracky = 1}, on_construct = function(pos) local meta = minetest.get_meta(pos) -- text entry formspec meta:set_string("formspec", "field[text;" .. S("Mob MinLight MaxLight Amount PlayerDist") .. ";${command}]") meta:set_string("infotext", S("Spawner Not Active (enter settings)")) meta:set_string("command", spawner_default) end, on_right_click = function(pos, placer) if minetest.is_protected(pos, placer:get_player_name()) then return end end, on_receive_fields = function(pos, formname, fields, sender) if not fields.text or fields.text == "" then return end local meta = minetest.get_meta(pos) local comm = fields.text:split(" ") local name = sender:get_player_name() if minetest.is_protected(pos, name) then minetest.record_protection_violation(pos, name) return end local mob = comm[1] -- mob to spawn local mlig = tonumber(comm[2]) -- min light local xlig = tonumber(comm[3]) -- max light local num = tonumber(comm[4]) -- total mobs in area local pla = tonumber(comm[5]) -- player distance (0 to disable) local yof = tonumber(comm[6]) or 0 -- Y offset to spawn mob if mob and mob ~= "" and mobs.spawning_mobs[mob] == true and num and num >= 0 and num <= 10 and mlig and mlig >= 0 and mlig <= 15 and xlig and xlig >= 0 and xlig <= 15 and pla and pla >=0 and pla <= 20 and yof and yof > -10 and yof < 10 then meta:set_string("command", fields.text) meta:set_string("infotext", S("Spawner Active (@1)", mob)) else minetest.chat_send_player(name, S("Mob Spawner settings failed!")) minetest.chat_send_player(name, S("Syntax: “name min_light[0-14] max_light[0-14] max_mobs_in_area[0 to disable] distance[1-20] y_offset[-10 to 10]”")) end end, }) local max_per_block = tonumber(minetest.settings:get("max_objects_per_block") or 99) -- spawner abm minetest.register_abm({ label = "Mob spawner node", nodenames = {"mobs:spawner"}, interval = 10, chance = 4, catch_up = false, action = function(pos, node, active_object_count, active_object_count_wider) -- return if too many entities already if active_object_count_wider >= max_per_block then return end -- get meta and command local meta = minetest.get_meta(pos) local comm = meta:get_string("command"):split(" ") -- get settings from command local mob = comm[1] local mlig = tonumber(comm[2]) local xlig = tonumber(comm[3]) local num = tonumber(comm[4]) local pla = tonumber(comm[5]) or 0 local yof = tonumber(comm[6]) or 0 -- if amount is 0 then do nothing if num == 0 then return end -- are we spawning a registered mob? if not mobs.spawning_mobs[mob] then --print ("--- mob doesn't exist", mob) return end -- check objects inside 9x9 area around spawner local objs = minetest.get_objects_inside_radius(pos, 9) local count = 0 local ent = nil -- count mob objects of same type in area for k, obj in ipairs(objs) do ent = obj:get_luaentity() if ent and ent.name and ent.name == mob then count = count + 1 end end -- is there too many of same type? if count >= num then return end -- spawn mob if player detected and in range if pla > 0 then local in_range = 0 local objs = minetest.get_objects_inside_radius(pos, pla) for _,oir in pairs(objs) do if oir:is_player() then in_range = 1 break end end -- player not found if in_range == 0 then return end end -- find air blocks within 5 nodes of spawner local air = minetest.find_nodes_in_area( {x = pos.x - 5, y = pos.y + yof, z = pos.z - 5}, {x = pos.x + 5, y = pos.y + yof, z = pos.z + 5}, {"air"}) -- spawn in random air block if air and #air > 0 then local pos2 = air[math.random(#air)] local lig = minetest.get_node_light(pos2) or 0 pos2.y = pos2.y + 0.5 -- only if light levels are within range if lig >= mlig and lig <= xlig and minetest.registered_entities[mob] then minetest.add_entity(pos2, mob) end end end })
QiskitBlocks/qiskitblocks/mods/mobs_redo/spawner.lua/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/mobs_redo/spawner.lua", "repo_id": "QiskitBlocks", "token_count": 1707 }
3
--[[ Copyright 2019 the original author or authors. 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. --]] --[[ Elements of the q_command table that supply information about areas in the game --]] -- The portal room ------------------------------------------------ q_command.areas.portal_room = {} q_command.areas.portal_room.help_btn_text = {} q_command.areas.portal_room.help_btn_text.en = [[ Welcome to the portal room, where you can teleport to other areas of this world such as escape room levels. After entering a portal, you may return to this room by entering an orange portal. ]] q_command.areas.portal_room.help_btn_text.es = q_command.areas.portal_room.help_btn_text.en q_command.areas.portal_room.help_btn_text.ja = q_command.areas.portal_room.help_btn_text.en q_command.areas.portal_room.help_btn_caption = {} q_command.areas.portal_room.help_btn_caption.en = "The portal room" q_command.areas.portal_room.help_btn_caption.es = q_command.areas.portal_room.help_btn_caption.en q_command.areas.portal_room.help_btn_caption.ja = q_command.areas.portal_room.help_btn_caption.en -- END The portal room --------------------------------------------
QiskitBlocks/qiskitblocks/mods/q_command/q_portal_room.lua/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/q_command/q_portal_room.lua", "repo_id": "QiskitBlocks", "token_count": 505 }
4
local dyes = { {"white", "White"}, {"grey", "Grey"}, {"black", "Black"}, {"red", "Red"}, {"yellow", "Yellow"}, {"green", "Green"}, {"cyan", "Cyan"}, {"blue", "Blue"}, {"magenta", "Magenta"}, {"orange", "Orange"}, {"violet", "Violet"}, {"brown", "Brown"}, {"pink", "Pink"}, {"dark_grey", "Dark Grey"}, {"dark_green", "Dark Green"}, } for i = 1, #dyes do local name, desc = unpack(dyes[i]) minetest.register_node("wool:" .. name, { description = desc .. " Wool", tiles = {"wool_" .. name .. ".png"}, is_ground_content = false, groups = {snappy = 2, choppy = 2, oddly_breakable_by_hand = 3, flammable = 3, wool = 1}, sounds = default.node_sound_defaults(), }) minetest.register_craft{ type = "shapeless", output = "wool:" .. name, recipe = {"group:dye,color_" .. name, "group:wool"}, } end -- Legacy -- Backwards compatibility with jordach's 16-color wool mod minetest.register_alias("wool:dark_blue", "wool:blue") minetest.register_alias("wool:gold", "wool:yellow")
QiskitBlocks/qiskitblocks/mods/wool/init.lua/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/wool/init.lua", "repo_id": "QiskitBlocks", "token_count": 471 }
5
<jupyter_start><jupyter_text>IBM Q setupThis tutorial will walk you through the configuration for your IBM Q Experience account so that, in the future, you are able to run your Quantum Programs in both online simulators as well as real Quantum Computers.We assume you have installed Qiskit if not please look at [qiskit.org](http://www.qiskit.org) or the install [documentation](https://github.com/qiskit/qiskit-tutorial/blob/master/INSTALL.md). To test this run the following commands<jupyter_code>import qiskit<jupyter_output><empty_output><jupyter_text>Execute on a Real Device (IBM Q Experience)You can use Qiskit to run your circuits on real quantum computers using the IBMQ provider. They are small and noisy but are advancing at a fast pace. In the future, more information will be given regarding this environment, but for now lets go ahead and set it up!To access IBMQ devices, you'll need an API token. For the public Quantum Experience devices, you can generate an API token [here](https://quantumexperience.ng.bluemix.net/qx/account/advanced) (create an account if you don't already have one). For Q Network devices, login to the q-console, click your hub, group, and project, and expand "Get Access" to generate your API token and access url.<jupyter_code>from qiskit import IBMQ # requires qiskit version >= 0.6<jupyter_output><empty_output><jupyter_text>After generating your API token, call:<jupyter_code>IBMQ.save_account("MY_TOKEN")<jupyter_output><empty_output><jupyter_text>For Q Network users, you'll also need to include your access url:`IBMQ.save_account('MY_TOKEN', 'URL')`This will store your IBMQ credentials in a local file. Unless your registration information has changed, you only need to do this once. You may now (or in any other exercise) load your accounts by calling:<jupyter_code>IBMQ.load_accounts()<jupyter_output><empty_output><jupyter_text>Which Backends are available right now?A backend is either an online Quantum simulator or a Quantum Computer.This is how you can list them by name:<jupyter_code>for backend in IBMQ.backends(): print(backend)<jupyter_output>ibmqx4 ibmqx5 ibmqx2 ibmq_16_melbourne ibmq_qasm_simulator<jupyter_text>Additionally, you can get all of their configurations, like so:<jupyter_code>backend_0 = IBMQ.backends()[0] # retrieve the Backend at index 0 print(backend_0.configuration()) print("Go check its specification at %s" % backend_0.configuration()["url"])<jupyter_output>Go check its specification at https://ibm.biz/qiskit-ibmqx4
Teach-Me-Quantum/Week 1 - Quantum Tools/exercises/IBMQ_setup.ipynb/0
{ "file_path": "Teach-Me-Quantum/Week 1 - Quantum Tools/exercises/IBMQ_setup.ipynb", "repo_id": "Teach-Me-Quantum", "token_count": 748 }
6
\documentclass[aspectratio=43]{beamer} \usepackage[utf8]{inputenc} %%%%%%%%%%%%%%%%%%%%%%%% THEME \usetheme{material} \useLightTheme \usePrimaryDeepOrange \useAccentCyan \usepackage{macros} % must come after theme \title{\qis} \keywords{\qis} \begin{document} \begin{frame} \titlepage \end{frame} \begin{frame}{Table of contents} \begin{card} \tableofcontents \end{card} \end{frame} \section{Introduction} \begin{frame}{Introduction} \begin{card} This week we are going to build the bridge between \textbf{\qm} and \textbf{\qc}, in other words, how the \q laws can be leveraged into the tools we need for, well, computing! This will be done through a parallelism with \cc. \\ Furthermore, we will also go through our first \textbf{\qk snippets} and finish of by running our first \q circuit on a \textbf{real Quantum Processor}, using \ibmqe. \qasm language will also be briefly mentioned as a tool for this course. \end{card} \pagenumber \end{frame} \section{\qis} \begin{frame}{\qis} \begin{card} Is a broad area of studies, it is the \q sibling of typical information science. It is concerned with \textbf{representing}, \textbf{manipulating} and \textbf{maintaining} information in quantum states. It tackles many problems that did not exist, at least in the same form, in \cc, such as \textit{quantum error correction}, \textit{quantum teleportation}, \textit{quantum communication}, ... \end{card} \pagenumber \end{frame} \section{Classical bits} \begin{frame}{Classical bits} \begin{card} The simplest unit of information in classical systems, a bit (short for binary unit), which can store either a 0 or a 1 value, thus binary. \end{card} \begin{card} There is quite an interesting metaphor for explaining the difference between bits and their quantum equivalent, based on the concept of coin tossing, from which we will start! \end{card} \pagenumber \end{frame} \begin{frame}{Coin tossing for bits} \begin{multicols}{2} [ \begin{cardTiny} When you toss a coin, the result will either be tails or heads - 0 or 1 (please try not to think of the cases of a vertical landing until you can do it). This is a binary and deterministic state. \end{cardTiny} ] \begin{center} \includegraphics[width=0.2\textwidth]{escudo_tails} \\Tails = 0 \end{center} \begin{center} \includegraphics[width=0.2\textwidth]{escudo_heads} \\Heads = 1 \end{center} \end{multicols} \begin{cardTiny} \textbf{classical register:} is an array of n independent bits. A 1-bit register is simply a bit and can be in 1 out of $2^1 = 2$ possible states, whereas an 8-bit register can be in 1 out of $2^8 = 256$ states. \end{cardTiny} \pagenumber \end{frame} \section{\q bits} \subsection{qubits} % https://twitter.com/drtaliagershon?lang=en % include qiskit snippets of both code parts \begin{frame}{qubit} \begin{card} Assuming you have a quantum state (isolated from interference) that has not been measured. If we refer back to the 2 possible states from Week 0, we know our state is a combination of both 0 and 1, remember? \begin{equation*} \superpos \end{equation*} But what does this mean, exactly? Well, that our system is not in just one of the states (assuming $\alpha \neq 0 \wedge \beta \neq 0$), it holds the information of both possible states, at the same time. \end{card} \pagenumber \end{frame} \begin{frame}{Coin tossing for qubits} \begin{card} And so, instead of heads or tails, we can compare this state to a coin that is still spinning. Such is the essence of the qubit, a simultaneous state of 0 and 1 (described according to the probability distribution of $\alpha$ and $\beta$). Notice that the state is not hidden according to the probabilities, but rather comprised of both possibilities! \end{card} \begin{center} \includegraphics[width=0.2\textwidth]{spinning_coin} \\$\superpos$ \end{center} \pagenumber \end{frame} \begin{frame}{qubit} \begin{card} Unlike a bit, we now have a single quantum state with two simultaneous states. Why does this matter? Because this uncertainty contains in itself much more than a deterministic bit, so that when we perform operations, they are applied to all possible states and not just the one. \end{card} \begin{cardTiny} \textbf{\q register:} is an array of n qubits. A 1-bit quantum register is simply a qubit and can hold $2^1 = 2$ possible states, whereas an 8-qubit quantum register can hold $2^8 = 256$ states, not just 1 of them like classical registers, all of them!! \end{cardTiny} \pagenumber \end{frame} \begin{frame}{Coin tossing metaphor} \begin{cardTiny} If we have one coin, the state \textbf{can be} 0 or 1. \end{cardTiny} \begin{center} \includegraphics[width=0.2\textwidth]{escudo_tails}\\ \includegraphics[width=0.1\textwidth]{escudo_tails} \includegraphics[width=0.1\textwidth]{escudo_tails}\\ \includegraphics[width=0.1\textwidth]{escudo_tails} \includegraphics[width=0.1\textwidth]{escudo_tails} \includegraphics[width=0.1\textwidth]{escudo_tails}\\... \end{center} \pagenumber \end{frame} \begin{frame}{Coin tossing metaphor} \begin{cardTiny} If we have two coins,the state \textbf{can be} 00 or 01 or 10 or 11. \end{cardTiny} \begin{center} \includegraphics[width=0.1\textwidth]{escudo_tails}\\ \includegraphics[width=0.2\textwidth]{escudo_tails} \includegraphics[width=0.2\textwidth]{escudo_tails}\\ \includegraphics[width=0.1\textwidth]{escudo_tails} \includegraphics[width=0.1\textwidth]{escudo_tails} \includegraphics[width=0.1\textwidth]{escudo_tails}\\... \end{center} \pagenumber \end{frame} \begin{frame}{Coin tossing metaphor} \begin{cardTiny} If we have three coins,the state \textbf{can be} 000 or 001 or 010 or 011 or 100 or 101 or 110 or 111. \end{cardTiny} \begin{center} \includegraphics[width=0.1\textwidth]{escudo_tails}\\ \includegraphics[width=0.1\textwidth]{escudo_tails} \includegraphics[width=0.1\textwidth]{escudo_tails}\\ \includegraphics[width=0.2\textwidth]{escudo_tails} \includegraphics[width=0.2\textwidth]{escudo_tails} \includegraphics[width=0.2\textwidth]{escudo_tails}\\... \end{center} \pagenumber \end{frame} \begin{frame}{Coin tossing metaphor} \begin{card} Essentially if we have \textbf{n} coins, we can have 1 of the \textbf{$2^n$} possible states.\\ For n=4 ($2^4=16$ possible states), 1010 would be: \end{card} \begin{center} \includegraphics[width=0.2\textwidth]{escudo_heads} \includegraphics[width=0.2\textwidth]{escudo_tails} \includegraphics[width=0.2\textwidth]{escudo_heads} \includegraphics[width=0.2\textwidth]{escudo_tails} \end{center} \pagenumber \end{frame} %%%%%Qubit coins \begin{frame}{Coin tossing metaphor} \begin{cardTiny} If we have one spinning coin, the state \textbf{is} 0 and 1. \end{cardTiny} \begin{center} \includegraphics[width=0.2\textwidth]{spinning_coin}\\ \includegraphics[width=0.1\textwidth]{spinning_coin} \includegraphics[width=0.1\textwidth]{spinning_coin}\\ \includegraphics[width=0.1\textwidth]{spinning_coin} \includegraphics[width=0.1\textwidth]{spinning_coin} \includegraphics[width=0.1\textwidth]{spinning_coin}\\... \end{center} \pagenumber \end{frame} \begin{frame}{Coin tossing metaphor} \begin{cardTiny} If we have two (independent) spinning coins, the state \textbf{is} 00 and 01 and 10 and 11. \end{cardTiny} \begin{center} \includegraphics[width=0.1\textwidth]{spinning_coin}\\ \includegraphics[width=0.2\textwidth]{spinning_coin} \includegraphics[width=0.2\textwidth]{spinning_coin}\\ \includegraphics[width=0.1\textwidth]{spinning_coin} \includegraphics[width=0.1\textwidth]{spinning_coin} \includegraphics[width=0.1\textwidth]{spinning_coin}\\... \end{center} \pagenumber \end{frame} \begin{frame}{Coin tossing metaphor} \begin{cardTiny} If we have three (independent) spinning coins, the state \textbf{is} 000 and 001 and 010 and 011 and 100 and 101 and 110 and 111. \end{cardTiny} \begin{center} \includegraphics[width=0.1\textwidth]{spinning_coin}\\ \includegraphics[width=0.1\textwidth]{spinning_coin} \includegraphics[width=0.1\textwidth]{spinning_coin}\\ \includegraphics[width=0.2\textwidth]{spinning_coin} \includegraphics[width=0.2\textwidth]{spinning_coin} \includegraphics[width=0.2\textwidth]{spinning_coin}\\... \end{center} \pagenumber \end{frame} \begin{frame}{Coin tossing metaphor} \begin{card} Essentially if we have \textbf{n} (independent) spinning coins, we can have \textbf{$2^n$} possible states simultaneously.\\ For $n=4$ our state holds $2^4=16$ possibilities. The information we can have grows \textbf{exponentially} with the number of spinning coins or, let me unveil the curtain, qubits! Such is the power of the qubit, and this "supercharged" version of the bit will help us understand why \qc really tips the scales. \end{card} \pagenumber \end{frame} \subsection{qudits} \begin{frame}{qudits} \begin{card}[Curiosity*] As the bits also have higher order units (\href{https://en.wikipedia.org/wiki/Ternary_numeral_system}{trit} for a ternary state, ...) so does the qubit have its d-order equivalent: the \textbf{qudit} (quantum d-git).\\ For the initial case of the hydrogen atom, we could simply consider it as having 3 possible orbits, thus $\ket{0}$, $\ket{1}$ and $\ket{2}$ (a qudit with $d=3$ is actually a qutrit - quantum trit).\\ Nevertheless, we will not spend much time with these units as their use is not so straightforward, and once you master qubits, it is easier to extrapolate to other arities than the other way around! \end{card} \pagenumber \end{frame} \section{Hands-on} \begin{frame}[fragile]{Hands-on - Registers} Let us now write some python that will follow us through many lessons to come.\\ Here's how to create a \href{https://qiskit.org/documentation/_autodoc/qiskit._classicalregister.html?highlight=classicalregister#module-qiskit._classicalregister}{ClassicalRegister} on \qk: \begin{cardTiny} \begin{minted}{python} from qiskit import ClassicalRegister # Create a Classical Register with 2 bits. c = ClassicalRegister(2) \end{minted} \end{cardTiny} %%%%%%% Likewise for \href{https://qiskit.org/documentation/_autodoc/qiskit._quantumregister.html?highlight=quantumregister#module-qiskit._quantumregister}{QuantumRegister}: \begin{cardTiny} \begin{minted}{python} from qiskit import QuantumRegister # Create a Quantum Register with 2 qubits. q = QuantumRegister(2) \end{minted} \end{cardTiny} For our purpose, classical registers will serve only to save the results of measurements on qubits. \end{frame} \begin{frame}[fragile]{Hands-on - Quantum Circuit} To connect our classical and quantum registers in a \href{https://qiskit.org/documentation/_autodoc/qiskit._quantumcircuit.html#qiskit._quantumcircuit.QuantumCircuit}{QuantumCircuit} we do: \begin{cardTiny} \begin{minted}{python} from qiskit import QuantumCircuit # Create a Quantum Circuit qc = QuantumCircuit(q, c) # perform a measurement of our qubits into our bits qc.measure(q, c) \end{minted} \end{cardTiny} What we can do so far is quite limited, but these are the building blocks we need. In the next lesson we will take a look at the operations that can happen before we measure a quantum circuit! \end{frame} \begin{frame}[fragile]{Hands-on - Quantum Circuit Visualization} Here is the code for visualizing our mighty complex circuit: \begin{cardTiny} \begin{minted}{python} from qiskit.tools.visualization import matplotlib_circuit_drawer as draw draw(qc) # visualize our quantum circuit \end{minted} \end{cardTiny} \begin{center} \includegraphics[width=0.25\textwidth]{circuit_01_measurement} \end{center} \small{ You will notice that both qubits ($q0_0$ and $q0_1$) are initially in state $\ket{0}$ meaning that $\beta=0$ in $\superpos$ (what do you think $\alpha=$?). This is by design and how most experiments begin. The symbol connecting the qubit to each bit is the universal symbol for quantum measurement. } \end{frame} \section{\qasm} \begin{frame}[fragile]{\qasm} \begin{cardTiny} \small{ \qasm derives from `Open Quantum Assembly Language' and reads `kazm'. This is a rather recent invention, coming of of a \href{https://arxiv.org/abs/1707.03429}{2017 paper}. It is a descriptive language that maps a quantum circuit as text instructions. It has since became a standard and, although we will not be going deeper into it, it is good to understand the overall structure of these documents, here is the example for the above circuit (q0 was changed into q, and c0 to c due to some \qasm interpreters): } \end{cardTiny} \begin{cardTiny} \begin{minted}{vhdl} % since qasm is not yet supported OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[2]; x q[0]; measure q[0] -> c[0]; measure q[1] -> c[1]; \end{minted} \end{cardTiny} \end{frame} %https://quantumexperience.ng.bluemix.net/qx/editor \begin{frame}[fragile]{QASM + \ibmqe exercise} \small{ \href{https://quantumexperience.ng.bluemix.net/qx/experience}{\ibmqe} supports QASM in their online editor, and you can literally use a GUI and check the \qasm equivalent (and vice versa). Your task is to go to the \href{https://quantumexperience.ng.bluemix.net/qx/editor}{editor} and do the following: \begin{itemize} \itemsep0em \item Login into \ibmqe \item Click on "New" for a new experiment \item Name it as you like (eg. "qasm\_test") \item Choose ibmqx2 or ibmqx4 (look for available) \item Click on "Switch to \qasm editor" \item Paste the above \qasm code and see the visual result \item Press "Simulate" and see the result (should be $00$ with $1.000$ frequency, this means that out of all the repetitions of the experiment, $100\%$ resulted in $00$). \item Go ahead and press "Run" and, just for this once, ignore if there is a cached version and choose "New Execution"! \end{itemize} You just executed instructions on a \q Computer, you will receive an email with the results (may be more queued jobs ahead of you). } \end{frame} \begin{frame}{\qk exercise} \begin{card} The code provided here has been written to a \href{\weekTwo/exercises/w2_01.ipynb}{Jupyter Notebook} that you are encouraged to execute on your machine, as that exercise will help you understand \qk from the beginning. There is also a code sample for generating the \qasm instructions and, at the end of the notebook, there are more suggested exercises. This, along with the previous slide on testing \ibmqe are your tasks for the week. Feel free, of course, to take some extra steps and trying out new stuff on your version of the notebook! \end{card} \pagenumber \end{frame} % \section{Computational Complexity} % % https://en.wikipedia.org/wiki/BQP % % https://www.quantiki.org/wiki/bqp % \begin{frame}{Frame Title} % \begin{card} % \end{card} % \pagenumber % \end{frame} \section{Where to learn more?} \begin{frame}{Where to learn more?} \begin{card} \begin{itemize} \item \href{https://github.com/Qiskit/openqasm/blob/master/spec/qasm2.rst}{\qasm documentation} \item \href{https://hackernoon.com/quantum-computing-explained-a114999299ca}{General article on Hackernoon} to widen your view \item \href{https://www.youtube.com/watch?v=g_IaVepNDT4}{Veritaserum video on qubits} \item \href{http://www.smbc-comics.com/comic/the-talk-3}{Eye-opening and funny commic on \qc} \end{itemize} \end{card} \end{frame} \end{document}
Teach-Me-Quantum/Week 2 - Quantum Information Science/latex/main.tex/0
{ "file_path": "Teach-Me-Quantum/Week 2 - Quantum Information Science/latex/main.tex", "repo_id": "Teach-Me-Quantum", "token_count": 5819 }
7
\documentclass[aspectratio=43]{beamer} \usepackage[utf8]{inputenc} %%%%%%%%%%%%%%%%%%%%%%%% THEME \usetheme{material} \useLightTheme \usePrimaryBlueGrey \useAccentDeepPurple \usepackage{macros} % must come after theme \title{High-Level Quantum Programming} \keywords{\qk, \q Programming} \begin{document} \begin{frame} \titlepage \end{frame} \begin{frame}{Table of contents} \begin{card} \tableofcontents \end{card} \end{frame} \section{Introduction} \begin{frame}{Meta-Introduction} \begin{card} By now, you should have a good grasp of the \textit{magic underneath the hood} of \qc. Meaning that quantum circuitry and quantum programming are now within your grasp. \end{card} \pagenumber \end{frame} \begin{frame}{Introduction} \begin{cardTiny} This week, a different approach will be taken. We will see how quantum computing can be used for the benefit of many other scientific and industry areas. Hopefully, some of the topics you will learn will have a direct application on your life and work. \end{cardTiny} \begin{cardTiny} We will do some \qka troubleshooting and then go through the latest examples on \href{https://github.com/Qiskit/qiskit-tutorial}{qiskit-tutorial} on how to use \qsa for solving real world problems. This example set is not fully explored and is expected to grow quite a lot in the short term (so keep your eyes open).\\ \small{*If you are an autodidact, feel free to skip examples on areas that do not interest you.} \end{cardTiny} \pagenumber \end{frame} \begin{frame}{Motivation} \begin{card} \begin{chapquote}[2pt]{\href{https://msramalho.github.io/}{Me}} ``The better people understand that quantum computing is within their grasp and can be leveraged towards personal gain, the sooner a day will come when running quantum algorithms is but a triviality.'' \end{chapquote} \end{card} \pagenumber \end{frame} \section{\qka} \begin{frame}{\qka} \begin{center} \includegraphics[width=1\textwidth]{qka} \end{center} \begin{card} As we saw in \href{\weekOne}{Week 1 - Quantum Tools}, \qka is the top-level block on the \qk full-stack infrastructure. This means it works on a higher level then what we have seen so far, abstracting a quantum compiler and providing an interface much similar to that of classical computing. \end{card} \pagenumber \end{frame} \begin{frame}{The Premise of \qka} \begin{card} \qka contains ``a library of cross-domain quantum algorithms upon which applications for near-term quantum computing can be built''. \textbf{Near-term} means this is the time to look into this, as these algorithms and applications will become feasible in a short time. \end{card} \pagenumber \end{frame} \section{\q Supremacy} \begin{frame}{\q Supremacy} \begin{card} The term \textbf{\q Supremacy} (not to be mistaken for a crossover between \textit{Quantum of Solace} and \textit{The Bourne Supremacy}...) stands for the moment in time in which quantum computers can do better than the most powerful computer in simulating a quantum system.\\ This may seem strange, but the fact is that classical computers are so developed they they are still able to simulate better quantum computers than those in existence, but this classical "quantum simulation" fits into the \np family and so there will come a time, in the not so far away future, when they are no longer able to do better than \textit{the real thing}. \end{card} \pagenumber \end{frame} \begin{frameImg}[height]{quantum_supremacy.jpeg} \end{frameImg} \section{Running algorithms in \qka} \begin{frame}{Running algorithms in \qka} \begin{card} First and foremost: \mintinline{bash}{pip install qiskit-aqua} \end{card} \begin{cardTiny} Then, we need to understand which algorithms have already been implemented in \qka. A comprehensive list can be found \href{https://qiskit.org/documentation/aqua/algorithms.html}{in the docs}, some that you may recognize are: \begin{itemize} \item \href{https://qiskit.org/documentation/aqua/algorithms.html#quantum-grover-search}{Grover Search} \item \href{https://qiskit.org/documentation/aqua/algorithms.html#quantum-dynamics}{Quantum Dynamics} (Simulating Universal Quantum Systems) \item \href{https://qiskit.org/documentation/aqua/algorithms.html#support-vector-machine-quantum-kernel-svm-q-kernel}{Support Vector Machine Quantum Kernel} (Machine Learning) \item \href{https://qiskit.org/documentation/aqua/algorithms.html#cplex}{CPLEX} (Constraint Solver) \end{itemize} \end{cardTiny} \pagenumber \end{frame} \begin{frame}{Running algorithms in \qka} \small{ \qka is very declarative, in fact, running an algorithm can be thought of as defining a description of your problem, for instance in a \href{https://www.json.org/}{JSON} file or in a \href{https://docs.python.org/3/tutorial/datastructures.html#dictionaries}{Python Dictionary}. It is a composition of the following settings (For more information, check the \href{https://qiskit.org/documentation/aqua/execution.html#input-file}{docs}.): \begin{description} \item[Problem] The type of experiment (\mintinline{python}{"energy" | "excited_states" | "ising" | "search" ...}) \item[Input/Oracle] The way to specify the input to the problem, depends on the type (SAT configuration, dataset, oracle, ...) \item[Algorithm] Optional specification of the algorithm to use (each problem has default algorithms) and its configurations \item[Backend] Which device to use (simulator, real device), highly customizable with number of shots (how many times should an experiment be repeated), activate compiler optimization, specify device noise parameters, ... \end{description} } \pagenumber \end{frame} \section{Troubleshooting \qka} \begin{frame}{Troubleshooting \qka} \begin{card} After installing head to a command line and run \mintinline{bash}{qiskit_aqua_ui}. If nothing happens, you should make sure you add your python \mintinline{bash}{bin} folder to the \href{https://docs.alfresco.com/4.2/tasks/fot-addpath.html}{system variable path}, it should be something like: \mintinline{python}{"C:/Program Files/Python36/Library/bin"}.\\ The same solution goes for \href{https://stackoverflow.com/questions/14778178/import-cvxopt-base-the-specified-module-could-not-be-found}{the cvxopt error} when running python scripts. \end{card} \pagenumber \end{frame} \begin{frame}{Troubleshooting \qka} \small{When everything is properly installed you should see something like (The \qka GUI for editing experimental settings):} \begin{center} \includegraphics[width=1\textwidth]{qskit_aqua_ui} \end{center} \pagenumber \end{frame} \section{\gvsa in \qka} \begin{frame}[fragile]{\gvsa in \qka} Go ahead and run the following code, while trying to understand it:\begin{minted}{python} from qiskit_aqua import run_algorithm # problem in DIMACS CNF format: sat_cnf = """ p cnf 3 5 -1 -2 -3 0 1 -2 3 0 1 2 -3 0 1 -2 -3 0 -1 2 3 0 """ params = { 'problem': {'name': 'search'}, 'oracle': {'name': 'SAT', 'cnf': sat_cnf}, 'algorithm': {'name': 'Grover'}, 'backend': {'name': 'qasm_simulator'} } print(run_algorithm(params)['result']) # [1, -2, 3] or another \end{minted} \end{frame} \section{\ai} \begin{frame}{\ai} \begin{card} If you work in Machine Learning, you probably know how the \href{https://en.wikipedia.org/wiki/Support_vector_machine}{Support Vector Machine}(SVM) works. It is simply an algorithm for \href{https://en.wikipedia.org/wiki/Supervised_learning}{supervised learning}.\\ \qka comes with more than one implementation of SVM Kernels. We will have a complete exercise on it this week (optional). \end{card} \begin{card} More \ai related algorithms are expected to be implemented on \qka in the future, and you may even \href{https://qiskit.org/documentation/aqua/extending.html#algorithms}{implement your own}! \end{card} \pagenumber \end{frame} \begin{frame}[fragile]{\ai (SVM)} \small{Here's an example of a configuration for an SVM classification model:}\begin{minted}{python} params = { 'problem': { 'name': 'svm_classification', 'random_seed': 1219 # same seed ensures reproducibility }, 'algorithm': { 'name': 'QSVM.Kernel' }, 'backend': { 'name': 'qasm_simulator', 'shots': 1024 }, 'feature_map': { 'name': 'SecondOrderExpansion', 'depth': 2, 'entanglement': 'linear' } } \end{minted} \end{frame} \section{Optimization} \begin{frame}{Optimization} \begin{cardTiny} Still related to AI, there is another very important topic nowadays in both research and industry settings: \textbf{optimization}. \end{cardTiny} \begin{cardTiny} In this week's exercises you will have 2 examples of optimization problems: \href{https://en.wikipedia.org/wiki/Maximum_cut}{maximum cut} and the iconic \href{https://en.wikipedia.org/wiki/Travelling_salesman_problem}{traveling salesman problem}. These can both be reduced to a traditional model called \href{https://en.wikipedia.org/wiki/Ising_model}{ising model} that has been studied from a \href{https://arxiv.org/ftp/arxiv/papers/1210/1210.0113.pdf}{quantum point of view}. Thus, by using the ising solver in \qka we are able to solve many different problems, literally the only limitation is our ability to map problem formulations into know and solved problems. \end{cardTiny} \pagenumber \end{frame} \section{Chemistry in \qka} \begin{frame}{Chemistry in \qka} \begin{card} Lastly, and especially directed at chemistry related research, there are also examples of extrapolation of quantum mechanical properties that allow to make simulation on the behaviour of atoms, electrons and on the evolution of molecule configurations.\\ If you think about it, what better to simulate an atomic process than quantum? \end{card} \begin{card} As a matter of fact, there is a \href{https://github.com/Qiskit/aqua-chemistry}{complete repository} form the \qk team dedicated to chemistry algorithms for research on the field. \end{card} \pagenumber \end{frame} \begin{frame}[fragile]{Chemistry in \qka} \small{We will not go much deeper into explaining the typical approaches, as this should be done by those students that truly benefit from it. However, here is an example of how such problems may be configured (the input comes from \href{https://support.hdfgroup.org/HDF5/whatishdf5.html}{HDF5} files):}\begin{minted}{python} # Input dictionary to configure Qiskit aqua Chemistry # for the chemistry problem. aqua_chemistry_dict = { 'driver': {'name': 'HDF5'}, 'HDF5': {'hdf5_input': 'H2/0.7_sto-3g.hdf5'}, 'operator': {'name': 'hamiltonian'}, 'algorithm': {'name': 'VQE'}, 'optimizer': {'name': 'COBYLA'}, 'variational_form': {'name': 'UCCSD'}, 'initial_state': {'name': 'HartreeFock'}, 'backend': {'name': 'statevector_simulator'} } \end{minted} \end{frame} \section{Hands-on} \begin{frame}{Hands-on} \begin{card} This week there will be quite a few exercise tutorials available, each student is expected to select and study at least one of them. Here are the topics covered in each: \begin{enumerate} \item Grover algorithm with \qka (search) \item SVM for Breast Cancer classification (\ai) \item Maximum Cut problem (optimization) \item Traveling Salesman problem (optimization) \item Computing the ground state energy of an $H_2$ molecule (Chemistry) \end{enumerate} \end{card} \end{frame} \section{Where to learn more?} \begin{frame}{Where to learn more?} \begin{card} \begin{itemize} \item \href{https://qiskit.org/documentation/aqua/index.html}{\qka documentation} seriously a good point to start \item \href{https://github.com/Qiskit/qiskit-tutorial/tree/master/qiskit/aqua}{\qka official tutorials} \item \href{https://github.com/Qiskit/qiskit-tutorial/tree/master/community/aqua}{\qka community tutorials} \item \href{https://en.wikipedia.org/wiki/Quantum_programming}{A comprehensive analysis of \q Programming SDKs and languages} including, of course, \qk \end{itemize} \end{card} \end{frame} \end{document}
Teach-Me-Quantum/Week 8 - High Level Quantum Programming/latex/main.tex/0
{ "file_path": "Teach-Me-Quantum/Week 8 - High Level Quantum Programming/latex/main.tex", "repo_id": "Teach-Me-Quantum", "token_count": 4195 }
8
[run] omit = */tests/* mitiq/_about.py [report] # Regexes for lines to exclude from consideration exclude_lines = pragma: no cover # Don't complain if tests don't hit defensive assertion code: raise NotImplementedError
mitiq/.coveragerc/0
{ "file_path": "mitiq/.coveragerc", "repo_id": "mitiq", "token_count": 84 }
9
GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/licenses/why-not-lgpl.html>.
mitiq/LICENSE/0
{ "file_path": "mitiq/LICENSE", "repo_id": "mitiq", "token_count": 8075 }
10
```{include} ../../CONTRIBUTING.md :relative-docs: docs/ :relative-images: ```
mitiq/docs/source/contributing.md/0
{ "file_path": "mitiq/docs/source/contributing.md", "repo_id": "mitiq", "token_count": 32 }
11
--- jupytext: text_representation: extension: .md format_name: myst format_version: 0.13 jupytext_version: 1.16.1 kernelspec: display_name: Python 3 (ipykernel) language: python name: python3 --- ```{tags} qiskit, zne, intermediate ``` # ZNE with Qiskit: Layerwise folding This tutorial shows an example of how to mitigate noise on IBMQ backends using layerwise folding in contrast with global folding. One may ask why folding by layer is potentially beneficial to consider. One reason is that applying global folding will increase the length of the entire circuit while layerwise folding on a subset of only the noisiest layers will increase the circuit by a smaller factor. If running a circuit on hardware is bottle-necked by the cost of running a long circuit, this technique could potentially be used to arrive at a better result (although not as good as global folding) but with less monetary cost. More information on the layerwise folding technique can be found in *Calderon et al. Quantum (2023)* {cite}`Calderon_2023_Quantum`. - [ZNE with Qiskit: Layerwise folding](#zne-with-qiskit-layerwise-folding) - [Setup](#setup) - [Helper functions](#helper-functions) - [Define circuit to analyze](#define-circuit-to-analyze) - [Total variational distance metric](#total-variational-distance-metric) - [Impact of single vs. multiple folding](#impact-of-single-vs-multiple-folding) - [Executor](#executor) - [Global folding with linear extrapolation](#global-folding-with-linear-extrapolation) - [Layerwise folding with linear extrapolation](#layerwise-folding-with-linear-extrapolation) +++ ## Setup ```{code-cell} ipython3 from typing import Dict, List, Optional import numpy as np import os import cirq import qiskit import matplotlib.pyplot as plt from mitiq import zne from mitiq.zne.scaling.layer_scaling import layer_folding, get_layer_folding from mitiq.interface.mitiq_qiskit.qiskit_utils import initialized_depolarizing_noise from mitiq.interface.mitiq_qiskit.conversions import to_qiskit from mitiq.interface.mitiq_cirq.cirq_utils import sample_bitstrings from cirq.contrib.svg import SVGCircuit from qiskit_aer import QasmSimulator # Default to a simulator. noise_model = initialized_depolarizing_noise(noise_level=0.02) backend = QasmSimulator(noise_model=noise_model) shots = 10_000 ``` ## Helper functions The following function will return a list of circuits where the ith element in the list is a circuit with layer "i" folded `num_folds` number of times. This will be useful when analyzing how much folding increases the noise on a given layer. ```{code-cell} ipython3 def apply_num_folds_to_all_layers(circuit: cirq.Circuit, num_folds: int = 1) -> List[cirq.Circuit]: """List of circuits where ith circuit is folded `num_folds` times.""" return [ layer_folding(circuit, [0] * i + [num_folds] + [0] * (len(circuit) - i)) for i in range(len(circuit)) ] ``` For instance, consider the following circuit. ```{code-cell} ipython3 # Define a basic circuit for q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( [cirq.ops.H(q0)], [cirq.ops.CNOT(q0, q1)], [cirq.measure(cirq.LineQubit(0))], ) print(circuit) ``` Let us invoke the `apply_num_folds_to_all_layers` function as follows. ```{code-cell} ipython3 folded_circuits = apply_num_folds_to_all_layers(circuit, num_folds=2) ``` Note that the first element of the list is the circuit with the first layer of the circuit folded twice. ```{code-cell} ipython3 print(folded_circuits[0]) ``` Similarly, the second element of the list is the circuit with the second layer folded. ```{code-cell} ipython3 print(folded_circuits[1]) ``` ## Define circuit to analyze We will use the following circuit to analyze, but of course, you could use other circuits here as well. ```{code-cell} ipython3 circuit = cirq.Circuit([cirq.X(cirq.LineQubit(0))] * 10, cirq.measure(cirq.LineQubit(0))) print(circuit) ``` ## Total variational distance metric An $i$-inversion can be viewed as a local perturbation of the circuit. We want to define some measure by which we can determine how much such a perturbation affects the outcome. Define the quantity: $$ p(k|C) = \langle \langle k | C | \rho_0 \rangle \rangle $$ as the probability distribution over measurement outcomes at the output of a circuit $C$ where $k \in B^n$ with $B^n$ being the set of all $n$-length bit strings where $\langle \langle k |$ is the vectorized POVM element that corresponds to measuring bit string $k$. The *impact* of applying an inversion is given by $$ d \left[p(\cdot|C), p(\cdot|C^{(i)})\right] $$ where $d$ is some distance measure. In *Calderon et al. Quantum (2023)* {cite}`Calderon_2023_Quantum` the authors used the total variational distance (TVD) measure where $$ \eta^{(i)} := \frac{1}{2} \sum_{k} |p(k|C) - p(k|C^{(i)})|. $$ ```{code-cell} ipython3 def tvd(circuit: cirq.Circuit, num_folds: int = 1, shots: int = 10_000) -> List[float]: """Compute the total variational distance (TVD) between ideal circuit and folded circuit(s).""" circuit_dist = sample_bitstrings(circuit=circuit, shots=shots).prob_distribution() folded_circuits = apply_num_folds_to_all_layers(circuit, num_folds) distances: Dict[int, float] = {} for i, folded_circuit in enumerate(folded_circuits): folded_circuit_dist = sample_bitstrings(circuit=folded_circuit, shots=shots).prob_distribution() res: float = 0.0 for bitstring in circuit_dist.keys(): res += np.abs(circuit_dist[bitstring] - folded_circuit_dist[bitstring]) distances[i] = res / 2 return distances ``` ## Impact of single vs. multiple folding We can plot the impact of applying layer inversions to the circuit. ```{code-cell} ipython3 def plot_single_vs_multiple_folding(circuit: cirq.Circuit) -> None: """Plot how single vs. multiple folding impact the error at a given layer.""" single_tvd = tvd(circuit, num_folds=1).values() multiple_tvd = tvd(circuit, num_folds=5).values() labels = [f"L{i}" for i in range(len(circuit))] x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, single_tvd, width, label="single") rects2 = ax.bar(x + width/2, multiple_tvd, width, label="multiple") # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_xlabel(r"$L_{G_i \theta_i}$") ax.set_ylabel(r"$\eta^{(i)}$") ax.set_title("Single vs. multiple folding") ax.set_xticks(x, labels, rotation=60) ax.legend() ax.bar_label(rects1, padding=3) ax.bar_label(rects2, padding=3) fig.tight_layout() plt.show() ``` ```{code-cell} ipython3 plot_single_vs_multiple_folding(circuit) ``` As can be seen, the amount of noise on each layer is increased if the number of folds on that layer are increased. ## Executor Next, we define an executor function that will allow us to run our experiment ```{code-cell} ipython3 def executor(circuit: cirq.Circuit, shots: int = 10_000) -> float: """Returns the expectation value to be mitigated. Args: circuit: Circuit to run. shots: Number of times to execute the circuit to compute the expectation value. """ qiskit_circuit = to_qiskit(circuit) # Transpile the circuit so it can be properly run exec_circuit = qiskit.transpile( qiskit_circuit, backend=backend, basis_gates=noise_model.basis_gates if noise_model else None, optimization_level=0, # Important to preserve folded gates. ) # Run the circuit job = backend.run(exec_circuit, shots=shots) # Convert from raw measurement counts to the expectation value counts = job.result().get_counts() expectation_value = 0.0 if counts.get("0") is None else counts.get("0") / shots return expectation_value ``` ## Global folding with linear extrapolation First, for comparison, we apply ZNE with global folding on the entire circuit. We then compare the mitigated result of applying ZNE with linear extrapolation against the unmitigated value. ```{code-cell} ipython3 unmitigated = executor(circuit) linear_factory = zne.inference.LinearFactory(scale_factors=[1.0, 1.5, 2.0, 2.5, 3.0]) mitigated = zne.execute_with_zne(circuit, executor, factory=linear_factory) print(f"Unmitigated result {unmitigated:.3f}") print(f"Mitigated result {mitigated:.3f}") ``` ## Layerwise folding with linear extrapolation For contrast, we apply layerwise folding on only the layer with the most noise and use linear extrapolation. As above, we compare the mitigated and unmitigated values. ```{code-cell} ipython3 # Calculate the TVDs of each layer in the circuit (with `num_folds=3`): tvds = tvd(circuit, num_folds=3) # Fold noisiest layer only. layer_to_fold = max(tvds, key=tvds.get) fold_layer_func = zne.scaling.get_layer_folding(layer_to_fold) mitigated = zne.execute_with_zne(circuit, executor, scale_noise=fold_layer_func, factory=linear_factory) print(f"Mitigated (layerwise folding) result {mitigated:.3f}") print(f"Unmitigated result {unmitigated:.3f}") ``` ```{note} While doing layerwise folding on the noisiest layer will, on average, improve the mitigated value, it still will not eclipse the benefit of doing global folding. ```
mitiq/docs/source/examples/layerwise-folding.md/0
{ "file_path": "mitiq/docs/source/examples/layerwise-folding.md", "repo_id": "mitiq", "token_count": 3319 }
12
<jupyter_start><jupyter_text>Variational Quantum Eigensolver improved with Zero Noise Extrapolation In this example we investigate how Zero Noise Extrapolation (ZNE) can improve convergence when applied to a variational problem. ZNE works by computing the observable of interest at increased noise levels, i.e. beyond the minimum noise strength in the computer, and then extrapolating back to the zero-noise limit. The two main components of ZNE are noise scaling and extrapolation. You can read more about ZNE in the Mitiq Users Guide.The Variational Quantum Eigensolver (VQE) is a hybrid quantum-classical algorithm used tosolve eigenvalue and optimization problems. The VQE algorithm consists of a quantum subroutine run inside of a classical optimization loop. In this example, the goal of the optimization is to find the smallest eigenvalue of a matrix H, which is the Hamiltonian of a simple quantum system. The quantum subroutine prepares the quantum state |Ψ(vec(θ))⟩ and measures the expectation value ⟨Ψ(vec(θ))|H|Ψ(vec(θ))⟩. By the variational principle, ⟨Ψ(vec(θ))|H|Ψ(vec(θ))⟩ is always greater than the smallest eigenvalue of H, which means a classical optimization loop can be used to find this eigenvalue. The VQE example shown here is adapted from the `VQE` function in Grove [[1]](references) and the pyQuil / Grove VQE tutorial [[2]](references). Defining the quantum system using pyQuil ```{tags} zne, advanced```<jupyter_code>import numpy as np from pyquil import get_qc, Program from pyquil.gates import RX, RY, S, T, Z, CNOT, MEASURE from pyquil.paulis import PauliTerm, PauliSum, sZ from pyquil.noise import pauli_kraus_map, append_kraus_to_gate from typing import List, Union from collections import Counter from matplotlib import pyplot as plt from scipy import optimize import mitiq from mitiq import zne from mitiq.zne.scaling.folding import fold_gates_at_random<jupyter_output><empty_output><jupyter_text>Use the `get_qc` command to initialize the simulated backend where the pyQuil program will run<jupyter_code>backend = get_qc("2q-qvm")<jupyter_output><empty_output><jupyter_text>Define example ansatz, consisting of a rotation by angle `theta` and a layer of static gates:<jupyter_code>program = Program() theta = program.declare("theta", memory_type="REAL") program += RX(theta, 0) program += T(0) program += CNOT(1, 0) program += S(0) program += Z(0)<jupyter_output><empty_output><jupyter_text>Simulate depolarizing noise on the static gates:<jupyter_code>def add_noise_to_circuit(quil_prog): """Define pyQuil gates with a custom noise model via Kraus operators: 1. Generate Kraus operators at given survival probability 2. Append Kraus operators to the gate matrices 3. Add custom gates to circuit Args: quil_prog: the pyQuil quantum program to which the noise model will be added Returns: A quantum program with depolarizing noise on the static gates. """ prob = 0.8 num_qubits = 1 d = 4 ** num_qubits d_sq = d ** 2 kraus_list = [(1 - prob) / d] * d kraus_list[0] += prob kraus_ops = pauli_kraus_map(kraus_list) k_list = [(1 - prob) / d_sq] * d_sq k_list[0] += prob k_ops = pauli_kraus_map(k_list) T_gate = np.array([[1, 0], [0, np.exp(1j * np.pi / 4)]]) CNOT_gate = np.block( [[np.eye(2), np.zeros((2, 2))], [np.zeros((2, 2)), np.flip(np.eye(2), 1)]] ) S_gate = np.array([[1, 0], [0, 1j]]) Z_gate = np.array([[1, 0], [0, -1]]) quil_prog.define_noisy_gate("T", [0], append_kraus_to_gate(kraus_ops, T_gate)) quil_prog.define_noisy_gate("CNOT", [1, 0], append_kraus_to_gate(k_ops, CNOT_gate)) quil_prog.define_noisy_gate("S", [0], append_kraus_to_gate(kraus_ops, S_gate)) quil_prog.define_noisy_gate("Z", [0], append_kraus_to_gate(kraus_ops, Z_gate)) return quil_prog<jupyter_output><empty_output><jupyter_text>Set up VQE: define Hamiltonian and energy expectation functions Hamiltonian in this example is just `sigma_z` on the zeroth qubit<jupyter_code>hamiltonian = sZ(0) pauli_sum = PauliSum([hamiltonian]) for j, term in enumerate(pauli_sum.terms): meas_basis_change = Program() marked_qubits = [] for index, gate in term: marked_qubits.append(index) if gate == "X": meas_basis_change.inst(RY(-np.pi / 2, index)) elif gate == "Y": meas_basis_change.inst(RX(np.pi / 2, index)) program += meas_basis_change readout_qubit = program.declare("ro", "BIT", max(marked_qubits) + 1) samples = 3000 program.wrap_in_numshots_loop(samples)<jupyter_output><empty_output><jupyter_text>Compute expectation value of the Hamiltonian over the over the distribution generated from the quantum program. The following function is a modified version of `expectation` from the `VQE` function in Grove [[1]](references). Here the noisy gates are defined inside the executor function via `add_noise_to_circuit`, since pyQuil custom gates cannot be folded in Mitiq.<jupyter_code>def executor( theta, backend, readout_qubit, samples: int, pauli_sum: Union[PauliSum, PauliTerm, np.ndarray], pyquil_prog: Program, ) -> float: """ Compute the expectation value of pauli_sum over the distribution generated from pyquil_prog. """ noisy = pyquil_prog.copy() noisy += [ MEASURE(qubit, r) for qubit, r in zip(list(range(max(marked_qubits) + 1)), readout_qubit) ] noisy = add_noise_to_circuit(noisy) expectation = 0.0 pauli_sum = PauliSum([pauli_sum]) for j, term in enumerate(pauli_sum.terms): qubits_to_measure = [] for index, gate in term: qubits_to_measure.append(index) meas_outcome = expectation_from_sampling( theta, noisy, qubits_to_measure, backend, samples ) expectation += term.coefficient * meas_outcome return expectation.real<jupyter_output><empty_output><jupyter_text>The following function is a modified version of `expectation_from_sampling` from the `VQE` function in Grove [[1]](references). It is modified to follow pyQuil conventions for defining custom gates.<jupyter_code>def expectation_from_sampling( theta, executable: Program, marked_qubits: List[int], backend, samples: int ) -> float: """Calculate the expectation value of the Zi operator where i ranges over all qubits given in marked_qubits. """ bitstring_samples = backend.run( executable.write_memory(region_name="theta", value=theta) ).readout_data.get("ro") bitstring_tuples = list(map(tuple, bitstring_samples)) freq = Counter(bitstring_tuples) exp_val = 0 for bitstring, count in freq.items(): bitstring_int = int("".join([str(x) for x in bitstring[::-1]]), 2) if parity_even_p(bitstring_int, marked_qubits): exp_val += float(count) / samples else: exp_val -= float(count) / samples return exp_val<jupyter_output><empty_output><jupyter_text>Calculate the parity of elements at indexes in marked_qubits. The function is a modified version of `parity_even_p` from the `VQE` function in Grove [[1]](references).<jupyter_code>def parity_even_p(state, marked_qubits): mask = 0 for q in marked_qubits: mask |= 1 << q return bin(mask & state).count("1") % 2 == 0<jupyter_output><empty_output><jupyter_text>Run VQE first without error mitigation and then with ZNE, and compare resultsScan over the parameter `theta` and calculate energy expectation, without mitigation. In a later section we will plot these results and compare them with the results from ZNE.<jupyter_code>thetas = np.linspace(0, 2 * np.pi, 51) results = [] for theta in thetas: results.append(executor(theta, backend, readout_qubit, samples, hamiltonian, program))<jupyter_output><empty_output><jupyter_text>Optimization routine without mitigation:<jupyter_code>init_angle = [3.0] res = optimize.minimize( executor, init_angle, args=(backend, readout_qubit, samples, hamiltonian, program), method="Nelder-Mead", options={"xatol": 1.0e-3, "fatol": 1.0e-2}, ) print(res)<jupyter_output>final_simplex: (array([[2.9953125 ], [2.99560547]]), array([-0.432 , -0.42733333])) fun: -0.432 message: 'Optimization terminated successfully.' nfev: 31 nit: 11 status: 0 success: True x: array([2.9953125])<jupyter_text>The result on the unmitigated noisy circuit result in loss of accuracy (relative to the ideal expectation value of -1.0) and additional iterations required to reach convergence. Now we introduce ZNE and compare results.This is done by wrapping the noisy executor into a mitigated executor. We will fold the gates from the right and apply a linear inference (using a Linear Factory object) to implement ZNE. You can read more about noise scaling by unitary folding in the Mitiq user guide.<jupyter_code>def mitigated_expectation( thetas, backend, readout_qubit, samples, pauli_sum, executable: Program, factory ) -> float: """ This function is the ZNE-wrapped executor, which outputs the error-mitigated expectation value. Args: thetas: the input parameter for the optimization backend: the quantum computer that runs the quantum program readout_qubit: declared memory for the readout samples: number of times the experiment (or simulation) will be run pauli_sum: the Hamiltonian expressed as executable: the pyQuil quantum program factory: factory object containing the type of inference and scaling parameters Returns: The error-mitigated expectation value as a float. """ mitigated_exp = zne.execute_with_zne( executable, lambda p: executor(thetas, backend, readout_qubit, samples, pauli_sum, p), factory=factory, scale_noise=fold_gates_at_random, ) return mitigated_exp<jupyter_output><empty_output><jupyter_text>Here we use a linear inference for the extrapolation. See the section on [Factory Objects](../guide/zne-3-options.mdextrapolation-methods-factory-objects) in the Mitiq user guide for more information:<jupyter_code>fac = mitiq.zne.inference.LinearFactory(scale_factors=[1.0, 3.0])<jupyter_output><empty_output><jupyter_text>Scan over the parameter `theta` and plot the energy expectation with error mitigation<jupyter_code>results_zne = [] for theta in thetas: results_zne.append( mitigated_expectation(theta, backend, readout_qubit, samples, hamiltonian, program, fac) ) _ = plt.figure() _ = plt.plot(thetas, np.cos(thetas), "o-", label="Ideal landscape") _ = plt.plot(thetas, results, "o-", label="Noisy landscape") _ = plt.plot(thetas, results_zne, "o-", label="Mitigated landscape") _ = plt.xlabel(r"$\theta$", fontsize=18) _ = plt.ylabel(r"$\langle \Psi(\theta) | Z | \Psi(\theta) \rangle$", fontsize=18) _ = plt.legend() _ = plt.title("Mitigated Energy Landscape") plt.show()<jupyter_output><empty_output><jupyter_text>In the energy landscape plot, we can see that the noise has flattened the unmitigated landscape and with error mitigation it has become peaked again. Therefore, we expect the optimization loop to have better convergence with ZNE applied.Run VQE routine with ZNE<jupyter_code>res_zne = optimize.minimize( mitigated_expectation, init_angle, args=(backend, readout_qubit, samples, hamiltonian, program, fac), method="Nelder-Mead", options={"xatol": 1.0e-3, "fatol": 1.0e-2}, ) print(res_zne)<jupyter_output>final_simplex: (array([[3.08437042], [3.084375 ]]), array([-0.79566667, -0.79533333])) fun: -0.7956666666666666 message: 'Optimization terminated successfully.' nfev: 45 nit: 16 status: 0 success: True x: array([3.08437042])<jupyter_text>We can see that the convergence to the minimum energy is enhanced by applying ZNE. ConclusionWhile the VQE algorithm is generally considered to be robust to noise [[2]](references), at the noise level modeled in this example, the accumulation of errors results in loss of accuracy and additional iterations required to reach convergence. Adding ZNE then improves the convergence of the algorithm to the minimum energy. The result is also demonstrated in the energy landscape plot, where the noisy landscape is noticeably flatter than the landscape generated with ZNE.Note: In this example, a small ansatz was used to keep the runtime within acceptable limits. ZNE generally performs better on longer circuits, but there is a tradeoff with execution time. References[1] Rigetti Computing (2018) Grove (Version 1.7.0) [[Source code].](https://github.com/rigetti/grove/blob/v1.7.0/grove/pyvqe/vqe.py)[2] [[VQE tutorial in pyQuil / Grove].](https://grove-docs.readthedocs.io/en/latest/vqe.html) This final block displays information about Mitiq, installed packages, and Python version/platform<jupyter_code>mitiq.about()<jupyter_output>Mitiq: A Python toolkit for implementing error mitigation on quantum computers ============================================================================== Authored by: Mitiq team, 2020 & later (https://github.com/unitaryfund/mitiq) Mitiq Version: 0.13.0dev Core Dependencies ----------------- Cirq Version: 0.13.1 NumPy Version: 1.20.3 SciPy Version: 1.7.3 Optional Dependencies --------------------- PyQuil Version: 3.0.1 Qiskit Version: 0.32.1 Braket Version: 1.14.0 Python Version: 3.7.7 Platform Info: Linux (x86_64)
mitiq/docs/source/examples/vqe-pyquil-demo.ipynb/0
{ "file_path": "mitiq/docs/source/examples/vqe-pyquil-demo.ipynb", "repo_id": "mitiq", "token_count": 4942 }
13
# Digital Dynamical Decoupling Digital Dynamical Decoupling (DDD) is an error mitigation technique in which sequences of gates are applied to slack windows, i.e. single-qubit idle windows, in a quantum circuit. Such sequences of gates can reduce the coupling between the qubits and the environment, mitigating the effects of noise. For more discussion of the theory of DDD, see the section [What is the theory behind DDD?](ddd-5-theory.md). ```{figure} ../img/ddd_workflow.svg --- width: 700px name: ddd-workflow-overview --- Workflow of the DDD technique in Mitiq, detailed in the [What happens when I use DDD?](ddd-4-low-level.md) section. ``` Below you can find sections of the documentation that address the following questions: ```{toctree} --- maxdepth: 1 --- ddd-1-intro.md ddd-2-use-case.md ddd-3-options.md ddd-4-low-level.md ddd-5-theory.md ``` Here is a tutorial on how to use DDD in Mitiq: [DDD with Cirq: Mirror circuits](../examples/ddd_tutorial.md) You can find many more examples on a variety of error mitigation techniques in the **[Examples](../examples/examples.md)** section of the documentation.
mitiq/docs/source/guide/ddd.md/0
{ "file_path": "mitiq/docs/source/guide/ddd.md", "repo_id": "mitiq", "token_count": 360 }
14
--- jupytext: text_representation: extension: .md format_name: myst format_version: 0.13 jupytext_version: 1.11.1 kernelspec: display_name: Python 3 language: python name: python3 --- # What happens when I use PT? ```{admonition} Warning: Pauli Twirling in Mitiq is still under construction. This users guide will change in the future after some utility functions are introduced. ``` The workflow of Pauli Twirling (PT) in Mitiq is represented in the figure below. ```{figure} ../img/pt_workflow.svg --- width: 700px name: pt-workflow-overview-2 --- Workflow of the PT technique in Mitiq, detailed in the [What happens when I use PT?](pt-4-low-level.md) section. ``` - The user provides a `QPROGRAM`, (i.e. a quantum circuit defined via any of the supported [frontends](frontends-backends.md)). - Mitiq modifies the input circuit with the insertion of PT gates on noisy operations. - The modified circuit is executed via a user-defined [Executor](executors.md). - The error mitigated expectation value is returned to the user. With respect to the workflows of other error-mitigation techniques (e.g. [ZNE](zne-4-low-level.md) or [PEC](pec-4-low-level.md)), PT involves the generation of a _single_ circuit with random modifications, and subsequently averages over many executions. For this reason, there is no need for a complex final inference step, which is necessary for other techniques, and so this average is instead trivial for PT. ```{note} When setting the `num_trials` option to a value larger than one, multiple circuits are actually generated by Mitiq and the associated results are averaged to obtain the final expectation value. This more general case is not shown in the figure since it can be considered as an average of independent single-circuit workflows. ``` As shown in [How do I use PT?](pt-1-intro.md), the function {func}`.pauli_twirl_circuit()` applies PT behind the scenes and returns the different versions of Pauli Twirled circuits. In the next sections instead, we show how one can apply PT at a lower level, i.e., by: - Twirling CZ and CNOT gates in the circuit; - Executing the modified circuit (still under construction). - Estimate expectation value by averaging over randomized twirling circuits ## Twirling CZ and CNOT gates in the circuit To twirl about particular gates, we need the Pauli group for those gates. These groups are stored as lookup tables, in {attr}`mitiq.pt.pt.CNOT_twirling_gates` and {attr}`mitiq.pt.pt.CZ_twirling_gates`, so that we can randomly select a tuple from the group. Now we're ready to twirl our gates. First let's define our circuit: ```{code-cell} ipython3 from cirq import LineQubit, Circuit, CZ, CNOT a, b, c, d = LineQubit.range(4) circuit = Circuit( CNOT.on(a, b), CZ.on(b, c), CNOT.on(c, d), ) print(circuit) ``` Now, we can see what happens when we apply the PT functions, through {func}`.twirl_CNOT_gates()` and the subsequent {func}`.twirl_CZ_gates()` ```{code-cell} ipython3 from mitiq import pt circuit_to_twirl = circuit.copy() CNOT_twirled_circuits = pt.twirl_CNOT_gates(circuit_to_twirl, num_circuits=10) twirled_circuits = [ pt.twirl_CZ_gates(c, num_circuits=1)[0] for c in CNOT_twirled_circuits ] print("Twirling just the CNOT gates: \n", CNOT_twirled_circuits[0], "\n") print("Twirling both CNOT and CZ gates: \n" ,twirled_circuits[0]) ``` We see that we return lists of the randomly twirled circuits, and so we must take a simple average over their expectation values. ## Executing the modified circuits ```{admonition} Warning: Pauli Twirling in Mitiq is still under construction. Some lines in the code blocks below are commented out as intended behavior is currently a WIP. ``` Now that we have our twirled circuits, let's simulate some noise and execute those circuits, using the {class}`mitiq.Executor` to collect the results. ```{code-cell} ipython3 from cirq import DensityMatrixSimulator, amplitude_damp from mitiq import Executor def execute(circuit, noise_level=0.003): """Returns Tr[ρ |00..⟩⟨00..|] where ρ is the state prepared by the circuit executed with depolarizing noise. """ noisy_circuit = circuit.with_noise(amplitude_damp(noise_level)) rho = DensityMatrixSimulator().simulate(noisy_circuit).final_density_matrix return rho[0, 0].real executor = Executor(execute) # expvals = executor.evaluate(twirled_circuits, None) ``` ## Estimate expectation value by averaging over randomized twirling circuits Pauli Twirling doesn't require running the circuit at different noise levels or with different noise models. It applies a randomized sequence of Pauli operations within the same quantum circuit and averages the results to reduce the effect of the noise. ```{code-cell} ipython3 # import numpy as np # from typing import cast # average = cast(float, np.average(expvals)) # print(average) ``` Keep in mind, ths code is for illustration and that the noise level, type of noise (here amplitude damping), and the observable need to be adapted to the specific experiment. If executed on a noiseless backend, a given `circuit_with_pt` and `circuit` are equivalent. On a real backend, they have a different sensitivity to noise. The core idea of the PT technique is that, `circuits_with_pt` (hopefully) tailors the noise into stochastic Pauli channels, such that a simple average over results will return a mitigated result. As a final remark, we stress that the low-level procedure that we have shown is exactly what {func}`.pauli_twirl_circuit()` does behind the scenes. Let's verify this fact: ```{code-cell} ipython3 # np.isclose( # pt.pauli_twirl_circuit(circuit, executor), # average, # ) ```
mitiq/docs/source/guide/pt-4-low-level.md/0
{ "file_path": "mitiq/docs/source/guide/pt-4-low-level.md", "repo_id": "mitiq", "token_count": 1747 }
15
```{toctree} --- maxdepth: 2 caption: Contents hidden: true --- guide/guide.md examples/examples.md apidoc.md toc_contributing.md changelog.md bibliography.md ``` ```{include} ./readme.md ```
mitiq/docs/source/index.md/0
{ "file_path": "mitiq/docs/source/index.md", "repo_id": "mitiq", "token_count": 84 }
16
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Functions for creating circuits of the form used in quantum volume experiments as defined in https://arxiv.org/abs/1811.12926. Useful overview of quantum volume experiments: https://pennylane.ai/qml/demos/quantum_volume Cirq implementation of quantum volume circuits: cirq-core/cirq/contrib/quantum_volume/quantum_volume.py """ from typing import Optional, Sequence, Tuple from cirq import decompose as cirq_decompose from cirq.circuits import Circuit from cirq.contrib.quantum_volume import ( compute_heavy_set, generate_model_circuit, ) from cirq.value import big_endian_int_to_bits from numpy import random from mitiq import QPROGRAM, Bitstring from mitiq.interface import convert_from_mitiq def generate_quantum_volume_circuit( num_qubits: int, depth: int, decompose: bool = False, seed: Optional[int] = None, return_type: Optional[str] = None, ) -> Tuple[QPROGRAM, Sequence[Bitstring]]: """Generate a quantum volume circuit with the given number of qubits and depth. The generated circuit consists of `depth` layers of random qubit permutations followed by random two-qubit gates that are sampled from the Haar measure on SU(4). Args: num_qubits: The number of qubits in the generated circuit. depth: The number of layers in the generated circuit. decompose: Recursively decomposes the randomly sampled (numerical) unitary matrix gates into simpler gates. seed: Seed for generating random circuit. return_type: String which specifies the type of the returned circuits. See the keys of ``mitiq.SUPPORTED_PROGRAM_TYPES`` for options. If ``None``, the returned circuits have type ``cirq.Circuit``. Returns: A quantum volume circuit acting on ``num_qubits`` qubits. A list of the heavy bitstrings for the returned circuit. """ random_state = random.RandomState(seed) circuit = generate_model_circuit( num_qubits, depth, random_state=random_state ) heavy_bitstrings = compute_heavy_bitstrings(circuit, num_qubits) if decompose: # Decompose random unitary gates into simpler gates. circuit = Circuit(cirq_decompose(circuit)) return_type = "cirq" if not return_type else return_type return convert_from_mitiq(circuit, return_type), heavy_bitstrings def compute_heavy_bitstrings( circuit: Circuit, num_qubits: int, ) -> Sequence[Bitstring]: """Classically compute the heavy bitstrings of the provided circuit. The heavy bitstrings are defined as the output bit-strings that have a greater than median probability of being generated. Args: circuit: The circuit to classically simulate. Returns: A list containing the heavy bitstrings. """ heavy_vals = compute_heavy_set(circuit) # Convert base-10 ints to Bitstrings. heavy_bitstrings = [ big_endian_int_to_bits(val, bit_count=num_qubits) for val in heavy_vals ] return heavy_bitstrings
mitiq/mitiq/benchmarks/quantum_volume_circuits.py/0
{ "file_path": "mitiq/mitiq/benchmarks/quantum_volume_circuits.py", "repo_id": "mitiq", "token_count": 1097 }
17
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. from dataclasses import asdict, dataclass from enum import Enum, auto from functools import partial from typing import Any, Callable, Dict, List, cast import cirq import networkx as nx import numpy as np from mitiq import QPROGRAM, SUPPORTED_PROGRAM_TYPES, Executor from mitiq.benchmarks import ( generate_ghz_circuit, generate_mirror_circuit, generate_rb_circuits, generate_rotated_rb_circuits, generate_w_circuit, ) from mitiq.interface import convert_from_mitiq from mitiq.pec import execute_with_pec from mitiq.pec.representations import ( represent_operation_with_local_biased_noise, represent_operation_with_local_depolarizing_noise, ) from mitiq.raw import execute from mitiq.zne import execute_with_zne from mitiq.zne.inference import LinearFactory, RichardsonFactory from mitiq.zne.scaling import fold_gates_at_random, fold_global class MitigationTechnique(Enum): """Simple enum type for handling validation, and providing helper functions when accessing mitigation techniques.""" ZNE = auto() PEC = auto() RAW = auto() @property def mitigation_function(self) -> Callable[..., float]: if self is MitigationTechnique.ZNE: return execute_with_zne elif self is MitigationTechnique.PEC: return cast(Callable[..., float], execute_with_pec) elif self is MitigationTechnique.RAW: return execute calibration_supported_techniques = { "ZNE": MitigationTechnique.ZNE, "PEC": MitigationTechnique.PEC, } @dataclass class BenchmarkProblem: """A dataclass containing information for instances of problems that will be run during the calibrations process. Args: id: A unique numerical id. circuit: The circuit to be run. type: The type of the circuit (often the name of the algorithm) ideal_distribution: The ideal probability distribution after applying ``circuit``. """ id: int circuit: cirq.Circuit type: str ideal_distribution: Dict[str, float] def most_likely_bitstring(self) -> str: distribution = self.ideal_distribution return max(distribution, key=distribution.__getitem__) def largest_probability(self) -> float: return max(self.ideal_distribution.values()) def converted_circuit( self, circuit_type: SUPPORTED_PROGRAM_TYPES ) -> QPROGRAM: """Adds measurements to all qubits and convert to the input frontend type. Args: circuit_type: The circuit type as a string. For supported circuit types see mitiq.SUPPORTED_PROGRAM_TYPES. Returns: The converted circuit with final measurements. """ circuit = self.circuit.copy() circuit.append(cirq.measure(circuit.all_qubits())) return convert_from_mitiq(circuit, circuit_type.value) @property def num_qubits(self) -> int: return len(self.circuit.all_qubits()) @property def circuit_depth(self) -> int: return len(self.circuit) @property def two_qubit_gate_count(self) -> int: return sum(len(op.qubits) > 1 for op in self.circuit.all_operations()) def to_dict(self) -> Dict[str, Any]: """Produces a summary of the ``BenchmarkProblem``, to be used in recording the results when running calibration experiments. Returns: Dictionary summarizing important attributes of the problem's circuit. """ base = asdict(self) # remove circuit; it can be regenerated if needed del base["circuit"] del base["id"] base["num_qubits"] = self.num_qubits base["circuit_depth"] = self.circuit_depth base["two_qubit_gate_count"] = self.two_qubit_gate_count return base def __repr__(self) -> str: return str(self.to_dict()) def __str__(self) -> str: result = "" for key, value in self.to_dict().items(): if key == "ideal_distribution": continue title: str = key.replace("_", " ").capitalize() result += f"{title}: {value}\n" return result.rstrip() @dataclass class Strategy: """A dataclass which describes precisely an error mitigation approach by specifying a technique and the associated options. Args: id: A unique numerical id. technique: One of Mitiq's support error mitigation strategies, specified as a :class:`MitigationTechnique`. technique_params: A dictionary of options to pass to the mitigation method specified in `technique`. """ id: int technique: MitigationTechnique technique_params: Dict[str, Any] @property def mitigation_function(self) -> Callable[..., float]: if self.technique is MitigationTechnique.PEC: self.technique_params.setdefault("noise_bias", 0) def partial_pec(circuit: cirq.Circuit, execute: Executor) -> float: rep_function = self.technique_params["representation_function"] operations = [] for op in circuit.all_operations(): if len(op.qubits) >= 2 and op not in operations: operations.append(cirq.Circuit(op)) num_samples = self.technique_params["num_samples"] if ( self.technique_params["representation_function"] == represent_operation_with_local_biased_noise ): reps = [ rep_function( op, self.technique_params["noise_level"], self.technique_params["noise_bias"], ) for op in operations ] else: reps = [ rep_function( op, self.technique_params["noise_level"], ) for op in operations ] return self.technique.mitigation_function( circuit, execute, representations=reps, num_samples=num_samples, ) return partial_pec elif self.technique is MitigationTechnique.ZNE: return partial( self.technique.mitigation_function, **self.technique_params ) else: raise ValueError( """Specified technique is not supported by calibration. See {} for supported techniques.""", calibration_supported_techniques, ) def to_dict(self) -> Dict[str, Any]: """A summary of the strategies parameters, without the technique added. Returns: A dictionary describing the strategies parameters.""" summary = {"technique": self.technique.name} if self.technique is MitigationTechnique.ZNE: inference_func = self.technique_params["factory"] summary["factory"] = inference_func.__class__.__name__ summary["scale_factors"] = inference_func._scale_factors summary["scale_method"] = self.technique_params[ "scale_noise" ].__name__ elif self.technique is MitigationTechnique.PEC: summary["representation_function"] = self.technique_params[ "representation_function" ].__name__ summary["noise_level"] = self.technique_params["noise_level"] summary["noise_bias"] = self.technique_params.setdefault( "noise_bias", 0 ) summary["is_qubit_dependent"] = self.technique_params[ "is_qubit_dependent" ] summary["num_samples"] = self.technique_params["num_samples"] return summary def to_pretty_dict(self) -> Dict[str, str]: summary = self.to_dict() if self.technique is MitigationTechnique.ZNE: summary["scale_factors"] = str(summary["scale_factors"])[1:-1] summary["factory"] = summary["factory"][:-7] elif self.technique is MitigationTechnique.PEC: summary["noise_bias"] = summary.get("noise_bias", "N/A") summary["representation_function"] = summary[ "representation_function" ][25:] return summary def __repr__(self) -> str: return str(self.to_dict()) def __str__(self) -> str: result = "" for key, value in self.to_pretty_dict().items(): title: str = key.replace("_", " ").capitalize() result += f"{title}: {value}\n" return result.rstrip() def num_circuits_required(self) -> int: summary = self.to_dict() if self.technique is MitigationTechnique.ZNE: return len(summary["scale_factors"]) elif self.technique is MitigationTechnique.PEC: return summary["num_samples"] elif self.technique is MitigationTechnique.RAW: return 1 return None class Settings: """A class to store the configuration settings of a :class:`.Calibrator`. Args: benchmarks: A list where each element is a dictionary of parameters for generating circuits to be used in calibration experiments. The dictionary keys include ``circuit_type``, ``num_qubits``, ``circuit_depth``, and in the case of mirror circuits, a random seed ``circuit_seed``. An example of input to ``benchmarks`` is:: [ { "circuit_type": "rb", "num_qubits": 2, "circuit_depth": 7, }, { "circuit_type": "mirror", "num_qubits": 2, "circuit_depth": 7, "circuit_seed": 1, } ] strategies: A specification of the methods/parameters to be used in calibration experiments. """ def __init__( self, benchmarks: List[Dict[str, Any]], strategies: List[Dict[str, Any]], ): self.techniques = [ MitigationTechnique[technique["technique"].upper()] for technique in strategies ] self.technique_params = strategies self.benchmarks = benchmarks self.strategy_dict: Dict[int, Strategy] = {} self.problem_dict: Dict[int, BenchmarkProblem] = {} def get_strategy(self, strategy_id: int) -> Strategy: return self.strategy_dict[strategy_id] def get_problem(self, problem_id: int) -> BenchmarkProblem: return self.problem_dict[problem_id] def make_problems(self) -> List[BenchmarkProblem]: """Generate the benchmark problems for the calibration experiment. Returns: A list of :class:`BenchmarkProblem` objects""" circuits = [] for i, benchmark in enumerate(self.benchmarks): circuit_type = benchmark["circuit_type"] num_qubits = benchmark["num_qubits"] # Set default to return correct type depth = benchmark.get("circuit_depth", -1) if circuit_type == "ghz": circuit = generate_ghz_circuit(num_qubits) ideal = {"0" * num_qubits: 0.5, "1" * num_qubits: 0.5} elif circuit_type == "w": circuit = generate_w_circuit(num_qubits) ideal = {} for i in range(num_qubits): bitstring = "0" * i + "1" + "0" * (num_qubits - i - 1) ideal[bitstring] = 1 / num_qubits elif circuit_type == "rb": circuit = generate_rb_circuits(num_qubits, depth)[0] ideal = {"0" * num_qubits: 1.0} elif circuit_type == "rotated_rb": theta = benchmark["theta"] if num_qubits == 1: circuit = generate_rotated_rb_circuits(num_qubits, depth)[ 0 ] p = (2 / 3) * np.sin(theta / 2) ** 2 ideal = {"0": p, "1": 1 - p} else: raise NotImplementedError( """rotated rb circuits with >1 qubits not yet supported in calibration""" ) elif circuit_type == "mirror": seed = benchmark.get("circuit_seed", None) circuit, bitstring_list = generate_mirror_circuit( nlayers=depth, two_qubit_gate_prob=1.0, connectivity_graph=nx.complete_graph(num_qubits), seed=seed, ) ideal_bitstring = "".join(map(str, bitstring_list)) ideal = {ideal_bitstring: 1.0} elif circuit_type == "qv": raise NotImplementedError( "quantum volume circuits not yet supported in calibration" ) else: raise ValueError( "invalid value passed for `circuit_types`. Must be " "one of `ghz`, `rb`, `mirror`, `w`, or `qv`, " f"but got {circuit_type}." ) circuit = cast(cirq.Circuit, circuit) problem = BenchmarkProblem( id=i, circuit=circuit, type=circuit_type, ideal_distribution=ideal, ) circuits.append(problem) self.problem_dict[problem.id] = problem return circuits def make_strategies(self) -> List[Strategy]: """Generates a list of :class:`Strategy` objects using the specified configurations. Returns: A list of :class:`Strategy` objects.""" funcs = [] for i, (technique, params) in enumerate( zip(self.techniques, self.technique_params) ): params_copy = params.copy() del params_copy["technique"] strategy = Strategy( id=i, technique=technique, technique_params=params_copy ) funcs.append(strategy) self.strategy_dict[strategy.id] = strategy return funcs ZNE_SETTINGS = Settings( benchmarks=[ { "circuit_type": "ghz", "num_qubits": 2, }, { "circuit_type": "w", "num_qubits": 2, }, { "circuit_type": "rb", "num_qubits": 2, "circuit_depth": 7, }, { "circuit_type": "mirror", "num_qubits": 2, "circuit_depth": 7, "circuit_seed": 1, }, ], strategies=[ { "technique": "zne", "scale_noise": fold_global, "factory": RichardsonFactory([1.0, 2.0, 3.0]), }, { "technique": "zne", "scale_noise": fold_global, "factory": RichardsonFactory([1.0, 3.0, 5.0]), }, { "technique": "zne", "scale_noise": fold_global, "factory": LinearFactory([1.0, 2.0, 3.0]), }, { "technique": "zne", "scale_noise": fold_global, "factory": LinearFactory([1.0, 3.0, 5.0]), }, { "technique": "zne", "scale_noise": fold_gates_at_random, "factory": RichardsonFactory([1.0, 2.0, 3.0]), }, { "technique": "zne", "scale_noise": fold_gates_at_random, "factory": RichardsonFactory([1.0, 3.0, 5.0]), }, { "technique": "zne", "scale_noise": fold_gates_at_random, "factory": LinearFactory([1.0, 2.0, 3.0]), }, { "technique": "zne", "scale_noise": fold_gates_at_random, "factory": LinearFactory([1.0, 3.0, 5.0]), }, ], ) PEC_SETTINGS = Settings( benchmarks=[ { "circuit_type": "ghz", "num_qubits": 2, }, { "circuit_type": "w", "num_qubits": 2, }, { "circuit_type": "rb", "num_qubits": 2, "circuit_depth": 7, }, { "circuit_type": "mirror", "num_qubits": 2, "circuit_depth": 7, "circuit_seed": 1, }, ], strategies=[ { "technique": "pec", "representation_function": ( represent_operation_with_local_depolarizing_noise ), "is_qubit_dependent": False, "noise_level": 0.001, "num_samples": 200, "force_run_all": False, }, { "technique": "pec", "representation_function": ( represent_operation_with_local_depolarizing_noise ), "is_qubit_dependent": False, "noise_level": 0.01, "num_samples": 200, "force_run_all": False, }, ], ) DefaultStrategy = Strategy(0, MitigationTechnique.RAW, {})
mitiq/mitiq/calibration/settings.py/0
{ "file_path": "mitiq/mitiq/calibration/settings.py", "repo_id": "mitiq", "token_count": 8815 }
18
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Built-in rules determining what DDD sequence should be applied in a given slack window.""" from mitiq.ddd.rules.rules import xx, xyxy, yy, general_rule, repeated_rule
mitiq/mitiq/ddd/rules/__init__.py/0
{ "file_path": "mitiq/mitiq/ddd/rules/__init__.py", "repo_id": "mitiq", "token_count": 94 }
19
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. from mitiq.interface.mitiq_pennylane.conversions import ( from_pennylane, to_pennylane, UnsupportedQuantumTapeError, )
mitiq/mitiq/interface/mitiq_pennylane/__init__.py/0
{ "file_path": "mitiq/mitiq/interface/mitiq_pennylane/__init__.py", "repo_id": "mitiq", "token_count": 100 }
20
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Unit tests for qiskit executors (qiskit_utils.py).""" import numpy as np import pytest from qiskit import QuantumCircuit from qiskit_ibm_runtime.fake_provider import FakeLima from mitiq import MeasurementResult, Observable, PauliString from mitiq.interface.mitiq_qiskit.qiskit_utils import ( compute_expectation_value_on_noisy_backend, execute, execute_with_noise, execute_with_shots, execute_with_shots_and_noise, initialized_depolarizing_noise, sample_bitstrings, ) NOISE = 0.007 ONE_QUBIT_GS_PROJECTOR = np.array([[1, 0], [0, 0]]) TWO_QUBIT_GS_PROJECTOR = np.diag([1, 0, 0, 0]) SHOTS = 1_000 def test_execute(): """Tests the Qiskit wavefunction simulation executor returns appropriate expectation value given an observable. """ circ = QuantumCircuit(1) expected_value = execute(circ, obs=ONE_QUBIT_GS_PROJECTOR) assert expected_value == 1.0 second_circ = QuantumCircuit(1) second_circ.x(0) expected_value = execute(second_circ, obs=ONE_QUBIT_GS_PROJECTOR) assert expected_value == 0.0 def test_execute_with_shots(): """Tests the Qiskit wavefunction sampling simulation executor returns appropriate expectation value given an observable. """ circ = QuantumCircuit(1, 1) expectation_value = execute_with_shots( circuit=circ, obs=ONE_QUBIT_GS_PROJECTOR, shots=SHOTS ) assert expectation_value == 1.0 second_circ = QuantumCircuit(1) second_circ.x(0) expectation_value = execute_with_shots( circuit=second_circ, obs=ONE_QUBIT_GS_PROJECTOR, shots=SHOTS ) assert expectation_value == 0.0 def test_execute_with_depolarizing_noise_single_qubit(): """Tests the noisy sampling executor across increasing levels of single qubit gate noise """ single_qubit_circ = QuantumCircuit(1) # noise model is defined on gates so include the gate to # demonstrate noise single_qubit_circ.z(0) noiseless_exp_value = 1.0 expectation_value = execute_with_noise( circuit=single_qubit_circ, obs=ONE_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), ) # anticipate that the expectation value will be less than # the noiseless simulation of the same circuit assert expectation_value < noiseless_exp_value def test_execute_with_depolarizing_noise_two_qubit(): """Tests the noisy sampling executor across increasing levels of two qubit gate noise. """ two_qubit_circ = QuantumCircuit(2) # noise model is defined on gates so include the gate to # demonstrate noise two_qubit_circ.cx(0, 1) noiseless_exp_value = 1.0 expectation_value = execute_with_noise( circuit=two_qubit_circ, obs=TWO_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), ) # anticipate that the expectation value will be less than # the noiseless simulation of the same circuit assert expectation_value < noiseless_exp_value def test_execute_with_shots_and_depolarizing_noise_single_qubit(): """Tests the noisy sampling executor across increasing levels of single qubit gate noise. """ single_qubit_circ = QuantumCircuit(1, 1) # noise model is defined on gates so include the gate to # demonstrate noise single_qubit_circ.z(0) noiseless_exp_value = 1.0 expectation_value = execute_with_shots_and_noise( circuit=single_qubit_circ, obs=ONE_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), shots=SHOTS, ) # anticipate that the expectation value will be less than # the noiseless simulation of the same circuit assert expectation_value < noiseless_exp_value def test_execute_with_shots_and_depolarizing_noise_two_qubit(): """Tests the noisy sampling executor across increasing levels of two qubit gate noise. """ two_qubit_circ = QuantumCircuit(2, 2) # noise model is defined on gates so include the gate to # demonstrate noise two_qubit_circ.cx(0, 1) noiseless_exp_value = 1.0 expectation_value = execute_with_shots_and_noise( circuit=two_qubit_circ, obs=TWO_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), shots=SHOTS, ) # anticipate that the expectation value will be less than # the noiseless simulation of the same circuit assert expectation_value < noiseless_exp_value def test_circuit_is_not_mutated_by_executors(): single_qubit_circ = QuantumCircuit(1, 1) single_qubit_circ.z(0) expected_circuit = single_qubit_circ.copy() execute_with_shots_and_noise( circuit=single_qubit_circ, obs=ONE_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), shots=SHOTS, ) assert single_qubit_circ.data == expected_circuit.data assert single_qubit_circ == expected_circuit execute_with_noise( circuit=single_qubit_circ, obs=ONE_QUBIT_GS_PROJECTOR, noise_model=initialized_depolarizing_noise(NOISE), ) assert single_qubit_circ.data == expected_circuit.data assert single_qubit_circ == expected_circuit def test_sample_bitstrings(): """Tests that the function sample_bitstrings returns a valid mitiq.MeasurementResult. """ two_qubit_circ = QuantumCircuit(2, 1) two_qubit_circ.cx(0, 1) two_qubit_circ.measure(0, 0) measurement_result = sample_bitstrings( circuit=two_qubit_circ, backend=None, noise_model=initialized_depolarizing_noise(0), shots=5, ) assert measurement_result.result == [[0], [0], [0], [0], [0]] assert measurement_result.qubit_indices == (0,) def test_sample_bitstrings_with_measure_all(): """Tests that the function sample_bitstrings returns a valid mitiq.MeasurementResult when "measure_all" is True. """ two_qubit_circ = QuantumCircuit(2) two_qubit_circ.cx(0, 1) measurement_result = sample_bitstrings( circuit=two_qubit_circ, backend=None, noise_model=initialized_depolarizing_noise(0), shots=2, measure_all=True, ) assert measurement_result.result == [[0, 0], [0, 0]] assert measurement_result.qubit_indices == (0, 1) assert isinstance(measurement_result, MeasurementResult) def test_sample_bitstrings_with_backend(): """Tests that the function sample_bitstrings returns a valid mitiq.MeasurementResult if a qiskit backend is used. """ two_qubit_circ = QuantumCircuit(2) two_qubit_circ.cx(0, 1) measurement_result = sample_bitstrings( circuit=two_qubit_circ, backend=FakeLima(), shots=5, measure_all=True, ) assert len(measurement_result.result) == 5 assert len(measurement_result.result[0]) == 2 assert measurement_result.qubit_indices == (0, 1) def test_sample_bitstrings_error_message(): """Tests that an error is given backend and nose_model are both None.""" two_qubit_circ = QuantumCircuit(2) two_qubit_circ.cx(0, 1) with pytest.raises(ValueError, match="Either a backend or a noise model"): sample_bitstrings( circuit=two_qubit_circ, shots=5, ) def test_compute_expectation_value_on_noisy_backend_with_noise_model(): """Tests the evaluation of an expectation value assuming a noise model.""" obs = Observable(PauliString("X")) qiskit_circuit = QuantumCircuit(1) qiskit_circuit.h(0) # First we try without noise noiseless_expval = compute_expectation_value_on_noisy_backend( qiskit_circuit, obs, noise_model=initialized_depolarizing_noise(0), ) assert isinstance(noiseless_expval, complex) assert np.isclose(np.imag(noiseless_expval), 0.0) assert np.isclose(np.real(noiseless_expval), 1.0) # Now we try with noise expval = compute_expectation_value_on_noisy_backend( qiskit_circuit, obs, noise_model=initialized_depolarizing_noise(0.01), ) assert isinstance(expval, complex) assert np.isclose(np.imag(expval), 0.0) # With noise the result is non-deterministic assert 0.9 < np.real(expval) < 1.0 def test_compute_expectation_value_on_noisy_backend_with_qiskit_backend(): """Tests the evaluation of an expectation value on a noisy backed""" obs = Observable(PauliString("X")) qiskit_circuit = QuantumCircuit(1) qiskit_circuit.h(0) expval = compute_expectation_value_on_noisy_backend( qiskit_circuit, obs, backend=FakeLima(), ) assert isinstance(expval, complex) assert np.isclose(np.imag(expval), 0.0) # With noise the result is non-deterministic assert 0.9 < np.real(expval) < 1.0
mitiq/mitiq/interface/mitiq_qiskit/tests/test_qiskit_utils.py/0
{ "file_path": "mitiq/mitiq/interface/mitiq_qiskit/tests/test_qiskit_utils.py", "repo_id": "mitiq", "token_count": 3526 }
21
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. from mitiq.pec.representations.depolarizing import ( represent_operation_with_global_depolarizing_noise, represent_operation_with_local_depolarizing_noise, represent_operations_in_circuit_with_global_depolarizing_noise, represent_operations_in_circuit_with_local_depolarizing_noise, global_depolarizing_kraus, local_depolarizing_kraus, ) from mitiq.pec.representations.damping import ( _represent_operation_with_amplitude_damping_noise, amplitude_damping_kraus, ) from mitiq.pec.representations.optimal import ( minimize_one_norm, find_optimal_representation, ) from mitiq.pec.representations.biased_noise import ( represent_operation_with_local_biased_noise, ) from mitiq.pec.representations.learning import ( depolarizing_noise_loss_function, biased_noise_loss_function, learn_depolarizing_noise_parameter, learn_biased_noise_parameters, )
mitiq/mitiq/pec/representations/__init__.py/0
{ "file_path": "mitiq/mitiq/pec/representations/__init__.py", "repo_id": "mitiq", "token_count": 382 }
22
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. from itertools import product import numpy as np from cirq import ( CNOT, CZ, AmplitudeDampingChannel, Circuit, DepolarizingChannel, H, I, LineQubit, ResetChannel, X, Y, Z, kraus, reset, ) from pytest import mark, raises from mitiq.interface import convert_from_mitiq from mitiq.pec.channels import ( _circuit_to_choi, _operation_to_choi, choi_to_super, kraus_to_choi, kraus_to_super, ) from mitiq.pec.representations import ( _represent_operation_with_amplitude_damping_noise, amplitude_damping_kraus, global_depolarizing_kraus, represent_operation_with_local_depolarizing_noise, ) from mitiq.pec.representations.optimal import ( find_optimal_representation, minimize_one_norm, ) from mitiq.pec.types import NoisyOperation def test_minimize_one_norm_failure_error(): ideal_matrix = np.random.rand(2, 2) basis_matrices = [np.random.rand(2, 2)] with raises(RuntimeError, match="optimal representation failed"): minimize_one_norm(ideal_matrix, basis_matrices) def test_minimize_one_norm_with_depolarized_choi(): for noise_level in [0.01, 0.02, 0.03]: q = LineQubit(0) ideal_matrix = _operation_to_choi(H(q)) basis_matrices = [ _operation_to_choi( [H(q), gate(q), DepolarizingChannel(noise_level, 1)(q)] ) for gate in [I, X, Y, Z, H] ] optimal_coeffs = minimize_one_norm(ideal_matrix, basis_matrices) represented_mat = sum( [eta * mat for eta, mat in zip(optimal_coeffs, basis_matrices)] ) assert np.allclose(ideal_matrix, represented_mat) # Optimal analytic result by Takagi (arXiv:2006.12509) eps = 4.0 / 3.0 * noise_level expected = (1.0 + 0.5 * eps) / (1.0 - eps) assert np.isclose(np.linalg.norm(optimal_coeffs, 1), expected) def test_minimize_one_norm_with_depolarized_superoperators(): for noise_level in [0.01, 0.02, 0.03]: depo_kraus = global_depolarizing_kraus(noise_level, num_qubits=1) depo_super = kraus_to_super(depo_kraus) ideal_matrix = kraus_to_super(kraus(H)) basis_matrices = [ depo_super @ kraus_to_super(kraus(gate)) @ ideal_matrix for gate in [I, X, Y, Z, H] ] optimal_coeffs = minimize_one_norm(ideal_matrix, basis_matrices) represented_mat = sum( [eta * mat for eta, mat in zip(optimal_coeffs, basis_matrices)] ) assert np.allclose(ideal_matrix, represented_mat) # Optimal analytic result by Takagi (arXiv:2006.12509) eps = 4.0 / 3.0 * noise_level expected = (1.0 + 0.5 * eps) / (1.0 - eps) assert np.isclose(np.linalg.norm(optimal_coeffs, 1), expected) def test_minimize_one_norm_with_amp_damp_choi(): for noise_level in [0.01, 0.02, 0.03]: q = LineQubit(0) ideal_matrix = _operation_to_choi(H(q)) basis_matrices = [ _operation_to_choi( [H(q), gate(q), AmplitudeDampingChannel(noise_level)(q)] ) for gate in [I, Z] ] # Append reset channel reset_kraus = kraus(ResetChannel()) basis_matrices.append(kraus_to_choi(reset_kraus)) optimal_coeffs = minimize_one_norm(ideal_matrix, basis_matrices) represented_mat = sum( [eta * mat for eta, mat in zip(optimal_coeffs, basis_matrices)] ) assert np.allclose(ideal_matrix, represented_mat) # Optimal analytic result by Takagi (arXiv:2006.12509) expected = (1.0 + noise_level) / (1.0 - noise_level) assert np.isclose(np.linalg.norm(optimal_coeffs, 1), expected) def test_minimize_one_norm_with_amp_damp_superoperators(): for noise_level in [0.01, 0.02, 0.03]: damp_kraus = amplitude_damping_kraus(noise_level, num_qubits=1) damp_super = kraus_to_super(damp_kraus) ideal_matrix = kraus_to_super(kraus(H)) basis_matrices = [ damp_super @ kraus_to_super(kraus(gate)) @ ideal_matrix for gate in [I, Z] ] # Append reset channel reset_kraus = kraus(ResetChannel()) basis_matrices.append(kraus_to_super(reset_kraus)) optimal_coeffs = minimize_one_norm( ideal_matrix, basis_matrices, tol=1.0e-6 ) represented_mat = sum( [eta * mat for eta, mat in zip(optimal_coeffs, basis_matrices)] ) assert np.allclose(ideal_matrix, represented_mat) # Optimal analytic result by Takagi (arXiv:2006.12509) expected = (1.0 + noise_level) / (1.0 - noise_level) assert np.isclose(np.linalg.norm(optimal_coeffs, 1), expected) def test_minimize_one_norm_tolerance(): depo_kraus = global_depolarizing_kraus(noise_level=0.1, num_qubits=1) depo_super = kraus_to_super(depo_kraus) ideal_matrix = kraus_to_super(kraus(H)) basis_matrices = [ depo_super @ kraus_to_super(kraus(gate)) @ ideal_matrix for gate in [I, X, Y, Z] ] previous_minimum = 0.0 previous_error = 1.0 for tol in [1.0e-2, 1.0e-4, 1.0e-6, 1.0e-8]: optimal_coeffs = minimize_one_norm(ideal_matrix, basis_matrices, tol) represented_mat = sum( [eta * mat for eta, mat in zip(optimal_coeffs, basis_matrices)] ) worst_case_error = np.max(abs(ideal_matrix - represented_mat)) minimum = np.linalg.norm(optimal_coeffs, 1) # Reducing "tol" should decrease the worst case error # and should also increase the objective function assert worst_case_error < previous_error assert minimum > previous_minimum previous_error = worst_case_error previous_minimum = minimum @mark.parametrize("circ_type", ["cirq", "qiskit", "pyquil", "braket"]) def test_find_optimal_representation_depolarizing_two_qubit_gates(circ_type): """Test optimal representation agrees with a known analytic result.""" for ideal_gate, noise_level in product([CNOT, CZ], [0.1, 0.5]): q = LineQubit.range(2) ideal_op = Circuit(ideal_gate(*q)) implementable_circuits = [Circuit(ideal_op)] # Append two-qubit-gate with Paulis on one qubit for gate in [X, Y, Z]: implementable_circuits.append(Circuit([ideal_op, gate(q[0])])) implementable_circuits.append(Circuit([ideal_op, gate(q[1])])) # Append two-qubit gate with Paulis on both qubits for gate_a, gate_b in product([X, Y, Z], repeat=2): implementable_circuits.append( Circuit([ideal_op, gate_a(q[0]), gate_b(q[1])]) ) noisy_circuits = [ circ + Circuit(DepolarizingChannel(noise_level).on_each(*q)) for circ in implementable_circuits ] super_operators = [ choi_to_super(_circuit_to_choi(circ)) for circ in noisy_circuits ] # Define circuits with native types implementable_native = [ convert_from_mitiq(c, circ_type) for c in implementable_circuits ] ideal_op_native = convert_from_mitiq(ideal_op, circ_type) noisy_operations = [ NoisyOperation(ideal, real) for ideal, real in zip(implementable_native, super_operators) ] # Find optimal representation rep = find_optimal_representation( ideal_op_native, noisy_operations, tol=1.0e-8 ) # Expected analytical result expected_rep = represent_operation_with_local_depolarizing_noise( ideal_op_native, noise_level, ) assert np.allclose(np.sort(rep.coeffs), np.sort(expected_rep.coeffs)) assert rep == expected_rep @mark.parametrize("circ_type", ["cirq", "qiskit", "pyquil", "braket"]) def test_find_optimal_representation_single_qubit_depolarizing(circ_type): """Test optimal representation agrees with a known analytic result.""" for ideal_gate, noise_level in product([X, Y, H], [0.1, 0.3]): q = LineQubit(0) ideal_op = Circuit(ideal_gate(q)) implementable_circuits = [Circuit(ideal_op)] # Add ideal gate followed by Paulis for gate in [X, Y, Z]: implementable_circuits.append(Circuit([ideal_op, gate(q)])) noisy_circuits = [ circ + Circuit(DepolarizingChannel(noise_level).on_each(q)) for circ in implementable_circuits ] super_operators = [ choi_to_super(_circuit_to_choi(circ)) for circ in noisy_circuits ] # Define circuits with native types implementable_native = [ convert_from_mitiq(c, circ_type) for c in implementable_circuits ] ideal_op_native = convert_from_mitiq(ideal_op, circ_type) noisy_operations = [ NoisyOperation(ideal, real) for ideal, real in zip(implementable_native, super_operators) ] # Find optimal representation rep = find_optimal_representation( ideal_op_native, noisy_operations, tol=1.0e-8, ) # Expected analytical result expected_rep = represent_operation_with_local_depolarizing_noise( ideal_op_native, noise_level, ) assert np.allclose(np.sort(rep.coeffs), np.sort(expected_rep.coeffs)) assert rep == expected_rep # After fixing the GitHub issue gh-702, other circuit types could be added. @mark.parametrize("circ_type", ["cirq"]) def test_find_optimal_representation_single_qubit_amp_damping(circ_type): """Test optimal representation of agrees with a known analytic result.""" for ideal_gate, noise_level in product([X, Y, H], [0.1, 0.3]): q = LineQubit(0) ideal_op = Circuit(ideal_gate(q)) implementable_circuits = [Circuit(ideal_op)] # Add ideal gate followed by Paulis and reset for gate in [Z, reset]: implementable_circuits.append(Circuit([ideal_op, gate(q)])) noisy_circuits = [ circ + Circuit(AmplitudeDampingChannel(noise_level).on_each(q)) for circ in implementable_circuits ] super_operators = [ choi_to_super(_circuit_to_choi(circ)) for circ in noisy_circuits ] # Define circuits with native types implementable_native = [ convert_from_mitiq(c, circ_type) for c in implementable_circuits ] ideal_op_native = convert_from_mitiq(ideal_op, circ_type) noisy_operations = [ NoisyOperation(ideal, real) for ideal, real in zip(implementable_native, super_operators) ] # Find optimal representation rep = find_optimal_representation( ideal_op_native, noisy_operations, tol=1.0e-7, initial_guess=[0, 0, 0], ) # Expected analytical result expected_rep = _represent_operation_with_amplitude_damping_noise( ideal_op_native, noise_level, ) assert np.allclose(np.sort(rep.coeffs), np.sort(expected_rep.coeffs)) assert rep == expected_rep def test_find_optimal_representation_no_superoperator_error(): q = LineQubit(0) # Define noisy operation without superoperator matrix noisy_op = NoisyOperation(Circuit(X(q))) with raises(ValueError, match="numerical superoperator matrix"): find_optimal_representation(Circuit(X(q)), [noisy_op]) def test_initial_guess_in_minimize_one_norm(): for noise_level in [0.7, 0.9]: depo_kraus = global_depolarizing_kraus(noise_level, num_qubits=1) depo_super = kraus_to_super(depo_kraus) ideal_matrix = kraus_to_super(kraus(H)) basis_matrices = [ depo_super @ kraus_to_super(kraus(gate)) @ ideal_matrix for gate in [I, X, Y, Z, H] ] optimal_coeffs = minimize_one_norm( ideal_matrix, basis_matrices, initial_guess=[1.0, 1.0, 1.0, 1.0, 1.0], ) represented_mat = sum( [eta * mat for eta, mat in zip(optimal_coeffs, basis_matrices)] ) assert np.allclose(ideal_matrix, represented_mat) # Test bad argument with raises(ValueError, match="shapes"): minimize_one_norm( ideal_matrix, basis_matrices, initial_guess=[1], )
mitiq/mitiq/pec/representations/tests/test_optimal.py/0
{ "file_path": "mitiq/mitiq/pec/representations/tests/test_optimal.py", "repo_id": "mitiq", "token_count": 5962 }
23
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Run experiments without error mitigation.""" from typing import Callable, Optional, Union from mitiq import QPROGRAM, Executor, Observable, QuantumResult def execute( circuit: QPROGRAM, executor: Union[Executor, Callable[[QPROGRAM], QuantumResult]], observable: Optional[Observable] = None, ) -> float: """Evaluates the expectation value associated to the input circuit without using error mitigation. The only purpose of this function is to provide the same interface for non-error-mitigated values as the rest of the techniques in Mitiq. This is useful when comparing error-mitigated results to non-error-mitigated results. Args: circuit: The circuit to run. executor: Executes a circuit and returns a `QuantumResult`. observable: Observable to compute the expectation value of. If None, the `executor` must return an expectation value. Otherwise, the `QuantumResult` returned by `executor` is used to compute the expectation of the observable. """ if not isinstance(executor, Executor): executor = Executor(executor) return executor.evaluate(circuit, observable)[0]
mitiq/mitiq/raw/raw.py/0
{ "file_path": "mitiq/mitiq/raw/raw.py", "repo_id": "mitiq", "token_count": 427 }
24
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Test classical shadow estimation process.""" from numbers import Number import cirq import mitiq from mitiq import MeasurementResult from mitiq.interface.mitiq_cirq.cirq_utils import ( sample_bitstrings as cirq_sample_bitstrings, ) from mitiq.shadows.shadows import ( classical_post_processing, pauli_twirling_calibrate, shadow_quantum_processing, ) # define a fully entangled state num_qubits: int = 2 qubits = cirq.LineQubit.range(num_qubits) circuit = cirq.Circuit([cirq.H(q) for q in qubits]) circuit.append(cirq.CNOT(qubits[0], qubits[1])) observables = [mitiq.PauliString("X", support=(i,)) for i in range(num_qubits)] def executor( circuit: cirq.Circuit, ) -> MeasurementResult: return cirq_sample_bitstrings( circuit, noise_level=(0,), shots=1, sampler=cirq.Simulator(), ) def test_pauli_twirling_calibrate(): # Call the function with valid inputs result = pauli_twirling_calibrate( qubits=qubits, executor=executor, num_total_measurements_calibration=2 ) # Check that the dictionary contains the correct number of entries assert len(result) <= 2**num_qubits for value in result.values(): assert isinstance(value, Number) # Call shadow_quantum_processing to get shadow_outcomes shadow_outcomes = (["11", "00"], ["ZZ", "XX"]) # Call the function with valid inputs result = pauli_twirling_calibrate( zero_state_shadow_outcomes=shadow_outcomes, num_total_measurements_calibration=2, ) # Check that the dictionary contains the correct number of entries assert len(result) <= 2**num_qubits for value in result.values(): assert isinstance(value, Number) def test_shadow_quantum_processing(): # Call the function with valid inputs result = shadow_quantum_processing( circuit, executor, num_total_measurements_shadow=10 ) # Check that the result is a tuple assert isinstance(result, tuple), f"Expected a tuple, got {type(result)}" # Check that the tuple contains two lists assert ( len(result) == 2 ), f"Expected two lists in the tuple, got {len(result)}" assert isinstance(result[0], list) assert isinstance(result[1], list) def test_classical_post_processing(): # Call shadow_quantum_processing to get shadow_outcomes shadow_outcomes = (["11", "00"], ["ZZ", "XX"]) # Call pauli_twirling_calibrate to get calibration_results calibration_results = {"00": 1, "01": 1 / 3, "10": 1 / 3, "11": 1 / 9} # Call the function with valid inputs and state_reconstruction=True result = classical_post_processing( shadow_outcomes, state_reconstruction=True ) # Check that the result is a dictionary assert isinstance( result, dict ), f"Expected a dictionary, got {type(result)}" # Check that the dictionary contains the expected keys assert "reconstructed_state" in result # Call the function with valid inputs and observables provided result = classical_post_processing( shadow_outcomes, observables=observables ) result_cal = classical_post_processing( shadow_outcomes, calibration_results=calibration_results, observables=observables, k_shadows=1, ) # Check that the result is a dictionary assert isinstance(result, dict) assert result_cal == result # Check that the dictionary contains the expected keys for obs in observables: assert str(obs) in result assert isinstance(result[str(obs)], float)
mitiq/mitiq/shadows/tests/test_shadows.py/0
{ "file_path": "mitiq/mitiq/shadows/tests/test_shadows.py", "repo_id": "mitiq", "token_count": 1349 }
25
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. import copy from typing import Callable, List, Optional, cast import numpy as np from cirq import ( Circuit, CXPowGate, CZPowGate, EigenGate, HPowGate, MeasurementGate, Moment, Qid, XPowGate, YPowGate, ZPowGate, ) from mitiq import QPROGRAM from mitiq.interface import accept_qprogram_and_validate class GateTypeException(Exception): pass def _get_base_gate(gate: EigenGate) -> EigenGate: BASE_GATES = [ZPowGate, HPowGate, XPowGate, YPowGate, CXPowGate, CZPowGate] for base_gate in BASE_GATES: if isinstance(gate, base_gate): return cast(EigenGate, base_gate) raise GateTypeException( "Must have circuit be made of rotation gates. " "Your gate {} may not be supported".format(gate) ) class CircuitMismatchException(Exception): pass def _generate_parameter_calibration_circuit( qubits: List[Qid], depth: int, gate: EigenGate ) -> Circuit: """Generates a circuit which should be the identity. Given a rotation gate R(param), it applies R(2 * pi / depth) depth times, resulting in R(2*pi). Requires that the gate is periodic in 2*pi. Args: qubits: A list of qubits. depth: The length of the circuit to create. gate: The base gate to apply several times, must be periodic in 2*pi. Returns: A parameter calibration circuit that can be used for estimating the parameter noise of the input gate. """ num_qubits = gate().num_qubits() if num_qubits != len(qubits): raise CircuitMismatchException( "Number of qubits does not match domain size of gate." ) return Circuit( gate(exponent=2 * np.pi / depth).on(*qubits) for _ in range(depth) ) def compute_parameter_variance( executor: Callable[..., float], gate: EigenGate, qubit: Qid, depth: int = 100, ) -> float: """Given an executor and a gate, determines the effective variance in the control parameter that can be used as the ``base_variance`` argument in ``mitiq.zne.scaling.scale_parameters``. Note: Only works for one qubit gates for now. Args: executor: A function that takes in a quantum circuit and returns an expectation value. gate: The quantum gate that you wish to profile. qubit: The index of the qubit you wish to profile. depth: The number of operations you would like to use to profile your gate. Returns: The estimated variance of the control parameter. """ base_gate = _get_base_gate(gate) circuit = _generate_parameter_calibration_circuit( [qubit], depth, base_gate ) expectation = executor(circuit) error_prob = (1 - np.power(2 * expectation - 1, 1 / depth)) / 2 variance = -0.5 * np.log(1 - 2 * error_prob) return variance @accept_qprogram_and_validate def scale_parameters( circuit: QPROGRAM, scale_factor: float, base_variance: float, seed: Optional[int] = None, ) -> Circuit: """Applies parameter-noise scaling to the input circuit, assuming that each gate has the same base level of noise. Args: circuit: The circuit to scale as a QPROGRAM. All measurements should be in the last moment of the circuit. scale_factor: The amount to scale the base noise level by. base_variance: The base level (variance) of parameter noise, assumed to be the same for each gate of the circuit. seed: Optional seed for random number generator. Returns: The parameter noise scaled circuit. """ final_moments = [] noise = (scale_factor - 1) * base_variance rng = np.random.RandomState(seed) for moment in circuit: curr_moment = [] for op in moment.operations: # type: ignore gate = copy.deepcopy(op.gate) qubits = op.qubits if isinstance(gate, MeasurementGate): curr_moment.append(gate(*qubits)) else: assert isinstance(gate, EigenGate) base_gate = _get_base_gate(gate) param = cast(float, gate.exponent) * np.pi error = rng.normal(loc=0.0, scale=np.sqrt(noise)) new_param = param + error curr_moment.append( base_gate(exponent=new_param / np.pi)(*qubits) ) final_moments.append(Moment(curr_moment)) return Circuit(final_moments)
mitiq/mitiq/zne/scaling/parameter.py/0
{ "file_path": "mitiq/mitiq/zne/scaling/parameter.py", "repo_id": "mitiq", "token_count": 1883 }
26
# Copyright 2021-2024 Xanadu Quantum Technologies Inc. # 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. r""" This module contains tests for applying operations on PennyLane IBMQ devices. """ import pytest import numpy as np import pennylane as qml from scipy.linalg import block_diag from conftest import U, U2 # pylint: disable=protected-access, too-many-arguments, too-few-public-methods np.random.seed(42) # global variables and rotations I = np.identity(2) X = np.array([[0, 1], [1, 0]]) Y = np.array([[0, -1j], [1j, 0]]) Z = np.array([[1, 0], [0, -1]]) H = np.array([[1, 1], [1, -1]]) / np.sqrt(2) S = np.diag([1, 1j]) T = np.diag([1, np.exp(1j * np.pi / 4)]) SWAP = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) CNOT = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) CZ = np.diag([1, 1, 1, -1]) toffoli = np.diag([1 for i in range(8)]) toffoli[6:8, 6:8] = np.array([[0, 1], [1, 0]]) CSWAP = block_diag(I, I, SWAP) # pylint: disable=unnecessary-lambda-assignment phase_shift = lambda phi: np.array([[1, 0], [0, np.exp(1j * phi)]]) rx = lambda theta: np.cos(theta / 2) * I + 1j * np.sin(-theta / 2) * X ry = lambda theta: np.cos(theta / 2) * I + 1j * np.sin(-theta / 2) * Y rz = lambda theta: np.cos(theta / 2) * I + 1j * np.sin(-theta / 2) * Z rot = lambda a, b, c: rz(c) @ (ry(b) @ rz(a)) crz = lambda theta: np.array( [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, np.exp(-1j * theta / 2), 0], [0, 0, 0, np.exp(1j * theta / 2)], ] ) isingxx = lambda phi: np.array( [ [np.cos(phi / 2), 0, 0, -1j * np.sin(phi / 2)], [0, np.cos(phi / 2), -1j * np.sin(phi / 2), 0], [0, -1j * np.sin(phi / 2), np.cos(phi / 2), 0], [-1j * np.sin(phi / 2), 0, 0, np.cos(phi / 2)], ] ) isingyy = lambda phi: np.array( [ [np.cos(phi / 2), 0, 0, 1j * np.sin(phi / 2)], [0, np.cos(phi / 2), -1j * np.sin(phi / 2), 0], [0, -1j * np.sin(phi / 2), np.cos(phi / 2), 0], [1j * np.sin(phi / 2), 0, 0, np.cos(phi / 2)], ] ) isingzz = lambda phi: np.array( [ [np.exp(-1.0j * phi / 2), 0, 0, 0], [0, np.exp(1.0j * phi / 2), 0, 0], [0, 0, np.exp(1.0j * phi / 2), 0], [0, 0, 0, np.exp(-1.0j * phi / 2)], ] ) single_qubit_operations = [ qml.Identity, qml.PauliX, qml.PauliY, qml.PauliZ, qml.Hadamard, qml.S, qml.T, qml.SX, qml.adjoint(qml.T), qml.adjoint(qml.S), qml.adjoint(qml.SX), ] single_qubit_operations_param = [qml.PhaseShift, qml.RX, qml.RY, qml.RZ] two_qubit = [qml.CNOT, qml.SWAP, qml.CZ, qml.ISWAP] two_qubit_param = [qml.CRZ, qml.IsingXX, qml.IsingYY, qml.IsingZZ] three_qubit = [qml.Toffoli, qml.CSWAP] @pytest.mark.parametrize("shots", [None]) @pytest.mark.usefixtures("skip_unitary") class TestAnalyticApply: """Test application of PennyLane operations with analytic calculation.""" @pytest.mark.parametrize("op", [qml.QubitStateVector, qml.StatePrep]) def test_qubit_state_vector(self, op, init_state, device, tol): """Test that the QubitStateVector and StatePrep operations produce the expected results with the apply method.""" dev = device(1) state = init_state(1) dev.apply([op(state, wires=[0])]) res = np.abs(dev.state) ** 2 expected = np.abs(state) ** 2 assert np.allclose(res, expected, **tol) @pytest.mark.parametrize("operation", single_qubit_operations) def test_single_qubit_operations_no_parameters(self, init_state, device, operation, tol): """Test that single qubit operations that take no parameters work fine with the apply method.""" dev = device(1) state = init_state(1) applied_operation = operation(wires=[0]) dev.apply([qml.StatePrep(state, wires=[0]), applied_operation]) res = np.abs(dev.state) ** 2 expected = np.abs(applied_operation.matrix() @ state) ** 2 assert np.allclose(res, expected, **tol) @pytest.mark.parametrize("theta", [0.5432, -0.232]) @pytest.mark.parametrize("operation", single_qubit_operations_param) def test_single_qubit_operations_parameters(self, init_state, device, operation, theta, tol): """Test that single qubit parametrized operations work fine with the apply method.""" dev = device(1) state = init_state(1) applied_operation = operation(theta, wires=[0]) dev.apply([qml.StatePrep(state, wires=[0]), applied_operation]) res = np.abs(dev.state) ** 2 expected = np.abs(applied_operation.matrix() @ state) ** 2 assert np.allclose(res, expected, **tol) @pytest.mark.parametrize("operation", two_qubit) def test_two_qubit_operations_no_parameters(self, init_state, device, operation, tol): """Test that two qubit operations that take no parameters work fine with the apply method.""" dev = device(2) state = init_state(2) wires = [0, 1] applied_operation = operation(wires=wires) dev.apply([qml.StatePrep(state, wires=wires), applied_operation]) res = np.abs(dev.state) ** 2 expected = np.abs(applied_operation.matrix() @ state) ** 2 assert np.allclose(res, expected, **tol) @pytest.mark.parametrize("theta", [0.5432, -0.232]) @pytest.mark.parametrize("operation", two_qubit_param) def test_two_qubit_operations_parameters(self, init_state, device, operation, theta, tol): """Test that two qubit parametrized operations work fine with the apply method.""" dev = device(2) state = init_state(2) wires = [0, 1] applied_operation = operation(theta, wires=wires) dev.apply([qml.StatePrep(state, wires=wires), applied_operation]) res = np.abs(dev.state) ** 2 expected = np.abs(applied_operation.matrix() @ state) ** 2 assert np.allclose(res, expected, **tol) @pytest.mark.parametrize("operation", three_qubit) def test_three_qubit_operations_no_parameters(self, init_state, device, operation, tol): """Test that three qubit operations that take no parameters work fine with the apply method.""" dev = device(3) state = init_state(3) applied_operation = operation(wires=[0, 1, 2]) dev.apply([qml.StatePrep(state, wires=[0, 1, 2]), applied_operation]) res = np.abs(dev.state) ** 2 expected = np.abs(applied_operation.matrix() @ state) ** 2 assert np.allclose(res, expected, **tol) @pytest.mark.parametrize("shots", [None]) @pytest.mark.usefixtures("run_only_for_unitary") class TestStateApplyUnitarySimulator: """Test application of PennyLane operations to the unitary simulator.""" def test_invalid_qubit(self, init_state, device): """Test that an exception is raised if the unitary matrix is applied on a unitary simulator.""" dev = device(1) state = init_state(1) with pytest.raises( qml.DeviceError, match="The StatePrep operation is not supported on the unitary simulator backend", ): dev.apply([qml.StatePrep(state, wires=[0])]) @pytest.mark.parametrize("shots", [8192]) @pytest.mark.usefixtures("skip_unitary") class TestNonAnalyticApply: """Test application of PennyLane operations with non-analytic calculation.""" @pytest.mark.parametrize("op", [qml.QubitStateVector, qml.StatePrep]) def test_qubit_state_vector(self, op, init_state, device, tol): """Test that the QubitStateVector and StatePrep operations produces the expected result with the apply method.""" dev = device(1) state = init_state(1) wires = [0] dev.apply([op(state, wires=wires)]) dev._samples = dev.generate_samples() res = np.fromiter(dev.probability(), dtype=np.float64) expected = np.abs(state) ** 2 assert np.allclose(res, expected, **tol) @pytest.mark.parametrize("op", [qml.QubitStateVector, qml.StatePrep]) def test_invalid_qubit_state_vector(self, op, device): """Test that an exception is raised if the state vector is the wrong size""" dev = device(2) state = np.array([0, 123.432]) wires = [0, 1] with pytest.raises(ValueError, match=r"State must be of length 4"): dev.apply([op(state, wires=wires)]) @pytest.mark.parametrize("mat", [U, U2]) def test_qubit_unitary(self, init_state, device, mat, tol): """Test that the QubitUnitary operation produces the expected result with the apply method.""" N = int(np.log2(len(mat))) dev = device(N) state = init_state(N) wires = list(range(N)) dev.apply([qml.StatePrep(state, wires=wires), qml.QubitUnitary(mat, wires=wires)]) dev._samples = dev.generate_samples() res = np.fromiter(dev.probability(), dtype=np.float64) expected = np.abs(mat @ state) ** 2 assert np.allclose(res, expected, **tol) def test_invalid_qubit_unitary(self, device): """Test that an exception is raised if the unitary matrix is the wrong size""" dev = device(2) state = np.array([[0, 123.432], [-0.432, 023.4]]) with pytest.raises(ValueError, match=r"Input unitary must be of shape"): dev.apply([qml.QubitUnitary(state, wires=[0, 1])]) @pytest.mark.parametrize("operation", single_qubit_operations) def test_single_qubit_operations_no_parameters(self, init_state, device, operation, tol): """Test that single qubit operations that take no parameters work fine with the apply method.""" dev = device(1) state = init_state(1) wires = [0] applied_operation = operation(wires=wires) dev.apply([qml.StatePrep(state, wires=wires), applied_operation]) dev._samples = dev.generate_samples() res = np.fromiter(dev.probability(), dtype=np.float64) expected = np.abs(applied_operation.matrix() @ state) ** 2 assert np.allclose(res, expected, **tol) @pytest.mark.parametrize("theta", [0.5432, -0.232]) @pytest.mark.parametrize("operation", single_qubit_operations_param) def test_single_qubit_operations_parameters(self, init_state, device, operation, theta, tol): """Test that single qubit parametrized operations work fine with the apply method.""" dev = device(1) state = init_state(1) wires = [0] applied_operation = operation(theta, wires=wires) dev.apply([qml.StatePrep(state, wires=wires), applied_operation]) dev._samples = dev.generate_samples() res = np.fromiter(dev.probability(), dtype=np.float64) expected = np.abs(applied_operation.matrix() @ state) ** 2 assert np.allclose(res, expected, **tol) @pytest.mark.parametrize("operation", two_qubit) def test_two_qubit_no_parameters(self, init_state, device, operation, tol): """Test that two qubit operations that take no parameters work fine with the apply method.""" dev = device(2) state = init_state(2) wires = [0, 1] applied_operation = operation(wires=wires) dev.apply([qml.StatePrep(state, wires=wires), applied_operation]) dev._samples = dev.generate_samples() res = np.fromiter(dev.probability(), dtype=np.float64) expected = np.abs(applied_operation.matrix() @ state) ** 2 assert np.allclose(res, expected, **tol) @pytest.mark.parametrize("theta", [0.5432, -0.232]) @pytest.mark.parametrize("operation", two_qubit_param) def test_two_qubit_operations_parameters(self, init_state, device, operation, theta, tol): """Test that two qubit parametrized operations work fine with the apply method.""" dev = device(2) state = init_state(2) wires = [0, 1] applied_operation = operation(theta, wires=wires) dev.apply([qml.StatePrep(state, wires=wires), applied_operation]) dev._samples = dev.generate_samples() res = np.fromiter(dev.probability(), dtype=np.float64) expected = np.abs(applied_operation.matrix() @ state) ** 2 assert np.allclose(res, expected, **tol) @pytest.mark.parametrize("operation", three_qubit) def test_three_qubit_no_parameters(self, init_state, device, operation, tol): """Test that three qubit operations that take no parameters work fine with the apply method.""" dev = device(3) state = init_state(3) applied_operation = operation(wires=[0, 1, 2]) wires = [0, 1, 2] dev.apply([qml.StatePrep(state, wires=wires), applied_operation]) dev._samples = dev.generate_samples() res = np.fromiter(dev.probability(), dtype=np.float64) expected = np.abs(applied_operation.matrix() @ state) ** 2 assert np.allclose(res, expected, **tol)
pennylane-qiskit/tests/test_apply.py/0
{ "file_path": "pennylane-qiskit/tests/test_apply.py", "repo_id": "pennylane-qiskit", "token_count": 5843 }
27
ignore: - "pennylane/devices/tests/*" - "pennylane/data/base/_lazy_modules.py" - "pennylane/logging/*" codecov: notify: after_n_builds: 1 comment: after_n_builds: 1 coverage: status: project: default: threshold: 0.02%
pennylane/codecov.yml/0
{ "file_path": "pennylane/codecov.yml", "repo_id": "pennylane", "token_count": 122 }
28
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """ This file generates the images used in docstrings for``qml.transforms.draw.draw_mpl``. This makes it easier to keep docstrings up to date with the latest styling. It is not intended to be used in any Continuous Integration, but save time and hassle for developers when making any change that might impact the resulting figures. """ import pathlib import matplotlib.pyplot as plt import pennylane as qml from pennylane import draw_mpl folder = pathlib.Path(__file__).parent def main_example(circuit): fig, ax = draw_mpl(circuit)(1.2345, 1.2345) plt.savefig(folder / "main_example.png") plt.close() def decimals(dev): @qml.qnode(dev) def circuit2(x, y): qml.RX(x, wires=0) qml.Rot(*y, wires=0) return qml.expval(qml.PauliZ(0)) fig, ax = draw_mpl(circuit2, decimals=2)(1.23456, [1.2345, 2.3456, 3.456]) plt.savefig(folder / "decimals.png") def wire_order(circuit): fig, ax = draw_mpl(circuit, wire_order=[3, 2, 1, 0])(1.2345, 1.2345) plt.savefig(folder / "wire_order.png") plt.close() def show_all_wires(circuit): fig, ax = draw_mpl(circuit, wire_order=["aux"], show_all_wires=True)(1.2345, 1.2345) plt.savefig(folder / "show_all_wires.png") plt.close() def postprocessing(circuit): fig, ax = draw_mpl(circuit)(1.2345, 1.2345) fig.suptitle("My Circuit", fontsize="xx-large") options = {"facecolor": "white", "edgecolor": "#f57e7e", "linewidth": 6, "zorder": -1} box1 = plt.Rectangle((-0.5, -0.5), width=3.0, height=4.0, **options) ax.add_patch(box1) ax.annotate( "CSWAP", xy=(3, 2.5), xycoords="data", xytext=(3.8, 1.5), textcoords="data", arrowprops={"facecolor": "black"}, fontsize=14, ) plt.savefig(folder / "postprocessing.png") plt.close() def rcparams(circuit): plt.rcParams["patch.facecolor"] = "mistyrose" plt.rcParams["patch.edgecolor"] = "maroon" plt.rcParams["text.color"] = "maroon" plt.rcParams["font.weight"] = "bold" plt.rcParams["patch.linewidth"] = 4 plt.rcParams["patch.force_edgecolor"] = True plt.rcParams["lines.color"] = "indigo" plt.rcParams["lines.linewidth"] = 5 plt.rcParams["figure.facecolor"] = "ghostwhite" fig, ax = qml.draw_mpl(circuit, style="rcParams")(1.2345, 1.2345) plt.savefig(folder / "rcparams.png") plt.close() qml.drawer.use_style("black_white") def use_style(circuit): fig, ax = qml.draw_mpl(circuit, style="sketch")(1.2345, 1.2345) plt.savefig(folder / "sketch_style.png") plt.close() qml.drawer.use_style("black_white") def wires_labels(circuit): fig, ax = draw_mpl( circuit, wire_options={"color": "teal", "linewidth": 5}, label_options={"size": 20} )(1.2345, 1.2345) plt.savefig(folder / "wires_labels.png") plt.close() def mid_measure(): def circuit(): m0 = qml.measure(0) qml.Hadamard(1) qml.cond(m0, qml.PauliZ)(1) _ = draw_mpl(circuit)() plt.savefig(folder / "mid_measure.png") plt.close() @qml.transforms.merge_rotations @qml.transforms.cancel_inverses @qml.qnode(qml.device("default.qubit"), diff_method="parameter-shift") def _levels_circ(): qml.RandomLayers([[1.0, 20]], wires=(0, 1)) qml.Permute([2, 1, 0], wires=(0, 1, 2)) qml.PauliX(0) qml.PauliX(0) qml.RX(0.1, wires=0) qml.RX(-0.1, wires=0) return qml.expval(qml.PauliX(0)) def levels(): for level in ("top", "user", None, slice(1, 2)): draw_mpl(_levels_circ, level=level)() plt.savefig(folder / f"level_{str(level).split('(')[0].lower()}.png") plt.close if __name__ == "__main__": dev = qml.device("lightning.qubit", wires=(0, 1, 2, 3)) @qml.qnode(dev) def circuit(x, z): qml.QFT(wires=(0, 1, 2, 3)) qml.IsingXX(1.234, wires=(0, 2)) qml.Toffoli(wires=(0, 1, 2)) qml.CSWAP(wires=(0, 2, 3)) qml.RX(x, wires=0) qml.CRZ(z, wires=(3, 0)) return qml.expval(qml.PauliZ(0)) main_example(circuit) decimals(dev) wire_order(circuit) show_all_wires(circuit) postprocessing(circuit) use_style(circuit) rcparams(circuit) wires_labels(circuit) mid_measure() levels()
pennylane/doc/_static/draw_mpl/draw_mpl_examples.py/0
{ "file_path": "pennylane/doc/_static/draw_mpl/draw_mpl_examples.py", "repo_id": "pennylane", "token_count": 2176 }
29
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg viewBox="0 0 401.14999 49.439999" version="1.1" id="svg52" sodipodi:docname="pennylane.svg" width="140" height="17.25" inkscape:version="1.2 (dc2aedaf03, 2022-05-15)" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"> <sodipodi:namedview id="namedview54" pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:showpageshadow="2" inkscape:pageopacity="0.0" inkscape:pagecheckerboard="0" inkscape:deskcolor="#d1d1d1" showgrid="false" inkscape:zoom="2.42" inkscape:cx="115.70248" inkscape:cy="-70.661157" inkscape:window-width="1920" inkscape:window-height="1017" inkscape:window-x="-8" inkscape:window-y="-8" inkscape:window-maximized="1" inkscape:current-layer="svg52" /> <defs id="defs4"> <style id="style2">.cls-1{fill:none;}.cls-2{fill:#00b1ff;}.cls-3{fill:#ffbe0c;}.cls-4{fill:#ff00d9;}</style> </defs> <g id="g44" transform="translate(-49.43,-240.06)"> <path d="m 75.27,241.87 c -2.02,-1.2 -4.35,-1.8 -6.99,-1.8 H 51.55 c -0.56,0 -1.06,0.21 -1.48,0.64 -0.42,0.42 -0.64,0.92 -0.64,1.48 v 45.16 c 0,0.56 0.19,1.06 0.56,1.48 0.38,0.42 0.89,0.64 1.55,0.64 0.56,0 1.06,-0.21 1.48,-0.64 0.42,-0.42 0.64,-0.92 0.64,-1.48 v -18.77 h 14.61 c 2.63,0 4.96,-0.63 6.99,-1.9 2.02,-1.27 3.62,-3 4.8,-5.19 1.18,-2.19 1.76,-4.65 1.76,-7.37 0,-2.72 -0.59,-5.15 -1.76,-7.27 -1.18,-2.12 -2.78,-3.78 -4.8,-4.98 z m 1.02,17.5 c -0.78,1.58 -1.85,2.82 -3.21,3.74 -1.37,0.92 -2.96,1.38 -4.8,1.38 H 53.67 v -20.25 h 14.61 c 1.83,0 3.43,0.42 4.8,1.27 1.36,0.85 2.43,2.01 3.21,3.49 0.78,1.48 1.16,3.19 1.16,5.12 0,1.93 -0.39,3.68 -1.16,5.26 z" id="path26" /> <path d="m 120.69,244.23 c 0.56,0 1.06,-0.19 1.48,-0.56 0.42,-0.38 0.64,-0.87 0.64,-1.48 0,-0.61 -0.21,-1.12 -0.64,-1.52 -0.42,-0.4 -0.92,-0.6 -1.48,-0.6 h -25.9 c -0.56,0 -1.06,0.21 -1.48,0.64 -0.42,0.42 -0.64,0.92 -0.64,1.48 v 45.16 c 0,0.56 0.21,1.06 0.64,1.48 0.42,0.42 0.92,0.64 1.48,0.64 h 25.9 c 0.56,0 1.06,-0.19 1.48,-0.56 0.42,-0.38 0.64,-0.87 0.64,-1.48 0,-0.56 -0.21,-1.06 -0.64,-1.48 -0.42,-0.42 -0.92,-0.63 -1.48,-0.63 H 97.12 v -19.19 h 20.39 c 0.56,0 1.06,-0.19 1.48,-0.56 0.42,-0.38 0.64,-0.87 0.64,-1.48 0,-0.56 -0.21,-1.06 -0.64,-1.48 -0.42,-0.42 -0.92,-0.63 -1.48,-0.63 H 97.12 v -17.71 h 23.57 z" id="path28" /> <path d="m 448.46,285.31 h -23.57 v -19.19 h 20.39 c 0.56,0 1.06,-0.19 1.48,-0.56 0.42,-0.38 0.64,-0.87 0.64,-1.48 0,-0.56 -0.21,-1.06 -0.64,-1.48 -0.42,-0.42 -0.92,-0.63 -1.48,-0.63 h -20.39 v -17.71 h 23.57 c 0.56,0 1.06,-0.19 1.48,-0.56 0.42,-0.38 0.64,-0.87 0.64,-1.48 0,-0.61 -0.21,-1.12 -0.64,-1.52 -0.42,-0.4 -0.92,-0.6 -1.48,-0.6 h -25.9 c -0.56,0 -1.06,0.21 -1.48,0.64 -0.42,0.42 -0.64,0.92 -0.64,1.48 v 45.16 c 0,0.56 0.21,1.06 0.64,1.48 0.42,0.42 0.92,0.64 1.48,0.64 h 25.9 c 0.56,0 1.06,-0.19 1.48,-0.56 0.42,-0.38 0.64,-0.87 0.64,-1.48 0,-0.56 -0.21,-1.06 -0.64,-1.48 -0.42,-0.42 -0.92,-0.63 -1.48,-0.63 z" id="path30" /> <path d="m 170.61,240.07 c -0.52,0 -0.98,0.19 -1.38,0.56 -0.4,0.38 -0.6,0.85 -0.6,1.41 v 39.77 l -30.42,-40.97 c -0.19,-0.28 -0.45,-0.48 -0.78,-0.6 -0.33,-0.12 -0.64,-0.18 -0.92,-0.18 -0.52,0 -0.99,0.18 -1.41,0.53 -0.42,0.35 -0.64,0.88 -0.64,1.59 v 45.38 c 0,0.52 0.18,0.96 0.53,1.34 0.35,0.38 0.83,0.56 1.45,0.56 0.56,0 1.03,-0.19 1.41,-0.56 0.38,-0.38 0.56,-0.82 0.56,-1.34 v -39.61 l 30.27,40.81 c 0.19,0.24 0.45,0.41 0.78,0.53 0.33,0.12 0.64,0.18 0.92,0.18 0.56,0 1.07,-0.2 1.52,-0.6 0.45,-0.4 0.67,-0.95 0.67,-1.66 v -45.16 c 0,-0.56 -0.18,-1.03 -0.53,-1.41 -0.35,-0.38 -0.84,-0.56 -1.45,-0.56 z" id="path32" /> <path d="m 220.39,240.07 c -0.52,0 -0.98,0.19 -1.38,0.56 -0.4,0.38 -0.6,0.85 -0.6,1.41 v 39.77 l -30.42,-40.97 c -0.19,-0.28 -0.45,-0.48 -0.78,-0.6 -0.33,-0.12 -0.64,-0.18 -0.92,-0.18 -0.52,0 -0.99,0.18 -1.41,0.53 -0.42,0.35 -0.64,0.88 -0.64,1.59 v 45.38 c 0,0.52 0.18,0.96 0.53,1.34 0.35,0.38 0.83,0.56 1.45,0.56 0.56,0 1.03,-0.19 1.41,-0.56 0.38,-0.38 0.56,-0.82 0.56,-1.34 v -39.61 l 30.27,40.81 c 0.19,0.24 0.45,0.41 0.78,0.53 0.33,0.12 0.64,0.18 0.92,0.18 0.56,0 1.07,-0.2 1.52,-0.6 0.45,-0.4 0.67,-0.95 0.67,-1.66 v -45.16 c 0,-0.56 -0.18,-1.03 -0.53,-1.41 -0.35,-0.38 -0.84,-0.56 -1.45,-0.56 z" id="path34" /> <path d="m 406.79,240.07 c -0.52,0 -0.98,0.19 -1.38,0.56 -0.4,0.38 -0.6,0.85 -0.6,1.41 v 39.77 l -30.42,-40.97 c -0.19,-0.28 -0.45,-0.48 -0.78,-0.6 -0.33,-0.12 -0.64,-0.18 -0.92,-0.18 -0.52,0 -0.99,0.18 -1.41,0.53 -0.42,0.35 -0.64,0.88 -0.64,1.59 v 45.38 c 0,0.52 0.18,0.96 0.53,1.34 0.35,0.38 0.83,0.56 1.45,0.56 0.56,0 1.03,-0.19 1.41,-0.56 0.38,-0.38 0.56,-0.82 0.56,-1.34 v -39.61 l 30.27,40.81 c 0.19,0.24 0.45,0.41 0.78,0.53 0.33,0.12 0.64,0.18 0.92,0.18 0.56,0 1.07,-0.2 1.52,-0.6 0.45,-0.4 0.67,-0.95 0.67,-1.66 v -45.16 c 0,-0.56 -0.18,-1.03 -0.53,-1.41 -0.35,-0.38 -0.84,-0.56 -1.45,-0.56 z" id="path36" /> <path d="m 266.9,240.07 c -0.75,0 -1.36,0.33 -1.82,0.98 l -14.2,19.77 -14.5,-19.77 c -0.47,-0.65 -1.05,-0.98 -1.75,-0.98 -0.52,0 -1.02,0.2 -1.51,0.6 -0.49,0.4 -0.74,0.9 -0.74,1.51 0,0.24 0.05,0.48 0.14,0.74 0.09,0.26 0.23,0.5 0.42,0.74 l 15.72,21.48 v 22.23 c 0,0.56 0.2,1.05 0.6,1.47 0.4,0.42 0.9,0.63 1.51,0.63 0.61,0 1.12,-0.21 1.54,-0.63 0.42,-0.42 0.63,-0.91 0.63,-1.47 v -22.35 l 15.65,-21.51 c 0.14,-0.23 0.25,-0.46 0.32,-0.67 0.07,-0.21 0.11,-0.43 0.11,-0.67 0,-0.51 -0.2,-0.99 -0.6,-1.44 -0.4,-0.44 -0.9,-0.67 -1.51,-0.67 z" id="path38" /> <path d="m 306.33,285.31 h -22.86 v -43.12 c 0,-0.56 -0.22,-1.06 -0.67,-1.48 -0.45,-0.42 -0.95,-0.64 -1.52,-0.64 -0.66,0 -1.2,0.21 -1.62,0.64 -0.42,0.42 -0.64,0.92 -0.64,1.48 v 45.16 c 0,0.56 0.2,1.06 0.6,1.48 0.4,0.42 0.91,0.64 1.52,0.64 h 25.19 c 0.56,0 1.06,-0.2 1.48,-0.6 0.42,-0.4 0.63,-0.91 0.63,-1.52 0,-0.56 -0.21,-1.05 -0.63,-1.45 -0.42,-0.4 -0.92,-0.6 -1.48,-0.6 z" id="path40" /> <path d="m 340.4,241.47 c -0.19,-0.42 -0.46,-0.76 -0.81,-1.02 -0.35,-0.26 -0.76,-0.39 -1.23,-0.39 -0.47,0 -0.88,0.11 -1.23,0.32 -0.35,0.21 -0.64,0.57 -0.88,1.09 l -18.52,45.33 c -0.09,0.33 -0.12,0.61 -0.07,0.84 0.05,0.51 0.23,0.95 0.56,1.3 0.33,0.35 0.82,0.53 1.47,0.53 0.42,0 0.8,-0.12 1.12,-0.35 0.33,-0.23 0.58,-0.58 0.77,-1.05 l 16.48,-40.97 16.78,40.97 c 0.19,0.42 0.46,0.76 0.81,1.02 0.35,0.26 0.76,0.39 1.23,0.39 0.56,0 1.05,-0.18 1.47,-0.53 0.42,-0.35 0.63,-0.85 0.63,-1.51 0,-0.28 -0.05,-0.56 -0.14,-0.84 l -18.46,-45.12 z" id="path42" /> </g> <g id="boxes" transform="translate(-49.43,-240.06)"> <rect class="cls-1" width="500" height="339" id="rect49" x="0" y="0" /> </g> </svg>
pennylane/doc/_static/pennylane.svg/0
{ "file_path": "pennylane/doc/_static/pennylane.svg", "repo_id": "pennylane", "token_count": 4381 }
30
\documentclass[amsmath,amssymb,aps,pra,10pt,twocolumn,groupedaddress]{revtex4-1} \usepackage{graphicx, epsf} \usepackage[T1]{fontenc} % fix quotation marks in code blocks \usepackage{caption} % allows some extra formatting for captions \usepackage[bitstream-charter]{mathdesign} \graphicspath{{figures/}} \usepackage{tikz} \input{Qcircuit} \usepackage{calrsfs} \DeclareMathAlphabet{\pazocal}{OMS}{zplm}{m}{n} \let\mathcal\undefined \newcommand{\mathcal}[1]{\pazocal{#1}} \usepackage{import} \let\bm\undefined \newcommand{\bm}[1]{\mathbf{#1}} \newcommand{\Rgate}{\Qcircuit @C=0.5em @R=.7em {& \gate{R} & \qw}} \newcommand{\Dgate}{\Qcircuit @C=0.5em @R=.7em {& \gate{D} & \qw}} \newcommand{\Sgate}{\Qcircuit @C=0.5em @R=.7em {& \gate{S} & \qw}} \newcommand{\BSgate}{\Qcircuit @C=0.5em @R=.7em { & \multigate{1}{BS} & \qw \\ & \ghost{BS}& \qw }} \newcommand{\Vgate}{\Qcircuit @C=0.5em @R=.7em {& \gate{V} & \qw}} \renewcommand{\Qcircuit}[1][0em]{\xymatrix @*=<#1>} \begin{document} \pagestyle{empty} \begin{figure} \mbox{\import{.}{var_circuit}} \end{figure} \end{document}
pennylane/doc/_static/qcircuit/main.tex/0
{ "file_path": "pennylane/doc/_static/qcircuit/main.tex", "repo_id": "pennylane", "token_count": 509 }
31
\documentclass[border=6pt]{standalone} \usepackage{qcircuit} \begin{document} \Qcircuit @C=1em @R=.7em { & \gate{H} & \gate{X} & \qw & \ctrl{1} & \qw & \gate{X} & \gate{H} & \qw \\ & \gate{H} & \gate{X} & \qw & \ctrl{1} & \qw & \gate{X} & \gate{H} & \qw \\ & \gate{H} & \gate{X} & \gate{H} & \targ & \gate{H} & \gate{X} & \gate{H} \\ } \end{document}
pennylane/doc/_static/templates/subroutines/grover2.tex/0
{ "file_path": "pennylane/doc/_static/templates/subroutines/grover2.tex", "repo_id": "pennylane", "token_count": 189 }
32
\documentclass[border=0.2cm]{standalone} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{outlines} \usepackage{braket} \usepackage[dvipsnames]{xcolor} \definecolor{templategreen}{RGB}{216, 234, 210} \usepackage{tikz} \usetikzlibrary{quantikz} \usepackage{braket} \begin{document} \begin{quantikz} \qw & \qw & \gate[wires=4][1cm]{\Pi_\phi} & \gate[wires=4][1cm]{U(A)} & \gate[wires=4][1cm]{\tilde{\Pi}_\phi}& \gate[wires=4][1cm]{U(A)^\dagger} & \gate[wires=4][1cm]{\Pi_\phi} & \qw &\qw \\ \qw & \qw &\qw & \qw & \qw &\qw &\qw & \qw & \qw \\ \qw & \qw &\qw & \qw & \qw &\qw &\qw & \qw & \qw \\ \qw & \qw & \qw &\qw& \qw &\qw &\qw & \qw & \qw \end{quantikz} \end{document}
pennylane/doc/_static/templates/subroutines/qsvt.tex/0
{ "file_path": "pennylane/doc/_static/templates/subroutines/qsvt.tex", "repo_id": "pennylane", "token_count": 385 }
33
.. role:: html(raw) :format: html qml.debugging ============= This module contains functionality for debugging quantum programs on simulator devices. :html:`<div class="summary-table">` .. autosummary:: :nosignatures: ~pennylane.breakpoint ~pennylane.debug_expval ~pennylane.debug_probs ~pennylane.debug_state ~pennylane.debug_tape ~pennylane.snapshots :html:`</div>` Entering the Debugging Context ------------------------------ The :func:`~pennylane.breakpoint` function provides an interface for interacting with and stepping through a quantum circuit during execution. It allows for faster debugging by providing access to the internal state of the circuit and the ``QuantumTape`` as the circuit operations are applied. The functionality is highlighted by the example circuit below. .. code-block:: python :linenos: import pennylane as qml @qml.qnode(qml.device('default.qubit', wires=(0,1,2))) def circuit(x): qml.breakpoint() qml.Hadamard(wires=0) qml.CNOT(wires=(0,2)) for w in (0, 1, 2): qml.RX(2*x, wires=w) qml.breakpoint() qml.RX(-x, wires=1) return qml.sample() circuit(1.2345) Running the above python script opens up the interactive ``[pldb]`` prompt in the terminal. When this code reaches ``qml.breakpoint()`` it will pause and launch an interactive debugging prompt. The prompt specifies the path to the script and the next line to be executed after the breakpoint: .. code-block:: console > /Users/your/path/to/script.py(7)circuit() -> qml.Hadamard(wires=0) [pldb] Controlling Code Execution in the Debugging Context --------------------------------------------------- The Pennylane Debugger (PLDB) is built on top of the native python debugger (PDB). As such, it shares a similar interface. We can interact with the debugger using the built-in commands such as ``list``, ``longlist``, ``next``, ``continue``, and ``quit``. Any variables defined within the scope of the quantum function can also be accessed from the debugger. .. code-block:: console [pldb] print(x) 1.2345 The ``list`` (and ``longlist``) command will print a section of code around the breakpoint, highlighting the next line to be executed. This can be used to determine the location of the execution in the circuit. .. code-block:: console [pldb] longlist 3 @qml.qnode(qml.device('default.qubit', wires=(0,1,2))) 4 def circuit(x): 5 qml.breakpoint() 6 7 -> qml.Hadamard(wires=0) 8 qml.CNOT(wires=(0,2)) 9 10 for w in (0, 1, 2): 11 qml.RX(2*x, wires=w) 12 13 qml.breakpoint() 14 qml.RX(-x, wires=1) 15 return qml.sample() The ``next`` command will execute the next line of code, and print the following line to be executed. In this example, the next operation to execute is the ``CNOT``. .. code-block:: console [pldb] next > /Users/your/path/to/script.py(8)circuit() -> qml.CNOT(wires=(0,2)) [pldb] list 3 @qml.qnode(qml.device('default.qubit', wires=(0,1,2))) 4 def circuit(x): 5 qml.breakpoint() 6 7 qml.Hadamard(wires=0) 8 -> qml.CNOT(wires=(0,2)) 9 10 for w in (0, 1, 2): 11 qml.RX(2*x, wires=w) 12 13 qml.breakpoint() Alternatively, the ``continue`` command allows for jumping between breakpoints. This command resumes code execution until the next breakpoint is reached, or termination if there is none. Finally, the ``quit`` command ends the debugging prompt and terminates the execution altogether. .. code-block:: console [pldb] continue > /Users/your/path/to/script.py(14)circuit() -> qml.RX(-x, wires=1) [pldb] list 9 10 for w in (0, 1, 2): 11 qml.RX(2*x, wires=w) 12 13 qml.breakpoint() 14 -> qml.RX(-x, wires=1) 15 return qml.sample() 16 17 circuit(1.2345) [EOF] [pldb] quit Extracting Circuit Information ------------------------------ While in the debugging prompt, we can extract information about the current contents of the quantum tape using :func:`~pennylane.debug_tape`. We can also perform measurements dynamically on the quantum circuit using :func:`~pennylane.debug_expval`, :func:`~pennylane.debug_state`, and :func:`~pennylane.debug_probs`. Consider the circuit from above, .. code-block:: console > /Users/your/path/to/script.py(7)circuit() -> qml.Hadamard(wires=0) [pldb] longlist 3 @qml.qnode(qml.device('default.qubit', wires=(0,1,2))) 4 def circuit(x): 5 qml.breakpoint() 6 7 -> qml.Hadamard(wires=0) 8 qml.CNOT(wires=(0,2)) 9 10 for w in (0, 1, 2): 11 qml.RX(2*x, wires=w) 12 13 qml.breakpoint() 14 qml.RX(-x, wires=1) 15 return qml.sample() [pldb] next > /Users/your/path/to/script.py(8)circuit() -> qml.CNOT(wires=(0,2)) [pldb] next > /Users/your/path/to/script.py(10)circuit() -> for w in (0, 1, 2): [pldb] All of the operations applied so far are tracked in the circuit's ``QuantumTape`` which is accessible using :func:`~pennylane.debug_tape`. This can be used to *visually* debug the circuit. .. code-block:: console [pldb] qtape = qml.debug_tape() [pldb] qtape.operations [Hadamard(wires=[0]), CNOT(wires=[0, 2])] [pldb] print(qtape.draw()) 0: ──H─╭●─┤ 2: ────╰X─┤ The quantum state of the circuit at this point can be extracted using :func:`~pennylane.debug_state`. The associated probability distribution for the wires of interest can be probed using :func:`~pennylane.debug_probs`. .. code-block:: console [pldb] qml.debug_state() array([0.70710678+0.j, 0. +0.j, 0. +0.j, 0. +0.j, 0. +0.j, 0.70710678+0.j, 0. +0.j, 0. +0.j]) [pldb] qml.debug_probs(wires=(0,2)) array([0.5, 0. , 0. , 0.5]) Another method for probing the system is by measuring observables via :func:`~pennylane.debug_expval`. .. code-block:: console [pldb] qml.debug_expval(qml.Z(0)) 0.0 [pldb] qml.debug_expval(qml.X(0) @ qml.X(2)) 0.9999999999999996 Additionally, the quantum circuit can be dynamically updated by adding gates directly from the prompt. This allows users to modify the circuit *on-the-fly*! .. code-block:: console [pldb] continue > /Users/your/path/to/script.py(14)circuit() -> qml.RX(-x, wires=1) [pldb] qtape = qml.debug_tape() [pldb] print(qtape.draw(wire_order=(0,1,2))) 0: ──H─╭●──RX─┤ 1: ────│───RX─┤ 2: ────╰X──RX─┤ [pldb] qml.RZ(0.5*x, wires=0) RZ(0.61725, wires=[0]) [pldb] qml.CZ(wires=(1,2)) CZ(wires=[1, 2]) [pldb] qtape = qml.debug_tape() [pldb] print(qtape.draw(wire_order=(0,1,2))) 0: ──H─╭●──RX──RZ─┤ 1: ────│───RX─╭●──┤ 2: ────╰X──RX─╰Z──┤
pennylane/doc/code/qml_debugging.rst/0
{ "file_path": "pennylane/doc/code/qml_debugging.rst", "repo_id": "pennylane", "token_count": 3152 }
34
qml.pytrees =========== .. currentmodule:: pennylane.pytrees .. warning:: Unless you are a PennyLane or plugin developer, you likely do not need to use these functions. .. automodapi:: pennylane.pytrees :no-heading: :include-all-objects:
pennylane/doc/code/qml_pytrees.rst/0
{ "file_path": "pennylane/doc/code/qml_pytrees.rst", "repo_id": "pennylane", "token_count": 91 }
35
.. _deprecations: Deprecations ============ All PennyLane deprecations will raise a ``qml.PennyLaneDeprecationWarning``. Pending and completed deprecations are listed below. Pending deprecations -------------------- * All of the legacy devices (any with the name ``default.qubit.{autograd,torch,tf,jax,legacy}``) are deprecated. Use ``default.qubit`` instead, as it supports backpropagation for the many backends the legacy devices support. - Deprecated in v0.38 - Will be removed in v0.39 * The logic for internally switching a device for a different backpropagation compatible device is now deprecated, as it was in place for the deprecated `default.qubit.legacy`. - Deprecated in v0.38 - Will be removed in v0.39 * The ``decomp_depth`` argument in ``qml.device`` is deprecated. - Deprecated in v0.38 - Will be removed in v0.39 * The ``max_expansion`` argument in ``qml.QNode`` is deprecated. - Deprecated in v0.38 - Will be removed in v0.39 * The functions ``qml.transforms.sum_expand`` and ``qml.transforms.hamiltonian_expand`` are deprecated. Instead, ``qml.transforms.split_non_commuting`` can be used for equivalent behaviour. - Deprecated in v0.38 - Will be removed in v0.39 * The ``expansion_strategy`` attribute of ``qml.QNode`` is deprecated. Users should make use of ``qml.workflow.construct_batch``, should they require fine control over the output tape(s). - Deprecated in v0.38 - Will be removed in v0.39 * The ``expansion_strategy`` argument in ``qml.specs``, ``qml.draw``, and ``qml.draw_mpl`` is deprecated. Instead, use the ``level`` argument which provides a superset of options. - Deprecated in v0.38 - Will be removed in v0.39 * The ``expand_fn`` argument in ``qml.execute`` is deprecated. Instead, please create a ``qml.transforms.core.TransformProgram`` with the desired preprocessing and pass it to the ``transform_program`` argument of ``qml.execute``. - Deprecated in v0.38 - Will be removed in v0.39 * The ``max_expansion`` argument in ``qml.execute`` is deprecated. Instead, please use ``qml.devices.preprocess.decompose`` with the desired expansion level, add it to a ``TransformProgram``, and pass it to the ``transform_program`` argument of ``qml.execute``. - Deprecated in v0.38 - Will be removed in v0.39 * The ``override_shots`` argument in ``qml.execute`` is deprecated. Instead, please add the shots to the ``QuantumTape``\ s to be executed. - Deprecated in v0.38 - Will be removed in v0.39 * The ``device_batch_transform`` argument in ``qml.execute`` is deprecated. Instead, please create a ``qml.transforms.core.TransformProgram`` with the desired preprocessing and pass it to the ``transform_program`` argument of ``qml.execute``. - Deprecated in v0.38 - Will be removed in v0.39 * The functions ``qml.qinfo.classical_fisher`` and ``qml.qinfo.quantum_fisher`` are deprecated since they are being migrated to the ``qml.gradients`` module. Therefore, ``qml.gradients.classical_fisher`` and ``qml.gradients.quantum_fisher`` should be used instead. - Deprecated and Duplicated in v0.38 - Will be removed in v0.39 * The ``simplify`` argument in ``qml.Hamiltonian`` and ``qml.ops.LinearCombination`` is deprecated. Instead, ``qml.simplify()`` can be called on the constructed operator. - Deprecated in v0.37 - Will be removed in v0.39 New operator arithmetic deprecations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The v0.36 release completes the main phase of PennyLane's switchover to an updated approach for handling arithmetic operations between operators, check out the :ref:`Updated operators <new_opmath>` page for more details. The old system is still accessible via :func:`~.disable_new_opmath`. However, the old system will be removed in an upcoming release and should be treated as deprecated. The following functionality will explicitly raise a deprecation warning when used: * ``op.ops`` and ``op.coeffs`` will be deprecated in the future. Use :meth:`~.Operator.terms` instead. - Added and deprecated for ``Sum`` and ``Prod`` instances in v0.35 * Accessing ``qml.ops.Hamiltonian`` is deprecated because it points to the old version of the class that may not be compatible with the new approach to operator arithmetic. Instead, using ``qml.Hamiltonian`` is recommended because it dispatches to the :class:`~.LinearCombination` class when the new approach to operator arithmetic is enabled. This will allow you to continue to use ``qml.Hamiltonian`` with existing code without needing to make any changes. - Use of ``qml.ops.Hamiltonian`` is deprecated in v0.36 * Accessing terms of a tensor product (e.g., ``op = X(0) @ X(1)``) via ``op.obs`` is deprecated with new operator arithmetic. A user should use :class:`op.operands <~.CompositeOp>` instead. - Deprecated in v0.36 Other deprecations ~~~~~~~~~~~~~~~~~~ * PennyLane Lightning and Catalyst will no longer support ``manylinux2014`` (GLIBC 2.17) compatibile Linux operating systems, and will be migrated to ``manylinux_2_28`` (GLIBC 2.28). See `pypa/manylinux <https://github.com/pypa/manylinux>`_ for additional details. - Last supported version of ``manylinux2014`` with v0.36 - Fully migrated to ``manylinux_2_28`` with v0.37 * ``MultiControlledX`` is the only controlled operation that still supports specifying control values with a bit string. In the future, it will no longer accepts strings as control values. - Deprecated in v0.36 - Will be removed in v0.37 Completed deprecation cycles ---------------------------- * ``queue_idx`` attribute has been removed from the ``Operator``, ``CompositeOp``, and ``SymboliOp`` classes. Instead, the index is now stored as the label of the ``CircuitGraph.graph`` nodes. - Deprecated in v0.38 - Removed in v0.38 * ``qml.from_qasm`` no longer removes measurements from the QASM code. Use ``measurements=[]`` to remove measurements from the original circuit. - Deprecated in v0.37 - Default behaviour changed in v0.38 * ``qml.transforms.map_batch_transform`` has been removed, since transforms can be applied directly to a batch of tapes. See :func:`~.pennylane.transform` for more information. - Deprecated in v0.37 - Removed in v0.38 * ``qml.from_qasm_file`` has been removed. Instead, the user can open the file and then load its content using ``qml.from_qasm``. >>> with open("test.qasm", "r") as f: ... circuit = qml.from_qasm(f.read()) - Deprecated in v0.36 - Removed in v0.37 * The ``qml.load`` function is a general-purpose way to convert circuits into PennyLane from other libraries. It has been removed in favour of the more specific functions ``from_qiskit``, ``from_qasm``, etc. - Deprecated in v0.36 - Removed in v0.37 * ``single_tape_transform``, ``batch_transform``, ``qfunc_transform``, ``op_transform``, ``gradient_transform`` and ``hessian_transform`` are deprecated. Instead switch to using the new ``qml.transform`` function. Please refer to `the transform docs <https://docs.pennylane.ai/en/stable/code/qml_transforms.html#custom-transforms>`_ to see how this can be done. - Deprecated in v0.34 - Removed in v0.36 * ``PauliWord`` and ``PauliSentence`` no longer use ``*`` for matrix and tensor products, but instead use ``@`` to conform with the PennyLane convention. - Deprecated in v0.35 - Removed in v0.36 * The private functions ``_pauli_mult``, ``_binary_matrix`` and ``_get_pauli_map`` from the ``pauli`` module have been removed, as they are no longer used anywhere and the same functionality can be achieved using newer features in the ``pauli`` module. - Deprecated in v0.35 - Removed in v0.36 * Calling ``qml.matrix`` without providing a ``wire_order`` on objects where the wire order could be ambiguous now raises an error. This includes tapes with multiple wires, QNodes with a device that does not provide wires, or quantum functions. - Deprecated in v0.35 - Raises an error in v0.36 * ``qml.pauli.pauli_mult`` and ``qml.pauli.pauli_mult_with_phase`` are now removed. Instead, you should use ``qml.simplify(qml.prod(pauli_1, pauli_2))`` to get the reduced operator. >>> op = qml.simplify(qml.prod(qml.PauliX(0), qml.PauliZ(0))) >>> op -1j*(PauliY(wires=[0])) >>> [phase], [base] = op.terms() >>> phase, base (-1j, PauliY(wires=[0])) - Deprecated in v0.35 - Removed in v0.36 * ``MeasurementProcess.name`` and ``MeasurementProcess.data`` have been removed, as they contain dummy values that are no longer needed. - Deprecated in v0.35 - Removed in v0.36 * The contents of ``qml.interfaces`` is moved inside ``qml.workflow``. - Contents moved in v0.35 - Old import path removed in v0.36 * The method ``Operator.validate_subspace(subspace)``, only employed under a specific set of qutrit operators, has been relocated to the ``qml.ops.qutrit.parametric_ops`` module and has been removed from the ``Operator`` class. - Deprecated in v0.35 - Removed in v0.36 * ``qml.transforms.one_qubit_decomposition`` and ``qml.transforms.two_qubit_decomposition`` are removed. Instead, you should use ``qml.ops.one_qubit_decomposition`` and ``qml.ops.two_qubit_decomposition``. - Deprecated in v0.34 - Removed in v0.35 * Passing additional arguments to a transform that decorates a QNode should now be done through use of ``functools.partial``. For example, the :func:`~pennylane.metric_tensor` transform has an optional ``approx`` argument which should now be set using: .. code-block:: python from functools import partial @partial(qml.metric_tensor, approx="block-diag") @qml.qnode(dev) def circuit(weights): ... The previously-recommended approach is now removed: .. code-block:: python @qml.metric_tensor(approx="block-diag") @qml.qnode(dev) def circuit(weights): ... Alternatively, consider calling the transform directly: .. code-block:: python @qml.qnode(dev) def circuit(weights): ... transformed_circuit = qml.metric_tensor(circuit, approx="block-diag") - Deprecated in v0.33 - Removed in v0.35 * ``Observable.return_type`` has been removed. Instead, you should inspect the type of the surrounding measurement process. - Deprecated in v0.34 - Removed in v0.35 * ``ClassicalShadow.entropy()`` no longer needs an ``atol`` keyword as a better method to estimate entropies from approximate density matrix reconstructions (with potentially negative eigenvalues) has been implemented. - Deprecated in v0.34 - Removed in v0.35 * ``QuantumScript.is_sampled`` and ``QuantumScript.all_sampled`` have been removed. Users should now validate these properties manually. .. code-block:: python from pennylane.measurements import * sample_types = (SampleMP, CountsMP, ClassicalShadowMP, ShadowExpvalMP) is_sample_type = [isinstance(m, sample_types) for m in tape.measurements] is_sampled = any(is_sample_type) all_sampled = all(is_sample_type) - Deprecated in v0.34 - Removed in v0.35 * ``qml.ExpvalCost`` has been removed. Users should use ``qml.expval()`` instead. .. code-block:: python @qml.qnode(dev) def cost_function(params): some_qfunc(params) return qml.expval(Hamiltonian) - Deprecated in v0.24 - Removed in v0.35 * Specifying ``control_values`` passed to ``qml.ctrl`` as a string is no longer supported. - Deprecated in v0.25 - Removed in v0.34 * ``qml.gradients.pulse_generator`` has become ``qml.gradients.pulse_odegen`` to adhere to paper naming conventions. - Deprecated in v0.33 - Removed in v0.34 * The ``prep`` keyword argument in ``QuantumScript`` has been removed. ``StatePrepBase`` operations should be placed at the beginning of the ``ops`` list instead. - Deprecated in v0.33 - Removed in v0.34 * The public methods of ``DefaultQubit`` are pending changes to follow the new device API. We will be switching to the new device interface in a coming release. In this new interface, simulation implementation details will be abstracted away from the device class itself and provided by composition, rather than inheritance. Therefore, some public and private methods from ``DefaultQubit`` will no longer exist, though its behaviour in a workflow will remain the same. If you directly interact with device methods, please consult :class:`pennylane.devices.Device` and :class:`pennylane.devices.DefaultQubit` for more information on what the new interface will look like and be prepared to make updates in a coming release. If you have any feedback on these changes, please create an `issue <https://github.com/PennyLaneAI/pennylane/issues>`_ or post in our `discussion forum <https://discuss.pennylane.ai/>`_. - Deprecated in v0.31 - Changed in v0.33 * The behaviour of ``Operator.__eq__`` and ``Operator.__hash__`` has been updated. Their documentation has been updated to reflect the incoming changes. The changes to operator equality allow users to use operator equality the same way as with ``qml.equal``. With the changes to hashing, unique operators that are equal now have the same hash. These changes now allow behaviour such as the following: >>> qml.RX(0.1, wires=0) == qml.RX(0.1, wires=0) True >>> {qml.PauliZ(0), qml.PauliZ(0)} {PauliZ(wires=[0])} Meanwhile, the previous behaviour is shown below: >>> qml.RX(0.1, wires=0) == qml.RX(0.1, wires=0) False >>> {qml.PauliZ(0), qml.PauliZ(0)} {PauliZ(wires=[0]), PauliZ(wires=[0])} - Added in v0.32 - Behaviour changed in v0.33 * ``qml.qchem.jordan_wigner`` had been removed. Use ``qml.jordan_wigner`` instead. List input to define the fermionic operator is no longer accepted; the fermionic operators ``qml.FermiA``, ``qml.FermiC``, ``qml.FermiWord`` and ``qml.FermiSentence`` should be used instead. See the :mod:`pennylane.fermi` module documentation and the `Fermionic Operator <https://pennylane.ai/qml/demos/tutorial_fermionic_operators>`_ tutorial for more details. - Deprecated in v0.32 - Removed in v0.33 * The ``tuple`` input type in ``qubit_observable`` has been removed. Please use a fermionic operator object. The ``tuple`` return type in ``fermionic_hamiltonian`` and ``fermionic_observable`` has been removed and these functions will return a fermionic operator by default. - Deprecated in v0.32 - Removed in v0.33 * The ``sampler_seed`` argument of ``qml.gradients.spsa_grad`` has been removed. Instead, the ``sampler_rng`` argument should be set, either to an integer value, which will be used to create a PRNG internally, or to a NumPy pseudo-random number generator (PRNG) created via ``np.random.default_rng(seed)``. The advantage of passing a PRNG is that one can reuse that PRNG when calling ``spsa_grad`` multiple times, for instance during an optimization procedure. - Deprecated in v0.32 - Removed in v0.33 * The ``RandomLayers.compute_decomposition`` keyword argument ``ratio_imprivitive`` has been changed to ``ratio_imprim`` to match the call signature of the operation. - Deprecated in v0.32 - Removed in v0.33 * The ``QuantumScript.set_parameters`` method and the ``QuantumScript.data`` setter have been removed. Please use ``QuantumScript.bind_new_parameters`` instead. - Deprecated in v0.32 - Removed in v0.33 * The ``observables`` argument in ``QubitDevice.statistics`` is removed. Please use ``circuit`` instead. Using a list of observables in ``QubitDevice.statistics`` is removed. Please use a ``QuantumTape`` instead. - Still accessible in v0.28-v0.31 - Removed in v0.32 * The CV observables ``qml.X`` and ``qml.P`` have been removed. Use ``qml.QuadX`` and ``qml.QuadP`` instead. - Deprecated in v0.32 - Removed in v0.33 * The method ``tape.unwrap()`` and corresponding ``UnwrapTape`` and ``Unwrap`` classes are removed. - Deprecated in v0.32 - Removed in v0.33 Instead of ``tape.unwrap()``, use :func:`~.transforms.convert_to_numpy_parameters`: .. code-block:: python from pennylane.transforms import convert_to_numpy_parameters qscript = qml.tape.QuantumTape([qml.RX(torch.tensor(0.1234), 0)], [qml.expval(qml.Hermitian(torch.eye(2), 0))] ) unwrapped_qscript = convert_to_numpy_parameters(qscript) torch_params = qscript.get_parameters() numpy_params = unwrapped_qscript.get_parameters() * ``qml.enable_return`` and ``qml.disable_return`` have been removed. The old return types are no longer available. - Deprecated in v0.32 - Removed in v0.33 * The ``mode`` keyword argument in ``QNode`` has been removed, as it was only used in the old return system (which has also been removed). Please use ``grad_on_execution`` instead. - Deprecated in v0.32 - Removed in v0.33 * ``qml.math.purity``, ``qml.math.vn_entropy``, ``qml.math.mutual_info``, ``qml.math.fidelity``, ``qml.math.relative_entropy``, and ``qml.math.max_entropy`` no longer support state vectors as input. Please call ``qml.math.dm_from_state_vector`` on the input before passing to any of these functions. - Still accepted in v0.31 - Removed in v0.32 * The ``do_queue`` keyword argument in ``qml.operation.Operator`` has been removed. This affects all child classes, such as ``Operation``, ``Observable``, ``SymbolicOp`` and more. Instead of setting ``do_queue=False``, use the ``qml.QueuingManager.stop_recording()`` context. - Deprecated in v0.31 - Removed in v0.32 * The ``qml.specs`` dictionary longer supports direct key access to certain keys. Instead these quantities can be accessed as fields of the new ``Resources`` object saved under ``specs_dict["resources"]``: - ``num_operations`` is no longer supported, use ``specs_dict["resources"].num_gates`` - ``num_used_wires`` is no longer supported, use ``specs_dict["resources"].num_wires`` - ``gate_types`` is no longer supported, use ``specs_dict["resources"].gate_types`` - ``gate_sizes`` is no longer supported, use ``specs_dict["resources"].gate_sizes`` - ``depth`` is no longer supported, use ``specs_dict["resources"].depth`` These keys were still accessible in v0.31 and removed in v0.32. * ``qml.math.reduced_dm`` has been removed. Please use ``qml.math.reduce_dm`` or ``qml.math.reduce_statevector`` instead. - Still accessible in v0.31 - Removed in v0.32 * ``QuantumScript``'s ``name`` keyword argument and property are removed. This also affects ``QuantumTape`` and ``OperationRecorder``. - Deprecated in v0.31 - Removed in v0.32 * The ``Operation.base_name`` property is removed. Please use ``Operator.name`` or ``type(obj).__name__`` instead. - Still accessible in v0.31 - Removed in v0.32 * ``LieAlgebraOptimizer`` has been renamed. Please use ``RiemannianGradientOptimizer`` instead. - Deprecated in v0.31 - Removed in v0.32 * The ``grouping_type`` and ``grouping_method`` arguments of ``qchem.molecular_hamiltonian()`` are removed. - Deprecated in v0.31 - Removed in v0.32 Instead, simply construct a new instance of ``Hamiltonian`` with the grouping specified: .. code-block:: python H, qubits = molecular_hamiltonian(symbols, coordinates) grouped_h = qml.Hamiltonian( H.coeffs, H.ops, grouping_type=grouping_type, groupingmethod=grouping_method, ) * ``zyz_decomposition`` and ``xyx_decomposition`` are removed, use ``one_qubit_decomposition`` with a rotations keyword instead. - Deprecated in v0.31 - Removed in v0.32 * The ``qml.utils.sparse_hamiltonian`` function has been removed. ``~.Hamiltonian.sparse_matrix`` should be used instead. - Deprecated in v0.29 - Removed in v0.31 * The ``collections`` module has been removed. - Deprecated in v0.29 - Removed in v0.31 * ``qml.op_sum`` has been removed. Users should use ``qml.sum`` instead. - Deprecated in v0.29. - Removed in v0.31. * The argument ``argnum`` for gradient transforms using the Jax interface is replaced by ``argnums``. - ``argnum`` is automatically changed to ``argnums`` for gradient transforms using JAX and a warning is raised in v0.30 - ``argnums`` is the only option for gradient transforms using JAX in v0.31 * ``Evolution`` now adds a ``-1`` to the input parameter. Beforehand, the minus sign was not included. - Transition warning added in v0.29. - Updated to current behaviour in v0.30. * The ``seed_recipes`` argument in ``qml.classical_shadow`` and ``qml.shadow_expval`` has been removed. An argument ``seed`` which defaults to ``None`` can contain an integer with the wanted seed. - Still accessible in v0.28, v0.29 - Removed in v0.30 * The ``get_operation`` tape method is updated to return the operation index as well, changing its signature. - The new signature is available by changing the arg ``return_op_index`` to ``True`` in v0.29 - The old signature is replaced with the new one in v0.30 * The ``grouping`` module has been removed. The functionality has been moved and reorganized in the new ``pauli`` module under ``pauli/utils.py`` or ``pauli/grouping/``. - Still accessible in v0.27, v0.28, v0.29, v0.30 - Removed in v0.31 The functions from ``grouping/pauli.py``, ``grouping/transformations.py`` and ``grouping/utils.py`` have been moved to ``pauli/utils.py``. The remaining functions have been consolidated in the ``pauli/grouping/`` directory. * ``qml.VQECost`` is removed. - Deprecated in 0.13 - Removed in 0.29 * In-place inversion — ``op.inv()`` and ``op.inverse=value`` — is deprecated. Please use ``qml.adjoint`` or ``qml.pow`` instead. - Still accessible in v0.27 and v0.28 - Removed in v0.29 Don't use: >>> v1 = qml.PauliX(0).inv() >>> v2 = qml.PauliX(0) >>> v2.inverse = True Instead, use: >>> qml.adjoint(qml.PauliX(0)) Adjoint(PauliX(wires=[0])) >>> qml.pow(qml.PauliX(0), -1) PauliX(wires=[0])**-1 >>> qml.pow(qml.PauliX(0), -1, lazy=False) PauliX(wires=[0]) >>> qml.PauliX(0) ** -1 PauliX(wires=[0])**-1 * The ``qml.utils.decompose_hamiltonian()`` method is removed. Please use ``qml.pauli_decompose()``. - Still accessible in v0.27 - Removed in v0.28 * ``qml.tape.get_active_tape`` is deprecated. Please use ``qml.QueuingManager.active_context()`` instead. - Deprecated in v0.27 - Removed in v0.28 * ``qml.transforms.qcut.remap_tape_wires`` is deprecated. Please use ``qml.map_wires`` instead. - Deprecated in v0.27 - Removed in v0.28 * ``QuantumTape.inv()`` is deprecated. Please use ``QuantumTape.adjoint()`` instead. This method returns a new tape instead of modifying itself in-place. - Deprecated in v0.27 - Removed in v0.28 * ``qml.tape.stop_recording`` and ``QuantumTape.stop_recording`` are moved to ``qml.QueuingManager.stop_recording`` - Deprecated in v0.27 - Removed in v0.28 * ``QueuingContext`` is renamed ``QueuingManager``. - Deprecated name ``QueuingContext`` in v0.27 - Removed in v0.28 * ``QueuingManager.safe_update_info`` and ``AnnotateQueue.safe_update_info`` are removed. - Deprecated in v0.27 - Removed in v0.28 * ``ObservableReturnTypes`` ``Sample``, ``Variance``, ``Expectation``, ``Probability``, ``State``, and ``MidMeasure`` are moved to ``measurements`` from ``operation``. - Deprecated in v0.23 - Removed in v0.27 * The ``qml.utils.expand`` function is deprecated. ``qml.math.expand_matrix`` should be used instead. - Deprecated in v0.24 - Removed in v0.27 * The ``qml.Operation.get_parameter_shift`` method is removed. Use the methods of the ``gradients`` module for general parameter-shift rules instead. - Deprecated in v0.22 - Removed in v0.28 * ``qml.transforms.measurement_grouping`` has been removed. Please use ``qml.transforms.hamiltonian_expand`` instead. - Deprecated in v0.28 - Removed in v0.29 * ``qml.transforms.make_tape`` was previously deprecated, but there is no longer a plan to remove it. It no longer raises a warning, and the functionality is unchanged. - Deprecated in v0.28 - Un-deprecated in v0.29
pennylane/doc/development/deprecations.rst/0
{ "file_path": "pennylane/doc/development/deprecations.rst", "repo_id": "pennylane", "token_count": 7935 }
36
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!-- Created with Inkscape (http://www.inkscape.org/) --> <svg width="238.31119mm" height="46.129436mm" viewBox="0 0 238.31119 46.129437" version="1.1" id="svg5" inkscape:version="1.1.1 (1:1.1+202109281949+c3084ef5ed)" sodipodi:docname="pl_workflow.svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"> <sodipodi:namedview id="namedview7" pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:pageshadow="2" inkscape:pageopacity="0.0" inkscape:pagecheckerboard="0" inkscape:document-units="mm" showgrid="false" inkscape:zoom="0.93859299" inkscape:cx="406.45946" inkscape:cy="117.1967" inkscape:window-width="1920" inkscape:window-height="1043" inkscape:window-x="1920" inkscape:window-y="0" inkscape:window-maximized="1" inkscape:current-layer="layer1" inkscape:snap-global="false" showguides="true" inkscape:guide-bbox="true" /> <defs id="defs2"> <inkscape:path-effect effect="bspline" id="path-effect64831" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <inkscape:path-effect effect="bspline" id="path-effect64827" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <inkscape:path-effect effect="bspline" id="path-effect64823" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <inkscape:path-effect effect="bspline" id="path-effect64599" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <inkscape:path-effect effect="bspline" id="path-effect64559" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <inkscape:path-effect effect="bspline" id="path-effect56003" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <inkscape:path-effect effect="bspline" id="path-effect50049" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <inkscape:path-effect effect="bspline" id="path-effect50045" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <rect x="786.59723" y="84.394836" width="132.2572" height="60.821018" id="rect18754" /> <inkscape:path-effect effect="bspline" id="path-effect191734" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <inkscape:path-effect effect="bspline" id="path-effect185159" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <rect x="-69.291611" y="166.01361" width="45.196968" height="28.646526" id="rect168618" /> <inkscape:path-effect effect="bspline" id="path-effect136681" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <inkscape:path-effect effect="bspline" id="path-effect136567" is_visible="true" lpeversion="1" weight="33.333333" steps="2" helper_size="0" apply_no_weight="true" apply_with_weight="true" only_selected="false" /> <rect x="-55.711456" y="-271.08939" width="386.31662" height="161.14485" id="rect92976" /> <rect x="43.564716" y="537.55164" width="451.7417" height="273.12805" id="rect40330" /> <rect x="-147.64961" y="-100.49405" width="1546.3665" height="268.34042" id="rect36530" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457" /> <rect x="0.5000003" y="0.49999988" width="159.74429" height="47.133663" id="rect3693" /> <rect x="0.5000003" y="0.49999988" width="159.74429" height="47.133663" id="rect3693-6" /> <rect x="0.5000003" y="0.49999988" width="159.74429" height="47.133663" id="rect3693-9" /> <rect x="0.5000003" y="0.49999988" width="159.74429" height="47.133663" id="rect3693-2" /> <rect x="0.5000003" y="0.49999988" width="159.74429" height="47.133663" id="rect3693-0" /> <rect x="0.5000003" y="0.49999988" width="159.74429" height="47.133663" id="rect3693-3" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-7" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-2" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-23" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-23-5" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-23-2" /> <rect x="43.564716" y="537.55164" width="452.59814" height="446.04898" id="rect40330-2" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8" /> <rect x="43.564716" y="537.55164" width="451.7417" height="273.12805" id="rect40330-8" /> <rect x="15.948248" y="27.844999" width="257.02402" height="26.530682" id="rect19457-8-7" /> <rect x="43.564716" y="537.55164" width="451.7417" height="273.12805" id="rect40330-7" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-1" /> <rect x="-69.291611" y="166.01361" width="45.196968" height="28.646526" id="rect168618-6" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-6" /> <inkscape:path-effect effect="fill_between_many" method="originald" linkedpaths="#g185115-3,0,1" id="path-effect3674" is_visible="true" lpeversion="0" join="true" close="true" autoreverse="true" applied="false" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-1-5" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-6-2" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-6-2-1" /> <rect x="43.564716" y="537.55164" width="451.7417" height="273.12805" id="rect40330-26" /> <rect x="43.564716" y="537.55164" width="452.59814" height="446.04898" id="rect40330-2-1" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-8" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-1-7" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-9" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-2" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-6-0" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-6-2-2" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-6-2-1-3" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-1-5-7" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-2-2" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-6-0-4" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-2-2-4" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-2-2-8" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-2-2-9" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-2-2-4-5" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-2-2-8-0" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-6-2-2-6" /> <rect x="15.948248" y="27.844999" width="177.85297" height="61.619263" id="rect19457-8-3-1-6-2-1-3-5" /> </defs> <g inkscape:label="Layer 1" inkscape:groupmode="layer" id="layer1" transform="translate(56.93211,47.079199)"> <path id="path77098-4-1-5-3" style="fill:#ff0000;fill-opacity:1;stroke:#ff0000;stroke-width:0.264584px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="M 82.396795,17.205073 H 55.842642 v 0.494997 h -7.9e-4 v 0.583488 h 26.554123 c 0.01405,-1.067908 0.03498,0.02607 8.2e-4,-1.078485 z" sodipodi:nodetypes="ccccccc" inkscape:export-filename="/home/maria/Desktop/XANADU/pl-backprop-device.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200" /> <text xml:space="preserve" transform="matrix(0.26458333,0,0,0.26458333,-64.252937,48.427212)" id="text36528" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect36530);fill:#666666;stroke:none;stroke-width:2.51339;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:2.51339, 5.02677" /> <text xml:space="preserve" transform="matrix(0.17305671,0,0,0.17305671,40.528212,-26.778649)" id="text40328-9" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect40330-7);fill:#666666;stroke:none;stroke-width:3.84268;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:3.84268, 7.68534" /> <text xml:space="preserve" transform="matrix(0.26458333,0,0,0.26458333,-64.252937,48.427212)" id="text92974" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:15.1181px;font-family:'Courier New';-inkscape-font-specification:'Courier New, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect92976);fill:#666666;fill-opacity:1;stroke:none;stroke-width:2.51339;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:2.51339, 5.02677" /> <text xml:space="preserve" style="font-size:4px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;fill:#ff0000;stroke:#808080;stroke-width:0.665001;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:0.665001, 1.33" x="44.746609" y="114.93942" id="text16118"><tspan sodipodi:role="line" id="tspan16116" style="stroke-width:0.665" x="44.746609" y="114.93942" /></text> <text xml:space="preserve" transform="matrix(0.26458333,0,0,0.26458333,-64.252937,48.427212)" id="text18752" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect18754);fill:#ff0000;stroke:#808080;stroke-width:2.51339;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:2.51339, 5.02677" /> <rect style="vector-effect:none;fill:#f2f2f2;fill-opacity:1;fill-rule:evenodd;stroke:#666666;stroke-width:0.264583;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" id="rect17030-59" width="79.711296" height="45.740433" x="24.008469" y="-46.822487" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200" /> <path id="path77098-1-7-6" style="fill:#f2f2f2;fill-opacity:1;stroke:#000000;stroke-width:0.264584px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 163.26587,-29.950471 v 3.59711 h -4.99389 v 3.89455 h -0.002 v 4.59073 h 4.99389 v 3.597441 l 6.92651,-7.825791 0.0275,-6.5e-4 -0.0133,-0.0149 0.0107,-0.0123 -0.022,-6.5e-4 z" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200" /> <rect style="vector-effect:none;fill:#f2f2f2;fill-opacity:1;fill-rule:evenodd;stroke:#666666;stroke-width:0.264583;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" id="rect17030-6-1" width="41.910072" height="45.737179" x="-35.426563" y="-46.946907" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200" /> <text xml:space="preserve" transform="matrix(0.26458333,0,0,0.26458333,-33.139199,-49.073828)" id="text19455-0-2" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect19457-8-8);fill:#f2f2f2;stroke:none;stroke-width:2.51339;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:2.51339, 5.02677" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"><tspan x="15.949219" y="41.747107" id="tspan1665"><tspan style="fill:#666666" id="tspan1663">construct tapes</tspan></tspan></text> <text xml:space="preserve" transform="matrix(0.26458333,0,0,0.26458333,43.265182,-49.305191)" id="text19455-4" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect19457-1-7);fill:#f2f2f2;stroke:none;stroke-width:2.51339;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:2.51339, 5.02677" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"><tspan x="15.949219" y="41.747107" id="tspan1669"><tspan style="fill:#666666" id="tspan1667">execute tapes on device</tspan></tspan></text> <rect style="vector-effect:none;fill:#f2f2f2;fill-opacity:1;fill-rule:evenodd;stroke:#666666;stroke-width:0.264583;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" id="rect17030-5-3" width="34.747616" height="45.562538" x="120.90775" y="-46.732918" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200" /> <path id="path77098-3-6" style="fill:#f2f2f2;fill-opacity:1;stroke:#000000;stroke-width:0.264584px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 112.26233,-29.952422 v 3.59713 h -4.99389 v 3.89454 h -0.002 v 4.59073 h 4.99389 v 3.59744 l 6.9265,-7.82579 0.0275,-6.5e-4 -0.0133,-0.0149 0.0107,-0.0123 0.0257,-0.0643 z" sodipodi:nodetypes="cccccccccccccc" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200" /> <g id="g185115-3-0-5" transform="matrix(0.53472809,0,0,0.56655363,-8.7445092,-70.989368)" style="stroke:#4d4d4d;stroke-width:1.81681" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"> <path id="path136565-7-5-6-4" style="fill:none;stroke:#4d4d4d;stroke-width:0.4807px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m -10.200819,73.467014 c 1.0723611,1.975514 2.1444737,3.950571 2.1355613,6.002679 -0.00891,2.052108 -1.0984842,4.18152 -0.9420332,6.481391 0.156451,2.299871 1.5585596,4.769735 1.877231,7.092569 0.3186715,2.322833 -0.4457555,4.498758 -1.2101215,6.674509 M -36.524074,73.396046 c 1.072362,1.975515 2.144475,3.950571 2.135562,6.002679 -0.0089,2.052108 -1.098484,4.181521 -0.942033,6.481392 0.156451,2.299871 1.558559,4.769735 1.877231,7.092568 0.318672,2.322834 -0.445751,4.498748 -1.210122,6.674517 m -0.294668,-0.0489 c 0,0 26.7342126,0 26.7342126,0 M -36.795887,73.399206 c 0,0 26.734213,0 26.734213,0" inkscape:original-d="m -10.200819,73.467014 c 1.0725198,1.975428 2.1446336,3.950484 3.2163316,5.925158 -1.0892041,2.129874 -2.1787779,4.259285 -3.2687786,6.38836 1.4025727,2.47034 2.8046827,4.940203 4.2064077,7.409736 -0.7640441,2.176389 -1.5284702,4.352314 -2.2933231,6.527894 M -36.524074,73.396046 c 1.07252,1.975429 2.144633,3.950485 3.216333,5.925158 -1.089205,2.129874 -2.17878,4.259285 -3.268779,6.388361 1.402572,2.47034 2.804681,4.940203 4.206407,7.409736 -0.764044,2.176388 -1.52847,4.352301 -2.293323,6.527901 m -0.294668,-0.0489 H -8.2238914 M -36.795887,73.399206 h 26.734213" inkscape:path-effect="#path-effect56003" /> <path style="fill:#ffe6d5;fill-opacity:1;stroke:#4d4d4d;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" d="m 112.817,192.68805 c 0,-0.0959 0.35404,-1.07059 0.78677,-2.16594 0.43273,-1.09535 1.3766,-4.2799 2.0975,-7.07678 2.36334,-9.16907 2.12183,-15.0695 -0.99448,-24.29615 -5.60942,-16.60813 -5.7839,-18.58099 -2.80509,-31.71645 0.71409,-3.14887 1.40213,-6.9628 1.52899,-8.4754 0.45264,-5.39723 -0.9786,-10.90926 -4.87097,-18.75926 -1.28409,-2.58971 -2.39142,-4.836327 -2.46074,-4.992486 -0.0693,-0.15616 21.88197,-0.240914 48.78064,-0.188343 l 48.90667,0.09558 2.90952,5.838599 c 5.18242,10.39973 5.88974,15.27249 3.65643,25.18951 -3.19802,14.20086 -3.10927,16.12673 1.37751,29.89164 3.28341,10.07311 3.63963,11.72526 3.63639,16.86559 -0.003,5.01287 -0.54846,7.94554 -2.78415,14.9732 l -1.58779,4.99107 h -49.0886 c -26.99873,0 -49.0886,-0.0785 -49.0886,-0.17439 z" id="path174233-9-1-7" transform="matrix(0.26458333,0,0,0.26458333,-64.252937,48.427212)" /> </g> <g id="g185115-3-0-5-9" transform="matrix(0.53472809,0,0,0.56655363,-3.595339,-62.800277)" style="stroke:#4d4d4d;stroke-width:1.81681" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"> <path id="path136565-7-5-6-4-2" style="fill:none;stroke:#4d4d4d;stroke-width:0.4807px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m -10.200819,73.467014 c 1.0723611,1.975514 2.1444737,3.950571 2.1355613,6.002679 -0.00891,2.052108 -1.0984842,4.18152 -0.9420332,6.481391 0.156451,2.299871 1.5585596,4.769735 1.877231,7.092569 0.3186715,2.322833 -0.4457555,4.498758 -1.2101215,6.674509 M -36.524074,73.396046 c 1.072362,1.975515 2.144475,3.950571 2.135562,6.002679 -0.0089,2.052108 -1.098484,4.181521 -0.942033,6.481392 0.156451,2.299871 1.558559,4.769735 1.877231,7.092568 0.318672,2.322834 -0.445751,4.498748 -1.210122,6.674517 m -0.294668,-0.0489 c 0,0 26.7342126,0 26.7342126,0 M -36.795887,73.399206 c 0,0 26.734213,0 26.734213,0" inkscape:original-d="m -10.200819,73.467014 c 1.0725198,1.975428 2.1446336,3.950484 3.2163316,5.925158 -1.0892041,2.129874 -2.1787779,4.259285 -3.2687786,6.38836 1.4025727,2.47034 2.8046827,4.940203 4.2064077,7.409736 -0.7640441,2.176389 -1.5284702,4.352314 -2.2933231,6.527894 M -36.524074,73.396046 c 1.07252,1.975429 2.144633,3.950485 3.216333,5.925158 -1.089205,2.129874 -2.17878,4.259285 -3.268779,6.388361 1.402572,2.47034 2.804681,4.940203 4.206407,7.409736 -0.764044,2.176388 -1.52847,4.352301 -2.293323,6.527901 m -0.294668,-0.0489 H -8.2238914 M -36.795887,73.399206 h 26.734213" inkscape:path-effect="#path-effect64559" /> <path style="fill:#ffe6d5;fill-opacity:1;stroke:#4d4d4d;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" d="m 112.817,192.68805 c 0,-0.0959 0.35404,-1.07059 0.78677,-2.16594 0.43273,-1.09535 1.3766,-4.2799 2.0975,-7.07678 2.36334,-9.16907 2.12183,-15.0695 -0.99448,-24.29615 -5.60942,-16.60813 -5.7839,-18.58099 -2.80509,-31.71645 0.71409,-3.14887 1.40213,-6.9628 1.52899,-8.4754 0.45264,-5.39723 -0.9786,-10.90926 -4.87097,-18.75926 -1.28409,-2.58971 -2.39142,-4.836327 -2.46074,-4.992486 -0.0693,-0.15616 21.88197,-0.240914 48.78064,-0.188343 l 48.90667,0.09558 2.90952,5.838599 c 5.18242,10.39973 5.88974,15.27249 3.65643,25.18951 -3.19802,14.20086 -3.10927,16.12673 1.37751,29.89164 3.28341,10.07311 3.63963,11.72526 3.63639,16.86559 -0.003,5.01287 -0.54846,7.94554 -2.78415,14.9732 l -1.58779,4.99107 h -49.0886 c -26.99873,0 -49.0886,-0.0785 -49.0886,-0.17439 z" id="path174233-9-1-7-0" transform="matrix(0.26458333,0,0,0.26458333,-64.252937,48.427212)" /> </g> <g id="g185115-3-0-5-92" transform="matrix(0.53472809,0,0,0.56655363,4.0278571,-73.900473)" style="stroke:#4d4d4d;stroke-width:1.81681" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"> <path id="path136565-7-5-6-4-6" style="fill:none;stroke:#4d4d4d;stroke-width:0.4807px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m -10.200819,73.467014 c 1.0723611,1.975514 2.1444737,3.950571 2.1355613,6.002679 -0.00891,2.052108 -1.0984842,4.18152 -0.9420332,6.481391 0.156451,2.299871 1.5585596,4.769735 1.877231,7.092569 0.3186715,2.322833 -0.4457555,4.498758 -1.2101215,6.674509 M -36.524074,73.396046 c 1.072362,1.975515 2.144475,3.950571 2.135562,6.002679 -0.0089,2.052108 -1.098484,4.181521 -0.942033,6.481392 0.156451,2.299871 1.558559,4.769735 1.877231,7.092568 0.318672,2.322834 -0.445751,4.498748 -1.210122,6.674517 m -0.294668,-0.0489 c 0,0 26.7342126,0 26.7342126,0 M -36.795887,73.399206 c 0,0 26.734213,0 26.734213,0" inkscape:original-d="m -10.200819,73.467014 c 1.0725198,1.975428 2.1446336,3.950484 3.2163316,5.925158 -1.0892041,2.129874 -2.1787779,4.259285 -3.2687786,6.38836 1.4025727,2.47034 2.8046827,4.940203 4.2064077,7.409736 -0.7640441,2.176389 -1.5284702,4.352314 -2.2933231,6.527894 M -36.524074,73.396046 c 1.07252,1.975429 2.144633,3.950485 3.216333,5.925158 -1.089205,2.129874 -2.17878,4.259285 -3.268779,6.388361 1.402572,2.47034 2.804681,4.940203 4.206407,7.409736 -0.764044,2.176388 -1.52847,4.352301 -2.293323,6.527901 m -0.294668,-0.0489 H -8.2238914 M -36.795887,73.399206 h 26.734213" inkscape:path-effect="#path-effect64599" /> <path style="fill:#ffe6d5;fill-opacity:1;stroke:#4d4d4d;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" d="m 112.817,192.68805 c 0,-0.0959 0.35404,-1.07059 0.78677,-2.16594 0.43273,-1.09535 1.3766,-4.2799 2.0975,-7.07678 2.36334,-9.16907 2.12183,-15.0695 -0.99448,-24.29615 -5.60942,-16.60813 -5.7839,-18.58099 -2.80509,-31.71645 0.71409,-3.14887 1.40213,-6.9628 1.52899,-8.4754 0.45264,-5.39723 -0.9786,-10.90926 -4.87097,-18.75926 -1.28409,-2.58971 -2.39142,-4.836327 -2.46074,-4.992486 -0.0693,-0.15616 21.88197,-0.240914 48.78064,-0.188343 l 48.90667,0.09558 2.90952,5.838599 c 5.18242,10.39973 5.88974,15.27249 3.65643,25.18951 -3.19802,14.20086 -3.10927,16.12673 1.37751,29.89164 3.28341,10.07311 3.63963,11.72526 3.63639,16.86559 -0.003,5.01287 -0.54846,7.94554 -2.78415,14.9732 l -1.58779,4.99107 h -49.0886 c -26.99873,0 -49.0886,-0.0785 -49.0886,-0.17439 z" id="path174233-9-1-7-6" transform="matrix(0.26458333,0,0,0.26458333,-64.252937,48.427212)" /> </g> <g id="g185115-3-0-5-4" transform="matrix(0.39856373,0,0,0.42220479,45.069285,-57.924119)" style="stroke:#4d4d4d;stroke-width:2.43773" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"> <path id="path136565-7-5-6-4-8" style="fill:none;stroke:#4d4d4d;stroke-width:0.644987px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m -10.200819,73.467014 c 1.0723611,1.975514 2.1444737,3.950571 2.1355613,6.002679 -0.00891,2.052108 -1.0984842,4.18152 -0.9420332,6.481391 0.156451,2.299871 1.5585596,4.769735 1.877231,7.092569 0.3186715,2.322833 -0.4457555,4.498758 -1.2101215,6.674509 M -36.524074,73.396046 c 1.072362,1.975515 2.144475,3.950571 2.135562,6.002679 -0.0089,2.052108 -1.098484,4.181521 -0.942033,6.481392 0.156451,2.299871 1.558559,4.769735 1.877231,7.092568 0.318672,2.322834 -0.445751,4.498748 -1.210122,6.674517 m -0.294668,-0.0489 c 0,0 26.7342126,0 26.7342126,0 M -36.795887,73.399206 c 0,0 26.734213,0 26.734213,0" inkscape:original-d="m -10.200819,73.467014 c 1.0725198,1.975428 2.1446336,3.950484 3.2163316,5.925158 -1.0892041,2.129874 -2.1787779,4.259285 -3.2687786,6.38836 1.4025727,2.47034 2.8046827,4.940203 4.2064077,7.409736 -0.7640441,2.176389 -1.5284702,4.352314 -2.2933231,6.527894 M -36.524074,73.396046 c 1.07252,1.975429 2.144633,3.950485 3.216333,5.925158 -1.089205,2.129874 -2.17878,4.259285 -3.268779,6.388361 1.402572,2.47034 2.804681,4.940203 4.206407,7.409736 -0.764044,2.176388 -1.52847,4.352301 -2.293323,6.527901 m -0.294668,-0.0489 H -8.2238914 M -36.795887,73.399206 h 26.734213" inkscape:path-effect="#path-effect64823" /> <path style="fill:#ffe6d5;fill-opacity:1;stroke:#4d4d4d;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" d="m 112.817,192.68805 c 0,-0.0959 0.35404,-1.07059 0.78677,-2.16594 0.43273,-1.09535 1.3766,-4.2799 2.0975,-7.07678 2.36334,-9.16907 2.12183,-15.0695 -0.99448,-24.29615 -5.60942,-16.60813 -5.7839,-18.58099 -2.80509,-31.71645 0.71409,-3.14887 1.40213,-6.9628 1.52899,-8.4754 0.45264,-5.39723 -0.9786,-10.90926 -4.87097,-18.75926 -1.28409,-2.58971 -2.39142,-4.836327 -2.46074,-4.992486 -0.0693,-0.15616 21.88197,-0.240914 48.78064,-0.188343 l 48.90667,0.09558 2.90952,5.838599 c 5.18242,10.39973 5.88974,15.27249 3.65643,25.18951 -3.19802,14.20086 -3.10927,16.12673 1.37751,29.89164 3.28341,10.07311 3.63963,11.72526 3.63639,16.86559 -0.003,5.01287 -0.54846,7.94554 -2.78415,14.9732 l -1.58779,4.99107 h -49.0886 c -26.99873,0 -49.0886,-0.0785 -49.0886,-0.17439 z" id="path174233-9-1-7-7" transform="matrix(0.26458333,0,0,0.26458333,-64.252937,48.427212)" /> </g> <path id="path77098-0" style="fill:#f2f2f2;fill-opacity:1;stroke:#000000;stroke-width:0.264584px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 15.052332,-29.952422 v 3.59712 h -4.99389 v 3.89455 h -0.002 v 4.59072 h 4.99389 v 3.59745 l 6.9265,-7.82579 0.0275,-6.5e-4 -0.0133,-0.0149 0.0107,-0.0123 0.0257,-0.0643 z" sodipodi:nodetypes="cccccccccccccc" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200" /> <g id="g185115-3-0-5-9-7" transform="matrix(0.39856373,0,0,0.42220479,48.907259,-51.821478)" style="stroke:#4d4d4d;stroke-width:2.43773" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"> <path id="path136565-7-5-6-4-2-2" style="fill:none;stroke:#4d4d4d;stroke-width:0.644987px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m -10.200819,73.467014 c 1.0723611,1.975514 2.1444737,3.950571 2.1355613,6.002679 -0.00891,2.052108 -1.0984842,4.18152 -0.9420332,6.481391 0.156451,2.299871 1.5585596,4.769735 1.877231,7.092569 0.3186715,2.322833 -0.4457555,4.498758 -1.2101215,6.674509 M -36.524074,73.396046 c 1.072362,1.975515 2.144475,3.950571 2.135562,6.002679 -0.0089,2.052108 -1.098484,4.181521 -0.942033,6.481392 0.156451,2.299871 1.558559,4.769735 1.877231,7.092568 0.318672,2.322834 -0.445751,4.498748 -1.210122,6.674517 m -0.294668,-0.0489 c 0,0 26.7342126,0 26.7342126,0 M -36.795887,73.399206 c 0,0 26.734213,0 26.734213,0" inkscape:original-d="m -10.200819,73.467014 c 1.0725198,1.975428 2.1446336,3.950484 3.2163316,5.925158 -1.0892041,2.129874 -2.1787779,4.259285 -3.2687786,6.38836 1.4025727,2.47034 2.8046827,4.940203 4.2064077,7.409736 -0.7640441,2.176389 -1.5284702,4.352314 -2.2933231,6.527894 M -36.524074,73.396046 c 1.07252,1.975429 2.144633,3.950485 3.216333,5.925158 -1.089205,2.129874 -2.17878,4.259285 -3.268779,6.388361 1.402572,2.47034 2.804681,4.940203 4.206407,7.409736 -0.764044,2.176388 -1.52847,4.352301 -2.293323,6.527901 m -0.294668,-0.0489 H -8.2238914 M -36.795887,73.399206 h 26.734213" inkscape:path-effect="#path-effect64827" /> <path style="fill:#ffe6d5;fill-opacity:1;stroke:#4d4d4d;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" d="m 112.817,192.68805 c 0,-0.0959 0.35404,-1.07059 0.78677,-2.16594 0.43273,-1.09535 1.3766,-4.2799 2.0975,-7.07678 2.36334,-9.16907 2.12183,-15.0695 -0.99448,-24.29615 -5.60942,-16.60813 -5.7839,-18.58099 -2.80509,-31.71645 0.71409,-3.14887 1.40213,-6.9628 1.52899,-8.4754 0.45264,-5.39723 -0.9786,-10.90926 -4.87097,-18.75926 -1.28409,-2.58971 -2.39142,-4.836327 -2.46074,-4.992486 -0.0693,-0.15616 21.88197,-0.240914 48.78064,-0.188343 l 48.90667,0.09558 2.90952,5.838599 c 5.18242,10.39973 5.88974,15.27249 3.65643,25.18951 -3.19802,14.20086 -3.10927,16.12673 1.37751,29.89164 3.28341,10.07311 3.63963,11.72526 3.63639,16.86559 -0.003,5.01287 -0.54846,7.94554 -2.78415,14.9732 l -1.58779,4.99107 h -49.0886 c -26.99873,0 -49.0886,-0.0785 -49.0886,-0.17439 z" id="path174233-9-1-7-0-7" transform="matrix(0.26458333,0,0,0.26458333,-64.252937,48.427212)" /> </g> <g id="g185115-3-0-5-92-2" transform="matrix(0.39856373,0,0,0.42220479,54.589268,-60.093521)" style="stroke:#4d4d4d;stroke-width:2.43773" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"> <path id="path136565-7-5-6-4-6-6" style="fill:none;stroke:#4d4d4d;stroke-width:0.644987px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m -10.200819,73.467014 c 1.0723611,1.975514 2.1444737,3.950571 2.1355613,6.002679 -0.00891,2.052108 -1.0984842,4.18152 -0.9420332,6.481391 0.156451,2.299871 1.5585596,4.769735 1.877231,7.092569 0.3186715,2.322833 -0.4457555,4.498758 -1.2101215,6.674509 M -36.524074,73.396046 c 1.072362,1.975515 2.144475,3.950571 2.135562,6.002679 -0.0089,2.052108 -1.098484,4.181521 -0.942033,6.481392 0.156451,2.299871 1.558559,4.769735 1.877231,7.092568 0.318672,2.322834 -0.445751,4.498748 -1.210122,6.674517 m -0.294668,-0.0489 c 0,0 26.7342126,0 26.7342126,0 M -36.795887,73.399206 c 0,0 26.734213,0 26.734213,0" inkscape:original-d="m -10.200819,73.467014 c 1.0725198,1.975428 2.1446336,3.950484 3.2163316,5.925158 -1.0892041,2.129874 -2.1787779,4.259285 -3.2687786,6.38836 1.4025727,2.47034 2.8046827,4.940203 4.2064077,7.409736 -0.7640441,2.176389 -1.5284702,4.352314 -2.2933231,6.527894 M -36.524074,73.396046 c 1.07252,1.975429 2.144633,3.950485 3.216333,5.925158 -1.089205,2.129874 -2.17878,4.259285 -3.268779,6.388361 1.402572,2.47034 2.804681,4.940203 4.206407,7.409736 -0.764044,2.176388 -1.52847,4.352301 -2.293323,6.527901 m -0.294668,-0.0489 H -8.2238914 M -36.795887,73.399206 h 26.734213" inkscape:path-effect="#path-effect64831" /> <path style="fill:#ffe6d5;fill-opacity:1;stroke:#4d4d4d;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" d="m 112.817,192.68805 c 0,-0.0959 0.35404,-1.07059 0.78677,-2.16594 0.43273,-1.09535 1.3766,-4.2799 2.0975,-7.07678 2.36334,-9.16907 2.12183,-15.0695 -0.99448,-24.29615 -5.60942,-16.60813 -5.7839,-18.58099 -2.80509,-31.71645 0.71409,-3.14887 1.40213,-6.9628 1.52899,-8.4754 0.45264,-5.39723 -0.9786,-10.90926 -4.87097,-18.75926 -1.28409,-2.58971 -2.39142,-4.836327 -2.46074,-4.992486 -0.0693,-0.15616 21.88197,-0.240914 48.78064,-0.188343 l 48.90667,0.09558 2.90952,5.838599 c 5.18242,10.39973 5.88974,15.27249 3.65643,25.18951 -3.19802,14.20086 -3.10927,16.12673 1.37751,29.89164 3.28341,10.07311 3.63963,11.72526 3.63639,16.86559 -0.003,5.01287 -0.54846,7.94554 -2.78415,14.9732 l -1.58779,4.99107 h -49.0886 c -26.99873,0 -49.0886,-0.0785 -49.0886,-0.17439 z" id="path174233-9-1-7-6-1" transform="matrix(0.26458333,0,0,0.26458333,-64.252937,48.427212)" /> </g> <text xml:space="preserve" transform="matrix(0.23072834,0,0,0.23060146,85.49512,-32.015238)" id="text19455-0-5-3-7-9-6" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect19457-8-3-1-6-2-2);fill:#ffffff;stroke:none;stroke-width:2.88298;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:2.88298, 5.76596" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"><tspan x="15.949219" y="41.747107" id="tspan1673"><tspan style="fill:#ff0000" id="tspan1671">res1 </tspan></tspan><tspan x="15.949219" y="60.644732" id="tspan1677"><tspan style="fill:#ff0000" id="tspan1675">res2 </tspan></tspan><tspan x="15.949219" y="79.542357" id="tspan1681"><tspan style="fill:#ff0000" id="tspan1679">res3</tspan></tspan></text> <text xml:space="preserve" transform="matrix(0.23072834,0,0,0.23060146,121.13743,-26.765629)" id="text19455-0-5-3-7-9-6-1" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect19457-8-3-1-6-2-2-6);fill:#ffffff;stroke:none;stroke-width:2.88298;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:2.88298, 5.76596" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"><tspan x="15.949219" y="41.747107" id="tspan1685"><tspan style="fill:#ff0000" id="tspan1683">g(res1, res2, res3)</tspan></tspan></text> <text xml:space="preserve" transform="matrix(0,-0.3642738,0.30569832,0,163.09292,-7.8269401)" id="text19455-0-5-3-7-9-2-9" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect19457-8-3-1-6-2-1-3);fill:#ffffff;stroke:none;stroke-width:1.99278;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:1.99278, 3.98559" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"><tspan x="15.949219" y="41.747107" id="tspan1689"><tspan style="fill:#ff0000" id="tspan1687">results </tspan></tspan><tspan x="15.949219" y="60.644732" id="tspan1693"><tspan style="fill:#ff0000" id="tspan1691"> </tspan></tspan></text> <path id="path77098-1-7-6-9" style="fill:#f2f2f2;fill-opacity:1;stroke:#000000;stroke-width:0.264584px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m -45.308044,-29.749382 v 3.59711 h -4.99389 v 3.89455 h -0.002 v 4.59073 h 4.99389 v 3.597441 l 6.92651,-7.825791 0.0275,-6.5e-4 -0.0133,-0.0149 0.0107,-0.0123 -0.022,-6.5e-4 z" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200" /> <text xml:space="preserve" transform="matrix(0,-0.3642738,0.30569832,0,-66.658963,-1.720729)" id="text19455-0-5-3-7-9-2-9-4" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect19457-8-3-1-6-2-1-3-5);fill:#ffffff;stroke:none;stroke-width:1.99278;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:1.99278, 3.98559" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"><tspan x="15.949219" y="41.747107" id="tspan1697"><tspan style="fill:#ff0000" id="tspan1695">parameters</tspan></tspan></text> <text xml:space="preserve" transform="matrix(0.26458333,0,0,0.26458333,121.1183,-48.448434)" id="text19455-6-3" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect19457-1-5-7);fill:#f2f2f2;stroke:none;stroke-width:2.51339;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:2.51339, 5.02677" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"><tspan x="15.949219" y="41.747107" id="tspan1701"><tspan style="fill:#808080" id="tspan1699">post-processs </tspan></tspan></text> <path id="path77098-4-1-5-5" style="fill:#ff0000;fill-opacity:1;stroke:#ff0000;stroke-width:0.264584px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 57.797399,-19.195061 v 0.457209 h -3.27081 v 0.494997 h -7.95e-4 v 0.583488 h 3.270789 v 0.45724 l 1.562099,-0.994665 0.01142,-9.2e-5 -0.0045,-0.0015 0.0045,-0.0015 0.01142,-0.0077 z" sodipodi:nodetypes="cccccccccccccc" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200" /> <g id="g54162" transform="matrix(1.451484,0,0,1.4538561,-20.512744,4.5889474)" style="stroke-width:0.688388" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"> <rect style="vector-effect:none;fill:#008080;fill-opacity:1;fill-rule:evenodd;stroke:#333333;stroke-width:0.182136;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" id="rect1034-4" width="14.824986" height="7.6152873" x="54.484165" y="-18.623169" /> <path style="fill:none;stroke:#333333;stroke-width:0.182136px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 54.443203,-18.651355 4.320526,-3.319736 h 13.88918 v 7.389223 l -3.378555,3.567762" id="path1118-7" sodipodi:nodetypes="ccccc" /> <path style="fill:none;stroke:#333333;stroke-width:0.182136px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 69.229794,-18.477471 3.285749,-3.427288" id="path1362-6" sodipodi:nodetypes="cc" /> <text xml:space="preserve" transform="matrix(0.14984632,0,0,0.15012816,55.439641,-20.716715)" id="text19455-0-5-3-7-5" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect19457-8-3-1-6-0);fill:#ffffff;stroke:none;stroke-width:3.05212;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:3.05212, 6.10425"><tspan x="15.949219" y="41.747107" id="tspan1703">device</tspan></text> <path style="fill:#6f918a;stroke:#333333;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" d="m 950.14548,-227.2683 c 18.10528,0.1227 34.14489,0.0669 51.07712,0.084 l -5.40589,5.63105 -6.01526,6.34541 c -21.65707,0.0974 -36.71717,0.20537 -55.15586,-0.18501 6.6379,-4.75757 11.35988,-8.46749 15.49989,-11.87549 z" id="path50594" transform="matrix(0.26458333,0,0,0.26458333,-192.58101,38.235762)" sodipodi:nodetypes="ccccccc" /> <path style="fill:#6f918a;stroke:#333333;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" d="m 990.31286,-201.42968 0.009,-13.17767 c 3.75428,-3.89241 7.86574,-8.05795 11.62004,-11.95036 0.01,8.71283 0.118,18.07699 0.125,26.78982 -4.13858,4.34983 -8.00724,8.4003 -11.7838,12.29726 z" id="path50633" transform="matrix(0.26458333,0,0,0.26458333,-192.58101,38.235762)" sodipodi:nodetypes="cccccc" /> </g> <path id="path77098-4-1-5" style="fill:#ff0000;fill-opacity:1;stroke:#ff0000;stroke-width:0.264584px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 85.790494,-20.2212 v 0.45721 h -3.27081 v 0.494997 h -7.94e-4 v 0.583488 h 3.270789 v 0.45724 l 1.562099,-0.994665 0.01142,-9.2e-5 -0.0045,-0.0015 0.0045,-0.0015 0.01142,-0.0077 z" sodipodi:nodetypes="cccccccccccccc" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200" /> <g id="g54162-0" transform="matrix(1.451484,0,0,1.4538561,-20.731448,41.55801)" style="stroke-width:0.688388" inkscape:export-filename="/home/maria/Desktop/XANADU/pl-backprop-device.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"> <rect style="vector-effect:none;fill:#008080;fill-opacity:0.702581;fill-rule:evenodd;stroke:#333333;stroke-width:0.182136;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" id="rect1034-4-7" width="14.824986" height="7.6152873" x="54.484165" y="-18.623169" /> <path style="fill:none;stroke:#333333;stroke-width:0.182136px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 54.443203,-18.651355 4.320526,-3.319736 h 13.88918 v 7.389223 l -3.378555,3.567762" id="path1118-7-8" sodipodi:nodetypes="ccccc" /> <path style="fill:none;stroke:#333333;stroke-width:0.182136px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 69.229794,-18.477471 3.285749,-3.427288" id="path1362-6-6" sodipodi:nodetypes="cc" /> <text xml:space="preserve" transform="matrix(0.14984632,0,0,0.15012816,55.071964,-21.756764)" id="text19455-0-5-3-7-5-8" style="font-size:15.1181px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;white-space:pre;shape-inside:url(#rect19457-8-3-1-6-0-4);fill:#ffffff;stroke:none;stroke-width:3.05212;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:3.05212, 6.10425"><tspan x="15.949219" y="41.747107" id="tspan1705">backprop </tspan><tspan x="15.949219" y="60.644732" id="tspan1707">device</tspan></text> <path style="fill:#6f918a;fill-opacity:0.676833;stroke:#333333;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" d="m 950.14548,-227.2683 c 18.10528,0.1227 34.14489,0.0669 51.07712,0.084 l -5.40589,5.63105 -6.01526,6.34541 c -21.65707,0.0974 -36.71717,0.20537 -55.15586,-0.18501 6.6379,-4.75757 11.35988,-8.46749 15.49989,-11.87549 z" id="path50594-8" transform="matrix(0.26458333,0,0,0.26458333,-192.58101,38.235762)" sodipodi:nodetypes="ccccccc" /> <path style="fill:#6f918a;fill-opacity:0.504408;stroke:#333333;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" d="m 990.31286,-201.42968 0.009,-13.17767 c 3.75428,-3.89241 7.86574,-8.05795 11.62004,-11.95036 0.01,8.71283 0.118,18.07699 0.125,26.78982 -4.13858,4.34983 -8.00724,8.4003 -11.7838,12.29726 z" id="path50633-4" transform="matrix(0.26458333,0,0,0.26458333,-192.58101,38.235762)" sodipodi:nodetypes="cccccc" /> </g> <path id="path77098-4-1-5-3-1" style="fill:#ff0000;fill-opacity:1;stroke:#ff0000;stroke-width:0.264584px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 86.184846,16.749993 v 0.45721 H 82.384863 V 17.7022 h -7.9e-4 v 0.583488 h 3.799953 v 0.45724 l 1.5621,-0.994665 0.0114,-9.2e-5 -0.005,-0.0015 0.005,-0.0015 0.0114,-0.0077 z" sodipodi:nodetypes="cccccccccccccc" inkscape:export-filename="/home/maria/Desktop/XANADU/pl-backprop-device.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200" /> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:4px;font-family:Roboto;-inkscape-font-specification:Roboto;writing-mode:lr-tb;fill:#ff0000;fill-opacity:1;stroke:#ff0000;stroke-width:0.1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0" x="13.194172" y="180.49509" id="text77717" transform="rotate(-90)" inkscape:export-filename="/home/maria/Desktop/XANADU/pennylane/doc/development/guide/pl_workflow.png" inkscape:export-xdpi="200" inkscape:export-ydpi="200"><tspan sodipodi:role="line" id="tspan77715" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto;-inkscape-font-specification:Roboto;fill:#ff0000;fill-opacity:1;stroke-width:0.1;stroke-miterlimit:4;stroke-dasharray:none" x="13.194172" y="180.49509">gradients</tspan></text> </g> </svg>
pennylane/doc/development/guide/pl_workflow.svg/0
{ "file_path": "pennylane/doc/development/guide/pl_workflow.svg", "repo_id": "pennylane", "token_count": 26830 }
37
.. role:: html(raw) :format: html .. _intro_interfaces: Gradients and training ====================== PennyLane offers seamless integration between classical and quantum computations. Code up quantum circuits in PennyLane, compute `gradients of quantum circuits <https://pennylane.ai/qml/glossary/quantum_gradient>`_, and connect them easily to the top scientific computing and machine learning libraries. Training and interfaces ----------------------- The bridge between the quantum and classical worlds is provided in PennyLane via interfaces to automatic differentiation libraries. Currently, four libraries are supported: :doc:`NumPy <interfaces/numpy>`, :doc:`PyTorch <interfaces/torch>`, :doc:`JAX <interfaces/jax>`, and :doc:`TensorFlow <interfaces/tf>`. PennyLane makes each of these libraries quantum-aware, allowing quantum circuits to be treated just like any other operation. Any automatic differentiation framework can be chosen with any device. In PennyLane, an automatic differentiation framework is declared using the ``interface`` argument when creating a :class:`QNode <pennylane.QNode>`, e.g., .. code-block:: python @qml.qnode(dev, interface="tf") def my_quantum_circuit(...): ... .. note:: If no interface is specified, PennyLane will automatically determine the interface based on provided arguments and keyword arguments. See ``qml.workflow.SUPPORTED_INTERFACES`` for a list of all accepted interface strings. This will allow native numerical objects of the specified library (NumPy arrays, JAX arrays, Torch Tensors, or TensorFlow Tensors) to be passed as parameters to the quantum circuit. It also makes the gradients of the quantum circuit accessible to the classical library, enabling the optimization of arbitrary hybrid circuits by making use of the library's native optimizers. When specifying an interface, the objects of the chosen framework are converted into NumPy objects and are passed to a device in most cases. Exceptions include cases when the devices support end-to-end computations in a framework. Such devices may be referred to as backpropagation or passthru devices. See the links below for walkthroughs of each specific interface: .. raw:: html <style> #interfaces .card { box-shadow: none!important; } #interfaces .card:hover { box-shadow: none!important; } </style> <div id="interfaces" class="container mt-2 mb-2"> <div class="row mt-3"> <div class="col-lg-3 mb-2 align-items-stretch"> <a href="interfaces/numpy.html"> <div class="card rounded-lg py-2" style="height:100%;"> <div class="d-flex justify-content-center align-items-center" style="height:100%;"> <img src="../_static/numpy.png" class="card-img-top" style="width:80%;"></img> </div> </div> </a> </div> <div class="col-lg-3 mb-2 align-items-stretch"> <a href="interfaces/torch.html"> <div class="card rounded-lg py-2" style="height:100%;"> <div class="d-flex justify-content-center align-items-center" style="height:100%;"> <img src="../_static/pytorch.png" class="card-img-top"></img> </div> </div> </a> </div> <div class="col-lg-3 mb-2 align-items-stretch"> <a href="interfaces/tf.html"> <div class="card rounded-lg py-2" style="height:100%;"> <div class="d-flex justify-content-center align-items-center" style="height:100%;"> <img src="../_static/tensorflow.png" class="card-img-top" style="width:90%;"></img> </div> </div> </a> </div> <div class="col-lg-3 mb-2 align-items-stretch"> <a href="interfaces/jax.html"> <div class="card rounded-lg py-2" style="height:100%;"> <div class="d-flex justify-content-center align-items-center" style="height:100%;"> <img src="../_static/jax.png" class="card-img-top" style="max-width:60%;"></img> </div> </div> </a> </div> </div> </div> In addition to the core automatic differentiation frameworks discussed above, PennyLane also provides higher-level classes for converting QNodes into both Keras and ``torch.nn`` layers: :html:`<div class="summary-table">` .. autosummary:: pennylane.qnn.KerasLayer pennylane.qnn.TorchLayer .. note:: QNodes that allow for automatic differentiation will always incur a small overhead on evaluation. If you do not need to compute quantum gradients of a QNode, specifying ``interface=None`` will remove this overhead and result in a slightly faster evaluation. However, gradients will no longer be available. .. _intro_ref_opt: Optimizers ---------- Optimizers are objects which can be used to automatically update the parameters of a quantum or hybrid machine learning model. The optimizers you should use are dependent on your choice of the classical autodifferentiation library, and are available from different access points. NumPy ~~~~~ When using the standard NumPy framework, PennyLane offers some built-in optimizers. Some of these are specific to quantum optimization, such as the :class:`~.QNGOptimizer`, :class:`~.RiemannianGradientOptimizer`, :class:`~.RotosolveOptimizer`, :class:`~.RotoselectOptimizer`, :class:`~.ShotAdaptiveOptimizer`, and :class:`~.QNSPSAOptimizer`. :html:`<div class="summary-table">` .. autosummary:: :nosignatures: ~pennylane.AdagradOptimizer ~pennylane.AdamOptimizer ~pennylane.AdaptiveOptimizer ~pennylane.GradientDescentOptimizer ~pennylane.MomentumOptimizer ~pennylane.NesterovMomentumOptimizer ~pennylane.QNGOptimizer ~pennylane.RiemannianGradientOptimizer ~pennylane.RMSPropOptimizer ~pennylane.RotosolveOptimizer ~pennylane.RotoselectOptimizer ~pennylane.ShotAdaptiveOptimizer ~pennylane.SPSAOptimizer ~pennylane.QNSPSAOptimizer :html:`</div>` PyTorch ~~~~~~~ If you are using the :ref:`PennyLane PyTorch framework <torch_interf>`, you should import one of the native `PyTorch optimizers <https://pytorch.org/docs/stable/optim.html>`_ (found in ``torch.optim``). TensorFlow ~~~~~~~~~~ When using the :ref:`PennyLane TensorFlow framework <tf_interf>`, you will need to leverage one of the `TensorFlow optimizers <https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Optimizer>`_ (found in ``tf.keras.optimizers``). JAX ~~~ Check out the `JAXopt <https://github.com/google/jaxopt>`_ and the `Optax <https://optax.readthedocs.io/en/latest/>`_ packages to find optimizers for the :ref:`PennyLane JAX framework <jax_interf>`. Gradients --------- The interface between PennyLane and automatic differentiation libraries relies on PennyLane's ability to compute or estimate gradients of quantum circuits. There are different strategies to do so, and they may depend on the device used. When creating a QNode, you can specify the `differentiation method <https://pennylane.ai/qml/glossary/quantum_differentiable_programming>`_ like this: .. code-block:: python @qml.qnode(dev, diff_method="parameter-shift") def circuit(x): qml.RX(x, wires=0) return qml.probs(wires=0) PennyLane currently provides the following differentiation methods for QNodes: Simulation-based differentiation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following methods use `reverse accumulation <https://en.wikipedia.org/wiki/Automatic_differentiation#Reverse_accumulation>`__ to compute gradients; a well-known example of this approach is backpropagation. These methods are **not** hardware compatible; they are only supported on *statevector* simulator devices such as :class:`default.qubit <pennylane.devices.DefaultQubit>`. However, for rapid prototyping on simulators, these methods typically out-perform forward-mode accumulators such as the parameter-shift rule and finite-differences. For more details, see the :doc:`quantum backpropagation <demos/tutorial_backprop>` demonstration. * ``"backprop"``: Use standard backpropagation. This differentiation method is only allowed on simulator devices that are classically end-to-end differentiable, for example :class:`default.qubit <pennylane.devices.DefaultQubit>`. This method does *not* work on devices that estimate measurement statistics using a finite number of shots; please use the ``parameter-shift`` rule instead. * ``"adjoint"``: Use a form of backpropagation that takes advantage of the unitary or reversible nature of quantum computation. The `adjoint method <https://arxiv.org/abs/2009.02823>`__ reverses through the circuit after a forward pass by iteratively applying the inverse (adjoint) gate. This method is similar to ``"backprop"``, but has significantly lower memory usage and a similar runtime. Hardware-compatible differentiation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following methods support both quantum hardware and simulators, and are examples of `forward accumulation <https://en.wikipedia.org/wiki/Automatic_differentiation#Forward_accumulation>`__. However, when using a simulator, you may notice that the number of circuit executions required to compute the gradients with these methods :doc:`scales linearly <demos/tutorial_backprop>` with the number of trainable circuit parameters. * ``"parameter-shift"``: Use the analytic `parameter-shift rule <https://pennylane.ai/qml/glossary/parameter_shift>`_ for all supported quantum operation arguments, with finite-difference as a fallback. * ``"finite-diff"``: Use numerical finite-differences for all quantum operation arguments. * ``"hadamard"``: Use hadamard tests on the generators for all compatible quantum operations arguments. * :func:`qml.gradients.stoch_pulse_grad <pennylane.gradients.stoch_pulse_grad>`: Use a stochastic variant of the parameter-shift rule for pulse programs. * :func:`qml.gradients.pulse_odegen <pennylane.gradients.pulse_odegen>`: Combine classical processing with the parameter-shift rule for multivariate gates to differentiate pulse programs. Device gradients ~~~~~~~~~~~~~~~~ * ``"device"``: Queries the device directly for the gradient. Only allowed on devices that provide their own gradient computation. .. note:: If not specified, the default differentiation method is ``diff_method="best"``. PennyLane will attempt to determine the *best* differentiation method given the device and interface. Typically, PennyLane will prioritize device-provided gradients, backpropagation, parameter-shift rule, and finally finite differences, in that order. Gradient transforms ------------------- In addition to registering the differentiation method of QNodes to be used with autodifferentiation frameworks, PennyLane also provides a library of **gradient transforms** via the :mod:`qml.gradients <pennylane.gradients>` module. Quantum gradient transforms are strategies for computing the gradient of a quantum circuit that work by **transforming** the quantum circuit into one or more gradient circuits. They accompany these circuits with a function that **post-processes** their output. These gradient circuits, once executed and post-processed, return the gradient of the original circuit. Examples of quantum gradient transforms include finite-difference rules and parameter-shift rules; these can be applied *directly* to QNodes: .. code-block:: python dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(weights): qml.RX(weights[0], wires=0) qml.RY(weights[1], wires=1) qml.CNOT(wires=[0, 1]) qml.RX(weights[2], wires=1) return qml.probs(wires=1) >>> weights = np.array([0.1, 0.2, 0.3], requires_grad=True) >>> circuit(weights) tensor([0.9658079, 0.0341921], requires_grad=True) >>> qml.gradients.param_shift(circuit)(weights) (tensor([-0.04673668, 0.04673668], requires_grad=True), tensor([-0.09442394, 0.09442394], requires_grad=True), tensor([-0.14409127, 0.14409127], requires_grad=True)) Note that, while gradient transforms allow quantum gradient rules to be applied directly to QNodes, this is not a replacement --- and should not be used instead of --- standard training workflows (for example, ``qml.grad()`` if using Autograd, ``loss.backward()`` for PyTorch, or ``tape.gradient()`` for TensorFlow). This is because gradient transforms do not take into account classical computation nodes, and only support gradients of QNodes. For more details on available gradient transforms, as well as learning how to define your own gradient transform, please see the :mod:`qml.gradients <pennylane.gradients>` documentation. Differentiating gradient transforms and higher-order derivatives ---------------------------------------------------------------- Gradient transforms are themselves differentiable, allowing higher-order gradients to be computed: .. code-block:: python dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(weights): qml.RX(weights[0], wires=0) qml.RY(weights[1], wires=1) qml.CNOT(wires=[0, 1]) qml.RX(weights[2], wires=1) return qml.expval(qml.PauliZ(1)) >>> weights = np.array([0.1, 0.2, 0.3], requires_grad=True) >>> circuit(weights) tensor(0.9316158, requires_grad=True) >>> qml.gradients.param_shift(circuit)(weights) # gradient (tensor(-0.09347337, requires_grad=True), tensor(-0.18884787, requires_grad=True), tensor(-0.28818254, requires_grad=True)) >>> def f(weights): ... return np.stack(qml.gradients.param_shift(circuit)(weights)) >>> qml.jacobian(f)(weights) # hessian array([[[-0.9316158 , 0.01894799, 0.0289147 ], [ 0.01894799, -0.9316158 , 0.05841749], [ 0.0289147 , 0.05841749, -0.9316158 ]]]) Another way to compute higher-order derivatives is by passing the ``max_diff`` and ``diff_method`` arguments to the QNode and by successive differentiation: .. code-block:: python @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(weights): qml.RX(weights[0], wires=0) qml.RY(weights[1], wires=1) qml.CNOT(wires=[0, 1]) qml.RX(weights[2], wires=1) return qml.expval(qml.PauliZ(1)) >>> weights = np.array([0.1, 0.2, 0.3], requires_grad=True) >>> qml.jacobian(qml.jacobian(circuit))(weights) # hessian array([[-0.9316158 , 0.01894799, 0.0289147 ], [ 0.01894799, -0.9316158 , 0.05841749], [ 0.0289147 , 0.05841749, -0.9316158 ]]) Note that the ``max_diff`` argument only applies to gradient transforms and that its default value is ``1``; failing to set its value correctly may yield incorrect results for higher-order derivatives. Also, passing ``diff_method="parameter-shift"`` is equivalent to passing ``diff_method=qml.gradients.param_shift``. Supported configurations ------------------------ .. role:: gr .. role:: rd .. raw:: html <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script> $(document).ready(function() { $('.gr').parent().parent().addClass('gr-parent'); $('.rd').parent().parent().addClass('rd-parent'); }); </script> <style> .gr-parent {background-color:#bbffbb} .rd-parent {background-color:#ffbbbb} </style> The table below show all the currently supported functionality for the ``"default.qubit"`` device. At the moment, it takes into account the following parameters: * The interface, e.g. ``"jax"`` * The differentiation method, e.g. ``"parameter-shift"`` * The return value of the QNode, e.g. ``qml.expval()`` or ``qml.probs()`` * The number of shots, either None or an integer > 0 .. raw:: html <style> .tb { border-collapse: collapse; } .tb th, .tb td { padding: 1px; border: solid 1px black; } </style> .. rst-class:: tb +-------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+ | | **Return type** | +==================+==============================+==============+===============+==============+==============+===============+================+================+=============+=============+=============+ | **Interface** |**Differentiation method** | state |density matrix | probs | sample |expval (obs) | expval (herm) | expval (proj) | var | vn entropy | mutual info | +------------------+------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | ``None`` | ``"device"`` | :rd:`1` | :rd:`1` | :rd:`1` | :rd:`9` | :rd:`1` | :rd:`1` | :rd:`1` | :rd:`1` | :rd:`1` | :rd:`1` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"backprop"`` | :rd:`1` | :rd:`1` | :rd:`1` | :rd:`9` | :rd:`1` | :rd:`1` | :rd:`1` | :rd:`1` | :rd:`1` | :rd:`1` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"adjoint"`` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`9` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"parameter-shift"`` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`9` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"finite-diff"`` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`9` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"spsa"`` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`9` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"hadamard"`` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`9` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | :rd:`2` | +------------------+------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | ``"autograd"`` | ``"device"`` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`9` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"backprop"`` | :gr:`4` | :gr:`4` | :gr:`5` | :rd:`9` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"adjoint"`` | :gr:`7` | :gr:`7` | :gr:`7` | :rd:`9` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"parameter-shift"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :rd:`10` | :rd:`10` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"finite-diff"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"spsa"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"hadamard"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :rd:`11` | :rd:`10` | :rd:`10` | +------------------+------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | ``"jax"`` | ``"device"`` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`9` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"backprop"`` | :gr:`5` | :gr:`5` | :gr:`5` | :rd:`9` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"adjoint"`` | :gr:`7` | :gr:`7` | :gr:`7` | :rd:`9` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"parameter-shift"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :rd:`10` | :rd:`10` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"finite-diff"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"spsa"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"hadamard"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :rd:`11` | :rd:`10` | :rd:`10` | +------------------+------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | ``"tf"`` | ``"device"`` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`9` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"backprop"`` | :gr:`5` | :gr:`5` | :gr:`5` | :rd:`9` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"adjoint"`` | :gr:`7` | :gr:`7` | :gr:`7` | :rd:`9` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"parameter-shift"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :rd:`10` | :rd:`10` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"finite-diff"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"spsa"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"hadamard"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :rd:`11` | :rd:`10` | :rd:`10` | +------------------+------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | ``"torch"`` | ``"device"`` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`9` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | :rd:`3` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"backprop"`` | :gr:`5` | :gr:`5` | :gr:`5` | :rd:`9` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | :gr:`5` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"adjoint"`` | :gr:`7` | :gr:`7` | :gr:`7` | :rd:`9` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | :gr:`7` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"parameter-shift"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :rd:`10` | :rd:`10` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"finite-diff"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"spsa"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | :gr:`8` | + +------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ | | ``"hadamard"`` | :rd:`10` | :rd:`10` | :gr:`8` | :rd:`9` | :gr:`8` | :gr:`8` | :gr:`8` | :rd:`11` | :rd:`10` | :rd:`10` | +------------------+------------------------------+--------------+---------------+--------------+--------------+---------------+----------------+----------------+-------------+-------------+-------------+ 1. Not supported. Gradients are not computed even though ``diff_method`` is provided. Fails with error. 2. Not supported. Gradients are not computed even though ``diff_method`` is provided. Warns that no auto-differentiation framework is being used, but does not fail. Forward pass is still supported. 3. Not supported. The ``default.qubit`` device does not provide a native way to compute gradients. See :ref:`Device jacobian <Device jacobian>` for details. 4. Supported, but only when ``shots=None``. See :ref:`Backpropagation <Analytic backpropagation>` for details. If the circuit returns a state, then the circuit itself is not differentiable directly. However, any real scalar-valued post-processing done to the output of the circuit will be differentiable. See :ref:`State gradients <State gradients>` for details. 5. Supported, but only when ``shots=None``. See :ref:`Backpropagation <Analytic backpropagation>` for details. 6. Not supported. The adjoint differentiation algorithm is only implemented for analytic simulation. See :ref:`Adjoint differentation <Adjoint differentation>` for details. 7. Supported. Raises error when ``shots>0`` since the gradient is always computed analytically. See :ref:`Adjoint differentation <Adjoint differentation>` for details. 8. Supported. 9. Not supported. The discretization of the output caused by wave function collapse is not differentiable. The forward pass is still supported. See :ref:`Sample gradients <Sample gradients>` for details. 10. Not supported. "We just don't have the theory yet." 11. Not implemented. :html:`</div>` .. toctree:: :hidden: interfaces/numpy interfaces/torch interfaces/tf interfaces/jax unsupported_gradients
pennylane/doc/introduction/interfaces.rst/0
{ "file_path": "pennylane/doc/introduction/interfaces.rst", "repo_id": "pennylane", "token_count": 13676 }
38
:orphan: # Release 0.13.0 <h3>New features since last release</h3> <h4>Automatically optimize the number of measurements</h4> * QNodes in tape mode now support returning observables on the same wire whenever the observables are qubit-wise commuting Pauli words. Qubit-wise commuting observables can be evaluated with a *single* device run as they are diagonal in the same basis, via a shared set of single-qubit rotations. [(#882)](https://github.com/PennyLaneAI/pennylane/pull/882) The following example shows a single QNode returning the expectation values of the qubit-wise commuting Pauli words `XX` and `XI`: ```python qml.enable_tape() @qml.qnode(dev) def f(x): qml.Hadamard(wires=0) qml.Hadamard(wires=1) qml.CRot(0.1, 0.2, 0.3, wires=[1, 0]) qml.RZ(x, wires=1) return qml.expval(qml.PauliX(0) @ qml.PauliX(1)), qml.expval(qml.PauliX(0)) ``` ```pycon >>> f(0.4) tensor([0.89431013, 0.9510565 ], requires_grad=True) ``` * The `ExpvalCost` class (previously `VQECost`) now provides observable optimization using the `optimize` argument, resulting in potentially fewer device executions. [(#902)](https://github.com/PennyLaneAI/pennylane/pull/902) This is achieved by separating the observables composing the Hamiltonian into qubit-wise commuting groups and evaluating those groups on a single QNode using functionality from the `qml.grouping` module: ```python qml.enable_tape() commuting_obs = [qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1)] H = qml.vqe.Hamiltonian([1, 1], commuting_obs) dev = qml.device("default.qubit", wires=2) ansatz = qml.templates.StronglyEntanglingLayers cost_opt = qml.ExpvalCost(ansatz, H, dev, optimize=True) cost_no_opt = qml.ExpvalCost(ansatz, H, dev, optimize=False) params = qml.init.strong_ent_layers_uniform(3, 2) ``` Grouping these commuting observables leads to fewer device executions: ```pycon >>> cost_opt(params) >>> ex_opt = dev.num_executions >>> cost_no_opt(params) >>> ex_no_opt = dev.num_executions - ex_opt >>> print("Number of executions:", ex_no_opt) Number of executions: 2 >>> print("Number of executions (optimized):", ex_opt) Number of executions (optimized): 1 ``` <h4>New quantum gradient features</h4> * Compute the analytic gradient of quantum circuits in parallel on supported devices. [(#840)](https://github.com/PennyLaneAI/pennylane/pull/840) This release introduces support for batch execution of circuits, via a new device API method `Device.batch_execute()`. Devices that implement this new API support submitting a batch of circuits for *parallel* evaluation simultaneously, which can significantly reduce the computation time. Furthermore, if using tape mode and a compatible device, gradient computations will automatically make use of the new batch API---providing a speedup during optimization. * Gradient recipes are now much more powerful, allowing for operations to define their gradient via an arbitrary linear combination of circuit evaluations. [(#909)](https://github.com/PennyLaneAI/pennylane/pull/909) [(#915)](https://github.com/PennyLaneAI/pennylane/pull/915) With this change, gradient recipes can now be of the form :math:`\frac{\partial}{\partial\phi_k}f(\phi_k) = \sum_{i} c_i f(a_i \phi_k + s_i )`, and are no longer restricted to two-term shifts with identical (but opposite in sign) shift values. As a result, PennyLane now supports native analytic quantum gradients for the controlled rotation operations `CRX`, `CRY`, `CRZ`, and `CRot`. This allows for parameter-shift analytic gradients on hardware, without decomposition. Note that this is a breaking change for developers; please see the *Breaking Changes* section for more details. * The `qnn.KerasLayer` class now supports differentiating the QNode through classical backpropagation in tape mode. [(#869)](https://github.com/PennyLaneAI/pennylane/pull/869) ```python qml.enable_tape() dev = qml.device("default.qubit.tf", wires=2) @qml.qnode(dev, interface="tf", diff_method="backprop") def f(inputs, weights): qml.templates.AngleEmbedding(inputs, wires=range(2)) qml.templates.StronglyEntanglingLayers(weights, wires=range(2)) return [qml.expval(qml.PauliZ(i)) for i in range(2)] weight_shapes = {"weights": (3, 2, 3)} qlayer = qml.qnn.KerasLayer(f, weight_shapes, output_dim=2) inputs = tf.constant(np.random.random((4, 2)), dtype=tf.float32) with tf.GradientTape() as tape: out = qlayer(inputs) tape.jacobian(out, qlayer.trainable_weights) ``` <h4>New operations, templates, and measurements</h4> * Adds the `qml.density_matrix` QNode return with partial trace capabilities. [(#878)](https://github.com/PennyLaneAI/pennylane/pull/878) The density matrix over the provided wires is returned, with all other subsystems traced out. `qml.density_matrix` currently works for both the `default.qubit` and `default.mixed` devices. ```python qml.enable_tape() dev = qml.device("default.qubit", wires=2) def circuit(x): qml.PauliY(wires=0) qml.Hadamard(wires=1) return qml.density_matrix(wires=[1]) # wire 0 is traced out ``` * Adds the square-root X gate `SX`. [(#871)](https://github.com/PennyLaneAI/pennylane/pull/871) ```python dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def circuit(): qml.SX(wires=[0]) return qml.expval(qml.PauliZ(wires=[0])) ``` * Two new hardware-efficient particle-conserving templates have been implemented to perform VQE-based quantum chemistry simulations. The new templates apply several layers of the particle-conserving entanglers proposed in Figs. 2a and 2b of Barkoutsos *et al*., [arXiv:1805.04340](https://arxiv.org/abs/1805.04340) [(#875)](https://github.com/PennyLaneAI/pennylane/pull/875) [(#876)](https://github.com/PennyLaneAI/pennylane/pull/876) <h4>Estimate and track resources</h4> * The `QuantumTape` class now contains basic resource estimation functionality. The method `tape.get_resources()` returns a dictionary with a list of the constituent operations and the number of times they appear in the circuit. Similarly, `tape.get_depth()` computes the circuit depth. [(#862)](https://github.com/PennyLaneAI/pennylane/pull/862) ```pycon >>> with qml.tape.QuantumTape() as tape: ... qml.Hadamard(wires=0) ... qml.RZ(0.26, wires=1) ... qml.CNOT(wires=[1, 0]) ... qml.Rot(1.8, -2.7, 0.2, wires=0) ... qml.Hadamard(wires=1) ... qml.CNOT(wires=[0, 1]) ... qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) >>> tape.get_resources() {'Hadamard': 2, 'RZ': 1, 'CNOT': 2, 'Rot': 1} >>> tape.get_depth() 4 ``` * The number of device executions over a QNode's lifetime can now be returned using `num_executions`. [(#853)](https://github.com/PennyLaneAI/pennylane/pull/853) ```pycon >>> dev = qml.device("default.qubit", wires=2) >>> @qml.qnode(dev) ... def circuit(x, y): ... qml.RX(x, wires=[0]) ... qml.RY(y, wires=[1]) ... qml.CNOT(wires=[0, 1]) ... return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)) >>> for _ in range(10): ... circuit(0.432, 0.12) >>> print(dev.num_executions) 10 ``` <h3>Improvements</h3> * Support for tape mode has improved across PennyLane. The following features now work in tape mode: - QNode collections [(#863)](https://github.com/PennyLaneAI/pennylane/pull/863) - `qnn.ExpvalCost` [(#863)](https://github.com/PennyLaneAI/pennylane/pull/863) [(#911)](https://github.com/PennyLaneAI/pennylane/pull/911) - `qml.qnn.KerasLayer` [(#869)](https://github.com/PennyLaneAI/pennylane/pull/869) - `qml.qnn.TorchLayer` [(#865)](https://github.com/PennyLaneAI/pennylane/pull/865) - The `qml.qaoa` module [(#905)](https://github.com/PennyLaneAI/pennylane/pull/905) * A new function, `qml.refresh_devices()`, has been added, allowing PennyLane to rescan installed PennyLane plugins and refresh the device list. In addition, the `qml.device` loader will attempt to refresh devices if the required plugin device cannot be found. This will result in an improved experience if installing PennyLane and plugins within a running Python session (for example, on Google Colab), and avoid the need to restart the kernel/runtime. [(#907)](https://github.com/PennyLaneAI/pennylane/pull/907) * When using `grad_fn = qml.grad(cost)` to compute the gradient of a cost function with the Autograd interface, the value of the intermediate forward pass is now available via the `grad_fn.forward` property [(#914)](https://github.com/PennyLaneAI/pennylane/pull/914): ```python def cost_fn(x, y): return 2 * np.sin(x[0]) * np.exp(-x[1]) + x[0] ** 3 + np.cos(y) params = np.array([0.1, 0.5], requires_grad=True) data = np.array(0.65, requires_grad=False) grad_fn = qml.grad(cost_fn) grad_fn(params, data) # perform backprop and evaluate the gradient grad_fn.forward # the cost function value ``` * Gradient-based optimizers now have a `step_and_cost` method that returns both the next step as well as the objective (cost) function output. [(#916)](https://github.com/PennyLaneAI/pennylane/pull/916) ```pycon >>> opt = qml.GradientDescentOptimizer() >>> params, cost = opt.step_and_cost(cost_fn, params) ``` * PennyLane provides a new experimental module `qml.proc` which provides framework-agnostic processing functions for array and tensor manipulations. [(#886)](https://github.com/PennyLaneAI/pennylane/pull/886) Given the input tensor-like object, the call is dispatched to the corresponding array manipulation framework, allowing for end-to-end differentiation to be preserved. ```pycon >>> x = torch.tensor([1., 2.]) >>> qml.proc.ones_like(x) tensor([1, 1]) >>> y = tf.Variable([[0], [5]]) >>> qml.proc.ones_like(y, dtype=np.complex128) <tf.Tensor: shape=(2, 1), dtype=complex128, numpy= array([[1.+0.j], [1.+0.j]])> ``` Note that these functions are experimental, and only a subset of common functionality is supported. Furthermore, the names and behaviour of these functions may differ from similar functions in common frameworks; please refer to the function docstrings for more details. * The gradient methods in tape mode now fully separate the quantum and classical processing. Rather than returning the evaluated gradients directly, they now return a tuple containing the required quantum and classical processing steps. [(#840)](https://github.com/PennyLaneAI/pennylane/pull/840) ```python def gradient_method(idx, param, **options): # generate the quantum tapes that must be computed # to determine the quantum gradient tapes = quantum_gradient_tapes(self) def processing_fn(results): # perform classical processing on the evaluated tapes # returning the evaluated quantum gradient return classical_processing(results) return tapes, processing_fn ``` The `JacobianTape.jacobian()` method has been similarly modified to accumulate all gradient quantum tapes and classical processing functions, evaluate all quantum tapes simultaneously, and then apply the post-processing functions to the evaluated tape results. * The MultiRZ gate now has a defined generator, allowing it to be used in quantum natural gradient optimization. [(#912)](https://github.com/PennyLaneAI/pennylane/pull/912) * The CRot gate now has a `decomposition` method, which breaks the gate down into rotations and CNOT gates. This allows `CRot` to be used on devices that do not natively support it. [(#908)](https://github.com/PennyLaneAI/pennylane/pull/908) * The classical processing in the `MottonenStatePreparation` template has been largely rewritten to use dense matrices and tensor manipulations wherever possible. This is in preparation to support differentiation through the template in the future. [(#864)](https://github.com/PennyLaneAI/pennylane/pull/864) * Device-based caching has replaced QNode caching. Caching is now accessed by passing a `cache` argument to the device. [(#851)](https://github.com/PennyLaneAI/pennylane/pull/851) The `cache` argument should be an integer specifying the size of the cache. For example, a cache of size 10 is created using: ```pycon >>> dev = qml.device("default.qubit", wires=2, cache=10) ``` * The `Operation`, `Tensor`, and `MeasurementProcess` classes now have the `__copy__` special method defined. [(#840)](https://github.com/PennyLaneAI/pennylane/pull/840) This allows us to ensure that, when a shallow copy is performed of an operation, the mutable list storing the operation parameters is *also* shallow copied. Both the old operation and the copied operation will continue to share the same parameter data, ```pycon >>> import copy >>> op = qml.RX(0.2, wires=0) >>> op2 = copy.copy(op) >>> op.data[0] is op2.data[0] True ``` however the *list container* is not a reference: ```pycon >>> op.data is op2.data False ``` This allows the parameters of the copied operation to be modified, without mutating the parameters of the original operation. * The `QuantumTape.copy` method has been tweaked so that [(#840)](https://github.com/PennyLaneAI/pennylane/pull/840): - Optionally, the tape's operations are shallow copied in addition to the tape by passing the `copy_operations=True` boolean flag. This allows the copied tape's parameters to be mutated without affecting the original tape's parameters. (Note: the two tapes will share parameter data *until* one of the tapes has their parameter list modified.) - Copied tapes can be cast to another `QuantumTape` subclass by passing the `tape_cls` keyword argument. <h3>Breaking changes</h3> * Updated how parameter-shift gradient recipes are defined for operations, allowing for gradient recipes that are specified as an arbitrary number of terms. [(#909)](https://github.com/PennyLaneAI/pennylane/pull/909) Previously, `Operation.grad_recipe` was restricted to two-term parameter-shift formulas. With this change, the gradient recipe now contains elements of the form :math:`[c_i, a_i, s_i]`, resulting in a gradient recipe of :math:`\frac{\partial}{\partial\phi_k}f(\phi_k) = \sum_{i} c_i f(a_i \phi_k + s_i )`. As this is a breaking change, all custom operations with defined gradient recipes must be updated to continue working with PennyLane 0.13. Note though that if `grad_recipe = None`, the default gradient recipe remains unchanged, and corresponds to the two terms :math:`[c_0, a_0, s_0]=[1/2, 1, \pi/2]` and :math:`[c_1, a_1, s_1]=[-1/2, 1, -\pi/2]` for every parameter. - The `VQECost` class has been renamed to `ExpvalCost` to reflect its general applicability beyond VQE. Use of `VQECost` is still possible but will result in a deprecation warning. [(#913)](https://github.com/PennyLaneAI/pennylane/pull/913) <h3>Bug fixes</h3> * The `default.qubit.tf` device is updated to handle TensorFlow objects (e.g., `tf.Variable`) as gate parameters correctly when using the `MultiRZ` and `CRot` operations. [(#921)](https://github.com/PennyLaneAI/pennylane/pull/921) * PennyLane tensor objects are now unwrapped in BaseQNode when passed as a keyword argument to the quantum function. [(#903)](https://github.com/PennyLaneAI/pennylane/pull/903) [(#893)](https://github.com/PennyLaneAI/pennylane/pull/893) * The new tape mode now prevents multiple observables from being evaluated on the same wire if the observables are not qubit-wise commuting Pauli words. [(#882)](https://github.com/PennyLaneAI/pennylane/pull/882) * Fixes a bug in `default.qubit` whereby inverses of common gates were not being applied via efficient gate-specific methods, instead falling back to matrix-vector multiplication. The following gates were affected: `PauliX`, `PauliY`, `PauliZ`, `Hadamard`, `SWAP`, `S`, `T`, `CNOT`, `CZ`. [(#872)](https://github.com/PennyLaneAI/pennylane/pull/872) * The `PauliRot` operation now gracefully handles single-qubit Paulis, and all-identity Paulis [(#860)](https://github.com/PennyLaneAI/pennylane/pull/860). * Fixes a bug whereby binary Python operators were not properly propagating the `requires_grad` attribute to the output tensor. [(#889)](https://github.com/PennyLaneAI/pennylane/pull/889) * Fixes a bug which prevents `TorchLayer` from doing `backward` when CUDA is enabled. [(#899)](https://github.com/PennyLaneAI/pennylane/pull/899) * Fixes a bug where multi-threaded execution of `QNodeCollection` sometimes fails because of simultaneous queuing. This is fixed by adding thread locking during queuing. [(#910)](https://github.com/PennyLaneAI/pennylane/pull/918) * Fixes a bug in `QuantumTape.set_parameters()`. The previous implementation assumed that the `self.trainable_parms` set would always be iterated over in increasing integer order. However, this is not guaranteed behaviour, and can lead to the incorrect tape parameters being set if this is not the case. [(#923)](https://github.com/PennyLaneAI/pennylane/pull/923) * Fixes broken error message if a QNode is instantiated with an unknown exception. [(#930)](https://github.com/PennyLaneAI/pennylane/pull/930) <h3>Contributors</h3> This release contains contributions from (in alphabetical order): Juan Miguel Arrazola, Thomas Bromley, Christina Lee, Alain Delgado Gran, Olivia Di Matteo, Anthony Hayes, Theodor Isacsson, Josh Izaac, Soran Jahangiri, Nathan Killoran, Shumpei Kobayashi, Romain Moyard, Zeyue Niu, Maria Schuld, Antal Száva.
pennylane/doc/releases/changelog-0.13.0.md/0
{ "file_path": "pennylane/doc/releases/changelog-0.13.0.md", "repo_id": "pennylane", "token_count": 5985 }
39
:orphan: # Release 0.23.0 <h3>New features since last release</h3> <h4> More powerful circuit cutting ✂️</h4> * Quantum circuit cutting (running `N`-wire circuits on devices with fewer than `N` wires) is now supported for QNodes of finite-shots using the new `@qml.cut_circuit_mc` transform. [(#2313)](https://github.com/PennyLaneAI/pennylane/pull/2313) [(#2321)](https://github.com/PennyLaneAI/pennylane/pull/2321) [(#2332)](https://github.com/PennyLaneAI/pennylane/pull/2332) [(#2358)](https://github.com/PennyLaneAI/pennylane/pull/2358) [(#2382)](https://github.com/PennyLaneAI/pennylane/pull/2382) [(#2399)](https://github.com/PennyLaneAI/pennylane/pull/2399) [(#2407)](https://github.com/PennyLaneAI/pennylane/pull/2407) [(#2444)](https://github.com/PennyLaneAI/pennylane/pull/2444) With these new additions, samples from the original circuit can be simulated using a Monte Carlo method, using fewer qubits at the expense of more device executions. Additionally, this transform can take an optional classical processing function as an argument and return an expectation value. The following `3`-qubit circuit contains a `WireCut` operation and a `sample` measurement. When decorated with `@qml.cut_circuit_mc`, we can cut the circuit into two `2`-qubit fragments: ```python dev = qml.device("default.qubit", wires=2, shots=1000) @qml.cut_circuit_mc @qml.qnode(dev) def circuit(x): qml.RX(0.89, wires=0) qml.RY(0.5, wires=1) qml.RX(1.3, wires=2) qml.CNOT(wires=[0, 1]) qml.WireCut(wires=1) qml.CNOT(wires=[1, 2]) qml.RX(x, wires=0) qml.RY(0.7, wires=1) qml.RX(2.3, wires=2) return qml.sample(wires=[0, 2]) ``` we can then execute the circuit as usual by calling the QNode: ```pycon >>> x = 0.3 >>> circuit(x) tensor([[1, 1], [0, 1], [0, 1], ..., [0, 1], [0, 1], [0, 1]], requires_grad=True) ``` Furthermore, the number of shots can be temporarily altered when calling the QNode: ```pycon >>> results = circuit(x, shots=123) >>> results.shape (123, 2) ``` The `cut_circuit_mc` transform also supports returning sample-based expectation values of observables using the `classical_processing_fn` argument. Refer to the `UsageDetails` section of the [transform documentation](https://pennylane.readthedocs.io/en/latest/code/api/pennylane.cut_circuit_mc.html) for an example. * The `cut_circuit` transform now supports automatic graph partitioning by specifying `auto_cutter=True` to cut arbitrary tape-converted graphs using the general purpose graph partitioning framework [KaHyPar](https://pypi.org/project/kahypar/). [(#2330)](https://github.com/PennyLaneAI/pennylane/pull/2330) [(#2428)](https://github.com/PennyLaneAI/pennylane/pull/2428) Note that `KaHyPar` needs to be installed separately with the `auto_cutter=True` option. For integration with the existing low-level manual cut pipeline, refer to the [documentation of the function](https://pennylane.readthedocs.io/en/latest/code/api/pennylane.transforms.qcut.find_and_place_cuts.html) . ```pycon @qml.cut_circuit(auto_cutter=True) @qml.qnode(dev) def circuit(x): qml.RX(x, wires=0) qml.RY(0.9, wires=1) qml.RX(0.3, wires=2) qml.CZ(wires=[0, 1]) qml.RY(-0.4, wires=0) qml.CZ(wires=[1, 2]) return qml.expval(qml.grouping.string_to_pauli_word("ZZZ")) ``` ```pycon >>> x = np.array(0.531, requires_grad=True) >>> circuit(x) 0.47165198882111165 >>> qml.grad(circuit)(x) -0.276982865449393 ``` <h4>Grand QChem unification ⚛️ 🏰</h4> * Quantum chemistry functionality --- previously split between an external `pennylane-qchem` package and internal `qml.hf` differentiable Hartree-Fock solver --- is now unified into a single, included, `qml.qchem` module. [(#2164)](https://github.com/PennyLaneAI/pennylane/pull/2164) [(#2385)](https://github.com/PennyLaneAI/pennylane/pull/2385) [(#2352)](https://github.com/PennyLaneAI/pennylane/pull/2352) [(#2420)](https://github.com/PennyLaneAI/pennylane/pull/2420) [(#2454)](https://github.com/PennyLaneAI/pennylane/pull/2454) [(#2199)](https://github.com/PennyLaneAI/pennylane/pull/2199) [(#2371)](https://github.com/PennyLaneAI/pennylane/pull/2371) [(#2272)](https://github.com/PennyLaneAI/pennylane/pull/2272) [(#2230)](https://github.com/PennyLaneAI/pennylane/pull/2230) [(#2415)](https://github.com/PennyLaneAI/pennylane/pull/2415) [(#2426)](https://github.com/PennyLaneAI/pennylane/pull/2426) [(#2465)](https://github.com/PennyLaneAI/pennylane/pull/2465) The `qml.qchem` module provides a differentiable Hartree-Fock solver and the functionality to construct a fully-differentiable molecular Hamiltonian. For example, one can continue to generate molecular Hamiltonians using `qml.qchem.molecular_hamiltonian`: ```python symbols = ["H", "H"] geometry = np.array([[0., 0., -0.66140414], [0., 0., 0.66140414]]) hamiltonian, qubits = qml.qchem.molecular_hamiltonian(symbols, geometry, method="dhf") ``` By default, this will use the differentiable Hartree-Fock solver; however, simply set `method="pyscf"` to continue to use PySCF for Hartree-Fock calculations. * Functions are added for building a differentiable dipole moment observable. Functions for computing multipole moment molecular integrals, needed for building the dipole moment observable, are also added. [(#2173)](https://github.com/PennyLaneAI/pennylane/pull/2173) [(#2166)](https://github.com/PennyLaneAI/pennylane/pull/2166) The dipole moment observable can be constructed using `qml.qchem.dipole_moment`: ```python symbols = ['H', 'H'] geometry = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) mol = qml.qchem.Molecule(symbols, geometry) args = [geometry] D = qml.qchem.dipole_moment(mol)(*args) ``` * The efficiency of computing molecular integrals and Hamiltonian is improved. This has been done by adding optimized functions for building fermionic and qubit observables and optimizing the functions used for computing the electron repulsion integrals. [(#2316)](https://github.com/PennyLaneAI/pennylane/pull/2316) * The `6-31G` basis set is added to the qchem basis set repo. This addition allows performing differentiable Hartree-Fock calculations with basis sets beyond the minimal `sto-3g` basis set for atoms with atomic number 1-10. [(#2372)](https://github.com/PennyLaneAI/pennylane/pull/2372) The `6-31G` basis set can be used to construct a Hamiltonian as ```python symbols = ["H", "H"] geometry = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) H, qubits = qml.qchem.molecular_hamiltonian(symbols, geometry, basis="6-31g") ``` * External dependencies are replaced with local functions for spin and particle number observables. [(#2197)](https://github.com/PennyLaneAI/pennylane/pull/2197) [(#2362)](https://github.com/PennyLaneAI/pennylane/pull/2362) <h4>Pattern matching optimization 🔎 💎 </h4> * Added an optimization transform that matches pieces of user-provided identity templates in a circuit and replaces them with an equivalent component. [(#2032)](https://github.com/PennyLaneAI/pennylane/pull/2032) For example, consider the following circuit where we want to replace sequence of two `pennylane.S` gates with a `pennylane.PauliZ` gate. ```python def circuit(): qml.S(wires=0) qml.PauliZ(wires=0) qml.S(wires=1) qml.CZ(wires=[0, 1]) qml.S(wires=1) qml.S(wires=2) qml.CZ(wires=[1, 2]) qml.S(wires=2) return qml.expval(qml.PauliX(wires=0)) ``` We specify use the following pattern that implements the identity: ```python with qml.tape.QuantumTape() as pattern: qml.S(wires=0) qml.S(wires=0) qml.PauliZ(wires=0) ``` To optimize the circuit with this identity pattern, we apply the `qml.transforms.pattern_matching` transform. ```pycon >>> dev = qml.device('default.qubit', wires=5) >>> qnode = qml.QNode(circuit, dev) >>> optimized_qfunc = qml.transforms.pattern_matching_optimization(pattern_tapes=[pattern])(circuit) >>> optimized_qnode = qml.QNode(optimized_qfunc, dev) >>> print(qml.draw(qnode)()) 0: ──S──Z─╭C──────────┤ <X> 1: ──S────╰Z──S─╭C────┤ 2: ──S──────────╰Z──S─┤ >>> print(qml.draw(optimized_qnode)()) 0: ──S⁻¹─╭C────┤ <X> 1: ──Z───╰Z─╭C─┤ 2: ──Z──────╰Z─┤ ``` For more details on using pattern matching optimization you can check the [corresponding documentation](https://pennylane.readthedocs.io/en/latest/code/api/pennylane.pattern_matching_optimization.html) and also the following [paper](https://dl.acm.org/doi/full/10.1145/3498325). <h4>Measure the distance between two unitaries📏</h4> * Added the `HilbertSchmidt` and the `LocalHilbertSchmidt` templates to be used for computing distance measures between unitaries. [(#2364)](https://github.com/PennyLaneAI/pennylane/pull/2364) Given a unitary `U`, `qml.HilberSchmidt` can be used to measure the distance between unitaries and to define a cost function (`cost_hst`) used for learning a unitary `V` that is equivalent to `U` up to a global phase: ```python # Represents unitary U with qml.tape.QuantumTape(do_queue=False) as u_tape: qml.Hadamard(wires=0) # Represents unitary V def v_function(params): qml.RZ(params[0], wires=1) @qml.qnode(dev) def hilbert_test(v_params, v_function, v_wires, u_tape): qml.HilbertSchmidt(v_params, v_function=v_function, v_wires=v_wires, u_tape=u_tape) return qml.probs(u_tape.wires + v_wires) def cost_hst(parameters, v_function, v_wires, u_tape): return (1 - hilbert_test(v_params=parameters, v_function=v_function, v_wires=v_wires, u_tape=u_tape)[0]) ``` ```pycon >>> cost_hst(parameters=[0.1], v_function=v_function, v_wires=[1], u_tape=u_tape) tensor(0.999, requires_grad=True) ``` For more information refer to the [documentation of qml.HilbertSchmidt](https://pennylane.readthedocs.io/en/latest/code/api/pennylane.HilbertSchmidt.html). <h4>More tensor network support 🕸️</h4> * Adds the `qml.MERA` template for implementing quantum circuits with the shape of a multi-scale entanglement renormalization ansatz (MERA). [(#2418)](https://github.com/PennyLaneAI/pennylane/pull/2418) MERA follows the style of previous tensor network templates and is similar to [quantum convolutional neural networks](https://arxiv.org/abs/1810.03787). ```python def block(weights, wires): qml.CNOT(wires=[wires[0],wires[1]]) qml.RY(weights[0], wires=wires[0]) qml.RY(weights[1], wires=wires[1]) n_wires = 4 n_block_wires = 2 n_params_block = 2 n_blocks = qml.MERA.get_n_blocks(range(n_wires),n_block_wires) template_weights = [[0.1,-0.3]]*n_blocks dev= qml.device('default.qubit',wires=range(n_wires)) @qml.qnode(dev) def circuit(template_weights): qml.MERA(range(n_wires),n_block_wires,block, n_params_block, template_weights) return qml.expval(qml.PauliZ(wires=1)) ``` It may be necessary to reorder the wires to see the MERA architecture clearly: ```pycon >>> print(qml.draw(circuit,expansion_strategy='device',wire_order=[2,0,1,3])(template_weights)) 2: ───────────────╭C──RY(0.10)──╭X──RY(-0.30)───────────────┤ 0: ─╭X──RY(-0.30)─│─────────────╰C──RY(0.10)──╭C──RY(0.10)──┤ 1: ─╰C──RY(0.10)──│─────────────╭X──RY(-0.30)─╰X──RY(-0.30)─┤ <Z> 3: ───────────────╰X──RY(-0.30)─╰C──RY(0.10)────────────────┤ ``` <h4>New transform for transpilation ⚙️ </h4> * Added a swap based transpiler transform. [(#2118)](https://github.com/PennyLaneAI/pennylane/pull/2118) The transpile function takes a quantum function and a coupling map as inputs and compiles the circuit to ensure that it can be executed on corresponding hardware. The transform can be used as a decorator in the following way: ```python dev = qml.device('default.qubit', wires=4) @qml.qnode(dev) @qml.transforms.transpile(coupling_map=[(0, 1), (1, 2), (2, 3)]) def circuit(param): qml.CNOT(wires=[0, 1]) qml.CNOT(wires=[0, 2]) qml.CNOT(wires=[0, 3]) qml.PhaseShift(param, wires=0) return qml.probs(wires=[0, 1, 2, 3]) ``` ```pycon >>> print(qml.draw(circuit)(0.3)) 0: ─╭C───────╭C──────────╭C──Rϕ(0.30)─┤ ╭Probs 1: ─╰X─╭SWAP─╰X────╭SWAP─╰X───────────┤ ├Probs 2: ────╰SWAP─╭SWAP─╰SWAP──────────────┤ ├Probs 3: ──────────╰SWAP────────────────────┤ ╰Probs ``` <h3>Improvements</h3> * `QuantumTape` objects are now iterable, allowing iteration over the contained operations and measurements. [(#2342)](https://github.com/PennyLaneAI/pennylane/pull/2342) ```python with qml.tape.QuantumTape() as tape: qml.RX(0.432, wires=0) qml.RY(0.543, wires=0) qml.CNOT(wires=[0, 'a']) qml.RX(0.133, wires='a') qml.expval(qml.PauliZ(wires=[0])) ``` Given a `QuantumTape` object the underlying quantum circuit can be iterated over using a `for` loop: ```pycon >>> for op in tape: ... print(op) RX(0.432, wires=[0]) RY(0.543, wires=[0]) CNOT(wires=[0, 'a']) RX(0.133, wires=['a']) expval(PauliZ(wires=[0])) ``` Indexing into the circuit is also allowed via `tape[i]`: ```pycon >>> tape[0] RX(0.432, wires=[0]) ``` A tape object can also be converted to a sequence (e.g., to a `list`) of operations and measurements: ```pycon >>> list(tape) [RX(0.432, wires=[0]), RY(0.543, wires=[0]), CNOT(wires=[0, 'a']), RX(0.133, wires=['a']), expval(PauliZ(wires=[0]))] ``` * Added the `QuantumTape.shape` method and `QuantumTape.numeric_type` attribute to allow extracting information about the shape and numeric type of the output returned by a quantum tape after execution. [(#2044)](https://github.com/PennyLaneAI/pennylane/pull/2044) ```python dev = qml.device("default.qubit", wires=2) a = np.array([0.1, 0.2, 0.3]) def func(a): qml.RY(a[0], wires=0) qml.RX(a[1], wires=0) qml.RY(a[2], wires=0) with qml.tape.QuantumTape() as tape: func(a) qml.state() ``` ```pycon >>> tape.shape(dev) (1, 4) >>> tape.numeric_type complex ``` * Defined a `MeasurementProcess.shape` method and a `MeasurementProcess.numeric_type` attribute to allow extracting information about the shape and numeric type of results obtained when evaluating QNodes using the specific measurement process. [(#2044)](https://github.com/PennyLaneAI/pennylane/pull/2044) * The parameter-shift Hessian can now be computed for arbitrary operations that support the general parameter-shift rule for gradients, using `qml.gradients.param_shift_hessian` [(#2319)](https://github.com/XanaduAI/pennylane/pull/2319) Multiple ways to obtain the gradient recipe are supported, in the following order of preference: - A custom `grad_recipe`. It is iterated to obtain the shift rule for the second-order derivatives in the diagonal entries of the Hessian. - Custom `parameter_frequencies`. The second-order shift rule can directly be computed using them. - An operation's `generator`. Its eigenvalues will be used to obtain `parameter_frequencies`, if they are not given explicitly for an operation. * The strategy for expanding a circuit can now be specified with the `qml.specs` transform, for example to calculate the specifications of the circuit that will actually be executed by the device (`expansion_strategy="device"`). [(#2395)](https://github.com/PennyLaneAI/pennylane/pull/2395) * The `default.qubit` and `default.mixed` devices now skip over identity operators instead of performing matrix multiplication with the identity. [(#2356)](https://github.com/PennyLaneAI/pennylane/pull/2356) [(#2365)](https://github.com/PennyLaneAI/pennylane/pull/2365) * The function `qml.eigvals` is modified to use the efficient `scipy.sparse.linalg.eigsh` method for obtaining the eigenvalues of a `SparseHamiltonian`. This `scipy` method is called to compute :math:`k` eigenvalues of a sparse :math:`N \times N` matrix if `k` is smaller than :math:`N-1`. If a larger :math:`k` is requested, the dense matrix representation of the Hamiltonian is constructed and the regular `qml.math.linalg.eigvalsh` is applied. [(#2333)](https://github.com/PennyLaneAI/pennylane/pull/2333) * The function `qml.ctrl` was given the optional argument `control_values=None`. If overridden, `control_values` takes an integer or a list of integers corresponding to the binary value that each control value should take. The same change is reflected in `ControlledOperation`. Control values of `0` are implemented by `qml.PauliX` applied before and after the controlled operation [(#2288)](https://github.com/PennyLaneAI/pennylane/pull/2288) * Operators now have a `has_matrix` property denoting whether or not the operator defines a matrix. [(#2331)](https://github.com/PennyLaneAI/pennylane/pull/2331) [(#2476)](https://github.com/PennyLaneAI/pennylane/pull/2476) * Circuit cutting now performs expansion to search for wire cuts in contained operations or tapes. [(#2340)](https://github.com/PennyLaneAI/pennylane/pull/2340) * The `qml.draw` and `qml.draw_mpl` transforms are now located in the `drawer` module. They can still be accessed via the top-level `qml` namespace. [(#2396)](https://github.com/PennyLaneAI/pennylane/pull/2396) * Raise a warning where caching produces identical shot noise on execution results with finite shots. [(#2478)](https://github.com/PennyLaneAI/pennylane/pull/2478) <h3>Deprecations</h3> * The `ObservableReturnTypes` `Sample`, `Variance`, `Expectation`, `Probability`, `State`, and `MidMeasure` have been moved to `measurements` from `operation`. [(#2329)](https://github.com/PennyLaneAI/pennylane/pull/2329) [(#2481)](https://github.com/PennyLaneAI/pennylane/pull/2481) <h3>Breaking changes</h3> * The caching ability of devices has been removed. Using the caching on the QNode level is the recommended alternative going forward. [(#2443)](https://github.com/PennyLaneAI/pennylane/pull/2443) One way for replicating the removed `QubitDevice` caching behaviour is by creating a `cache` object (e.g., a dictionary) and passing it to the `QNode`: ```python n_wires = 4 wires = range(n_wires) dev = qml.device('default.qubit', wires=n_wires) cache = {} @qml.qnode(dev, diff_method='parameter-shift', cache=cache) def expval_circuit(params): qml.templates.BasicEntanglerLayers(params, wires=wires, rotation=qml.RX) return qml.expval(qml.PauliZ(0) @ qml.PauliY(1) @ qml.PauliX(2) @ qml.PauliZ(3)) shape = qml.templates.BasicEntanglerLayers.shape(5, n_wires) params = np.random.random(shape) ``` ```pycon >>> expval_circuit(params) tensor(0.20598436, requires_grad=True) >>> dev.num_executions 1 >>> expval_circuit(params) tensor(0.20598436, requires_grad=True) >>> dev.num_executions 1 ``` * The `qml.finite_diff` function has been removed. Please use `qml.gradients.finite_diff` to compute the gradient of tapes of QNodes. Otherwise, manual implementation is required. [(#2464)](https://github.com/PennyLaneAI/pennylane/pull/2464) * The `get_unitary_matrix` transform has been removed, please use `qml.matrix` instead. [(#2457)](https://github.com/PennyLaneAI/pennylane/pull/2457) * The `update_stepsize` method has been removed from `GradientDescentOptimizer` and its child optimizers. The `stepsize` property can be interacted with directly instead. [(#2370)](https://github.com/PennyLaneAI/pennylane/pull/2370) * Most optimizers no longer flatten and unflatten arguments during computation. Due to this change, user provided gradient functions *must* return the same shape as `qml.grad`. [(#2381)](https://github.com/PennyLaneAI/pennylane/pull/2381) * The old circuit text drawing infrastructure has been removed. [(#2310)](https://github.com/PennyLaneAI/pennylane/pull/2310) - `RepresentationResolver` was replaced by the `Operator.label` method. - `qml.drawer.CircuitDrawer` was replaced by `qml.drawer.tape_text`. - `qml.drawer.CHARSETS` was removed because unicode is assumed to be accessible. - `Grid` and `qml.drawer.drawable_grid` were removed because the custom data class was replaced by list of sets of operators or measurements. - `qml.transforms.draw_old` was replaced by `qml.draw`. - `qml.CircuitGraph.greedy_layers` was deleted, as it was no longer needed by the circuit drawer and did not seem to have uses outside of that situation. - `qml.CircuitGraph.draw` was deleted, as we draw tapes instead. - The tape method `qml.tape.QuantumTape.draw` now simply calls `qml.drawer.tape_text`. - In the new pathway, the `charset` keyword was deleted, the `max_length` keyword defaults to `100`, and the `decimals` and `show_matrices` keywords were added. * The deprecated QNode, available via `qml.qnode_old.QNode`, has been removed. Please transition to using the standard `qml.QNode`. [(#2336)](https://github.com/PennyLaneAI/pennylane/pull/2336) [(#2337)](https://github.com/PennyLaneAI/pennylane/pull/2337) [(#2338)](https://github.com/PennyLaneAI/pennylane/pull/2338) In addition, several other components which powered the deprecated QNode have been removed: - The deprecated, non-batch compatible interfaces, have been removed. - The deprecated tape subclasses `QubitParamShiftTape`, `JacobianTape`, `CVParamShiftTape`, and `ReversibleTape` have been removed. * The deprecated tape execution method `tape.execute(device)` has been removed. Please use `qml.execute([tape], device)` instead. [(#2339)](https://github.com/PennyLaneAI/pennylane/pull/2339) <h3>Bug fixes</h3> * Fixed a bug in the `qml.PauliRot` operation, where computing the generator was not taking into account the operation wires. [(#2466)](https://github.com/PennyLaneAI/pennylane/pull/2466) * Fixed a bug where non-trainable arguments were shifted in the `NesterovMomentumOptimizer` if a trainable argument was after it in the argument list. [(#2466)](https://github.com/PennyLaneAI/pennylane/pull/2466) * Fixed a bug with `@jax.jit` for grad when `diff_method="adjoint"` and `mode="backward"`. [(#2460)](https://github.com/PennyLaneAI/pennylane/pull/2460) * Fixed a bug where `qml.DiagonalQubitUnitary` did not support `@jax.jit` and `@tf.function`. [(#2445)](https://github.com/PennyLaneAI/pennylane/pull/2445) * Fixed a bug in the `qml.PauliRot` operation, where computing the generator was not taking into account the operation wires. [(#2442)](https://github.com/PennyLaneAI/pennylane/pull/2442) * Fixed a bug with the padding capability of `AmplitudeEmbedding` where the inputs are on the GPU. [(#2431)](https://github.com/PennyLaneAI/pennylane/pull/2431) * Fixed a bug by adding a comprehensible error message for calling `qml.probs` without passing wires or an observable. [(#2438)](https://github.com/PennyLaneAI/pennylane/pull/2438) * The behaviour of `qml.about()` was modified to avoid warnings being emitted due to legacy behaviour of `pip`. [(#2422)](https://github.com/PennyLaneAI/pennylane/pull/2422) * Fixed a bug where observables were not considered when determining the use of the `jax-jit` interface. [(#2427)](https://github.com/PennyLaneAI/pennylane/pull/2427) [(#2474)](https://github.com/PennyLaneAI/pennylane/pull/2474) * Fixed a bug where computing statistics for a relatively few number of shots (e.g., `shots=10`), an error arose due to indexing into an array using a `Array`. [(#2427)](https://github.com/PennyLaneAI/pennylane/pull/2427) * PennyLane Lightning version in Docker container is pulled from latest wheel-builds. [(#2416)](https://github.com/PennyLaneAI/pennylane/pull/2416) * Optimizers only consider a variable trainable if they have `requires_grad = True`. [(#2381)](https://github.com/PennyLaneAI/pennylane/pull/2381) * Fixed a bug with `qml.expval`, `qml.var`, `qml.state` and `qml.probs` (when `qml.probs` is the only measurement) where the `dtype` specified on the device did not match the `dtype` of the QNode output. [(#2367)](https://github.com/PennyLaneAI/pennylane/pull/2367) * Fixed a bug where the output shapes from batch transforms are inconsistent with the QNode output shape. [(#2215)](https://github.com/PennyLaneAI/pennylane/pull/2215) * Fixed a bug caused by the squeezing in `qml.gradients.param_shift_hessian`. [(#2215)](https://github.com/PennyLaneAI/pennylane/pull/2215) * Fixed a bug in which the `expval`/`var` of a `Tensor(Observable)` would depend on the order in which the observable is defined: [(#2276)](https://github.com/PennyLaneAI/pennylane/pull/2276) ```pycon >>> @qml.qnode(dev) ... def circ(op): ... qml.RX(0.12, wires=0) ... qml.RX(1.34, wires=1) ... qml.RX(3.67, wires=2) ... return qml.expval(op) >>> op1 = qml.Identity(wires=0) @ qml.Identity(wires=1) @ qml.PauliZ(wires=2) >>> op2 = qml.PauliZ(wires=2) @ qml.Identity(wires=0) @ qml.Identity(wires=1) >>> print(circ(op1), circ(op2)) -0.8636111153905662 -0.8636111153905662 ``` * Fixed a bug where `qml.hf.transform_hf()` would fail due to missing wires in the qubit operator that is prepared for tapering the HF state. [(#2441)](https://github.com/PennyLaneAI/pennylane/pull/2441) * Fixed a bug with custom device defined jacobians not being returned properly. [(#2485)](https://github.com/PennyLaneAI/pennylane/pull/2485) <h3>Documentation</h3> * The sections on adding operator and observable support in the "How to add a plugin" section of the plugins page have been updated. [(#2389)](https://github.com/PennyLaneAI/pennylane/pull/2389) * The missing arXiv reference in the `LieAlgebra` optimizer has been fixed. [(#2325)](https://github.com/PennyLaneAI/pennylane/pull/2325) <h3>Contributors</h3> This release contains contributions from (in alphabetical order): Karim Alaa El-Din, Guillermo Alonso-Linaje, Juan Miguel Arrazola, Ali Asadi, Utkarsh Azad, Sam Banning, Thomas Bromley, Alain Delgado, Isaac De Vlugt, Olivia Di Matteo, Amintor Dusko, Anthony Hayes, David Ittah, Josh Izaac, Soran Jahangiri, Nathan Killoran, Christina Lee, Angus Lowe, Romain Moyard, Zeyue Niu, Matthew Silverman, Lee James O'Riordan, Maria Schuld, Jay Soni, Antal Száva, Maurice Weber, David Wierichs.
pennylane/doc/releases/changelog-0.23.0.md/0
{ "file_path": "pennylane/doc/releases/changelog-0.23.0.md", "repo_id": "pennylane", "token_count": 10196 }
40
:orphan: # Release 0.33.1 <h3>Bug fixes 🐛</h3> * Fix gradient performance regression due to expansion of VJP products. [(#4806)](https://github.com/PennyLaneAI/pennylane/pull/4806) * `qml.defer_measurements` now correctly transforms circuits when terminal measurements include wires used in mid-circuit measurements. [(#4787)](https://github.com/PennyLaneAI/pennylane/pull/4787) * Any `ScalarSymbolicOp`, like `Evolution`, now states that it has a matrix if the target is a `Hamiltonian`. [(#4768)](https://github.com/PennyLaneAI/pennylane/pull/4768) * In `default.qubit`, initial states are now initialized with the simulator's wire order, not the circuit's wire order. [(#4781)](https://github.com/PennyLaneAI/pennylane/pull/4781) <h3>Contributors ✍️</h3> This release contains contributions from (in alphabetical order): Christina Lee, Lee James O'Riordan, Mudit Pandey
pennylane/doc/releases/changelog-0.33.1.md/0
{ "file_path": "pennylane/doc/releases/changelog-0.33.1.md", "repo_id": "pennylane", "token_count": 313 }
41
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # 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. # pylint: disable=protected-access """ Contains a utility class ``BooleanFn`` that allows logical composition of functions with boolean output. """ import functools # pylint: disable=unnecessary-lambda class BooleanFn: r"""Wrapper for simple callables with Boolean output that can be manipulated and combined with bitwise operators. Args: fn (callable): Function to be wrapped. It can accept any number of arguments, and must return a Boolean. **Example** Consider functions that filter numbers to lie within a certain domain. We may wrap them using ``BooleanFn``: .. code-block:: python bigger_than_4 = qml.BooleanFn(lambda x: x > 4) smaller_than_10 = qml.BooleanFn(lambda x: x < 10) is_int = qml.BooleanFn(lambda x: isinstance(x, int)) >>> bigger_than_4(5.2) True >>> smaller_than_10(20.1) False >>> is_int(2.3) False These can then be combined into a single callable using boolean operators, such as ``&`` (logical and): >>> between_4_and_10 = bigger_than_4 & smaller_than_10 >>> between_4_and_10(-3.2) False >>> between_4_and_10(9.9) True >>> between_4_and_10(19.7) False Other supported operators are ``|`` (logical or) and ``~`` (logical not): .. code-block:: python smaller_equal_than_4 = ~bigger_than_4 smaller_than_10_or_int = smaller_than_10 | is_int .. warning:: Note that Python conditional expressions are evaluated from left to right. As a result, the order of composition may matter, even though logical operators such as ``|`` and ``&`` are symmetric. For example: >>> is_int = qml.BooleanFn(lambda x: isinstance(x, int)) >>> has_bit_length_3 = qml.BooleanFn(lambda x: x.bit_length()==3) >>> (is_int & has_bit_length_3)(4) True >>> (is_int & has_bit_length_3)(2.3) False >>> (has_bit_length_3 & is_int)(2.3) AttributeError: 'float' object has no attribute 'bit_length' """ def __init__(self, fn, name=None): self.fn = fn self.name = name or self.fn.__name__ functools.update_wrapper(self, fn) def __and__(self, other): return And(self, other) def __or__(self, other): return Or(self, other) def __xor__(self, other): return Xor(self, other) def __invert__(self): return Not(self) def __call__(self, *args, **kwargs): return self.fn(*args, **kwargs) def __repr__(self): return f"BooleanFn({self.name})" if not (self.bitwise or self.conditional) else self.name @property def bitwise(self): """Determine whether the wrapped callable performs a bitwise operation or not. This checks for the ``operands`` attribute that should be defined by it.""" return bool(getattr(self, "operands", tuple())) @property def conditional(self): """Determine whether the wrapped callable is for a conditional or not. This checks for the ``condition`` attribute that should be defined by it.""" return bool(getattr(self, "condition", None)) class And(BooleanFn): """Developer facing class for implemeting bitwise ``AND`` for callables wrapped up with :class:`BooleanFn <pennylane.BooleanFn>`. Args: left (~.BooleanFn): Left operand in the bitwise expression. right (~.BooleanFn): Right operand in the bitwise expression. """ def __init__(self, left, right): self.operands = (left, right) if any(getattr(opr, "condition", None) for opr in self.operands): self.condition = tuple(getattr(opr, "condition", ()) for opr in self.operands) super().__init__( lambda *args, **kwargs: left(*args, **kwargs) and right(*args, **kwargs), f"And({left.name}, {right.name})", ) def __str__(self): return f"{self.operands[0].name} & {self.operands[1].name}" class Or(BooleanFn): """Developer facing class for implemeting bitwise ``OR`` for callables wrapped up with :class:`BooleanFn <pennylane.BooleanFn>`. Args: left (~.BooleanFn): Left operand in the bitwise expression. right (~.BooleanFn): Right operand in the bitwise expression. """ def __init__(self, left, right): self.operands = (left, right) if any(getattr(opr, "condition", None) for opr in self.operands): self.condition = tuple(getattr(opr, "condition", ()) for opr in self.operands) super().__init__( lambda *args, **kwargs: left(*args, **kwargs) or right(*args, **kwargs), f"Or({left.name}, {right.name})", ) def __str__(self): return f"{self.operands[0].name} | {self.operands[1].name}" class Xor(BooleanFn): """Developer facing class for implemeting bitwise ``XOR`` for callables wrapped up with :class:`BooleanFn <pennylane.BooleanFn>`. Args: left (~.BooleanFn): Left operand in the bitwise expression. right (~.BooleanFn): Right operand in the bitwise expression. """ def __init__(self, left, right): self.operands = (left, right) if any(getattr(opr, "condition", None) for opr in self.operands): self.condition = tuple(getattr(opr, "condition", ()) for opr in self.operands) super().__init__( lambda *args, **kwargs: left(*args, **kwargs) ^ right(*args, **kwargs), f"Xor({left.name}, {right.name})", ) def __str__(self): return f"{self.operands[0].name} ^ {self.operands[1].name}" class Not(BooleanFn): """Developer facing class for implemeting bitwise ``NOT`` for callables wrapped up with :class:`BooleanFn <pennylane.BooleanFn>`. Args: left (~.BooleanFn): Left operand in the bitwise expression. """ def __init__(self, left): self.operands = (left,) if any(getattr(opr, "condition", None) for opr in self.operands): self.condition = tuple(getattr(opr, "condition", ()) for opr in self.operands) super().__init__( lambda *args, **kwargs: not left(*args, **kwargs), f"Not({left.name})", ) def __str__(self): return f"~{self.operands[0].name}"
pennylane/pennylane/boolean_fn.py/0
{ "file_path": "pennylane/pennylane/boolean_fn.py", "repo_id": "pennylane", "token_count": 2764 }
42
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # 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. """Contains DatasetAttribute definitions.""" from .array import DatasetArray from .dictionary import DatasetDict from .json import DatasetJSON from .list import DatasetList from .molecule import DatasetMolecule from .none import DatasetNone from .operator import DatasetOperator from .scalar import DatasetScalar from .sparse_array import DatasetSparseArray from .string import DatasetString from .tuple import DatasetTuple from .pytree import DatasetPyTree __all__ = ( "DatasetArray", "DatasetScalar", "DatasetString", "DatasetDict", "DatasetList", "DatasetOperator", "DatasetPyTree", "DatasetSparseArray", "DatasetMolecule", "DatasetNone", "DatasetJSON", "DatasetTuple", )
pennylane/pennylane/data/attributes/__init__.py/0
{ "file_path": "pennylane/pennylane/data/attributes/__init__.py", "repo_id": "pennylane", "token_count": 432 }
43
"""Contains a lazy-loaded interface to the HDF5 module. For internal use only.""" import importlib from collections.abc import Callable from types import ModuleType from typing import Any, Optional, Union _MISSING_MODULES_EXC = ImportError( "This feature requires the 'aiohttp', 'h5py' and 'fsspec' packages. " "They can be installed with:\n\n pip install aiohttp fsspec h5py" ) class lazy_module: # pylint: disable=too-few-public-methods """Provides a lazy-loaded interface to a Python module, and its submodules. The module will not be imported until an attribute is accessed.""" def __init__( self, module_name_or_module: Union[str, ModuleType], import_exc: Optional[Exception] = None, post_import_cb: Optional[Callable[[ModuleType], None]] = None, ): """Creates a new top-level lazy module or initializes a nested one. Args: module_name_or_module: Name of module to lazily import, or a module object for a nested lazy module. import_exc: Custom Exception to raise when an ``ImportError`` occurs. Will only be used by the top-level ``lazy_module`` instance, not nested modules """ if isinstance(module_name_or_module, ModuleType): # pragma: no cover self.__module = module_name_or_module self.__module_name = self.__module.__name__ else: self.__module = None self.__module_name = module_name_or_module self.__import_exc = import_exc self.__post_import_cb = post_import_cb self.__submods = {} def __getattr__(self, __name: str) -> Any: if self.__module is None: self.__import_module() elif __name in self.__submods: return self.__submods[__name] # pragma: no cover try: resource = getattr(self.__module, __name) except AttributeError as attr_exc: # pragma: no cover try: submod = lazy_module(importlib.import_module(f"{self.__module_name}.{__name}")) except ImportError as import_exc: raise attr_exc from import_exc self.__submods[__name] = submod return submod return resource def __import_module(self) -> None: try: self.__module = importlib.import_module(self.__module_name) except ImportError as exc: # pragma: no cover if self.__import_exc: raise self.__import_exc from exc raise exc if self.__post_import_cb: self.__post_import_cb(self.__module) def _configure_h5py(h5py_module: ModuleType) -> None: """Configures the ``h5py`` module after import. Sets the ``track_order`` flag, so that groups and files remember the insert order of objects, like Python dictionaries. See https://docs.h5py.org/en/stable/config.html """ h5py_module.get_config().track_order = True h5py = lazy_module("h5py", _MISSING_MODULES_EXC, _configure_h5py) fsspec = lazy_module("fsspec", _MISSING_MODULES_EXC)
pennylane/pennylane/data/base/_lazy_modules.py/0
{ "file_path": "pennylane/pennylane/data/base/_lazy_modules.py", "repo_id": "pennylane", "token_count": 1306 }
44
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # 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. """ This subpackage provides default devices for PennyLane, which do not need external plugins to be installed. The default devices provide basic built-in qubit and CV circuit simulators that can be used with PennyLane without the need for additional dependencies. They may also be used in the PennyLane test suite in order to verify and test quantum gradient computations. .. currentmodule:: pennylane.devices .. autosummary:: :toctree: api default_qubit default_qubit_legacy default_qubit_jax default_qubit_torch default_qubit_tf default_qubit_autograd default_gaussian default_mixed default_qutrit default_qutrit_mixed default_clifford default_tensor _legacy_device _qubit_device _qutrit_device null_qubit tests Next generation devices ----------------------- :class:`pennylane.devices.Device` is the latest interface for the next generation of devices that replaces :class:`pennylane.Device` and :class:`pennylane.QubitDevice`. While the previous interface :class:`pennylane.Device` is imported top level, the new :class:`pennylane.devices.Device` is accessible from the ``pennylane.devices`` submodule. .. currentmodule:: pennylane.devices .. autosummary:: :toctree: api ExecutionConfig MCMConfig Device DefaultQubit DefaultTensor NullQubit DefaultQutritMixed LegacyDeviceFacade Preprocessing Transforms ------------------------ The ``preprocess`` module offers several transforms that can be used in constructing the :meth:`~.devices.Device.preprocess` method for devices. .. currentmodule:: pennylane.devices.preprocess .. autosummary:: :toctree: api decompose validate_observables validate_measurements validate_device_wires validate_multiprocessing_workers validate_adjoint_trainable_params no_sampling Other transforms that may be relevant to device preprocessing include: .. currentmodule:: pennylane .. autosummary:: :toctree: api defer_measurements transforms.broadcast_expand transforms.sum_expand transforms.split_non_commuting transforms.hamiltonian_expand Modifiers --------- The ``modifiers`` allow for the easy addition of default behaviour to a device. .. currentmodule:: pennylane.devices.modifiers .. autosummary:: :toctree: api single_tape_support simulator_tracking For example with a custom device we can add simulator-style tracking and the ability to handle a single circuit. See the documentation for each modifier for more details. .. code-block:: python @simulator_tracking @single_tape_support class MyDevice(qml.devices.Device): def execute(self, circuits, execution_config = qml.devices.DefaultExecutionConfig): return tuple(0.0 for _ in circuits) >>> dev = MyDevice() >>> tape = qml.tape.QuantumTape([qml.S(0)], [qml.expval(qml.X(0))]) >>> with dev.tracker: ... out = dev.execute(tape) >>> out 0.0 >>> dev.tracker.history {'batches': [1], 'simulations': [1], 'executions': [1], 'results': [0.0], 'resources': [Resources(num_wires=1, num_gates=1, gate_types=defaultdict(<class 'int'>, {'S': 1}), gate_sizes=defaultdict(<class 'int'>, {1: 1}), depth=1, shots=Shots(total_shots=None, shot_vector=()))]} Qubit Simulation Tools ---------------------- .. currentmodule:: pennylane.devices.qubit .. automodule:: pennylane.devices.qubit Qutrit Mixed-State Simulation Tools ----------------------------------- .. currentmodule:: pennylane.devices.qutrit_mixed .. automodule:: pennylane.devices.qutrit_mixed """ from .execution_config import ExecutionConfig, DefaultExecutionConfig, MCMConfig from .device_constructor import device, refresh_devices from .device_api import Device from .default_qubit import DefaultQubit from .legacy_facade import LegacyDeviceFacade # DefaultQubitTF and DefaultQubitAutograd not imported here since this # would lead to an automatic import of tensorflow and autograd, which are # not PennyLane core dependencies. # DefaultTensor is not imported here to avoid warnings # from quimb in case it is installed on the system. from .default_qubit_legacy import DefaultQubitLegacy from .default_gaussian import DefaultGaussian from .default_mixed import DefaultMixed from .default_clifford import DefaultClifford from .default_tensor import DefaultTensor from .null_qubit import NullQubit from .default_qutrit import DefaultQutrit from .default_qutrit_mixed import DefaultQutritMixed from ._legacy_device import Device as LegacyDevice from ._qubit_device import QubitDevice from ._qutrit_device import QutritDevice # pylint: disable=undefined-variable def __getattr__(name): if name == "plugin_devices": return device_constructor.plugin_devices raise AttributeError(f"module 'pennylane.devices' has no attribute '{name}'")
pennylane/pennylane/devices/__init__.py/0
{ "file_path": "pennylane/pennylane/devices/__init__.py", "repo_id": "pennylane", "token_count": 1720 }
45
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # 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. """ This module contains the Abstract Base Class for the next generation of devices. """ # pylint: disable=comparison-with-callable import abc from collections.abc import Iterable from dataclasses import replace from numbers import Number from typing import Optional, Union from pennylane import Tracker from pennylane.measurements import Shots from pennylane.tape import QuantumScript, QuantumScriptOrBatch from pennylane.transforms.core import TransformProgram from pennylane.typing import Result, ResultBatch from pennylane.wires import Wires from .execution_config import DefaultExecutionConfig, ExecutionConfig # pylint: disable=unused-argument, no-self-use class Device(abc.ABC): """A device driver that can control one or more backends. A backend can be either a physical Quantum Processing Unit or a virtual one such as a simulator. Only the ``execute`` method must be defined to construct a device driver. .. details:: :title: Design Motivation **Streamlined interface:** Only methods that are required to interact with the rest of PennyLane will be placed in the interface. Developers will be able to clearly see what they can change while still having a fully functional device. **Reduction of duplicate methods:** Methods that solve similar problems are combined together. Only one place will have to solve each individual problem. **Support for dynamic execution configurations:** Properties such as shots belong to specific executions. **Greater coverage for differentiation methods:** Devices can define any order of derivative, the vector jacobian product, or the jacobian vector product. Calculation of derivatives can be done at the same time as execution to allow reuse of intermediate results. .. details:: :title: Porting from the old interface :meth:`pennylane.Device.batch_execute` and :meth:`~pennylane.Device.execute` are now a single method, :meth:`~.Device.execute` :meth:`~.Device.batch_transform` and :meth:`~.Device.expand_fn` are now a single method, :meth:`~.Device.preprocess` Shot information is no longer stored on the device, but instead specified on individual input :class:`~.QuantumTape`. The old devices defined a :meth:`~.Device.capabilities` dictionary that defined characteristics of the devices and controlled various preprocessing and validation steps, such as ``"supports_broadcasting"``. These capabilites should now be handled by the :meth:`~.Device.preprocess` method. For example, if a device does not support broadcasting, ``preprocess`` should split a quantum script with broadcasted parameters into a batch of quantum scripts. If the device does not support mid circuit measurements, then ``preprocess`` should apply :func:`~.defer_measurements`. A set of default preprocessing steps will be available to make a seamless transition to the new interface. A class will be provided to easily construct default preprocessing steps from supported operations, supported observables, supported measurement processes, and various capabilities. Utility functions will be added to the ``devices`` module to query whether or not the device driver can do certain things, such as ``devices.supports_operator(op, dev, native=True)``. These functions will work by checking the behaviour of :meth:`~.Device.preprocess` to certain inputs. Versioning should be specified by the package containing the device. If an external package includes a PennyLane device, then the package requirements should specify the minimium PennyLane version required to work with the device. .. details:: :title: The relationship between preprocessing and execution The :meth:`~.preprocess` method is assumed to be run before any :meth:`~.execute` or differentiation method. If an arbitrary, non-preprocessed circuit is provided, :meth:`~.execute` has no responsibility to perform any validation or provide clearer error messages. >>> op = qml.Permute(["c", 3,"a",2,0], wires=[3,2,"a",0,"c"]) >>> circuit = qml.tape.QuantumScript([op], [qml.state()]) >>> dev = DefaultQubit() >>> dev.execute(circuit) MatrixUndefinedError >>> circuit = qml.tape.QuantumScript([qml.Rot(1.2, 2.3, 3.4, 0)], [qml.expval(qml.Z(0))]) >>> config = ExecutionConfig(gradient_method="adjoint") >>> dev.compute_derivatives(circuit, config) ValueError: Operation Rot is not written in terms of a single parameter >>> new_circuit, postprocessing, new_config = dev.preprocess(circuit, config) >>> dev.compute_derivatives(new_circuit, new_config) ((array(0.), array(-0.74570521), array(0.)),) Any validation checks or error messages should occur in :meth:`~.preprocess` to avoid failures after expending computation resources. .. details:: :title: Execution Configuration Execution config properties related to configuring a device include: * ``device_options``: A dictionary of device specific options. For example, the python device may have ``multiprocessing_mode`` as a key. These should be documented in the class docstring. * ``gradient_method``: A device can choose to have native support for any type of gradient method. If the method :meth:`~.supports_derivatives` returns ``True`` for a particular gradient method, it will be treated as a device derivative and not handled by pennylane core code. * ``gradient_keyword_arguments``: Options for the gradient method. * ``derivative_order``: Relevant for requested device derivatives. """ @property def name(self) -> str: """The name of the device or set of devices. This property can either be the name of the class, or an alias to be used in the :func:`~.device` constructor, such as ``"default.qubit"`` or ``"lightning.qubit"``. """ return type(self).__name__ tracker: Tracker = Tracker() """A :class:`~.Tracker` that can store information about device executions, shots, batches, intermediate results, or any additional device dependent information. A plugin developer can store information in the tracker by: .. code-block:: python # querying if the tracker is active if self.tracker.active: # store any keyword: value pairs of information self.tracker.update(executions=1, shots=self._shots, results=results) # Calling a user-provided callback function self.tracker.record() """ def __init__(self, wires=None, shots=None) -> None: # each instance should have its own Tracker. self.tracker = Tracker() self._shots = Shots(shots) if wires is not None: if not isinstance(wires, Iterable): # interpret wires as the number of consecutive wires wires = range(wires) wires = Wires(wires) self._wires = wires def __repr__(self): """String representation.""" details = [] if self.wires: details.append(f"wires={len(self.wires)}") if self.shots: details.append(f"shots={self.shots.total_shots}") details = f"({', '.join(details)}) " if details else "" return f"<{self.name} device {details}at {hex(id(self))}>" def __getattr__(self, key): raise AttributeError( f"{type(self).__name__} has no attribute '{key}'." " You may be looking for a property or method present in the legacy device interface." f" Please consult the {type(self).__name__} documentation for an updated list of public" " properties and methods." ) @property def shots(self) -> Shots: """Default shots for execution workflows containing this device. Note that the device itself should **always** pull shots from the provided :class:`~.QuantumTape` and its :attr:`~.QuantumTape.shots`, not from this property. This property is used to provide a default at the start of a workflow. """ return self._shots @shots.setter def shots(self, _): raise AttributeError( ( "Shots can no longer be set on a device instance. " "You can set shots on a call to a QNode, on individual tapes, or " "create a new device instance instead." ) ) @property def wires(self) -> Wires: """The device wires. Note that wires are optional, and the default value of None means any wires can be used. If a device has wires defined, they will only be used for certain features. This includes: * Validation of tapes being executed on the device * Defining the wires used when evaluating a :func:`~pennylane.state` measurement """ return self._wires def preprocess( self, execution_config: ExecutionConfig = DefaultExecutionConfig, ) -> tuple[TransformProgram, ExecutionConfig]: """Device preprocessing function. .. warning:: This function is tracked by machine learning interfaces and should be fully differentiable. The ``pennylane.math`` module can be used to construct fully differentiable transformations. Additional preprocessing independent of machine learning interfaces can be done inside of the :meth:`~.execute` method. Args: execution_config (ExecutionConfig): A datastructure describing the parameters needed to fully describe the execution. Returns: TransformProgram, ExecutionConfig: A transform program that is called before execution, and a configuration with unset specifications filled in. Raises: Exception: An exception can be raised if the input cannot be converted into a form supported by the device. Preprocessing program may include: * expansion to :class:`~.Operator`'s and :class:`~.MeasurementProcess` objects supported by the device. * splitting a circuit with the measurement of non-commuting observables or Hamiltonians into multiple executions * splitting circuits with batched parameters into multiple executions * gradient specific preprocessing, such as making sure trainable operators have generators * validation of configuration parameters * choosing a best gradient method and ``grad_on_execution`` value. **Example** All the transforms that are part of the preprocessing need to respect the transform contract defined in :func:`pennylane.transform`. .. code-block:: python from pennylane.tape import TapeBatch from pennylane.typing import PostprocessingFn @transform def my_preprocessing_transform(tape: qml.tape.QuantumScript) -> tuple[QuantumScriptBatch, PostprocessingFn]: # e.g. valid the measurements, expand the tape for the hardware execution, ... def blank_processing_fn(results): return results[0] return [tape], processing_fn Then we can define the preprocess method on the custom device. The program can accept an arbitrary number of transforms. .. code-block:: python def preprocess(config): program = TransformProgram() program.add_transform(my_preprocessing_transform) return program, config .. seealso:: :func:`~.pennylane.transform.core.transform` and :class:`~.pennylane.transform.core.TransformProgram` .. details:: :title: Post processing function and derivatives Derivatives and jacobian products will be bound to the machine learning library before the postprocessing function is called on results. Therefore the machine learning library will be responsible for combining the device provided derivatives and post processing derivatives. .. code-block:: python from pennylane.interfaces.jax import execute as jax_boundary def f(x): circuit = qml.tape.QuantumScript([qml.Rot(*x, wires=0)], [qml.expval(qml.Z(0))]) config = ExecutionConfig(gradient_method="adjoint") program, config = dev.preprocess(config) circuit_batch, postprocessing = program((circuit, )) def execute_fn(tapes): return dev.execute_and_compute_derivatives(tapes, config) results = jax_boundary(circuit_batch, dev, execute_fn, None, {}) return postprocessing(results) x = jax.numpy.array([1.0, 2.0, 3.0]) jax.grad(f)(x) In the above code, the quantum derivatives are registered with jax in the ``jax_boundary`` function. Only then is the classical postprocessing called on the result object. """ if self.supports_derivatives(execution_config) and execution_config.gradient_method in { "best", None, }: return TransformProgram(), replace(execution_config, gradient_method="device") return TransformProgram(), execution_config @abc.abstractmethod def execute( self, circuits: QuantumScriptOrBatch, execution_config: ExecutionConfig = DefaultExecutionConfig, ) -> Union[Result, ResultBatch]: """Execute a circuit or a batch of circuits and turn it into results. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): the quantum circuits to be executed execution_config (ExecutionConfig): a datastructure with additional information required for execution Returns: TensorLike, tuple[TensorLike], tuple[tuple[TensorLike]]: A numeric result of the computation. **Interface parameters:** The provided ``circuits`` may contain interface specific data-types like ``torch.Tensor`` or ``jax.Array`` when :attr:`~.ExecutionConfig.gradient_method` of ``"backprop"`` is requested. If the gradient method is not backpropagation, then only vanilla numpy parameters or builtins will be present in the circuits. .. details:: :title: Return Shape See :ref:`Return Type Specification <ReturnTypeSpec>` for more detailed information. The result for each :class:`~.QuantumTape` must match the shape specified by :class:`~.QuantumTape.shape`. The level of priority for dimensions from outer dimension to inner dimension is: 1. Quantum Script in batch 2. Shot choice in a shot vector 3. Measurement in the quantum script 4. Parameter broadcasting 5. Measurement shape for array-valued measurements like probabilities For a batch of quantum scripts with multiple measurements, a shot vector, and parameter broadcasting: * ``result[0]``: the results for the first script * ``result[0][0]``: the first shot number in the shot vector * ``result[0][0][0]``: the first measurement in the quantum script * ``result[0][0][0][0]``: the first parameter broadcasting choice * ``result[0][0][0][0][0]``: the first value for an array-valued measurement With the exception of quantum script batches, dimensions with only a single component should be eliminated. For example: With a single script and a single measurement process, execute should return just the measurement value in a numpy array. ``shape`` currently accepts a device, as historically devices stored shot information. In the future, this method will accept an ``ExecutionConfig`` instead. >>> tape = qml.tape.QuantumTape(measurements=qml.expval(qml.Z(0))]) >>> tape.shape(dev) () >>> dev.execute(tape) array(1.0) If execute recieves a batch of scripts, then it should return a tuple of results: >>> dev.execute([tape, tape]) (array(1.0), array(1.0)) >>> dev.execute([tape]) (array(1.0),) If the script has multiple measurments, then the device should return a tuple of measurements. >>> tape = qml.tape.QuantumTape(measurements=[qml.expval(qml.Z(0)), qml.probs(wires=(0,1))]) >>> tape.shape(dev) ((), (4,)) >>> dev.execute(tape) (array(1.0), array([1., 0., 0., 0.])) """ raise NotImplementedError def supports_derivatives( self, execution_config: Optional[ExecutionConfig] = None, circuit: Optional[QuantumScript] = None, ) -> bool: """Determine whether or not a device provided derivative is potentially available. Default behaviour assumes first order device derivatives for all circuits exist if :meth:`~.compute_derivatives` is overriden. Args: execution_config (ExecutionConfig): A description of the hyperparameters for the desired computation. circuit (None, QuantumTape): A specific circuit to check differentation for. Returns: Bool The device can support multiple different types of "device derivatives", chosen via ``execution_config.gradient_method``. For example, a device can natively calculate ``"parameter-shift"`` derivatives, in which case :meth:`~.compute_derivatives` will be called for the derivative instead of :meth:`~.execute` with a batch of circuits. >>> config = ExecutionConfig(gradient_method="parameter-shift") >>> custom_device.supports_derivatives(config) True In this case, :meth:`~.compute_derivatives` or :meth:`~.execute_and_compute_derivatives` will be called instead of :meth:`~.execute` with a batch of circuits. If ``circuit`` is not provided, then the method should return whether or not device derivatives exist for **any** circuit. **Example:** For example, the Python device will support device differentiation via the adjoint differentiation algorithm if the order is ``1`` and the execution occurs with no shots (``shots=None``). >>> config = ExecutionConfig(derivative_order=1, gradient_method="adjoint") >>> dev.supports_derivatives(config) True >>> circuit_analytic = qml.tape.QuantumScript([qml.RX(0.1, wires=0)], [qml.expval(qml.Z(0))], shots=None) >>> dev.supports_derivatives(config, circuit=circuit_analytic) True >>> circuit_finite_shots = qml.tape.QuantumScript([qml.RX(0.1, wires=0)], [qml.expval(qml.Z(0))], shots=10) >>> dev.supports_derivatives(config, circuit = circuit_fintite_shots) False >>> config = ExecutionConfig(derivative_order=2, gradient_method="adjoint") >>> dev.supports_derivatives(config) False Adjoint differentiation will only be supported for circuits with expectation value measurements. If a circuit is provided and it cannot be converted to a form supported by differentiation method by :meth:`~.Device.preprocess`, then ``supports_derivatives`` should return False. >>> config = ExecutionConfig(derivative_order=1, shots=None, gradient_method="adjoint") >>> circuit = qml.tape.QuantumScript([qml.RX(2.0, wires=0)], [qml.probs(wires=(0,1))]) >>> dev.supports_derivatives(config, circuit=circuit) False If the circuit is not natively supported by the differentiation method but can be converted into a form that is supported, it should still return ``True``. For example, :class:`~.Rot` gates are not natively supported by adjoint differentation, as they do not have a generator, but they can be compiled into operations supported by adjoint differentiation. Therefore this method may reproduce compilation and validation steps performed by :meth:`~.Device.preprocess`. >>> config = ExecutionConfig(derivative_order=1, shots=None, gradient_method="adjoint") >>> circuit = qml.tape.QuantumScript([qml.Rot(1.2, 2.3, 3.4, wires=0)], [qml.expval(qml.Z(0))]) >>> dev.supports_derivatives(config, circuit=circuit) True **Backpropagation:** This method is also used be to validate support for backpropagation derivatives. Backpropagation is only supported if the device is transparent to the machine learning framework from start to finish. >>> config = ExecutionConfig(gradient_method="backprop") >>> python_device.supports_derivatives(config) True >>> cpp_device.supports_derivatives(config) False """ if execution_config is None: return type(self).compute_derivatives != Device.compute_derivatives if ( execution_config.gradient_method not in {"device", "best"} or execution_config.derivative_order != 1 ): return False return type(self).compute_derivatives != Device.compute_derivatives def compute_derivatives( self, circuits: QuantumScriptOrBatch, execution_config: ExecutionConfig = DefaultExecutionConfig, ): """Calculate the jacobian of either a single or a batch of circuits on the device. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): the circuits to calculate derivatives for execution_config (ExecutionConfig): a datastructure with all additional information required for execution Returns: Tuple: The jacobian for each trainable parameter .. seealso:: :meth:`~.supports_derivatives` and :meth:`~.execute_and_compute_derivatives`. **Execution Config:** The execution config has ``gradient_method`` and ``order`` property that describes the order of differentiation requested. If the requested method or order of gradient is not provided, the device should raise a ``NotImplementedError``. The :meth:`~.supports_derivatives` method can pre-validate supported orders and gradient methods. **Return Shape:** If a batch of quantum scripts is provided, this method should return a tuple with each entry being the gradient of each individual quantum script. If the batch is of length 1, then the return tuple should still be of length 1, not squeezed. """ raise NotImplementedError(f"{self.name} does not support differentiable workflows.") def execute_and_compute_derivatives( self, circuits: QuantumScriptOrBatch, execution_config: ExecutionConfig = DefaultExecutionConfig, ): """Compute the results and jacobians of circuits at the same time. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): the circuits or batch of circuits execution_config (ExecutionConfig): a datastructure with all additional information required for execution Returns: tuple: A numeric result of the computation and the gradient. See :meth:`~.execute` and :meth:`~.compute_derivatives` for more information about return shapes and behaviour. If :meth:`~.compute_derivatives` is defined, this method should be as well. This method can be used when the result and execution need to be computed at the same time, such as during a forward mode calculation of gradients. For certain gradient methods, such as adjoint diff gradients, calculating the result and gradient at the same can save computational work. """ return self.execute(circuits, execution_config), self.compute_derivatives( circuits, execution_config ) def compute_jvp( self, circuits: QuantumScriptOrBatch, tangents: tuple[Number, ...], execution_config: ExecutionConfig = DefaultExecutionConfig, ): r"""The jacobian vector product used in forward mode calculation of derivatives. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): the circuit or batch of circuits tangents (tensor-like): Gradient vector for input parameters. execution_config (ExecutionConfig): a datastructure with all additional information required for execution Returns: Tuple: A numeric result of computing the jacobian vector product **Definition of jvp:** If we have a function with jacobian: .. math:: \vec{y} = f(\vec{x}) \qquad J_{i,j} = \frac{\partial y_i}{\partial x_j} The Jacobian vector product is the inner product with the derivatives of :math:`x`, yielding only the derivatives of the output :math:`y`: .. math:: \text{d}y_i = \Sigma_{j} J_{i,j} \text{d}x_j **Shape of tangents:** The ``tangents`` tuple should be the same length as ``circuit.get_parameters()`` and have a single number per parameter. If a number is zero, then the gradient with respect to that parameter does not need to be computed. """ raise NotImplementedError def execute_and_compute_jvp( self, circuits: QuantumScriptOrBatch, tangents: tuple[Number, ...], execution_config: ExecutionConfig = DefaultExecutionConfig, ): """Execute a batch of circuits and compute their jacobian vector products. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): circuit or batch of circuits tangents (tensor-like): Gradient vector for input parameters. execution_config (ExecutionConfig): a datastructure with all additional information required for execution Returns: Tuple, Tuple: A numeric result of execution and of computing the jacobian vector product .. seealso:: :meth:`~pennylane.devices.Device.execute` and :meth:`~.Device.compute_jvp` """ return self.execute(circuits, execution_config), self.compute_jvp( circuits, tangents, execution_config ) def supports_jvp( self, execution_config: Optional[ExecutionConfig] = None, circuit: Optional[QuantumScript] = None, ) -> bool: """Whether or not a given device defines a custom jacobian vector product. Args: execution_config (ExecutionConfig): A description of the hyperparameters for the desired computation. circuit (None, QuantumTape): A specific circuit to check differentation for. Default behaviour assumes this to be ``True`` if :meth:`~.compute_jvp` is overridden. """ return type(self).compute_jvp != Device.compute_jvp def compute_vjp( self, circuits: QuantumScriptOrBatch, cotangents: tuple[Number, ...], execution_config: ExecutionConfig = DefaultExecutionConfig, ): r"""The vector jacobian product used in reverse-mode differentiation. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): the circuit or batch of circuits cotangents (Tuple[Number, Tuple[Number]]): Gradient-output vector. Must have shape matching the output shape of the corresponding circuit. If the circuit has a single output, `cotangents` may be a single number, not an iterable of numbers. execution_config (ExecutionConfig): a datastructure with all additional information required for execution Returns: tensor-like: A numeric result of computing the vector jacobian product **Definition of vjp:** If we have a function with jacobian: .. math:: \vec{y} = f(\vec{x}) \qquad J_{i,j} = \frac{\partial y_i}{\partial x_j} The vector jacobian product is the inner product of the derivatives of the output ``y`` with the Jacobian matrix. The derivatives of the output vector are sometimes called the **cotangents**. .. math:: \text{d}x_i = \Sigma_{i} \text{d}y_i J_{i,j} **Shape of cotangents:** The value provided to ``cotangents`` should match the output of :meth:`~.execute`. """ raise NotImplementedError def execute_and_compute_vjp( self, circuits: QuantumScriptOrBatch, cotangents: tuple[Number, ...], execution_config: ExecutionConfig = DefaultExecutionConfig, ): r"""Calculate both the results and the vector jacobian product used in reverse-mode differentiation. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): the circuit or batch of circuits to be executed cotangents (Tuple[Number, Tuple[Number]]): Gradient-output vector. Must have shape matching the output shape of the corresponding circuit. If the circuit has a single output, `cotangents` may be a single number, not an iterable of numbers. execution_config (ExecutionConfig): a datastructure with all additional information required for execution Returns: Tuple, Tuple: the result of executing the scripts and the numeric result of computing the vector jacobian product .. seealso:: :meth:`~pennylane.devices.Device.execute` and :meth:`~.Device.compute_vjp` """ return self.execute(circuits, execution_config), self.compute_vjp( circuits, cotangents, execution_config ) def supports_vjp( self, execution_config: Optional[ExecutionConfig] = None, circuit: Optional[QuantumScript] = None, ) -> bool: """Whether or not a given device defines a custom vector jacobian product. Args: execution_config (ExecutionConfig): A description of the hyperparameters for the desired computation. circuit (None, QuantumTape): A specific circuit to check differentation for. Default behaviour assumes this to be ``True`` if :meth:`~.compute_vjp` is overridden. """ return type(self).compute_vjp != Device.compute_vjp
pennylane/pennylane/devices/device_api.py/0
{ "file_path": "pennylane/pennylane/devices/device_api.py", "repo_id": "pennylane", "token_count": 11303 }
46
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # 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. """Simulate a quantum script.""" import logging # pylint: disable=protected-access from collections import Counter from functools import partial, singledispatch from typing import Optional import numpy as np from numpy.random import default_rng import pennylane as qml from pennylane.logging import debug_logger from pennylane.measurements import ( CountsMP, ExpectationMP, MidMeasureMP, ProbabilityMP, SampleMP, VarianceMP, find_post_processed_mcms, ) from pennylane.transforms.dynamic_one_shot import gather_mcm from pennylane.typing import Result from .apply_operation import apply_operation from .initialize_state import create_initial_state from .measure import measure from .sampling import jax_random_split, measure_with_samples logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) INTERFACE_TO_LIKE = { # map interfaces known by autoray to themselves None: None, "numpy": "numpy", "autograd": "autograd", "jax": "jax", "torch": "torch", "tensorflow": "tensorflow", # map non-standard interfaces to those known by autoray "auto": None, "scipy": "numpy", "jax-jit": "jax", "jax-python": "jax", "JAX": "jax", "pytorch": "torch", "tf": "tensorflow", "tensorflow-autograph": "tensorflow", "tf-autograph": "tensorflow", } class TreeTraversalStack: """This class is used to record various data used during the depth-first tree-traversal procedure for simulating dynamic circuits.""" counts: list probs: list results_0: list results_1: list states: list def __init__(self, max_depth): self.counts = [None] * max_depth self.probs = [None] * max_depth self.results_0 = [None] * max_depth self.results_1 = [None] * max_depth self.states = [None] * max_depth def any_is_empty(self, depth): """Return True if any result at ``depth`` is ``None`` and False otherwise.""" return self.results_0[depth] is None or self.results_1[depth] is None def is_full(self, depth): """Return True if the results at ``depth`` are both not ``None`` and False otherwise.""" return self.results_0[depth] is not None and self.results_1[depth] is not None def prune(self, depth): """Reset all stack entries at ``depth`` to ``None``.""" self.counts[depth] = None self.probs[depth] = None self.results_0[depth] = None self.results_1[depth] = None self.states[depth] = None class _FlexShots(qml.measurements.Shots): """Shots class that allows zero shots.""" # pylint: disable=super-init-not-called def __init__(self, shots=None): if isinstance(shots, int): self.total_shots = shots self.shot_vector = (qml.measurements.ShotCopies(shots, 1),) elif isinstance(shots, self.__class__): return # self already _is_ shots as defined by __new__ else: self.__all_tuple_init__([s if isinstance(s, tuple) else (s, 1) for s in shots]) self._frozen = True def _postselection_postprocess(state, is_state_batched, shots, **execution_kwargs): """Update state after projector is applied.""" if is_state_batched: raise ValueError( "Cannot postselect on circuits with broadcasting. Use the " "qml.transforms.broadcast_expand transform to split a broadcasted " "tape into multiple non-broadcasted tapes before executing if " "postselection is used." ) rng = execution_kwargs.get("rng", None) prng_key = execution_kwargs.get("prng_key", None) postselect_mode = execution_kwargs.get("postselect_mode", None) # The floor function is being used here so that a norm very close to zero becomes exactly # equal to zero so that the state can become invalid. This way, execution can continue, and # bad postselection gives results that are invalid rather than results that look valid but # are incorrect. norm = qml.math.norm(state) if not qml.math.is_abstract(state) and qml.math.allclose(norm, 0.0): norm = 0.0 if shots: # Clip the number of shots using a binomial distribution using the probability of # measuring the postselected state. if prng_key is not None: # pylint: disable=import-outside-toplevel from jax.random import binomial binomial_fn = partial(binomial, prng_key) else: binomial_fn = np.random.binomial if rng is None else rng.binomial postselected_shots = ( shots if postselect_mode == "fill-shots" or qml.math.is_abstract(norm) else [int(binomial_fn(s, float(norm**2))) for s in shots] ) # _FlexShots is used here since the binomial distribution could result in zero # valid samples shots = _FlexShots(postselected_shots) state = state / norm return state, shots @debug_logger def get_final_state(circuit, debugger=None, **execution_kwargs): """ Get the final state that results from executing the given quantum script. This is an internal function that will be called by the successor to ``default.qubit``. Args: circuit (.QuantumScript): The single circuit to simulate. This circuit is assumed to have non-negative integer wire labels debugger (._Debugger): The debugger to use interface (str): The machine learning interface to create the initial state with mid_measurements (None, dict): Dictionary of mid-circuit measurements rng (Optional[numpy.random._generator.Generator]): A NumPy random number generator. prng_key (Optional[jax.random.PRNGKey]): An optional ``jax.random.PRNGKey``. This is the key to the JAX pseudo random number generator. Only for simulation using JAX. If None, a ``numpy.random.default_rng`` will be used for sampling. postselect_mode (str): Configuration for handling shots with mid-circuit measurement postselection. Use ``"hw-like"`` to discard invalid shots and ``"fill-shots"`` to keep the same number of shots. Default is ``None``. Returns: Tuple[TensorLike, bool]: A tuple containing the final state of the quantum script and whether the state has a batch dimension. """ prng_key = execution_kwargs.pop("prng_key", None) interface = execution_kwargs.get("interface", None) prep = None if len(circuit) > 0 and isinstance(circuit[0], qml.operation.StatePrepBase): prep = circuit[0] state = create_initial_state(sorted(circuit.op_wires), prep, like=INTERFACE_TO_LIKE[interface]) # initial state is batched only if the state preparation (if it exists) is batched is_state_batched = bool(prep and prep.batch_size is not None) key = prng_key for op in circuit.operations[bool(prep) :]: if isinstance(op, MidMeasureMP): prng_key, key = jax_random_split(prng_key) state = apply_operation( op, state, is_state_batched=is_state_batched, debugger=debugger, prng_key=key, tape_shots=circuit.shots, **execution_kwargs, ) # Handle postselection on mid-circuit measurements if isinstance(op, qml.Projector): prng_key, key = jax_random_split(prng_key) state, new_shots = _postselection_postprocess( state, is_state_batched, circuit.shots, prng_key=key, **execution_kwargs ) circuit._shots = new_shots # new state is batched if i) the old state is batched, or ii) the new op adds a batch dim is_state_batched = is_state_batched or (op.batch_size is not None) for _ in range(circuit.num_wires - len(circuit.op_wires)): # if any measured wires are not operated on, we pad the state with zeros. # We know they belong at the end because the circuit is in standard wire-order state = qml.math.stack([state, qml.math.zeros_like(state)], axis=-1) return state, is_state_batched # pylint: disable=too-many-arguments @debug_logger def measure_final_state(circuit, state, is_state_batched, **execution_kwargs) -> Result: """ Perform the measurements required by the circuit on the provided state. This is an internal function that will be called by the successor to ``default.qubit``. Args: circuit (.QuantumScript): The single circuit to simulate. This circuit is assumed to have non-negative integer wire labels state (TensorLike): The state to perform measurement on is_state_batched (bool): Whether the state has a batch dimension or not. rng (Union[None, int, array_like[int], SeedSequence, BitGenerator, Generator]): A seed-like parameter matching that of ``seed`` for ``numpy.random.default_rng``. If no value is provided, a default RNG will be used. prng_key (Optional[jax.random.PRNGKey]): An optional ``jax.random.PRNGKey``. This is the key to the JAX pseudo random number generator. Only for simulation using JAX. If None, the default ``sample_state`` function and a ``numpy.random.default_rng`` will be used for sampling. mid_measurements (None, dict): Dictionary of mid-circuit measurements Returns: Tuple[TensorLike]: The measurement results """ rng = execution_kwargs.get("rng", None) prng_key = execution_kwargs.get("prng_key", None) mid_measurements = execution_kwargs.get("mid_measurements", None) # analytic case if not circuit.shots: if mid_measurements is not None: raise TypeError("Native mid-circuit measurements are only supported with finite shots.") if len(circuit.measurements) == 1: return measure(circuit.measurements[0], state, is_state_batched=is_state_batched) return tuple( measure(mp, state, is_state_batched=is_state_batched) for mp in circuit.measurements ) # finite-shot case rng = default_rng(rng) results = measure_with_samples( circuit.measurements, state, shots=circuit.shots, is_state_batched=is_state_batched, rng=rng, prng_key=prng_key, mid_measurements=mid_measurements, ) if len(circuit.measurements) == 1: if circuit.shots.has_partitioned_shots: return tuple(res[0] for res in results) return results[0] return results @debug_logger def simulate( circuit: qml.tape.QuantumScript, debugger=None, state_cache: Optional[dict] = None, **execution_kwargs, ) -> Result: """Simulate a single quantum script. This is an internal function that is used by``default.qubit``. Args: circuit (QuantumTape): The single circuit to simulate debugger (_Debugger): The debugger to use state_cache=None (Optional[dict]): A dictionary mapping the hash of a circuit to the pre-rotated state. Used to pass the state between forward passes and vjp calculations. rng (Optional[numpy.random._generator.Generator]): A NumPy random number generator. prng_key (Optional[jax.random.PRNGKey]): An optional ``jax.random.PRNGKey``. This is the key to the JAX pseudo random number generator. If None, a random key will be generated. Only for simulation using JAX. interface (str): The machine learning interface to create the initial state with postselect_mode (str): Configuration for handling shots with mid-circuit measurement postselection. Use ``"hw-like"`` to discard invalid shots and ``"fill-shots"`` to keep the same number of shots. Default is ``None``. mcm_method (str): Strategy to use when executing circuits with mid-circuit measurements. ``"deferred"`` is ignored. If mid-circuit measurements are found in the circuit, the device will use ``"tree-traversal"`` if specified and the ``"one-shot"`` method otherwise. For usage details, please refer to the :doc:`dynamic quantum circuits page </introduction/dynamic_quantum_circuits>`. Returns: tuple(TensorLike): The results of the simulation Note that this function can return measurements for non-commuting observables simultaneously. This function assumes that all operations provide matrices. >>> qs = qml.tape.QuantumScript([qml.RX(1.2, wires=0)], [qml.expval(qml.Z(0)), qml.probs(wires=(0,1))]) >>> simulate(qs) (0.36235775447667357, tensor([0.68117888, 0. , 0.31882112, 0. ], requires_grad=True)) """ prng_key = execution_kwargs.pop("prng_key", None) circuit = circuit.map_to_standard_wires() has_mcm = any(isinstance(op, MidMeasureMP) for op in circuit.operations) if has_mcm: if execution_kwargs.get("mcm_method", None) == "tree-traversal": return simulate_tree_mcm(circuit, prng_key=prng_key, **execution_kwargs) results = [] aux_circ = qml.tape.QuantumScript( circuit.operations, circuit.measurements, shots=[1], ) keys = jax_random_split(prng_key, num=circuit.shots.total_shots) if qml.math.get_deep_interface(circuit.data) == "jax" and prng_key is not None: # pylint: disable=import-outside-toplevel import jax def simulate_partial(k): return simulate_one_shot_native_mcm( aux_circ, debugger=debugger, prng_key=k, **execution_kwargs ) results = jax.vmap(simulate_partial, in_axes=(0,))(keys) results = tuple(zip(*results)) else: for i in range(circuit.shots.total_shots): results.append( simulate_one_shot_native_mcm( aux_circ, debugger=debugger, prng_key=keys[i], **execution_kwargs ) ) return tuple(results) ops_key, meas_key = jax_random_split(prng_key) state, is_state_batched = get_final_state( circuit, debugger=debugger, prng_key=ops_key, **execution_kwargs ) if state_cache is not None: state_cache[circuit.hash] = state return measure_final_state( circuit, state, is_state_batched, prng_key=meas_key, **execution_kwargs ) # pylint: disable=too-many-branches,too-many-statements def simulate_tree_mcm( circuit: qml.tape.QuantumScript, debugger=None, **execution_kwargs, ) -> Result: """Simulate a single quantum script with native mid-circuit measurements using the tree-traversal algorithm. The tree-traversal algorithm recursively explores all combinations of mid-circuit measurement outcomes using a depth-first approach. The depth-first approach requires ``n_mcm`` copies of the state vector (``n_mcm + 1`` state vectors in total) and records ``n_mcm`` vectors of mid-circuit measurement samples. It is generally more efficient than ``one-shot`` because it takes all samples at a leaf at once and stops exploring more branches when a single shot is allocated to a sub-tree. Args: circuit (QuantumTape): The single circuit to simulate rng (Union[None, int, array_like[int], SeedSequence, BitGenerator, Generator]): A seed-like parameter matching that of ``seed`` for ``numpy.random.default_rng``. If no value is provided, a default RNG will be used. prng_key (Optional[jax.random.PRNGKey]): An optional ``jax.random.PRNGKey``. This is the key to the JAX pseudo random number generator. If None, a random key will be generated. Only for simulation using JAX. debugger (_Debugger): The debugger to use interface (str): The machine learning interface to create the initial state with Returns: tuple(TensorLike): The results of the simulation """ PROBS_TOL = 0.0 interface = execution_kwargs.get("interface", None) postselect_mode = execution_kwargs.get("postselect_mode", None) ########################## # shot vector processing # ########################## if circuit.shots.has_partitioned_shots: prng_key = execution_kwargs.pop("prng_key", None) keys = jax_random_split(prng_key, num=circuit.shots.num_copies) results = [] for k, s in zip(keys, circuit.shots): aux_circuit = qml.tape.QuantumScript( circuit.operations, circuit.measurements, shots=s, ) results.append(simulate_tree_mcm(aux_circuit, debugger, prng_key=k, **execution_kwargs)) return tuple(results) ####################### # main implementation # ####################### # `var` measurements cannot be aggregated on the fly as they require the global `expval` # variance_transform replaces `var` measurements with `expval` and `expval**2` measurements [circuit], variance_post_processing = variance_transform(circuit) finite_shots = bool(circuit.shots) ################## # Parse MCM info # ################## # mcms is the list of all mid-circuit measurement operations # mcms[d] is the parent MCM (node) of a circuit segment (edge) at depth `d` # The first element is None because there is no parent MCM at depth 0 mcms = tuple([None] + [op for op in circuit.operations if isinstance(op, MidMeasureMP)]) n_mcms = len(mcms) - 1 # We obtain `measured_mcms_indices`, the list of MCMs which require post-processing: # either as requested by terminal measurements or post-selection measured_mcms = find_post_processed_mcms(circuit) measured_mcms_indices = [i for i, mcm in enumerate(mcms[1:]) if mcm in measured_mcms] # `mcm_samples` is a register of MCMs. It is necessary to correctly keep track of # correlated MCM values which may be requested by terminal measurements. mcm_samples = { k + 1: qml.math.empty((circuit.shots.total_shots,), dtype=bool) if finite_shots else None for k in measured_mcms_indices } ############################# # Initialize tree-traversal # ############################# # mcm_current[:d+1] is the active branch at depth `d` # The first entry is always 0 as the first edge does not stem from an MCM. # For example, if `d = 2` and `mcm_current = [0, 1, 1, 0]` we are on the 11-branch, # i.e. the first two MCMs had outcome 1. The last entry isn't meaningful until we are # at depth `d=3`. mcm_current = qml.math.zeros(n_mcms + 1, dtype=int) # `mid_measurements` maps the elements of `mcm_current` to their respective MCMs # This is used by `get_final_state::apply_operation` for `Conditional` operations mid_measurements = dict(zip(mcms[1:], mcm_current[1:].tolist())) # Split circuit into segments circuits = split_circuit_at_mcms(circuit) circuits[0] = prepend_state_prep(circuits[0], None, interface, circuit.wires) terminal_measurements = circuits[-1].measurements if finite_shots else circuit.measurements # Initialize stacks cumcounts = [0] * (n_mcms + 1) stack = TreeTraversalStack(n_mcms + 1) # The goal is to obtain the measurements of the zero-branch and one-branch # and to combine them into the final result. Exit the loop once the # zero-branch and one-branch measurements are available. depth = 0 while stack.any_is_empty(1): ########################################### # Combine measurements & step up the tree # ########################################### # Combine two leaves once measurements are available if stack.is_full(depth): # Call `combine_measurements` to count-average measurements measurement_dicts = get_measurement_dicts(terminal_measurements, stack, depth) measurements = combine_measurements( terminal_measurements, measurement_dicts, mcm_samples ) mcm_current[depth:] = 0 # Reset current branch stack.prune(depth) # Clear stacks # Go up one level to explore alternate subtree of the same depth depth -= 1 if mcm_current[depth] == 1: stack.results_1[depth] = measurements mcm_current[depth] = 0 else: stack.results_0[depth] = measurements mcm_current[depth] = 1 # Update MCM values mid_measurements.update( (k, v) for k, v in zip(mcms[depth:], mcm_current[depth:].tolist()) ) continue ################################################ # Determine whether to execute the active edge # ################################################ # Parse shots for the current branch if finite_shots: if stack.counts[depth]: shots = stack.counts[depth][mcm_current[depth]] else: shots = circuits[depth].shots.total_shots skip_subtree = not bool(shots) else: shots = None skip_subtree = ( stack.probs[depth] is not None and float(stack.probs[depth][mcm_current[depth]]) <= PROBS_TOL ) # Update active branch dict invalid_postselect = ( depth > 0 and mcms[depth].postselect is not None and mcm_current[depth] != mcms[depth].postselect ) ########################################### # Obtain measurements for the active edge # ########################################### # If num_shots is zero or postselecting on the wrong branch, update measurements with an empty tuple if skip_subtree or invalid_postselect: # Adjust counts if `invalid_postselect` if invalid_postselect: if finite_shots: # Bump downstream cumulative counts before zeroing-out counts for d in range(depth + 1, n_mcms + 1): cumcounts[d] += stack.counts[depth][mcm_current[depth]] stack.counts[depth][mcm_current[depth]] = 0 else: stack.probs[depth][mcm_current[depth]] = 0 measurements = tuple() else: # If num_shots is non-zero, simulate the current depth circuit segment if depth == 0: initial_state = stack.states[0] else: initial_state = branch_state(stack.states[depth], mcm_current[depth], mcms[depth]) circtmp = qml.tape.QuantumScript( circuits[depth].operations, circuits[depth].measurements, qml.measurements.shots.Shots(shots), ) circtmp = prepend_state_prep(circtmp, initial_state, interface, circuit.wires) state, is_state_batched = get_final_state( circtmp, debugger=debugger, mid_measurements=mid_measurements, **execution_kwargs, ) measurements = measure_final_state(circtmp, state, is_state_batched, **execution_kwargs) ##################################### # Update stack & step down the tree # ##################################### # If not at a leaf, project on the zero-branch and increase depth by one if depth < n_mcms and (not skip_subtree and not invalid_postselect): depth += 1 # Update the active branch samples with `update_mcm_samples` if finite_shots: if ( mcms[depth] and mcms[depth].postselect is not None and postselect_mode == "fill-shots" ): samples = mcms[depth].postselect * qml.math.ones_like(measurements) else: samples = qml.math.atleast_1d(measurements) stack.counts[depth] = samples_to_counts(samples) stack.probs[depth] = counts_to_probs(stack.counts[depth]) else: stack.probs[depth] = dict(zip([False, True], measurements)) samples = None # Store a copy of the state-vector to project on the one-branch stack.states[depth] = state mcm_samples, cumcounts = update_mcm_samples(samples, mcm_samples, depth, cumcounts) continue ################################################ # Update terminal measurements & step sideways # ################################################ if not skip_subtree and not invalid_postselect: measurements = insert_mcms(circuit, measurements, mid_measurements) # If at a zero-branch leaf, update measurements and switch to the one-branch if mcm_current[depth] == 0: stack.results_0[depth] = measurements mcm_current[depth] = True mid_measurements[mcms[depth]] = True continue # If at a one-branch leaf, update measurements stack.results_1[depth] = measurements ################################################## # Finalize terminal measurements post-processing # ################################################## measurement_dicts = get_measurement_dicts(terminal_measurements, stack, depth) if finite_shots: terminal_measurements = circuit.measurements mcm_samples = {mcms[i]: v for i, v in mcm_samples.items()} mcm_samples = prune_mcm_samples(mcm_samples) results = combine_measurements(terminal_measurements, measurement_dicts, mcm_samples) return variance_post_processing((results,)) def split_circuit_at_mcms(circuit): """Return a list of circuits segments (one for each mid-circuit measurement in the original circuit) where the terminal measurements probe the MCM statistics. Only the last segment retains the original terminal measurements. Args: circuit (QuantumTape): The circuit to simulate Returns: Sequence[QuantumTape]: Circuit segments. """ mcm_gen = ((i, op) for i, op in enumerate(circuit) if isinstance(op, MidMeasureMP)) circuits = [] first = 0 for last, op in mcm_gen: new_operations = circuit.operations[first:last] new_measurements = ( [qml.sample(wires=op.wires)] if circuit.shots else [qml.probs(wires=op.wires)] ) circuits.append( qml.tape.QuantumScript(new_operations, new_measurements, shots=circuit.shots) ) first = last + 1 last_circuit_operations = circuit.operations[first:] last_circuit_measurements = [] for m in circuit.measurements: if not m.mv: last_circuit_measurements.append(m) circuits.append( qml.tape.QuantumScript( last_circuit_operations, last_circuit_measurements, shots=circuit.shots ) ) return circuits def prepend_state_prep(circuit, state, interface, wires): """Prepend a ``StatePrep`` operation with the prescribed ``wires`` to the circuit. ``get_final_state`` executes a circuit on a subset of wires found in operations or measurements. This function makes sure that an initial state with the correct size is created on the first invocation of ``simulate_tree_mcm``. ``wires`` should be the wires attribute of the original circuit (which included all wires).""" if len(circuit) > 0 and isinstance(circuit[0], qml.operation.StatePrepBase): return circuit state = ( create_initial_state(wires, None, like=INTERFACE_TO_LIKE[interface]) if state is None else state ) return qml.tape.QuantumScript( [qml.StatePrep(state.ravel(), wires=wires, validate_norm=False)] + circuit.operations, circuit.measurements, shots=circuit.shots, ) def insert_mcms(circuit, results, mid_measurements): """Inserts terminal measurements of MCMs if the circuit is evaluated in analytic mode.""" if circuit.shots or not any(m.mv for m in circuit.measurements): return results results = list(results) new_results = [] mid_measurements = {k: qml.math.array([[v]]) for k, v in mid_measurements.items()} for m in circuit.measurements: if m.mv: new_results.append(gather_mcm(m, mid_measurements, qml.math.array([[True]]))) else: new_results.append(results.pop(0)) return new_results def get_measurement_dicts(measurements, stack, depth): """Combine a probs dictionary and two tuples of measurements into a tuple of dictionaries storing the probs and measurements of both branches.""" # We use `circuits[-1].measurements` since it contains the # target measurements (this is the only tape segment with # unmodified measurements) probs, results_0, results_1 = stack.probs[depth], stack.results_0[depth], stack.results_1[depth] measurement_dicts = [{} for _ in measurements] # Special treatment for single measurements single_measurement = len(measurements) == 1 # Store each measurement in a dictionary `{branch: (prob, measure)}` for branch, prob in probs.items(): meas = results_0 if branch == 0 else results_1 if single_measurement: meas = [meas] for i, m in enumerate(meas): measurement_dicts[i][branch] = (prob, m) return measurement_dicts def branch_state(state, branch, mcm): """Collapse the state on a given branch. Args: state (TensorLike): The initial state branch (int): The branch on which the state is collapsed mcm (MidMeasureMP): Mid-circuit measurement object used to obtain the wires and ``reset`` Returns: TensorLike: The collapsed state """ if isinstance(state, np.ndarray): # FASTER state = state.copy() slices = [slice(None)] * qml.math.ndim(state) axis = mcm.wires.toarray()[0] slices[axis] = int(not branch) state[tuple(slices)] = 0.0 state /= qml.math.norm(state) else: # SLOWER state = apply_operation(qml.Projector([branch], mcm.wires), state) state = state / qml.math.norm(state) if mcm.reset and branch == 1: state = apply_operation(qml.PauliX(mcm.wires), state) return state def samples_to_counts(samples): """Converts samples to counts. This function forces integer keys and values which are required by ``simulate_tree_mcm``. """ counts_1 = int(qml.math.count_nonzero(samples)) return {0: samples.size - counts_1, 1: counts_1} def counts_to_probs(counts): """Converts counts to probs.""" probs = qml.math.array(list(counts.values())) probs = probs / qml.math.sum(probs) return dict(zip(counts.keys(), probs)) def prune_mcm_samples(mcm_samples): """Removes invalid mid-measurement samples. Post-selection on a given mid-circuit measurement leads to ignoring certain branches of the tree and samples. The corresponding samples in all other mid-circuit measurement must be deleted accordingly. We need to find which samples are corresponding to the current branch by looking at all parent nodes. """ if not mcm_samples or all(v is None for v in mcm_samples.values()): return mcm_samples mask = qml.math.ones(list(mcm_samples.values())[0].shape, dtype=bool) for mcm, s in mcm_samples.items(): if mcm.postselect is None: continue mask = qml.math.logical_and(mask, s == mcm.postselect) return {k: v[mask] for k, v in mcm_samples.items()} def update_mcm_samples(samples, mcm_samples, depth, cumcounts): """Updates the depth-th mid-measurement samples. To illustrate how the function works, let's take an example. Suppose there are ``2**20`` shots in total and the computation is midway through the circuit at the 7th MCM, the active branch is ``[0,1,1,0,0,1]``, and at each MCM everything happened to split the counts 50/50, so there are ``2**14`` samples to update. These samples are correlated with the parent branches, so where do they go? They must update the ``2**14`` elements whose parent sequence corresponds to ``[0,1,1,0,0,1]``. ``cumcounts`` is used for this job and increased by the size of ``samples`` each time this function is called. """ if depth not in mcm_samples or mcm_samples[depth] is None: return mcm_samples, cumcounts count1 = qml.math.sum(samples) count0 = samples.size - count1 mcm_samples[depth][cumcounts[depth] : cumcounts[depth] + count0] = 0 cumcounts[depth] += count0 mcm_samples[depth][cumcounts[depth] : cumcounts[depth] + count1] = 1 cumcounts[depth] += count1 return mcm_samples, cumcounts @qml.transform def variance_transform(circuit): """Replace variance measurements by expectation value measurements of both the observable and the observable square. This is necessary since computing the variance requires the global expectation value which is not available from measurements on subtrees. """ skip_transform = not any(isinstance(m, VarianceMP) for m in circuit.measurements) if skip_transform: return (circuit,), lambda x: x[0] def variance_post_processing(results): """Compute the global variance from expectation value measurements of both the observable and the observable square.""" new_results = list(results[0]) offset = len(circuit.measurements) for i, (r, m) in enumerate(zip(new_results, circuit.measurements)): if isinstance(m, VarianceMP): expval = new_results.pop(offset) new_results[i] = r - expval**2 return new_results[0] if len(new_results) == 1 else new_results new_measurements = [] extra_measurements = [] for m in circuit.measurements: if isinstance(m, VarianceMP): obs2 = m.mv * m.mv if m.mv else m.obs @ m.obs new_measurements.append(ExpectationMP(obs=obs2)) extra_measurements.append(ExpectationMP(obs=m.mv if m.mv else m.obs)) else: new_measurements.append(m) new_measurements.extend(extra_measurements) return ( ( qml.tape.QuantumScript( circuit.operations, new_measurements, shots=circuit.shots, ), ), variance_post_processing, ) def measurement_with_no_shots(measurement): """Returns a NaN scalar or array of the correct size when executing an all-invalid-shot circuit.""" if isinstance(measurement, ProbabilityMP): return np.nan * qml.math.ones(2 ** len(measurement.wires)) return np.nan def combine_measurements(terminal_measurements, results, mcm_samples): """Returns combined measurement values of various types.""" empty_mcm_samples = False need_mcm_samples = not all(v is None for v in mcm_samples.values()) need_mcm_samples = need_mcm_samples and any(circ_meas.mv for circ_meas in terminal_measurements) if need_mcm_samples: empty_mcm_samples = len(next(iter(mcm_samples.values()))) == 0 if empty_mcm_samples and any(len(m) != 0 for m in mcm_samples.values()): # pragma: no cover raise ValueError("mcm_samples have inconsistent shapes.") final_measurements = [] for circ_meas in terminal_measurements: if need_mcm_samples and circ_meas.mv and empty_mcm_samples: comb_meas = measurement_with_no_shots(circ_meas) elif need_mcm_samples and circ_meas.mv: mcm_samples = {k: v.reshape((-1, 1)) for k, v in mcm_samples.items()} is_valid = qml.math.ones(list(mcm_samples.values())[0].shape[0], dtype=bool) comb_meas = gather_mcm(circ_meas, mcm_samples, is_valid) elif not results or not results[0]: if len(results) > 0: _ = results.pop(0) comb_meas = measurement_with_no_shots(circ_meas) else: comb_meas = combine_measurements_core(circ_meas, results.pop(0)) if isinstance(circ_meas, SampleMP): comb_meas = qml.math.squeeze(comb_meas) final_measurements.append(comb_meas) return final_measurements[0] if len(final_measurements) == 1 else tuple(final_measurements) @singledispatch def combine_measurements_core(original_measurement, measures): # pylint: disable=unused-argument """Returns the combined measurement value of a given type.""" raise TypeError( f"Native mid-circuit measurement mode does not support {type(original_measurement).__name__}" ) @combine_measurements_core.register def _(original_measurement: CountsMP, measures): # pylint: disable=unused-argument """The counts are accumulated using a ``Counter`` object.""" keys = list(measures.keys()) new_counts = Counter() for k in keys: if not measures[k][0]: continue new_counts.update(measures[k][1]) return dict(sorted(new_counts.items())) @combine_measurements_core.register def _(original_measurement: ExpectationMP, measures): # pylint: disable=unused-argument """The expectation value of two branches is a weighted sum of expectation values.""" cum_value = 0 total_counts = 0 for v in measures.values(): if not v[0] or v[1] is tuple(): continue cum_value += v[0] * v[1] total_counts += v[0] return cum_value / total_counts @combine_measurements_core.register def _(original_measurement: ProbabilityMP, measures): # pylint: disable=unused-argument """The combined probability of two branches is a weighted sum of the probabilities. Note the implementation is the same as for ``ExpectationMP``.""" cum_value = 0 total_counts = 0 for v in measures.values(): if not v[0] or v[1] is tuple(): continue cum_value += v[0] * v[1] total_counts += v[0] return cum_value / total_counts @combine_measurements_core.register def _(original_measurement: SampleMP, measures): # pylint: disable=unused-argument """The combined samples of two branches is obtained by concatenating the sample if each branch..""" new_sample = tuple( qml.math.atleast_1d(m[1]) for m in measures.values() if m[0] and not m[1] is tuple() ) return qml.math.squeeze(qml.math.concatenate(new_sample)) @debug_logger def simulate_one_shot_native_mcm( circuit: qml.tape.QuantumScript, debugger=None, **execution_kwargs ) -> Result: """Simulate a single shot of a single quantum script with native mid-circuit measurements. Args: circuit (QuantumTape): The single circuit to simulate debugger (_Debugger): The debugger to use rng (Optional[numpy.random._generator.Generator]): A NumPy random number generator. prng_key (Optional[jax.random.PRNGKey]): An optional ``jax.random.PRNGKey``. This is the key to the JAX pseudo random number generator. If None, a random key will be generated. Only for simulation using JAX. interface (str): The machine learning interface to create the initial state with postselect_mode (str): Configuration for handling shots with mid-circuit measurement postselection. Use ``"hw-like"`` to discard invalid shots and ``"fill-shots"`` to keep the same number of shots. Default is ``None``. Returns: tuple(TensorLike): The results of the simulation dict: The mid-circuit measurement results of the simulation """ prng_key = execution_kwargs.pop("prng_key", None) ops_key, meas_key = jax_random_split(prng_key) mid_measurements = {} state, is_state_batched = get_final_state( circuit, debugger=debugger, mid_measurements=mid_measurements, prng_key=ops_key, **execution_kwargs, ) return measure_final_state( circuit, state, is_state_batched, prng_key=meas_key, mid_measurements=mid_measurements, **execution_kwargs, )
pennylane/pennylane/devices/qubit/simulate.py/0
{ "file_path": "pennylane/pennylane/devices/qubit/simulate.py", "repo_id": "pennylane", "token_count": 16305 }
47
# Copyright 2024 Xanadu Quantum Technologies Inc. # 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. """Tests trainable circuits using the TensorFlow interface.""" import numpy as np # pylint:disable=no-self-use import pytest import pennylane as qml tf = pytest.importorskip("tensorflow") @pytest.mark.usefixtures("validate_diff_method") @pytest.mark.parametrize("diff_method", ["backprop", "parameter-shift", "hadamard"]) class TestGradients: """Test various gradient computations.""" @pytest.fixture(autouse=True) def skip_if_braket(self, device): """Skip braket tests with tensorflow.""" dev = device(1) if "raket" in dev.name: pytest.skip(reason="braket cannot convert TF variables to literal") def test_basic_grad(self, diff_method, device, tol): """Test a basic function with one RX and one expectation.""" wires = 2 if diff_method == "hadamard" else 1 dev = device(wires=wires) tol = tol(dev.shots) if diff_method == "hadamard": tol += 0.01 @qml.qnode(dev, diff_method=diff_method) def circuit(x): qml.RX(x, 0) return qml.expval(qml.Z(0)) x = tf.Variable(0.5) with tf.GradientTape() as tape: res = circuit(x) grad = tape.gradient(res, x) assert np.isclose(grad, -np.sin(x), atol=tol, rtol=0) def test_backprop_state(self, diff_method, device, tol): """Test the trainability of parameters in a circuit returning the state.""" if diff_method != "backprop": pytest.skip(reason="test only works with backprop") dev = device(2) if dev.shots: pytest.skip("test uses backprop, must be in analytic mode") if "mixed" in dev.name: pytest.skip("mixed-state simulator will wrongly use grad on non-scalar results") tol = tol(dev.shots) x = tf.Variable(0.543) y = tf.Variable(-0.654) @qml.qnode(dev, diff_method="backprop", grad_on_execution=True) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.state() def cost_fn(x, y): res = circuit(x, y) probs = tf.abs(res) ** 2 return probs[0] + probs[2] with tf.GradientTape() as tape: res = cost_fn(x, y) grad = tape.gradient(res, [x, y]) expected = np.array([-np.sin(x) * np.cos(y) / 2, -np.cos(x) * np.sin(y) / 2]) assert np.allclose(grad, expected, atol=tol, rtol=0) def test_parameter_shift(self, diff_method, device, tol): """Test a multi-parameter circuit with parameter-shift.""" if diff_method != "parameter-shift": pytest.skip(reason="test only works with parameter-shift") a = tf.Variable(0.1) b = tf.Variable(0.2) dev = device(2) tol = tol(dev.shots) @qml.qnode(dev, diff_method="parameter-shift", grad_on_execution=False) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.Hamiltonian([1, 1], [qml.Z(0), qml.Y(1)])) with tf.GradientTape() as tape: res = circuit(a, b) grad = tape.gradient(res, [a, b]) expected = [-np.sin(a) + np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)] assert np.allclose(grad, expected, atol=tol, rtol=0) def test_probs(self, diff_method, device, tol): """Test differentiation of a circuit returning probs().""" wires = 3 if diff_method == "hadamard" else 2 dev = device(wires=wires) tol = tol(dev.shots) x = tf.Variable(0.543) y = tf.Variable(-0.654) @qml.qnode(dev, diff_method=diff_method) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[1]) with tf.GradientTape() as tape: res0 = circuit(x, y) res = tape.jacobian(res0, [x, y]) expected = np.array( [ [-np.sin(x) * np.cos(y) / 2, -np.cos(x) * np.sin(y) / 2], [np.cos(y) * np.sin(x) / 2, np.cos(x) * np.sin(y) / 2], ] ) assert isinstance(res, list) assert len(res) == 2 assert isinstance(res[0], tf.Tensor) assert res[0].shape == (2,) assert isinstance(res[1], tf.Tensor) assert res[1].shape == (2,) assert np.allclose(res[0], expected.T[0], atol=tol, rtol=0) assert np.allclose(res[1], expected.T[1], atol=tol, rtol=0) def test_multi_meas(self, diff_method, device, tol): """Test differentiation of a circuit with both scalar and array-like returns.""" wires = 3 if diff_method == "hadamard" else 2 dev = device(wires=wires) tol = tol(dev.shots) # TODO: remove the following lines after tensorflow dtype preservation is fixed if "lightning" in getattr(dev, "name", "").lower(): pytest.skip("tf interfaces not working correctly with lightning") x = tf.Variable(0.543) y = tf.Variable(-0.654) @qml.qnode(dev, diff_method=diff_method) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.Z(0)), qml.probs(wires=[1]) with tf.GradientTape() as tape: res = circuit(x, y) res = tf.experimental.numpy.hstack(res) jac = tape.jacobian(res, [x, y]) expected = np.array( [ [-np.sin(x), -np.sin(x) * np.cos(y) / 2, np.cos(y) * np.sin(x) / 2], [0.0, -np.cos(x) * np.sin(y) / 2, np.cos(x) * np.sin(y) / 2], ] ) assert isinstance(jac, list) assert len(jac) == 2 assert all(isinstance(j, tf.Tensor) and j.shape == (3,) for j in jac) assert np.allclose(jac, expected, atol=tol, rtol=0) # assert isinstance(jac[0], tuple) # assert len(jac[0]) == 1 # assert isinstance(jac[0][0], tf.Tensor) # assert jac[0][0].shape == () # assert np.allclose(jac[0][0], expected[0][0], atol=tol, rtol=0) # assert isinstance(jac[1], tuple) # assert len(jac[1]) == 1 # assert isinstance(jac[1][0], tf.Tensor) # assert jac[1][0].shape == (2,) # assert np.allclose(jac[1][0], expected[1][0], atol=tol, rtol=0) def test_hessian(self, diff_method, device, tol): """Test hessian computation.""" wires = 3 if diff_method == "hadamard" else 1 dev = device(wires=wires) tol = tol(dev.shots) # TODO: remove the following lines after tensorflow dtype preservation is fixed if "lightning" in getattr(dev, "name", "").lower(): pytest.skip("tf interfaces not working correctly with lightning") @qml.qnode(dev, diff_method=diff_method, max_diff=2) def circuit(x): qml.RY(x[0], wires=0) qml.RX(x[1], wires=0) return qml.expval(qml.Z(0)) x = tf.Variable([1.0, 2.0], dtype=tf.float64) with tf.GradientTape() as tape1: with tf.GradientTape() as tape2: res = circuit(x) g = tape2.gradient(res, x) hess = tape1.jacobian(g, x) a, b = x expected_res = np.cos(a) * np.cos(b) assert np.allclose(res, expected_res, atol=tol, rtol=0) expected_g = [-np.sin(a) * np.cos(b), -np.cos(a) * np.sin(b)] assert np.allclose(g, expected_g, atol=tol, rtol=0) expected_hess = [ [-np.cos(a) * np.cos(b), np.sin(a) * np.sin(b)], [np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)], ] assert np.allclose(hess, expected_hess, atol=tol, rtol=0)
pennylane/pennylane/devices/tests/test_gradients_tf.py/0
{ "file_path": "pennylane/pennylane/devices/tests/test_gradients_tf.py", "repo_id": "pennylane", "token_count": 4133 }
48
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """ This module contains some useful utility functions for circuit drawing. """ from pennylane.measurements import MeasurementProcess, MeasurementValue, MidMeasureMP from pennylane.ops import Conditional, Controlled from pennylane.tape import QuantumScript def default_wire_map(tape): """Create a dictionary mapping used wire labels to non-negative integers Args: tape [~.tape.QuantumTape): the QuantumTape containing operations and measurements Returns: dict: map from wires to sequential positive integers """ # Use dictionary to preserve ordering, sets break order used_wires = {wire: None for op in tape for wire in op.wires} return {wire: ind for ind, wire in enumerate(used_wires)} def default_bit_map(tape): """Create a dictionary mapping ``MidMeasureMP``'s to indices corresponding to classical wires. We only add mid-circuit measurements that are used for classical conditions and for collecting statistics to this dictionary. Args: tape [~.tape.QuantumTape]: the QuantumTape containing operations and measurements Returns: dict: map from mid-circuit measurements to classical wires.""" bit_map = {} for op in tape: if isinstance(op, Conditional): for m in op.meas_val.measurements: bit_map[m] = None if isinstance(op, MeasurementProcess) and op.mv is not None: if isinstance(op.mv, MeasurementValue): for m in op.mv.measurements: bit_map[m] = None else: for m in op.mv: bit_map[m.measurements[0]] = None cur_cwire = 0 for op in tape: if isinstance(op, MidMeasureMP) and op in bit_map: bit_map[op] = cur_cwire cur_cwire += 1 return bit_map def convert_wire_order(tape, wire_order=None, show_all_wires=False): """Creates the mapping between wire labels and place in order. Args: tape (~.tape.QuantumTape): the Quantum Tape containing operations and measurements wire_order Sequence[Any]: the order (from top to bottom) to print the wires Keyword Args: show_all_wires=False (bool): whether to display all wires in ``wire_order`` or only include ones used by operations in ``ops`` Returns: dict: map from wire labels to sequential positive integers """ default = default_wire_map(tape) if wire_order is None: return default wire_order = list(wire_order) + [wire for wire in default if wire not in wire_order] if not show_all_wires: used_wires = {wire for op in tape for wire in op.wires} wire_order = [wire for wire in wire_order if wire in used_wires] return {wire: ind for ind, wire in enumerate(wire_order)} def unwrap_controls(op): """Unwraps nested controlled operations for drawing. Controlled operations may themselves contain controlled operations; check for any nesting of operators when drawing so that we correctly identify and label _all_ control and target qubits. Args: op (.Operation): A PennyLane operation. Returns: Wires, List: The control wires of the operation, along with any associated control values. """ # Get wires and control values of base operation; need to make a copy of # control values, otherwise it will modify the list in the operation itself. control_wires = getattr(op, "control_wires", []) control_values = getattr(op, "hyperparameters", {}).get("control_values", None) if isinstance(control_values, list): control_values = control_values.copy() if isinstance(op, Controlled): next_ctrl = op while hasattr(next_ctrl, "base"): if isinstance(next_ctrl.base, Controlled): base_control_wires = getattr(next_ctrl.base, "control_wires", []) control_wires += base_control_wires base_control_values = next_ctrl.base.hyperparameters.get( "control_values", [True] * len(base_control_wires) ) if control_values is not None: control_values.extend(base_control_values) next_ctrl = next_ctrl.base control_values = [bool(int(i)) for i in control_values] if control_values else control_values return control_wires, control_values def cwire_connections(layers, bit_map): """Extract the information required for classical control wires. Args: layers (List[List[.Operator, .MeasurementProcess]]): the operations and measurements sorted into layers via ``drawable_layers``. Measurement layers may be appended to operation layers. bit_map (Dict): Dictionary containing mid-circuit measurements that are used for classical conditions or measurement statistics as keys. Returns: list, list: list of list of accessed layers for each classical wire, and largest wire corresponding to the accessed layers in the list above. >>> with qml.queuing.AnnotatedQueue() as q: ... m0 = qml.measure(0) ... m1 = qml.measure(1) ... qml.cond(m0 & m1, qml.Y)(0) ... qml.cond(m0, qml.S)(3) >>> tape = qml.tape.QuantumScript.from_queue(q) >>> layers = drawable_layers(tape) >>> bit_map, cwire_layers, cwire_wires = cwire_connections(layers) >>> bit_map {measure(wires=[0]): 0, measure(wires=[1]): 1} >>> cwire_layers [[0, 2, 3], [1, 2]] >>> cwire_wires [[0, 0, 3], [1, 0]] From this information, we can see that the first classical wire is active in layers 0, 2, and 3 while the second classical wire is active in layers 1 and 2. The first "active" layer will always be the one with the mid circuit measurement. """ if len(bit_map) == 0: return [], [] connected_layers = [[] for _ in bit_map] connected_wires = [[] for _ in bit_map] for layer_idx, layer in enumerate(layers): for op in layer: if isinstance(op, MidMeasureMP) and op in bit_map: connected_layers[bit_map[op]].append(layer_idx) connected_wires[bit_map[op]].append(op.wires[0]) elif isinstance(op, Conditional): for m in op.meas_val.measurements: cwire = bit_map[m] connected_layers[cwire].append(layer_idx) connected_wires[cwire].append(max(op.wires)) elif isinstance(op, MeasurementProcess) and op.mv is not None: if isinstance(op.mv, MeasurementValue): for m in op.mv.measurements: cwire = bit_map[m] connected_layers[cwire].append(layer_idx) else: for m in op.mv: cwire = bit_map[m.measurements[0]] connected_layers[cwire].append(layer_idx) return connected_layers, connected_wires def transform_deferred_measurements_tape(tape): """Helper function to replace MeasurementValues with wires for tapes using deferred measurements.""" if not any(isinstance(op, MidMeasureMP) for op in tape.operations) and any( m.mv is not None for m in tape.measurements ): new_measurements = [] for m in tape.measurements: if m.mv is not None: new_m = type(m)(wires=m.wires) new_measurements.append(new_m) else: new_measurements.append(m) new_tape = QuantumScript(tape.operations, new_measurements) return new_tape return tape
pennylane/pennylane/drawer/utils.py/0
{ "file_path": "pennylane/pennylane/drawer/utils.py", "repo_id": "pennylane", "token_count": 3290 }
49
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """Contains a function for generating generalized parameter shift rules and helper methods for processing shift rules as well as for creating tapes with shifted parameters.""" import functools import itertools import numbers import warnings import numpy as np from scipy.linalg import solve as linalg_solve import pennylane as qml from pennylane.measurements import MeasurementProcess from pennylane.ops.functions import bind_new_parameters from pennylane.tape import QuantumScript def process_shifts(rule, tol=1e-10, batch_duplicates=True): """Utility function to process gradient rules. Args: rule (array): a ``(M, N)`` array corresponding to ``M`` terms with parameter shifts. ``N`` has to be either ``2`` or ``3``. The first column corresponds to the linear combination coefficients; the last column contains the shift values. If ``N=3``, the middle column contains the multipliers. tol (float): floating point tolerance used when comparing shifts/coefficients Terms with coefficients below ``tol`` will be removed. batch_duplicates (bool): whether to check the input ``rule`` for duplicate shift values in its second column. Returns: array: The processed shift rule with small entries rounded to 0, sorted with respect to the absolute value of the shifts, and groups of shift terms with identical (multiplier and) shift fused into one term each, if ``batch_duplicates=True``. This utility function accepts coefficients and shift values as well as optionally multipliers, and performs the following processing: - Set all small (within absolute tolerance ``tol``) coefficients and shifts to 0 - Remove terms where the coefficients are 0 (including the ones set to 0 in the previous step) - Terms with the same shift value (and multiplier) are combined into a single term. - Finally, the terms are sorted according to the absolute value of ``shift``, This ensures that a zero-shift term, if it exists, is returned first. For equal absolute values of two shifts, the positive shift is sorted to come first. """ # set all small coefficients, multipliers if present, and shifts to zero. rule[np.abs(rule) < tol] = 0 # remove columns where the coefficients are 0 rule = rule[~(rule[:, 0] == 0)] if batch_duplicates: round_decimals = int(-np.log10(tol)) rounded_rule = np.round(rule[:, 1:], round_decimals) # determine unique shifts or (multiplier, shift) combinations unique_mods = np.unique(rounded_rule, axis=0) if rule.shape[0] != unique_mods.shape[0]: matches = np.all(rounded_rule[:, np.newaxis] == unique_mods[np.newaxis, :], axis=-1) # TODO: The following line probably can be done in numpy coeffs = [np.sum(rule[slc, 0]) for slc in matches.T] rule = np.hstack([np.stack(coeffs)[:, np.newaxis], unique_mods]) # sort columns according to abs(shift), ties are resolved with the sign, # positive shifts being returned before negative shifts. return rule[np.lexsort((-np.sign(rule[:, -1]), np.abs(rule[:, -1])))] @functools.lru_cache(maxsize=None) def eigvals_to_frequencies(eigvals): r"""Convert an eigenvalue spectrum to frequency values, defined as the the set of positive, unique differences of the eigenvalues in the spectrum. Args: eigvals (tuple[int, float]): eigenvalue spectra Returns: tuple[int, float]: frequencies **Example** >>> eigvals = (-0.5, 0, 0, 0.5) >>> eigvals_to_frequencies(eigvals) (0.5, 1.0) """ unique_eigvals = sorted(set(eigvals)) return tuple({j - i for i, j in itertools.combinations(unique_eigvals, 2)}) @functools.lru_cache(maxsize=None) def frequencies_to_period(frequencies, decimals=5): r"""Returns the period of a Fourier series as defined by a set of frequencies. The period is simply :math:`2\pi/gcd(frequencies)`, where :math:`\text{gcd}` is the greatest common divisor. Args: spectra (tuple[int, float]): frequency spectra decimals (int): Number of decimal places to round to if there are non-integral frequencies. Returns: tuple[int, float]: frequencies **Example** >>> frequencies = (0.5, 1.0) >>> frequencies_to_period(frequencies) 12.566370614359172 """ try: gcd = np.gcd.reduce(frequencies) except TypeError: # np.gcd only support integer frequencies exponent = 10**decimals frequencies = np.round(frequencies, decimals) * exponent gcd = np.gcd.reduce(np.int64(frequencies)) / exponent return 2 * np.pi / gcd @functools.lru_cache(maxsize=None) def _get_shift_rule(frequencies, shifts=None): n_freqs = len(frequencies) frequencies = qml.math.sort(qml.math.stack(frequencies)) freq_min = frequencies[0] if len(set(frequencies)) != n_freqs or freq_min <= 0: raise ValueError( f"Expected frequencies to be a list of unique positive values, instead got {frequencies}." ) mu = np.arange(1, n_freqs + 1) if shifts is None: # assume equidistant shifts shifts = (2 * mu - 1) * np.pi / (2 * n_freqs * freq_min) equ_shifts = True else: shifts = qml.math.sort(qml.math.stack(shifts)) if len(shifts) != n_freqs: raise ValueError( f"Expected number of shifts to equal the number of frequencies ({n_freqs}), instead got {shifts}." ) if len(set(shifts)) != n_freqs: raise ValueError(f"Shift values must be unique, instead got {shifts}") equ_shifts = np.allclose(shifts, (2 * mu - 1) * np.pi / (2 * n_freqs * freq_min)) if len(set(np.round(np.diff(frequencies), 10))) <= 1 and equ_shifts: # equidistant case coeffs = ( freq_min * (-1) ** (mu - 1) / (4 * n_freqs * np.sin(np.pi * (2 * mu - 1) / (4 * n_freqs)) ** 2) ) else: # non-equidistant case sin_matrix = -4 * np.sin(np.outer(shifts, frequencies)) det_sin_matrix = np.linalg.det(sin_matrix) if abs(det_sin_matrix) < 1e-6: warnings.warn( f"Solving linear problem with near zero determinant ({det_sin_matrix}) " "may give unstable results for the parameter shift rules." ) coeffs = -2 * linalg_solve(sin_matrix.T, frequencies) coeffs = np.concatenate((coeffs, -coeffs)) shifts = np.concatenate((shifts, -shifts)) # pylint: disable=invalid-unary-operand-type return np.stack([coeffs, shifts]).T def _iterate_shift_rule_with_multipliers(rule, order, period): r"""Helper method to repeat a shift rule that includes multipliers multiple times along the same parameter axis for higher-order derivatives.""" combined_rules = [] for partial_rules in itertools.product(rule, repeat=order): c, m, s = np.stack(partial_rules).T cumul_shift = 0.0 for _m, _s in zip(m, s): cumul_shift *= _m cumul_shift += _s if period is not None: cumul_shift = np.mod(cumul_shift + 0.5 * period, period) - 0.5 * period combined_rules.append(np.stack([np.prod(c), np.prod(m), cumul_shift])) # combine all terms in the linear combination into a single # array, with column order (coefficients, multipliers, shifts) return qml.math.stack(combined_rules) def _iterate_shift_rule(rule, order, period=None): r"""Helper method to repeat a shift rule multiple times along the same parameter axis for higher-order derivatives.""" if len(rule[0]) == 3: return _iterate_shift_rule_with_multipliers(rule, order, period) # TODO: optimization: Without multipliers, the order of shifts does not matter, # so that we can only iterate over the symmetric part of the combined_rules tensor. # This requires the corresponding multinomial prefactors to be included in the coeffs. combined_rules = np.array(list(itertools.product(rule, repeat=order))) # multiply the coefficients of each rule coeffs = np.prod(combined_rules[..., 0], axis=1) # sum the shifts of each rule shifts = np.sum(combined_rules[..., 1], axis=1) if period is not None: # if a period is provided, make sure the shift value is within [-period/2, period/2) shifts = np.mod(shifts + 0.5 * period, period) - 0.5 * period return qml.math.stack([coeffs, shifts]).T def _combine_shift_rules(rules): r"""Helper method to combine shift rules for multiple parameters into simultaneous multivariate shift rules.""" combined_rules = [] for partial_rules in itertools.product(*rules): c, *m, s = np.stack(partial_rules).T combined = np.concatenate([[np.prod(c)], *m, s]) combined_rules.append(np.stack(combined)) return np.stack(combined_rules) @functools.lru_cache() def generate_shift_rule(frequencies, shifts=None, order=1): r"""Computes the parameter shift rule for a unitary based on its generator's eigenvalue frequency spectrum. To compute gradients of circuit parameters in variational quantum algorithms, expressions for cost function first derivatives with respect to the variational parameters can be cast into linear combinations of expectation values at shifted parameter values. The coefficients and shifts defining the linear combination can be obtained from the unitary generator's eigenvalue frequency spectrum. Details can be found in `Wierichs et al. (2022) <https://doi.org/10.22331/q-2022-03-30-677>`__. Args: frequencies (tuple[int or float]): The tuple of eigenvalue frequencies. Eigenvalue frequencies are defined as the unique positive differences obtained from a set of eigenvalues. shifts (tuple[int or float]): the tuple of shift values. If unspecified, equidistant shifts are assumed. If supplied, the length of this tuple should match the number of given frequencies. order (int): the order of differentiation to compute the shift rule for Returns: tuple: a tuple of coefficients and shifts describing the gradient rule for the parameter-shift method. For parameter :math:`\phi`, the coefficients :math:`c_i` and the shifts :math:`s_i` combine to give a gradient rule of the following form: .. math:: \frac{\partial}{\partial\phi}f = \sum_{i} c_i f(\phi + s_i). where :math:`f(\phi) = \langle 0|U(\phi)^\dagger \hat{O} U(\phi)|0\rangle` for some observable :math:`\hat{O}` and the unitary :math:`U(\phi)=e^{iH\phi}`. Raises: ValueError: if ``frequencies`` is not a list of unique positive values, or if ``shifts`` (if specified) is not a list of unique values the same length as ``frequencies``. **Examples** An example of obtaining the frequencies from generator eigenvalues, and obtaining the parameter shift rule: >>> eigvals = (-0.5, 0, 0, 0.5) >>> frequencies = eigvals_to_frequencies(eigvals) >>> generate_shift_rule(frequencies) array([[ 0.4267767 , 1.57079633], [-0.4267767 , -1.57079633], [-0.0732233 , 4.71238898], [ 0.0732233 , -4.71238898]]) An example with explicitly specified shift values: >>> frequencies = (1, 2, 4) >>> shifts = (np.pi / 3, 2 * np.pi / 3, np.pi / 4) >>> generate_shift_rule(frequencies, shifts) array([[ 3. , 0.78539816], [-3. , -0.78539816], [-2.09077028, 1.04719755], [ 2.09077028, -1.04719755], [ 0.2186308 , 2.0943951 ], [-0.2186308 , -2.0943951 ]]) Higher order shift rules (corresponding to the :math:`n`-th derivative of the parameter) can be requested via the ``order`` argument. For example, to extract the second order shift rule for a gate with generator :math:`X/2`: >>> eigvals = (0.5, -0.5) >>> frequencies = eigvals_to_frequencies(eigvals) >>> generate_shift_rule(frequencies, order=2) array([[-0.5 , 0. ], [ 0.5 , -3.14159265]]) This corresponds to the shift rule :math:`\frac{\partial^2 f}{\partial \phi^2} = \frac{1}{2} \left[f(\phi) - f(\phi-\pi)\right]`. """ frequencies = tuple(f for f in frequencies if f > 0) rule = _get_shift_rule(frequencies, shifts=shifts) if order > 1: T = frequencies_to_period(frequencies) rule = _iterate_shift_rule(rule, order, period=T) return process_shifts(rule, tol=1e-10) def generate_multi_shift_rule(frequencies, shifts=None, orders=None): r"""Computes the parameter shift rule with respect to two parametrized unitaries, given their generator's eigenvalue frequency spectrum. This corresponds to a shift rule that computes off-diagonal elements of higher order derivative tensors. For the second order, this corresponds to the Hessian. Args: frequencies (list[tuple[int or float]]): List of eigenvalue frequencies corresponding to the each parametrized unitary. shifts (list[tuple[int or float]]): List of shift values corresponding to each parametrized unitary. If unspecified, equidistant shifts are assumed. If supplied, the length of each tuple in the list must be the same as the length of the corresponding tuple in ``frequencies``. orders (list[int]): the order of differentiation for each parametrized unitary. If unspecified, the first order derivative shift rule is computed for each parametrized unitary. Returns: tuple: a tuple of coefficients, shifts for the first parameter, and shifts for the second parameter, describing the gradient rule for the parameter-shift method. For parameters :math:`\phi_a` and :math:`\phi_b`, the coefficients :math:`c_i` and the shifts :math:`s^{(a)}_i`, :math:`s^{(b)}_i`, combine to give a gradient rule of the following form: .. math:: \frac{\partial^2}{\partial\phi_a \partial\phi_b}f = \sum_{i} c_i f(\phi_a + s^{(a)}_i, \phi_b + s^{(b)}_i). where :math:`f(\phi_a, \phi_b) = \langle 0|U(\phi_a)^\dagger V(\phi_b)^\dagger \hat{O} V(\phi_b) U(\phi_a)|0\rangle` for some observable :math:`\hat{O}` and unitaries :math:`U(\phi_a)=e^{iH_a\phi_a}` and :math:`V(\phi_b)=e^{iH_b\phi_b}`. **Example** >>> generate_multi_shift_rule([(1,), (1,)]) array([[ 0.25 , 1.57079633, 1.57079633], [-0.25 , 1.57079633, -1.57079633], [-0.25 , -1.57079633, 1.57079633], [ 0.25 , -1.57079633, -1.57079633]]) This corresponds to the gradient rule .. math:: \begin{align*} \frac{\partial^2 f}{\partial x\partial y} &= \frac{1}{4} [f(x+\pi/2, y+\pi/2) - f(x+\pi/2, y-\pi/2)\\ &\phantom{\frac{1}{4}[}-f(x-\pi/2, y+\pi/2) + f(x-\pi/2, y-\pi/2) ]. \end{align*} """ rules = [] shifts = shifts or [None] * len(frequencies) orders = orders or [1] * len(frequencies) for f, s, o in zip(frequencies, shifts, orders): rule = generate_shift_rule(f, shifts=s, order=o) rules.append(process_shifts(rule)) return _combine_shift_rules(rules) def _copy_and_shift_params(tape, indices, shifts, multipliers, cast=False): """Create a copy of a tape and of parameters, and set the new tape to the parameters rescaled and shifted as indicated by ``indices``, ``multipliers`` and ``shifts``.""" all_ops = tape.circuit for idx, shift, multiplier in zip(indices, shifts, multipliers): _, op_idx, p_idx = tape.get_operation(idx) op = ( all_ops[op_idx].obs if isinstance(all_ops[op_idx], MeasurementProcess) else all_ops[op_idx] ) # Shift copied parameter new_params = list(op.data) if not isinstance(new_params[p_idx], numbers.Integral): multiplier = qml.math.convert_like(multiplier, new_params[p_idx]) multiplier = qml.math.cast_like(multiplier, new_params[p_idx]) shift = qml.math.convert_like(shift, new_params[p_idx]) shift = qml.math.cast_like(shift, new_params[p_idx]) new_params[p_idx] = new_params[p_idx] * multiplier new_params[p_idx] = new_params[p_idx] + shift if cast: dtype = getattr(new_params[p_idx], "dtype", float) new_params[p_idx] = qml.math.cast(new_params[p_idx], dtype) # Create operator with shifted parameter and put into shifted tape shifted_op = bind_new_parameters(op, new_params) if op_idx < len(tape.operations): all_ops[op_idx] = shifted_op else: mp = all_ops[op_idx].__class__ all_ops[op_idx] = mp(obs=shifted_op) # pylint: disable=protected-access ops = all_ops[: len(tape.operations)] meas = all_ops[len(tape.operations) :] return QuantumScript(ops=ops, measurements=meas, shots=tape.shots) def generate_shifted_tapes(tape, index, shifts, multipliers=None, broadcast=False): r"""Generate a list of tapes or a single broadcasted tape, where one marked trainable parameter has been shifted by the provided shift values. Args: tape (.QuantumTape): input quantum tape index (int): index of the trainable parameter to shift shifts (Sequence[float or int]): sequence of shift values. The length determines how many parameter-shifted tapes are created. multipliers (Sequence[float or int]): sequence of multiplier values. The length should match the one of ``shifts``. Each multiplier scales the corresponding gate parameter before the shift is applied. If not provided, the parameters will not be scaled. broadcast (bool): Whether or not to use broadcasting to create a single tape with the shifted parameters. Returns: list[QuantumTape]: List of quantum tapes. In each tape the parameter indicated by ``index`` has been shifted by the values in ``shifts``. The number of tapes matches the length of ``shifts`` and ``multipliers`` (if provided). If ``broadcast=True`` was used, the list contains a single broadcasted tape with all shifts distributed over the broadcasting dimension. In this case, the ``batch_size`` of the returned tape matches the length of ``shifts``. """ if len(shifts) == 0: return tuple() if multipliers is None: multipliers = np.ones_like(shifts) if broadcast: return (_copy_and_shift_params(tape, [index], [shifts], [multipliers]),) return tuple( _copy_and_shift_params(tape, [index], [shift], [multiplier]) for shift, multiplier in zip(shifts, multipliers) ) def generate_multishifted_tapes(tape, indices, shifts, multipliers=None): r"""Generate a list of tapes where multiple marked trainable parameters have been shifted by the provided shift values. Args: tape (.QuantumTape): input quantum tape indices (Sequence[int]): indices of the trainable parameters to shift shifts (Sequence[Sequence[float or int]]): Nested sequence of shift values. The length of the outer Sequence determines how many parameter-shifted tapes are created. The lengths of the inner sequences should match and have the same length as ``indices``. multipliers (Sequence[Sequence[float or int]]): Nested sequence of multiplier values of the same format as `shifts``. Each multiplier scales the corresponding gate parameter before the shift is applied. If not provided, the parameters will not be scaled. Returns: list[QuantumTape]: List of quantum tapes. Each tape has the marked parameters indicated by ``indices`` shifted by the values of ``shifts``. The number of tapes will match the summed lengths of all inner sequences in ``shifts`` and ``multipliers`` (if provided). """ if multipliers is None: multipliers = np.ones_like(shifts) tapes = [ _copy_and_shift_params(tape, indices, _shifts, _multipliers, cast=True) for _shifts, _multipliers in zip(shifts, multipliers) ] return tapes
pennylane/pennylane/gradients/general_shift_rules.py/0
{ "file_path": "pennylane/pennylane/gradients/general_shift_rules.py", "repo_id": "pennylane", "token_count": 8194 }
50
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """ This file contains functionalities for postprocessing of kernel matrices. """ import numpy as np def threshold_matrix(K): r"""Remove negative eigenvalues from the given kernel matrix. This method yields the closest positive semi-definite matrix in any unitarily invariant norm, e.g. the Frobenius norm. Args: K (array[float]): Kernel matrix, assumed to be symmetric. Returns: array[float]: Kernel matrix with cropped negative eigenvalues. **Example:** Consider a symmetric matrix with both positive and negative eigenvalues: .. code-block :: pycon >>> K = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 2]]) >>> np.linalg.eigvalsh(K) array([-1., 1., 2.]) We then can threshold/truncate the eigenvalues of the matrix via .. code-block :: pycon >>> K_thresh = qml.kernels.threshold_matrix(K) >>> np.linalg.eigvalsh(K_thresh) array([0., 1., 2.]) If the input matrix does not have negative eigenvalues, ``threshold_matrix`` does not have any effect. """ w, v = np.linalg.eigh(K) if w[0] < 0: # Transform spectrum: Threshold/clip at 0. w0 = np.clip(w, 0, None) return (v * w0) @ np.transpose(v) return K def displace_matrix(K): r"""Remove negative eigenvalues from the given kernel matrix by adding a multiple of the identity matrix. This method keeps the eigenvectors of the matrix intact. Args: K (array[float]): Kernel matrix, assumed to be symmetric. Returns: array[float]: Kernel matrix with eigenvalues offset by adding the identity. **Example:** Consider a symmetric matrix with both positive and negative eigenvalues: .. code-block :: pycon >>> K = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 2]]) >>> np.linalg.eigvalsh(K) array([-1., 1., 2.]) We then can shift all eigenvalues of the matrix by adding the identity matrix multiplied with the absolute value of the smallest (the most negative, that is) eigenvalue: .. code-block :: pycon >>> K_displaced = qml.kernels.displace_matrix(K) >>> np.linalg.eigvalsh(K_displaced) array([0., 2., 3.]) If the input matrix does not have negative eigenvalues, ``displace_matrix`` does not have any effect. """ wmin = np.linalg.eigvalsh(K)[0] if wmin < 0: return K - np.eye(K.shape[0]) * wmin return K def flip_matrix(K): r"""Remove negative eigenvalues from the given kernel matrix by taking the absolute value. This method keeps the eigenvectors of the matrix intact. Args: K (array[float]): Kernel matrix, assumed to be symmetric. Returns: array[float]: Kernel matrix with flipped negative eigenvalues. Reference: This method is introduced in `Wang, Du, Luo & Tao (2021) <https://doi.org/10.22331/q-2021-08-30-531>`_. **Example:** Consider a symmetric matrix with both positive and negative eigenvalues: .. code-block :: pycon >>> K = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 2]]) >>> np.linalg.eigvalsh(K) array([-1., 1., 2.]) We then can invert the sign of all negative eigenvalues of the matrix, obtaining non-negative eigenvalues only: .. code-block :: pycon >>> K_flipped = qml.kernels.flip_matrix(K) >>> np.linalg.eigvalsh(K_flipped) array([1., 1., 2.]) If the input matrix does not have negative eigenvalues, ``flip_matrix`` does not have any effect. """ w, v = np.linalg.eigh(K) if w[0] < 0: # Transform spectrum: absolute value w_abs = np.abs(w) return (v * w_abs) @ np.transpose(v) return K def closest_psd_matrix(K, fix_diagonal=False, solver=None, **kwargs): r"""Return the closest positive semi-definite matrix to the given kernel matrix. This method either fixes the diagonal entries to be 1 (``fix_diagonal=True``) or keeps the eigenvectors intact (``fix_diagonal=False``), in which case it reduces to the method :func:`~.kernels.threshold_matrix`. For ``fix_diagonal=True`` a semi-definite program is solved. Args: K (array[float]): Kernel matrix, assumed to be symmetric. fix_diagonal (bool): Whether to fix the diagonal to 1. solver (str, optional): Solver to be used by cvxpy. Defaults to CVXOPT. kwargs (kwarg dict): Passed to cvxpy.Problem.solve(). Returns: array[float]: closest positive semi-definite matrix in Frobenius norm. Comments: Requires cvxpy and the used solver (default CVXOPT) to be installed if ``fix_diagonal=True``. Reference: This method is introduced in `arXiv:2105.02276 <https://arxiv.org/abs/2105.02276>`_. **Example:** Consider a symmetric matrix with both positive and negative eigenvalues: .. code-block :: pycon >>> K = np.array([[0.9, 1.], [1., 0.9]]) >>> np.linalg.eigvalsh(K) array([-0.1, 1.9]) The positive semi-definite matrix that is closest to this matrix in any unitarily invariant norm is then given by the matrix with the eigenvalues thresholded at 0, as computed by :func:`~.kernels.threshold_matrix`: .. code-block :: pycon >>> K_psd = qml.kernels.closest_psd_matrix(K) >>> K_psd array([[0.95, 0.95], [0.95, 0.95]]) >>> np.linalg.eigvalsh(K_psd) array([0., 1.9]) >>> np.allclose(K_psd, qml.kernels.threshold_matrix(K)) True However, for quantum kernel matrices we may want to restore the value 1 on the diagonal: .. code-block :: pycon >>> K_psd = qml.kernels.closest_psd_matrix(K, fix_diagonal=True) >>> K_psd array([[1. , 0.99998008], [0.99998008, 1. ]]) >>> np.linalg.eigvalsh(K_psd) array([1.99162415e-05, 1.99998008e+00]) If the input matrix does not have negative eigenvalues and ``fix_diagonal=False``, ``closest_psd_matrix`` does not have any effect. """ if not fix_diagonal: return threshold_matrix(K) try: import cvxpy as cp # pylint: disable=import-outside-toplevel if solver is None: solver = cp.CVXOPT except ImportError as e: raise ImportError("CVXPY is required for this post-processing method.") from e X = cp.Variable(K.shape, PSD=True) constraint = [cp.diag(X) == 1.0] if fix_diagonal else [] objective_fn = cp.norm(X - K, "fro") problem = cp.Problem(cp.Minimize(objective_fn), constraint) try: problem.solve(solver=solver, **kwargs) except Exception: # pylint: disable=broad-except try: problem.solve(solver=solver, verbose=True, **kwargs) except Exception as e: raise RuntimeError("CVXPY solver did not converge.") from e return X.value def mitigate_depolarizing_noise(K, num_wires, method, use_entries=None): r"""Estimate depolarizing noise rate(s) using on the diagonal entries of a kernel matrix and mitigate the noise, assuming a global depolarizing noise model. Args: K (array[float]): Noisy kernel matrix. num_wires (int): Number of wires/qubits of the quantum embedding kernel. method (``'single'`` | ``'average'`` | ``'split_channel'``): Strategy for mitigation * ``'single'``: An alias for ``'average'`` with ``len(use_entries)=1``. * ``'average'``: Estimate a global noise rate based on the average of the diagonal entries in ``use_entries``, which need to be measured on the quantum computer. * ``'split_channel'``: Estimate individual noise rates per embedding, requiring all diagonal entries to be measured on the quantum computer. use_entries (array[int]): Diagonal entries to use if method in ``['single', 'average']``. If ``None``, defaults to ``[0]`` (``'single'``) or ``range(len(K))`` (``'average'``). Returns: array[float]: Mitigated kernel matrix. Reference: This method is introduced in Section V in `arXiv:2105.02276 <https://arxiv.org/abs/2105.02276>`_. **Example:** For an example usage of ``mitigate_depolarizing_noise`` please refer to the `PennyLane demo on the kernel module <https://github.com/PennyLaneAI/qml/tree/master/demonstrations/tutorial_kernel_based_training.py>`_ or `the postprocessing demo for arXiv:2105.02276 <https://github.com/thubregtsen/qhack/blob/master/paper/post_processing_demo.py>`_. """ dim = 2**num_wires if method == "single": if use_entries is None: use_entries = (0,) if K[use_entries[0], use_entries[0]] <= (1 / dim): raise ValueError( "The single noise mitigation method cannot be applied " "as the single diagonal element specified is too small." ) diagonal_element = K[use_entries[0], use_entries[0]] noise_rate = (1 - diagonal_element) * dim / (dim - 1) mitigated_matrix = (K - noise_rate / dim) / (1 - noise_rate) elif method == "average": if use_entries is None: diagonal_elements = np.diag(K) else: diagonal_elements = np.diag(K)[np.array(use_entries)] if np.mean(diagonal_elements) <= 1 / dim: raise ValueError( "The average noise mitigation method cannot be applied " "as the average of the used diagonal terms is too small." ) noise_rates = (1 - diagonal_elements) * dim / (dim - 1) mean_noise_rate = np.mean(noise_rates) mitigated_matrix = (K - mean_noise_rate / dim) / (1 - mean_noise_rate) elif method == "split_channel": if np.any(np.diag(K) <= 1 / dim): raise ValueError( "The split channel noise mitigation method cannot be applied " "to the input matrix as its diagonal terms are too small." ) eff_noise_rates = np.clip((1 - np.diag(K)) * dim / (dim - 1), 0.0, 1.0) noise_rates = 1 - np.sqrt(1 - eff_noise_rates) inverse_noise = ( -np.outer(noise_rates, noise_rates) + noise_rates.reshape((1, len(K))) + noise_rates.reshape((len(K), 1)) ) mitigated_matrix = (K - inverse_noise / dim) / (1 - inverse_noise) else: raise ValueError( "Incorrect noise depolarization mitigation method specified. " "Accepted strategies are: 'single', 'average' and 'split_channel'." ) return mitigated_matrix
pennylane/pennylane/kernels/postprocessing.py/0
{ "file_path": "pennylane/pennylane/kernels/postprocessing.py", "repo_id": "pennylane", "token_count": 4603 }
51
# Copyright 2018-2022 Xanadu Quantum Technologies Inc. # 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. """Differentiable quantum functions""" import functools # pylint: disable=import-outside-toplevel import itertools from string import ascii_letters as ABC from autoray import numpy as np from numpy import float64 # pylint:disable=wrong-import-order import pennylane as qml from . import single_dispatch # pylint:disable=unused-import from .matrix_manipulation import _permute_dense_matrix from .multi_dispatch import diag, dot, einsum, get_interface, scatter_element_add from .utils import allclose, cast, cast_like, convert_like, is_abstract ABC_ARRAY = np.array(list(ABC)) def cov_matrix(prob, obs, wires=None, diag_approx=False): """Calculate the covariance matrix of a list of commuting observables, given the joint probability distribution of the system in the shared eigenbasis. .. note:: This method only works for **commuting observables.** If the probability distribution is the result of a quantum circuit, the quantum state must be rotated into the shared eigenbasis of the list of observables before measurement. Args: prob (tensor_like): probability distribution obs (list[.Observable]): a list of observables for which to compute the covariance matrix diag_approx (bool): if True, return the diagonal approximation wires (.Wires): The wire register of the system. If not provided, it is assumed that the wires are labelled with consecutive integers. Returns: tensor_like: the covariance matrix of size ``(len(obs), len(obs))`` **Example** Consider the following ansatz and observable list: >>> obs_list = [qml.X(0) @ qml.Z(1), qml.Y(2)] >>> ansatz = qml.templates.StronglyEntanglingLayers We can construct a QNode to output the probability distribution in the shared eigenbasis of the observables: .. code-block:: python dev = qml.device("default.qubit", wires=3) @qml.qnode(dev, interface="autograd") def circuit(weights): ansatz(weights, wires=[0, 1, 2]) # rotate into the basis of the observables for o in obs_list: o.diagonalizing_gates() return qml.probs(wires=[0, 1, 2]) We can now compute the covariance matrix: >>> shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=2, n_wires=3) >>> weights = pnp.random.random(shape, requires_grad=True) >>> cov = qml.math.cov_matrix(circuit(weights), obs_list) >>> cov tensor([[0.98125435, 0.4905541 ], [0.4905541 , 0.99920878]], requires_grad=True) Autodifferentiation is fully supported using all interfaces. Here we use autograd: >>> cost_fn = lambda weights: qml.math.cov_matrix(circuit(weights), obs_list)[0, 1] >>> qml.grad(cost_fn)(weights) array([[[ 4.94240914e-17, -2.33786398e-01, -1.54193959e-01], [-3.05414996e-17, 8.40072236e-04, 5.57884080e-04], [ 3.01859411e-17, 8.60411436e-03, 6.15745204e-04]], [[ 6.80309533e-04, -1.23162742e-03, 1.08729813e-03], [-1.53863193e-01, -1.38700657e-02, -1.36243323e-01], [-1.54665054e-01, -1.89018172e-02, -1.56415558e-01]]]) """ variances = [] # diagonal variances for i, o in enumerate(obs): eigvals = cast(o.eigvals(), dtype=float64) w = o.wires.labels if wires is None else wires.indices(o.wires) p = marginal_prob(prob, w) res = dot(eigvals**2, p) - (dot(eigvals, p)) ** 2 variances.append(res) cov = diag(variances) if diag_approx: return cov for i, j in itertools.combinations(range(len(obs)), r=2): o1 = obs[i] o2 = obs[j] o1wires = o1.wires.labels if wires is None else wires.indices(o1.wires) o2wires = o2.wires.labels if wires is None else wires.indices(o2.wires) shared_wires = set(o1wires + o2wires) l1 = cast(o1.eigvals(), dtype=float64) l2 = cast(o2.eigvals(), dtype=float64) l12 = cast(np.kron(l1, l2), dtype=float64) p1 = marginal_prob(prob, o1wires) p2 = marginal_prob(prob, o2wires) p12 = marginal_prob(prob, shared_wires) res = dot(l12, p12) - dot(l1, p1) * dot(l2, p2) cov = scatter_element_add(cov, [i, j], res) cov = scatter_element_add(cov, [j, i], res) return cov def marginal_prob(prob, axis): """Compute the marginal probability given a joint probability distribution expressed as a tensor. Each random variable corresponds to a dimension. If the distribution arises from a quantum circuit measured in computational basis, each dimension corresponds to a wire. For example, for a 2-qubit quantum circuit `prob[0, 1]` is the probability of measuring the first qubit in state 0 and the second in state 1. Args: prob (tensor_like): 1D tensor of probabilities. This tensor should of size ``(2**N,)`` for some integer value ``N``. axis (list[int]): the axis for which to calculate the marginal probability distribution Returns: tensor_like: the marginal probabilities, of size ``(2**len(axis),)`` **Example** >>> x = tf.Variable([1, 0, 0, 1.], dtype=tf.float64) / np.sqrt(2) >>> marginal_prob(x, axis=[0, 1]) <tf.Tensor: shape=(4,), dtype=float64, numpy=array([0.70710678, 0. , 0. , 0.70710678])> >>> marginal_prob(x, axis=[0]) <tf.Tensor: shape=(2,), dtype=float64, numpy=array([0.70710678, 0.70710678])> """ prob = np.flatten(prob) num_wires = int(np.log2(len(prob))) if num_wires == len(axis): return prob inactive_wires = tuple(set(range(num_wires)) - set(axis)) prob = np.reshape(prob, [2] * num_wires) prob = np.sum(prob, axis=inactive_wires) return np.flatten(prob) def reduce_dm(density_matrix, indices, check_state=False, c_dtype="complex128"): """Compute the density matrix from a state represented with a density matrix. Args: density_matrix (tensor_like): 2D or 3D density matrix tensor. This tensor should be of size ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)``, for some integer number of wires``N``. indices (list(int)): List of indices in the considered subsystem. check_state (bool): If True, the function will check the state validity (shape and norm). c_dtype (str): Complex floating point precision type. Returns: tensor_like: Density matrix of size ``(2**len(indices), 2**len(indices))`` or ``(batch_dim, 2**len(indices), 2**len(indices))`` .. seealso:: :func:`pennylane.math.reduce_statevector`, and :func:`pennylane.density_matrix` **Example** >>> x = np.array([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) >>> reduce_dm(x, indices=[0]) [[1.+0.j 0.+0.j] [0.+0.j 0.+0.j]] >>> y = [[0.5, 0, 0.5, 0], [0, 0, 0, 0], [0.5, 0, 0.5, 0], [0, 0, 0, 0]] >>> reduce_dm(y, indices=[0]) [[0.5+0.j 0.5+0.j] [0.5+0.j 0.5+0.j]] >>> reduce_dm(y, indices=[1]) [[1.+0.j 0.+0.j] [0.+0.j 0.+0.j]] >>> z = tf.Variable([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], dtype=tf.complex128) >>> reduce_dm(z, indices=[1]) tf.Tensor( [[1.+0.j 0.+0.j] [0.+0.j 0.+0.j]], shape=(2, 2), dtype=complex128) >>> x = np.array([[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], ... [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]) >>> reduce_dm(x, indices=[1]) array([[[1.+0.j, 0.+0.j], [0.+0.j, 0.+0.j]], [[0.+0.j, 0.+0.j], [0.+0.j, 1.+0.j]]]) """ density_matrix = cast(density_matrix, dtype=c_dtype) if check_state: _check_density_matrix(density_matrix) if len(np.shape(density_matrix)) == 2: batch_dim, dim = None, density_matrix.shape[0] else: batch_dim, dim = density_matrix.shape[:2] num_indices = int(np.log2(dim)) consecutive_indices = list(range(num_indices)) # Return the full density matrix if all the wires are given, potentially permuted if len(indices) == num_indices: return _permute_dense_matrix(density_matrix, consecutive_indices, indices, batch_dim) if batch_dim is None: density_matrix = qml.math.stack([density_matrix]) # Compute the partial trace traced_wires = [x for x in consecutive_indices if x not in indices] density_matrix = partial_trace(density_matrix, traced_wires, c_dtype=c_dtype) if batch_dim is None: density_matrix = density_matrix[0] # Permute the remaining indices of the density matrix return _permute_dense_matrix(density_matrix, sorted(indices), indices, batch_dim) def partial_trace(matrix, indices, c_dtype="complex128"): """Compute the reduced density matrix by tracing out the provided indices. Args: matrix (tensor_like): 2D or 3D density matrix tensor. For a 2D tensor, the size is assumed to be ``(2**n, 2**n)``, for some integer number of wires ``n``. For a 3D tensor, the first dimension is assumed to be the batch dimension, ``(batch_dim, 2**N, 2**N)``. indices (list(int)): List of indices to be traced. Returns: tensor_like: (reduced) Density matrix of size ``(2**len(wires), 2**len(wires))`` .. seealso:: :func:`pennylane.math.reduce_dm`, and :func:`pennylane.math.reduce_statevector` **Example** We can compute the partial trace of the matrix ``x`` with respect to its 0th index. >>> x = np.array([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) >>> partial_trace(x, indices=[0]) array([[1.+0.j, 0.+0.j], [0.+0.j, 0.+0.j]]) We can also pass a batch of matrices ``x`` to the function and return the partial trace of each matrix with respect to each matrix's 0th index. >>> x = np.array([ ... [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], ... [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ... ]) >>> partial_trace(x, indices=[0]) array([[[1.+0.j, 0.+0.j], [0.+0.j, 0.+0.j]], [[0.+0.j, 0.+0.j], [0.+0.j, 1.+0.j]]]) The partial trace can also be computed with respect to multiple indices within different frameworks such as TensorFlow. >>> x = tf.Variable([[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], ... [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]]], dtype=tf.complex128) >>> partial_trace(x, indices=[1]) <tf.Tensor: shape=(2, 2, 2), dtype=complex128, numpy= array([[[1.+0.j, 0.+0.j], [0.+0.j, 0.+0.j]], [[0.+0.j, 0.+0.j], [0.+0.j, 1.+0.j]]])> """ # Autograd does not support same indices sum in backprop, and tensorflow # has a limit of 8 dimensions if same indices are used matrix = cast(matrix, dtype=c_dtype) if qml.math.ndim(matrix) == 2: is_batched = False batch_dim, dim = 1, matrix.shape[1] else: is_batched = True batch_dim, dim = matrix.shape[:2] if get_interface(matrix) in ["autograd", "tensorflow"]: return _batched_partial_trace_nonrep_indices(matrix, is_batched, indices, batch_dim, dim) # Dimension and reshape num_indices = int(np.log2(dim)) rho_dim = 2 * num_indices matrix = np.reshape(matrix, [batch_dim] + [2] * 2 * num_indices) indices = np.sort(indices) # For loop over wires for i, target_index in enumerate(indices): target_index = target_index - i state_indices = ABC[1 : rho_dim - 2 * i + 1] state_indices = list(state_indices) target_letter = state_indices[target_index] state_indices[target_index + num_indices - i] = target_letter state_indices = "".join(state_indices) einsum_indices = f"a{state_indices}" matrix = einsum(einsum_indices, matrix) number_wires_sub = num_indices - len(indices) reduced_density_matrix = np.reshape( matrix, (batch_dim, 2**number_wires_sub, 2**number_wires_sub) ) return reduced_density_matrix if is_batched else reduced_density_matrix[0] def _batched_partial_trace_nonrep_indices(matrix, is_batched, indices, batch_dim, dim): """Compute the reduced density matrix for autograd interface by tracing out the provided indices with the use of projectors as same subscripts indices are not supported in autograd backprop. """ num_indices = int(np.log2(dim)) rho_dim = 2 * num_indices matrix = np.reshape(matrix, [batch_dim] + [2] * 2 * num_indices) kraus = cast(np.eye(2), matrix.dtype) kraus = np.reshape(kraus, (2, 1, 2)) kraus_dagger = np.asarray([np.conj(np.transpose(k)) for k in kraus]) kraus = convert_like(kraus, matrix) kraus_dagger = convert_like(kraus_dagger, matrix) # For loop over wires for target_wire in indices: # Tensor indices of density matrix state_indices = ABC[1 : rho_dim + 1] # row indices of the quantum state affected by this operation row_wires_list = [target_wire + 1] row_indices = "".join(ABC_ARRAY[row_wires_list].tolist()) # column indices are shifted by the number of wires col_wires_list = [w + num_indices for w in row_wires_list] col_indices = "".join(ABC_ARRAY[col_wires_list].tolist()) # indices in einsum must be replaced with new ones num_partial_trace_wires = 1 new_row_indices = ABC[rho_dim + 1 : rho_dim + num_partial_trace_wires + 1] new_col_indices = ABC[ rho_dim + num_partial_trace_wires + 1 : rho_dim + 2 * num_partial_trace_wires + 1 ] # index for summation over Kraus operators kraus_index = ABC[ rho_dim + 2 * num_partial_trace_wires + 1 : rho_dim + 2 * num_partial_trace_wires + 2 ] # new state indices replace row and column indices with new ones new_state_indices = functools.reduce( lambda old_string, idx_pair: old_string.replace(idx_pair[0], idx_pair[1]), zip(col_indices + row_indices, new_col_indices + new_row_indices), state_indices, ) # index mapping for einsum, e.g., 'iga,abcdef,idh->gbchef' einsum_indices = ( f"{kraus_index}{new_row_indices}{row_indices}, a{state_indices}," f"{kraus_index}{col_indices}{new_col_indices}->a{new_state_indices}" ) matrix = einsum(einsum_indices, kraus, matrix, kraus_dagger) number_wires_sub = num_indices - len(indices) reduced_density_matrix = np.reshape( matrix, (batch_dim, 2**number_wires_sub, 2**number_wires_sub) ) return reduced_density_matrix if is_batched else reduced_density_matrix[0] def reduce_statevector(state, indices, check_state=False, c_dtype="complex128"): """Compute the density matrix from a state vector. Args: state (tensor_like): 1D or 2D tensor state vector. This tensor should of size ``(2**N,)`` or ``(batch_dim, 2**N)``, for some integer value ``N``. indices (list(int)): List of indices in the considered subsystem. check_state (bool): If True, the function will check the state validity (shape and norm). c_dtype (str): Complex floating point precision type. Returns: tensor_like: Density matrix of size ``(2**len(indices), 2**len(indices))`` or ``(batch_dim, 2**len(indices), 2**len(indices))`` .. seealso:: :func:`pennylane.math.reduce_dm` and :func:`pennylane.density_matrix` **Example** >>> x = np.array([1, 0, 0, 0]) >>> reduce_statevector(x, indices=[0]) [[1.+0.j 0.+0.j] [0.+0.j 0.+0.j]] >>> y = [1, 0, 1, 0] / np.sqrt(2) >>> reduce_statevector(y, indices=[0]) [[0.5+0.j 0.5+0.j] [0.5+0.j 0.5+0.j]] >>> reduce_statevector(y, indices=[1]) [[1.+0.j 0.+0.j] [0.+0.j 0.+0.j]] >>> z = tf.Variable([1, 0, 0, 0], dtype=tf.complex128) >>> reduce_statevector(z, indices=[1]) tf.Tensor( [[1.+0.j 0.+0.j] [0.+0.j 0.+0.j]], shape=(2, 2), dtype=complex128) >>> x = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) >>> reduce_statevector(x, indices=[1]) array([[[1.+0.j, 0.+0.j], [0.+0.j, 0.+0.j]], [[0.+0.j, 0.+0.j], [0.+0.j, 1.+0.j]]]) """ state = cast(state, dtype=c_dtype) # Check the format and norm of the state vector if check_state: _check_state_vector(state) if len(np.shape(state)) == 1: batch_dim, dim = None, np.shape(state)[0] else: batch_dim, dim = np.shape(state)[:2] # batch dim exists but is unknown; cast to int so that reshaping works if batch_dim is None: batch_dim = -1 # Get dimension of the quantum system and reshape num_wires = int(np.log2(dim)) consecutive_wires = list(range(num_wires)) if batch_dim is None: state = qml.math.stack([state]) state = np.reshape(state, [batch_dim if batch_dim is not None else 1] + [2] * num_wires) # Get the system to be traced # traced_system = [x + 1 for x in consecutive_wires if x not in indices] # trace out the subsystem indices1 = ABC[1 : num_wires + 1] indices2 = "".join( [ABC[num_wires + i + 1] if i in indices else ABC[i + 1] for i in consecutive_wires] ) target = "".join( [ABC[i + 1] for i in sorted(indices)] + [ABC[num_wires + i + 1] for i in sorted(indices)] ) density_matrix = einsum( f"a{indices1},a{indices2}->a{target}", state, np.conj(state), optimize="greedy", ) # Return the reduced density matrix by using numpy tensor product # density_matrix = np.tensordot(state, np.conj(state), axes=(traced_system, traced_system)) if batch_dim is None: density_matrix = np.reshape(density_matrix, (2 ** len(indices), 2 ** len(indices))) else: density_matrix = np.reshape( density_matrix, (batch_dim, 2 ** len(indices), 2 ** len(indices)) ) return _permute_dense_matrix(density_matrix, sorted(indices), indices, batch_dim) def dm_from_state_vector(state, check_state=False, c_dtype="complex128"): """ Convenience function to compute a (full) density matrix from a state vector. Args: state (tensor_like): 1D or 2D tensor state vector. This tensor should of size ``(2**N,)`` or ``(batch_dim, 2**N)``, for some integer value ``N``. check_state (bool): If True, the function will check the state validity (shape and norm). c_dtype (str): Complex floating point precision type. Returns: tensor_like: Density matrix of size ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)`` **Example** >>> x = np.array([1, 0, 1j, 0]) / np.sqrt(2) >>> dm_from_state_vector(x) array([[0.5+0.j , 0. +0.j , 0. -0.5j, 0. +0.j ], [0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ], [0. +0.5j, 0. +0.j , 0.5+0.j , 0. +0.j ], [0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ]]) """ num_wires = int(np.log2(np.shape(state)[-1])) return reduce_statevector( state, indices=list(range(num_wires)), check_state=check_state, c_dtype=c_dtype, ) def purity(state, indices, check_state=False, c_dtype="complex128"): r"""Computes the purity of a density matrix. .. math:: \gamma = \text{Tr}(\rho^2) where :math:`\rho` is the density matrix. The purity of a normalized quantum state satisfies :math:`\frac{1}{d} \leq \gamma \leq 1`, where :math:`d` is the dimension of the Hilbert space. A pure state has a purity of 1. It is possible to compute the purity of a sub-system from a given state. To find the purity of the overall state, include all wires in the ``indices`` argument. Args: state (tensor_like): Density matrix of shape ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)`` indices (list(int)): List of indices in the considered subsystem. check_state (bool): If ``True``, the function will check the state validity (shape and norm). c_dtype (str): Complex floating point precision type. Returns: float: Purity of the considered subsystem. **Example** >>> x = [[1/2, 0, 0, 1/2], [0, 0, 0, 0], [0, 0, 0, 0], [1/2, 0, 0, 1/2]] >>> purity(x, [0, 1]) 1.0 >>> purity(x, [0]) 0.5 >>> x = [[1/2, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1/2]] >>> purity(x, [0, 1]) 0.5 .. seealso:: :func:`pennylane.qinfo.transforms.purity` """ # Cast as a c_dtype array state = cast(state, dtype=c_dtype) density_matrix = reduce_dm(state, indices, check_state) return _compute_purity(density_matrix) def _compute_purity(density_matrix): """Compute the purity from a density matrix Args: density_matrix (tensor_like): ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)`` tensor for an integer `N`. Returns: float: Purity of the density matrix. **Example** >>> x = [[1/2, 0], [0, 1/2]] >>> _compute_purity(x) 0.5 >>> x = [[1/2, 1/2], [1/2, 1/2]] >>> _compute_purity(x) 1 """ batched = len(qml.math.shape(density_matrix)) > 2 if batched: return qml.math.real(qml.math.einsum("abc,acb->a", density_matrix, density_matrix)) return qml.math.real(qml.math.einsum("ab,ba", density_matrix, density_matrix)) def vn_entropy(state, indices, base=None, check_state=False, c_dtype="complex128"): r"""Compute the Von Neumann entropy from a density matrix on a given subsystem. It supports all interfaces (NumPy, Autograd, Torch, TensorFlow and Jax). .. math:: S( \rho ) = -\text{Tr}( \rho \log ( \rho )) Args: state (tensor_like): Density matrix of shape ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)``. indices (list(int)): List of indices in the considered subsystem. base (float): Base for the logarithm. If None, the natural logarithm is used. check_state (bool): If True, the function will check the state validity (shape and norm). c_dtype (str): Complex floating point precision type. Returns: float: Von Neumann entropy of the considered subsystem. **Example** The entropy of a subsystem for any state vectors can be obtained. Here is an example for the maximally entangled state, where the subsystem entropy is maximal (default base for log is exponential). >>> x = [1, 0, 0, 1] / np.sqrt(2) >>> x = dm_from_state_vector(x) >>> vn_entropy(x, indices=[0]) 0.6931472 The logarithm base can be switched to 2 for example. >>> vn_entropy(x, indices=[0], base=2) 1.0 .. seealso:: :func:`pennylane.qinfo.transforms.vn_entropy` and :func:`pennylane.vn_entropy` """ density_matrix = reduce_dm(state, indices, check_state, c_dtype) entropy = _compute_vn_entropy(density_matrix, base) return entropy def _compute_vn_entropy(density_matrix, base=None): """Compute the Von Neumann entropy from a density matrix Args: density_matrix (tensor_like): ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)`` tensor for an integer `N`. base (float, int): Base for the logarithm. If None, the natural logarithm is used. Returns: float: Von Neumann entropy of the density matrix. **Example** >>> x = [[1/2, 0], [0, 1/2]] >>> _compute_vn_entropy(x) 0.6931472 >>> x = [[1/2, 0], [0, 1/2]] >>> _compute_vn_entropy(x, base=2) 1.0 """ # Change basis if necessary if base: div_base = np.log(base) else: div_base = 1 evs = qml.math.eigvalsh(density_matrix) evs = qml.math.where(evs > 0, evs, 1.0) entropy = qml.math.entr(evs) / div_base return entropy # pylint: disable=too-many-arguments def mutual_info( state, indices0, indices1, base=None, check_state=False, c_dtype="complex128", ): r"""Compute the mutual information between two subsystems given a state: .. math:: I(A, B) = S(\rho^A) + S(\rho^B) - S(\rho^{AB}) where :math:`S` is the von Neumann entropy. The mutual information is a measure of correlation between two subsystems. More specifically, it quantifies the amount of information obtained about one system by measuring the other system. It supports all interfaces (NumPy, Autograd, Torch, TensorFlow and Jax). Each state must be given as a density matrix. To find the mutual information given a pure state, call :func:`~.math.dm_from_state_vector` first. Args: state (tensor_like): ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)`` density matrix. indices0 (list[int]): List of indices in the first subsystem. indices1 (list[int]): List of indices in the second subsystem. base (float): Base for the logarithm. If None, the natural logarithm is used. check_state (bool): If True, the function will check the state validity (shape and norm). c_dtype (str): Complex floating point precision type. Returns: float: Mutual information between the subsystems **Examples** The mutual information between subsystems for a state vector can be returned as follows: >>> x = np.array([1, 0, 0, 1]) / np.sqrt(2) >>> x = qml.math.dm_from_state_vector(x) >>> qml.math.mutual_info(x, indices0=[0], indices1=[1]) 1.3862943611198906 It is also possible to change the log basis. >>> qml.math.mutual_info(x, indices0=[0], indices1=[1], base=2) 2.0 Similarly the quantum state can be provided as a density matrix: >>> y = np.array([[1/2, 1/2, 0, 1/2], [1/2, 0, 0, 0], [0, 0, 0, 0], [1/2, 0, 0, 1/2]]) >>> qml.math.mutual_info(y, indices0=[0], indices1=[1]) 0.4682351577408206 .. seealso:: :func:`~.math.vn_entropy`, :func:`pennylane.qinfo.transforms.mutual_info` and :func:`pennylane.mutual_info` """ # the subsystems cannot overlap if len([index for index in indices0 if index in indices1]) > 0: raise ValueError("Subsystems for computing mutual information must not overlap.") return _compute_mutual_info( state, indices0, indices1, base=base, check_state=check_state, c_dtype=c_dtype, ) # pylint: disable=too-many-arguments def _compute_mutual_info( state, indices0, indices1, base=None, check_state=False, c_dtype="complex128", ): """Compute the mutual information between the subsystems.""" all_indices = sorted([*indices0, *indices1]) vn_entropy_1 = vn_entropy( state, indices=indices0, base=base, check_state=check_state, c_dtype=c_dtype, ) vn_entropy_2 = vn_entropy( state, indices=indices1, base=base, check_state=check_state, c_dtype=c_dtype, ) vn_entropy_12 = vn_entropy( state, indices=all_indices, base=base, check_state=check_state, c_dtype=c_dtype, ) return vn_entropy_1 + vn_entropy_2 - vn_entropy_12 def _check_hermitian_operator(operators): """Check the shape, and if the matrix is hermitian.""" dim = operators.shape[-1] if ( len(operators.shape) not in (2, 3) or operators.shape[-2] != dim or not np.log2(dim).is_integer() ): raise ValueError( "Operator matrix must be of shape (2**wires,2**wires) " "or (batch_dim, 2**wires, 2**wires)." ) if len(operators.shape) == 2: operators = qml.math.stack([operators]) if not is_abstract(operators): for ops in operators: conj_trans = np.transpose(np.conj(ops)) if not allclose(ops, conj_trans): raise ValueError("The matrix is not Hermitian.") def expectation_value( operator_matrix, state_vector, check_state=False, check_operator=False, c_dtype="complex128" ): r"""Compute the expectation value of an operator with respect to a pure state. The expectation value is the probabilistic expected result of an experiment. Given a pure state, i.e., a state which can be represented as a single vector :math:`\ket{\psi}` in the Hilbert space, the expectation value of an operator :math:`A` can computed as .. math:: \langle A \rangle_\psi = \bra{\psi} A \ket{\psi} Args: operator_matrix (tensor_like): operator matrix with shape ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)``. state_vector (tensor_like): state vector with shape ``(2**N)`` or ``(batch_dim, 2**N)``. check_state (bool): if True, the function will check the validity of the state vector via its shape and the norm. check_operator (bool): if True, the function will check the validity of the operator via its shape and whether it is hermitian. c_dtype (str): complex floating point precision type. Returns: float: Expectation value of the operator for the state vector. **Example** The expectation value for any operator can obtained by passing their matrix representation as an argument. For example, for a 2 qubit state, we can compute the expectation value of the operator :math:`Z \otimes I` as >>> import pennylane as qml >>> import numpy as np >>> state_vector = [1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0] >>> operator_matrix = qml.matrix(qml.PauliZ(0), wire_order=[0, 1]) >>> qml.math.expectation_value(operator_matrix, state_vector) tensor(-2.23711432e-17+0.j, requires_grad=True) .. seealso:: :func:`pennylane.math.fidelity` """ state_vector = cast(state_vector, dtype=c_dtype) operator_matrix = cast(operator_matrix, dtype=c_dtype) if check_state: _check_state_vector(state_vector) if check_operator: _check_hermitian_operator(operator_matrix) if qml.math.shape(operator_matrix)[-1] != qml.math.shape(state_vector)[-1]: raise qml.QuantumFunctionError( "The operator and the state vector must have the same number of wires." ) # The overlap <psi|A|psi> expval = qml.math.einsum( "...i,...i->...", qml.math.conj(state_vector), qml.math.einsum("...ji,...i->...j", operator_matrix, state_vector, optimize="greedy"), optimize="greedy", ) return expval # pylint: disable=too-many-arguments def vn_entanglement_entropy( state, indices0, indices1, base=None, check_state=False, c_dtype="complex128" ): r"""Compute the Von Neumann entanglement entropy between two subsystems in a given state. .. math:: S(\rho_A) = -\text{Tr}[\rho_A \log \rho_A] = -\text{Tr}[\rho_B \log \rho_B] = S(\rho_B) where :math:`S` is the von Neumann entropy, and :math:`\rho_A = \text{Tr}_B [\rho_{AB}]` and :math:`\rho_B = \text{Tr}_A [\rho_{AB}]` are the reduced density matrices for each partition. The Von Neumann entanglement entropy is a measure of the degree of quantum entanglement between two subsystems constituting a pure bipartite quantum state. The entropy of entanglement is the Von Neumann entropy of the reduced density matrix for any of the subsystems. If it is non-zero, it indicates the two subsystems are entangled. Each state must be given as a density matrix. To find the mutual information given a pure state, call :func:`~.math.dm_from_state_vector` first. Args: state (tensor_like): ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)`` density matrix. indices0 (list[int]): Indices of the qubits in the first subsystem. indices1 (list[int]): Indices of the qubits in the second subsystem. base (float): Base for the logarithm. If ``None``, the natural logarithm is used. check_state (bool): If True, the function will check the state validity (shape and norm). c_dtype (str): Complex floating point precision type. Returns: float: The von Neumann entanglement entropy of the bipartite state. **Examples** The entanglement entropy between subsystems for a state vector can be returned as follows: >>> x = np.array([0, -1, 1, 0]) / np.sqrt(2) >>> x = qml.math.dm_from_state_vector(x) >>> qml.math.vn_entanglement_entropy(x, indices0=[0], indices1=[1]) 0.6931471805599453 It is also possible to change the logarithm base: >>> qml.math.vn_entanglement_entropy(x, indices0=[0], indices1=[1], base=2) 1 Similarly, the quantum state can be provided as a density matrix: >>> y = np.array([[1, 1, -1, -1], [1, 1, -1, -1], [-1, -1, 1, 1], [-1, -1, 1, 1]]) * 0.25 >>> qml.math.vn_entanglement_entropy(y, indices0=[0], indices1=[1]) 0 """ # The subsystems cannot overlap if len([index for index in indices0 if index in indices1]) > 0: raise ValueError("Subsystems for computing the entanglement entropy must not overlap.") return _compute_vn_entanglement_entropy( state, indices0, indices1, base=base, check_state=check_state, c_dtype=c_dtype ) def _compute_vn_entanglement_entropy( state, indices0, _, base=None, check_state=False, c_dtype="complex128" ): """Computes the Von Neumann entanglement entropy between the subsystems.""" vn_entropy_1 = vn_entropy( state, indices=indices0, base=base, check_state=check_state, c_dtype=c_dtype ) # The Von Neumann entropy of the two subsystems should be the same if the overall state is a # pure state. Here we trust that the user only uses this function for pure states, and do not # perform any checks so that the code is compatible with jax.jit return vn_entropy_1 def sqrt_matrix(density_matrix): r"""Compute the square root matrix of a density matrix where :math:`\rho = \sqrt{\rho} \times \sqrt{\rho}` Args: density_matrix (tensor_like): 2D or 3D (with batching) density matrix of the quantum system. Returns: (tensor_like): Square root of the density matrix. """ evs, vecs = qml.math.linalg.eigh(density_matrix) evs = qml.math.real(evs) evs = qml.math.where(evs > 0.0, evs, 0.0) if not is_abstract(evs): evs = qml.math.cast_like(evs, vecs) shape = qml.math.shape(density_matrix) if len(shape) > 2: # broadcasting case i = qml.math.cast_like(qml.math.convert_like(qml.math.eye(shape[-1]), evs), evs) sqrt_evs = qml.math.expand_dims(qml.math.sqrt(evs), 1) * i return vecs @ sqrt_evs @ qml.math.conj(qml.math.transpose(vecs, (0, 2, 1))) return vecs @ qml.math.diag(qml.math.sqrt(evs)) @ qml.math.conj(qml.math.transpose(vecs)) def _compute_relative_entropy(rho, sigma, base=None): r""" Compute the quantum relative entropy of density matrix rho with respect to sigma. .. math:: S(\rho\,\|\,\sigma)=-\text{Tr}(\rho\log\sigma)-S(\rho)=\text{Tr}(\rho\log\rho)-\text{Tr}(\rho\log\sigma) =\text{Tr}(\rho(\log\rho-\log\sigma)) where :math:`S` is the von Neumann entropy. """ if base: div_base = np.log(base) else: div_base = 1 evs_rho, u_rho = qml.math.linalg.eigh(rho) evs_sig, u_sig = qml.math.linalg.eigh(sigma) # cast all eigenvalues to real evs_rho, evs_sig = np.real(evs_rho), np.real(evs_sig) # zero eigenvalues need to be treated very carefully here # we use the convention that 0 * log(0) = 0 evs_sig = qml.math.where(evs_sig == 0, 0.0, evs_sig) rho_nonzero_mask = qml.math.where(evs_rho == 0.0, False, True) ent = qml.math.entr(qml.math.where(rho_nonzero_mask, evs_rho, 1.0)) # whether the inputs are batched rho_batched = len(qml.math.shape(rho)) > 2 sig_batched = len(qml.math.shape(sigma)) > 2 indices_rho = "abc" if rho_batched else "bc" indices_sig = "abd" if sig_batched else "bd" target = "acd" if rho_batched or sig_batched else "cd" # the matrix of inner products between eigenvectors of rho and eigenvectors # of sigma; this is a doubly stochastic matrix rel = qml.math.einsum( f"{indices_rho},{indices_sig}->{target}", np.conj(u_rho), u_sig, optimize="greedy", ) rel = np.abs(rel) ** 2 if sig_batched: evs_sig = qml.math.expand_dims(evs_sig, 1) rel = qml.math.sum(qml.math.where(rel == 0.0, 0.0, np.log(evs_sig) * rel), -1) rel = -qml.math.sum(qml.math.where(rho_nonzero_mask, evs_rho * rel, 0.0), -1) return (rel - ent) / div_base def relative_entropy(state0, state1, base=None, check_state=False, c_dtype="complex128"): r""" Compute the quantum relative entropy of one state with respect to another. .. math:: S(\rho\,\|\,\sigma)=-\text{Tr}(\rho\log\sigma)-S(\rho)=\text{Tr}(\rho\log\rho)-\text{Tr}(\rho\log\sigma) =\text{Tr}(\rho(\log\rho-\log\sigma)) Roughly speaking, quantum relative entropy is a measure of distinguishability between two quantum states. It is the quantum mechanical analog of relative entropy. Each state must be given as a density matrix. To find the relative entropy given a pure state, call :func:`~.math.dm_from_state_vector` first. Args: state0 (tensor_like): ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)`` density matrix. state1 (tensor_like): ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)`` density matrix. base (float): Base for the logarithm. If None, the natural logarithm is used. check_state (bool): If True, the function will check the state validity (shape and norm). c_dtype (str): Complex floating point precision type. Returns: float: Quantum relative entropy of state0 with respect to state1 **Examples** The relative entropy between two equal states is always zero: >>> x = np.array([1, 0]) >>> x = qml.math.dm_from_state_vector(x) >>> qml.math.relative_entropy(x, x) 0.0 and the relative entropy between two non-equal pure states is always infinity: >>> y = np.array([1, 1]) / np.sqrt(2) >>> y = qml.math.dm_from_state_vector(y) >>> qml.math.relative_entropy(x, y) inf The quantum states can be provided as density matrices, allowing for computation of relative entropy between mixed states: >>> rho = np.array([[0.3, 0], [0, 0.7]]) >>> sigma = np.array([[0.5, 0], [0, 0.5]]) >>> qml.math.relative_entropy(rho, sigma) 0.08228288 It is also possible to change the log base: >>> qml.math.relative_entropy(rho, sigma, base=2) 0.1187091 .. seealso:: :func:`pennylane.qinfo.transforms.relative_entropy` """ # Cast as a c_dtype array state0 = cast(state0, dtype=c_dtype) # Cannot be cast_like if jit if not is_abstract(state0): state1 = cast_like(state1, state0) if check_state: # pylint: disable=expression-not-assigned _check_density_matrix(state0) _check_density_matrix(state1) # Compare the number of wires on both subsystems if qml.math.shape(state0)[-1] != qml.math.shape(state1)[-1]: raise qml.QuantumFunctionError("The two states must have the same number of wires.") return _compute_relative_entropy(state0, state1, base=base) def _check_density_matrix(density_matrix): """Check the shape, the trace and the positive semi-definitiveness of a matrix.""" dim = density_matrix.shape[-1] if ( len(density_matrix.shape) not in (2, 3) or density_matrix.shape[-2] != dim or not np.log2(dim).is_integer() ): raise ValueError("Density matrix must be of shape (2**N, 2**N) or (batch_dim, 2**N, 2**N).") if len(density_matrix.shape) == 2: density_matrix = qml.math.stack([density_matrix]) if not is_abstract(density_matrix): for dm in density_matrix: # Check trace trace = np.trace(dm) if not allclose(trace, 1.0, atol=1e-10): raise ValueError("The trace of the density matrix should be one.") # Check if the matrix is Hermitian conj_trans = np.transpose(np.conj(dm)) if not allclose(dm, conj_trans): raise ValueError("The matrix is not Hermitian.") # Check if positive semi-definite evs, _ = qml.math.linalg.eigh(dm) evs = np.real(evs) evs_non_negative = [ev for ev in evs if ev >= -1e-7] if len(evs) != len(evs_non_negative): raise ValueError("The matrix is not positive semi-definite.") def _check_state_vector(state_vector): """Check the shape and the norm of a state vector.""" dim = state_vector.shape[-1] if len(np.shape(state_vector)) not in (1, 2) or not np.log2(dim).is_integer(): raise ValueError("State vector must be of shape (2**wires,) or (batch_dim, 2**wires)") if len(state_vector.shape) == 1: state_vector = qml.math.stack([state_vector]) # Check norm if not is_abstract(state_vector): for sv in state_vector: norm = np.linalg.norm(sv, ord=2) if not allclose(norm, 1.0, atol=1e-10): raise ValueError("Sum of amplitudes-squared does not equal one.") def max_entropy(state, indices, base=None, check_state=False, c_dtype="complex128"): r"""Compute the maximum entropy of a density matrix on a given subsystem. It supports all interfaces (NumPy, Autograd, Torch, TensorFlow and Jax). .. math:: S_{\text{max}}( \rho ) = \log( \text{rank} ( \rho )) Args: state (tensor_like): Density matrix of shape ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)``. indices (list(int)): List of indices in the considered subsystem. base (float): Base for the logarithm. If None, the natural logarithm is used. check_state (bool): If True, the function will check the state validity (shape and norm). c_dtype (str): Complex floating point precision type. Returns: float: The maximum entropy of the considered subsystem. **Example** The maximum entropy of a subsystem for any state vector can be obtained by first calling :func:`~.math.dm_from_state_vector` on the input. Here is an example for the maximally entangled state, where the subsystem entropy is maximal (default base for log is exponential). >>> x = [1, 0, 0, 1] / np.sqrt(2) >>> x = dm_from_state_vector(x) >>> max_entropy(x, indices=[0]) 0.6931472 The logarithm base can be changed. For example: >>> max_entropy(x, indices=[0], base=2) 1.0 The maximum entropy can be obtained by providing a quantum state as a density matrix. For example: >>> y = [[1/2, 0, 0, 1/2], [0, 0, 0, 0], [0, 0, 0, 0], [1/2, 0, 0, 1/2]] >>> max_entropy(y, indices=[0]) 0.6931472 The maximum entropy is always greater or equal to the Von Neumann entropy. In this maximally entangled example, they are equal: >>> vn_entropy(x, indices=[0]) 0.6931472 However, in general, the Von Neumann entropy is lower: >>> x = [np.cos(np.pi/8), 0, 0, -1j*np.sin(np.pi/8)] >>> x = dm_from_state_vector(x) >>> vn_entropy(x, indices=[1]) 0.4164955 >>> max_entropy(x, indices=[1]) 0.6931472 """ density_matrix = reduce_dm(state, indices, check_state, c_dtype) maximum_entropy = _compute_max_entropy(density_matrix, base) return maximum_entropy def _compute_max_entropy(density_matrix, base): """Compute the maximum entropy from a density matrix Args: density_matrix (tensor_like): ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)`` tensor for an integer `N`. base (float, int): Base for the logarithm. If None, the natural logarithm is used. Returns: float: Maximum entropy of the density matrix. **Example** >>> x = [[1/2, 0], [0, 1/2]] >>> _compute_max_entropy(x) 0.6931472 >>> x = [[1/2, 0], [0, 1/2]] >>> _compute_max_entropy(x, base=2) 1.0 """ # Change basis if necessary if base: div_base = np.log(base) else: div_base = 1 evs = qml.math.eigvalsh(density_matrix) evs = qml.math.real(evs) rank = qml.math.sum(evs / qml.math.where(evs > 1e-8, evs, 1.0), -1) maximum_entropy = qml.math.log(rank) / div_base return maximum_entropy def min_entropy(state, indices, base=None, check_state=False, c_dtype="complex128"): r"""Compute the minimum entropy from a density matrix. .. math:: S_{\text{min}}( \rho ) = -\log( \max_{i} ( p_{i} )) Args: state (tensor_like): Density matrix of shape ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)``. indices (list(int)): List of indices in the considered subsystem. base (float): Base for the logarithm. If None, the natural logarithm is used. check_state (bool): If True, the function will check the state validity (shape and norm). c_dtype (str): Complex floating point precision type. Returns: float: The minimum entropy of the considered subsystem. **Example** The minimum entropy of a subsystem for any state vector can be obtained by first calling :func:`~.math.dm_from_state_vector` on the input. Here is an example for the maximally entangled state, where the subsystem entropy is maximal (default base for log is exponential). >>> x = [1, 0, 0, 1] / np.sqrt(2) >>> x = dm_from_state_vector(x) >>> min_entropy(x, indices=[0]) 0.6931472 The logarithm base can be changed. For example: >>> min_entropy(x, indices=[0], base=2) 1.0 The minimum entropy can be obtained by providing a quantum state as a density matrix. For example: >>> y = [[1/2, 0, 0, 1/2], [0, 0, 0, 0], [0, 0, 0, 0], [1/2, 0, 0, 1/2]] >>> min_entropy(y, indices=[0]) 0.6931472 The Von Neumann entropy is always greater than the minimum entropy. >>> x = [np.cos(np.pi/8), 0, 0, -1j*np.sin(np.pi/8)] >>> x = dm_from_state_vector(x) >>> vn_entropy(x, indices=[1]) 0.4164955 >>> min_entropy(x, indices=[1]) 0.1583472 """ density_matrix = reduce_dm(state, indices, check_state, c_dtype) minimum_entropy = _compute_min_entropy(density_matrix, base) return minimum_entropy def _compute_min_entropy(density_matrix, base): r"""Compute the minimum entropy from a density matrix Args: density_matrix (tensor_like): ``(2**N, 2**N)`` tensor density matrix for an integer `N`. base (float, int): Base for the logarithm. If None, the natural logarithm is used. Returns: float: Minimum entropy of the density matrix. **Example** >>> x = [[1/2, 0], [0, 1/2]] >>> _compute_min_entropy(x) 0.6931472 >>> x = [[1/2, 0], [0, 1/2]] >>> _compute_min_entropy(x, base=2) 1.0 """ # Change basis if necessary div_base = np.log(base) if base else 1 evs, _ = qml.math.linalg.eigh(density_matrix) evs = qml.math.real(evs) minimum_entropy = -qml.math.log(qml.math.max(evs)) / div_base return minimum_entropy def trace_distance(state0, state1, check_state=False, c_dtype="complex128"): r""" Compute the trace distance between two quantum states. .. math:: T(\rho, \sigma)=\frac12\|\rho-\sigma\|_1 =\frac12\text{Tr}\left(\sqrt{(\rho-\sigma)^{\dagger}(\rho-\sigma)}\right) where :math:`\|\cdot\|_1` is the Schatten :math:`1`-norm. The trace distance measures how close two quantum states are. In particular, it upper-bounds the probability of distinguishing two quantum states. Args: state0 (tensor_like): ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)`` density matrix. state1 (tensor_like): ``(2**N, 2**N)`` or ``(batch_dim, 2**N, 2**N)`` density matrix. check_state (bool): If True, the function will check the states' validity (shape and norm). c_dtype (str): Complex floating point precision type. Returns: float: Trace distance between state0 and state1 **Examples** The trace distance between two equal states is always zero: >>> x = np.array([[1, 0], [0, 0]]) >>> qml.math.trace_distance(x, x) 0.0 It is possible to use state vectors by first transforming them into density matrices via the :func:`~reduce_statevector` function: >>> y = qml.math.reduce_statevector(np.array([0.2, np.sqrt(0.96)]), [0]) >>> qml.math.trace_distance(x, y) 0.9797958971132713 The quantum states can also be provided as batches of density matrices: >>> batch0 = np.array([np.eye(2) / 2, np.ones((2, 2)) / 2, np.array([[1, 0],[0, 0]])]) >>> batch1 = np.array([np.ones((2, 2)) / 2, np.ones((2, 2)) / 2, np.array([[1, 0],[0, 0]])]) >>> qml.math.trace_distance(batch0, batch1) array([0.5, 0. , 0. ]) If only one of the two states represent a single element, then the trace distances are taken with respect to that element: >>> rho = np.ones((2, 2)) / 2 >>> qml.math.trace_distance(rho, batch0) array([0.5 , 0. , 0.70710678]) .. seealso:: :func:`pennylane.qinfo.transforms.trace_distance` """ # Cast as a c_dtype array state0 = cast(state0, dtype=c_dtype) # Cannot be cast_like if jit if not is_abstract(state0): state1 = cast_like(state1, state0) if check_state: _check_density_matrix(state0) _check_density_matrix(state1) if state0.shape[-1] != state1.shape[-1]: raise qml.QuantumFunctionError("The two states must have the same number of wires.") if len(state0.shape) == len(state1.shape) == 3 and state0.shape[0] != state1.shape[0]: raise ValueError( "The two states must be batches of the same size, or one of them must contain a single " "element." ) eigvals = qml.math.abs(qml.math.eigvalsh(state0 - state1)) return qml.math.sum(eigvals, axis=-1) / 2
pennylane/pennylane/math/quantum.py/0
{ "file_path": "pennylane/pennylane/math/quantum.py", "repo_id": "pennylane", "token_count": 21396 }
52
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. # pylint: disable=protected-access """ This module contains the qml.vn_entropy measurement. """ from collections.abc import Sequence from typing import Optional import pennylane as qml from pennylane.wires import Wires from .measurements import StateMeasurement, VnEntropy def vn_entropy(wires, log_base=None) -> "VnEntropyMP": r"""Von Neumann entropy of the system prior to measurement. .. math:: S( \rho ) = -\text{Tr}( \rho \log ( \rho )) Args: wires (Sequence[int] or int): The wires of the subsystem log_base (float): Base for the logarithm. Returns: VnEntropyMP: Measurement process instance **Example:** .. code-block:: python3 dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit_entropy(x): qml.IsingXX(x, wires=[0, 1]) return qml.vn_entropy(wires=[0]) Executing this QNode: >>> circuit_entropy(np.pi/2) 0.6931472 It is also possible to get the gradient of the previous QNode: >>> param = np.array(np.pi/4, requires_grad=True) >>> qml.grad(circuit_entropy)(param) tensor(0.62322524, requires_grad=True) .. note:: Calculating the derivative of :func:`~.vn_entropy` is currently supported when using the classical backpropagation differentiation method (``diff_method="backprop"``) with a compatible device and finite differences (``diff_method="finite-diff"``). .. seealso:: :func:`pennylane.qinfo.transforms.vn_entropy` and :func:`pennylane.math.vn_entropy` """ wires = Wires(wires) return VnEntropyMP(wires=wires, log_base=log_base) class VnEntropyMP(StateMeasurement): """Measurement process that computes the Von Neumann entropy of the system prior to measurement. Please refer to :func:`vn_entropy` for detailed documentation. Args: wires (.Wires): The wires the measurement process applies to. This can only be specified if an observable was not provided. id (str): custom label given to a measurement instance, can be useful for some applications where the instance has to be identified log_base (float): Base for the logarithm. """ def _flatten(self): metadata = (("wires", self.raw_wires), ("log_base", self.log_base)) return (None, None), metadata # pylint: disable=too-many-arguments, unused-argument def __init__( self, wires: Optional[Wires] = None, id: Optional[str] = None, log_base: Optional[float] = None, ): self.log_base = log_base super().__init__(wires=wires, id=id) @property def hash(self): """int: returns an integer hash uniquely representing the measurement process""" fingerprint = (self.__class__.__name__, tuple(self.wires.tolist()), self.log_base) return hash(fingerprint) @property def return_type(self): return VnEntropy @property def numeric_type(self): return float def shape(self, shots: Optional[int] = None, num_device_wires: int = 0) -> tuple: return () def process_state(self, state: Sequence[complex], wire_order: Wires): state = qml.math.dm_from_state_vector(state) return qml.math.vn_entropy( state, indices=self.wires, c_dtype=state.dtype, base=self.log_base )
pennylane/pennylane/measurements/vn_entropy.py/0
{ "file_path": "pennylane/pennylane/measurements/vn_entropy.py", "repo_id": "pennylane", "token_count": 1498 }
53
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # 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. """ This module contains the qml.bind_new_parameters function. """ # pylint: disable=missing-docstring import copy from collections.abc import Sequence from functools import singledispatch from typing import Union import pennylane as qml from pennylane.operation import Operator, Tensor from pennylane.typing import TensorLike from ..identity import Identity from ..op_math import Adjoint, CompositeOp, Pow, ScalarSymbolicOp, SProd, SymbolicOp from ..qubit import Projector @singledispatch def bind_new_parameters(op: Operator, params: Sequence[TensorLike]) -> Operator: """Create a new operator with updated parameters This function takes an :class:`~.Operator` and new parameters as input and returns a new operator of the same type with the new parameters. This function does not mutate the original operator. Args: op (.Operator): Operator to update params (Sequence[TensorLike]): New parameters to create operator with. This must have the same shape as `op.data`. Returns: .Operator: New operator with updated parameters """ try: return op.__class__(*params, wires=op.wires, **copy.deepcopy(op.hyperparameters)) except (TypeError, ValueError): # operation is doing something different with its call signature. new_op = copy.deepcopy(op) new_op.data = tuple(params) return new_op @bind_new_parameters.register def bind_new_parameters_approx_time_evolution( op: qml.ApproxTimeEvolution, params: Sequence[TensorLike] ): new_hamiltonian = bind_new_parameters(op.hyperparameters["hamiltonian"], params[:-1]) time = params[-1] n = op.hyperparameters["n"] return qml.ApproxTimeEvolution(new_hamiltonian, time, n) @bind_new_parameters.register def bind_new_parameters_commuting_evolution( op: qml.CommutingEvolution, params: Sequence[TensorLike] ): new_hamiltonian = bind_new_parameters(op.hyperparameters["hamiltonian"], params[1:]) freq = op.hyperparameters["frequencies"] shifts = op.hyperparameters["shifts"] time = params[0] return qml.CommutingEvolution(new_hamiltonian, time, frequencies=freq, shifts=shifts) @bind_new_parameters.register def bind_new_parameters_qdrift(op: qml.QDrift, params: Sequence[TensorLike]): new_hamiltonian = bind_new_parameters(op.hyperparameters["base"], params[:-1]) time = params[-1] n = op.hyperparameters["n"] seed = op.hyperparameters["seed"] return qml.QDrift(new_hamiltonian, time, n=n, seed=seed) @bind_new_parameters.register def bind_new_parameters_fermionic_double_excitation( op: qml.FermionicDoubleExcitation, params: Sequence[TensorLike] ): wires1 = op.hyperparameters["wires1"] wires2 = op.hyperparameters["wires2"] return qml.FermionicDoubleExcitation(params[0], wires1=wires1, wires2=wires2) @bind_new_parameters.register def bind_new_parameters_angle_embedding(op: qml.AngleEmbedding, params: Sequence[TensorLike]): rotation = op.hyperparameters["rotation"].basis return qml.AngleEmbedding(params[0], wires=op.wires, rotation=rotation) @bind_new_parameters.register def bind_new_parameters_identity(op: Identity, params: Sequence[TensorLike]): return qml.Identity(*params, wires=op.wires) @bind_new_parameters.register def bind_new_parameters_linear_combination( op: qml.ops.LinearCombination, params: Sequence[TensorLike] ): new_coeffs, new_ops = [], [] i = 0 for o in op.ops: new_coeffs.append(params[i]) i += 1 if o.data: sub_data = params[i : i + len(o.data)] new_ops.append(bind_new_parameters(o, sub_data)) i += len(sub_data) else: new_ops.append(o) new_H = qml.ops.LinearCombination(new_coeffs, new_ops) if op.grouping_indices is not None: new_H.grouping_indices = op.grouping_indices return new_H @bind_new_parameters.register def bind_new_parameters_composite_op(op: CompositeOp, params: Sequence[TensorLike]): new_operands = [] for operand in op.operands: op_num_params = operand.num_params sub_params = params[:op_num_params] params = params[op_num_params:] new_operands.append(bind_new_parameters(operand, sub_params)) return op.__class__(*new_operands) @bind_new_parameters.register(qml.CY) @bind_new_parameters.register(qml.CZ) @bind_new_parameters.register(qml.CH) @bind_new_parameters.register(qml.CCZ) @bind_new_parameters.register(qml.CSWAP) @bind_new_parameters.register(qml.CNOT) @bind_new_parameters.register(qml.Toffoli) @bind_new_parameters.register(qml.MultiControlledX) def bind_new_parameters_copy(op, params: Sequence[TensorLike]): # pylint:disable=unused-argument return copy.copy(op) @bind_new_parameters.register(qml.CRX) @bind_new_parameters.register(qml.CRY) @bind_new_parameters.register(qml.CRZ) @bind_new_parameters.register(qml.CRot) @bind_new_parameters.register(qml.ControlledPhaseShift) def bind_new_parameters_parametric_controlled_ops( op: Union[qml.CRX, qml.CRY, qml.CRZ, qml.CRot, qml.ControlledPhaseShift], params: Sequence[TensorLike], ): return op.__class__(*params, wires=op.wires) @bind_new_parameters.register def bind_new_parameters_symbolic_op(op: SymbolicOp, params: Sequence[TensorLike]): new_base = bind_new_parameters(op.base, params) new_hyperparameters = copy.deepcopy(op.hyperparameters) _ = new_hyperparameters.pop("base") return op.__class__(new_base, **new_hyperparameters) @bind_new_parameters.register def bind_new_parameters_controlled_sequence( op: qml.ControlledSequence, params: Sequence[TensorLike] ): new_base = bind_new_parameters(op.base, params) return op.__class__(new_base, control=op.control) @bind_new_parameters.register def bind_new_parameters_adjoint(op: Adjoint, params: Sequence[TensorLike]): # Need a separate dispatch for `Adjoint` because using a more general class # signature results in a call to `Adjoint.__new__` which doesn't raise an # error but does return an unusable object. return Adjoint(bind_new_parameters(op.base, params)) @bind_new_parameters.register def bind_new_parameters_projector(op: Projector, params: Sequence[TensorLike]): # Need a separate dispatch for `Projector` because using a more general class # signature results in a call to `Projector.__new__` which doesn't raise an # error but does return an unusable object. return Projector(*params, wires=op.wires) @bind_new_parameters.register def bind_new_parameters_scalar_symbolic_op(op: ScalarSymbolicOp, params: Sequence[TensorLike]): new_scalar = params[0] params = params[1:] new_base = bind_new_parameters(op.base, params) new_hyperparameters = copy.deepcopy(op.hyperparameters) _ = new_hyperparameters.pop("base") return op.__class__(new_base, new_scalar, **new_hyperparameters) @bind_new_parameters.register def bind_new_parameters_sprod(op: SProd, params: Sequence[TensorLike]): # Separate dispatch for `SProd` since its constructor has a different interface new_scalar = params[0] params = params[1:] new_base = bind_new_parameters(op.base, params) return SProd(new_scalar, new_base) @bind_new_parameters.register def bind_new_parameters_pow(op: Pow, params: Sequence[TensorLike]): # Need a separate dispatch for `Pow` because using a more general class # signature results in a call to `Pow.__new__` which doesn't raise an # error but does return an unusable object. return Pow(bind_new_parameters(op.base, params), op.scalar) @bind_new_parameters.register def bind_new_parameters_hamiltonian(op: qml.ops.Hamiltonian, params: Sequence[TensorLike]): new_H = qml.ops.Hamiltonian(params, op.ops) if op.grouping_indices is not None: new_H.grouping_indices = op.grouping_indices return new_H @bind_new_parameters.register def bind_new_parameters_tensor(op: Tensor, params: Sequence[TensorLike]): new_obs = [] for obs in op.obs: sub_params = params[: obs.num_params] params = params[obs.num_params :] new_obs.append(bind_new_parameters(obs, sub_params)) return Tensor(*new_obs) @bind_new_parameters.register def bind_new_parameters_conditional(op: qml.ops.Conditional, params: Sequence[TensorLike]): then_op = bind_new_parameters(op.base, params) mv = copy.deepcopy(op.meas_val) return qml.ops.Conditional(mv, then_op)
pennylane/pennylane/ops/functions/bind_new_parameters.py/0
{ "file_path": "pennylane/pennylane/ops/functions/bind_new_parameters.py", "repo_id": "pennylane", "token_count": 3350 }
54
# Copyright 2018-2022 Xanadu Quantum Technologies Inc. # 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. """ This module contains classes and functions for Operator arithmetic. Constructor Functions ~~~~~~~~~~~~~~~~~~~~~ .. currentmodule:: pennylane .. autosummary:: :toctree: api ~adjoint ~ctrl ~cond ~exp ~sum ~pow ~prod ~s_prod Symbolic Classes ~~~~~~~~~~~~~~~~ .. currentmodule:: pennylane.ops.op_math .. autosummary:: :toctree: api ~Adjoint ~CompositeOp ~Conditional ~Controlled ~ControlledOp ~Evolution ~Exp ~LinearCombination ~Pow ~Prod ~Sum ~SProd ~SymbolicOp ~ScalarSymbolicOp Controlled Operator Classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. currentmodule:: pennylane .. autosummary:: :toctree: api ~ControlledQubitUnitary ~CY ~CZ ~CH ~CCZ ~CSWAP ~CNOT ~Toffoli ~MultiControlledX ~CRX ~CRY ~CRZ ~CRot ~ControlledPhaseShift Decompositions ~~~~~~~~~~~~~~ .. currentmodule:: pennylane.ops .. autosummary:: :toctree: api ~one_qubit_decomposition ~two_qubit_decomposition ~sk_decomposition Control Decompositions ~~~~~~~~~~~~~~~~~~~~~~ .. currentmodule:: pennylane.ops.op_math .. autosummary:: :toctree: api ~ctrl_decomp_zyz ~ctrl_decomp_bisect """ from .adjoint import Adjoint, adjoint from .composite import CompositeOp from .condition import Conditional, cond from .controlled import Controlled, ControlledOp, ctrl from .controlled_decompositions import ctrl_decomp_bisect, ctrl_decomp_zyz from .controlled_ops import ( CCZ, CH, CNOT, CRX, CRY, CRZ, CSWAP, CY, CZ, ControlledPhaseShift, ControlledQubitUnitary, CPhase, CRot, MultiControlledX, Toffoli, ) from .decompositions import one_qubit_decomposition, sk_decomposition, two_qubit_decomposition from .evolution import Evolution from .exp import Exp, exp from .linear_combination import LinearCombination from .pow import Pow, pow from .prod import Prod, prod from .sprod import SProd, s_prod from .sum import Sum, sum from .symbolicop import ScalarSymbolicOp, SymbolicOp controlled_qubit_ops = { "ControlledQubitUnitary", "CY", "CZ", "CH", "CCZ", "CSWAP", "CNOT", "Toffoli", "MultiControlledX", "CRX", "CRY", "CRZ", "CRot", "ControlledPhaseShift", "CPhase", }
pennylane/pennylane/ops/op_math/__init__.py/0
{ "file_path": "pennylane/pennylane/ops/op_math/__init__.py", "repo_id": "pennylane", "token_count": 1145 }
55
# Copyright 2018-2022 Xanadu Quantum Technologies Inc. # 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. """ This file contains the implementation of the SProd class which contains logic for computing the scalar product of operations. """ from copy import copy from typing import Union import pennylane as qml import pennylane.math as qnp from pennylane.operation import Operator, TermsUndefinedError, convert_to_opmath from pennylane.ops.op_math.pow import Pow from pennylane.ops.op_math.sum import Sum from pennylane.queuing import QueuingManager from .symbolicop import ScalarSymbolicOp def s_prod(scalar, operator, lazy=True, id=None): r"""Construct an operator which is the scalar product of the given scalar and operator provided. Args: scalar (float or complex): the scale factor being multiplied to the operator. operator (~.operation.Operator): the operator which will get scaled. Keyword Args: lazy=True (bool): If ``lazy=False`` and the operator is already a scalar product operator, the scalar provided will simply be combined with the existing scaling factor. id (str or None): id for the scalar product operator. Default is None. Returns: ~ops.op_math.SProd: The operator representing the scalar product. .. note:: This operator supports a batched base, a batched coefficient and a combination of both: >>> op = qml.s_prod(scalar=4, operator=qml.RX([1, 2, 3], wires=0)) >>> qml.matrix(op).shape (3, 2, 2) >>> op = qml.s_prod(scalar=[1, 2, 3], operator=qml.RX(1, wires=0)) >>> qml.matrix(op).shape (3, 2, 2) >>> op = qml.s_prod(scalar=[4, 5, 6], operator=qml.RX([1, 2, 3], wires=0)) >>> qml.matrix(op).shape (3, 2, 2) But it doesn't support batching of operators: >>> op = qml.s_prod(scalar=4, operator=[qml.RX(1, wires=0), qml.RX(2, wires=0)]) AttributeError: 'list' object has no attribute 'batch_size' .. seealso:: :class:`~.ops.op_math.SProd` and :class:`~.ops.op_math.SymbolicOp` **Example** >>> sprod_op = s_prod(2.0, qml.X(0)) >>> sprod_op 2.0 * X(0) >>> sprod_op.matrix() array([[ 0., 2.], [ 2., 0.]]) """ operator = convert_to_opmath(operator) if lazy or not isinstance(operator, SProd): return SProd(scalar, operator, id=id) sprod_op = SProd(scalar=scalar * operator.scalar, base=operator.base, id=id) QueuingManager.remove(operator) return sprod_op class SProd(ScalarSymbolicOp): r"""Arithmetic operator representing the scalar product of an operator with the given scalar. Args: scalar (float or complex): the scale factor being multiplied to the operator. base (~.operation.Operator): the operator which will get scaled. Keyword Args: id (str or None): id for the scalar product operator. Default is None. .. note:: Currently this operator can not be queued in a circuit as an operation, only measured terminally. .. seealso:: :func:`~.ops.op_math.s_prod` **Example** >>> sprod_op = SProd(1.23, qml.X(0)) >>> sprod_op 1.23 * X(0) >>> qml.matrix(sprod_op) array([[0. , 1.23], [1.23, 0. ]]) >>> sprod_op.terms() ([1.23], [PauliX(wires=[0]]) .. details:: :title: Usage Details The SProd operation can also be measured inside a qnode as an observable. If the circuit is parameterized, then we can also differentiate through the observable. .. code-block:: python dev = qml.device("default.qubit", wires=1) @qml.qnode(dev, diff_method="best") def circuit(scalar, theta): qml.RX(theta, wires=0) return qml.expval(qml.s_prod(scalar, qml.Hadamard(wires=0))) >>> scalar, theta = (1.2, 3.4) >>> qml.grad(circuit, argnum=[0,1])(scalar, theta) (array(-0.68362956), array(0.21683382)) """ _name = "SProd" def _flatten(self): return (self.scalar, self.base), tuple() @classmethod def _unflatten(cls, data, _): return cls(data[0], data[1]) def __init__( self, scalar: Union[int, float, complex], base: Operator, id=None, _pauli_rep=None ): super().__init__(base=base, scalar=scalar, id=id) if _pauli_rep: self._pauli_rep = _pauli_rep elif (base_pauli_rep := getattr(self.base, "pauli_rep", None)) and ( self.batch_size is None ): scalar = copy(self.scalar) pr = {pw: qnp.dot(coeff, scalar) for pw, coeff in base_pauli_rep.items()} self._pauli_rep = qml.pauli.PauliSentence(pr) else: self._pauli_rep = None def __repr__(self): """Constructor-call-like representation.""" if isinstance(self.base, qml.ops.CompositeOp): return f"{self.scalar} * ({self.base})" return f"{self.scalar} * {self.base}" def label(self, decimals=None, base_label=None, cache=None): """The label produced for the SProd op.""" scalar_val = ( f"{self.scalar}" if decimals is None else format(qml.math.toarray(self.scalar), f".{decimals}f") ) return base_label or f"{scalar_val}*{self.base.label(decimals=decimals, cache=cache)}" @property def num_params(self): """Number of trainable parameters that the operator depends on. Usually 1 + the number of trainable parameters for the base op. Returns: int: number of trainable parameters """ return 1 + self.base.num_params def terms(self): r"""Representation of the operator as a linear combination of other operators. .. math:: O = \sum_i c_i O_i A ``TermsUndefinedError`` is raised if no representation by terms is defined. Returns: tuple[list[tensor_like or float], list[.Operation]]: list of coefficients :math:`c_i` and list of operations :math:`O_i` """ try: base_coeffs, base_ops = self.base.terms() return [self.scalar * coeff for coeff in base_coeffs], base_ops except TermsUndefinedError: return [self.scalar], [self.base] @property def is_hermitian(self): """If the base operator is hermitian and the scalar is real, then the scalar product operator is hermitian.""" return self.base.is_hermitian and not qml.math.iscomplex(self.scalar) # pylint: disable=arguments-renamed,invalid-overridden-method @property def has_diagonalizing_gates(self): """Bool: Whether the Operator returns defined diagonalizing gates.""" return self.base.has_diagonalizing_gates def diagonalizing_gates(self): r"""Sequence of gates that diagonalize the operator in the computational basis. Given the eigendecomposition :math:`O = U \Sigma U^{\dagger}` where :math:`\Sigma` is a diagonal matrix containing the eigenvalues, the sequence of diagonalizing gates implements the unitary :math:`U^{\dagger}`. The diagonalizing gates rotate the state into the eigenbasis of the operator. A ``DiagGatesUndefinedError`` is raised if no representation by decomposition is defined. .. seealso:: :meth:`~.Operator.compute_diagonalizing_gates`. Returns: list[.Operator] or None: a list of operators """ return self.base.diagonalizing_gates() def eigvals(self): r"""Return the eigenvalues of the specified operator. This method uses pre-stored eigenvalues for standard observables where possible and stores the corresponding eigenvectors from the eigendecomposition. Returns: array: array containing the eigenvalues of the operator. """ base_eigs = self.base.eigvals() if qml.math.get_interface(self.scalar) == "torch" and self.scalar.requires_grad: base_eigs = qml.math.convert_like(base_eigs, self.scalar) return self.scalar * base_eigs def sparse_matrix(self, wire_order=None): """Computes, by default, a `scipy.sparse.csr_matrix` representation of this Tensor. This is useful for larger qubit numbers, where the dense matrix becomes very large, while consisting mostly of zero entries. Args: wire_order (Iterable): Wire labels that indicate the order of wires according to which the matrix is constructed. If not provided, ``self.wires`` is used. Returns: :class:`scipy.sparse._csr.csr_matrix`: sparse matrix representation """ if self.pauli_rep: # Get the sparse matrix from the PauliSentence representation return self.pauli_rep.to_mat(wire_order=wire_order or self.wires, format="csr") mat = self.base.sparse_matrix(wire_order=wire_order).multiply(self.scalar) mat.eliminate_zeros() return mat @property def has_matrix(self): """Bool: Whether or not the Operator returns a defined matrix.""" return isinstance(self.base, qml.ops.Hamiltonian) or self.base.has_matrix @staticmethod def _matrix(scalar, mat): return scalar * mat @property def _queue_category(self): # don't queue scalar prods as they might not be Unitary! """Used for sorting objects into their respective lists in `QuantumTape` objects. This property is a temporary solution that should not exist long-term and should not be used outside of ``QuantumTape._process_queue``. Returns: None """ return None def pow(self, z): """Returns the operator raised to a given power.""" return [SProd(scalar=self.scalar**z, base=Pow(base=self.base, z=z))] def adjoint(self): """Create an operation that is the adjoint of this one. Adjointed operations are the conjugated and transposed version of the original operation. Adjointed ops are equivalent to the inverted operation for unitary gates. Returns: The adjointed operation. """ return SProd(scalar=qml.math.conjugate(self.scalar), base=qml.adjoint(self.base)) # pylint: disable=too-many-return-statements def simplify(self) -> Operator: """Reduce the depth of nested operators to the minimum. Returns: .Operator: simplified operator """ # try using pauli_rep: if pr := self.pauli_rep: pr.simplify() return pr.operation(wire_order=self.wires) if self.scalar == 1: return self.base.simplify() if isinstance(self.base, SProd): scalar = self.scalar * self.base.scalar if scalar == 1: return self.base.base.simplify() return SProd(scalar=scalar, base=self.base.base.simplify()) new_base = self.base.simplify() if isinstance(new_base, Sum): return Sum( *(SProd(scalar=self.scalar, base=summand).simplify() for summand in new_base) ) if isinstance(new_base, SProd): return SProd(scalar=self.scalar, base=new_base).simplify() return SProd(scalar=self.scalar, base=new_base)
pennylane/pennylane/ops/op_math/sprod.py/0
{ "file_path": "pennylane/pennylane/ops/op_math/sprod.py", "repo_id": "pennylane", "token_count": 4974 }
56
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # 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. # pylint: disable=too-many-arguments """ This module contains the available built-in noisy qutrit quantum channels supported by PennyLane, as well as their conventions. """ import numpy as np from pennylane import math from pennylane.operation import AnyWires, Channel QUDIT_DIM = 3 class QutritDepolarizingChannel(Channel): r""" Single-qutrit symmetrically depolarizing error channel. This channel is modelled by the Kraus matrices generated by the following relationship: .. math:: K_0 = K_{0,0} = \sqrt{1-p} \begin{bmatrix} 1 & 0 & 0\\ 0 & 1 & 0\\ 0 & 0 & 1 \end{bmatrix}, \quad K_{i,j} = \sqrt{\frac{p}{8}}X^iZ^j Where: .. math:: X = \begin{bmatrix} 0 & 1 & 0 \\ 0 & 0 & 1 \\ 1 & 0 & 0 \end{bmatrix}, \quad Z = \begin{bmatrix} 1 & 0 & 0\\ 0 & \omega & 0\\ 0 & 0 & \omega^2 \end{bmatrix} These relations create the following Kraus matrices: .. math:: \begin{matrix} K_0 = K_{0,0} = \sqrt{1-p} \begin{bmatrix} 1 & 0 & 0\\ 0 & 1 & 0\\ 0 & 0 & 1 \end{bmatrix}& K_1 = K_{0,1} = \sqrt{\frac{p}{8}}\begin{bmatrix} 1 & 0 & 0\\ 0 & \omega & 0\\ 0 & 0 & \omega^2 \end{bmatrix}& K_2 = K_{0,2} = \sqrt{\frac{p}{8}}\begin{bmatrix} 1 & 0 & 0\\ 0 & \omega^2 & 0\\ 0 & 0 & \omega \end{bmatrix}\\ K_3 = K_{1,0} = \sqrt{\frac{p}{8}}\begin{bmatrix} 0 & 1 & 0 \\ 0 & 0 & 1 \\ 1 & 0 & 0 \end{bmatrix}& K_4 = K_{1,1} = \sqrt{\frac{p}{8}}\begin{bmatrix} 0 & \omega & 0 \\ 0 & 0 & \omega^2 \\ 1 & 0 & 0 \end{bmatrix}& K_5 = K_{1,2} = \sqrt{\frac{p}{8}}\begin{bmatrix} 0 & \omega^2 & 0 \\ 0 & 0 & \omega \\ 1 & 0 & 0 \end{bmatrix}\\ K_6 = K_{2,0} = \sqrt{\frac{p}{8}}\begin{bmatrix} 0 & 0 & 1 \\ 1 & 0 & 0 \\ 0 & 1 & 0 \end{bmatrix}& K_7 = K_{2,1} = \sqrt{\frac{p}{8}}\begin{bmatrix} 0 & 0 & \omega^2 \\ 1 & 0 & 0 \\ 0 & \omega & 0 \end{bmatrix}& K_8 = K_{2,2} = \sqrt{\frac{p}{8}}\begin{bmatrix} 0 & 0 & \omega \\ 1 & 0 & 0 \\ 0 & \omega^2 & 0 \end{bmatrix} \end{matrix} Where :math:`\omega=\exp(\frac{2\pi}{3})` is the third root of unity, and :math:`p \in [0, 1]` is the depolarization probability, equally divided in the application of all qutrit Pauli operators. .. note:: The Kraus operators :math:`\{K_0 \ldots K_8\}` used are the representations of the single qutrit Pauli group. These Pauli group operators are defined in [`1 <https://doi.org/10.48550/arXiv.quant-ph/9802007>`_] (Eq. 5). The Kraus Matrices we use are adapted from [`2 <https://doi.org/10.48550/arXiv.1905.10481>`_] (Eq. 5). For this definition, please make a note of the following: * For :math:`p = 0`, the channel will be an Identity channel, i.e., a noise-free channel. * For :math:`p = \frac{8}{9}`, the channel will be a fully depolarizing channel. * For :math:`p = 1`, the channel will be a uniform error channel. **Details:** * Number of wires: 1 * Number of parameters: 1 Args: p (float): Each qutrit Pauli operator is applied with probability :math:`\frac{p}{8}` wires (Sequence[int] or int): The wire the channel acts on id (str or None): String representing the operation (optional) """ num_params = 1 num_wires = 1 grad_method = "A" grad_recipe = ([[1, 0, 1], [-1, 0, 0]],) def __init__(self, p, wires, id=None): super().__init__(p, wires=wires, id=id) @staticmethod def compute_kraus_matrices(p): # pylint:disable=arguments-differ r"""Kraus matrices representing the qutrit depolarizing channel. Args: p (float): Each qutrit Pauli gate is applied with probability :math:`\frac{p}{8}` Returns: list (array): list of Kraus matrices **Example** >>> np.round(qml.QutritDepolarizingChannel.compute_kraus_matrices(0.5), 3) array([[[ 0.707+0.j , 0. +0.j , 0. +0.j ], [ 0. +0.j , 0.707+0.j , 0. +0.j ], [ 0. +0.j , 0. +0.j , 0.707+0.j ]], [[ 0.25 +0.j , 0. +0.j , 0. +0.j ], [ 0. +0.j , -0.125+0.217j, 0. +0.j ], [ 0. +0.j , 0. +0.j , -0.125-0.217j]], [[ 0.25 +0.j , 0. +0.j , 0. +0.j ], [ 0. +0.j , -0.125-0.217j, 0. +0.j ], [ 0. +0.j , 0. +0.j , -0.125+0.217j]], [[ 0. +0.j , 0.25 +0.j , 0. +0.j ], [ 0. +0.j , 0. +0.j , 0.25 +0.j ], [ 0.25 +0.j , 0. +0.j , 0. +0.j ]], [[ 0. +0.j , -0.125+0.217j, 0. +0.j ], [ 0. +0.j , 0. +0.j , -0.125-0.217j], [ 0.25 +0.j , 0. +0.j , 0. +0.j ]], [[ 0. +0.j , -0.125-0.217j, 0. +0.j ], [ 0. +0.j , 0. +0.j , -0.125+0.217j], [ 0.25 +0.j , 0. +0.j , 0. +0.j ]], [[ 0. +0.j , 0. +0.j , 0.25 +0.j ], [ 0.25 +0.j , 0. +0.j , 0. +0.j ], [ 0. +0.j , 0.25 +0.j , 0. +0.j ]], [[ 0. +0.j , 0. +0.j , -0.125-0.217j], [ 0.25 +0.j , 0. +0.j , 0. +0.j ], [ 0. +0.j , -0.125+0.217j, 0. +0.j ]], [[ 0. +0.j , 0. +0.j , -0.125+0.217j], [ 0.25 +0.j , 0. +0.j , 0. +0.j ], [ 0. +0.j , -0.125-0.217j, 0. +0.j ]]]) """ if not math.is_abstract(p) and not 0.0 <= p <= 1.0: raise ValueError("p must be in the interval [0,1]") interface = math.get_interface(p) w = math.exp(2j * np.pi / 3) one = 1 z = 0 if interface == "tensorflow": p = math.cast_like(p, 1j) w = math.cast_like(w, p) one = math.cast_like(one, p) z = math.cast_like(z, p) w2 = w**2 # The matrices are explicitly written, not generated to ensure PyTorch differentiation. depolarizing_mats = [ [[one, z, z], [z, w, z], [z, z, w2]], [[one, z, z], [z, w2, z], [z, z, w]], [[z, one, z], [z, z, one], [one, z, z]], [[z, w, z], [z, z, w2], [one, z, z]], [[z, w2, z], [z, z, w], [one, z, z]], [[z, z, one], [one, z, z], [z, one, z]], [[z, z, w2], [one, z, z], [z, w, z]], [[z, z, w], [one, z, z], [z, w2, z]], ] normalization = math.sqrt(p / 8 + math.eps) Ks = [normalization * math.array(m, like=interface) for m in depolarizing_mats] identity = math.sqrt(1 - p + math.eps) * math.array( math.eye(QUDIT_DIM, dtype=complex), like=interface ) return [identity] + Ks class QutritAmplitudeDamping(Channel): r""" Single-qutrit amplitude damping error channel. Interaction with the environment can lead to changes in the state populations of a qutrit. This can be modelled by the qutrit amplitude damping channel with the following Kraus matrices: .. math:: K_0 = \begin{bmatrix} 1 & 0 & 0\\ 0 & \sqrt{1-\gamma_{10}} & 0 \\ 0 & 0 & \sqrt{1-(\gamma_{20}+\gamma_{21})} \end{bmatrix} .. math:: K_1 = \begin{bmatrix} 0 & \sqrt{\gamma_{10}} & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix}, \quad K_2 = \begin{bmatrix} 0 & 0 & \sqrt{\gamma_{20}} \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix}, \quad K_3 = \begin{bmatrix} 0 & 0 & 0 \\ 0 & 0 & \sqrt{\gamma_{21}} \\ 0 & 0 & 0 \end{bmatrix} where :math:`\gamma_{10}, \gamma_{20}, \gamma_{21} \in [0, 1]` are the amplitude damping probabilities for subspaces :math:`(0, 1)`, :math:`(0, 2)`, and :math:`(1, 2)` respectively. .. note:: When :math:`\gamma_{21}=0` then Kraus operators :math:`\{K_0, K_1, K_2\}` are adapted from [`1 <https://doi.org/10.48550/arXiv.1905.10481>`_] (Eq. 8). The Kraus operator :math:`K_3` represents the :math:`|2 \rangle \rightarrow |1 \rangle` transition which is more likely on some devices [`2 <https://arxiv.org/abs/2003.03307>`_] (Sec II.A). To maintain normalization :math:`\gamma_{20} + \gamma_{21} \leq 1`. **Details:** * Number of wires: 1 * Number of parameters: 3 Args: gamma_10 (float): :math:`|1 \rangle \rightarrow |0 \rangle` amplitude damping probability. gamma_20 (float): :math:`|2 \rangle \rightarrow |0 \rangle` amplitude damping probability. gamma_21 (float): :math:`|2 \rangle \rightarrow |1 \rangle` amplitude damping probability. wires (Sequence[int] or int): the wire the channel acts on. id (str or None): String representing the operation (optional). """ num_params = 3 num_wires = 1 grad_method = "F" def __init__(self, gamma_10, gamma_20, gamma_21, wires, id=None): # Verify input for gamma in (gamma_10, gamma_20, gamma_21): if not math.is_abstract(gamma): if not 0.0 <= gamma <= 1.0: raise ValueError("Each probability must be in the interval [0,1]") if not (math.is_abstract(gamma_20) or math.is_abstract(gamma_21)): if not 0.0 <= gamma_20 + gamma_21 <= 1.0: raise ValueError(r"\gamma_{20}+\gamma_{21} must be in the interval [0,1]") super().__init__(gamma_10, gamma_20, gamma_21, wires=wires, id=id) @staticmethod def compute_kraus_matrices(gamma_10, gamma_20, gamma_21): # pylint:disable=arguments-differ r"""Kraus matrices representing the ``QutritAmplitudeDamping`` channel. Args: gamma_10 (float): :math:`|1\rangle \rightarrow |0\rangle` amplitude damping probability. gamma_20 (float): :math:`|2\rangle \rightarrow |0\rangle` amplitude damping probability. gamma_21 (float): :math:`|2\rangle \rightarrow |1\rangle` amplitude damping probability. Returns: list(array): list of Kraus matrices **Example** >>> qml.QutritAmplitudeDamping.compute_kraus_matrices(0.5, 0.25, 0.36) [ array([ [1. , 0. , 0. ], [0. , 0.70710678, 0. ], [0. , 0. , 0.6244998 ]]), array([ [0. , 0.70710678, 0. ], [0. , 0. , 0. ], [0. , 0. , 0. ]]), array([ [0. , 0. , 0.5 ], [0. , 0. , 0. ], [0. , 0. , 0. ]]) array([ [0. , 0. , 0. ], [0. , 0. , 0.6 ], [0. , 0. , 0. ]]) ] """ K0 = math.diag( [1, math.sqrt(1 - gamma_10 + math.eps), math.sqrt(1 - gamma_20 - gamma_21 + math.eps)] ) K1 = math.sqrt(gamma_10 + math.eps) * math.convert_like( math.cast_like(math.array([[0, 1, 0], [0, 0, 0], [0, 0, 0]]), gamma_10), gamma_10 ) K2 = math.sqrt(gamma_20 + math.eps) * math.convert_like( math.cast_like(math.array([[0, 0, 1], [0, 0, 0], [0, 0, 0]]), gamma_20), gamma_20 ) K3 = math.sqrt(gamma_21 + math.eps) * math.convert_like( math.cast_like(math.array([[0, 0, 0], [0, 0, 1], [0, 0, 0]]), gamma_21), gamma_21 ) return [K0, K1, K2, K3] class TritFlip(Channel): r""" Single-qutrit trit flip error channel, used for applying "bit flips" on each qutrit subspace. This channel is modelled by the following Kraus matrices: .. math:: K_0 = \sqrt{1-(p_{01} + p_{02} + p_{12})} \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix} .. math:: K_1 = \sqrt{p_{01}}\begin{bmatrix} 0 & 1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \end{bmatrix}, \quad K_2 = \sqrt{p_{02}}\begin{bmatrix} 0 & 0 & 1 \\ 0 & 1 & 0 \\ 1 & 0 & 0 \end{bmatrix}, \quad K_3 = \sqrt{p_{12}}\begin{bmatrix} 1 & 0 & 0 \\ 0 & 0 & 1 \\ 0 & 1 & 0 \end{bmatrix} where :math:`p_{01}, p_{02}, p_{12} \in [0, 1]` is the probability of a "trit flip" occurring within subspaces (0,1), (0,2), and (1,2) respectively. .. note:: The Kraus operators :math:`\{K_0, K_1, K_2, K_3\}` are adapted from the `BitFlip <https://docs.pennylane.ai/en/stable/code/api/pennylane.BitFlip.html>`_ channel's Kraus operators. This channel is primarily meant to simulate the misclassification inherent to measurements on some platforms. An example of a measurement with misclassification can be seen in [`1 <https://arxiv.org/abs/2309.11303>`_] (Fig 1a). To maintain normalization :math:`p_{01} + p_{02} + p_{12} \leq 1`. **Details:** * Number of wires: 1 * Number of parameters: 3 Args: p_01 (float): The probability that a :math:`|0 \rangle \leftrightarrow |1 \rangle` trit flip error occurs. p_02 (float): The probability that a :math:`|0 \rangle \leftrightarrow |2 \rangle` trit flip error occurs. p_12 (float): The probability that a :math:`|1 \rangle \leftrightarrow |2 \rangle` trit flip error occurs. wires (Sequence[int] or int): The wire the channel acts on. id (str or None): String representing the operation (optional). """ num_params = 3 num_wires = 1 grad_method = "F" def __init__(self, p_01, p_02, p_12, wires, id=None): # Verify input ps = (p_01, p_02, p_12) for p in ps: if not math.is_abstract(p) and not 0.0 <= p <= 1.0: raise ValueError("All probabilities must be in the interval [0,1]") if not any(math.is_abstract(p) for p in ps): if not 0.0 <= sum(ps) <= 1.0: raise ValueError("The sum of probabilities must be in the interval [0,1]") super().__init__(p_01, p_02, p_12, wires=wires, id=id) @staticmethod def compute_kraus_matrices(p_01, p_02, p_12): # pylint:disable=arguments-differ r"""Kraus matrices representing the TritFlip channel. Args: p_01 (float): The probability that a :math:`|0 \rangle \leftrightarrow |1 \rangle` trit flip error occurs. p_02 (float): The probability that a :math:`|0 \rangle \leftrightarrow |2 \rangle` trit flip error occurs. p_12 (float): The probability that a :math:`|1 \rangle \leftrightarrow |2 \rangle` trit flip error occurs. Returns: list (array): list of Kraus matrices **Example** >>> qml.TritFlip.compute_kraus_matrices(0.05, 0.01, 0.10) [ array([ [0.91651514, 0. , 0. ], [0. , 0.91651514, 0. ], [0. , 0. , 0.91651514]]), array([ [0. , 0.2236068 , 0. ], [0.2236068 , 0. , 0. ], [0. , 0. , 0.2236068]]), array([ [0. , 0. , 0.1 ], [0. , 0.1 , 0. ], [0.1 , 0. , 0. ]]), array([ [0.31622777, 0. , 0. ], [0. , 0. , 0.31622777], [0. , 0.31622777, 0. ]]) ] """ K0 = math.sqrt(1 - (p_01 + p_02 + p_12) + math.eps) * math.convert_like( math.cast_like(np.eye(3), p_01), p_01 ) K1 = math.sqrt(p_01 + math.eps) * math.convert_like( math.cast_like(math.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]]), p_01), p_01 ) K2 = math.sqrt(p_02 + math.eps) * math.convert_like( math.cast_like(math.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]), p_02), p_02 ) K3 = math.sqrt(p_12 + math.eps) * math.convert_like( math.cast_like(math.array([[1, 0, 0], [0, 0, 1], [0, 1, 0]]), p_12), p_12 ) return [K0, K1, K2, K3] class QutritChannel(Channel): r""" Apply an arbitrary fixed qutrit channel. Kraus matrices that represent the fixed channel are provided as a list of NumPy arrays. **Details:** * Number of wires: Any (the operation can act on any number of wires) * Number of parameters: 1 * Gradient recipe: None Args: K_list (list[array[complex]]): list of Kraus matrices wires (Union[Wires, Sequence[int], or int]): the wire(s) the operation acts on id (str or None): String representing the operation (optional) """ num_wires = AnyWires grad_method = None def __init__(self, K_list, wires=None, id=None): super().__init__(*K_list, wires=wires, id=id) # check all Kraus matrices are square matrices if any(K.shape[0] != K.shape[1] for K in K_list): raise ValueError( "Only channels with the same input and output Hilbert space dimensions can be applied." ) # check all Kraus matrices have the same shape if any(K.shape != K_list[0].shape for K in K_list): raise ValueError("All Kraus matrices must have the same shape.") # check the dimension of all Kraus matrices are valid kraus_dim = QUDIT_DIM ** len(self.wires) if any(K.shape[0] != kraus_dim for K in K_list): raise ValueError(f"Shape of all Kraus matrices must be ({kraus_dim},{kraus_dim}).") # check that the channel represents a trace-preserving map if not any(math.is_abstract(K) for K in K_list): K_arr = math.array(K_list) Kraus_sum = math.einsum("ajk,ajl->kl", K_arr.conj(), K_arr) if not math.allclose(Kraus_sum, math.eye(K_list[0].shape[0])): raise ValueError("Only trace preserving channels can be applied.") def _flatten(self): return (self.data,), (self.wires, ()) @staticmethod def compute_kraus_matrices(*kraus_matrices): # pylint:disable=arguments-differ """Kraus matrices representing the QutritChannel channel. Args: *K_list (list[array[complex]]): list of Kraus matrices Returns: list (array): list of Kraus matrices **Example** >>> K_list = qml.QutritDepolarizingChannel(0.75, wires=0).kraus_matrices() >>> res = qml.QutritChannel.compute_kraus_matrices(K_list) >>> all(np.allclose(r, k) for r, k in zip(res, K_list)) True """ return list(kraus_matrices)
pennylane/pennylane/ops/qutrit/channel.py/0
{ "file_path": "pennylane/pennylane/ops/qutrit/channel.py", "repo_id": "pennylane", "token_count": 10893 }
57
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """Root mean square propagation optimizer""" from numpy import sqrt from .adagrad import AdagradOptimizer class RMSPropOptimizer(AdagradOptimizer): r"""Root mean squared propagation optimizer. The root mean square progation optimizer is a modified :class:`Adagrad optimizer <pennylane.optmimize.AdagradOptimizer>`, with a decay of learning rate adaptation. Extensions of the Adagrad optimization method generally start the sum :math:`a` over past gradients in the denominator of the learning rate at a finite :math:`t'` with :math:`0 < t' < t`, or decay past gradients to avoid an ever-decreasing learning rate. Root Mean Square propagation is such an adaptation, where .. math:: a_i^{(t+1)} = \gamma a_i^{(t)} + (1-\gamma) (\partial_{x_i} f(x^{(t)}))^2. Args: stepsize (float): the user-defined hyperparameter :math:`\eta` used in the Adagrad optmization decay (float): the learning rate decay :math:`\gamma` eps (float): offset :math:`\epsilon` added for numerical stability (see :class:`Adagrad <pennylane.optmimize.AdagradOptimizer>`) """ def __init__(self, stepsize=0.01, decay=0.9, eps=1e-8): super().__init__(stepsize) self.decay = decay self.eps = eps def apply_grad(self, grad, args): r"""Update the variables args to take a single optimization step. Flattens and unflattens the inputs to maintain nested iterables as the parameters of the optimization. Args: grad (tuple [array]): the gradient of the objective function at point :math:`x^{(t)}`: :math:`\nabla f(x^{(t)})`. args (tuple): the current value of the variables :math:`x^{(t)}`. Returns: list [array]: the new values :math:`x^{(t+1)}` """ args_new = list(args) if self.accumulation is None: self.accumulation = [0.0] * len(args) trained_index = 0 for index, arg in enumerate(args): if getattr(arg, "requires_grad", False): self._update_accumulation(index, grad[trained_index]) args_new[index] = ( arg - (self.stepsize / sqrt(self.accumulation[index] + self.eps)) * grad[trained_index] ) trained_index += 1 return args_new def _update_accumulation(self, index, grad): r"""Update the accumulation with the gradient. Args: index (int): index of argument to update. grad (ndarray): gradient at the index. """ self.accumulation[index] = ( self.decay * self.accumulation[index] + (1 - self.decay) * grad**2 )
pennylane/pennylane/optimize/rms_prop.py/0
{ "file_path": "pennylane/pennylane/optimize/rms_prop.py", "repo_id": "pennylane", "token_count": 1368 }
58
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # 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. """ Utility functions to interact with and extract information from Pauli words and Pauli sentences. """ from functools import singledispatch from typing import Union from pennylane.operation import Tensor from pennylane.ops import ( Hamiltonian, Identity, LinearCombination, PauliX, PauliY, PauliZ, Prod, SProd, ) from .conversion import pauli_sentence from .utils import is_pauli_word def pauli_word_prefactor(observable): """If the operator provided is a valid Pauli word (i.e a single term which may be a tensor product of pauli operators), then this function extracts the prefactor. Args: observable (~.Operator): the operator to be examined Returns: Union[int, float, complex]: The scaling/phase coefficient of the Pauli word. Raises: ValueError: If an operator is provided that is not a valid Pauli word. **Example** >>> pauli_word_prefactor(qml.Identity(0)) 1 >>> pauli_word_prefactor(qml.X(0) @ qml.Y(1)) 1 >>> pauli_word_prefactor(qml.X(0) @ qml.Y(0)) 1j """ return _pauli_word_prefactor(observable) @singledispatch def _pauli_word_prefactor(observable): """Private wrapper function for pauli_word_prefactor.""" raise ValueError(f"Expected a valid Pauli word, got {observable}") @_pauli_word_prefactor.register(PauliX) @_pauli_word_prefactor.register(PauliY) @_pauli_word_prefactor.register(PauliZ) @_pauli_word_prefactor.register(Identity) def _pw_prefactor_pauli( observable: Union[PauliX, PauliY, PauliZ, Identity] ): # pylint:disable=unused-argument return 1 @_pauli_word_prefactor.register def _pw_prefactor_tensor(observable: Tensor): if is_pauli_word(observable): return list(pauli_sentence(observable).values())[0] # only one term, raise ValueError(f"Expected a valid Pauli word, got {observable}") @_pauli_word_prefactor.register(Hamiltonian) @_pauli_word_prefactor.register(LinearCombination) def _pw_prefactor_ham(observable: Union[Hamiltonian, LinearCombination]): if is_pauli_word(observable): return observable.coeffs[0] raise ValueError(f"Expected a valid Pauli word, got {observable}") @_pauli_word_prefactor.register(Prod) @_pauli_word_prefactor.register(SProd) def _pw_prefactor_prod_sprod(observable: Union[Prod, SProd]): ps = observable.pauli_rep if ps is not None and len(ps) == 1: return list(ps.values())[0] raise ValueError(f"Expected a valid Pauli word, got {observable}")
pennylane/pennylane/pauli/pauli_interface.py/0
{ "file_path": "pennylane/pennylane/pauli/pauli_interface.py", "repo_id": "pennylane", "token_count": 1140 }
59
# Copyright 2021 Xanadu Quantum Technologies Inc. # 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. r""" Functionality for finding the maximum weighted cycle of directed graphs. """ # pylint: disable=unnecessary-comprehension, unnecessary-lambda-assignment import itertools from collections.abc import Iterable from typing import Union import networkx as nx import numpy as np import rustworkx as rx import pennylane as qml def edges_to_wires(graph: Union[nx.Graph, rx.PyGraph, rx.PyDiGraph]) -> dict[tuple, int]: r"""Maps the edges of a graph to corresponding wires. **Example** >>> g = nx.complete_graph(4).to_directed() >>> edges_to_wires(g) {(0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 0): 3, (1, 2): 4, (1, 3): 5, (2, 0): 6, (2, 1): 7, (2, 3): 8, (3, 0): 9, (3, 1): 10, (3, 2): 11} >>> g = rx.generators.directed_mesh_graph(4, [0,1,2,3]) >>> edges_to_wires(g) {(0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 0): 3, (1, 2): 4, (1, 3): 5, (2, 0): 6, (2, 1): 7, (2, 3): 8, (3, 0): 9, (3, 1): 10, (3, 2): 11} Args: graph (nx.Graph or rx.PyGraph or rx.PyDiGraph): the graph specifying possible edges Returns: Dict[Tuple, int]: a mapping from graph edges to wires """ if isinstance(graph, nx.Graph): return {edge: i for i, edge in enumerate(graph.edges)} if isinstance(graph, (rx.PyGraph, rx.PyDiGraph)): gnodes = graph.nodes() return { (gnodes.index(e[0]), gnodes.index(e[1])): i for i, e in enumerate(sorted(graph.edge_list())) } raise ValueError( f"Input graph must be a nx.Graph or rx.PyGraph or rx.PyDiGraph, got {type(graph).__name__}" ) def wires_to_edges(graph: Union[nx.Graph, rx.PyGraph, rx.PyDiGraph]) -> dict[int, tuple]: r"""Maps the wires of a register of qubits to corresponding edges. **Example** >>> g = nx.complete_graph(4).to_directed() >>> wires_to_edges(g) {0: (0, 1), 1: (0, 2), 2: (0, 3), 3: (1, 0), 4: (1, 2), 5: (1, 3), 6: (2, 0), 7: (2, 1), 8: (2, 3), 9: (3, 0), 10: (3, 1), 11: (3, 2)} >>> g = rx.generators.directed_mesh_graph(4, [0,1,2,3]) >>> wires_to_edges(g) {0: (0, 1), 1: (0, 2), 2: (0, 3), 3: (1, 0), 4: (1, 2), 5: (1, 3), 6: (2, 0), 7: (2, 1), 8: (2, 3), 9: (3, 0), 10: (3, 1), 11: (3, 2)} Args: graph (nx.Graph or rx.PyGraph or rx.PyDiGraph): the graph specifying possible edges Returns: Dict[Tuple, int]: a mapping from wires to graph edges """ if isinstance(graph, nx.Graph): return {i: edge for i, edge in enumerate(graph.edges)} if isinstance(graph, (rx.PyGraph, rx.PyDiGraph)): gnodes = graph.nodes() return { i: (gnodes.index(e[0]), gnodes.index(e[1])) for i, e in enumerate(sorted(graph.edge_list())) } raise ValueError( f"Input graph must be a nx.Graph or rx.PyGraph or rx.PyDiGraph, got {type(graph).__name__}" ) def cycle_mixer(graph: Union[nx.DiGraph, rx.PyDiGraph]) -> qml.operation.Operator: r"""Calculates the cycle-mixer Hamiltonian. Following methods outlined `here <https://arxiv.org/abs/1709.03489>`__, the cycle-mixer Hamiltonian preserves the set of valid cycles: .. math:: \frac{1}{4}\sum_{(i, j)\in E} \left(\sum_{k \in V, k\neq i, k\neq j, (i, k) \in E, (k, j) \in E} \left[X_{ij}X_{ik}X_{kj} +Y_{ij}Y_{ik}X_{kj} + Y_{ij}X_{ik}Y_{kj} - X_{ij}Y_{ik}Y_{kj}\right] \right) where :math:`E` are the edges of the directed graph. A valid cycle is defined as a subset of edges in :math:`E` such that all of the graph's nodes :math:`V` have zero net flow (see the :func:`~.net_flow_constraint` function). **Example** >>> import networkx as nx >>> g = nx.complete_graph(3).to_directed() >>> h_m = cycle_mixer(g) >>> print(h_m) (-0.25) [X0 Y1 Y5] + (-0.25) [X1 Y0 Y3] + (-0.25) [X2 Y3 Y4] + (-0.25) [X3 Y2 Y1] + (-0.25) [X4 Y5 Y2] + (-0.25) [X5 Y4 Y0] + (0.25) [X0 X1 X5] + (0.25) [Y0 Y1 X5] + (0.25) [Y0 X1 Y5] + (0.25) [X1 X0 X3] + (0.25) [Y1 Y0 X3] + (0.25) [Y1 X0 Y3] + (0.25) [X2 X3 X4] + (0.25) [Y2 Y3 X4] + (0.25) [Y2 X3 Y4] + (0.25) [X3 X2 X1] + (0.25) [Y3 Y2 X1] + (0.25) [Y3 X2 Y1] + (0.25) [X4 X5 X2] + (0.25) [Y4 Y5 X2] + (0.25) [Y4 X5 Y2] + (0.25) [X5 X4 X0] + (0.25) [Y5 Y4 X0] + (0.25) [Y5 X4 Y0] >>> import rustworkx as rx >>> g = rx.generators.directed_mesh_graph(3, [0,1,2]) >>> h_m = cycle_mixer(g) >>> print(h_m) (-0.25) [X0 Y1 Y5] + (-0.25) [X1 Y0 Y3] + (-0.25) [X2 Y3 Y4] + (-0.25) [X3 Y2 Y1] + (-0.25) [X4 Y5 Y2] + (-0.25) [X5 Y4 Y0] + (0.25) [X0 X1 X5] + (0.25) [Y0 Y1 X5] + (0.25) [Y0 X1 Y5] + (0.25) [X1 X0 X3] + (0.25) [Y1 Y0 X3] + (0.25) [Y1 X0 Y3] + (0.25) [X2 X3 X4] + (0.25) [Y2 Y3 X4] + (0.25) [Y2 X3 Y4] + (0.25) [X3 X2 X1] + (0.25) [Y3 Y2 X1] + (0.25) [Y3 X2 Y1] + (0.25) [X4 X5 X2] + (0.25) [Y4 Y5 X2] + (0.25) [Y4 X5 Y2] + (0.25) [X5 X4 X0] + (0.25) [Y5 Y4 X0] + (0.25) [Y5 X4 Y0] Args: graph (nx.DiGraph or rx.PyDiGraph): the directed graph specifying possible edges Returns: qml.Hamiltonian: the cycle-mixer Hamiltonian """ if not isinstance(graph, (nx.DiGraph, rx.PyDiGraph)): raise ValueError( f"Input graph must be a nx.DiGraph or rx.PyDiGraph, got {type(graph).__name__}" ) hamiltonian = qml.Hamiltonian([], []) graph_edges = sorted(graph.edge_list()) if isinstance(graph, rx.PyDiGraph) else graph.edges for edge in graph_edges: hamiltonian += _partial_cycle_mixer(graph, edge) return hamiltonian def _partial_cycle_mixer( graph: Union[nx.DiGraph, rx.PyDiGraph], edge: tuple ) -> qml.operation.Operator: r"""Calculates the partial cycle-mixer Hamiltonian for a specific edge. For an edge :math:`(i, j)`, this function returns: .. math:: \sum_{k \in V, k\neq i, k\neq j, (i, k) \in E, (k, j) \in E}\left[ X_{ij}X_{ik}X_{kj} + Y_{ij}Y_{ik}X_{kj} + Y_{ij}X_{ik}Y_{kj} - X_{ij}Y_{ik}Y_{kj}\right] Args: graph (nx.DiGraph or rx.PyDiGraph): the directed graph specifying possible edges edge (tuple): a fixed edge Returns: qml.Hamiltonian: the partial cycle-mixer Hamiltonian """ if not isinstance(graph, (nx.DiGraph, rx.PyDiGraph)): raise ValueError( f"Input graph must be a nx.DiGraph or rx.PyDiGraph, got {type(graph).__name__}" ) coeffs = [] ops = [] is_rx = isinstance(graph, rx.PyDiGraph) edges_to_qubits = edges_to_wires(graph) graph_nodes = graph.node_indexes() if is_rx else graph.nodes graph_edges = sorted(graph.edge_list()) if is_rx else graph.edges # In RX each node is assigned to an integer index starting from 0; # thus, we use the following lambda function to get node-values. get_nvalues = lambda T: (graph.nodes().index(T[0]), graph.nodes().index(T[1])) if is_rx else T for node in graph_nodes: out_edge = (edge[0], node) in_edge = (node, edge[1]) if node not in edge and out_edge in graph_edges and in_edge in graph_edges: wire = edges_to_qubits[get_nvalues(edge)] out_wire = edges_to_qubits[get_nvalues(out_edge)] in_wire = edges_to_qubits[get_nvalues(in_edge)] t = qml.X(wire) @ qml.X(out_wire) @ qml.X(in_wire) ops.append(t) t = qml.Y(wire) @ qml.Y(out_wire) @ qml.X(in_wire) ops.append(t) t = qml.Y(wire) @ qml.X(out_wire) @ qml.Y(in_wire) ops.append(t) t = qml.X(wire) @ qml.Y(out_wire) @ qml.Y(in_wire) ops.append(t) coeffs.extend([0.25, 0.25, 0.25, -0.25]) return qml.Hamiltonian(coeffs, ops) def loss_hamiltonian(graph: Union[nx.Graph, rx.PyGraph, rx.PyDiGraph]) -> qml.operation.Operator: r"""Calculates the loss Hamiltonian for the maximum-weighted cycle problem. We consider the problem of selecting a cycle from a graph that has the greatest product of edge weights, as outlined `here <https://1qbit.com/whitepaper/arbitrage/>`__. The product of weights of a subset of edges in a graph is given by .. math:: P = \prod_{(i, j) \in E} [(c_{ij} - 1)x_{ij} + 1] where :math:`E` are the edges of the graph, :math:`x_{ij}` is a binary number that selects whether to include the edge :math:`(i, j)` and :math:`c_{ij}` is the corresponding edge weight. Our objective is to maximimize :math:`P`, subject to selecting the :math:`x_{ij}` so that our subset of edges composes a cycle. The product of edge weights is maximized by equivalently considering .. math:: \sum_{(i, j) \in E} x_{ij}\log c_{ij}, assuming :math:`c_{ij} > 0`. This can be restated as a minimization of the expectation value of the following qubit Hamiltonian: .. math:: H = \sum_{(i, j) \in E} Z_{ij}\log c_{ij}. where :math:`Z_{ij}` is a qubit Pauli-Z matrix acting upon the wire specified by the edge :math:`(i, j)`. Mapping from edges to wires can be achieved using :func:`~.edges_to_wires`. .. note:: The expectation value of the returned Hamiltonian :math:`H` is not equal to :math:`P`, but minimizing the expectation value of :math:`H` is equivalent to maximizing :math:`P`. Also note that the returned Hamiltonian does not impose that the selected set of edges is a cycle. This constraint can be enforced using a penalty term or by selecting a QAOA mixer Hamiltonian that only transitions between states that correspond to cycles. **Example** >>> import networkx as nx >>> g = nx.complete_graph(3).to_directed() >>> edge_weight_data = {edge: (i + 1) * 0.5 for i, edge in enumerate(g.edges)} >>> for k, v in edge_weight_data.items(): g[k[0]][k[1]]["weight"] = v >>> h = loss_hamiltonian(g) >>> h ( -0.6931471805599453 * Z(0) + 0.0 * Z(1) + 0.4054651081081644 * Z(2) + 0.6931471805599453 * Z(3) + 0.9162907318741551 * Z(4) + 1.0986122886681098 * Z(5) ) >>> import rustworkx as rx >>> g = rx.generators.directed_mesh_graph(3, [0, 1, 2]) >>> edge_weight_data = {edge: (i + 1) * 0.5 for i, edge in enumerate(sorted(g.edge_list()))} >>> for k, v in edge_weight_data.items(): g.update_edge(k[0], k[1], {"weight": v}) >>> h = loss_hamiltonian(g) >>> print(h) ( -0.6931471805599453 * Z(0) + 0.0 * Z(1) + 0.4054651081081644 * Z(2) + 0.6931471805599453 * Z(3) + 0.9162907318741551 * Z(4) + 1.0986122886681098 * Z(5) ) Args: graph (nx.Graph or rx.PyGraph or rx.PyDiGraph): the graph specifying possible edges Returns: qml.Hamiltonian: the loss Hamiltonian Raises: ValueError: if the graph contains self-loops KeyError: if one or more edges do not contain weight data """ if not isinstance(graph, (nx.Graph, rx.PyGraph, rx.PyDiGraph)): raise ValueError( f"Input graph must be a nx.Graph or rx.PyGraph or rx.PyDiGraph, got {type(graph).__name__}" ) edges_to_qubits = edges_to_wires(graph) coeffs = [] ops = [] is_rx = isinstance(graph, (rx.PyGraph, rx.PyDiGraph)) edges_data = sorted(graph.weighted_edge_list()) if is_rx else graph.edges(data=True) # In RX each node is assigned to an integer index starting from 0; # thus, we use the following lambda function to get node-values. get_nvalues = lambda T: (graph.nodes().index(T[0]), graph.nodes().index(T[1])) if is_rx else T for edge_data in edges_data: edge = edge_data[:2] if edge[0] == edge[1]: raise ValueError("Graph contains self-loops") try: weight = edge_data[2]["weight"] except KeyError as e: raise KeyError(f"Edge {edge} does not contain weight data") from e except TypeError as e: raise TypeError(f"Edge {edge} does not contain weight data") from e coeffs.append(np.log(weight)) ops.append(qml.Z(edges_to_qubits[get_nvalues(edge)])) H = qml.Hamiltonian(coeffs, ops) # store the valuable information that all observables are in one commuting group H.grouping_indices = [list(range(len(H.ops)))] return H def _square_hamiltonian_terms( coeffs: Iterable[float], ops: Iterable[qml.operation.Observable] ) -> tuple[list[float], list[qml.operation.Observable]]: """Calculates the coefficients and observables that compose the squared Hamiltonian. Args: coeffs (Iterable[float]): coeffients of the input Hamiltonian ops (Iterable[qml.operation.Observable]): observables of the input Hamiltonian Returns: Tuple[List[float], List[qml.operation.Observable]]: The list of coefficients and list of observables of the squared Hamiltonian. """ squared_coeffs, squared_ops = [], [] pairs = [(coeff, op) for coeff, op in zip(coeffs, ops)] products = itertools.product(pairs, repeat=2) for (coeff1, op1), (coeff2, op2) in products: squared_coeffs.append(coeff1 * coeff2) if isinstance(op1, qml.Identity): squared_ops.append(op2) elif isinstance(op2, qml.Identity): squared_ops.append(op1) # pylint: disable=unidiomatic-typecheck elif op1.wires == op2.wires and isinstance(op1, type(op2)): squared_ops.append(qml.Identity(0)) elif op2.wires[0] < op1.wires[0]: squared_ops.append(op2 @ op1) else: squared_ops.append(op1 @ op2) return squared_coeffs, squared_ops def out_flow_constraint(graph: Union[nx.DiGraph, rx.PyDiGraph]) -> qml.operation.Operator: r"""Calculates the `out flow constraint <https://1qbit.com/whitepaper/arbitrage/>`__ Hamiltonian for the maximum-weighted cycle problem. Given a subset of edges in a directed graph, the out-flow constraint imposes that at most one edge can leave any given node, i.e., for all :math:`i`: .. math:: \sum_{j,(i,j)\in E}x_{ij} \leq 1, where :math:`E` are the edges of the graph and :math:`x_{ij}` is a binary number that selects whether to include the edge :math:`(i, j)`. A set of edges satisfies the out-flow constraint whenever the following Hamiltonian is minimized: .. math:: \sum_{i\in V}\left(d_{i}^{out}(d_{i}^{out} - 2)\mathbb{I} - 2(d_{i}^{out}-1)\sum_{j,(i,j)\in E}\hat{Z}_{ij} + \left( \sum_{j,(i,j)\in E}\hat{Z}_{ij} \right)^{2}\right) where :math:`V` are the graph vertices, :math:`d_{i}^{\rm out}` is the outdegree of node :math:`i`, and :math:`Z_{ij}` is a qubit Pauli-Z matrix acting upon the qubit specified by the pair :math:`(i, j)`. Mapping from edges to wires can be achieved using :func:`~.edges_to_wires`. Args: graph (nx.DiGraph or rx.PyDiGraph): the directed graph specifying possible edges Returns: qml.Hamiltonian: the out flow constraint Hamiltonian Raises: ValueError: if the input graph is not directed """ if not isinstance(graph, (nx.DiGraph, rx.PyDiGraph)): raise ValueError( f"Input graph must be a nx.DiGraph or rx.PyDiGraph, got {type(graph).__name__}" ) if isinstance(graph, (nx.DiGraph, rx.PyDiGraph)) and not hasattr(graph, "out_edges"): raise ValueError("Input graph must be directed") hamiltonian = qml.Hamiltonian([], []) graph_nodes = graph.node_indexes() if isinstance(graph, rx.PyDiGraph) else graph.nodes for node in graph_nodes: hamiltonian += _inner_out_flow_constraint_hamiltonian(graph, node) return hamiltonian def net_flow_constraint(graph: Union[nx.DiGraph, rx.PyDiGraph]) -> qml.operation.Operator: r"""Calculates the `net flow constraint <https://doi.org/10.1080/0020739X.2010.526248>`__ Hamiltonian for the maximum-weighted cycle problem. Given a subset of edges in a directed graph, the net-flow constraint imposes that the number of edges leaving any given node is equal to the number of edges entering the node, i.e., .. math:: \sum_{j, (i, j) \in E} x_{ij} = \sum_{j, (j, i) \in E} x_{ji}, for all nodes :math:`i`, where :math:`E` are the edges of the graph and :math:`x_{ij}` is a binary number that selects whether to include the edge :math:`(i, j)`. A set of edges has zero net flow whenever the following Hamiltonian is minimized: .. math:: \sum_{i \in V} \left((d_{i}^{\rm out} - d_{i}^{\rm in})\mathbb{I} - \sum_{j, (i, j) \in E} Z_{ij} + \sum_{j, (j, i) \in E} Z_{ji} \right)^{2}, where :math:`V` are the graph vertices, :math:`d_{i}^{\rm out}` and :math:`d_{i}^{\rm in}` are the outdegree and indegree, respectively, of node :math:`i` and :math:`Z_{ij}` is a qubit Pauli-Z matrix acting upon the wire specified by the pair :math:`(i, j)`. Mapping from edges to wires can be achieved using :func:`~.edges_to_wires`. Args: graph (nx.DiGraph or rx.PyDiGraph): the directed graph specifying possible edges Returns: qml.Hamiltonian: the net-flow constraint Hamiltonian Raises: ValueError: if the input graph is not directed """ if isinstance(graph, (nx.DiGraph, rx.PyDiGraph)) and ( not hasattr(graph, "in_edges") or not hasattr(graph, "out_edges") ): raise ValueError("Input graph must be directed") if not isinstance(graph, (nx.DiGraph, rx.PyDiGraph)): raise ValueError( f"Input graph must be a nx.DiGraph or rx.PyDiGraph, got {type(graph).__name__}" ) hamiltonian = qml.Hamiltonian([], []) graph_nodes = graph.node_indexes() if isinstance(graph, rx.PyDiGraph) else graph.nodes for node in graph_nodes: hamiltonian += _inner_net_flow_constraint_hamiltonian(graph, node) return hamiltonian def _inner_out_flow_constraint_hamiltonian( graph: Union[nx.DiGraph, rx.PyDiGraph], node: int ) -> qml.operation.Operator: r"""Calculates the inner portion of the Hamiltonian in :func:`out_flow_constraint`. For a given :math:`i`, this function returns: .. math:: d_{i}^{out}(d_{i}^{out} - 2)\mathbb{I} - 2(d_{i}^{out}-1)\sum_{j,(i,j)\in E}\hat{Z}_{ij} + ( \sum_{j,(i,j)\in E}\hat{Z}_{ij} )^{2} Args: graph (nx.DiGraph or rx.PyDiGraph): the directed graph specifying possible edges node: a fixed node Returns: qml.Hamiltonian: The inner part of the out-flow constraint Hamiltonian. """ if not isinstance(graph, (nx.DiGraph, rx.PyDiGraph)): raise ValueError( f"Input graph must be a nx.DiGraph or rx.PyDiGraph, got {type(graph).__name__}" ) coeffs = [] ops = [] is_rx = isinstance(graph, rx.PyDiGraph) # In RX each node is assigned to an integer index starting from 0; # thus, we use the following lambda function to get node-values. get_nvalues = lambda T: (graph.nodes().index(T[0]), graph.nodes().index(T[1])) if is_rx else T edges_to_qubits = edges_to_wires(graph) out_edges = graph.out_edges(node) d = len(out_edges) # To ensure the out_edges method in both RX and NX returns # the list of edges in the same order, we sort results. if is_rx: out_edges = sorted(out_edges) for edge in out_edges: if len(edge) > 2: edge = tuple(edge[:2]) wire = (edges_to_qubits[get_nvalues(edge)],) coeffs.append(1) ops.append(qml.Z(wire)) coeffs, ops = _square_hamiltonian_terms(coeffs, ops) for edge in out_edges: if len(edge) > 2: edge = tuple(edge[:2]) wire = (edges_to_qubits[get_nvalues(edge)],) coeffs.append(-2 * (d - 1)) ops.append(qml.Z(wire)) coeffs.append(d * (d - 2)) ops.append(qml.Identity(0)) H = qml.Hamiltonian(coeffs, ops) H.simplify() # store the valuable information that all observables are in one commuting group H.grouping_indices = [list(range(len(H.ops)))] return H def _inner_net_flow_constraint_hamiltonian( graph: Union[nx.DiGraph, rx.PyDiGraph], node: int ) -> qml.operation.Operator: r"""Calculates the squared inner portion of the Hamiltonian in :func:`net_flow_constraint`. For a given :math:`i`, this function returns: .. math:: \left((d_{i}^{\rm out} - d_{i}^{\rm in})\mathbb{I} - \sum_{j, (i, j) \in E} Z_{ij} + \sum_{j, (j, i) \in E} Z_{ji} \right)^{2}. Args: graph (nx.DiGraph or rx.PyDiGraph): the directed graph specifying possible edges node: a fixed node Returns: qml.Hamiltonian: The inner part of the net-flow constraint Hamiltonian. """ if not isinstance(graph, (nx.DiGraph, rx.PyDiGraph)): raise ValueError( f"Input graph must be a nx.DiGraph or rx.PyDiGraph, got {type(graph).__name__}" ) edges_to_qubits = edges_to_wires(graph) coeffs = [] ops = [] is_rx = isinstance(graph, rx.PyDiGraph) out_edges = graph.out_edges(node) in_edges = graph.in_edges(node) # To ensure out_edges and in_edges methods in both RX and NX return # the lists of edges in the same order, we sort results. if is_rx: out_edges = sorted(out_edges) in_edges = sorted(in_edges) # In RX each node is assigned to an integer index starting from 0; # thus, we use the following lambda function to get node-values. get_nvalues = lambda T: (graph.nodes().index(T[0]), graph.nodes().index(T[1])) if is_rx else T coeffs.append(len(out_edges) - len(in_edges)) ops.append(qml.Identity(0)) for edge in out_edges: if len(edge) > 2: edge = tuple(edge[:2]) wires = (edges_to_qubits[get_nvalues(edge)],) coeffs.append(-1) ops.append(qml.Z(wires)) for edge in in_edges: if len(edge) > 2: edge = tuple(edge[:2]) wires = (edges_to_qubits[get_nvalues(edge)],) coeffs.append(1) ops.append(qml.Z(wires)) coeffs, ops = _square_hamiltonian_terms(coeffs, ops) H = qml.Hamiltonian(coeffs, ops) H = H.simplify() # store the valuable information that all observables are in one commuting group H.grouping_indices = [list(range(len(H.ops)))] return H
pennylane/pennylane/qaoa/cycle.py/0
{ "file_path": "pennylane/pennylane/qaoa/cycle.py", "repo_id": "pennylane", "token_count": 10439 }
60
# Copyright 2018-2022 Xanadu Quantum Technologies Inc. # 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. """ This module contains the functions needed for computing the particle number observable. """ from pennylane.fermi import FermiSentence, FermiWord from .observable_hf import qubit_observable def particle_number(orbitals): r"""Compute the particle number observable :math:`\hat{N}=\sum_\alpha \hat{n}_\alpha` in the Pauli basis. The particle number operator is given by .. math:: \hat{N} = \sum_\alpha \hat{c}_\alpha^\dagger \hat{c}_\alpha, where the index :math:`\alpha` runs over the basis of single-particle states :math:`\vert \alpha \rangle`, and the operators :math:`\hat{c}^\dagger` and :math:`\hat{c}` are the particle creation and annihilation operators, respectively. Args: orbitals (int): Number of *spin* orbitals. If an active space is defined, this is the number of active spin-orbitals. Returns: pennylane.Hamiltonian: the particle number observable Raises: ValueError: If orbitals is less than or equal to 0 **Example** >>> orbitals = 4 >>> print(particle_number(orbitals)) ( 2.0 * I(0) + -0.5 * Z(0) + -0.5 * Z(1) + -0.5 * Z(2) + -0.5 * Z(3) ) """ if orbitals <= 0: raise ValueError(f"'orbitals' must be greater than 0; got for 'orbitals' {orbitals}") sentence = FermiSentence({FermiWord({(0, i): "+", (1, i): "-"}): 1.0 for i in range(orbitals)}) sentence.simplify() return qubit_observable(sentence)
pennylane/pennylane/qchem/number.py/0
{ "file_path": "pennylane/pennylane/qchem/number.py", "repo_id": "pennylane", "token_count": 753 }
61
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # 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. """QNode transforms for the quantum information quantities.""" # pylint: disable=import-outside-toplevel, not-callable import warnings from collections.abc import Callable, Sequence from functools import partial import pennylane as qml from pennylane import transform from pennylane.devices import DefaultMixed, DefaultQubit, DefaultQubitLegacy from pennylane.gradients import adjoint_metric_tensor, metric_tensor from pennylane.measurements import DensityMatrixMP, StateMP from pennylane.tape import QuantumScript, QuantumScriptBatch from pennylane.typing import PostprocessingFn @partial(transform, final_transform=True) def reduced_dm(tape: QuantumScript, wires, **kwargs) -> tuple[QuantumScriptBatch, PostprocessingFn]: """Compute the reduced density matrix from a :class:`~.QNode` returning :func:`~pennylane.state`. Args: tape (QuantumTape or QNode or Callable)): A quantum circuit returning :func:`~pennylane.state`. wires (Sequence(int)): List of wires in the considered subsystem. Returns: qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. Executing this circuit will provide the reduced density matrix in the form of a tensor. **Example** .. code-block:: python import numpy as np dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(x): qml.IsingXX(x, wires=[0,1]) return qml.state() >>> transformed_circuit = reduced_dm(circuit, wires=[0]) >>> transformed_circuit(np.pi/2) tensor([[0.5+0.j, 0. +0.j], [0. +0.j, 0.5+0.j]], requires_grad=True) This is equivalent to the state of the wire ``0`` after measuring the wire ``1``: .. code-block:: python @qml.qnode(dev) def measured_circuit(x): qml.IsingXX(x, wires=[0,1]) m = qml.measure(1) return qml.density_matrix(wires=[0]), qml.probs(op=m) >>> dm, probs = measured_circuit(np.pi/2) >>> dm tensor([[0.5+0.j, 0. +0.j], [0. +0.j, 0.5+0.j]], requires_grad=True) >>> probs tensor([0.5, 0.5], requires_grad=True) .. seealso:: :func:`pennylane.density_matrix` and :func:`pennylane.math.reduce_dm` """ # device_wires is provided by the custom QNode transform all_wires = kwargs.get("device_wires", tape.wires) wire_map = {w: i for i, w in enumerate(all_wires)} indices = [wire_map[w] for w in wires] measurements = tape.measurements if len(measurements) != 1 or not isinstance(measurements[0], StateMP): raise ValueError("The qfunc measurement needs to be State.") def processing_fn(res): # device is provided by the custom QNode transform device = kwargs.get("device", None) c_dtype = getattr(device, "C_DTYPE", "complex128") # determine the density matrix dm_func = ( qml.math.reduce_dm if isinstance(measurements[0], DensityMatrixMP) or isinstance(device, DefaultMixed) else qml.math.reduce_statevector ) density_matrix = dm_func(res[0], indices=indices, c_dtype=c_dtype) return density_matrix return [tape], processing_fn @reduced_dm.custom_qnode_transform def _reduced_dm_qnode(self, qnode, targs, tkwargs): if tkwargs.get("device", False): raise ValueError( "Cannot provide a 'device' value directly to the reduced_dm decorator when " "transforming a QNode." ) if tkwargs.get("device_wires", None): raise ValueError( "Cannot provide a 'device_wires' value directly to the reduced_dm decorator when " "transforming a QNode." ) tkwargs.setdefault("device", qnode.device) tkwargs.setdefault("device_wires", qnode.device.wires) return self.default_qnode_transform(qnode, targs, tkwargs) @partial(transform, final_transform=True) def purity(tape: QuantumScript, wires, **kwargs) -> tuple[QuantumScriptBatch, PostprocessingFn]: r"""Compute the purity of a :class:`~.QuantumTape` returning :func:`~pennylane.state`. .. math:: \gamma = \text{Tr}(\rho^2) where :math:`\rho` is the density matrix. The purity of a normalized quantum state satisfies :math:`\frac{1}{d} \leq \gamma \leq 1`, where :math:`d` is the dimension of the Hilbert space. A pure state has a purity of 1. It is possible to compute the purity of a sub-system from a given state. To find the purity of the overall state, include all wires in the ``wires`` argument. Args: tape (QNode or QuantumTape or Callable): A quantum circuit object returning a :func:`~pennylane.state`. wires (Sequence(int)): List of wires in the considered subsystem. Returns: qnode (QNode) or quantum function (Callable) or tuple[List[.QuantumTape], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. Executing this circuit will provide the purity in the form of a tensor. **Example** .. code-block:: python dev = qml.device("default.mixed", wires=2) @qml.qnode(dev) def noisy_circuit(p): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.BitFlip(p, wires=0) qml.BitFlip(p, wires=1) return qml.state() @qml.qnode(dev) def circuit(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() >>> purity(noisy_circuit, wires=[0, 1])(0.2) 0.5648000000000398 >>> purity(circuit, wires=[0])(np.pi / 2) 0.5 >>> purity(circuit, wires=[0, 1])(np.pi / 2) 1.0 .. seealso:: :func:`pennylane.math.purity` """ # device_wires is provided by the custom QNode transform all_wires = kwargs.get("device_wires", tape.wires) wire_map = {w: i for i, w in enumerate(all_wires)} indices = [wire_map[w] for w in wires] # Check measurement measurements = tape.measurements if len(measurements) != 1 or not isinstance(measurements[0], StateMP): raise ValueError("The qfunc return type needs to be a state.") def processing_fn(res): # device is provided by the custom QNode transform device = kwargs.get("device", None) c_dtype = getattr(device, "C_DTYPE", "complex128") # determine the density matrix density_matrix = ( res[0] if isinstance(measurements[0], DensityMatrixMP) or isinstance(device, DefaultMixed) else qml.math.dm_from_state_vector(res[0], c_dtype=c_dtype) ) return qml.math.purity(density_matrix, indices, c_dtype=c_dtype) return [tape], processing_fn @purity.custom_qnode_transform def _purity_qnode(self, qnode, targs, tkwargs): if tkwargs.get("device", False): raise ValueError( "Cannot provide a 'device' value directly to the purity decorator when " "transforming a QNode." ) if tkwargs.get("device_wires", None): raise ValueError( "Cannot provide a 'device_wires' value directly to the purity decorator when " "transforming a QNode." ) tkwargs.setdefault("device", qnode.device) tkwargs.setdefault("device_wires", qnode.device.wires) return self.default_qnode_transform(qnode, targs, tkwargs) @partial(transform, final_transform=True) def vn_entropy( tape: QuantumScript, wires: Sequence[int], base: float = None, **kwargs ) -> tuple[QuantumScriptBatch, PostprocessingFn]: r"""Compute the Von Neumann entropy from a :class:`.QuantumTape` returning a :func:`~pennylane.state`. .. math:: S( \rho ) = -\text{Tr}( \rho \log ( \rho )) Args: tape (QNode or QuantumTape or Callable): A quantum circuit returning a :func:`~pennylane.state`. wires (Sequence(int)): List of wires in the considered subsystem. base (float): Base for the logarithm, default is None the natural logarithm is used in this case. Returns: qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. Executing this circuit will provide the Von Neumann entropy in the form of a tensor. **Example** It is possible to obtain the entropy of a subsystem from a :class:`.QNode` returning a :func:`~pennylane.state`. .. code-block:: python dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() >>> vn_entropy(circuit, wires=[0])(np.pi/2) 0.6931471805599453 The function is differentiable with backpropagation for all interfaces, e.g.: >>> param = np.array(np.pi/4, requires_grad=True) >>> qml.grad(vn_entropy(circuit, wires=[0]))(param) tensor(0.62322524, requires_grad=True) .. seealso:: :func:`pennylane.math.vn_entropy` and :func:`pennylane.vn_entropy` """ # device_wires is provided by the custom QNode transform all_wires = kwargs.get("device_wires", tape.wires) wire_map = {w: i for i, w in enumerate(all_wires)} indices = [wire_map[w] for w in wires] measurements = tape.measurements if len(measurements) != 1 or not isinstance(measurements[0], StateMP): raise ValueError("The qfunc return type needs to be a state.") def processing_fn(res): # device is provided by the custom QNode transform device = kwargs.get("device", None) c_dtype = getattr(device, "C_DTYPE", "complex128") # determine if the measurement is a state vector or a density matrix if not isinstance(measurements[0], DensityMatrixMP) and not isinstance( device, DefaultMixed ): # Compute entropy from state vector if len(wires) == len(all_wires): # The subsystem has all wires, so the entropy is 0 return 0.0 density_matrix = qml.math.dm_from_state_vector(res[0], c_dtype=c_dtype) entropy = qml.math.vn_entropy(density_matrix, indices, base, c_dtype=c_dtype) return entropy # Compute entropy from density matrix entropy = qml.math.vn_entropy(res[0], indices, base, c_dtype) return entropy return [tape], processing_fn @vn_entropy.custom_qnode_transform def _vn_entropy_qnode(self, qnode, targs, tkwargs): if tkwargs.get("device", False): raise ValueError( "Cannot provide a 'device' value directly to the vn_entropy decorator when " "transforming a QNode." ) if tkwargs.get("device_wires", None): raise ValueError( "Cannot provide a 'device_wires' value directly to the vn_entropy decorator when " "transforming a QNode." ) tkwargs.setdefault("device", qnode.device) tkwargs.setdefault("device_wires", qnode.device.wires) return self.default_qnode_transform(qnode, targs, tkwargs) def _bipartite_qinfo_transform( transform_func: Callable, tape: QuantumScript, wires0: Sequence[int], wires1: Sequence[int], base: float = None, **kwargs, ): # device_wires is provided by the custom QNode transform all_wires = kwargs.get("device_wires", tape.wires) wire_map = {w: i for i, w in enumerate(all_wires)} indices0 = [wire_map[w] for w in wires0] indices1 = [wire_map[w] for w in wires1] # Check measurement measurements = tape.measurements if len(measurements) != 1 or not isinstance(measurements[0], StateMP): raise ValueError("The qfunc return type needs to be a state.") def processing_fn(res): # device is provided by the custom QNode transform device = kwargs.get("device", None) c_dtype = getattr(device, "C_DTYPE", "complex128") density_matrix = ( res[0] if isinstance(measurements[0], DensityMatrixMP) or isinstance(device, DefaultMixed) else qml.math.dm_from_state_vector(res[0], c_dtype=c_dtype) ) entropy = transform_func(density_matrix, indices0, indices1, base=base, c_dtype=c_dtype) return entropy return [tape], processing_fn @partial(transform, final_transform=True) def mutual_info( tape: QuantumScript, wires0: Sequence[int], wires1: Sequence[int], base: float = None, **kwargs ) -> tuple[QuantumScriptBatch, PostprocessingFn]: r"""Compute the mutual information from a :class:`.QuantumTape` returning a :func:`~pennylane.state`: .. math:: I(A, B) = S(\rho^A) + S(\rho^B) - S(\rho^{AB}) where :math:`S` is the von Neumann entropy. The mutual information is a measure of correlation between two subsystems. More specifically, it quantifies the amount of information obtained about one system by measuring the other system. Args: qnode (QNode or QuantumTape or Callable): A quantum circuit returning a :func:`~pennylane.state`. wires0 (Sequence(int)): List of wires in the first subsystem. wires1 (Sequence(int)): List of wires in the second subsystem. base (float): Base for the logarithm. If None, the natural logarithm is used. Returns: qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. Executing this circuit will provide the mutual information in the form of a tensor. **Example** It is possible to obtain the mutual information of two subsystems from a :class:`.QNode` returning a :func:`~pennylane.state`. .. code-block:: python dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() >>> mutual_info_circuit = qinfo.mutual_info(circuit, wires0=[0], wires1=[1]) >>> mutual_info_circuit(np.pi/2) 1.3862943611198906 >>> x = np.array(0.4, requires_grad=True) >>> mutual_info_circuit(x) 0.3325090393262875 >>> qml.grad(mutual_info_circuit)(np.array(0.4, requires_grad=True)) tensor(1.24300677, requires_grad=True) .. seealso:: :func:`~.qinfo.vn_entropy`, :func:`pennylane.math.mutual_info` and :func:`pennylane.mutual_info` """ return _bipartite_qinfo_transform(qml.math.mutual_info, tape, wires0, wires1, base, **kwargs) @mutual_info.custom_qnode_transform def _mutual_info_qnode(self, qnode, targs, tkwargs): if tkwargs.get("device", False): raise ValueError( "Cannot provide a 'device' value directly to the mutual_info decorator when " "transforming a QNode." ) if tkwargs.get("device_wires", None): raise ValueError( "Cannot provide a 'device_wires' value directly to the mutual_info decorator when " "transforming a QNode." ) tkwargs.setdefault("device", qnode.device) tkwargs.setdefault("device_wires", qnode.device.wires) return self.default_qnode_transform(qnode, targs, tkwargs) @partial(transform, final_transform=True) def vn_entanglement_entropy( tape, wires0: Sequence[int], wires1: Sequence[int], base: float = None, **kwargs ): r"""Compute the Von Neumann entanglement entropy from a circuit returning a :func:`~pennylane.state`: .. math:: S(\rho_A) = -\text{Tr}[\rho_A \log \rho_A] = -\text{Tr}[\rho_B \log \rho_B] = S(\rho_B) where :math:`S` is the von Neumann entropy; :math:`\rho_A = \text{Tr}_B [\rho_{AB}]` and :math:`\rho_B = \text{Tr}_A [\rho_{AB}]` are the reduced density matrices for each partition. The Von Neumann entanglement entropy is a measure of the degree of quantum entanglement between two subsystems constituting a pure bipartite quantum state. The entropy of entanglement is the Von Neumann entropy of the reduced density matrix for any of the subsystems. If it is non-zero, it indicates the two subsystems are entangled. Args: tape (QNode or QuantumTape or Callable): A quantum circuit returning a :func:`~pennylane.state`. wires0 (Sequence(int)): List of wires in the first subsystem. wires1 (Sequence(int)): List of wires in the second subsystem. base (float): Base for the logarithm. If None, the natural logarithm is used. Returns: qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. Executing this circuit will provide the entanglement entropy in the form of a tensor. """ return _bipartite_qinfo_transform( qml.math.vn_entanglement_entropy, tape, wires0, wires1, base, **kwargs ) def classical_fisher(qnode, argnums=0): r"""Returns a function that computes the classical fisher information matrix (CFIM) of a given :class:`.QNode` or quantum tape. Given a parametrized (classical) probability distribution :math:`p(\bm{\theta})`, the classical fisher information matrix quantifies how changes to the parameters :math:`\bm{\theta}` are reflected in the probability distribution. For a parametrized quantum state, we apply the concept of classical fisher information to the computational basis measurement. More explicitly, this function implements eq. (15) in `arxiv:2103.15191 <https://arxiv.org/abs/2103.15191>`_: .. math:: \text{CFIM}_{i, j} = \sum_{\ell=0}^{2^N-1} \frac{1}{p_\ell(\bm{\theta})} \frac{\partial p_\ell(\bm{\theta})}{ \partial \theta_i} \frac{\partial p_\ell(\bm{\theta})}{\partial \theta_j} for :math:`N` qubits. Args: tape (:class:`.QNode` or qml.QuantumTape): A :class:`.QNode` or quantum tape that may have arbitrary return types. argnums (Optional[int or List[int]]): Arguments to be differentiated in case interface ``jax`` is used. Returns: func: The function that computes the classical fisher information matrix. This function accepts the same signature as the :class:`.QNode`. If the signature contains one differentiable variable ``params``, the function returns a matrix of size ``(len(params), len(params))``. For multiple differentiable arguments ``x, y, z``, it returns a list of sizes ``[(len(x), len(x)), (len(y), len(y)), (len(z), len(z))]``. .. warning:: ``pennylane.qinfo.classical_fisher`` is being migrated to a different module and will removed in version 0.39. Instead, use :func:`pennylane.gradients.classical_fisher`. .. seealso:: :func:`~.pennylane.metric_tensor`, :func:`~.pennylane.qinfo.transforms.quantum_fisher` **Example** First, let us define a parametrized quantum state and return its (classical) probability distribution for all computational basis elements: .. code-block:: python import pennylane.numpy as pnp dev = qml.device("default.qubit") @qml.qnode(dev) def circ(params): qml.RX(params[0], wires=0) qml.CNOT([0, 1]) qml.CRY(params[1], wires=[1, 0]) qml.Hadamard(1) return qml.probs(wires=[0, 1]) Executing this circuit yields the ``2**2=4`` elements of :math:`p_\ell(\bm{\theta})` >>> pnp.random.seed(25) >>> params = pnp.random.random(2) >>> circ(params) [0.41850088 0.41850088 0.08149912 0.08149912] We can obtain its ``(2, 2)`` classical fisher information matrix (CFIM) by simply calling the function returned by ``classical_fisher()``: >>> cfim_func = qml.qinfo.classical_fisher(circ) >>> cfim_func(params) [[ 0.901561 -0.125558] [-0.125558 0.017486]] This function has the same signature as the :class:`.QNode`. Here is a small example with multiple arguments: .. code-block:: python @qml.qnode(dev) def circ(x, y): qml.RX(x, wires=0) qml.RY(y, wires=0) return qml.probs(wires=range(n_wires)) >>> x, y = pnp.array([0.5, 0.6], requires_grad=True) >>> circ(x, y) [0.86215007 0. 0.13784993 0. ] >>> qml.qinfo.classical_fisher(circ)(x, y) [array([[0.32934729]]), array([[0.51650396]])] Note how in the case of multiple variables we get a list of matrices with sizes ``[(n_params0, n_params0), (n_params1, n_params1)]``, which in this case is simply two ``(1, 1)`` matrices. A typical setting where the classical fisher information matrix is used is in variational quantum algorithms. Closely related to the `quantum natural gradient <https://arxiv.org/abs/1909.02108>`_, which employs the `quantum` fisher information matrix, we can compute a rescaled gradient using the CFIM. In this scenario, typically a Hamiltonian objective function :math:`\langle H \rangle` is minimized: .. code-block:: python H = qml.Hamiltonian(coeffs=[0.5, 0.5], observables=[qml.Z(0), qml.Z(1)]) @qml.qnode(dev) def circ(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=0) qml.RX(params[2], wires=1) qml.RY(params[3], wires=1) qml.CNOT(wires=(0,1)) return qml.expval(H) params = pnp.random.random(4) We can compute both the gradient of :math:`\langle H \rangle` and the CFIM with the same :class:`.QNode` ``circ`` in this example since ``classical_fisher()`` ignores the return types and assumes ``qml.probs()`` for all wires. >>> grad = qml.grad(circ)(params) >>> cfim = qml.qinfo.classical_fisher(circ)(params) >>> print(grad.shape, cfim.shape) (4,) (4, 4) Combined together, we can get a rescaled gradient to be employed for optimization schemes like natural gradient descent. >>> rescaled_grad = cfim @ grad >>> print(rescaled_grad) [-0.66772533 -0.16618756 -0.05865127 -0.06696078] The ``classical_fisher`` matrix itself is again differentiable: .. code-block:: python @qml.qnode(dev) def circ(params): qml.RX(qml.math.cos(params[0]), wires=0) qml.RX(qml.math.cos(params[0]), wires=1) qml.RX(qml.math.cos(params[1]), wires=0) qml.RX(qml.math.cos(params[1]), wires=1) return qml.probs(wires=range(2)) params = pnp.random.random(2) >>> qml.qinfo.classical_fisher(circ)(params) [[4.18575068e-06 2.34443943e-03] [2.34443943e-03 1.31312079e+00]] >>> qml.jacobian(qml.qinfo.classical_fisher(circ))(params) array([[[9.98030491e-01, 3.46944695e-18], [1.36541817e-01, 5.15248592e-01]], [[1.36541817e-01, 5.15248592e-01], [2.16840434e-18, 2.81967252e-01]]])) """ warnings.warn( "pennylane.qinfo.classical_fisher is being migrated to a different module and will " "removed in version 0.39. Instead, use pennylane.gradients.classical_fisher.", qml.PennyLaneDeprecationWarning, ) return qml.gradients.classical_fisher(qnode, argnums=argnums) @partial(transform, is_informative=True) def quantum_fisher( tape: QuantumScript, device, *args, **kwargs ) -> tuple[QuantumScriptBatch, PostprocessingFn]: r"""Returns a function that computes the quantum fisher information matrix (QFIM) of a given :class:`.QNode`. Given a parametrized quantum state :math:`|\psi(\bm{\theta})\rangle`, the quantum fisher information matrix (QFIM) quantifies how changes to the parameters :math:`\bm{\theta}` are reflected in the quantum state. The metric used to induce the QFIM is the fidelity :math:`f = |\langle \psi | \psi' \rangle|^2` between two (pure) quantum states. This leads to the following definition of the QFIM (see eq. (27) in `arxiv:2103.15191 <https://arxiv.org/abs/2103.15191>`_): .. math:: \text{QFIM}_{i, j} = 4 \text{Re}\left[ \langle \partial_i \psi(\bm{\theta}) | \partial_j \psi(\bm{\theta}) \rangle - \langle \partial_i \psi(\bm{\theta}) | \psi(\bm{\theta}) \rangle \langle \psi(\bm{\theta}) | \partial_j \psi(\bm{\theta}) \rangle \right] with short notation :math:`| \partial_j \psi(\bm{\theta}) \rangle := \frac{\partial}{\partial \theta_j}| \psi(\bm{\theta}) \rangle`. .. seealso:: :func:`~.pennylane.metric_tensor`, :func:`~.pennylane.adjoint_metric_tensor`, :func:`~.pennylane.qinfo.transforms.classical_fisher` Args: tape (QNode or QuantumTape or Callable): A quantum circuit that may have arbitrary return types. *args: In case finite shots are used, further arguments according to :func:`~.pennylane.metric_tensor` may be passed. Returns: qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. Executing this circuit will provide the quantum Fisher information in the form of a tensor. .. warning:: ``pennylane.qinfo.quantum_fisher`` is being migrated to a different module and will removed in version 0.39. Instead, use :func:`pennylane.gradients.quantum_fisher`. .. note:: ``quantum_fisher`` coincides with the ``metric_tensor`` with a prefactor of :math:`4`. Internally, :func:`~.pennylane.adjoint_metric_tensor` is used when executing on ``"default.qubit"`` with exact expectations (``shots=None``). In all other cases, e.g. if a device with finite shots is used, the hardware-compatible transform :func:`~.pennylane.metric_tensor` is used, which may require an additional wire on the device. Please refer to the respective documentations for details. **Example** The quantum Fisher information matrix (QIFM) can be used to compute the `natural` gradient for `Quantum Natural Gradient Descent <https://arxiv.org/abs/1909.02108>`_. A typical scenario is optimizing the expectation value of a Hamiltonian: .. code-block:: python n_wires = 2 dev = qml.device("default.qubit", wires=n_wires) H = 1.*qml.X(0) @ qml.X(1) - 0.5 * qml.Z(1) @qml.qnode(dev) def circ(params): qml.RY(params[0], wires=1) qml.CNOT(wires=(1,0)) qml.RY(params[1], wires=1) qml.RZ(params[2], wires=1) return qml.expval(H) params = pnp.array([0.5, 1., 0.2], requires_grad=True) The natural gradient is then simply the QFIM multiplied by the gradient: >>> grad = qml.grad(circ)(params) >>> grad [ 0.59422561 -0.02615095 -0.05146226] >>> qfim = qml.qinfo.quantum_fisher(circ)(params) >>> qfim [[1. 0. 0. ] [0. 1. 0. ] [0. 0. 0.77517241]] >>> qfim @ grad tensor([ 0.59422561, -0.02615095, -0.03989212], requires_grad=True) When using real hardware or finite shots, ``quantum_fisher`` is internally calling :func:`~.pennylane.metric_tensor`. To obtain the full QFIM, we need an auxilary wire to perform the Hadamard test. >>> dev = qml.device("default.qubit", wires=n_wires+1, shots=1000) >>> @qml.qnode(dev) ... def circ(params): ... qml.RY(params[0], wires=1) ... qml.CNOT(wires=(1,0)) ... qml.RY(params[1], wires=1) ... qml.RZ(params[2], wires=1) ... return qml.expval(H) >>> qfim = qml.qinfo.quantum_fisher(circ)(params) Alternatively, we can fall back on the block-diagonal QFIM without the additional wire. >>> qfim = qml.qinfo.quantum_fisher(circ, approx="block-diag")(params) """ warnings.warn( "pennylane.qinfo.quantum_fisher is being migrated to a different module and will " "removed in version 0.39. Instead, use pennylane.gradients.quantum_fisher.", qml.PennyLaneDeprecationWarning, ) if device.shots or not isinstance(device, (DefaultQubitLegacy, DefaultQubit)): tapes, processing_fn = metric_tensor(tape, *args, **kwargs) def processing_fn_multiply(res): res = qml.execute(res, device=device) return 4 * processing_fn(res) return tapes, processing_fn_multiply res = adjoint_metric_tensor(tape, *args, **kwargs) def processing_fn_multiply(r): # pylint: disable=function-redefined r = qml.math.stack(r) return 4 * r return res, processing_fn_multiply @quantum_fisher.custom_qnode_transform def qnode_execution_wrapper(self, qnode, targs, tkwargs): """Here, we overwrite the QNode execution wrapper in order to take into account that classical processing may be present inside the QNode.""" tkwargs["device"] = qnode.device return self.default_qnode_transform(qnode, targs, tkwargs) def fidelity(qnode0, qnode1, wires0, wires1): r"""Compute the fidelity for two :class:`.QNode` returning a :func:`~pennylane.state` (a state can be a state vector or a density matrix, depending on the device) acting on quantum systems with the same size. The fidelity for two mixed states given by density matrices :math:`\rho` and :math:`\sigma` is defined as .. math:: F( \rho , \sigma ) = \text{Tr}( \sqrt{\sqrt{\rho} \sigma \sqrt{\rho}})^2 If one of the states is pure, say :math:`\rho=\ket{\psi}\bra{\psi}`, then the expression for fidelity simplifies to .. math:: F( \ket{\psi} , \sigma ) = \bra{\psi} \sigma \ket{\psi} Finally, if both states are pure, :math:`\sigma=\ket{\phi}\bra{\phi}`, then the fidelity is simply .. math:: F( \ket{\psi} , \ket{\phi}) = \left|\braket{\psi| \phi}\right|^2 .. note:: The second state is coerced to the type and dtype of the first state. The fidelity is returned in the type of the interface of the first state. Args: state0 (QNode): A :class:`.QNode` returning a :func:`~pennylane.state`. state1 (QNode): A :class:`.QNode` returning a :func:`~pennylane.state`. wires0 (Sequence[int]): the wires of the first subsystem wires1 (Sequence[int]): the wires of the second subsystem Returns: func: A function that returns the fidelity between the states outputted by the QNodes. **Example** First, let's consider two QNodes with potentially different signatures: a circuit with two parameters and another circuit with a single parameter. The output of the :func:`~.qinfo.fidelity` transform then requires two tuples to be passed as arguments, each containing the args and kwargs of their respective circuit, e.g. ``all_args0 = (0.1, 0.3)`` and ``all_args1 = (0.2)`` in the following case: .. code-block:: python dev = qml.device('default.qubit', wires=1) @qml.qnode(dev) def circuit_rx(x, y): qml.RX(x, wires=0) qml.RZ(y, wires=0) return qml.state() @qml.qnode(dev) def circuit_ry(y): qml.RY(y, wires=0) return qml.state() >>> qml.qinfo.fidelity(circuit_rx, circuit_ry, wires0=[0], wires1=[0])((0.1, 0.3), (0.2)) 0.9905158135644924 It is also possible to use QNodes that do not depend on any parameters. When it is the case for the first QNode, it is required to pass an empty tuple as an argument for the first QNode. .. code-block:: python dev = qml.device('default.qubit', wires=1) @qml.qnode(dev) def circuit_rx(): return qml.state() @qml.qnode(dev) def circuit_ry(x): qml.RY(x, wires=0) return qml.state() >>> qml.qinfo.fidelity(circuit_rx, circuit_ry, wires0=[0], wires1=[0])(None, (0.2)) 0.9900332889206207 On the other hand, if the second QNode is the one that does not depend on parameters then a single tuple can also be passed: >>> qml.qinfo.fidelity(circuit_ry, circuit_rx, wires0=[0], wires1=[0])((0.2)) 0.9900332889206207 The :func:`~.qinfo.fidelity` transform is also differentiable and the gradient can be obtained in the different frameworks with backpropagation, the following example uses ``jax`` and ``backprop``. .. code-block:: python dev = qml.device("default.qubit", wires=1) @qml.qnode(dev, interface="jax") def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface="jax") def circuit1(): qml.Z(0) return qml.state() >>> jax.grad(qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0]))((jax.numpy.array(0.3))) Array(-0.14776011, dtype=float64, weak_type=True) There is also the possibility to pass a single dictionary at the end of the tuple for fixing args, you can follow this example: .. code-block:: python dev = qml.device('default.qubit', wires=1) @qml.qnode(dev) def circuit_rx(x, y): qml.RX(x, wires=0) qml.RZ(y, wires=0) return qml.state() @qml.qnode(dev) def circuit_ry(y, use_ry): if use_ry: qml.RY(y, wires=0) return qml.state() >>> fidelity(circuit_rx, circuit_ry, wires0=[0], wires1=[0])((0.1, 0.3), (0.9, {'use_ry': True})) 0.8208074192135424 .. seealso:: :func:`pennylane.math.fidelity` """ if len(wires0) != len(wires1): raise qml.QuantumFunctionError("The two states must have the same number of wires.") state_qnode0 = qml.qinfo.reduced_dm(qnode0, wires=wires0) state_qnode1 = qml.qinfo.reduced_dm(qnode1, wires=wires1) def evaluate_fidelity(all_args0=None, all_args1=None): """Wrapper used for evaluation of the fidelity between two states computed from QNodes. It allows giving the args and kwargs to each :class:`.QNode`. Args: all_args0 (tuple): Tuple containing the arguments (*args, kwargs) of the first :class:`.QNode`. all_args1 (tuple): Tuple containing the arguments (*args, kwargs) of the second :class:`.QNode`. Returns: float: Fidelity between two quantum states """ if not isinstance(all_args0, tuple) and all_args0 is not None: all_args0 = (all_args0,) if not isinstance(all_args1, tuple) and all_args1 is not None: all_args1 = (all_args1,) # If no all_args is given, evaluate the QNode without args if all_args0 is not None: # Handle a dictionary as last argument if isinstance(all_args0[-1], dict): args0 = all_args0[:-1] kwargs0 = all_args0[-1] else: args0 = all_args0 kwargs0 = {} state0 = state_qnode0(*args0, **kwargs0) else: # No args state0 = state_qnode0() # If no all_args is given, evaluate the QNode without args if all_args1 is not None: # Handle a dictionary as last argument if isinstance(all_args1[-1], dict): args1 = all_args1[:-1] kwargs1 = all_args1[-1] else: args1 = all_args1 kwargs1 = {} state1 = state_qnode1(*args1, **kwargs1) else: # No args state1 = state_qnode1() # From the two generated states, compute the fidelity. fid = qml.math.fidelity(state0, state1) return fid return evaluate_fidelity def relative_entropy(qnode0, qnode1, wires0, wires1): r""" Compute the relative entropy for two :class:`.QNode` returning a :func:`~pennylane.state` (a state can be a state vector or a density matrix, depending on the device) acting on quantum systems with the same size. .. math:: S(\rho\,\|\,\sigma)=-\text{Tr}(\rho\log\sigma)-S(\rho)=\text{Tr}(\rho\log\rho)-\text{Tr}(\rho\log\sigma) =\text{Tr}(\rho(\log\rho-\log\sigma)) Roughly speaking, quantum relative entropy is a measure of distinguishability between two quantum states. It is the quantum mechanical analog of relative entropy. Args: qnode0 (QNode): A :class:`.QNode` returning a :func:`~pennylane.state`. qnode1 (QNode): A :class:`.QNode` returning a :func:`~pennylane.state`. wires0 (Sequence[int]): the subsystem of the first QNode wires1 (Sequence[int]): the subsystem of the second QNode Returns: func: A function that takes as input the joint arguments of the two QNodes, and returns the relative entropy from their output states. **Example** Consider the following QNode: .. code-block:: python dev = qml.device('default.qubit', wires=2) @qml.qnode(dev) def circuit(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() The ``qml.qinfo.relative_entropy`` transform can be used to compute the relative entropy between the output states of the QNode: >>> relative_entropy_circuit = qml.qinfo.relative_entropy(circuit, circuit, wires0=[0], wires1=[0]) The returned function takes two tuples as input, the first being the arguments to the first QNode and the second being the arguments to the second QNode: >>> x, y = np.array(0.4), np.array(0.6) >>> relative_entropy_circuit((x,), (y,)) tensor(0.01775001, requires_grad=True) This transform is fully differentiable: .. code-block:: python def wrapper(x, y): return relative_entropy_circuit((x,), (y,)) >>> wrapper(x, y) tensor(0.01775001, requires_grad=True) >>> qml.grad(wrapper)(x, y) (tensor(-0.16458856, requires_grad=True), tensor(0.16953273, requires_grad=True)) """ if len(wires0) != len(wires1): raise qml.QuantumFunctionError("The two states must have the same number of wires.") state_qnode0 = qml.qinfo.reduced_dm(qnode0, wires=wires0) state_qnode1 = qml.qinfo.reduced_dm(qnode1, wires=wires1) def evaluate_relative_entropy(all_args0=None, all_args1=None): """Wrapper used for evaluation of the relative entropy between two states computed from QNodes. It allows giving the args and kwargs to each :class:`.QNode`. Args: all_args0 (tuple): Tuple containing the arguments (*args, kwargs) of the first :class:`.QNode`. all_args1 (tuple): Tuple containing the arguments (*args, kwargs) of the second :class:`.QNode`. Returns: float: Relative entropy between two quantum states """ if not isinstance(all_args0, tuple) and all_args0 is not None: all_args0 = (all_args0,) if not isinstance(all_args1, tuple) and all_args1 is not None: all_args1 = (all_args1,) # If no all_args is given, evaluate the QNode without args if all_args0 is not None: # Handle a dictionary as last argument if isinstance(all_args0[-1], dict): args0 = all_args0[:-1] kwargs0 = all_args0[-1] else: args0 = all_args0 kwargs0 = {} state0 = state_qnode0(*args0, **kwargs0) else: # No args state0 = state_qnode0() # If no all_args is given, evaluate the QNode without args if all_args1 is not None: # Handle a dictionary as last argument if isinstance(all_args1[-1], dict): args1 = all_args1[:-1] kwargs1 = all_args1[-1] else: args1 = all_args1 kwargs1 = {} state1 = state_qnode1(*args1, **kwargs1) else: # No args state1 = state_qnode1() # From the two generated states, compute the relative entropy return qml.math.relative_entropy(state0, state1) return evaluate_relative_entropy def trace_distance(qnode0, qnode1, wires0, wires1): r""" Compute the trace distance for two :class:`.QNode` returning a :func:`~pennylane.state` (a state can be a state vector or a density matrix, depending on the device) acting on quantum systems with the same size. .. math:: T(\rho, \sigma)=\frac12\|\rho-\sigma\|_1 =\frac12\text{Tr}\left(\sqrt{(\rho-\sigma)^{\dagger}(\rho-\sigma)}\right) where :math:`\|\cdot\|_1` is the Schatten :math:`1`-norm. The trace distance measures how close two quantum states are. In particular, it upper-bounds the probability of distinguishing two quantum states. Args: qnode0 (QNode): A :class:`.QNode` returning a :func:`~pennylane.state`. qnode1 (QNode): A :class:`.QNode` returning a :func:`~pennylane.state`. wires0 (Sequence[int]): the subsystem of the first QNode. wires1 (Sequence[int]): the subsystem of the second QNode. Returns: func: A function that takes as input the joint arguments of the two QNodes, and returns the trace distance between their output states. **Example** Consider the following QNode: .. code-block:: python dev = qml.device('default.qubit', wires=2) @qml.qnode(dev) def circuit(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() The ``qml.qinfo.trace_distance`` transform can be used to compute the trace distance between the output states of the QNode: >>> trace_distance_circuit = qml.qinfo.trace_distance(circuit, circuit, wires0=[0], wires1=[0]) The returned function takes two tuples as input, the first being the arguments to the first QNode and the second being the arguments to the second QNode: >>> x, y = np.array(0.4), np.array(0.6) >>> trace_distance_circuit((x,), (y,)) 0.047862689546603415 This transform is fully differentiable: .. code-block:: python def wrapper(x, y): return trace_distance_circuit((x,), (y,)) >>> wrapper(x, y) 0.047862689546603415 >>> qml.grad(wrapper)(x, y) (tensor(-0.19470917, requires_grad=True), tensor(0.28232124, requires_grad=True)) """ if len(wires0) != len(wires1): raise qml.QuantumFunctionError("The two states must have the same number of wires.") state_qnode0 = qml.qinfo.reduced_dm(qnode0, wires=wires0) state_qnode1 = qml.qinfo.reduced_dm(qnode1, wires=wires1) def evaluate_trace_distance(all_args0=None, all_args1=None): """Wrapper used for evaluation of the trace distance between two states computed from QNodes. It allows giving the args and kwargs to each :class:`.QNode`. Args: all_args0 (tuple): Tuple containing the arguments (*args, kwargs) of the first :class:`.QNode`. all_args1 (tuple): Tuple containing the arguments (*args, kwargs) of the second :class:`.QNode`. Returns: float: Trace distance between two quantum states """ if not isinstance(all_args0, tuple) and all_args0 is not None: all_args0 = (all_args0,) if not isinstance(all_args1, tuple) and all_args1 is not None: all_args1 = (all_args1,) # If no all_args is given, evaluate the QNode without args if all_args0 is not None: # Handle a dictionary as last argument if isinstance(all_args0[-1], dict): args0 = all_args0[:-1] kwargs0 = all_args0[-1] else: args0 = all_args0 kwargs0 = {} state0 = state_qnode0(*args0, **kwargs0) else: # No args state0 = state_qnode0() # If no all_args is given, evaluate the QNode without args if all_args1 is not None: # Handle a dictionary as last argument if isinstance(all_args1[-1], dict): args1 = all_args1[:-1] kwargs1 = all_args1[-1] else: args1 = all_args1 kwargs1 = {} state1 = state_qnode1(*args1, **kwargs1) else: # No args state1 = state_qnode1() # From the two generated states, compute the trace distance return qml.math.trace_distance(state0, state1) return evaluate_trace_distance
pennylane/pennylane/qinfo/transforms.py/0
{ "file_path": "pennylane/pennylane/qinfo/transforms.py", "repo_id": "pennylane", "token_count": 18848 }
62
# Copyright 2022 Xanadu Quantum Technologies Inc. # 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. r""" .. currentmodule:: pennylane Measurements ------------ .. autosummary:: :toctree: api ~classical_shadow ~shadow_expval Shadow class for classical post-processing ------------------------------------------ .. autosummary:: :toctree: api ~ClassicalShadow QNode transforms ---------------- .. autosummary:: :toctree: api ~shadows.shadow_expval ~shadows.shadow_state Classical Shadows formalism --------------------------- .. note:: As per `arXiv:2103.07510 <https://arxiv.org/abs/2103.07510>`_, when computing multiple expectation values it is advisable to directly estimate the desired observables by simultaneously measuring qubit-wise-commuting terms. One way of doing this in PennyLane is via :class:`~pennylane.Hamiltonian` and setting ``grouping_type="qwc"``. For more details on this topic, see the PennyLane demo on `estimating expectation values with classical shadows <https://pennylane.ai/qml/demos/tutorial_diffable_shadows.html>`_. A :class:`ClassicalShadow` is a classical description of a quantum state that is capable of reproducing expectation values of local Pauli observables, see `arXiv:2002.08953 <https://arxiv.org/abs/2002.08953>`_. The idea is to capture :math:`T` local snapshots (given by the ``shots`` set in the device) of the state by performing measurements in random Pauli bases at each qubit. The measurement outcomes, denoted ``bits``, as well as the choices of measurement bases, ``recipes``, are recorded in two ``(T, len(wires))`` integer tensors, respectively. From the :math:`t`-th measurement, we can reconstruct the ``local_snapshots`` (see :class:`ClassicalShadow` methods) .. math:: \rho^{(t)} = \bigotimes_{i=1}^{n} 3 U^\dagger_i |b_i \rangle \langle b_i | U_i - \mathbb{I}, where :math:`U_i` is the rotation corresponding to the measurement (e.g. :math:`U_i=H` for measurement in :math:`X`) of qubit :math:`i` at snapshot :math:`t` and :math:`|b_i\rangle = (1 - b_i, b_i)` the corresponding computational basis state given the output bit :math:`b_i`. From these local snapshots, one can compute expectation values of local Pauli strings, where locality refers to the number of non-Identity operators. The accuracy of the procedure is determined by the number of measurements :math:`T` (``shots``). To target an error :math:`\epsilon`, one needs of order :math:`T = \mathcal{O}\left( \log(M) 4^\ell/\epsilon^2 \right)` measurements to determine :math:`M` different, :math:`\ell`-local observables. One can in principle also reconstruct the global state :math:`\sum_t \rho^{(t)}/T`, though it is not advisable nor practical for larger systems due to its exponential scaling. Basic usage ----------- The easiest way of computing expectation values with classical shadows in PennyLane is to return :func:`shadow_expval` directly from the qnode. .. code-block:: python3 H = qml.Hamiltonian([1., 1.], [qml.Z(0) @ qml.Z(1), qml.X(0) @ qml.Z(1)]) dev = qml.device("default.qubit", shots=10000) # shadow_expval + mid-circuit measurements require to defer measurements @qml.defer_measurements @qml.qnode(dev) def qnode(x): qml.Hadamard(0) qml.CNOT((0,1)) qml.RX(x, wires=0) qml.measure(1) return qml.shadow_expval(H) x = np.array(0.5, requires_grad=True) The big advantage of this way of computing expectation values is that it is differentiable. >>> qnode(x) array(0.8406) >>> qml.grad(qnode)(x) -0.49680000000000013 There are more options for post-processing classical shadows in :class:`ClassicalShadow`. """ from .classical_shadow import ClassicalShadow, median_of_means, pauli_expval # allow aliasing in the module namespace from .transforms import shadow_expval, shadow_state
pennylane/pennylane/shadows/__init__.py/0
{ "file_path": "pennylane/pennylane/shadows/__init__.py", "repo_id": "pennylane", "token_count": 1391 }
63
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. r""" Contains the ``DisplacementEmbedding`` template. """ # pylint: disable-msg=too-many-branches,too-many-arguments,protected-access import pennylane as qml from pennylane.operation import AnyWires, Operation class DisplacementEmbedding(Operation): r"""Encodes :math:`N` features into the displacement amplitudes :math:`r` or phases :math:`\phi` of :math:`M` modes, where :math:`N\leq M`. The mathematical definition of the displacement gate is given by the operator .. math:: D(\alpha) = \exp(r (e^{i\phi}\ad -e^{-i\phi}\a)), where :math:`\a` and :math:`\ad` are the bosonic creation and annihilation operators. ``features`` has to be an array of at most ``len(wires)`` floats. If there are fewer entries in ``features`` than wires, the circuit does not apply the remaining displacement gates. Args: features (tensor_like): tensor of features wires (Any or Iterable[Any]): wires that the template acts on method (str): ``'phase'`` encodes the input into the phase of single-mode displacement, while ``'amplitude'`` uses the amplitude c (float): value of the phase of all displacement gates if ``execution='amplitude'``, or the amplitude of all displacement gates if ``execution='phase'`` Raises: ValueError: if inputs do not have the correct format Example: Depending on the ``method`` argument, the feature vector will be encoded in the phase or the amplitude. The argument ``c`` will define the value of the other quantity. The default values are :math:`0.1` for ``c`` and ``'amplitude'`` for ``method``. .. code-block:: python dev = qml.device('default.gaussian', wires=3) @qml.qnode(dev) def circuit(feature_vector): qml.DisplacementEmbedding(features=feature_vector, wires=range(3)) qml.QuadraticPhase(0.1, wires=1) return qml.expval(qml.NumberOperator(wires=1)) X = [1, 2, 3] >>> print(circuit(X)) 4.1215690638748494 And, the resulting circuit is: >>> print(qml.draw(circuit, show_matrices=False)(X)) 0: ─╭DisplacementEmbedding(M0)──────────┤ 1: ─├DisplacementEmbedding(M0)──P(0.10)─┤ <n> 2: ─╰DisplacementEmbedding(M0)──────────┤ Using different parameters: .. code-block:: python dev = qml.device('default.gaussian', wires=3) @qml.qnode(dev) def circuit(feature_vector): qml.DisplacementEmbedding(features=feature_vector, wires=range(3), method='phase', c=0.5) qml.QuadraticPhase(0.1, wires=1) return qml.expval(qml.NumberOperator(wires=1)) X = [1, 2, 3] >>> print(circuit(X)) 0.23401288309122226 And, the resulting circuit is: >>> print(qml.draw(circuit, show_matrices=False)(X)) 0: ─╭DisplacementEmbedding(M0)──────────┤ 1: ─├DisplacementEmbedding(M0)──P(0.10)─┤ <n> 2: ─╰DisplacementEmbedding(M0)──────────┤ """ num_wires = AnyWires grad_method = None @classmethod def _unflatten(cls, data, metadata): new_op = cls.__new__(cls) Operation.__init__(new_op, *data, wires=metadata[0]) return new_op def __init__(self, features, wires, method="amplitude", c=0.1, id=None): shape = qml.math.shape(features) constants = [c] * shape[0] constants = qml.math.convert_like(constants, features) if len(shape) != 1: raise ValueError(f"Features must be a one-dimensional tensor; got shape {shape}.") n_features = shape[0] if n_features != len(wires): raise ValueError(f"Features must be of length {len(wires)}; got length {n_features}.") if method == "amplitude": pars = qml.math.stack([features, constants], axis=1) elif method == "phase": pars = qml.math.stack([constants, features], axis=1) else: raise ValueError(f"did not recognize method {method}") super().__init__(pars, wires=wires, id=id) @property def num_params(self): return 1 @staticmethod def compute_decomposition(pars, wires): # pylint: disable=arguments-differ r"""Representation of the operator as a product of other operators. .. math:: O = O_1 O_2 \dots O_n. .. seealso:: :meth:`~.DisplacementEmbedding.decomposition`. Args: pars (tensor_like): parameters extracted from features and constant wires (Any or Iterable[Any]): wires that the template acts on Returns: list[.Operator]: decomposition of the operator **Example** >>> pars = torch.tensor([[1., 0.], [2., 0.]]) >>> qml.DisplacementEmbedding.compute_decomposition(pars, wires=[0, 1]) [Displacement(tensor(1.), tensor(0.), wires=[0]), Displacement(tensor(2.), tensor(0.), wires=[1])] """ return [ qml.Displacement(pars[i, 0], pars[i, 1], wires=wires[i : i + 1]) for i in range(len(wires)) ]
pennylane/pennylane/templates/embeddings/displacement.py/0
{ "file_path": "pennylane/pennylane/templates/embeddings/displacement.py", "repo_id": "pennylane", "token_count": 2438 }
64
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. r""" Contains the BasisStatePreparation template. """ import numpy as np import pennylane as qml from pennylane.operation import AnyWires, Operation class BasisStatePreparation(Operation): r""" Prepares a basis state on the given wires using a sequence of Pauli-X gates. .. warning:: ``basis_state`` influences the circuit architecture and is therefore incompatible with gradient computations. Args: basis_state (array): Input array of shape ``(n,)``, where n is the number of wires the state preparation acts on. wires (Iterable): wires that the template acts on **Example** .. code-block:: python dev = qml.device("default.qubit", wires=4) @qml.qnode(dev) def circuit(basis_state): qml.BasisStatePreparation(basis_state, wires=range(4)) return [qml.expval(qml.Z(i)) for i in range(4)] basis_state = [0, 1, 1, 0] >>> print(circuit(basis_state)) [ 1. -1. -1. 1.] """ num_params = 1 num_wires = AnyWires grad_method = None ndim_params = (1,) def __init__(self, basis_state, wires, id=None): basis_state = qml.math.stack(basis_state) # check if the `basis_state` param is batched batched = len(qml.math.shape(basis_state)) > 1 state_batch = basis_state if batched else [basis_state] for i, state in enumerate(state_batch): shape = qml.math.shape(state) if len(shape) != 1: raise ValueError( f"Basis states must be one-dimensional; state {i} has shape {shape}." ) n_bits = shape[0] if n_bits != len(wires): raise ValueError( f"Basis states must be of length {len(wires)}; state {i} has length {n_bits}." ) if not qml.math.is_abstract(state): if any(bit not in [0, 1] for bit in state): raise ValueError( f"Basis states must only consist of 0s and 1s; state {i} is {state}" ) # TODO: basis_state should be a hyperparameter, not a trainable parameter. # However, this breaks a test that ensures compatibility with batch_transform. # The transform should be rewritten to support hyperparameters as well. super().__init__(basis_state, wires=wires, id=id) @staticmethod def compute_decomposition(basis_state, wires): # pylint: disable=arguments-differ r"""Representation of the operator as a product of other operators. .. math:: O = O_1 O_2 \dots O_n. .. seealso:: :meth:`~.BasisStatePreparation.decomposition`. Args: basis_state (array): Input array of shape ``(len(wires),)`` wires (Any or Iterable[Any]): wires that the operator acts on Returns: list[.Operator]: decomposition of the operator **Example** >>> qml.BasisStatePreparation.compute_decomposition(basis_state=[1, 1], wires=["a", "b"]) [X('a'), X('b')] """ if len(qml.math.shape(basis_state)) > 1: raise ValueError( "Broadcasting with BasisStatePreparation is not supported. Please use the " "qml.transforms.broadcast_expand transform to use broadcasting with " "BasisStatePreparation." ) if not qml.math.is_abstract(basis_state): op_list = [] for wire, state in zip(wires, basis_state): if state == 1: op_list.append(qml.X(wire)) return op_list op_list = [] for wire, state in zip(wires, basis_state): op_list.append(qml.PhaseShift(state * np.pi / 2, wire)) op_list.append(qml.RX(state * np.pi, wire)) op_list.append(qml.PhaseShift(state * np.pi / 2, wire)) return op_list
pennylane/pennylane/templates/state_preparations/basis.py/0
{ "file_path": "pennylane/pennylane/templates/state_preparations/basis.py", "repo_id": "pennylane", "token_count": 1974 }
65
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. r""" Contains the FermionicSingleExcitation template. """ # pylint: disable-msg=too-many-branches,too-many-arguments,protected-access import numpy as np import pennylane as qml from pennylane.operation import AnyWires, Operation from pennylane.ops import CNOT, RX, RZ, Hadamard class FermionicSingleExcitation(Operation): r"""Circuit to exponentiate the tensor product of Pauli matrices representing the single-excitation operator entering the Unitary Coupled-Cluster Singles and Doubles (UCCSD) ansatz. UCCSD is a VQE ansatz commonly used to run quantum chemistry simulations. The CC single-excitation operator is given by .. math:: \hat{U}_{pr}(\theta) = \mathrm{exp} \{ \theta_{pr} (\hat{c}_p^\dagger \hat{c}_r -\mathrm{H.c.}) \}, where :math:`\hat{c}` and :math:`\hat{c}^\dagger` are the fermionic annihilation and creation operators and the indices :math:`r` and :math:`p` run over the occupied and unoccupied molecular orbitals, respectively. Using the `Jordan-Wigner transformation <https://arxiv.org/abs/1208.5986>`_ the fermionic operator defined above can be written in terms of Pauli matrices (for more details see `arXiv:1805.04340 <https://arxiv.org/abs/1805.04340>`_). .. math:: \hat{U}_{pr}(\theta) = \mathrm{exp} \Big\{ \frac{i\theta}{2} \bigotimes_{a=r+1}^{p-1}\hat{Z}_a (\hat{Y}_r \hat{X}_p) \Big\} \mathrm{exp} \Big\{ -\frac{i\theta}{2} \bigotimes_{a=r+1}^{p-1} \hat{Z}_a (\hat{X}_r \hat{Y}_p) \Big\}. The quantum circuit to exponentiate the tensor product of Pauli matrices entering the latter equation is shown below (see `arXiv:1805.04340 <https://arxiv.org/abs/1805.04340>`_): | .. figure:: ../../_static/templates/subroutines/single_excitation_unitary.png :align: center :width: 60% :target: javascript:void(0); | As explained in `Seely et al. (2012) <https://arxiv.org/abs/1208.5986>`_, the exponential of a tensor product of Pauli-Z operators can be decomposed in terms of :math:`2(n-1)` CNOT gates and a single-qubit Z-rotation referred to as :math:`U_\theta` in the figure above. If there are :math:`X` or :math:`Y` Pauli matrices in the product, the Hadamard (:math:`H`) or :math:`R_x` gate has to be applied to change to the :math:`X` or :math:`Y` basis, respectively. The latter operations are denoted as :math:`U_1` and :math:`U_2` in the figure above. See the Usage Details section for more information. Args: weight (float): angle :math:`\theta` entering the Z rotation acting on wire ``p`` wires (Iterable): Wires that the template acts on. The wires represent the subset of orbitals in the interval ``[r, p]``. Must be of minimum length 2. The first wire is interpreted as ``r`` and the last wire as ``p``. Wires in between are acted on with CNOT gates to compute the parity of the set of qubits. .. details:: :title: Usage Details Notice that: #. :math:`\hat{U}_{pr}(\theta)` involves two exponentiations where :math:`\hat{U}_1`, :math:`\hat{U}_2`, and :math:`\hat{U}_\theta` are defined as follows, .. math:: [U_1, U_2, U_{\theta}] = \Bigg\{\bigg[R_x(-\pi/2), H, R_z(\theta/2)\bigg], \bigg[H, R_x(-\frac{\pi}{2}), R_z(-\theta/2) \bigg] \Bigg\} #. For a given pair ``[r, p]``, ten single-qubit and ``4*(len(wires)-1)`` CNOT operations are applied. Notice also that CNOT gates act only on qubits ``wires[1]`` to ``wires[-2]``. The operations performed across these qubits are shown in dashed lines in the figure above. An example of how to use this template is shown below: .. code-block:: python import pennylane as qml dev = qml.device('default.qubit', wires=3) @qml.qnode(dev) def circuit(weight, wires=None): qml.FermionicSingleExcitation(weight, wires=wires) return qml.expval(qml.Z(0)) weight = 0.56 print(circuit(weight, wires=[0, 1, 2])) """ num_wires = AnyWires grad_method = "A" parameter_frequencies = [(0.5, 1.0)] def __init__(self, weight, wires=None, id=None): if len(wires) < 2: raise ValueError(f"expected at least two wires; got {len(wires)}") shape = qml.math.shape(weight) if shape != (): raise ValueError(f"Weight must be a scalar tensor {()}; got shape {shape}.") super().__init__(weight, wires=wires, id=id) @property def num_params(self): return 1 @staticmethod def compute_decomposition(weight, wires): # pylint: disable=arguments-differ r"""Representation of the operator as a product of other operators. .. math:: O = O_1 O_2 \dots O_n. .. seealso:: :meth:`~.FermionicSingleExcitation.decomposition`. Args: weight (float): angle entering the Z rotation wires (Any or Iterable[Any]): wires that the operator acts on Returns: list[.Operator]: decomposition of the operator """ # Interpret first and last wire as r and p r = wires[0] p = wires[-1] # Sequence of the wires entering the CNOTs between wires 'r' and 'p' set_cnot_wires = [wires[l : l + 2] for l in range(len(wires) - 1)] op_list = [] # ------------------------------------------------------------------ # Apply the first layer # U_1, U_2 acting on wires 'r' and 'p' op_list.append(RX(-np.pi / 2, wires=r)) op_list.append(Hadamard(wires=p)) # Applying CNOTs between wires 'r' and 'p' for cnot_wires in set_cnot_wires: op_list.append(CNOT(wires=cnot_wires)) # Z rotation acting on wire 'p' op_list.append(RZ(weight / 2, wires=p)) # Applying CNOTs in reverse order for cnot_wires in reversed(set_cnot_wires): op_list.append(CNOT(wires=cnot_wires)) # U_1^+, U_2^+ acting on wires 'r' and 'p' op_list.append(RX(np.pi / 2, wires=r)) op_list.append(Hadamard(wires=p)) # ------------------------------------------------------------------ # Apply the second layer # U_1, U_2 acting on wires 'r' and 'p' op_list.append(Hadamard(wires=r)) op_list.append(RX(-np.pi / 2, wires=p)) # Applying CNOTs between wires 'r' and 'p' for cnot_wires in set_cnot_wires: op_list.append(CNOT(wires=cnot_wires)) # Z rotation acting on wire 'p' op_list.append(RZ(-weight / 2, wires=p)) # Applying CNOTs in reverse order for cnot_wires in reversed(set_cnot_wires): op_list.append(CNOT(wires=cnot_wires)) # U_1^+, U_2^+ acting on wires 'r' and 'p' op_list.append(Hadamard(wires=r)) op_list.append(RX(np.pi / 2, wires=p)) return op_list
pennylane/pennylane/templates/subroutines/fermionic_single_excitation.py/0
{ "file_path": "pennylane/pennylane/templates/subroutines/fermionic_single_excitation.py", "repo_id": "pennylane", "token_count": 3258 }
66
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """ Contains the QuantumPhaseEstimation template. """ # pylint: disable=too-many-arguments,arguments-differ import copy import pennylane as qml from pennylane.operation import AnyWires, Operator from pennylane.queuing import QueuingManager from pennylane.resource.error import ErrorOperation, SpectralNormError from pennylane.wires import Wires class QuantumPhaseEstimation(ErrorOperation): r"""Performs the `quantum phase estimation <https://en.wikipedia.org/wiki/Quantum_phase_estimation_algorithm>`__ circuit. Given a unitary matrix :math:`U`, this template applies the circuit for quantum phase estimation. The unitary is applied to the qubits specified by ``target_wires`` and :math:`n` qubits are used for phase estimation as specified by ``estimation_wires``. .. figure:: ../../_static/templates/subroutines/qpe.svg :align: center :width: 60% :target: javascript:void(0); Args: unitary (array or Operator): the phase estimation unitary, specified as a matrix or an :class:`~.Operator` target_wires (Union[Wires, Sequence[int], or int]): the target wires to apply the unitary. If the unitary is specified as an operator, the target wires should already have been defined as part of the operator. In this case, target_wires should not be specified. estimation_wires (Union[Wires, Sequence[int], or int]): the wires to be used for phase estimation Raises: QuantumFunctionError: if the ``target_wires`` and ``estimation_wires`` share a common element, or if ``target_wires`` are specified for an operator unitary. .. details:: :title: Usage Details This circuit can be used to perform the standard quantum phase estimation algorithm, consisting of the following steps: #. Prepare ``target_wires`` in a given state. If ``target_wires`` are prepared in an eigenstate of :math:`U` that has corresponding eigenvalue :math:`e^{2 \pi i \theta}` with phase :math:`\theta \in [0, 1)`, this algorithm will measure :math:`\theta`. Other input states can be prepared more generally. #. Apply the ``QuantumPhaseEstimation`` circuit. #. Measure ``estimation_wires`` using :func:`~.probs`, giving a probability distribution over measurement outcomes in the computational basis. #. Find the index of the largest value in the probability distribution and divide that number by :math:`2^{n}`. This number will be an estimate of :math:`\theta` with an error that decreases exponentially with the number of qubits :math:`n`. Note that if :math:`\theta \in (-1, 0]`, we can estimate the phase by again finding the index :math:`i` found in step 4 and calculating :math:`\theta \approx \frac{1 - i}{2^{n}}`. An example of this case is below. Consider the matrix corresponding to a rotation from an :class:`~.RX` gate: .. code-block:: python import pennylane as qml from pennylane.templates import QuantumPhaseEstimation from pennylane import numpy as np phase = 5 target_wires = [0] unitary = qml.RX(phase, wires=0).matrix() The ``phase`` parameter can be estimated using ``QuantumPhaseEstimation``. An example is shown below using a register of five phase-estimation qubits: .. code-block:: python n_estimation_wires = 5 estimation_wires = range(1, n_estimation_wires + 1) dev = qml.device("default.qubit", wires=n_estimation_wires + 1) @qml.qnode(dev) def circuit(): # Start in the |+> eigenstate of the unitary qml.Hadamard(wires=target_wires) QuantumPhaseEstimation( unitary, target_wires=target_wires, estimation_wires=estimation_wires, ) return qml.probs(estimation_wires) phase_estimated = np.argmax(circuit()) / 2 ** n_estimation_wires # Need to rescale phase due to convention of RX gate phase_estimated = 4 * np.pi * (1 - phase_estimated) We can also perform phase estimation on an operator. Note that since operators are defined with target wires, the target wires should not be provided for the QPE. .. code-block:: python # use the product to specify compound operators unitary = qml.RX(np.pi / 2, wires=[0]) @ qml.CNOT(wires=[0, 1]) eigenvector = np.array([-1/2, -1/2, 1/2, 1/2]) n_estimation_wires = 5 estimation_wires = range(2, n_estimation_wires + 2) target_wires = [0, 1] dev = qml.device("default.qubit", wires=n_estimation_wires + 2) @qml.qnode(dev) def circuit(): qml.StatePrep(eigenvector, wires=target_wires) QuantumPhaseEstimation( unitary, estimation_wires=estimation_wires, ) return qml.probs(estimation_wires) phase_estimated = np.argmax(circuit()) / 2 ** n_estimation_wires """ num_wires = AnyWires grad_method = None # pylint: disable=no-member def _flatten(self): data = (self.hyperparameters["unitary"],) metadata = (self.hyperparameters["estimation_wires"],) return data, metadata @classmethod def _primitive_bind_call(cls, *args, **kwargs): return cls._primitive.bind(*args, **kwargs) @classmethod def _unflatten(cls, data, metadata) -> "QuantumPhaseEstimation": return cls(data[0], estimation_wires=metadata[0]) def __init__(self, unitary, target_wires=None, estimation_wires=None, id=None): if isinstance(unitary, Operator): # If the unitary is expressed in terms of operators, do not provide target wires if target_wires is not None: raise qml.QuantumFunctionError( "The unitary is expressed as an operator, which already has target wires " "defined, do not additionally specify target wires." ) target_wires = unitary.wires elif target_wires is None: raise qml.QuantumFunctionError( "Target wires must be specified if the unitary is expressed as a matrix." ) else: unitary = qml.QubitUnitary(unitary, wires=target_wires) # Estimation wires are required, but kept as an optional argument so that it can be # placed after target_wires for backwards compatibility. if estimation_wires is None: raise qml.QuantumFunctionError("No estimation wires specified.") target_wires = qml.wires.Wires(target_wires) estimation_wires = qml.wires.Wires(estimation_wires) wires = target_wires + estimation_wires if any(wire in target_wires for wire in estimation_wires): raise qml.QuantumFunctionError( "The target wires and estimation wires must not overlap." ) self._hyperparameters = { "unitary": unitary, "target_wires": target_wires, "estimation_wires": estimation_wires, } super().__init__(wires=wires, id=id) @property def target_wires(self): """The target wires of the QPE""" return self._hyperparameters["target_wires"] @property def estimation_wires(self): """The estimation wires of the QPE""" return self._hyperparameters["estimation_wires"] def error(self): """The QPE error computed from the spectral norm error of the input unitary operator. **Example** >>> class CustomOP(qml.resource.ErrorOperation): ... def error(self): ... return qml.resource.SpectralNormError(0.005) >>> Op = CustomOP(wires=[0]) >>> QPE = QuantumPhaseEstimation(Op, estimation_wires = range(1, 5)) >>> QPE.error() SpectralNormError(0.075) """ base_unitary = self._hyperparameters["unitary"] if not isinstance(base_unitary, ErrorOperation): return SpectralNormError(0.0) unitary_error = base_unitary.error().error sequence_error = qml.math.array( [unitary_error * (2**i) for i in range(len(self.estimation_wires) - 1, -1, -1)], like=qml.math.get_interface(unitary_error), ) additive_error = qml.math.sum(sequence_error) return SpectralNormError(additive_error) # pylint: disable=protected-access def map_wires(self, wire_map: dict): new_op = copy.deepcopy(self) new_op._wires = Wires([wire_map.get(wire, wire) for wire in self.wires]) new_op._hyperparameters["unitary"] = qml.map_wires( new_op._hyperparameters["unitary"], wire_map ) for key in ["estimation_wires", "target_wires"]: new_op._hyperparameters[key] = [ wire_map.get(wire, wire) for wire in self.hyperparameters[key] ] return new_op def queue(self, context=QueuingManager): context.remove(self._hyperparameters["unitary"]) context.append(self) return self @staticmethod def compute_decomposition( wires, unitary, target_wires, estimation_wires ): # pylint: disable=arguments-differ,unused-argument r"""Representation of the QPE circuit as a product of other operators. .. math:: O = O_1 O_2 \dots O_n. .. seealso:: :meth:`~.QuantumPhaseEstimation.decomposition`. Args: wires (Any or Iterable[Any]): wires that the QPE circuit acts on unitary (Operator): the phase estimation unitary, specified as an operator target_wires (Any or Iterable[Any]): the target wires to apply the unitary estimation_wires (Any or Iterable[Any]): the wires to be used for phase estimation Returns: list[.Operator]: decomposition of the operator """ op_list = [qml.Hadamard(w) for w in estimation_wires] pow_ops = (qml.pow(unitary, 2**i) for i in range(len(estimation_wires) - 1, -1, -1)) op_list.extend(qml.ctrl(op, w) for op, w in zip(pow_ops, estimation_wires)) op_list.append(qml.adjoint(qml.templates.QFT(wires=estimation_wires))) return op_list
pennylane/pennylane/templates/subroutines/qpe.py/0
{ "file_path": "pennylane/pennylane/templates/subroutines/qpe.py", "repo_id": "pennylane", "token_count": 4620 }
67
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # 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. """Transform for adding a noise model to a quantum circuit or device""" from copy import copy from functools import lru_cache import pennylane as qml from pennylane.transforms.core import TransformContainer, transform @transform def add_noise(tape, noise_model, level=None): """Insert operations according to a provided noise model. Circuits passed through this quantum transform will be updated to apply the insertion-based :class:`~.NoiseModel`, which contains a mapping ``{BooleanFn: Callable}`` from conditions to the corresponding noise gates. Each condition in the noise model will be evaluated on the operations contained within the given circuit. For conditions that evaluate to ``True``, the noisy gates contained within the ``Callable`` will be inserted after the operation under consideration. Args: tape (QNode or QuantumTape or Callable or pennylane.devices.Device): the input circuit or device to be transformed. noise_model (~pennylane.NoiseModel): noise model according to which noise has to be inserted. level (None, str, int, slice): An indication of which stage in the transform program the noise model should be applied to. Only relevant when transforming a ``QNode``. More details on the following permissible values can be found in the :func:`~.workflow.get_transform_program` - * ``None``: expands the tape to have no ``Adjoint`` and ``Templates``. * ``str``: acceptable keys are ``"top"``, ``"user"``, ``"device"``, and ``"gradient"``. * ``int``: how many transforms to include, starting from the front of the program. * ``slice``: a slice to select out components of the transform program. Returns: qnode (QNode) or quantum function (Callable) or tuple[List[.QuantumTape], function] or device (pennylane.devices.Device): Transformed circuit as described in :func:`qml.transform <pennylane.transform>`. Raises: ValueError: argument ``noise_model`` is not a valid noise model. .. note:: For a given ``model_map`` within a ``NoiseModel``, if multiple conditionals in the ``model_map`` evaluate to ``True`` for an operation, then the noise operations defined via their respective noisy quantum functions will be added in the same order in which the conditionals appear in the ``model_map``. **Example:** The following QNode can be transformed to add noise to the circuit: .. code-block:: python3 from functools import partial dev = qml.device("default.mixed", wires=2) fcond1 = qml.noise.op_eq(qml.RX) & qml.noise.wires_in([0, 1]) noise1 = qml.noise.partial_wires(qml.PhaseDamping, 0.4) fcond2 = qml.noise.op_in([qml.RX, qml.RZ]) def noise2(op, **kwargs): qml.ThermalRelaxationError(op.parameters[0] * 0.5, kwargs["t1"], kwargs["t2"], 0.6, op.wires) noise_model = qml.NoiseModel({fcond1: noise1, fcond2: noise2}, t1=2.0, t2=0.2) @partial(qml.transforms.add_noise, noise_model=noise_model) @qml.qnode(dev) def circuit(w, x, y, z): qml.RX(w, wires=0) qml.RY(x, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(y, wires=0) qml.RX(z, wires=1) return qml.expval(qml.Z(0) @ qml.Z(1)) Executions of this circuit will differ from the noise-free value: .. code-block:: python >>> circuit(0.9, 0.4, 0.5, 0.6) array(0.544053) >>> print(qml.draw(circuit)(0.9, 0.4, 0.5, 0.6)) 0: ──RX(0.90)──PhaseDamping(0.40)──ThermalRelaxationError(0.45,2.00,0.20,0.60)─╭●──RY(0.50) 1: ──RY(0.40)──────────────────────────────────────────────────────────────────╰X──RX(0.60) ───────────────────────────────────────────────────────────────────┤ ╭<Z@Z> ───PhaseDamping(0.40)──ThermalRelaxationError(0.30,2.00,0.20,0.60)─┤ ╰<Z@Z> .. details:: :title: Tranform Levels :href: add-noise-levels When transforming an already constructed ``QNode``, the ``add_noise`` transform will be added at the end of the "user" transforms by default, i.e., after all the transforms that have been manually applied to the QNode up to that point. .. code-block:: python3 dev = qml.device("default.mixed", wires=2) @qml.metric_tensor @qml.transforms.undo_swaps @qml.transforms.merge_rotations @qml.transforms.cancel_inverses @qml.qnode(dev) def circuit(w, x, y, z): qml.RX(w, wires=0) qml.RY(x, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(y, wires=0) qml.RX(z, wires=1) return qml.expval(qml.Z(0) @ qml.Z(1)) noisy_circuit = qml.transforms.add_noise(circuit, noise_model) >>> qml.workflow.get_transform_program(circuit) TransformProgram(cancel_inverses, merge_rotations, undo_swaps, _expand_metric_tensor, batch_transform, expand_fn, metric_tensor) >>> qml.workflow.get_transform_program(noisy_circuit) TransformProgram(cancel_inverses, merge_rotations, undo_swaps, _expand_metric_tensor, add_noise, batch_transform, expand_fn, metric_tensor) However, one can request to insert the ``add_noise`` transform at any specific point in the transform program. By specifying the ``level`` keyword argument while transforming a ``QNode``, this transform can be added at a designated level within the transform program, as determined using the :func:`get_transform_program <pennylane.workflow.get_transform_program>`. For example, specifying ``None`` will add it at the end, ensuring that the tape is expanded to have no ``Adjoint`` and ``Templates``: >>> qml.transforms.add_noise(circuit, noise_model, level=None).transform_program TransformProgram(cancel_inverses, merge_rotations, undo_swaps, _expand_metric_tensor, batch_transform, expand_fn, add_noise, metric_tensor) Other acceptable values for ``level`` are ``"top"``, ``"user"``, ``"device"``, and ``"gradient"``. Among these, `"top"` will allow addition to an empty transform program, `"user"` will allow addition at the end of user-specified transforms, `"device"` will allow addition at the end of device-specific transforms, and `"gradient"` will allow addition at the end of transforms that expand trainable operations. For example: >>> qml.transforms.add_noise(circuit, noise_model, level="top").transform_program TransformProgram(add_noise) >>> qml.transforms.add_noise(circuit, noise_model, level="user").transform_program TransformProgram(cancel_inverses, merge_rotations, undo_swaps, _expand_metric_tensor, add_noise, metric_tensor) >>> qml.transforms.add_noise(circuit, noise_model, level="device").transform_program TransformProgram(cancel_inverses, merge_rotations, undo_swaps, _expand_metric_tensor, batch_transform, expand_fn, add_noise, metric_tensor) Finally, more precise control over the insertion of the transform can be achieved by specifying an integer or slice for indexing when extracting the transform program. For example, one can do: >>> qml.transforms.add_noise(circuit, noise_model, level=2).transform_program TransformProgram(cancel_inverses, merge_rotations, add_noise) >>> qml.transforms.add_noise(circuit, noise_model, level=slice(1,3)).transform_program TransformProgram(merge_rotations, undo_swaps, add_noise) """ if not hasattr(noise_model, "model_map") or not hasattr(noise_model, "metadata"): raise ValueError( f"Provided noise model object must define model_map and metatadata attributes, got {noise_model}." ) if level is None or level == "user": # decompose templates and their adjoints def stop_at(obj): if not isinstance(obj, qml.operation.Operator): return True if not obj.has_decomposition: return True return not (hasattr(qml.templates, obj.name) or isinstance(obj, qml.ops.Adjoint)) error_type = (qml.operation.DecompositionUndefinedError,) decompose = qml.devices.preprocess.decompose [tape], _ = decompose(tape, stopping_condition=stop_at, name="add_noise", error=error_type) conditions, noises = [], [] metadata = noise_model.metadata for condition, noise in noise_model.model_map.items(): conditions.append(lru_cache(maxsize=512)(condition)) noises.append(qml.tape.make_qscript(noise)) new_operations = [] for operation in tape.operations: curr_ops = [operation] for condition, noise in zip(conditions, noises): if condition(operation): noise_ops = noise(operation, **metadata).operations if operation in noise_ops and _check_queue_op(operation, noise, metadata): ops_indx = noise_ops.index(operation) curr_ops = noise_ops[:ops_indx] + curr_ops + noise_ops[ops_indx + 1 :] else: curr_ops.extend(noise_ops) new_operations.extend(curr_ops) new_tape = type(tape)(new_operations, tape.measurements, shots=tape.shots) post_processing_fn = qml.devices.preprocess.null_postprocessing return [new_tape], post_processing_fn def _check_queue_op(operation, noise_func, metadata): """Performs a secondary check for existence of an operation in the queue using a randomized ID""" test_id = "f49968bfc4W0H86df3A733bf6e92904d21a_!$-T-@!_c131S549b169b061I25b85398bfd8ec1S3c" test_queue = noise_func( qml.noise.partial_wires(operation, id=test_id)(operation.wires), **metadata ).operations return any(test_id == getattr(o, "id", "") for o in test_queue) # pylint:disable = protected-access @add_noise.custom_qnode_transform def custom_qnode_wrapper(self, qnode, targs, tkwargs): """QNode execution wrapper for supporting ``add_noise`` with levels""" cqnode = copy(qnode) level = tkwargs.get("level", "user") transform_program = qml.workflow.get_transform_program(qnode, level=level) cqnode._transform_program = transform_program cqnode.add_transform( TransformContainer( self._transform, targs, {**tkwargs}, self._classical_cotransform, self._is_informative, self._final_transform, ) ) return cqnode
pennylane/pennylane/transforms/add_noise.py/0
{ "file_path": "pennylane/pennylane/transforms/add_noise.py", "repo_id": "pennylane", "token_count": 4442 }
68
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # 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. """ Contains the batch dimension transform. """ import itertools # pylint: disable=import-outside-toplevel from collections import Counter from collections.abc import Sequence import numpy as np import pennylane as qml from pennylane.measurements import ( CountsMP, ExpectationMP, MeasurementValue, MidMeasureMP, ProbabilityMP, SampleMP, VarianceMP, ) from pennylane.tape import QuantumScript, QuantumScriptBatch from pennylane.typing import PostprocessingFn, TensorLike from .core import transform fill_in_value = np.iinfo(np.int32).min def is_mcm(operation): """Returns True if the operation is a mid-circuit measurement and False otherwise.""" mcm = isinstance(operation, MidMeasureMP) return mcm or "MidCircuitMeasure" in str(type(operation)) def null_postprocessing(results): """A postprocessing function returned by a transform that only converts the batch of results into a result for a single ``QuantumTape``. """ return results[0] @transform def dynamic_one_shot(tape: QuantumScript, **kwargs) -> tuple[QuantumScriptBatch, PostprocessingFn]: """Transform a QNode to into several one-shot tapes to support dynamic circuit execution. Args: tape (QNode or QuantumTape or Callable): a quantum circuit to add a batch dimension to. Returns: qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. This circuit will provide the results of a dynamic execution. **Example** Consider the following circuit: .. code-block:: python dev = qml.device("default.qubit", shots=100) params = np.pi / 4 * np.ones(2) @qml.dynamic_one_shot @qml.qnode(dev) def func(x, y): qml.RX(x, wires=0) m0 = qml.measure(0) qml.cond(m0, qml.RY)(y, wires=1) return qml.expval(op=m0) The ``qml.dynamic_one_shot`` decorator prompts the QNode to perform a hundred one-shot calculations, where in each calculation the ``qml.measure`` operations dynamically measures the 0-wire and collapse the state vector stochastically. This transforms contrasts with ``qml.defer_measurements``, which instead introduces an extra wire for each mid-circuit measurement. The ``qml.dynamic_one_shot`` transform is favorable in the few-shots several-mid-circuit-measurement limit, whereas ``qml.defer_measurements`` is favorable in the opposite limit. """ if not any(is_mcm(o) for o in tape.operations): return (tape,), null_postprocessing for m in tape.measurements: if not isinstance(m, (CountsMP, ExpectationMP, ProbabilityMP, SampleMP, VarianceMP)): raise TypeError( f"Native mid-circuit measurement mode does not support {type(m).__name__} " "measurements." ) _ = kwargs.get("device", None) if not tape.shots: raise qml.QuantumFunctionError("dynamic_one_shot is only supported with finite shots.") samples_present = any(isinstance(mp, SampleMP) for mp in tape.measurements) postselect_present = any(op.postselect is not None for op in tape.operations if is_mcm(op)) if postselect_present and samples_present and tape.batch_size is not None: raise ValueError( "Returning qml.sample is not supported when postselecting mid-circuit " "measurements with broadcasting" ) if (batch_size := tape.batch_size) is not None: tapes, broadcast_fn = qml.transforms.broadcast_expand(tape) else: tapes = [tape] broadcast_fn = None aux_tapes = [init_auxiliary_tape(t) for t in tapes] postselect_mode = kwargs.get("postselect_mode", None) def reshape_data(array): return qml.math.squeeze(qml.math.vstack(array)) def processing_fn(results, has_partitioned_shots=None, batched_results=None): if batched_results is None and batch_size is not None: # If broadcasting, recursively process the results for each batch. For each batch # there are tape.shots.total_shots results. The length of the first axis of final_results # will be batch_size. final_results = [] for result in results: final_results.append(processing_fn((result,), batched_results=False)) return broadcast_fn(final_results) if has_partitioned_shots is None and tape.shots.has_partitioned_shots: # If using shot vectors, recursively process the results for each shot bin. The length # of the first axis of final_results will be the length of the shot vector. results = list(results[0]) final_results = [] for s in tape.shots: final_results.append( processing_fn(results[0:s], has_partitioned_shots=False, batched_results=False) ) del results[0:s] return tuple(final_results) if not tape.shots.has_partitioned_shots: results = results[0] is_scalar = not isinstance(results[0], Sequence) if is_scalar: results = [reshape_data(tuple(results))] else: results = [ reshape_data(tuple(res[i] for res in results)) for i, _ in enumerate(results[0]) ] return parse_native_mid_circuit_measurements( tape, aux_tapes, results, postselect_mode=postselect_mode ) return aux_tapes, processing_fn @dynamic_one_shot.custom_qnode_transform def _dynamic_one_shot_qnode(self, qnode, targs, tkwargs): """Custom qnode transform for ``dynamic_one_shot``.""" if tkwargs.get("device", None): raise ValueError( "Cannot provide a 'device' value directly to the dynamic_one_shot decorator " "when transforming a QNode." ) if qnode.device is not None: support_mcms = hasattr(qnode.device, "capabilities") and qnode.device.capabilities().get( "supports_mid_measure", False ) support_mcms = support_mcms or qnode.device.name in ("default.qubit", "lightning.qubit") if not support_mcms: raise TypeError( f"Device {qnode.device.name} does not support mid-circuit measurements " "natively, and hence it does not support the dynamic_one_shot transform. " "'default.qubit' and 'lightning.qubit' currently support mid-circuit " "measurements and the dynamic_one_shot transform." ) tkwargs.setdefault("device", qnode.device) return self.default_qnode_transform(qnode, targs, tkwargs) def init_auxiliary_tape(circuit: qml.tape.QuantumScript): """Creates an auxiliary circuit to perform one-shot mid-circuit measurement calculations. Measurements are replaced by SampleMP measurements on wires and observables found in the original measurements. Args: circuit (QuantumTape): The original QuantumScript Returns: QuantumScript: A copy of the circuit with modified measurements """ new_measurements = [] for m in circuit.measurements: if not m.mv: if isinstance(m, VarianceMP): new_measurements.append(SampleMP(obs=m.obs)) else: new_measurements.append(m) for op in circuit.operations: if "MidCircuitMeasure" in str(type(op)): # pragma: no cover new_measurements.append(qml.sample(op.out_classical_tracers[0])) elif isinstance(op, MidMeasureMP): new_measurements.append(qml.sample(MeasurementValue([op], lambda res: res))) return qml.tape.QuantumScript( circuit.operations, new_measurements, shots=[1] * circuit.shots.total_shots, trainable_params=circuit.trainable_params, ) # pylint: disable=too-many-branches,too-many-statements def parse_native_mid_circuit_measurements( circuit: qml.tape.QuantumScript, aux_tapes: qml.tape.QuantumScript, results: TensorLike, postselect_mode=None, ): """Combines, gathers and normalizes the results of native mid-circuit measurement runs. Args: circuit (QuantumTape): The original ``QuantumScript``. aux_tapes (List[QuantumTape]): List of auxiliary ``QuantumScript`` objects. results (TensorLike): Array of measurement results. Returns: tuple(TensorLike): The results of the simulation. """ def measurement_with_no_shots(measurement): return ( np.nan * np.ones_like(measurement.eigvals()) if isinstance(measurement, ProbabilityMP) else np.nan ) interface = qml.math.get_deep_interface(results) interface = "numpy" if interface == "builtins" else interface interface = "tensorflow" if interface == "tf" else interface active_qjit = qml.compiler.active() all_mcms = [op for op in aux_tapes[0].operations if is_mcm(op)] n_mcms = len(all_mcms) mcm_samples = qml.math.hstack( tuple(qml.math.reshape(res, (-1, 1)) for res in results[-n_mcms:]) ) mcm_samples = qml.math.array(mcm_samples, like=interface) # Can't use boolean dtype array with tf, hence why conditionally setting items to 0 or 1 has_postselect = qml.math.array( [[op.postselect is not None for op in all_mcms]], like=interface, dtype=mcm_samples.dtype, ) postselect = qml.math.array( [[0 if op.postselect is None else op.postselect for op in all_mcms]], like=interface, dtype=mcm_samples.dtype, ) is_valid = qml.math.all(mcm_samples * has_postselect == postselect, axis=1) has_valid = qml.math.any(is_valid) mid_meas = [op for op in circuit.operations if is_mcm(op)] mcm_samples = [mcm_samples[:, i : i + 1] for i in range(n_mcms)] mcm_samples = dict((k, v) for k, v in zip(mid_meas, mcm_samples)) normalized_meas = [] m_count = 0 for m in circuit.measurements: if not isinstance(m, (CountsMP, ExpectationMP, ProbabilityMP, SampleMP, VarianceMP)): raise TypeError( f"Native mid-circuit measurement mode does not support {type(m).__name__} measurements." ) if interface != "jax" and m.mv and not has_valid: meas = measurement_with_no_shots(m) elif m.mv and active_qjit: meas = gather_mcm_qjit( m, mcm_samples, is_valid, postselect_mode=postselect_mode ) # pragma: no cover elif m.mv: meas = gather_mcm(m, mcm_samples, is_valid, postselect_mode=postselect_mode) elif interface != "jax" and not has_valid: meas = measurement_with_no_shots(m) m_count += 1 else: result = results[m_count] if not isinstance(m, CountsMP): # We don't need to cast to arrays when using qml.counts. qml.math.array is not viable # as it assumes all elements of the input are of builtin python types and not belonging # to any particular interface result = qml.math.array(result, like=interface) if active_qjit: # pragma: no cover # `result` contains (bases, counts) need to return (basis, sum(counts)) where `is_valid` # Any row of `result[0]` contains basis, so we return `result[0][0]` # We return the sum of counts (`result[1]`) weighting by `is_valid`, which is `0` for invalid samples if isinstance(m, CountsMP): normalized_meas.append( ( result[0][0], qml.math.sum(result[1] * qml.math.reshape(is_valid, (-1, 1)), axis=0), ) ) m_count += 1 continue result = qml.math.squeeze(result) meas = gather_non_mcm(m, result, is_valid, postselect_mode=postselect_mode) m_count += 1 if isinstance(m, SampleMP): meas = qml.math.squeeze(meas) normalized_meas.append(meas) return tuple(normalized_meas) if len(normalized_meas) > 1 else normalized_meas[0] def gather_mcm_qjit(measurement, samples, is_valid, postselect_mode=None): # pragma: no cover """Process MCM measurements when the Catalyst compiler is active. Args: measurement (MeasurementProcess): measurement samples (dict): Mid-circuit measurement samples is_valid (TensorLike): Boolean array with the same shape as ``samples`` where the value at each index specifies whether or not the respective sample is valid. Returns: TensorLike: The combined measurement outcome """ found, meas = False, None for k, meas in samples.items(): if measurement.mv is k.out_classical_tracers[0]: found = True break if not found: raise LookupError("MCM not found") meas = qml.math.squeeze(meas) if isinstance(measurement, (CountsMP, ProbabilityMP)): interface = qml.math.get_interface(is_valid) sum_valid = qml.math.sum(is_valid) count_1 = qml.math.sum(meas * is_valid) if isinstance(measurement, CountsMP): return qml.math.array([0, 1], like=interface), qml.math.array( [sum_valid - count_1, count_1], like=interface ) if isinstance(measurement, ProbabilityMP): counts = qml.math.array([sum_valid - count_1, count_1], like=interface) return counts / sum_valid return gather_non_mcm(measurement, meas, is_valid, postselect_mode=postselect_mode) def gather_non_mcm(measurement, samples, is_valid, postselect_mode=None): """Combines, gathers and normalizes several measurements with trivial measurement values. Args: measurement (MeasurementProcess): measurement samples (TensorLike): Post-processed measurement samples is_valid (TensorLike): Boolean array with the same shape as ``samples`` where the value at each index specifies whether or not the respective sample is valid. Returns: TensorLike: The combined measurement outcome """ if isinstance(measurement, CountsMP): tmp = Counter() for i, d in enumerate(samples): tmp.update( {k if isinstance(k, str) else float(k): v * is_valid[i] for k, v in d.items()} ) if not measurement.all_outcomes: tmp = Counter({k: v for k, v in tmp.items() if v > 0}) return dict(sorted(tmp.items())) if isinstance(measurement, SampleMP): if postselect_mode == "pad-invalid-samples" and samples.ndim == 2: is_valid = qml.math.reshape(is_valid, (-1, 1)) if postselect_mode == "pad-invalid-samples": return qml.math.where(is_valid, samples, fill_in_value) if qml.math.shape(samples) == (): # single shot case samples = qml.math.reshape(samples, (-1, 1)) return samples[is_valid] if (interface := qml.math.get_interface(is_valid)) == "tensorflow": # Tensorflow requires arrays that are used for arithmetic with each other to have the # same dtype. We don't cast if measuring samples as float tf.Tensors cannot be used to # index other tf.Tensors (is_valid is used to index valid samples). is_valid = qml.math.cast_like(is_valid, samples) if isinstance(measurement, ExpectationMP): return qml.math.sum(samples * is_valid) / qml.math.sum(is_valid) if isinstance(measurement, ProbabilityMP): return qml.math.sum(samples * qml.math.reshape(is_valid, (-1, 1)), axis=0) / qml.math.sum( is_valid ) # VarianceMP expval = qml.math.sum(samples * is_valid) / qml.math.sum(is_valid) if interface == "tensorflow": # Casting needed for tensorflow samples = qml.math.cast_like(samples, expval) is_valid = qml.math.cast_like(is_valid, expval) return qml.math.sum((samples - expval) ** 2 * is_valid) / qml.math.sum(is_valid) def gather_mcm(measurement, samples, is_valid, postselect_mode=None): """Combines, gathers and normalizes several measurements with non-trivial measurement values. Args: measurement (MeasurementProcess): measurement samples (List[dict]): Mid-circuit measurement samples is_valid (TensorLike): Boolean array with the same shape as ``samples`` where the value at each index specifies whether or not the respective sample is valid. Returns: TensorLike: The combined measurement outcome """ interface = qml.math.get_deep_interface(is_valid) mv = measurement.mv # The following block handles measurement value lists, like ``qml.counts(op=[mcm0, mcm1, mcm2])``. if isinstance(measurement, (CountsMP, ProbabilityMP, SampleMP)) and isinstance(mv, Sequence): mcm_samples = [m.concretize(samples) for m in mv] mcm_samples = qml.math.concatenate(mcm_samples, axis=1) if isinstance(measurement, ProbabilityMP): values = [list(m.branches.values()) for m in mv] values = list(itertools.product(*values)) values = [qml.math.array([v], like=interface, dtype=mcm_samples.dtype) for v in values] # Need to use boolean functions explicitly as Tensorflow does not allow integer math # on boolean arrays counts = [ qml.math.count_nonzero( qml.math.logical_and(qml.math.all(mcm_samples == v, axis=1), is_valid) ) for v in values ] counts = qml.math.array(counts, like=interface) return counts / qml.math.sum(counts) if isinstance(measurement, CountsMP): mcm_samples = [{"".join(str(int(v)) for v in tuple(s)): 1} for s in mcm_samples] return gather_non_mcm(measurement, mcm_samples, is_valid, postselect_mode=postselect_mode) mcm_samples = qml.math.ravel(qml.math.array(mv.concretize(samples), like=interface)) if isinstance(measurement, ProbabilityMP): # Need to use boolean functions explicitly as Tensorflow does not allow integer math # on boolean arrays counts = [ qml.math.count_nonzero(qml.math.logical_and((mcm_samples == v), is_valid)) for v in list(mv.branches.values()) ] counts = qml.math.array(counts, like=interface) return counts / qml.math.sum(counts) if isinstance(measurement, CountsMP): mcm_samples = [{float(s): 1} for s in mcm_samples] return gather_non_mcm(measurement, mcm_samples, is_valid, postselect_mode=postselect_mode)
pennylane/pennylane/transforms/dynamic_one_shot.py/0
{ "file_path": "pennylane/pennylane/transforms/dynamic_one_shot.py", "repo_id": "pennylane", "token_count": 8120 }
69
# 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. """ Contains the sign (and xi) decomposition tape transform, implementation of ideas from arXiv:2207.09479 """ # pylint: disable=protected-access import json from os import path import numpy as np import pennylane as qml from pennylane.tape import QuantumScript, QuantumScriptBatch from pennylane.transforms import transform from pennylane.typing import PostprocessingFn def controlled_pauli_evolution(theta, wires, pauli_word, controls): r"""Controlled Evolution under generic Pauli words, adapted from the decomposition of qml.PauliRot to suit our needs Args: theta (float): rotation angle :math:`\theta` pauli_word (string): the Pauli word defining the rotation wires (Iterable, Wires): the wires the operation acts on controls (List[control1, control2]): The two additional controls to implement the Hadamard test and the quantum signal processing part on Returns: list[Operator]: decomposition that make up the controlled evolution """ active_wires, active_gates = zip( *[(wire, gate) for wire, gate in zip(wires, pauli_word) if gate != "I"] ) ops = [] for wire, gate in zip(active_wires, active_gates): if gate in ("X", "Y"): ops.append( qml.Hadamard(wires=[wire]) if gate == "X" else qml.RX(-np.pi / 2, wires=[wire]) ) ops.append(qml.CNOT(wires=[controls[1], wires[0]])) ops.append(qml.ctrl(op=qml.MultiRZ(theta, wires=list(active_wires)), control=controls[0])) ops.append(qml.CNOT(wires=[controls[1], wires[0]])) for wire, gate in zip(active_wires, active_gates): if gate in ("X", "Y"): ops.append( qml.Hadamard(wires=[wire]) if gate == "X" else qml.RX(-np.pi / 2, wires=[wire]) ) return ops def evolve_under(ops, coeffs, time, controls): """ Evolves under the given Hamiltonian deconstructed into its Pauli words Args: ops (List[Observables]): List of Pauli words that comprise the Hamiltonian coeffs (List[int]): List of the respective coefficients of the Pauliwords of the Hamiltonian time (float): At what time to evaluate these Pauliwords """ ops_temp = [] for op, coeff in zip(ops, coeffs): pauli_word = qml.pauli.pauli_word_to_string(op) ops_temp.append( controlled_pauli_evolution( coeff * time, wires=op.wires, pauli_word=pauli_word, controls=controls, ) ) return ops_temp def calculate_xi_decomposition(hamiltonian): r""" Calculates the Xi-decomposition from the given Hamiltonian by constructing the sparse matrix representing the Hamiltonian, finding its spectrum and then construct projectors and eigenvalue spacings Definition of the Xi decomposition of operator O: .. math:: \frac{\lambda_0 +\lambda_J}{2} \mathbb{1} + \sum_{x=1}^{J-1} \frac{\delta \lambda_x}{2}\Xi_x , where the lambdas are the sorted eigenvalues of O and ..math:: \Xi_x = \mathbb{1} - \sum_(j<x) 2 \Pi_j \,, \quad \delta \lambda_x = \lambda_x - \lambda_{x-1} Args: hamiltonian (qml.Hamiltonian): The pennylane Hamiltonian to be decomposed Returns: dEs (List[float]): The energy (E_1-E-2)/2 separating the two eigenvalues of the spectrum mus (List[float]): The average between the two eigenvalues (E_1+E-2)/2 times (List[float]): The time for this term group to be evaluated/evolved at projs (List[np.array]): The analytical observables associated with these groups, to be measured by qml.Hermitian """ mat = hamiltonian.sparse_matrix().toarray() size = len(mat) eigs, eigvecs = np.linalg.eigh(mat) norm = eigs[-1] proj = np.identity(size, dtype="complex64") def Pi(j): """Projector on eigenspace of eigenvalue E_i""" return np.outer(np.conjugate(eigvecs[:, j]), eigvecs[:, j]) proj += -2 * Pi(0) last_i = 1 dEs, mus, projs, times = [], [], [], [] for index in range(len(eigs) - 1): dE = (eigs[index + 1] - eigs[index]) / 2 if np.isclose(dE, 0): continue dEs.append(dE) mu = (eigs[index + 1] + eigs[index]) / 2 mus.append(mu) time = np.pi / (2 * (norm + abs(mu))) times.append(time) for j in range(last_i, index + 1): proj += -2 * Pi(j) last_i = index + 1 projs.append(proj.copy() * dE) return dEs, mus, times, projs def construct_sgn_circuit( # pylint: disable=too-many-arguments hamiltonian, tape, mus, times, phis, controls ): """ Takes a tape with state prep and ansatz and constructs the individual tapes approximating/estimating the individual terms of your decomposition Args: hamiltonian (qml.Hamiltonian): The pennylane Hamiltonian to be decomposed tape (qml.QuantumTape: Tape containing the circuit to be expanded into the new circuits mus (List[float]): The average between the two eigenvalues (E_1+E-2)/2 times (List[float]): The time for this term group to be evaluated/evolved at phis (List[float]): Optimal phi values for the QSP part associated with the respective delta and J controls (List[control1, control2]): The two additional controls to implement the Hadamard test and the quantum signal processing part on Returns: tapes (List[qml.tape]): Expanded tapes from the original tape that measures the terms via the approximate sgn decomposition """ coeffs = hamiltonian.data tapes = [] for mu, time in zip(mus, times): added_operations = [] # Put QSP and Hadamard test on the two ancillas Target and Control added_operations.append(qml.Hadamard(controls[0])) for i, phi in enumerate(phis): added_operations.append(qml.CRX(phi, wires=controls)) if i == len(phis) - 1: added_operations.append(qml.CRY(np.pi, wires=controls)) else: for ops in evolve_under(hamiltonian.ops, coeffs, 2 * time, controls): added_operations.extend(ops) added_operations.append(qml.CRZ(-2 * mu * time, wires=controls)) added_operations.append(qml.Hadamard(controls[0])) operations = tape.operations + added_operations if tape.measurements[0].return_type == qml.measurements.Expectation: measurements = [qml.expval(-1 * qml.Z(controls[0]))] else: measurements = [qml.var(qml.Z(controls[0]))] new_tape = qml.tape.QuantumScript(operations, measurements, shots=tape.shots) tapes.append(new_tape) return tapes @transform def sign_expand( # pylint: disable=too-many-arguments tape: QuantumScript, circuit=False, J=10, delta=0.0, controls=("Hadamard", "Target") ) -> tuple[QuantumScriptBatch, PostprocessingFn]: r""" Splits a tape measuring a (fast-forwardable) Hamiltonian expectation into mutliple tapes of the Xi or sgn decomposition, and provides a function to recombine the results. Implementation of ideas from arXiv:2207.09479 For the calculation of variances, one assumes an even distribution of shots among the groups. Args: tape (QNode or QuantumTape): the quantum circuit used when calculating the expectation value of the Hamiltonian circuit (bool): Toggle the calculation of the analytical Xi decomposition or if True constructs the circuits of the approximate sign decomposition to measure the expectation value J (int): The times the time evolution of the hamiltonian is repeated in the quantum signal processing approximation of the sgn-decomposition delta (float): The minimal controls (List[control1, control2]): The two additional controls to implement the Hadamard test and the quantum signal processing part on, have to be wires on the device Returns: qnode (pennylane.QNode) or tuple[List[.QuantumTape], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. **Example** Given a Hamiltonian, .. code-block:: python3 H = qml.Z(0) + 0.5 * qml.Z(2) + qml.Z(1) a device with auxiliary qubits, .. code-block:: python3 dev = qml.device("default.qubit", wires=[0,1,2,'Hadamard','Target']) and a circuit of the form, with the transform as decorator. .. code-block:: python3 @qml.transforms.sign_expand @qml.qnode(dev) def circuit(): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.X(2) return qml.expval(H) >>> circuit() -0.4999999999999999 You can also work directly on tapes: .. code-block:: python3 operations = [qml.Hadamard(wires=0), qml.CNOT(wires=[0, 1]), qml.X(2)] measurements = [qml.expval(H)] tape = qml.tape.QuantumTape(operations, measurements) We can use the ``sign_expand`` transform to generate new tapes and a classical post-processing function for computing the expectation value of the Hamiltonian in these new decompositions >>> tapes, fn = qml.transforms.sign_expand(tape) We can evaluate these tapes on a device, it needs two additional ancilla gates labeled 'Hadamard' and 'Target' if one wants to make the circuit approximation of the decomposition: >>> dev = qml.device("default.qubit", wires=[0,1,2,'Hadamard','Target']) >>> res = dev.execute(tapes) >>> fn(res) -0.4999999999999999 To evaluate the circuit approximation of the decomposition one can construct the sgn-decomposition by changing the kwarg circuit to True: >>> tapes, fn = qml.transforms.sign_expand(tape, circuit=True, J=20, delta=0) >>> dev = qml.device("default.qubit", wires=[0,1,2,'Hadamard','Target']) >>> dev.execute(tapes) >>> fn(res) -0.24999999999999994 Lastly, as the paper is about minimizing variance, one can also calculate the variance of the estimator by changing the tape: .. code-block:: python3 operations = [qml.Hadamard(wires=0), qml.CNOT(wires=[0, 1]), qml.X(2)] measurements = [qml.var(H)] tape = qml.tape.QuantumTape(operations, measurements) >>> tapes, fn = qml.transforms.sign_expand(tape, circuit=True, J=20, delta=0) >>> dev = qml.device("default.qubit", wires=[0,1,2,'Hadamard','Target']) >>> res = dev.execute(tapes) >>> fn(res) 10.108949481425782 """ path_str = path.dirname(__file__) with open(path_str + "/sign_expand_data.json", "r", encoding="utf-8") as f: data = json.load(f) phis = list(filter(lambda data: data["delta"] == delta and data["order"] == J, data))[0][ "opt_params" ] hamiltonian = tape.measurements[0].obs wires = hamiltonian.wires # TODO qml.utils.sparse_hamiltonian at the moment does not allow autograd to push gradients through if ( not isinstance(hamiltonian, (qml.ops.Hamiltonian, qml.ops.LinearCombination)) or len(tape.measurements) > 1 or tape.measurements[0].return_type not in [qml.measurements.Expectation, qml.measurements.Variance] ): raise ValueError( "Passed tape must end in `qml.expval(H)` or 'qml.var(H)', where H is of type `qml.Hamiltonian`" ) hamiltonian.compute_grouping() if len(hamiltonian.grouping_indices) != 1: raise ValueError("Passed hamiltonian must be jointly measurable") dEs, mus, times, projs = calculate_xi_decomposition(hamiltonian) if circuit: tapes = construct_sgn_circuit(hamiltonian, tape, mus, times, phis, controls) if tape.measurements[0].return_type == qml.measurements.Expectation: # pylint: disable=function-redefined def processing_fn(res): products = [a * b for a, b in zip(res, dEs)] return qml.math.sum(products) else: # pylint: disable=function-redefined def processing_fn(res): products = [a * b for a, b in zip(res, dEs)] return qml.math.sum(products) * len(products) return tapes, processing_fn # make one tape per observable tapes = [] for proj in projs: if tape.measurements[0].return_type == qml.measurements.Expectation: measurements = [qml.expval(qml.Hermitian(proj, wires=wires))] else: measurements = [qml.var(qml.Hermitian(proj, wires=wires))] new_tape = qml.tape.QuantumScript(tape.operations, measurements, shots=tape.shots) tapes.append(new_tape) # pylint: disable=function-redefined def processing_fn(res): return ( qml.math.sum(res) if tape.measurements[0].return_type == qml.measurements.Expectation else qml.math.sum(res) * len(res) ) return tapes, processing_fn
pennylane/pennylane/transforms/sign_expand/sign_expand.py/0
{ "file_path": "pennylane/pennylane/transforms/sign_expand/sign_expand.py", "repo_id": "pennylane", "token_count": 5507 }
70
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """ This module contains functions for adding the Autograd interface to a PennyLane Device class. **How to bind a custom derivative with autograd.** Suppose I have a function ``f`` that I want to change how autograd takes the derivative of. I need to: 1) Mark it as an autograd primitive with ``@autograd.extend.primitive`` 2) Register its VJP with ``autograd.extend.defvjp`` .. code-block:: python @autograd.extend.primitive def f(x, exponent=2): return x**exponent def vjp(ans, x, exponent=2): def grad_fn(dy): print(f"Calculating the gradient with {x}, {dy}") return dy * exponent * x**(exponent-1) return grad_fn autograd.extend.defvjp(f, vjp, argnums=[0]) >>> autograd.grad(f)(autograd.numpy.array(2.0)) Calculating the gradient with 2.0, 1.0 4.0 The above code told autograd how to differentiate the first argument of ``f``. We have an additional problem that autograd does not understand that a :class:`~.QuantumTape` contains parameters we want to differentiate. So in order to match the ``vjp`` function with the correct parameters, we need to extract them from the batch of tapes, and pass them as is as the first argument to the primitive. Even though the primitive function does not use the parameters, that is how we communicate to autograd what parameters the derivatives belong to. **Jacobian Calculations and the need for caching:** Suppose we use the above function with an array and take the jacobian: >>> x = autograd.numpy.array([1.0, 2.0]) >>> autograd.jacobian(f)(x) Calculating the gradient with [1. 2.], [1. 0.] Calculating the gradient with [1. 2.], [0. 1.] array([[2., 0.], [0., 4.]]) Here, the ``grad_fn`` was called once for each output quantity. Each time ``grad_fn`` is called, we are forced to reproduce the calculation for ``exponent * x ** (exponent-1)``, only to multiply it by a different vector. When executing quantum circuits, that quantity can potentially be quite expensive. Autograd would naively request indepedent vjps for each entry in the output, even though the internal circuits will be exactly the same. When caching is enabled, the expensive part (re-executing identical circuits) is avoided, but when normal caching is turned off, the above can lead to an explosion in the number of required circuit executions. To avoid this explosion in the number of executed circuits when caching is turned off, we will instead internally cache the full jacobian so that is is reused between different calls to the same ``grad_fn``. This behaviour is toggled by the ``cache_full_jacobian`` keyword argument to :class:`~.TransformJacobianProducts`. Other interfaces are capable of calculating the full jacobian in one call, so this patch is only present for autograd. """ # pylint: disable=too-many-arguments, unused-argument import logging from collections.abc import Callable import autograd from autograd.numpy.numpy_boxes import ArrayBox import pennylane as qml from pennylane.tape import QuantumScriptBatch ExecuteFn = Callable[[QuantumScriptBatch], qml.typing.ResultBatch] logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) # pylint: disable=unused-argument def autograd_execute( tapes: QuantumScriptBatch, execute_fn: ExecuteFn, jpc: qml.workflow.jacobian_products.JacobianProductCalculator, device=None, ): """Execute a batch of tapes with Autograd parameters on a device. Args: tapes (Sequence[.QuantumTape]): batch of tapes to execute execute_fn (Callable[[Sequence[.QuantumTape]], ResultBatch]): a function that turns a batch of circuits into results jpc (JacobianProductCalculator): a class that can compute the vector Jacobian product (VJP) for the input tapes. Returns: TensorLike: A nested tuple of tape results. Each element in the returned tuple corresponds in order to the provided tapes. **Example:** >>> from pennylane.workflow.jacobian_products import DeviceDerivatives >>> from pennylane.workflow.autograd import autograd_execute >>> execute_fn = qml.device('default.qubit').execute >>> config = qml.devices.ExecutionConfig(gradient_method="adjoint", use_device_gradient=True) >>> jpc = DeviceDerivatives(qml.device('default.qubit'), config) >>> def f(x): ... tape = qml.tape.QuantumScript([qml.RX(x, 0)], [qml.expval(qml.Z(0))]) ... batch = (tape, ) ... return autograd_execute(batch, execute_fn, jpc) >>> qml.grad(f)(qml.numpy.array(0.1)) -0.09983341664682815 """ tapes = tuple(tapes) if logger.isEnabledFor(logging.DEBUG): logger.debug("Entry with (tapes=%s, execute_fn=%s, jpc=%s)", tapes, execute_fn, jpc) for tape in tapes: # set the trainable parameters params = tape.get_parameters(trainable_only=False) tape.trainable_params = qml.math.get_trainable_indices(params) # pylint misidentifies autograd.builtins as a dict # pylint: disable=no-member parameters = autograd.builtins.tuple( [autograd.builtins.list(t.get_parameters()) for t in tapes] ) return _execute(parameters, tuple(tapes), execute_fn, jpc) @autograd.extend.primitive def _execute( parameters, tapes, execute_fn, jpc, ): # pylint: disable=unused-argument """Autodifferentiable wrapper around a way of executing tapes. Args: parameters (list[list[Any]]): Nested list of the quantum tape parameters. This argument should be generated from the provided list of tapes. tapes (Sequence[.QuantumTape]): batch of tapes to execute execute_fn (Callable[[Sequence[.QuantumTape]], ResultBatch]): a function that turns a batch of circuits into results jpc (JacobianProductCalculator): a class that can compute the vector Jacobian product (VJP) for the input tapes. """ return execute_fn(tapes) # pylint: disable=unused-argument def vjp( ans, parameters, tapes, execute_fn, jpc, ): """Returns the vector-Jacobian product operator for a batch of quantum tapes. Args: ans (array): the result of the batch tape execution parameters (list[list[Any]]): Nested list of the quantum tape parameters. This argument should be generated from the provided list of tapes. tapes (Sequence[.QuantumTape]): batch of tapes to execute execute_fn (Callable[[Sequence[.QuantumTape]], ResultBatch]): a function that turns a batch of circuits into results jpc (JacobianProductCalculator): a class that can compute the vector Jacobian product (VJP) for the input tapes. Returns: function: this function accepts the backpropagation gradient output vector, and computes the vector-Jacobian product """ def grad_fn(dy): """Returns the vector-Jacobian product with given parameter values and output gradient dy""" vjps = jpc.compute_vjp(tapes, dy) return tuple( qml.math.to_numpy(v, max_depth=1) if isinstance(v, ArrayBox) else v for v in vjps ) return grad_fn autograd.extend.defvjp(_execute, vjp, argnums=[0])
pennylane/pennylane/workflow/interfaces/autograd.py/0
{ "file_path": "pennylane/pennylane/workflow/interfaces/autograd.py", "repo_id": "pennylane", "token_count": 2672 }
71
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # 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. """ Tests for capturing conditionals into jaxpr. """ # pylint: disable=redefined-outer-name, too-many-arguments # pylint: disable=no-self-use import numpy as np import pytest import pennylane as qml from pennylane.ops.op_math.condition import CondCallable, ConditionalTransformError pytestmark = pytest.mark.jax jax = pytest.importorskip("jax") # must be below jax importorskip from pennylane.capture.primitives import cond_prim # pylint: disable=wrong-import-position @pytest.fixture(autouse=True) def enable_disable_plxpr(): """Enable and disable the PennyLane JAX capture context manager.""" qml.capture.enable() yield qml.capture.disable() @pytest.fixture def testing_functions(): """Returns a set of functions for testing.""" def true_fn(arg): return 2 * arg def elif_fn1(arg): return arg - 1 def elif_fn2(arg): return arg - 2 def elif_fn3(arg): return arg - 3 def elif_fn4(arg): return arg - 4 def false_fn(arg): return 3 * arg return true_fn, false_fn, elif_fn1, elif_fn2, elif_fn3, elif_fn4 @pytest.mark.parametrize("decorator", [True, False]) class TestCond: """Tests for conditional functions using qml.cond.""" @pytest.mark.parametrize( "selector, arg, expected", [ (1, 10, 20), # True condition (-1, 10, 9), # Elif condition 1 (-2, 10, 8), # Elif condition 2 (-3, 10, 7), # Elif condition 3 (-4, 10, 6), # Elif condition 4 (0, 10, 30), # False condition ], ) def test_cond_true_elifs_false(self, testing_functions, selector, arg, expected, decorator): """Test the conditional with true, elifs, and false branches.""" true_fn, false_fn, elif_fn1, elif_fn2, elif_fn3, elif_fn4 = testing_functions def test_func(pred): if decorator: conditional = qml.cond(pred > 0)(true_fn) conditional.else_if(pred == -1)(elif_fn1) conditional.else_if(pred == -2)(elif_fn2) conditional.else_if(pred == -3)(elif_fn3) conditional.else_if(pred == -4)(elif_fn4) conditional.otherwise(false_fn) return conditional return qml.cond( pred > 0, true_fn, false_fn, elifs=( (pred == -1, elif_fn1), (pred == -2, elif_fn2), (pred == -3, elif_fn3), (pred == -4, elif_fn4), ), ) result = test_func(selector)(arg) assert np.allclose(result, expected), f"Expected {expected}, but got {result}" jaxpr = jax.make_jaxpr(test_func(selector))(arg) assert jaxpr.eqns[0].primitive == cond_prim res_ev_jxpr = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, arg) assert np.allclose(res_ev_jxpr, expected), f"Expected {expected}, but got {res_ev_jxpr}" # Note that this would fail by running the abstract evaluation of the jaxpr # because the false branch must be provided if the true branch returns any variables. @pytest.mark.parametrize( "selector, arg, expected", [ (1, 10, 20), # True condition (-1, 10, 9), # Elif condition 1 (-2, 10, 8), # Elif condition 2 (-3, 10, ()), # No condition met ], ) def test_cond_true_elifs(self, testing_functions, selector, arg, expected, decorator): """Test the conditional with true and elifs branches.""" true_fn, _, elif_fn1, elif_fn2, _, _ = testing_functions def test_func(pred): if decorator: conditional = qml.cond(pred > 0)(true_fn) conditional.else_if(pred == -1)(elif_fn1) conditional.else_if(pred == -2)(elif_fn2) return conditional return qml.cond( pred > 0, true_fn, elifs=( (pred == -1, elif_fn1), (pred == -2, elif_fn2), ), ) result = test_func(selector)(arg) assert np.allclose(result, expected), f"Expected {expected}, but got {result}" @pytest.mark.parametrize( "selector, arg, expected", [ (1, 10, 20), (0, 10, 30), ], ) def test_cond_true_false(self, testing_functions, selector, arg, expected, decorator): """Test the conditional with true and false branches.""" true_fn, false_fn, _, _, _, _ = testing_functions def test_func(pred): if decorator: conditional = qml.cond(pred > 0)(true_fn) conditional.otherwise(false_fn) return conditional return qml.cond( pred > 0, true_fn, false_fn, ) result = test_func(selector)(arg) assert np.allclose(result, expected), f"Expected {expected}, but got {result}" jaxpr = jax.make_jaxpr(test_func(selector))(arg) res_ev_jxpr = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, arg) assert np.allclose(res_ev_jxpr, expected), f"Expected {expected}, but got {res_ev_jxpr}" # Note that this would fail by running the abstract evaluation of the jaxpr # because the false branch must be provided if the true branch returns any variables. @pytest.mark.parametrize( "selector, arg, expected", [ (1, 10, 20), (0, 10, ()), ], ) def test_cond_true(self, testing_functions, selector, arg, expected, decorator): """Test the conditional with only the true branch.""" true_fn, _, _, _, _, _ = testing_functions def test_func(pred): if decorator: conditional = qml.cond(pred > 0)(true_fn) return conditional return qml.cond( pred > 0, true_fn, ) result = test_func(selector)(arg) assert np.allclose(result, expected), f"Expected {expected}, but got {result}" @pytest.mark.parametrize( "selector, arg, expected", [ (1, jax.numpy.array([2, 3]), 12), (0, jax.numpy.array([2, 3]), 15), ], ) def test_cond_with_jax_array(self, selector, arg, expected, decorator): """Test the conditional with array arguments.""" def true_fn(jax_array): return jax_array[0] * jax_array[1] * 2.0 def false_fn(jax_array): return jax_array[0] * jax_array[1] * 2.5 def test_func(pred): if decorator: conditional = qml.cond(pred > 0)(true_fn) conditional.otherwise(false_fn) return conditional return qml.cond( pred > 0, true_fn, false_fn, ) result = test_func(selector)(arg) assert np.allclose(result, expected), f"Expected {expected}, but got {result}" jaxpr = jax.make_jaxpr(test_func(selector))(arg) res_ev_jxpr = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, arg) assert np.allclose(res_ev_jxpr, expected), f"Expected {expected}, but got {res_ev_jxpr}" def test_mcm_return_error(self, decorator): """Test that an error is raised if executing a quantum function that uses qml.cond with mid-circuit measurement predicates where the conditional functions return something.""" def true_fn(arg): qml.RX(arg, 0) return 0 def false_fn(arg): qml.RY(arg, 0) return 1 def f(x): m1 = qml.measure(0) if decorator: conditional = qml.cond(m1)(true_fn) conditional.otherwise(false_fn) conditional(x) else: qml.cond(m1, true_fn, false_fn)(x) return qml.expval(qml.Z(0)) jaxpr = jax.make_jaxpr(f)(1.23) with pytest.raises( ConditionalTransformError, match="Only quantum functions without return values" ): _ = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, 1.23) def test_mcm_mixed_conds_error(self, decorator): """Test that an error is raised if executing a quantum function that uses qml.cond with a combination of mid-circuit measurement and other predicates.""" def true_fn(arg): qml.RX(arg, 0) def elif_fn(arg): qml.RZ(arg, 0) def false_fn(arg): qml.RY(arg, 0) def f(x): m1 = qml.measure(0) if decorator: conditional = qml.cond(m1)(true_fn) conditional.else_if(x > 1.5)(elif_fn) conditional.otherwise(false_fn) conditional(x) else: qml.cond(m1, true_fn, false_fn, elifs=(x > 1.5, elif_fn))(x) return qml.expval(qml.Z(0)) jaxpr = jax.make_jaxpr(f)(1.23) with pytest.raises( ConditionalTransformError, match="Cannot use qml.cond with a combination of mid-circuit measurements", ): _ = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, 1.23) class TestCondReturns: """Tests for validating the number and types of output variables in conditional functions.""" @pytest.mark.parametrize( "true_fn, false_fn, expected_error, match", [ ( lambda x: (x + 1, x + 2), lambda x: None, ValueError, r"Mismatch in number of output variables", ), ( lambda x: (x + 1, x + 2), lambda x: (x + 1,), ValueError, r"Mismatch in number of output variables", ), ( lambda x: (x + 1, x + 2), lambda x: (x + 1, x + 2.0), ValueError, r"Mismatch in output abstract values", ), ], ) def test_validate_mismatches(self, true_fn, false_fn, expected_error, match): """Test mismatch in number and type of output variables.""" with pytest.raises(expected_error, match=match): jax.make_jaxpr(CondCallable(True, true_fn, false_fn))(jax.numpy.array(1)) def test_validate_number_of_output_variables(self): """Test mismatch in number of output variables.""" def true_fn(x): return x + 1, x + 2 def false_fn(x): return x + 1 with pytest.raises(ValueError, match=r"Mismatch in number of output variables"): jax.make_jaxpr(CondCallable(True, true_fn, false_fn))(jax.numpy.array(1)) def test_validate_output_variable_types(self): """Test mismatch in output variable types.""" def true_fn(x): return x + 1, x + 2 def false_fn(x): return x + 1, x + 2.0 with pytest.raises(ValueError, match=r"Mismatch in output abstract values"): jax.make_jaxpr(CondCallable(True, true_fn, false_fn))(jax.numpy.array(1)) def test_validate_no_false_branch_with_return(self): """Test no false branch provided with return variables.""" def true_fn(x): return x + 1, x + 2 with pytest.raises( ValueError, match=r"The false branch must be provided if the true branch returns any variables", ): jax.make_jaxpr(CondCallable(True, true_fn))(jax.numpy.array(1)) def test_validate_no_false_branch_with_return_2(self): """Test no false branch provided with return variables.""" def true_fn(x): return x + 1, x + 2 def elif_fn(x): return x + 1, x + 2 with pytest.raises( ValueError, match=r"The false branch must be provided if the true branch returns any variables", ): jax.make_jaxpr(CondCallable(True, true_fn, elifs=[(True, elif_fn)]))(jax.numpy.array(1)) def test_validate_elif_branches(self): """Test elif branch mismatches.""" def true_fn(x): return x + 1, x + 2 def false_fn(x): return x + 1, x + 2 def elif_fn1(x): return x + 1, x + 2 def elif_fn2(x): return x + 1, x + 2.0 def elif_fn3(x): return x + 1 with pytest.raises( ValueError, match=r"Mismatch in output abstract values in elif branch #1" ): jax.make_jaxpr( CondCallable(True, true_fn, false_fn, [(True, elif_fn1), (False, elif_fn2)]) )(jax.numpy.array(1)) with pytest.raises( ValueError, match=r"Mismatch in number of output variables in elif branch #0" ): jax.make_jaxpr(CondCallable(True, true_fn, false_fn, elifs=[(True, elif_fn3)]))( jax.numpy.array(1) ) dev = qml.device("default.qubit", wires=3) @qml.qnode(dev) def circuit(pred): """Quantum circuit with only a true branch.""" def true_fn(): qml.RX(0.1, wires=0) qml.cond(pred > 0, true_fn)() return qml.expval(qml.Z(wires=0)) @qml.qnode(dev) def circuit_branches(pred, arg1, arg2): """Quantum circuit with conditional branches.""" qml.RX(0.10, wires=0) def true_fn(arg1, arg2): qml.RY(arg1, wires=0) qml.RX(arg2, wires=0) qml.RZ(arg1, wires=0) def false_fn(arg1, arg2): qml.RX(arg1, wires=0) qml.RX(arg2, wires=0) def elif_fn1(arg1, arg2): qml.RZ(arg2, wires=0) qml.RX(arg1, wires=0) qml.cond(pred > 0, true_fn, false_fn, elifs=(pred == -1, elif_fn1))(arg1, arg2) qml.RX(0.10, wires=0) return qml.expval(qml.Z(wires=0)) @qml.qnode(dev) def circuit_with_returned_operator(pred, arg1, arg2): """Quantum circuit with conditional branches that return operators.""" qml.RX(0.10, wires=0) def true_fn(arg1, arg2): qml.RY(arg1, wires=0) return 7, 4.6, qml.RY(arg2, wires=0), True def false_fn(arg1, arg2): qml.RZ(arg2, wires=0) return 2, 2.2, qml.RZ(arg1, wires=0), False qml.cond(pred > 0, true_fn, false_fn)(arg1, arg2) qml.RX(0.10, wires=0) return qml.expval(qml.Z(wires=0)) @qml.qnode(dev) def circuit_multiple_cond(tmp_pred, tmp_arg): """Quantum circuit with multiple dynamic conditional branches.""" dyn_pred_1 = tmp_pred > 0 arg = tmp_arg def true_fn_1(arg): return True, qml.RX(arg, wires=0) # pylint: disable=unused-argument def false_fn_1(arg): return False, qml.RY(0.1, wires=0) def true_fn_2(arg): return qml.RX(arg, wires=0) # pylint: disable=unused-argument def false_fn_2(arg): return qml.RY(0.1, wires=0) [dyn_pred_2, _] = qml.cond(dyn_pred_1, true_fn_1, false_fn_1, elifs=())(arg) qml.cond(dyn_pred_2, true_fn_2, false_fn_2, elifs=())(arg) return qml.expval(qml.Z(0)) @qml.qnode(dev) def circuit_with_consts(pred, arg): """Quantum circuit with jaxpr constants.""" # these are captured as consts arg1 = arg arg2 = arg + 0.2 arg3 = arg + 0.3 arg4 = arg + 0.4 arg5 = arg + 0.5 arg6 = arg + 0.6 def true_fn(): qml.RX(arg1, 0) def false_fn(): qml.RX(arg2, 0) qml.RX(arg3, 0) def elif_fn1(): qml.RX(arg4, 0) qml.RX(arg5, 0) qml.RX(arg6, 0) qml.cond(pred > 0, true_fn, false_fn, elifs=((pred == 0, elif_fn1),))() return qml.expval(qml.Z(0)) class TestCondCircuits: """Tests for conditional quantum circuits.""" @pytest.mark.parametrize( "pred, expected", [ (1, 0.99500417), # RX(0.1) (0, 1.0), # No operation ], ) def test_circuit(self, pred, expected): """Test circuit with only a true branch.""" result = circuit(pred) assert np.allclose(result, expected), f"Expected {expected}, but got {result}" args = [pred] jaxpr = jax.make_jaxpr(circuit)(*args) res_ev_jxpr = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, *args) assert np.allclose(res_ev_jxpr, expected), f"Expected {expected}, but got {res_ev_jxpr}" @pytest.mark.parametrize( "pred, arg1, arg2, expected", [ (1, 0.5, 0.6, 0.63340907), # RX(0.10) -> RY(0.5) -> RX(0.6) -> RZ(0.5) -> RX(0.10) (0, 0.5, 0.6, 0.26749883), # RX(0.10) -> RX(0.5) -> RX(0.6) -> RX(0.10) (-1, 0.5, 0.6, 0.77468805), # RX(0.10) -> RZ(0.6) -> RX(0.5) -> RX(0.10) ], ) def test_circuit_branches(self, pred, arg1, arg2, expected): """Test circuit with true, false, and elif branches.""" result = circuit_branches(pred, arg1, arg2) assert np.allclose(result, expected), f"Expected {expected}, but got {result}" args = [pred, arg1, arg2] jaxpr = jax.make_jaxpr(circuit_branches)(*args) res_ev_jxpr = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, *args) assert np.allclose(res_ev_jxpr, expected), f"Expected {expected}, but got {res_ev_jxpr}" @pytest.mark.parametrize( "pred, arg1, arg2, expected", [ (1, 0.5, 0.6, 0.43910855), # RX(0.10) -> RY(0.5) -> RY(0.6) -> RX(0.10) (0, 0.5, 0.6, 0.98551243), # RX(0.10) -> RZ(0.6) -> RX(0.5) -> RX(0.10) ], ) def test_circuit_with_returned_operator(self, pred, arg1, arg2, expected): """Test circuit with returned operators in the branches.""" result = circuit_with_returned_operator(pred, arg1, arg2) assert np.allclose(result, expected), f"Expected {expected}, but got {result}" args = [pred, arg1, arg2] jaxpr = jax.make_jaxpr(circuit_with_returned_operator)(*args) res_ev_jxpr = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, *args) assert np.allclose(res_ev_jxpr, expected), f"Expected {expected}, but got {res_ev_jxpr}" @pytest.mark.parametrize( "tmp_pred, tmp_arg, expected", [ (1, 0.5, 0.54030231), # RX(0.5) -> RX(0.5) (-1, 0.5, 0.98006658), # RY(0.1) -> RY(0.1) ], ) def test_circuit_multiple_cond(self, tmp_pred, tmp_arg, expected): """Test circuit with returned operators in the branches.""" result = circuit_multiple_cond(tmp_pred, tmp_arg) assert np.allclose(result, expected), f"Expected {expected}, but got {result}" args = [tmp_pred, tmp_arg] jaxpr = jax.make_jaxpr(circuit_multiple_cond)(*args) res_ev_jxpr = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, *args) assert np.allclose(res_ev_jxpr, expected), f"Expected {expected}, but got {res_ev_jxpr}" @pytest.mark.parametrize( "pred, arg, expected", [ (1, 0.5, 0.87758256), # RX(0.5) (-1, 0.5, 0.0707372), # RX(0.7) -> RX(0.8) (0, 0.5, -0.9899925), # RX(0.9) -> RX(1.0) -> RX(1.1) ], ) def test_circuit_consts(self, pred, arg, expected): """Test circuit with jaxpr constants.""" result = circuit_with_consts(pred, arg) assert np.allclose(result, expected), f"Expected {expected}, but got {result}" args = [pred, arg] jaxpr = jax.make_jaxpr(circuit_with_consts)(*args) res_ev_jxpr = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, *args) assert np.allclose(res_ev_jxpr, expected), f"Expected {expected}, but got {res_ev_jxpr}" @pytest.mark.parametrize("reset", [True, False]) @pytest.mark.parametrize("postselect", [None, 0, 1]) @pytest.mark.parametrize("shots", [None, 20]) def test_mcm_predicate_execution(self, reset, postselect, shots): """Test that QNodes executed with mid-circuit measurement predicates for qml.cond give correct results.""" device = qml.device("default.qubit", wires=3, shots=shots, seed=jax.random.PRNGKey(1234)) def true_fn(arg): qml.RX(arg, 0) def false_fn(arg): qml.RY(3 * arg, 0) @qml.qnode(device) def f(x, y): qml.RX(x, 0) m = qml.measure(0, reset=reset, postselect=postselect) qml.cond(m, true_fn, false_fn)(y) return qml.expval(qml.Z(0)) params = [2.5, 4.0] res = f(*params) qml.capture.disable() expected = f(*params) assert np.allclose(res, expected), f"Expected {expected}, but got {res}" @pytest.mark.parametrize("shots", [None, 100]) @pytest.mark.parametrize( "params, expected", # The parameters used here will essentially apply a PauliX just before mid-circuit # measurements, each of which will trigger a different conditional block. Each # conditional block prepares basis states in different bases, so the expectation value # for the measured observables will vary accordingly. [ ([np.pi, 0, 0], (1, 1 / np.sqrt(2), 0, 1 / np.sqrt(2))), # true_fn, Hadamard basis ([0, np.pi, 0], (1 / np.sqrt(2), 1, 0, 0)), # elif_fn1, PauliX basis ([0, 0, np.pi], (0, 0, 1, 0)), # elif_fn2, PauliY basis ([0, 0, 0, 0], (1 / np.sqrt(2), 0, 0, 1)), # false_fn, PauliZ basis ], ) def test_mcm_predicate_execution_with_elifs(self, params, expected, shots, tol): """Test that QNodes executed with mid-circuit measurement predicates for qml.cond give correct results when there are also elifs present.""" # pylint: disable=expression-not-assigned device = qml.device("default.qubit", wires=5, shots=shots, seed=jax.random.PRNGKey(10)) def true_fn(): # Adjoint Hadamard diagonalizing gates to get Hadamard basis state [qml.adjoint(op) for op in qml.Hadamard.compute_diagonalizing_gates(0)[::-1]] def elif_fn1(): # Adjoint PauliX diagonalizing gates to get X basis state [qml.adjoint(op) for op in qml.X.compute_diagonalizing_gates(0)[::-1]] def elif_fn2(): # Adjoint PauliY diagonalizing gates to get Y basis state [qml.adjoint(op) for op in qml.Y.compute_diagonalizing_gates(0)[::-1]] def false_fn(): # Adjoint PauliZ diagonalizing gates to get Z basis state return @qml.qnode(device) def f(*x): qml.RX(x[0], 0) m1 = qml.measure(0, reset=True) qml.RX(x[1], 0) m2 = qml.measure(0, reset=True) qml.RX(x[2], 0) m3 = qml.measure(0, reset=True) qml.cond(m1, true_fn, false_fn, elifs=((m2, elif_fn1), (m3, elif_fn2)))() return ( qml.expval(qml.Hadamard(0)), qml.expval(qml.X(0)), qml.expval(qml.Y(0)), qml.expval(qml.Z(0)), ) res = f(*params) atol = tol if shots is None else 0.1 assert np.allclose(res, expected, atol=atol, rtol=0), f"Expected {expected}, but got {res}" @pytest.mark.parametrize("upper_bound, arg", [(3, [0.1, 0.3, 0.5]), (2, [2, 7, 12])]) def test_nested_cond_for_while_loop(self, upper_bound, arg): """Test that a nested control flows are correctly captured into a jaxpr.""" dev = qml.device("default.qubit", wires=3) # Control flow for qml.conds def true_fn(_): @qml.for_loop(0, upper_bound, 1) def loop_fn(i): qml.Hadamard(wires=i) loop_fn() def elif_fn(arg): qml.RY(arg**2, wires=[2]) def false_fn(arg): qml.RY(-arg, wires=[2]) @qml.qnode(dev) def circuit(upper_bound, arg): qml.RY(-np.pi / 2, wires=[2]) m_0 = qml.measure(2) # NOTE: qml.cond(m_0, qml.RX)(arg[1], wires=1) doesn't work def rx_fn(): qml.RX(arg[1], wires=1) qml.cond(m_0, rx_fn)() def ry_fn(): qml.RY(arg[1] ** 3, wires=1) # nested for loops. # outer for loop updates x @qml.for_loop(0, upper_bound, 1) def loop_fn_returns(i, x): qml.RX(x, wires=i) m_1 = qml.measure(0) # NOTE: qml.cond(m_0, qml.RY)(arg[1], wires=1) doesn't work qml.cond(m_1, ry_fn)() # inner while loop @qml.while_loop(lambda j: j < upper_bound) def inner(j): qml.RZ(j, wires=0) qml.RY(x**2, wires=0) m_2 = qml.measure(0) qml.cond(m_2, true_fn=true_fn, false_fn=false_fn, elifs=((m_1, elif_fn)))( arg[0] ) return j + 1 inner(i + 1) return x + 0.1 loop_fn_returns(arg[2]) return qml.expval(qml.Z(0)) args = [upper_bound, arg] result = circuit(*args) jaxpr = jax.make_jaxpr(circuit)(*args) res_ev_jxpr = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, upper_bound, *arg) assert np.allclose(result, res_ev_jxpr), f"Expected {result}, but got {res_ev_jxpr}" class TestPytree: """Test pytree support for cond.""" def test_pytree_input_output(self): """Test that cond can handle pytree inputs and outputs.""" def f(x): return {"val": x["1"]} def g(x): return {"val": x["2"]} def h(x): return {"val": x["h"]} res_true = qml.cond(True, f, false_fn=g, elifs=(False, h))({"1": 1, "2": 2, "h": 3}) assert res_true == {"val": 1} res_elif = qml.cond(False, f, false_fn=g, elifs=(True, h))({"1": 1, "2": 2, "h": 3}) assert res_elif == {"val": 3} res_false = qml.cond(False, f, false_fn=g, elifs=(False, h))({"1": 1, "2": 2, "h": 3}) assert res_false == {"val": 2} def test_pytree_measurment_value(self): """Test that pytree args can be used when the condition is on a measurement value.""" def g(x): qml.RX(x["x"], x["wire"]) def f(x): m0 = qml.measure(0) qml.cond(m0, g)(x) with qml.queuing.AnnotatedQueue() as q: f({"x": 0.5, "wire": 0}) assert len(q) == 2 assert isinstance(q.queue[0], qml.measurements.MidMeasureMP) assert isinstance(q.queue[1], qml.ops.Conditional) qml.assert_equal(q.queue[1].base, qml.RX(0.5, 0))
pennylane/tests/capture/test_capture_cond.py/0
{ "file_path": "pennylane/tests/capture/test_capture_cond.py", "repo_id": "pennylane", "token_count": 13914 }
72
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # 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. """ Tests for the wire serialization functions in :mod:`pennylane.data.attributes.operator._wires` """ import json import numpy as np import pytest import pennylane as qml from pennylane.data.attributes.operator._wires import UnserializableWireError, wires_to_json from pennylane.wires import Wires pytestmark = pytest.mark.data class TestWiresToJson: @pytest.mark.parametrize( "in_, out", [ (np.array([0, 1, 2]), "[0, 1, 2]"), ([0, 1, 2], "[0, 1, 2]"), ((0, 1, 2), "[0, 1, 2]"), (range(3), "[0, 1, 2]"), (["a", "b"], '["a", "b"]'), ([0, 1, None], "[0, 1, null]"), (["a", 1, None], '["a", 1, null]'), (None, "[null]"), (1, "[1]"), ("a", '["a"]'), (np.int64(1), "[1]"), ], ) def test_wires_output_is_expected(self, in_, out): """Test that ``wires_to_json`` returns the expected output for json-serializable wire labels, as well as numpy integers, to to a json list.""" in_ = Wires(in_) assert wires_to_json(Wires(in_)) == out @pytest.mark.parametrize( "in_", [ np.array([0, 1, 2]), [0, 1, 2], (0, 1, 2), range(3), ["a", "b"], ["a", 0, 1, None], 1, "a", np.int64(3), ], ) def test_wires_hash_equal(self, in_): """Test that the hash of the wires object is the same when loading from JSON.""" in_ = Wires(in_) out = Wires(json.loads(wires_to_json(in_))) assert hash(in_) == hash(out) for in_w, out_w in zip(in_, out): assert hash(in_w) == hash(out_w) @pytest.mark.parametrize("in_", [[np.float64(1)], [qml.PauliX(1)]]) def test_unserializable(self, in_): """Test that wires_to_json raises an ``UnserializableWiresError`` when the wires are not json types or integers.""" in_ = Wires(in_) with pytest.raises(UnserializableWireError): wires_to_json(in_) def test_bad_integral_unserializable(self): """Test that wires_to_json raises an ``UnserializableWiresError`` if any of the wires are integer-like, but have a different hash if converted to int.""" class BadInt(int): def __hash__(self) -> int: return 0 def __int__(self) -> int: return 1 with pytest.raises(UnserializableWireError): wires_to_json(Wires([BadInt()]))
pennylane/tests/data/attributes/operator/test__wires.py/0
{ "file_path": "pennylane/tests/data/attributes/operator/test__wires.py", "repo_id": "pennylane", "token_count": 1473 }
73
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # 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. """ Tests for the :mod:`pennylane.data.base.typing_util` functions. """ from typing import Optional, Type, Union import pytest import pennylane as qml from pennylane.data.base.typing_util import UNSET, get_type, get_type_str, resolve_special_type from pennylane.qchem import Molecule pytestmark = pytest.mark.data @pytest.mark.parametrize( "type_, expect", [ (list, "list"), (list, "list"), (Molecule, "pennylane.qchem.molecule.Molecule"), ("nonsense", "nonsense"), (list[int], "list[int]"), (list[tuple[int, "str"]], "list[tuple[int, str]]"), (Optional[int], "Union[int, None]"), (Union[int, "str", Molecule], "Union[int, str, pennylane.qchem.molecule.Molecule]"), (str, "str"), (Type[str], "type[str]"), (Union[list[list[int]], str], "Union[list[list[int]], str]"), ], ) def test_get_type_str(type_, expect): """Test that ``get_type_str()`` returns the expected value for various typing forms.""" assert get_type_str(type_) == expect @pytest.mark.parametrize( "obj, expect", [ (list, list), ([1, 2], list), (list, list), (list[int], list), (qml.RX, qml.RX), (qml.RX(1, [1]), qml.RX), ], ) def test_get_type(obj, expect): """Test that ``get_type()`` returns the expected value for various objects and types.""" assert get_type(obj) is expect def test_unset_bool(): """Test that UNSET is falsy.""" assert not UNSET @pytest.mark.parametrize("type_, expect", [(list[list[int]], (list, [list]))]) def test_resolve_special_type(type_, expect): """Test resolve_special_type().""" assert resolve_special_type(type_) == expect
pennylane/tests/data/base/test_typing_util.py/0
{ "file_path": "pennylane/tests/data/base/test_typing_util.py", "repo_id": "pennylane", "token_count": 912 }
74
# Copyright 2024 Xanadu Quantum Technologies Inc. # 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. """ Tests that apply to all device modifiers or act on a combination of them together. """ # pylint: disable=unused-argument, too-few-public-methods, missing-class-docstring, no-member import pytest import pennylane as qml from pennylane.devices import Device from pennylane.devices.modifiers import simulator_tracking, single_tape_support # pylint: disable=protected-access def test_chained_modifiers(): """Test that modifiers can be stacked together.""" @simulator_tracking @single_tape_support class DummyDev(qml.devices.Device): def execute(self, circuits, execution_config=qml.devices.DefaultExecutionConfig): return tuple(0.0 for _ in circuits) assert DummyDev._applied_modifiers == [single_tape_support, simulator_tracking] tape = qml.tape.QuantumScript([], [qml.expval(qml.X(0))], shots=50) dev = DummyDev() with dev.tracker: out = dev.execute(tape) # result unwrapped assert out == 0.0 assert len(dev.tracker.history) == 7 assert dev.tracker.history["batches"] == [1] assert dev.tracker.history["simulations"] == [1] assert dev.tracker.history["executions"] == [1] assert dev.tracker.history["results"] == [0.0] assert dev.tracker.history["resources"] == [tape.specs["resources"]] assert dev.tracker.history["shots"] == [50] @pytest.mark.parametrize("modifier", (simulator_tracking, single_tape_support)) class TestModifierDefaultBeahviour: """Test generic behavior for device modifiers.""" def test_error_on_old_interface(self, modifier): """Test that a ValueError is raised is called on something that is not a subclass of Device.""" with pytest.raises(ValueError, match=f"{modifier.__name__} only accepts"): modifier(qml.devices.DefaultQubitLegacy) def test_adds_to_applied_modifiers_private_property(self, modifier): """Test that the modifier is added to the `_applied_modifiers` property.""" @modifier class DummyDev(qml.devices.Device): def execute(self, circuits, execution_config=qml.devices.DefaultExecutionConfig): return 0.0 assert DummyDev._applied_modifiers == [modifier] @modifier class DummyDev2(qml.devices.Device): _applied_modifiers = [None] # some existing value def execute(self, circuits, execution_config=qml.devices.DefaultExecutionConfig): return 0.0 assert DummyDev2._applied_modifiers == [None, modifier] def test_leaves_undefined_methods_untouched(self, modifier): """Test that undefined methods are left the same as the Device class methods.""" @modifier class DummyDev(qml.devices.Device): def execute(self, circuits, execution_config=qml.devices.DefaultExecutionConfig): return 0.0 assert DummyDev.compute_derivatives == Device.compute_derivatives assert DummyDev.execute_and_compute_derivatives == Device.execute_and_compute_derivatives assert DummyDev.compute_jvp == Device.compute_jvp assert DummyDev.execute_and_compute_jvp == Device.execute_and_compute_jvp assert DummyDev.compute_vjp == Device.compute_vjp assert DummyDev.execute_and_compute_vjp == Device.execute_and_compute_vjp dev = DummyDev() assert not dev.supports_derivatives() assert not dev.supports_jvp() assert not dev.supports_vjp()
pennylane/tests/devices/modifiers/test_all_modifiers.py/0
{ "file_path": "pennylane/tests/devices/modifiers/test_all_modifiers.py", "repo_id": "pennylane", "token_count": 1469 }
75
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # 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. """ Tests for the tracking capabilities of default qutrit mixed. """ import numpy as np import pytest import pennylane as qml from pennylane.resource import Resources class TestTracking: """Testing the tracking capabilities of DefaultQutritMixed.""" def test_tracker_set_upon_initialization(self): """Test that a new tracker is initialized with each device.""" tracker_1 = qml.device("default.qutrit.mixed").tracker tracker_2 = qml.device("default.qutrit.mixed").tracker assert tracker_1 is not tracker_2 def test_tracker_not_updated_if_not_active(self): """Test that the tracker is not updated if not active.""" dev = qml.device("default.qutrit.mixed") assert len(dev.tracker.totals) == 0 dev.execute(qml.tape.QuantumScript()) assert len(dev.tracker.totals) == 0 assert len(dev.tracker.history) == 0 def test_tracking(self): """Test that the new default qutrit mixed integrates with the tracker.""" qs = qml.tape.QuantumScript([], [qml.expval(qml.GellMann(0, 3))]) dev = qml.device("default.qutrit.mixed") with qml.Tracker(dev) as tracker: dev.execute(qs) assert tracker.history == { "batches": [1], "executions": [1], "simulations": [1], "results": [1.0], "resources": [Resources(num_wires=1)], "errors": [{}], } assert tracker.totals == { "batches": 1, "executions": 1, "results": 1.0, "simulations": 1, } assert tracker.latest == { "executions": 1, "simulations": 1, "results": 1, "resources": Resources(num_wires=1), "errors": {}, } def test_tracking_resources(self): """Test that resources are tracked for the new default qutrit mixed device.""" qs = qml.tape.QuantumScript( [ qml.THadamard(0), qml.THadamard(1), qml.TAdd(wires=[0, 2]), qml.TRZ(1.23, 1, subspace=(0, 2)), qml.TAdd(wires=[1, 2]), qml.THadamard(0), ], [qml.expval(qml.GellMann(1, 8)), qml.expval(qml.GellMann(2, 7))], ) expected_resources = Resources( num_wires=3, num_gates=6, gate_types={"THadamard": 3, "TAdd": 2, "TRZ": 1}, gate_sizes={1: 4, 2: 2}, depth=3, ) dev = qml.device("default.qutrit.mixed") with qml.Tracker(dev) as tracker: dev.execute(qs) assert len(tracker.history["resources"]) == 1 assert tracker.history["resources"][0] == expected_resources def test_tracking_batched_execution(self): """Test the number of times the device is executed over a QNode's lifetime is tracked by the device's tracker.""" dev_1 = qml.device("default.qutrit.mixed", wires=2) def circuit_1(x, y): qml.TRX(x, wires=[0]) qml.TRY(y, wires=[1]) qml.TAdd(wires=[0, 1]) return qml.expval(qml.GellMann(0, 3) @ qml.GellMann(1, 4)) node_1 = qml.QNode(circuit_1, dev_1) num_evals_1 = 10 with qml.Tracker(dev_1, persistent=True) as tracker1: for _ in range(num_evals_1): node_1(0.432, np.array([0.12, 0.5, 3.2])) assert tracker1.totals["executions"] == 3 * num_evals_1 assert tracker1.totals["simulations"] == num_evals_1 # test a second instance of a default qutrit mixed device dev_2 = qml.device("default.qutrit.mixed", wires=2) def circuit_2(x): qml.TRX(x, wires=[0]) qml.TAdd(wires=[0, 1]) return qml.expval(qml.GellMann(0, 3) @ qml.GellMann(1, 4)) node_2 = qml.QNode(circuit_2, dev_2) num_evals_2 = 5 with qml.Tracker(dev_2) as tracker2: for _ in range(num_evals_2): node_2(np.array([0.432, 0.61, 8.2])) assert tracker2.totals["simulations"] == num_evals_2 assert tracker2.totals["executions"] == 3 * num_evals_2 # test a new circuit on an existing instance of a qutrit mixed device def circuit_3(y): qml.TRY(y, wires=[1]) qml.TAdd(wires=[0, 1]) return qml.expval(qml.GellMann(0, 3) @ qml.GellMann(1, 4)) node_3 = qml.QNode(circuit_3, dev_1) num_evals_3 = 7 with tracker1: for _ in range(num_evals_3): node_3(np.array([0.12, 1.214])) assert tracker1.totals["simulations"] == num_evals_1 + num_evals_3 assert tracker1.totals["executions"] == 3 * num_evals_1 + 2 * num_evals_3 shot_testing_combos = [ # expval combinations ([qml.expval(qml.GellMann(0, 1))], 1, 10), ([qml.expval(qml.GellMann(0, 1)), qml.expval(qml.GellMann(0, 2))], 2, 20), # Hamiltonian test cases ([qml.expval(qml.Hamiltonian([1, 1], [qml.GellMann(0, 1), qml.GellMann(1, 5)]))], 1, 10), # op arithmetic test cases ([qml.expval(qml.sum(qml.GellMann(0, 1), qml.GellMann(1, 4)))], 2, 20), ( [ qml.expval(qml.prod(qml.GellMann(0, 1), qml.GellMann(1, 4))), qml.expval(qml.prod(qml.GellMann(1, 4), qml.GellMann(2, 7))), ], 2, 20, ), # computational basis measurements ([qml.sample(wires=(0, 1))], 1, 10), ([qml.sample(wires=(0, 1)), qml.expval(qml.GellMann(0, 1))], 2, 20), ] class TestExecuteTracker: """Test that tracker tracks default qutrit mixed execute number of shots""" # pylint: disable=too-few-public-methods @pytest.mark.parametrize("mps, expected_exec, expected_shots", shot_testing_combos) def test_single_expval(self, mps, expected_exec, expected_shots): """Test tracker tracks default qutrit mixed execute number of shots for single measurements""" dev = qml.device("default.qutrit.mixed") tape = qml.tape.QuantumScript([], mps, shots=10) with dev.tracker: dev.execute(tape) assert dev.tracker.totals["executions"] == expected_exec assert dev.tracker.totals["simulations"] == 1 assert dev.tracker.totals["shots"] == expected_shots tape = qml.tape.QuantumScript([qml.TRX((1.2, 2.3, 3.4), wires=0)], mps, shots=10) with dev.tracker: dev.execute(tape) assert dev.tracker.totals["executions"] == 3 * expected_exec assert dev.tracker.totals["simulations"] == 1 assert dev.tracker.totals["shots"] == 3 * expected_shots @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_multiple_expval_with_prods(self): """ Test tracker tracks default qutrit mixed execute number of shots for new and old opmath tensors. """ mps, expected_exec, expected_shots = ( [qml.expval(qml.GellMann(0, 1)), qml.expval(qml.GellMann(0, 1) @ qml.GellMann(1, 5))], 2, 20, ) dev = qml.device("default.qutrit.mixed") tape = qml.tape.QuantumScript([], mps, shots=10) with dev.tracker: dev.execute(tape) assert dev.tracker.totals["executions"] == expected_exec assert dev.tracker.totals["simulations"] == 1 assert dev.tracker.totals["shots"] == expected_shots
pennylane/tests/devices/qutrit_mixed/test_qutrit_mixed_tracking.py/0
{ "file_path": "pennylane/tests/devices/qutrit_mixed/test_qutrit_mixed_tracking.py", "repo_id": "pennylane", "token_count": 3845 }
76
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # 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. """ Unit tests for the :mod:`pennylane` :class:`Device` class. """ from collections import OrderedDict from importlib import metadata, reload from sys import version_info import numpy as np import pytest import pennylane as qml from pennylane import Device from pennylane.wires import Wires mock_device_paulis = ["PauliX", "PauliY", "PauliZ"] mock_device_paulis_and_hamiltonian = ["Hamiltonian", "PauliX", "PauliY", "PauliZ"] # pylint: disable=abstract-class-instantiated, no-self-use, redefined-outer-name, invalid-name, missing-function-docstring @pytest.fixture(scope="function") def mock_device_with_identity(monkeypatch): """A function to create a mock device with non-empty observables""" with monkeypatch.context() as m: m.setattr(Device, "__abstractmethods__", frozenset()) m.setattr(Device, "operations", mock_device_paulis + ["Identity"]) m.setattr(Device, "observables", mock_device_paulis + ["Identity"]) m.setattr(Device, "short_name", "MockDevice") def get_device(wires=1): return Device(wires=wires) yield get_device @pytest.fixture(scope="function") def mock_device_supporting_paulis(monkeypatch): """A function to create a mock device with non-empty observables""" with monkeypatch.context() as m: m.setattr(Device, "__abstractmethods__", frozenset()) m.setattr(Device, "operations", mock_device_paulis) m.setattr(Device, "observables", mock_device_paulis) m.setattr(Device, "short_name", "MockDevice") def get_device(wires=1): return Device(wires=wires) yield get_device @pytest.fixture(scope="function") def mock_device_supporting_paulis_and_inverse(monkeypatch): """A function to create a mock device with non-empty operations and supporting inverses""" with monkeypatch.context() as m: m.setattr(Device, "__abstractmethods__", frozenset()) m.setattr(Device, "operations", mock_device_paulis) m.setattr(Device, "observables", mock_device_paulis) m.setattr(Device, "short_name", "MockDevice") m.setattr(Device, "_capabilities", {"supports_inverse_operations": True}) def get_device(wires=1): return Device(wires=wires) yield get_device @pytest.fixture(scope="function") def mock_device_supporting_observables_and_inverse(monkeypatch): """A function to create a mock device with non-empty operations and supporting inverses""" with monkeypatch.context() as m: m.setattr(Device, "__abstractmethods__", frozenset()) m.setattr(Device, "operations", mock_device_paulis) m.setattr(Device, "observables", mock_device_paulis + ["Hermitian"]) m.setattr(Device, "short_name", "MockDevice") m.setattr(Device, "_capabilities", {"supports_inverse_operations": True}) def get_device(wires=1): return Device(wires=wires) yield get_device mock_device_capabilities = { "measurements": "everything", "noise_models": ["depolarizing", "bitflip"], } @pytest.fixture(scope="function") def mock_device_with_capabilities(monkeypatch): """A function to create a mock device with non-empty observables""" with monkeypatch.context() as m: m.setattr(Device, "__abstractmethods__", frozenset()) m.setattr(Device, "_capabilities", mock_device_capabilities) def get_device(wires=1): return Device(wires=wires) yield get_device @pytest.fixture(scope="function") def mock_device_with_paulis_and_methods(monkeypatch): """A function to create a mock device with non-empty observables""" with monkeypatch.context() as m: m.setattr(Device, "__abstractmethods__", frozenset()) m.setattr(Device, "_capabilities", mock_device_capabilities) m.setattr(Device, "operations", mock_device_paulis) m.setattr(Device, "observables", mock_device_paulis) m.setattr(Device, "short_name", "MockDevice") m.setattr(Device, "expval", lambda self, x, y, z: 0) m.setattr(Device, "var", lambda self, x, y, z: 0) m.setattr(Device, "sample", lambda self, x, y, z: 0) m.setattr(Device, "apply", lambda self, x, y, z: None) def get_device(wires=1): return Device(wires=wires) yield get_device @pytest.fixture(scope="function") def mock_device_with_paulis_hamiltonian_and_methods(monkeypatch): """A function to create a mock device with non-empty observables""" with monkeypatch.context() as m: m.setattr(Device, "__abstractmethods__", frozenset()) m.setattr(Device, "_capabilities", mock_device_capabilities) m.setattr(Device, "operations", mock_device_paulis) m.setattr(Device, "observables", mock_device_paulis_and_hamiltonian) m.setattr(Device, "short_name", "MockDevice") m.setattr(Device, "expval", lambda self, x, y, z: 0) m.setattr(Device, "var", lambda self, x, y, z: 0) m.setattr(Device, "sample", lambda self, x, y, z: 0) m.setattr(Device, "apply", lambda self, x, y, z: None) def get_device(wires=1): return Device(wires=wires) yield get_device @pytest.fixture(scope="function") def mock_device(monkeypatch): with monkeypatch.context() as m: m.setattr(Device, "__abstractmethods__", frozenset()) m.setattr(Device, "_capabilities", mock_device_capabilities) m.setattr(Device, "operations", ["PauliY", "RX", "Rot"]) m.setattr(Device, "observables", ["PauliZ"]) m.setattr(Device, "short_name", "MockDevice") m.setattr(Device, "expval", lambda self, x, y, z: 0) m.setattr(Device, "var", lambda self, x, y, z: 0) m.setattr(Device, "sample", lambda self, x, y, z: 0) m.setattr(Device, "apply", lambda self, x, y, z: None) def get_device(wires=1): return Device(wires=wires) yield get_device @pytest.fixture(scope="function") def mock_device_supporting_prod(monkeypatch): with monkeypatch.context() as m: m.setattr(Device, "__abstractmethods__", frozenset()) m.setattr(Device, "_capabilities", mock_device_capabilities) m.setattr(Device, "operations", ["PauliX", "PauliZ"]) m.setattr(Device, "observables", ["PauliX", "PauliZ", "Prod"]) m.setattr(Device, "short_name", "MockDevice") def get_device(wires=1): return Device(wires=wires) yield get_device # pylint: disable=pointless-statement def test_invalid_attribute_in_devices_raises_error(): with pytest.raises(AttributeError, match="'pennylane.devices' has no attribute 'blabla'"): qml.devices.blabla def test_gradients_record(): """Test that execute_and_gradients and gradient both track the number of gradients requested.""" dev = qml.device("default.qubit.legacy", wires=1) tape = qml.tape.QuantumScript([qml.RX(0.1, wires=0)], [qml.expval(qml.PauliZ(0))]) with dev.tracker: dev.execute_and_gradients((tape, tape), method="adjoint_jacobian", use_device_state=True) assert dev.tracker.totals["execute_and_derivative_batches"] == 1 assert dev.tracker.totals["derivatives"] == 2 with dev.tracker: dev.gradients((tape, tape), method="adjoint_jacobian", use_device_state=True) assert dev.tracker.totals["derivatives"] == 2 class TestDeviceSupportedLogic: """Test the logic associated with the supported operations and observables""" # pylint: disable=no-self-use, redefined-outer-name def test_supports_operation_argument_types(self, mock_device_supporting_paulis): """Checks that device.supports_operations returns the correct result when passed both string and Operation class arguments""" dev = mock_device_supporting_paulis() assert dev.supports_operation("PauliX") assert dev.supports_operation(qml.PauliX) assert not dev.supports_operation("S") assert not dev.supports_operation(qml.CNOT) def test_supports_observable_argument_types(self, mock_device_supporting_paulis): """Checks that device.supports_observable returns the correct result when passed both string and Operation class arguments""" dev = mock_device_supporting_paulis() assert dev.supports_observable("PauliX") assert dev.supports_observable(qml.PauliX) assert not dev.supports_observable("Identity") assert not dev.supports_observable(qml.Identity) def test_supports_operation_exception(self, mock_device): """check that device.supports_operation raises proper errors if the argument is of the wrong type""" dev = mock_device() with pytest.raises( ValueError, match="The given operation must either be a pennylane.Operation class or a string.", ): dev.supports_operation(3) with pytest.raises( ValueError, match="The given operation must either be a pennylane.Operation class or a string.", ): dev.supports_operation(Device) def test_supports_observable_exception(self, mock_device): """check that device.supports_observable raises proper errors if the argument is of the wrong type""" dev = mock_device() with pytest.raises( ValueError, match="The given observable must either be a pennylane.Observable class or a string.", ): dev.supports_observable(3) operation = qml.CNOT with pytest.raises( ValueError, match="The given observable must either be a pennylane.Observable class or a string.", ): dev.supports_observable(operation) class TestInternalFunctions: # pylint:disable=too-many-public-methods """Test the internal functions of the abstract Device class""" # pylint: disable=unnecessary-dunder-call def test_repr(self, mock_device_supporting_paulis): """Tests the __repr__ function""" dev = mock_device_supporting_paulis() assert "<Device device (wires=1, shots=1000) at " in dev.__repr__() def test_str(self, mock_device_supporting_paulis): """Tests the __str__ function""" dev = mock_device_supporting_paulis() string = str(dev) assert "Short name: MockDevice" in string assert "Package: pennylane" in string assert "Plugin version: None" in string assert "Author: None" in string assert "Wires: 1" in string assert "Shots: 1000" in string def test_check_validity_on_valid_queue(self, mock_device_supporting_paulis): """Tests the function Device.check_validity with valid queue and observables""" dev = mock_device_supporting_paulis() queue = [ qml.PauliX(wires=0), qml.PauliY(wires=1), qml.PauliZ(wires=2), ] observables = [qml.expval(qml.PauliZ(0))] # Raises an error if queue or observables are invalid dev.check_validity(queue, observables) @pytest.mark.usefixtures("use_new_opmath") def test_check_validity_containing_prod(self, mock_device_supporting_prod): """Tests that the function Device.check_validity works with Prod""" dev = mock_device_supporting_prod() queue = [ qml.PauliX(wires=0), qml.PauliZ(wires=1), ] observables = [ qml.expval(qml.PauliX(0) @ qml.PauliZ(1)), qml.expval(qml.PauliZ(0) @ (qml.PauliX(1) @ qml.PauliZ(2))), ] dev.check_validity(queue, observables) @pytest.mark.usefixtures("use_new_opmath") def test_prod_containing_unsupported_nested_observables(self, mock_device_supporting_prod): """Tests that the observables nested within Prod are checked for validity""" dev = mock_device_supporting_prod() queue = [ qml.PauliX(wires=0), qml.PauliZ(wires=1), ] unsupported_nested_observables = [ qml.expval(qml.PauliZ(0) @ (qml.PauliX(1) @ qml.PauliY(2))) ] with pytest.raises(qml.DeviceError, match="Observable PauliY not supported"): dev.check_validity(queue, unsupported_nested_observables) @pytest.mark.usefixtures("use_legacy_opmath") def test_check_validity_on_tensor_support_legacy_opmath(self, mock_device_supporting_paulis): """Tests the function Device.check_validity with tensor support capability""" dev = mock_device_supporting_paulis() queue = [ qml.PauliX(wires=0), qml.PauliY(wires=1), qml.PauliZ(wires=2), ] observables = [qml.expval(qml.PauliZ(0) @ qml.PauliX(1))] # mock device does not support Tensor product with pytest.raises(qml.DeviceError, match="Tensor observables not supported"): dev.check_validity(queue, observables) @pytest.mark.usefixtures("use_new_opmath") def test_check_validity_on_prod_support(self, mock_device_supporting_paulis): """Tests the function Device.check_validity with prod support capability""" dev = mock_device_supporting_paulis() queue = [ qml.PauliX(wires=0), qml.PauliY(wires=1), qml.PauliZ(wires=2), ] observables = [qml.expval(qml.PauliZ(0) @ qml.PauliX(1))] # mock device does not support Tensor product with pytest.raises(qml.DeviceError, match="Observable Prod not supported"): dev.check_validity(queue, observables) @pytest.mark.usefixtures("use_legacy_opmath") def test_check_validity_on_invalid_observable_with_tensor_support(self, monkeypatch): """Tests the function Device.check_validity with tensor support capability but with an invalid observable""" queue = [ qml.PauliX(wires=0), qml.PauliY(wires=1), qml.PauliZ(wires=2), ] observables = [qml.expval(qml.PauliZ(0) @ qml.Hadamard(1))] D = Device with monkeypatch.context() as m: m.setattr(D, "__abstractmethods__", frozenset()) m.setattr(D, "operations", ["PauliX", "PauliY", "PauliZ"]) m.setattr(D, "observables", ["PauliX", "PauliY", "PauliZ"]) m.setattr(D, "capabilities", lambda self: {"supports_tensor_observables": True}) m.setattr(D, "short_name", "Dummy") dev = D() # mock device supports Tensor products but not hadamard with pytest.raises(qml.DeviceError, match="Observable Hadamard not supported"): dev.check_validity(queue, observables) def test_check_validity_on_invalid_queue(self, mock_device_supporting_paulis): """Tests the function Device.check_validity with invalid queue and valid observables""" dev = mock_device_supporting_paulis() queue = [ qml.RX(1.0, wires=0), qml.PauliY(wires=1), qml.PauliZ(wires=2), ] observables = [qml.expval(qml.PauliZ(0))] with pytest.raises(qml.DeviceError, match="Gate RX not supported on device"): dev.check_validity(queue, observables) def test_check_validity_on_invalid_observable(self, mock_device_supporting_paulis): """Tests the function Device.check_validity with valid queue and invalid observables""" dev = mock_device_supporting_paulis() queue = [ qml.PauliX(wires=0), qml.PauliY(wires=1), qml.PauliZ(wires=2), ] observables = [qml.expval(qml.Hadamard(0))] with pytest.raises(qml.DeviceError, match="Observable Hadamard not supported on device"): dev.check_validity(queue, observables) def test_check_validity_on_projector_as_operation(self, mock_device_supporting_paulis): """Test that an error is raised if the operation queue contains qml.Projector""" dev = mock_device_supporting_paulis(wires=1) queue = [qml.PauliX(0), qml.Projector([0], wires=0), qml.PauliZ(0)] observables = [] with pytest.raises(ValueError, match="Postselection is not supported"): dev.check_validity(queue, observables) def test_check_validity_on_non_observable_measurement(self, mock_device_with_identity, recwarn): """Test that using non-observable measurements like state() works.""" dev = mock_device_with_identity(wires=1) queue = [] observables = [qml.state()] dev.check_validity(queue, observables) assert len(recwarn) == 0 def test_args(self, mock_device): """Test that the device requires correct arguments""" with pytest.raises( qml.DeviceError, match="specified number of shots needs to be at least 1" ): Device(mock_device, shots=0) @pytest.mark.parametrize( "wires, expected", [(["a1", "q", -1, 3], Wires(["a1", "q", -1, 3])), (3, Wires([0, 1, 2])), ([3], Wires([3]))], ) def test_wires_property(self, mock_device, wires, expected): """Tests that the wires attribute is set correctly.""" dev = mock_device(wires=wires) assert dev.wires == expected def test_wire_map_property(self, mock_device): """Tests that the wire_map is constructed correctly.""" dev = mock_device(wires=["a1", "q", -1, 3]) expected = OrderedDict([("a1", 0), ("q", 1), (-1, 2), (3, 3)]) assert dev.wire_map == expected def test_execution_property(self, mock_device): """Tests that the number of executions is initialised correctly""" dev = mock_device() expected = 0 assert dev.num_executions == expected def test_device_executions(self): """Test the number of times a device is executed over a QNode's lifetime is tracked by `num_executions`""" # test default Gaussian device dev_gauss = qml.device("default.gaussian", wires=1) def circuit_gauss(mag_alpha, phase_alpha, phi): qml.Displacement(mag_alpha, phase_alpha, wires=0) qml.Rotation(phi, wires=0) return qml.expval(qml.NumberOperator(0)) node_gauss = qml.QNode(circuit_gauss, dev_gauss) num_evals_gauss = 12 for _ in range(num_evals_gauss): node_gauss(0.015, 0.02, 0.005) assert dev_gauss.num_executions == num_evals_gauss @pytest.mark.parametrize( "depth, expanded_ops", [ (0, [qml.PauliX(0), qml.BasisEmbedding([1, 0], wires=[1, 2])]), (1, [qml.PauliX(wires=0), qml.PauliX(wires=1)]), ], ) def test_device_default_expand_ops( self, depth, expanded_ops, mock_device_with_paulis_hamiltonian_and_methods ): """Test that the default expand method can selectively expand operations without expanding measurements.""" ops = [qml.PauliX(0), qml.BasisEmbedding([1, 0], wires=[1, 2])] measurements = [ qml.expval(qml.PauliZ(0)), qml.expval(qml.Hamiltonian([2], [qml.PauliX(0) @ qml.PauliY(1)])), ] circuit = qml.tape.QuantumScript(ops=ops, measurements=measurements) dev = mock_device_with_paulis_hamiltonian_and_methods(wires=3) expanded_tape = dev.default_expand_fn(circuit, max_expansion=depth) for op, expected_op in zip( expanded_tape.operations[expanded_tape.num_preps :], expanded_ops, ): qml.assert_equal(op, expected_op) for mp, expected_mp in zip(expanded_tape.measurements, measurements): qml.assert_equal(mp, expected_mp) wires_to_try = [ (1, Wires([0])), (4, Wires([1, 3])), (["a", 2], Wires([2])), (["a", 2], Wires([2, "a"])), ] @pytest.mark.parametrize("dev_wires, wires_to_map", wires_to_try) def test_map_wires_caches(self, dev_wires, wires_to_map, mock_device): """Test that multiple calls to map_wires will use caching.""" dev = mock_device(dev_wires) original_hits = dev.map_wires.cache_info().hits original_misses = dev.map_wires.cache_info().misses # The first call is computed: it's a miss as it didn't come from the cache dev.map_wires(wires_to_map) # The number of misses increased assert dev.map_wires.cache_info().misses > original_misses # The second call comes from the cache: it's a hit dev.map_wires(wires_to_map) # The number of hits increased assert dev.map_wires.cache_info().hits > original_hits def test_mcm_unsupported_error(self, mock_device_with_paulis_and_methods): """Test that an error is raised if mid-circuit measurements are not supported natively""" dev = mock_device_with_paulis_and_methods(wires=2) # mid-circuit measurements are part of the queue (for now) with qml.queuing.AnnotatedQueue() as q: qml.measure(1) qml.PauliZ(0) tape = qml.tape.QuantumScript.from_queue(q) # Raises an error for device that doesn't support mid-circuit measurements natively with pytest.raises(qml.DeviceError, match="Mid-circuit measurements are not natively"): dev.check_validity(tape.operations, tape.observables) @pytest.mark.parametrize( "wires, subset, expected_subset", [ (Wires(["a", "b", "c"]), Wires(["c", "b"]), Wires(["b", "c"])), (Wires([0, 1, 2]), Wires([1, 0, 2]), Wires([0, 1, 2])), (Wires([3, "beta", "a"]), Wires(["a", "beta", 3]), Wires([3, "beta", "a"])), (Wires([0]), Wires([0]), Wires([0])), ], ) def test_order_wires(self, wires, subset, expected_subset, mock_device): dev = mock_device(wires=wires) ordered_subset = dev.order_wires(subset_wires=subset) assert ordered_subset == expected_subset @pytest.mark.parametrize( "wires, subset", [ (Wires(["a", "b", "c"]), Wires(["c", "d"])), (Wires([0, 1, 2]), Wires([3, 4, 5])), (Wires([3, "beta", "a"]), Wires(["alpha", "beta", "gamma"])), (Wires([0]), Wires([2])), ], ) def test_order_wires_raises_value_error(self, wires, subset, mock_device): dev = mock_device(wires=wires) with pytest.raises(ValueError, match="Could not find some or all subset wires"): _ = dev.order_wires(subset_wires=subset) @pytest.mark.parametrize( "op, decomp", zip( [ qml.BasisState([0, 0], wires=[0, 1]), qml.StatePrep([0, 1, 0, 0], wires=[0, 1]), ], [ [], [ qml.RY(1.57079633, wires=[1]), qml.CNOT(wires=[0, 1]), qml.RY(1.57079633, wires=[1]), qml.CNOT(wires=[0, 1]), ], ], ), ) def test_default_expand_with_initial_state(self, op, decomp): """Test the default expand function with StatePrepBase operations integrates well.""" prep = [op] ops = [qml.AngleEmbedding(features=[0.1], wires=[0], rotation="Z"), op, qml.PauliZ(wires=2)] dev = qml.device("default.mixed", wires=3) tape = qml.tape.QuantumTape(ops=prep + ops, measurements=[], shots=100) new_tape = dev.default_expand_fn(tape) true_decomposition = [] # prep op is not decomposed at start of circuit: true_decomposition.append(op) # AngleEmbedding decomp: true_decomposition.append(qml.RZ(0.1, wires=[0])) # prep op decomposed if its mid-circuit: true_decomposition.extend(decomp) # Z: true_decomposition.append(qml.PauliZ(wires=2)) assert len(new_tape.operations) == len(true_decomposition) for tape_op, true_op in zip(new_tape.operations, true_decomposition): qml.assert_equal(tape_op, true_op) assert new_tape.shots is tape.shots assert new_tape.wires == tape.wires assert new_tape.batch_size == tape.batch_size assert new_tape.output_dim == tape.output_dim def test_default_expand_fn_with_invalid_op(self, mock_device_supporting_paulis, recwarn): """Test that default_expand_fn works with an invalid op and some measurement.""" invalid_tape = qml.tape.QuantumScript([qml.S(0)], [qml.expval(qml.PauliZ(0))]) expected_tape = qml.tape.QuantumScript([qml.RZ(np.pi / 2, 0)], [qml.expval(qml.PauliZ(0))]) dev = mock_device_supporting_paulis(wires=1) expanded_tape = dev.expand_fn(invalid_tape, max_expansion=3) qml.assert_equal(expanded_tape, expected_tape) assert len(recwarn) == 0 def test_stopping_condition_passes_with_non_obs_mp(self, mock_device_with_identity, recwarn): """Test that Device.stopping_condition passes with non-observable measurements""" dev = mock_device_with_identity(wires=1) assert dev.stopping_condition(qml.state()) assert len(recwarn) == 0 # pylint: disable=too-few-public-methods class TestClassmethods: """Test the classmethods of Device""" def test_capabilities(self, mock_device_with_capabilities): """check that device can give a dict of further capabilities""" dev = mock_device_with_capabilities() assert dev.capabilities() == mock_device_capabilities class TestOperations: """Tests the logic related to operations""" # pylint: disable=protected-access def test_shots_setter(self, mock_device): """Tests that the property setter of shots changes the number of shots.""" dev = mock_device() assert dev._shots == 1000 dev.shots = 10 assert dev._shots == 10 @pytest.mark.parametrize("shots", [-10, 0]) def test_shots_setter_error(self, mock_device, shots): """Tests that the property setter of shots raises an error if the requested number of shots is erroneous.""" dev = mock_device() with pytest.raises( qml.DeviceError, match="The specified number of shots needs to be at least 1" ): dev.shots = shots # pylint: disable=pointless-statement def test_op_queue_accessed_outside_execution_context(self, mock_device): """Tests that a call to op_queue outside the execution context raises the correct error""" dev = mock_device() with pytest.raises( ValueError, match="Cannot access the operation queue outside of the execution context!" ): dev.op_queue def test_op_queue_is_filled_at_pre_measure( self, mock_device_with_paulis_and_methods, monkeypatch ): """Tests that the op_queue is correctly filled when pre_measure is called and that accessing op_queue raises no error""" dev = mock_device_with_paulis_and_methods(wires=3) queue = [ qml.PauliX(wires=0), qml.PauliY(wires=1), qml.PauliZ(wires=2), ] observables = [ qml.expval(qml.PauliZ(0)), qml.var(qml.PauliZ(1)), qml.sample(qml.PauliZ(2)), ] queue_at_pre_measure = [] with monkeypatch.context() as m: m.setattr( Device, "pre_measure", lambda self: queue_at_pre_measure.extend(self.op_queue) ) dev.execute(queue, observables) assert queue_at_pre_measure == queue def test_op_queue_is_filled_during_execution( self, mock_device_with_paulis_and_methods, monkeypatch ): """Tests that the operations are properly applied and queued""" dev = mock_device_with_paulis_and_methods(wires=3) queue = [ qml.PauliX(wires=0), qml.PauliY(wires=1), qml.PauliZ(wires=2), ] observables = [ qml.expval(qml.PauliZ(0)), qml.var(qml.PauliZ(1)), qml.sample(qml.PauliZ(2)), ] call_history = [] with monkeypatch.context() as m: m.setattr( Device, "apply", lambda self, op, wires, params: call_history.append([op, wires, params]), ) dev.execute(queue, observables) assert call_history[0] == ["PauliX", Wires([0]), []] assert call_history[1] == ["PauliY", Wires([1]), []] assert call_history[2] == ["PauliZ", Wires([2]), []] def test_unsupported_operations_raise_error(self, mock_device_with_paulis_and_methods): """Tests that the operations are properly applied and queued""" dev = mock_device_with_paulis_and_methods() queue = [ qml.PauliX(wires=0), qml.PauliY(wires=1), qml.Hadamard(wires=2), ] observables = [ qml.expval(qml.PauliZ(0)), qml.var(qml.PauliZ(1)), qml.sample(qml.PauliZ(2)), ] with pytest.raises(qml.DeviceError, match="Gate Hadamard not supported on device"): dev.execute(queue, observables) def test_execute_obs_probs(self, mock_device_supporting_paulis): """Tests that the execute function raises an error if probabilities are not supported by the device""" dev = mock_device_supporting_paulis() obs = qml.probs(op=qml.PauliZ(0)) with pytest.raises(NotImplementedError): dev.execute([], [obs]) def test_var(self, mock_device_supporting_paulis): """Tests that the variance method are not implemented by the device by default""" dev = mock_device_supporting_paulis() with pytest.raises(NotImplementedError): dev.var(qml.PauliZ, 0, []) def test_sample(self, mock_device_supporting_paulis): """Tests that the sample method are not implemented by the device by default""" dev = mock_device_supporting_paulis() with pytest.raises(NotImplementedError): dev.sample(qml.PauliZ, 0, []) @pytest.mark.parametrize("wires", [None, []]) def test_probability(self, mock_device_supporting_paulis, wires): """Tests that the probability method are not implemented by the device by default""" dev = mock_device_supporting_paulis() with pytest.raises(NotImplementedError): dev.probability(wires=wires) class TestObservables: """Tests the logic related to observables""" # pylint: disable=no-self-use, redefined-outer-name, pointless-statement def test_obs_queue_accessed_outside_execution_context(self, mock_device): """Tests that a call to op_queue outside the execution context raises the correct error""" dev = mock_device() with pytest.raises( ValueError, match="Cannot access the observable value queue outside of the execution context!", ): dev.obs_queue def test_obs_queue_is_filled_at_pre_measure( self, mock_device_with_paulis_and_methods, monkeypatch ): """Tests that the op_queue is correctly filled when pre_measure is called and that accessing op_queue raises no error""" dev = mock_device_with_paulis_and_methods(wires=3) queue = [ qml.PauliX(wires=0), qml.PauliY(wires=1), qml.PauliZ(wires=2), ] observables = [ qml.expval(qml.PauliZ(0)), qml.var(qml.PauliZ(1)), qml.sample(qml.PauliZ(2)), ] queue_at_pre_measure = [] with monkeypatch.context() as m: m.setattr( Device, "pre_measure", lambda self: queue_at_pre_measure.extend(self.obs_queue) ) dev.execute(queue, observables) assert queue_at_pre_measure == observables def test_obs_queue_is_filled_during_execution( self, monkeypatch, mock_device_with_paulis_and_methods ): """Tests that the operations are properly applied and queued""" dev = mock_device_with_paulis_and_methods(wires=3) observables = [qml.expval(qml.PauliX(0)), qml.var(qml.PauliY(1)), qml.sample(qml.PauliZ(2))] # capture the arguments passed to dev methods expval_args = [] var_args = [] sample_args = [] with monkeypatch.context() as m: m.setattr(Device, "expval", lambda self, *args: expval_args.extend(args)) m.setattr(Device, "var", lambda self, *args: var_args.extend(args)) m.setattr(Device, "sample", lambda self, *args: sample_args.extend(args)) dev.execute([], observables) assert expval_args == ["PauliX", Wires([0]), []] assert var_args == ["PauliY", Wires([1]), []] assert sample_args == ["PauliZ", Wires([2]), []] def test_unsupported_observables_raise_error(self, mock_device_with_paulis_and_methods): """Tests that the operations are properly applied and queued""" dev = mock_device_with_paulis_and_methods() queue = [ qml.PauliX(wires=0), qml.PauliY(wires=1), qml.PauliZ(wires=2), ] observables = [ qml.expval(qml.Hadamard(0)), qml.var(qml.PauliZ(1)), qml.sample(qml.PauliZ(2)), ] with pytest.raises(qml.DeviceError, match="Observable Hadamard not supported on device"): dev.execute(queue, observables) def test_unsupported_observable_return_type_raise_error( self, mock_device_with_paulis_and_methods ): """Check that an error is raised if the return type of an observable is unsupported""" dev = mock_device_with_paulis_and_methods() queue = [qml.PauliX(wires=0)] # Make a observable without specifying a return operation upon measuring observables = [qml.counts(op=qml.PauliZ(0))] with pytest.raises( qml.QuantumFunctionError, match="Unsupported return type specified for observable" ): dev.execute(queue, observables) class TestParameters: """Test for checking device parameter mappings""" # pylint: disable=pointless-statement def test_parameters_accessed_outside_execution_context(self, mock_device): """Tests that a call to parameters outside the execution context raises the correct error""" dev = mock_device() with pytest.raises( ValueError, match="Cannot access the free parameter mapping outside of the execution context!", ): dev.parameters def test_parameters_available_at_pre_measure(self, mock_device, monkeypatch): """Tests that the parameter mapping is available when pre_measure is called and that accessing Device.parameters raises no error""" dev = mock_device(wires=3) p0 = 0.54 p1 = -0.32 queue = [ qml.RX(p0, wires=0), qml.PauliY(wires=1), qml.Rot(0.432, 0.123, p1, wires=2), ] parameters = {0: (0, 0), 1: (2, 3)} observables = [ qml.expval(qml.PauliZ(0)), qml.var(qml.PauliZ(1)), qml.sample(qml.PauliZ(2)), ] p_mapping = {} with monkeypatch.context() as m: m.setattr(Device, "pre_measure", lambda self: p_mapping.update(self.parameters)) dev.execute(queue, observables, parameters=parameters) assert p_mapping == parameters class TestDeviceInit: """Tests for device loader in __init__.py""" def test_no_device(self): """Test that an exception is raised for a device that doesn't exist""" with pytest.raises(qml.DeviceError, match="Device None does not exist"): qml.device("None", wires=0) def test_outdated_API(self, monkeypatch): """Test that an exception is raised if plugin that targets an old API is loaded""" with monkeypatch.context() as m: m.setattr(qml, "version", lambda: "0.0.1") with pytest.raises(qml.DeviceError, match="plugin requires PennyLane versions"): qml.device("default.mixed", wires=0) def test_plugin_devices_from_devices_triggers_getattr(self, mocker): spied = mocker.spy(qml.devices, "__getattr__") qml.devices.plugin_devices spied.assert_called_once() def test_refresh_entrypoints(self, monkeypatch): """Test that new entrypoints are found by the refresh_devices function""" assert qml.plugin_devices with monkeypatch.context() as m: # remove all entry points retval = {"pennylane.plugins": []} if version_info[:2] == (3, 9) else [] m.setattr(metadata, "entry_points", lambda **kwargs: retval) # reimporting PennyLane within the context sets qml.plugin_devices to {} reload(qml) reload(qml.devices.device_constructor) # since there are no entry points, there will be no plugin devices assert not qml.plugin_devices # outside of the context, entrypoints will now be found assert not qml.plugin_devices qml.refresh_devices() assert qml.plugin_devices # Test teardown: re-import PennyLane to revert all changes and # restore the plugin_device dictionary reload(qml) reload(qml.devices.device_constructor) def test_hot_refresh_entrypoints(self, monkeypatch): """Test that new entrypoints are found by the device loader if not currently present""" assert qml.plugin_devices with monkeypatch.context() as m: # remove all entry points retval = {"pennylane.plugins": []} if version_info[:2] == (3, 9) else [] m.setattr(metadata, "entry_points", lambda **kwargs: retval) # reimporting PennyLane within the context sets qml.plugin_devices to {} reload(qml.devices) reload(qml.devices.device_constructor) m.setattr(qml.devices.device_constructor, "refresh_devices", lambda: None) assert not qml.plugin_devices # since there are no entry points, there will be no plugin devices with pytest.raises(qml.DeviceError, match="Device default.qubit does not exist"): qml.device("default.qubit", wires=0) # outside of the context, entrypoints will now be found automatically assert not qml.plugin_devices dev = qml.device("default.qubit", wires=0) assert qml.plugin_devices assert dev.name == "default.qubit" # Test teardown: re-import PennyLane to revert all changes and # restore the plugin_device dictionary reload(qml) reload(qml.devices.device_constructor) def test_shot_vector_property(self): """Tests shot vector initialization.""" dev = qml.device("default.mixed", wires=1, shots=[1, 3, 3, 4, 4, 4, 3]) shot_vector = dev.shot_vector assert len(shot_vector) == 4 assert shot_vector[0].shots == 1 assert shot_vector[0].copies == 1 assert shot_vector[1].shots == 3 assert shot_vector[1].copies == 2 assert shot_vector[2].shots == 4 assert shot_vector[2].copies == 3 assert shot_vector[3].shots == 3 assert shot_vector[3].copies == 1 assert dev.shots.total_shots == 22 def test_decomp_depth_is_deprecated(self): """Test that a warning is raised when using the deprecated decomp_depth argument""" with pytest.warns( qml.PennyLaneDeprecationWarning, match="The decomp_depth argument is deprecated", ): qml.device("default.qubit", decomp_depth=1) class TestBatchExecution: """Tests for the batch_execute method.""" with qml.queuing.AnnotatedQueue() as q1: qml.PauliX(wires=0) qml.expval(qml.PauliZ(wires=0)) qml.expval(qml.PauliZ(wires=1)) tape1 = qml.tape.QuantumScript.from_queue(q1) with qml.queuing.AnnotatedQueue() as q2: qml.PauliX(wires=0) qml.expval(qml.PauliZ(wires=0)) tape2 = qml.tape.QuantumScript.from_queue(q2) @pytest.mark.parametrize("n_tapes", [1, 2, 3]) def test_calls_to_execute(self, n_tapes, mocker, mock_device_with_paulis_and_methods): """Tests that the device's execute method is called the correct number of times.""" dev = mock_device_with_paulis_and_methods(wires=2) spy = mocker.spy(Device, "execute") tapes = [self.tape1] * n_tapes dev.batch_execute(tapes) assert spy.call_count == n_tapes @pytest.mark.parametrize("n_tapes", [1, 2, 3]) def test_calls_to_reset(self, n_tapes, mocker, mock_device_with_paulis_and_methods): """Tests that the device's reset method is called the correct number of times.""" dev = mock_device_with_paulis_and_methods(wires=2) spy = mocker.spy(Device, "reset") tapes = [self.tape1] * n_tapes dev.batch_execute(tapes) assert spy.call_count == n_tapes def test_result(self, mock_device_with_paulis_and_methods, tol): """Tests that the result has the correct shape and entry types.""" dev = mock_device_with_paulis_and_methods(wires=2) tapes = [self.tape1, self.tape2] res = dev.batch_execute(tapes) assert len(res) == 2 assert np.allclose( res[0], dev.execute(self.tape1.operations, self.tape1.measurements), rtol=tol, atol=0 ) assert np.allclose( res[1], dev.execute(self.tape2.operations, self.tape2.measurements), rtol=tol, atol=0 ) def test_result_empty_tape(self, mock_device_with_paulis_and_methods, tol): """Tests that the result has the correct shape and entry types for empty tapes.""" dev = mock_device_with_paulis_and_methods(wires=2) empty_tape = qml.tape.QuantumScript() tapes = [empty_tape] * 3 res = dev.batch_execute(tapes) assert len(res) == 3 assert np.allclose( res[0], dev.execute(empty_tape.operations, empty_tape.measurements), rtol=tol, atol=0 ) class TestGrouping: """Tests for the use_grouping option for devices.""" # pylint: disable=too-few-public-methods, unused-argument, missing-function-docstring, missing-class-docstring class SomeDevice(qml.Device): name = "" short_name = "" pennylane_requires = "" version = "" author = "" operations = "" observables = "" def apply(self, *args, **kwargs): return 0 def expval(self, *args, **kwargs): return 0 def reset(self, *args, **kwargs): return 0 def supports_observable(self, *args, **kwargs): return True # pylint: disable=attribute-defined-outside-init @pytest.mark.parametrize("use_grouping", (True, False)) def test_batch_transform_checks_use_grouping_property(self, use_grouping, mocker): """If the device specifies `use_grouping=False`, the batch transform method won't expand the hamiltonian when the measured hamiltonian has grouping indices. """ H = qml.Hamiltonian([1.0, 1.0], [qml.PauliX(0), qml.PauliY(0)], grouping_type="qwc") qs = qml.tape.QuantumScript(measurements=[qml.expval(H)]) spy = mocker.spy(qml.transforms, "split_non_commuting") dev = self.SomeDevice() dev.use_grouping = use_grouping new_qscripts, _ = dev.batch_transform(qs) if use_grouping: assert len(new_qscripts) == 2 spy.assert_called_once() else: assert len(new_qscripts) == 1 spy.assert_not_called() def test_batch_transform_does_not_expand_supported_sum(self, mocker): """Tests that batch_transform does not expand Sums if they are supported.""" H = qml.sum(qml.PauliX(0), qml.PauliY(0)) qs = qml.tape.QuantumScript(measurements=[qml.expval(H)]) spy = mocker.spy(qml.transforms, "split_non_commuting") dev = self.SomeDevice(shots=None) new_qscripts, _ = dev.batch_transform(qs) assert len(new_qscripts) == 1 spy.assert_not_called() def test_batch_transform_expands_not_supported_sums(self, mocker): """Tests that batch_transform expand Sums if they are not supported.""" H = qml.sum(qml.PauliX(0), qml.PauliY(0)) qs = qml.tape.QuantumScript(measurements=[qml.expval(H)]) spy = mocker.spy(qml.transforms, "split_non_commuting") dev = self.SomeDevice() dev.supports_observable = lambda *args, **kwargs: False new_qscripts, _ = dev.batch_transform(qs) assert len(new_qscripts) == 2 spy.assert_called() def test_batch_transform_expands_prod_containing_sums(self, mocker): """Tests that batch_transform expands a Prod with a nested Sum""" H = qml.prod(qml.PauliX(0), qml.sum(qml.PauliY(0), qml.PauliZ(0))) qs = qml.tape.QuantumScript(measurements=[qml.expval(H)]) spy = mocker.spy(qml.transforms, "split_non_commuting") dev = self.SomeDevice() dev.supports_observable = lambda *args, **kwargs: False new_qscripts, _ = dev.batch_transform(qs) assert len(new_qscripts) == 2 spy.assert_called()
pennylane/tests/devices/test_device.py/0
{ "file_path": "pennylane/tests/devices/test_device.py", "repo_id": "pennylane", "token_count": 20487 }
77
"""Unit testing of conversion functions for parity transform""" import pytest import pennylane as qml from pennylane.fermi.conversion import bravyi_kitaev from pennylane.fermi.fermionic import FermiSentence, FermiWord from pennylane.ops import Identity, SProd from pennylane.pauli import PauliSentence, PauliWord from pennylane.pauli.conversion import pauli_sentence def test_error_is_raised_for_incompatible_type(): """Test that an error is raised in the input is not a FermiWord or FermiSentence""" with pytest.raises(ValueError, match="fermi_operator must be a FermiWord or FermiSentence"): bravyi_kitaev(qml.PauliX(0), 10) def test_error_is_raised_for_dimension_mismatch(): """Test that an error is raised if the number of qubits are not compatible with the FermiWord or FermiSentence""" with pytest.raises( ValueError, match="Can't create or annihilate a particle on qubit index 6 for a system with only 6 qubits", ): bravyi_kitaev(FermiWord({(0, 1): "-", (1, 0): "+", (2, 6): "-"}), 6) FERMI_WORDS_AND_OPS = [ ( FermiWord({(0, 0): "+"}), 1, # trivial case of a creation operator with one qubit, 0^ -> (X_0 - iY_0) / 2 : Same as Jordan-Wigner ([0.5, -0.5j], [qml.PauliX(0), qml.PauliY(0)]), ), ( FermiWord({(0, 0): "-"}), 1, # trivial case of an annihilation operator with one qubit , 0 -> (X_0 + iY_0) / 2 : Same as Jordan-Wigner ([(0.5 + 0j), (0.0 + 0.5j)], [qml.PauliX(0), qml.PauliY(0)]), ), ( FermiWord({(0, 0): "+"}), 2, # trivial case of a creation operator with two qubits, 0^ -> (X_0 @ X_1 - iY_0 @ X_1) / 2 ([0.5, -0.5j], [qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliX(1)]), ), ( FermiWord({(0, 0): "-"}), 2, # trivial case of an annihilation operator with two qubits , 0 -> (X_0 @ X_1 + iY_0 @ X_1) / 2 ( [(0.5 + 0j), (0.0 + 0.5j)], [qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliX(1)], ), ), ( FermiWord({(0, 0): "+", (1, 0): "-"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('0^ 0'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output: (0.5+0j) [] + (-0.5+0j) [Z0] ([(0.5 + 0j), (-0.5 + 0j)], [qml.Identity(0), qml.PauliZ(0)]), ), ( FermiWord({(0, 0): "-", (1, 0): "+"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('0 0^'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output: (0.5+0j) [] + (0.5+0j) [Z0] ([(0.5 + 0j), (0.5 + 0j)], [qml.Identity(0), qml.PauliZ(0)]), ), ( FermiWord({(0, 0): "-", (1, 1): "+"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('0 1^'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output: # (-0.25+0j) [X0] + # 0.25 [X0 Z1] + # (-0-0.25j) [Y0] + # 0.25j [Y0 Z1] ( [(-0.25 + 0j), 0.25, (-0 - 0.25j), (0.25j)], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliY(0), qml.PauliY(0) @ qml.PauliZ(1), ], ), ), ( FermiWord({(0, 3): "+", (1, 0): "-"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('3^ 0'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output # (-0.25+0j) [X0 X1 Z3] + # 0.25j [X0 Y1 Z2] + # -0.25j [Y0 X1 Z3] + # (-0.25+0j) [Y0 Y1 Z2] ( [(-0.25 + 0j), 0.25j, (-0 - 0.25j), -0.25], [ qml.PauliX(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliX(0) @ qml.PauliY(1) @ qml.PauliZ(2), qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliY(0) @ qml.PauliY(1) @ qml.PauliZ(2), ], ), ), ( FermiWord({(0, 5): "+", (1, 5): "-", (2, 5): "+", (3, 5): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('5^ 5 5^ 5'), parity_code(n_qubits)) with 6 qubits ( [(0.5 + 0j), (-0.5 + 0j)], [qml.Identity(0), qml.PauliZ(4) @ qml.PauliZ(5)], ), ), ( FermiWord({(0, 3): "+", (1, 3): "-", (2, 3): "+", (3, 1): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('3^ 3 3^ 1'), parity_code(n_qubits)) with 6 qubits # (-0.25+0j) [Z0 X1 Z3] + # 0.25j [Z0 Y1 Z2] + # (0.25+0j) [X1 Z2] + # -0.25j [Y1 Z3] ( [-0.25, 0.25j, -0.25j, 0.25], [ qml.PauliZ(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliZ(0) @ qml.PauliY(1) @ qml.PauliZ(2), qml.PauliY(1) @ qml.PauliZ(3), qml.PauliX(1) @ qml.PauliZ(2), ], ), ), ( FermiWord({(0, 1): "+", (1, 0): "-", (2, 1): "+", (3, 1): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('1^ 0 1^ 1'), parity_code(n_qubits)) with 6 qubits ([0], [qml.Identity(0)]), ), ] FERMI_OPS_COMPLEX = [ ( FermiWord({(0, 2): "-", (1, 0): "+", (2, 3): "+"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('2 0^ 3^'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output # (0.125+0j) [X0 X1 X2 X3] + # 0.125j [X0 X1 Y2 X3] + # (0.125+0j) [X0 Y1 X2 Y3] + # 0.125j [X0 Y1 Y2 Y3] + # -0.125j [Y0 X1 X2 X3] + # (0.125+0j) [Y0 X1 Y2 X3] + # -0.125j [Y0 Y1 X2 Y3] + # (0.125+0j) [Y0 Y1 Y2 Y3] ( [0.125, 0.125j, 0.125 + 0j, 0.125j, -0.125j, 0.125 + 0j, -0.125j, 0.125], [ qml.PauliX(0) @ qml.PauliX(1) @ qml.PauliX(2) @ qml.PauliX(3), qml.PauliX(0) @ qml.PauliX(1) @ qml.PauliY(2) @ qml.PauliX(3), qml.PauliX(0) @ qml.PauliY(1) @ qml.PauliX(2) @ qml.PauliY(3), qml.PauliX(0) @ qml.PauliY(1) @ qml.PauliY(2) @ qml.PauliY(3), qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliX(2) @ qml.PauliX(3), qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliY(2) @ qml.PauliX(3), qml.PauliY(0) @ qml.PauliY(1) @ qml.PauliX(2) @ qml.PauliY(3), qml.PauliY(0) @ qml.PauliY(1) @ qml.PauliY(2) @ qml.PauliY(3), ], ), ), ( FermiWord({(0, 0): "-", (1, 3): "+"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('0 3^'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output # (0.25+0j) [X0 X1 Z3] + # -0.25j [X0 Y1 Z2] + # 0.25j [Y0 X1 Z3] + # (0.25+0j) [Y0 Y1 Z2] ( [0.25, -0.25j, 0.25j, 0.25], [ qml.PauliX(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliX(0) @ qml.PauliY(1) @ qml.PauliZ(2), qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliY(0) @ qml.PauliY(1) @ qml.PauliZ(2), ], ), ), ( FermiWord({(0, 3): "+", (1, 1): "+", (2, 3): "-", (3, 1): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('3^ 1^ 3 1'), parity_code(n_qubits)) with 6 qubits # -0.25 [] + # 0.25 [Z0 Z1] + # -0.25 [Z0 Z2 Z3] + # 0.25 [Z1 Z2 Z3] # reformatted the original openfermion output ( [(-0.25 + 0j), (0.25 + 0j), (-0.25 + 0j), (0.25 + 0j)], [ qml.Identity(0), qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(2) @ qml.PauliZ(3), qml.PauliZ(1) @ qml.PauliZ(2) @ qml.PauliZ(3), ], ), ), ( FermiWord({(0, 1): "+", (1, 4): "-", (2, 3): "-", (3, 4): "+"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('1^ 4 3 4^'), parity_code(n_qubits)) with 6 qubits # reformatted the original openfermion output # (0.125+0j) [Z0 X1 Z3] + # (0.125+0j) [Z0 X1 Z3 Z4] + # 0.125j [Z0 Y1 Z2] + # 0.125j [Z0 Y1 Z2 Z4] + # (-0.125+0j) [X1 Z2] + # (-0.125+0j) [X1 Z2 Z4] + # -0.125j [Y1 Z3] + # -0.125j [Y1 Z3 Z4] ( [0.125, 0.125, 0.125j, 0.125j, -0.125, -0.125, -0.125j, -0.125j], [ qml.PauliZ(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliZ(0) @ qml.PauliX(1) @ qml.PauliZ(3) @ qml.PauliZ(4), qml.PauliZ(0) @ qml.PauliY(1) @ qml.PauliZ(2), qml.PauliZ(0) @ qml.PauliY(1) @ qml.PauliZ(2) @ qml.PauliZ(4), qml.PauliX(1) @ qml.PauliZ(2), qml.PauliX(1) @ qml.PauliZ(2) @ qml.PauliZ(4), qml.PauliY(1) @ qml.PauliZ(3), qml.PauliY(1) @ qml.PauliZ(3) @ qml.PauliZ(4), ], ), ), ( FermiWord({(0, 3): "+", (1, 1): "-", (2, 3): "+", (3, 1): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('3^ 1 3^ 1'), parity_code(n_qubits)) with 6 qubits ([0], [qml.Identity(3)]), ), ( FermiWord({(0, 1): "+", (1, 0): "+", (2, 4): "-", (3, 5): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('1^ 0^ 4 5'), parity_code(n_qubits)) with 6 qubits # (0.0625+0j) [X0 Z1 X4] + # (0.0625+0j) [X0 Z1 X4 Z5] + # 0.0625j [X0 Z1 Y4] + # 0.0625j [X0 Z1 Y4 Z5] + # (0.0625+0j) [X0 X4] + # (0.0625+0j) [X0 X4 Z5] + # 0.0625j [X0 Y4] + # 0.0625j [X0 Y4 Z5] + # -0.0625j [Y0 Z1 X4] + # -0.0625j [Y0 Z1 X4 Z5] + # (0.0625+0j) [Y0 Z1 Y4] + # (0.0625+0j) [Y0 Z1 Y4 Z5] + # -0.0625j [Y0 X4] + # -0.0625j [Y0 X4 Z5] + # (0.0625+0j) [Y0 Y4] + # (0.0625+0j) [Y0 Y4 Z5] ( [ 0.0625, 0.0625, 0.0625j, 0.0625j, 0.0625, 0.0625, 0.0625j, 0.0625j, -0.0625j, -0.0625j, 0.0625, 0.0625, -0.0625j, -0.0625j, 0.0625, 0.0625, ], [ qml.PauliX(0) @ qml.PauliZ(1) @ qml.PauliX(4), qml.PauliX(0) @ qml.PauliZ(1) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliX(0) @ qml.PauliZ(1) @ qml.PauliY(4), qml.PauliX(0) @ qml.PauliZ(1) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliX(0) @ qml.PauliX(4), qml.PauliX(0) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliX(0) @ qml.PauliY(4), qml.PauliX(0) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliY(0) @ qml.PauliZ(1) @ qml.PauliX(4), qml.PauliY(0) @ qml.PauliZ(1) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliY(0) @ qml.PauliZ(1) @ qml.PauliY(4), qml.PauliY(0) @ qml.PauliZ(1) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliY(0) @ qml.PauliX(4), qml.PauliY(0) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliY(0) @ qml.PauliY(4), qml.PauliY(0) @ qml.PauliY(4) @ qml.PauliZ(5), ], ), ), ( FermiWord({(0, 1): "-", (1, 0): "+"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('1 0^'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output: # -0.25 [X0] + # 0.25 [X0 Z1] + # 0.25j [Y0] + # (-0-0.25j) [Y0 Z1] ( [(-0.25 + 0j), 0.25, 0.25j, (-0 - 0.25j)], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliY(0), qml.PauliY(0) @ qml.PauliZ(1), ], ), ), ( FermiWord({(0, 1): "+", (1, 1): "-", (2, 3): "+", (3, 4): "-", (4, 2): "+", (5, 5): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('1^ 1 3^ 4 2^ 5'), parity_code(n_qubits)) with 6 qubits # (0.03125+0j) [Z0 Z1 X2 X4] + # (0.03125+0j) [Z0 Z1 X2 X4 Z5] + # 0.03125j [Z0 Z1 X2 Y4] + # 0.03125j [Z0 Z1 X2 Y4 Z5] + # -0.03125j [Z0 Z1 Y2 X4] + # -0.03125j [Z0 Z1 Y2 X4 Z5] + # (0.03125+0j) [Z0 Z1 Y2 Y4] + # (0.03125+0j) [Z0 Z1 Y2 Y4 Z5] + # (0.03125+0j) [Z0 X2 Z3 X4] + # (0.03125+0j) [Z0 X2 Z3 X4 Z5] + # 0.03125j [Z0 X2 Z3 Y4] + # 0.03125j [Z0 X2 Z3 Y4 Z5] + # -0.03125j [Z0 Y2 Z3 X4] + # -0.03125j [Z0 Y2 Z3 X4 Z5] + # (0.03125+0j) [Z0 Y2 Z3 Y4] + # (0.03125+0j) [Z0 Y2 Z3 Y4 Z5] + # (-0.03125+0j) [Z1 X2 Z3 X4] + # (-0.03125+0j) [Z1 X2 Z3 X4 Z5] + # -0.03125j [Z1 X2 Z3 Y4] + # -0.03125j [Z1 X2 Z3 Y4 Z5] + # 0.03125j [Z1 Y2 Z3 X4] + # 0.03125j [Z1 Y2 Z3 X4 Z5] + # (-0.03125+0j) [Z1 Y2 Z3 Y4] + # (-0.03125+0j) [Z1 Y2 Z3 Y4 Z5] + # (-0.03125+0j) [X2 X4] + # (-0.03125+0j) [X2 X4 Z5] + # -0.03125j [X2 Y4] + # -0.03125j [X2 Y4 Z5] + # 0.03125j [Y2 X4] + # 0.03125j [Y2 X4 Z5] + # (-0.03125+0j) [Y2 Y4] + # (-0.03125+0j) [Y2 Y4 Z5] ( [ 0.03125, 0.03125, 0.03125j, 0.03125j, -0.03125j, -0.03125j, 0.03125, 0.03125, 0.03125, 0.03125, 0.03125j, 0.03125j, -0.03125j, -0.03125j, 0.03125, 0.03125, -0.03125, -0.03125, -0.03125j, -0.03125j, 0.03125j, 0.03125j, -0.03125, -0.03125, -0.03125, -0.03125, -0.03125j, -0.03125j, 0.03125j, 0.03125j, -0.03125, -0.03125, ], [ qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliX(4), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliY(4), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliX(4), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliY(4), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliX(4), qml.PauliZ(0) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliY(4), qml.PauliZ(0) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliX(4), qml.PauliZ(0) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliY(4), qml.PauliZ(0) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliX(4), qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliY(4), qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliX(4), qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliY(4), qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliX(2) @ qml.PauliX(4), qml.PauliX(2) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliX(2) @ qml.PauliY(4), qml.PauliX(2) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliY(2) @ qml.PauliX(4), qml.PauliY(2) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliY(2) @ qml.PauliY(4), qml.PauliY(2) @ qml.PauliY(4) @ qml.PauliZ(5), ], ), ), ] with qml.operation.disable_new_opmath_cm(): FERMI_WORDS_AND_OPS_LEGACY = [ ( FermiWord({(0, 0): "+"}), 1, # trivial case of a creation operator with one qubit, 0^ -> (X_0 - iY_0) / 2 : Same as Jordan-Wigner ([0.5, -0.5j], [qml.PauliX(0), qml.PauliY(0)]), ), ( FermiWord({(0, 0): "-"}), 1, # trivial case of an annihilation operator with one qubit , 0 -> (X_0 + iY_0) / 2 : Same as Jordan-Wigner ([(0.5 + 0j), (0.0 + 0.5j)], [qml.PauliX(0), qml.PauliY(0)]), ), ( FermiWord({(0, 0): "+"}), 2, # trivial case of a creation operator with two qubits, 0^ -> (X_0 @ X_1 - iY_0 @ X_1) / 2 ([0.5, -0.5j], [qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliX(1)]), ), ( FermiWord({(0, 0): "-"}), 2, # trivial case of an annihilation operator with two qubits , 0 -> (X_0 @ X_1 + iY_0 @ X_1) / 2 ( [(0.5 + 0j), (0.0 + 0.5j)], [qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliX(1)], ), ), ( FermiWord({(0, 0): "+", (1, 0): "-"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('0^ 0'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output: (0.5+0j) [] + (-0.5+0j) [Z0] ([(0.5 + 0j), (-0.5 + 0j)], [qml.Identity(0), qml.PauliZ(0)]), ), ( FermiWord({(0, 0): "-", (1, 0): "+"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('0 0^'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output: (0.5+0j) [] + (0.5+0j) [Z0] ([(0.5 + 0j), (0.5 + 0j)], [qml.Identity(0), qml.PauliZ(0)]), ), ( FermiWord({(0, 0): "-", (1, 1): "+"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('0 1^'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output: # (-0.25+0j) [X0] + # 0.25 [X0 Z1] + # (-0-0.25j) [Y0] + # 0.25j [Y0 Z1] ( [(-0.25 + 0j), 0.25, (-0 - 0.25j), (0.25j)], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliY(0), qml.PauliY(0) @ qml.PauliZ(1), ], ), ), ( FermiWord({(0, 3): "+", (1, 0): "-"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('3^ 0'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output # (-0.25+0j) [X0 X1 Z3] + # 0.25j [X0 Y1 Z2] + # -0.25j [Y0 X1 Z3] + # (-0.25+0j) [Y0 Y1 Z2] ( [(-0.25 + 0j), 0.25j, (-0 - 0.25j), -0.25], [ qml.PauliX(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliX(0) @ qml.PauliY(1) @ qml.PauliZ(2), qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliY(0) @ qml.PauliY(1) @ qml.PauliZ(2), ], ), ), ( FermiWord({(0, 5): "+", (1, 5): "-", (2, 5): "+", (3, 5): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('5^ 5 5^ 5'), parity_code(n_qubits)) with 6 qubits ( [(0.5 + 0j), (-0.5 + 0j)], [qml.Identity(0), qml.PauliZ(4) @ qml.PauliZ(5)], ), ), ( FermiWord({(0, 3): "+", (1, 3): "-", (2, 3): "+", (3, 1): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('3^ 3 3^ 1'), parity_code(n_qubits)) with 6 qubits # (-0.25+0j) [Z0 X1 Z3] + # 0.25j [Z0 Y1 Z2] + # (0.25+0j) [X1 Z2] + # -0.25j [Y1 Z3] ( [-0.25, 0.25j, -0.25j, 0.25], [ qml.PauliZ(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliZ(0) @ qml.PauliY(1) @ qml.PauliZ(2), qml.PauliY(1) @ qml.PauliZ(3), qml.PauliX(1) @ qml.PauliZ(2), ], ), ), ( FermiWord({(0, 1): "+", (1, 0): "-", (2, 1): "+", (3, 1): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('1^ 0 1^ 1'), parity_code(n_qubits)) with 6 qubits ([0], [qml.Identity(0)]), ), ] FERMI_OPS_COMPLEX_LEGACY = [ ( FermiWord({(0, 2): "-", (1, 0): "+", (2, 3): "+"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('2 0^ 3^'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output # (0.125+0j) [X0 X1 X2 X3] + # 0.125j [X0 X1 Y2 X3] + # (0.125+0j) [X0 Y1 X2 Y3] + # 0.125j [X0 Y1 Y2 Y3] + # -0.125j [Y0 X1 X2 X3] + # (0.125+0j) [Y0 X1 Y2 X3] + # -0.125j [Y0 Y1 X2 Y3] + # (0.125+0j) [Y0 Y1 Y2 Y3] ( [0.125, 0.125j, 0.125 + 0j, 0.125j, -0.125j, 0.125 + 0j, -0.125j, 0.125], [ qml.PauliX(0) @ qml.PauliX(1) @ qml.PauliX(2) @ qml.PauliX(3), qml.PauliX(0) @ qml.PauliX(1) @ qml.PauliY(2) @ qml.PauliX(3), qml.PauliX(0) @ qml.PauliY(1) @ qml.PauliX(2) @ qml.PauliY(3), qml.PauliX(0) @ qml.PauliY(1) @ qml.PauliY(2) @ qml.PauliY(3), qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliX(2) @ qml.PauliX(3), qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliY(2) @ qml.PauliX(3), qml.PauliY(0) @ qml.PauliY(1) @ qml.PauliX(2) @ qml.PauliY(3), qml.PauliY(0) @ qml.PauliY(1) @ qml.PauliY(2) @ qml.PauliY(3), ], ), ), ( FermiWord({(0, 0): "-", (1, 3): "+"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('0 3^'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output # (0.25+0j) [X0 X1 Z3] + # -0.25j [X0 Y1 Z2] + # 0.25j [Y0 X1 Z3] + # (0.25+0j) [Y0 Y1 Z2] ( [0.25, -0.25j, 0.25j, 0.25], [ qml.PauliX(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliX(0) @ qml.PauliY(1) @ qml.PauliZ(2), qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliY(0) @ qml.PauliY(1) @ qml.PauliZ(2), ], ), ), ( FermiWord({(0, 3): "+", (1, 1): "+", (2, 3): "-", (3, 1): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('3^ 1^ 3 1'), parity_code(n_qubits)) with 6 qubits # -0.25 [] + # 0.25 [Z0 Z1] + # -0.25 [Z0 Z2 Z3] + # 0.25 [Z1 Z2 Z3] # reformatted the original openfermion output ( [(-0.25 + 0j), (0.25 + 0j), (-0.25 + 0j), (0.25 + 0j)], [ qml.Identity(0), qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(2) @ qml.PauliZ(3), qml.PauliZ(1) @ qml.PauliZ(2) @ qml.PauliZ(3), ], ), ), ( FermiWord({(0, 1): "+", (1, 4): "-", (2, 3): "-", (3, 4): "+"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('1^ 4 3 4^'), parity_code(n_qubits)) with 6 qubits # reformatted the original openfermion output # (0.125+0j) [Z0 X1 Z3] + # (0.125+0j) [Z0 X1 Z3 Z4] + # 0.125j [Z0 Y1 Z2] + # 0.125j [Z0 Y1 Z2 Z4] + # (-0.125+0j) [X1 Z2] + # (-0.125+0j) [X1 Z2 Z4] + # -0.125j [Y1 Z3] + # -0.125j [Y1 Z3 Z4] ( [0.125, 0.125, 0.125j, 0.125j, -0.125, -0.125, -0.125j, -0.125j], [ qml.PauliZ(0) @ qml.PauliX(1) @ qml.PauliZ(3), qml.PauliZ(0) @ qml.PauliX(1) @ qml.PauliZ(3) @ qml.PauliZ(4), qml.PauliZ(0) @ qml.PauliY(1) @ qml.PauliZ(2), qml.PauliZ(0) @ qml.PauliY(1) @ qml.PauliZ(2) @ qml.PauliZ(4), qml.PauliX(1) @ qml.PauliZ(2), qml.PauliX(1) @ qml.PauliZ(2) @ qml.PauliZ(4), qml.PauliY(1) @ qml.PauliZ(3), qml.PauliY(1) @ qml.PauliZ(3) @ qml.PauliZ(4), ], ), ), ( FermiWord({(0, 3): "+", (1, 1): "-", (2, 3): "+", (3, 1): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('3^ 1 3^ 1'), parity_code(n_qubits)) with 6 qubits ([0], [qml.Identity(3)]), ), ( FermiWord({(0, 1): "+", (1, 0): "+", (2, 4): "-", (3, 5): "-"}), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('1^ 0^ 4 5'), parity_code(n_qubits)) with 6 qubits # (0.0625+0j) [X0 Z1 X4] + # (0.0625+0j) [X0 Z1 X4 Z5] + # 0.0625j [X0 Z1 Y4] + # 0.0625j [X0 Z1 Y4 Z5] + # (0.0625+0j) [X0 X4] + # (0.0625+0j) [X0 X4 Z5] + # 0.0625j [X0 Y4] + # 0.0625j [X0 Y4 Z5] + # -0.0625j [Y0 Z1 X4] + # -0.0625j [Y0 Z1 X4 Z5] + # (0.0625+0j) [Y0 Z1 Y4] + # (0.0625+0j) [Y0 Z1 Y4 Z5] + # -0.0625j [Y0 X4] + # -0.0625j [Y0 X4 Z5] + # (0.0625+0j) [Y0 Y4] + # (0.0625+0j) [Y0 Y4 Z5] ( [ 0.0625, 0.0625, 0.0625j, 0.0625j, 0.0625, 0.0625, 0.0625j, 0.0625j, -0.0625j, -0.0625j, 0.0625, 0.0625, -0.0625j, -0.0625j, 0.0625, 0.0625, ], [ qml.PauliX(0) @ qml.PauliZ(1) @ qml.PauliX(4), qml.PauliX(0) @ qml.PauliZ(1) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliX(0) @ qml.PauliZ(1) @ qml.PauliY(4), qml.PauliX(0) @ qml.PauliZ(1) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliX(0) @ qml.PauliX(4), qml.PauliX(0) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliX(0) @ qml.PauliY(4), qml.PauliX(0) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliY(0) @ qml.PauliZ(1) @ qml.PauliX(4), qml.PauliY(0) @ qml.PauliZ(1) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliY(0) @ qml.PauliZ(1) @ qml.PauliY(4), qml.PauliY(0) @ qml.PauliZ(1) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliY(0) @ qml.PauliX(4), qml.PauliY(0) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliY(0) @ qml.PauliY(4), qml.PauliY(0) @ qml.PauliY(4) @ qml.PauliZ(5), ], ), ), ( FermiWord({(0, 1): "-", (1, 0): "+"}), 4, # obtained with openfermion using: binary_code_transform(FermionOperator('1 0^'), parity_code(n_qubits)) for n_qubits = 4 # reformatted the original openfermion output: # -0.25 [X0] + # 0.25 [X0 Z1] + # 0.25j [Y0] + # (-0-0.25j) [Y0 Z1] ( [(-0.25 + 0j), 0.25, 0.25j, (-0 - 0.25j)], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliY(0), qml.PauliY(0) @ qml.PauliZ(1), ], ), ), ( FermiWord( {(0, 1): "+", (1, 1): "-", (2, 3): "+", (3, 4): "-", (4, 2): "+", (5, 5): "-"} ), 6, # obtained with openfermion using: binary_code_transform(FermionOperator('1^ 1 3^ 4 2^ 5'), parity_code(n_qubits)) with 6 qubits # (0.03125+0j) [Z0 Z1 X2 X4] + # (0.03125+0j) [Z0 Z1 X2 X4 Z5] + # 0.03125j [Z0 Z1 X2 Y4] + # 0.03125j [Z0 Z1 X2 Y4 Z5] + # -0.03125j [Z0 Z1 Y2 X4] + # -0.03125j [Z0 Z1 Y2 X4 Z5] + # (0.03125+0j) [Z0 Z1 Y2 Y4] + # (0.03125+0j) [Z0 Z1 Y2 Y4 Z5] + # (0.03125+0j) [Z0 X2 Z3 X4] + # (0.03125+0j) [Z0 X2 Z3 X4 Z5] + # 0.03125j [Z0 X2 Z3 Y4] + # 0.03125j [Z0 X2 Z3 Y4 Z5] + # -0.03125j [Z0 Y2 Z3 X4] + # -0.03125j [Z0 Y2 Z3 X4 Z5] + # (0.03125+0j) [Z0 Y2 Z3 Y4] + # (0.03125+0j) [Z0 Y2 Z3 Y4 Z5] + # (-0.03125+0j) [Z1 X2 Z3 X4] + # (-0.03125+0j) [Z1 X2 Z3 X4 Z5] + # -0.03125j [Z1 X2 Z3 Y4] + # -0.03125j [Z1 X2 Z3 Y4 Z5] + # 0.03125j [Z1 Y2 Z3 X4] + # 0.03125j [Z1 Y2 Z3 X4 Z5] + # (-0.03125+0j) [Z1 Y2 Z3 Y4] + # (-0.03125+0j) [Z1 Y2 Z3 Y4 Z5] + # (-0.03125+0j) [X2 X4] + # (-0.03125+0j) [X2 X4 Z5] + # -0.03125j [X2 Y4] + # -0.03125j [X2 Y4 Z5] + # 0.03125j [Y2 X4] + # 0.03125j [Y2 X4 Z5] + # (-0.03125+0j) [Y2 Y4] + # (-0.03125+0j) [Y2 Y4 Z5] ( [ 0.03125, 0.03125, 0.03125j, 0.03125j, -0.03125j, -0.03125j, 0.03125, 0.03125, 0.03125, 0.03125, 0.03125j, 0.03125j, -0.03125j, -0.03125j, 0.03125, 0.03125, -0.03125, -0.03125, -0.03125j, -0.03125j, 0.03125j, 0.03125j, -0.03125, -0.03125, -0.03125, -0.03125, -0.03125j, -0.03125j, 0.03125j, 0.03125j, -0.03125, -0.03125, ], [ qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliX(4), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliY(4), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliX(4), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliY(4), qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliX(4), qml.PauliZ(0) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliY(4), qml.PauliZ(0) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliX(4), qml.PauliZ(0) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(0) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliY(4), qml.PauliZ(0) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliX(4), qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliY(4), qml.PauliZ(1) @ qml.PauliX(2) @ qml.PauliZ(3) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliX(4), qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliY(4), qml.PauliZ(1) @ qml.PauliY(2) @ qml.PauliZ(3) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliX(2) @ qml.PauliX(4), qml.PauliX(2) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliX(2) @ qml.PauliY(4), qml.PauliX(2) @ qml.PauliY(4) @ qml.PauliZ(5), qml.PauliY(2) @ qml.PauliX(4), qml.PauliY(2) @ qml.PauliX(4) @ qml.PauliZ(5), qml.PauliY(2) @ qml.PauliY(4), qml.PauliY(2) @ qml.PauliY(4) @ qml.PauliZ(5), ], ), ), ] @pytest.mark.usefixtures("use_new_opmath") @pytest.mark.parametrize("fermionic_op, n_qubits, result", FERMI_WORDS_AND_OPS + FERMI_OPS_COMPLEX) def test_bravyi_kitaev_fermi_word_ps(fermionic_op, n_qubits, result): """Test that the parity_transform function returns the correct qubit operator.""" # convert FermiWord to PauliSentence and simplify qubit_op = bravyi_kitaev(fermionic_op, n_qubits, ps=True) qubit_op.simplify() # get expected op as PauliSentence and simplify expected_op = pauli_sentence(qml.Hamiltonian(result[0], result[1])) expected_op.simplify() assert qubit_op == expected_op @pytest.mark.usefixtures("use_legacy_opmath") @pytest.mark.parametrize( "fermionic_op, n_qubits, result", FERMI_WORDS_AND_OPS_LEGACY + FERMI_OPS_COMPLEX_LEGACY ) def test_bravyi_kitaev_fermi_word_ps_legacy(fermionic_op, n_qubits, result): """Test that the parity_transform function returns the correct qubit operator.""" # convert FermiWord to PauliSentence and simplify qubit_op = bravyi_kitaev(fermionic_op, n_qubits, ps=True) qubit_op.simplify() # get expected op as PauliSentence and simplify expected_op = pauli_sentence(qml.Hamiltonian(result[0], result[1])) expected_op.simplify() assert qubit_op == expected_op @pytest.mark.usefixtures("use_new_opmath") @pytest.mark.parametrize("fermionic_op, n_qubits, result", FERMI_WORDS_AND_OPS) def test_bravyi_kitaev_fermi_word_operation(fermionic_op, n_qubits, result): wires = fermionic_op.wires or [0] qubit_op = bravyi_kitaev(fermionic_op, n_qubits) expected_op = pauli_sentence(qml.Hamiltonian(result[0], result[1])) expected_op = expected_op.operation(wires) qml.assert_equal(qubit_op.simplify(), expected_op.simplify()) @pytest.mark.usefixtures("use_legacy_opmath") @pytest.mark.parametrize("fermionic_op, n_qubits, result", FERMI_WORDS_AND_OPS_LEGACY) def test_bravyi_kitaev_fermi_word_operation_legacy(fermionic_op, n_qubits, result): wires = fermionic_op.wires or [0] qubit_op = bravyi_kitaev(fermionic_op, n_qubits) expected_op = pauli_sentence(qml.Hamiltonian(result[0], result[1])) expected_op = expected_op.operation(wires) qml.assert_equal(qubit_op.simplify(), expected_op.simplify()) def test_bravyi_kitaev_for_identity(): """Test that the bravyi_kitaev function returns the correct qubit operator for Identity.""" qml.assert_equal(bravyi_kitaev(FermiWord({}), 2), qml.Identity(0)) def test_bravyi_kitaev_for_identity_ps(): """Test that the bravyi_kitaev function returns the correct PauliSentence for Identity when ps=True.""" assert bravyi_kitaev(FermiWord({}), 2, ps=True) == PauliSentence( {PauliWord({0: "I"}): 1.0 + 0.0j} ) @pytest.mark.parametrize( "operator", ( FermiWord({(0, 1): "-", (1, 0): "+", (2, 2): "-", (3, 1): "-"}), # ('1 0^ 2 1') FermiWord({(0, 1): "-", (1, 0): "+", (2, 2): "+", (3, 1): "-"}), # ('1 0^ 2^ 1') FermiWord({(0, 3): "-", (1, 0): "+", (2, 2): "+", (3, 3): "-"}), # ('3 0^ 2^ 3') FermiWord({(0, 3): "-", (1, 2): "+", (2, 2): "+", (3, 3): "-"}), # ('3 2^ 2^ 3') ), ) def test_bravyi_kitaev_for_null_operator_fermi_word_ps(operator): """Test that the parity_tranform function works when the result is 0""" # in PauliSentence return format, returns None assert bravyi_kitaev(operator, 4, ps=True).simplify() is None # in operation return format, '0 * I' op = bravyi_kitaev(operator, 4).simplify() assert isinstance(op, SProd) assert isinstance(op.base, Identity) assert op.scalar == 0 fw1 = FermiWord({(0, 0): "+", (1, 1): "-"}) fw2 = FermiWord({(0, 0): "+", (1, 0): "-"}) fw3 = FermiWord({(0, 0): "+", (1, 3): "-", (2, 0): "+", (3, 4): "-"}) fw4 = FermiWord({}) fw5 = FermiWord({(0, 3): "+", (1, 2): "-"}) fw6 = FermiWord({(0, 1): "+", (1, 4): "-"}) def test_empty_fermi_sentence(): """Test that an empty FermiSentence (fermi null operator) is converted to an empty PauliSentence or the null operator""" op = FermiSentence({}) ps_op = bravyi_kitaev(op, 6, ps=True) ps_op.simplify() assert ps_op == PauliSentence({}) op = bravyi_kitaev(op, 6).simplify() assert isinstance(op, SProd) assert isinstance(op.base, Identity) assert op.scalar == 0 def test_fermi_sentence_identity(): """Test that a FermiSentence composed of a single Identity operator converts to PauliSentence and operation as expected""" op = FermiSentence({fw4: 1}) ps = PauliSentence({PauliWord({}): 1}) ps_op = bravyi_kitaev(op, 6, ps=True) qubit_op = bravyi_kitaev(op, 6) assert ps_op == ps result = ps.operation(wire_order=[0]) qml.assert_equal(qubit_op.simplify(), result.simplify()) FERMI_AND_PAULI_SENTENCES = [ (FermiSentence({fw4: 0, fw2: 0}), 4, PauliSentence({})), # all 0 coeffs FermiSentence to null ( FermiSentence({fw2: 2}), 4, PauliSentence({PauliWord({}): (1 + 0j), PauliWord({0: "Z"}): (-1 + 0j)}), ), ( FermiSentence({fw1: 1, fw2: 1}), 4, PauliSentence( { PauliWord({0: "Y"}): -0.25j, PauliWord({0: "X", 1: "Z"}): (-0.25 + 0j), PauliWord({0: "X"}): (0.25 + 0j), PauliWord({0: "Y", 1: "Z"}): 0.25j, PauliWord({}): (0.5 + 0j), PauliWord({0: "Z"}): (-0.5 + 0j), } ), ), ( FermiSentence({fw1: 1j, fw2: -2}), 4, PauliSentence( { PauliWord({0: "Y"}): (0.25 + 0j), PauliWord({0: "X", 1: "Z"}): -0.25j, PauliWord({0: "X"}): 0.25j, PauliWord({0: "Y", 1: "Z"}): (-0.25 + 0j), PauliWord({}): (-1 + 0j), PauliWord({0: "Z"}): (1 + 0j), } ), ), ( FermiSentence({fw1: -2, fw5: 1j}), 4, PauliSentence( { PauliWord({0: "X"}): -0.5, PauliWord({0: "X", 1: "Z"}): 0.5, PauliWord({0: "Y"}): 0.5j, PauliWord({0: "Y", 1: "Z"}): -0.5j, PauliWord({1: "Z", 2: "X", 3: "Z"}): -0.25j, PauliWord({1: "Z", 2: "Y", 3: "Z"}): 0.25, PauliWord({2: "X"}): 0.25j, PauliWord({2: "Y"}): -0.25, } ), ), ( FermiSentence({fw6: 1, fw2: 2}), 5, PauliSentence( { PauliWord({0: "I"}): 1.0, PauliWord({0: "Z"}): -1.0, PauliWord({0: "Z", 1: "X", 3: "Y", 4: "X"}): -0.25j, PauliWord({0: "Z", 1: "X", 3: "Y", 4: "Y"}): 0.25, PauliWord({1: "Y", 3: "Y", 4: "X"}): -0.25, PauliWord({1: "Y", 3: "Y", 4: "Y"}): -0.25j, } ), ), ( FermiSentence({fw5: 1, fw6: 1}), 5, PauliSentence( { PauliWord({0: "Z", 1: "X", 3: "Y", 4: "X"}): -0.25j, PauliWord({0: "Z", 1: "X", 3: "Y", 4: "Y"}): 0.25, PauliWord({1: "Y", 3: "Y", 4: "X"}): -0.25, PauliWord({1: "Y", 3: "Y", 4: "Y"}): -0.25j, PauliWord({1: "Z", 2: "X", 3: "Z"}): -0.25, PauliWord({1: "Z", 2: "Y", 3: "Z"}): -0.25j, PauliWord({2: "X"}): 0.25, PauliWord({2: "Y"}): 0.25j, } ), ), ] @pytest.mark.parametrize("fermionic_op, n_qubits, result", FERMI_AND_PAULI_SENTENCES) def test_bravyi_kitaev_for_fermi_sentence_ps(fermionic_op, n_qubits, result): qubit_op = bravyi_kitaev(fermionic_op, n_qubits, ps=True) qubit_op.simplify() assert qubit_op == result @pytest.mark.parametrize("fermionic_op, n_qubits, result", FERMI_AND_PAULI_SENTENCES) def test_bravyi_kitaev_for_fermi_sentence_operation(fermionic_op, n_qubits, result): wires = fermionic_op.wires or [0] qubit_op = bravyi_kitaev(fermionic_op, n_qubits) result = result.operation(wires) qml.assert_equal(qubit_op.simplify(), result.simplify()) WIRE_MAP_FOR_FERMI_SENTENCE = [ ( None, [ qml.s_prod(-0.25j, qml.PauliY(0)), qml.s_prod((0.25j), qml.prod(qml.PauliY(0), qml.PauliZ(1))), qml.s_prod((-0.25 + 0j), qml.prod(qml.PauliX(0), qml.PauliZ(1))), qml.s_prod(0.25, qml.PauliX(0)), qml.s_prod((0.5 + 0j), qml.Identity(0)), qml.s_prod((-0.5 + 0j), qml.PauliZ(0)), ], ), ( {0: 0, 1: 1}, [ qml.s_prod(-0.25j, qml.PauliY(0)), qml.s_prod((0.25j), qml.prod(qml.PauliY(0), qml.PauliZ(1))), qml.s_prod((-0.25 + 0j), qml.prod(qml.PauliX(0), qml.PauliZ(1))), qml.s_prod(0.25, qml.PauliX(0)), qml.s_prod((0.5 + 0j), qml.Identity(0)), qml.s_prod((-0.5 + 0j), qml.PauliZ(0)), ], ), ( {0: 1, 1: 0}, [ qml.s_prod(-0.25j, qml.PauliY(1)), qml.s_prod((0.25j), qml.prod(qml.PauliY(1), qml.PauliZ(0))), qml.s_prod((-0.25 + 0j), qml.prod(qml.PauliX(1), qml.PauliZ(0))), qml.s_prod(0.25, qml.PauliX(1)), qml.s_prod((0.5 + 0j), qml.Identity(0)), qml.s_prod((-0.5 + 0j), qml.PauliZ(1)), ], ), ( {0: 3, 1: 2}, [ qml.s_prod(-0.25j, qml.PauliY(3)), qml.s_prod((0.25j), qml.prod(qml.PauliY(3), qml.PauliZ(2))), qml.s_prod((-0.25 + 0j), qml.prod(qml.PauliX(3), qml.PauliZ(2))), qml.s_prod(0.25, qml.PauliX(3)), qml.s_prod((0.5 + 0j), qml.Identity(3)), qml.s_prod((-0.5 + 0j), qml.PauliZ(3)), ], ), ( {0: "b", 1: "a"}, [ qml.s_prod(-0.25j, qml.PauliY("b")), qml.s_prod((0.25j), qml.prod(qml.PauliY("b"), qml.PauliZ("a"))), qml.s_prod((-0.25 + 0j), qml.prod(qml.PauliX("b"), qml.PauliZ("a"))), qml.s_prod(0.25, qml.PauliX("b")), qml.s_prod((0.5 + 0j), qml.Identity("b")), qml.s_prod((-0.5 + 0j), qml.PauliZ("b")), ], ), ] @pytest.mark.parametrize("wire_map, ops", WIRE_MAP_FOR_FERMI_SENTENCE) def test_providing_wire_map_fermi_sentence_to_operation(wire_map, ops): fs = FermiSentence( {FermiWord({(0, 0): "+", (1, 1): "-"}): 1, FermiWord({(0, 0): "+", (1, 0): "-"}): 1} ) n_qubits = 4 op = bravyi_kitaev(fs, n_qubits, wire_map=wire_map) result = qml.sum(*ops) assert op.wires == result.wires # converting to Pauli representation for comparison because # qml.equal isn't playing nicely with term ordering assert pauli_sentence(op) == pauli_sentence(result) @pytest.mark.parametrize("wire_map, ops", WIRE_MAP_FOR_FERMI_SENTENCE) def test_providing_wire_map_fermi_sentence_to_ps(wire_map, ops): fs = FermiSentence( {FermiWord({(0, 0): "+", (1, 1): "-"}): 1, FermiWord({(0, 0): "+", (1, 0): "-"}): 1} ) n_qubits = 4 op = bravyi_kitaev(fs, n_qubits, wire_map=wire_map, ps=True) result_op = qml.sum(*ops) ps = pauli_sentence(result_op) ps.simplify() op.simplify() assert ps == op WIRE_MAP_FOR_FERMI_WORDS = [ ( None, [ qml.s_prod(-0.25j, qml.PauliY(0)), qml.s_prod(0.25 + 0j, qml.prod(qml.PauliX(0), qml.PauliZ(1))), qml.s_prod(0.25 + 0j, qml.PauliX(0)), qml.s_prod(-0.25j, qml.prod(qml.PauliY(0), qml.PauliZ(1))), ], ), ( {0: 3, 1: 2}, [ qml.s_prod(-0.25j, qml.PauliY(3)), qml.s_prod(0.25 + 0j, qml.prod(qml.PauliX(3), qml.PauliZ(2))), qml.s_prod(0.25 + 0j, qml.PauliX(3)), qml.s_prod(-0.25j, qml.prod(qml.PauliY(3), qml.PauliZ(2))), ], ), ( {0: "b", 1: "a"}, [ qml.s_prod(-0.25j, qml.PauliY("b")), qml.s_prod(0.25 + 0j, qml.prod(qml.PauliX("b"), qml.PauliZ("a"))), qml.s_prod(0.25 + 0j, qml.PauliX("b")), qml.s_prod(-0.25j, qml.prod(qml.PauliY("b"), qml.PauliZ("a"))), ], ), ] @pytest.mark.parametrize("wire_map, ops", WIRE_MAP_FOR_FERMI_WORDS) def test_providing_wire_map_fermi_word_to_operation(wire_map, ops): w = FermiWord({(0, 0): "+", (1, 1): "+"}) n_qubits = 4 op = bravyi_kitaev(w, n_qubits, wire_map=wire_map) result = qml.sum(*ops) op.simplify() # converting to Pauli representation for comparison because # qml.equal isn't playing nicely with term ordering assert pauli_sentence(op) == pauli_sentence(result) @pytest.mark.parametrize("wire_map, ops", WIRE_MAP_FOR_FERMI_WORDS) def test_providing_wire_map_fermi_word_to_ps(wire_map, ops): w = FermiWord({(0, 0): "+", (1, 1): "+"}) n_qubits = 4 op = bravyi_kitaev(w, n_qubits, wire_map=wire_map, ps=True) result_op = qml.sum(*ops) ps = pauli_sentence(result_op) ps.simplify() op.simplify() assert ps == op fs1 = FermiSentence({fw1: 1}) @pytest.mark.parametrize( "fermi_op, qubit_op_data, tol", ( (fw1, (-0.25j, (0.25 + 0j), (0.25 + 0j), 0.25j), None), (fw1, (-0.25j, 0.25, 0.25, 0.25j), 0.0), (fw1, (-0.25j, 0.25, 0.25, 0.25j), 1.0e-12), (fw1, (0, -0.25, 0.25, 0), 0.3), (fs1, (-0.25j, (0.25 + 0j), (0.25 + 0j), 0.25j), None), (fs1, (-0.25j, 0.25, 0.25, 0.25j), 0.0), (fs1, (-0.25j, 0.25, 0.25, 0.25j), 1.0e-12), (fs1, (0, -0.25, 0.25, 0), 0.3), ), ) def test_bravyi_kitaev_tolerance(fermi_op, qubit_op_data, tol): """Test that bravyi_kitaev properly removes negligible imaginary components""" n_qubits = 4 op = bravyi_kitaev(fermi_op, n_qubits, tol=tol) assert isinstance(op.data[1], type(qubit_op_data[1]))
pennylane/tests/fermi/test_bravyi_kitaev.py/0
{ "file_path": "pennylane/tests/fermi/test_bravyi_kitaev.py", "repo_id": "pennylane", "token_count": 31449 }
78
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """Tests for the gradients.general_shift_rules module.""" import numpy as np import pytest import pennylane as qml from pennylane.gradients.general_shift_rules import ( _get_shift_rule, _iterate_shift_rule_with_multipliers, eigvals_to_frequencies, frequencies_to_period, generate_multi_shift_rule, generate_multishifted_tapes, generate_shift_rule, generate_shifted_tapes, ) class TestEigvalsToFrequencies: """Tests for the eigvals_to_frequencies function""" def test_two_eigvals(self): """Test the case of two eigenvalues""" res = eigvals_to_frequencies((-0.5, 0.5)) expected = (1,) assert res == expected def test_four_eigvals(self): """Test the case of four eigenvalues""" res = eigvals_to_frequencies((0.5, -0.5, 0, 0)) expected = (0.5, 1) assert res == expected def test_nonequidistant_eigvals(self): """Test the case of non-equidistant eigenvalues""" res = eigvals_to_frequencies((0.453, 0.65, -1.2, 0)) expected = (0.453, 1.2, 1.85, 1.653, 0.65, 0.197) assert res == expected class TestFrequenciesToPeriod: """Tests for the frequencies_to_period function""" def test_single_frequency(self): """Test with a single frequency.""" res = frequencies_to_period((0.8,)) expected = 2.5 * np.pi assert res == expected def test_equidistant_frequencies(self): """Test with equidistant frequencies.""" res = frequencies_to_period((0.7, 1.4, 2.1)) expected = 2 * np.pi / 0.7 assert res == expected def test_nonequidistant_frequencies(self): """Test with non-equidistant frequencies.""" res = frequencies_to_period((1.8, 2.7, 9.0)) expected = 2 * np.pi / 0.9 assert res == expected def test_with_decimals(self): """Test with rounding "very" non-equidistant frequencies.""" res = frequencies_to_period((0.8, 1.6002), decimals=3) expected = 2.5 * np.pi assert res == expected class TestIterateShiftRuleWithMultipliers: """Tests `_iterate_shift_rule_with_multipliers` to produce the correct rules.""" @pytest.mark.parametrize("period", [None, np.pi / 3, 2 * np.pi]) def test_first_order(self, period): """Test first order iteration of a rule with multipliers.""" rule = [(-0.9, 0.7, -0.2), (0.2, 1.2, 0.4)] iterated_rule = _iterate_shift_rule_with_multipliers(rule, 1, period) assert np.allclose(iterated_rule, rule) @pytest.mark.parametrize("period", [None, np.pi / 3, 2 * np.pi]) def test_second_order(self, period): """Test second order iteration of a rule with multipliers.""" rule = [(0.2, 1.2, 0.4), (-0.9, 0.7, -0.2)] iterated_rule = _iterate_shift_rule_with_multipliers(rule, 2, period) expected = np.array( [ [0.2**2, 1.2**2, 0.4 * 1.2 + 0.4], [0.2 * -0.9, 1.2 * 0.7, 0.4 * 0.7 - 0.2], [-0.9 * 0.2, 0.7 * 1.2, -0.2 * 1.2 + 0.4], [(-0.9) ** 2, 0.7**2, -0.2 * 0.7 - 0.2], ] ) if period == np.pi / 3: expected[0, -1] -= period assert np.allclose(iterated_rule, expected) @pytest.mark.parametrize("period", [None, np.pi / 3, 2 * np.pi]) def test_third_order(self, period): """Test third order iteration of a rule with multipliers.""" rule = [(0.2, 1.2, 0.4), (-0.9, 0.7, -0.2)] iterated_rule = _iterate_shift_rule_with_multipliers(rule, 3, period) expected = np.array( [ [0.2**3, 1.2**3, (0.4 * 1.2 + 0.4) * 1.2 + 0.4], [0.2**2 * -0.9, 1.2**2 * 0.7, (0.4 * 1.2 + 0.4) * 0.7 - 0.2], [0.2 * -0.9 * 0.2, 1.2 * 0.7 * 1.2, (0.4 * 0.7 - 0.2) * 1.2 + 0.4], [0.2 * (-0.9) ** 2, 1.2 * 0.7**2, (0.4 * 0.7 - 0.2) * 0.7 - 0.2], [-0.9 * 0.2**2, 0.7 * 1.2**2, (-0.2 * 1.2 + 0.4) * 1.2 + 0.4], [-0.9 * 0.2 * -0.9, 0.7 * 1.2 * 0.7, (-0.2 * 1.2 + 0.4) * 0.7 - 0.2], [(-0.9) ** 2 * 0.2, 0.7**2 * 1.2, (-0.2 * 0.7 - 0.2) * 1.2 + 0.4], [(-0.9) ** 3, 0.7**3, (-0.2 * 0.7 - 0.2) * 0.7 - 0.2], ] ) if period == np.pi / 3: expected[0, -1] -= period expected[4, -1] -= period assert np.allclose(iterated_rule, expected) class TestGenerateShiftRule: """Tests of input validation and output correctness of function `generate_shift_rule`.""" def test_invalid_frequency_spectrum(self): """Tests ValueError is raised if input frequency spectrum is non positive or non unique.""" non_positive_frequency_spectrum = (-1, 1) non_unique_frequency_spectrum = (1, 2, 2, 3) assert pytest.raises(ValueError, _get_shift_rule, non_positive_frequency_spectrum) assert pytest.raises(ValueError, _get_shift_rule, non_unique_frequency_spectrum) def test_invalid_shifts(self): """Tests ValueError is raised if specified shifts is not of the same length as `frequencies`, or if shifts are non-unique.""" frequencies = (1, 4, 5, 6) invalid_shifts_num = (np.pi / 8, 3 * np.pi / 8, 5 * np.pi / 8) non_unique_shifts = (np.pi / 8, 3 * np.pi / 8, 5 * np.pi / 8, np.pi / 8) assert pytest.raises(ValueError, generate_shift_rule, frequencies, invalid_shifts_num) assert pytest.raises(ValueError, generate_shift_rule, frequencies, non_unique_shifts) def test_two_term_rule_default_shifts(self): """Tests the correct two term equidistant rule is generated using default shift pi/2. Frequency 1 corresponds to any generator of the form: 1/2*P, where P is a Pauli word.""" frequencies = (1,) correct_terms = [[0.5, np.pi / 2], [-0.5, -np.pi / 2]] generated_terms = generate_shift_rule(frequencies) assert np.allclose(generated_terms, correct_terms) def test_four_term_rule_default_shifts(self): """Tests the correct two term equidistant rule is generated using the default shifts [pi/4, 3*pi/4]. The frequency [1,2] corresponds to a generator e.g. of the form 1/2*X0Y1 + 1/2*Y0X1.""" frequencies = (1, 2) correct_terms = [ [0.8535533905932737, np.pi / 4], [-0.8535533905932737, -np.pi / 4], [-0.14644660940672624, 3 * np.pi / 4], [0.14644660940672624, -3 * np.pi / 4], ] generated_terms = generate_shift_rule(frequencies) assert np.allclose(generated_terms, correct_terms) def test_eight_term_rule_non_equidistant_default_shifts(self): """Tests the correct non-equidistant eight term shift rule is generated given the frequencies using the default shifts. The frequency [1,4,5,6] corresponds to e.g. a 2-qubit generator of the form: 1/2*X0Y1 + 5/2*Y0X1.""" frequencies = (1, 4, 5, 6) correct_terms = [ [2.8111804455102014, np.pi / 8], [-2.8111804455102014, -np.pi / 8], [0.31327576445128014, 3 * np.pi / 8], [-0.31327576445128014, -3 * np.pi / 8], [-0.8080445791083615, 5 * np.pi / 8], [0.8080445791083615, -5 * np.pi / 8], [-0.3101398980494395, 7 * np.pi / 8], [0.3101398980494395, -7 * np.pi / 8], ] generated_terms = generate_shift_rule(frequencies) assert np.allclose(generated_terms, correct_terms) def test_eight_term_rule_non_equidistant_custom_shifts(self): """Tests the correct non-equidistant eight term shift rule is generated given the frequencies using non-default shifts. The frequency [1,4,5,6] corresponds to e.g. a 2-qubit generator of the form: 1/2*X0Y1 + 5/2*Y0X1.""" frequencies = (1, 4, 5, 6) custom_shifts = (1 / 13 * np.pi, 3 / 7 * np.pi, 2 / 3 * np.pi, 3 / 4 * np.pi) correct_terms = [ [2.709571194594805, np.pi / 13], [-2.709571194594805, -np.pi / 13], [-0.12914139932030527, 3 * np.pi / 7], [0.12914139932030527, -3 * np.pi / 7], [-0.3820906256032637, 2 * np.pi / 3], [0.3820906256032637, -2 * np.pi / 3], [0.436088184940856, 3 * np.pi / 4], [-0.436088184940856, -3 * np.pi / 4], ] generated_terms = generate_shift_rule(frequencies, custom_shifts) assert np.allclose(generated_terms, correct_terms) def test_non_integer_frequency_default_shifts(self): """Tests the correct four term shift rule is generated given non-integer frequencies.""" frequencies = (1 / 3, 2 / 3) correct_terms = [ [0.2845177968644246, 3 * np.pi / 4], [-0.2845177968644246, -3 * np.pi / 4], [-0.048815536468908745, 9 * np.pi / 4], [0.048815536468908745, -9 * np.pi / 4], ] generated_terms = generate_shift_rule(frequencies) assert np.allclose(generated_terms, correct_terms) def test_non_integer_frequency_custom_shifts(self): """Tests the correct four term shift rule is generated given non-integer frequencies using explicitly defined shifts.""" frequencies = (1 / 3, 2 / 3, 4 / 3) custom_shifts = ( np.pi / 4, np.pi / 3, 2 * np.pi / 3, ) correct_terms = [ [1.7548361197453346, 0.7853981633974483], [-1.7548361197453346, -0.7853981633974483], [-0.8720240894718643, 1.0471975511965976], [0.8720240894718643, -1.0471975511965976], [0.016695190986336428, 2.0943951023931953], [-0.016695190986336428, -2.0943951023931953], ] generated_terms = generate_shift_rule(frequencies, custom_shifts) assert np.allclose(generated_terms, correct_terms) def test_near_singular_warning(self): """Tests a warning is raised if the determinant of the matrix to be inverted is near zero for obtaining parameter shift rules for the non-equidistant frequency case.""" frequencies = (1, 2, 3, 4, 5, 67) with pytest.warns(UserWarning, match="Solving linear problem with near zero determinant"): generate_shift_rule(frequencies) def test_second_order_two_term_shift_rule(self): """Test that the second order shift rule is correct and properly simplified""" frequencies = (1,) generated_terms = generate_shift_rule(frequencies, order=2) correct_terms = [[-0.5, 0], [0.5, -np.pi]] assert np.allclose(generated_terms, correct_terms) def test_second_order_two_term_shift_rule_custom_shifts(self): """Test that the second order shift rule is correct and properly simplified when custom shift values are provided""" frequencies = (1,) generated_terms = generate_shift_rule(frequencies, shifts=(np.pi / 4,), order=2) correct_terms = [[-1, 0], [0.5, np.pi / 2], [0.5, -np.pi / 2]] assert np.allclose(generated_terms, correct_terms) def test_second_order_four_term_shift_rule(self): """Test that the second order shift rule is correct and properly simplified for generators with 4-term rules""" frequencies = (0.5, 1) generated_terms = generate_shift_rule(frequencies, order=2) correct_terms = [ [-0.375, 0], [0.25, np.pi], [0.25, -np.pi], [-0.125, -2 * np.pi], ] assert np.allclose(generated_terms, correct_terms) def test_second_order_non_equidistant_shift_rule(self): """Test that the second order shift rule is correct and properly simplified for generators with non-equidistant frequencies""" frequencies = (2, 3) generated_terms = generate_shift_rule(frequencies, order=2) correct_terms = [ [-6, 0], [3.91421356, np.pi / 4], [3.91421356, -np.pi / 4], [-1, np.pi / 2], [-1, -np.pi / 2], [0.08578644, 3 * np.pi / 4], [0.08578644, -3 * np.pi / 4], ] assert np.allclose(generated_terms, correct_terms) class TestMultiShiftRule: """Tests for the generate_multi_shift_rule function""" def test_single_parameter(self): """Test that the generate_multi_shift_rule function correctly returns a single-parameter shift rule""" res = generate_multi_shift_rule([(1,)]) expected = [[0.5, np.pi / 2], [-0.5, -np.pi / 2]] assert np.allclose(res, expected) res = generate_multi_shift_rule([(1,)], orders=[2]) expected = [[-0.5, 0], [0.5, -np.pi]] assert np.allclose(res, expected) res = generate_multi_shift_rule([(1,)], orders=[2], shifts=[(np.pi / 4,)]) expected = [[-1, 0], [0.5, np.pi / 2], [0.5, -np.pi / 2]] assert np.allclose(res, expected) def test_two_single_frequency(self): """Test that two independent single-frequency parameters are correctly combined.""" res = generate_multi_shift_rule([(1,), (1,)]) expected = [ [0.25, np.pi / 2, np.pi / 2], [-0.25, np.pi / 2, -np.pi / 2], [-0.25, -np.pi / 2, np.pi / 2], [0.25, -np.pi / 2, -np.pi / 2], ] assert np.allclose(res, expected) def test_three_single_frequency(self): """Test that three independent single-frequency parameters are correctly combined.""" res = generate_multi_shift_rule([(1,), (1,), (1,)]) expected = [ [0.125, np.pi / 2, np.pi / 2, np.pi / 2], [-0.125, np.pi / 2, np.pi / 2, -np.pi / 2], [-0.125, np.pi / 2, -np.pi / 2, np.pi / 2], [0.125, np.pi / 2, -np.pi / 2, -np.pi / 2], [-0.125, -np.pi / 2, np.pi / 2, np.pi / 2], [0.125, -np.pi / 2, np.pi / 2, -np.pi / 2], [0.125, -np.pi / 2, -np.pi / 2, np.pi / 2], [-0.125, -np.pi / 2, -np.pi / 2, -np.pi / 2], ] assert np.allclose(res, expected) def test_two_frequency(self): """Test that two independent 2-frequency parameters are correctly combined.""" c1 = (np.sqrt(2) + 1) / (4 * np.sqrt(2)) c2 = (np.sqrt(2) - 1) / (4 * np.sqrt(2)) f = [(1,), (0.5, 1)] res = generate_multi_shift_rule(f) expected = [ [c1 * 0.5, np.pi / 2, np.pi / 2], [-c1 * 0.5, np.pi / 2, -np.pi / 2], [-c2 * 0.5, np.pi / 2, 3 * np.pi / 2], [c2 * 0.5, np.pi / 2, -3 * np.pi / 2], [-c1 * 0.5, -np.pi / 2, np.pi / 2], [c1 * 0.5, -np.pi / 2, -np.pi / 2], [c2 * 0.5, -np.pi / 2, 3 * np.pi / 2], [-c2 * 0.5, -np.pi / 2, -3 * np.pi / 2], ] assert np.allclose(res, expected) class TestGenerateShiftedTapes: """Tests for the generate_shifted_tapes function""" def test_behaviour(self): """Test that the function behaves as expected""" with qml.queuing.AnnotatedQueue() as q: qml.PauliZ(0) qml.RX(1.0, wires=0) qml.CNOT(wires=[0, 2]) qml.Rot(2.0, 3.0, 4.0, wires=0) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2} shifts = [0.1, -0.2, 1.6] res = generate_shifted_tapes(tape, 1, shifts) assert len(res) == len(shifts) assert res[0].get_parameters(trainable_only=False) == [1.0, 2.0, 3.1, 4.0] assert res[1].get_parameters(trainable_only=False) == [1.0, 2.0, 2.8, 4.0] assert res[2].get_parameters(trainable_only=False) == [1.0, 2.0, 4.6, 4.0] def test_multipliers(self): """Test that the function behaves as expected when multipliers are used""" with qml.queuing.AnnotatedQueue() as q: qml.PauliZ(0) qml.RX(1.0, wires=0) qml.CNOT(wires=[0, 2]) qml.Rot(2.0, 3.0, 4.0, wires=0) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2} shifts = [0.3, 0.6] multipliers = [0.2, 0.5] res = generate_shifted_tapes(tape, 0, shifts, multipliers) assert len(res) == 2 assert res[0].get_parameters(trainable_only=False) == [0.2 * 1.0 + 0.3, 2.0, 3.0, 4.0] assert res[1].get_parameters(trainable_only=False) == [0.5 * 1.0 + 0.6, 2.0, 3.0, 4.0] class TestGenerateMultishiftedTapes: """Tests for the generate_multishifted_tapes function""" def test_with_single_par(self): """Test that the function shifts a single tape parameter as expected""" with qml.queuing.AnnotatedQueue() as q: qml.PauliZ(0) qml.RX(1.0, wires=0) qml.CNOT(wires=[0, 2]) qml.Rot(2.0, 3.0, 4.0, wires=0) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2} shifts = [[0.1], [-0.2], [1.6]] res = generate_multishifted_tapes(tape, [1], shifts) assert len(res) == len(shifts) assert res[0].get_parameters(trainable_only=False) == [1.0, 2.0, 3.1, 4.0] assert res[1].get_parameters(trainable_only=False) == [1.0, 2.0, 2.8, 4.0] assert res[2].get_parameters(trainable_only=False) == [1.0, 2.0, 4.6, 4.0] def test_with_multiple_pars(self): """Test that the function shifts multiple tape parameters as expected""" with qml.queuing.AnnotatedQueue() as q: qml.PauliZ(0) qml.RX(1.0, wires=0) qml.CNOT(wires=[0, 2]) qml.Rot(2.0, 3.0, 4.0, wires=0) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2, 3} shifts = [[0.1, -0.5], [-0.2, 0.9], [1.6, 0.1]] res = generate_multishifted_tapes(tape, [0, 2], shifts) assert len(res) == len(shifts) assert res[0].get_parameters(trainable_only=False) == [1.1, 2.0, 3.0, 3.5] assert res[1].get_parameters(trainable_only=False) == [0.8, 2.0, 3.0, 4.9] assert res[2].get_parameters(trainable_only=False) == [2.6, 2.0, 3.0, 4.1] def test_with_multipliers(self): """Test that the function behaves as expected when multipliers are used""" with qml.queuing.AnnotatedQueue() as q: qml.PauliZ(0) qml.RX(1.0, wires=0) qml.CNOT(wires=[0, 2]) qml.Rot(2.0, 3.0, 4.0, wires=0) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2} shifts = [[0.3, -0.6], [0.2, 0.6], [0.6, 0.0]] multipliers = [[0.2, 0.5], [-0.3, 0], [1.0, 1]] expected = [ [0.5 * 1.0 - 0.6, 2.0, 0.2 * 3.0 + 0.3, 4.0], [0 * 1.0 + 0.6, 2.0, -0.3 * 3.0 + 0.2, 4.0], [1 * 1.0 + 0.0, 2.0, 1.0 * 3.0 + 0.6, 4.0], ] res = generate_multishifted_tapes(tape, [1, 0], shifts, multipliers) assert len(res) == len(shifts) for new_tape, exp in zip(res, expected): assert new_tape.get_parameters(trainable_only=False) == exp
pennylane/tests/gradients/core/test_general_shift_rules.py/0
{ "file_path": "pennylane/tests/gradients/core/test_general_shift_rules.py", "repo_id": "pennylane", "token_count": 9727 }
79
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """Tests for the gradients.param_shift_hessian module.""" from itertools import product import pytest import pennylane as qml from pennylane import numpy as np from pennylane.gradients.parameter_shift_hessian import ( _collect_recipes, _generate_offdiag_tapes, _process_argnum, ) class TestProcessArgnum: """Tests for the helper method _process_argnum.""" with qml.queuing.AnnotatedQueue() as q: qml.RX(0.2, wires=0) qml.CRZ(0.9, wires=[1, 0]) qml.RX(0.2, wires=0) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 1, 2} def test_none(self): """Test that for argnum=None all parameters are marked in the returned Boolean mask.""" argnum = _process_argnum(None, self.tape) assert qml.math.allclose(argnum, qml.math.ones((3, 3), dtype=bool)) @pytest.mark.parametrize("argnum", [0, 2]) def test_int(self, argnum): """Test that an integer argnum correctly is transformed into a Boolean mask with the corresponding diagonal element set to True.""" new_argnum = _process_argnum(argnum, self.tape) expected = qml.math.zeros((3, 3), dtype=bool) expected[argnum, argnum] = True assert qml.math.allclose(new_argnum, expected) def test_index_sequence(self): """Test that a sequence argnum with indices correctly is transformed into a Boolean mask.""" new_argnum = _process_argnum([1, 2], self.tape) expected = qml.math.zeros((3, 3), dtype=bool) expected[1:3, 1:3] = True assert qml.math.allclose(new_argnum, expected) def test_bool_sequence(self): """Test that a Boolean sequence argnum correctly is transformed into a Boolean mask.""" new_argnum = _process_argnum([True, False, True], self.tape) expected = qml.math.zeros((3, 3), dtype=bool) expected[0, 0] = expected[2, 2] = expected[2, 0] = expected[0, 2] = True assert qml.math.allclose(new_argnum, expected) @pytest.mark.parametrize( "argnum", [ [[True, False, True], [False, False, False], [True, False, False]], [[False, True, True], [True, False, True], [True, True, False]], ], ) def test_boolean_mask(self, argnum): """Test that a Boolean mask argnum correctly isn't changed.""" new_argnum = _process_argnum(argnum, self.tape) assert qml.math.allclose(new_argnum, argnum) def test_error_single_index_too_big(self): """Test that an error is raised if a (single) index is too large.""" with pytest.raises(ValueError, match="The index 10 exceeds the number"): _process_argnum(10, self.tape) def test_error_max_index_too_big(self): """Test that an error is raised if the largest index is too large.""" with pytest.raises(ValueError, match="The index 10 exceeds the number"): _process_argnum([0, 1, 10], self.tape) @pytest.mark.parametrize("length", (2, 5)) def test_error_1D_bool_wrong_length(self, length): """Test that an error is raised if a 1D boolean array with wrong length is provided.""" argnum = qml.math.ones(length, dtype=bool) with pytest.raises(ValueError, match="One-dimensional Boolean array argnum"): _process_argnum(argnum, self.tape) def test_error_wrong_ndim(self): """Test that an error is raised if an nD boolean array with wrong number of dimensions is provided.""" argnum = qml.math.ones((3, 3, 3), dtype=bool) with pytest.raises(ValueError, match="Expected a symmetric 2D Boolean array"): _process_argnum(argnum, self.tape) @pytest.mark.parametrize("shape", [(4, 4), (3, 2)]) def test_error_wrong_shape(self, shape): """Test that an error is raised if an nD boolean array with wrong shape is provided.""" argnum = qml.math.ones(shape, dtype=bool) with pytest.raises(ValueError, match="Expected a symmetric 2D Boolean array"): _process_argnum(argnum, self.tape) @pytest.mark.parametrize("dtype", [float, int]) def test_error_wrong_dtype(self, dtype): """Test that an error is raised if a 2D array with wrong data type is provided.""" argnum = qml.math.ones((3, 3), dtype=dtype) with pytest.raises(ValueError, match="Expected a symmetric 2D Boolean array"): _process_argnum(argnum, self.tape) def test_error_asymmetric(self): """Test that an error is raised if an asymmetric 2D boolean array type is provided.""" argnum = [[True, False, False], [True, True, False], [False, False, True]] with pytest.raises(ValueError, match="Expected a symmetric 2D Boolean array"): _process_argnum(argnum, self.tape) class TestCollectRecipes: """Test that gradient recipes are collected/generated correctly based on provided shift values, hard-coded recipes of operations, and argnum.""" with qml.queuing.AnnotatedQueue() as q: qml.RX(0.4, wires=0) qml.CRZ(-0.9, wires=[1, 0]) qml.Hadamard(wires=0) qml.SingleExcitation(-1.2, wires=[1, 3]) tape = qml.tape.QuantumScript.from_queue(q) def test_with_custom_recipes(self): """Test that custom gradient recipes are used correctly.""" dummy_recipe = [(-0.3, 1.0, 0.0), (0.3, 1.0, 0.4)] dummy_recipe_2nd_order = [(0.09, 1.0, 0.0), (-0.18, 1.0, 0.4), (0.09, 1.0, 0.8)] channel_recipe = [(-1, 0, 0), (1, 0, 1)] channel_recipe_2nd_order = [(0, 0, 0), (0, 0, 1)] # pylint: disable=too-few-public-methods class DummyOp(qml.RX): """A custom RX variant with dummy gradient recipe.""" grad_recipe = (dummy_recipe,) with qml.queuing.AnnotatedQueue() as q: qml.DepolarizingChannel(0.2, wires=0) DummyOp(0.3, wires=0) tape = qml.tape.QuantumScript.from_queue(q) argnum = qml.math.ones((tape.num_params, tape.num_params), dtype=bool) diag, offdiag = _collect_recipes(tape, argnum, ("A", "A"), None, None) assert qml.math.allclose(diag[0], channel_recipe_2nd_order) assert qml.math.allclose(diag[1], qml.math.array(dummy_recipe_2nd_order)) assert qml.math.allclose(offdiag[0], qml.math.array(channel_recipe)) assert qml.math.allclose(offdiag[1], qml.math.array(dummy_recipe)) two_term_recipe = [(0.5, 1.0, np.pi / 2), (-0.5, 1.0, -np.pi / 2)] c0 = (np.sqrt(2) + 1) / (4 * np.sqrt(2)) c1 = (np.sqrt(2) - 1) / (4 * np.sqrt(2)) four_term_recipe = [ (c0, 1.0, np.pi / 2), (-c0, 1.0, -np.pi / 2), (-c1, 1.0, 3 * np.pi / 2), (c1, 1.0, -3 * np.pi / 2), ] two_term_2nd_order = [(-0.5, 1.0, 0.0), (0.5, 1.0, -np.pi)] four_term_2nd_order = [ (-0.375, 1.0, 0), (0.25, 1.0, np.pi), (0.25, 1.0, -np.pi), (-0.125, 1.0, -2 * np.pi), ] expected_diag_recipes = [two_term_2nd_order, four_term_2nd_order, four_term_2nd_order] def test_with_diag_argnum(self): """Test that a diagonal boolean argnum is considered correctly.""" argnum = qml.math.eye(3, dtype=bool) diag, offdiag = _collect_recipes(self.tape, argnum, ("A",) * 3, None, None) for res, exp in zip(diag, self.expected_diag_recipes): assert qml.math.allclose(res, exp) assert all(entry == (None, None, None) for entry in offdiag) def test_with_block_diag_argnum(self): """Test that a block diagonal boolean argnum is considered correctly.""" argnum = qml.math.array([[True, True, False], [True, True, False], [False, False, True]]) diag, offdiag = _collect_recipes(self.tape, argnum, ("A",) * 3, None, None) for res, exp in zip(diag, self.expected_diag_recipes): assert qml.math.allclose(res, exp) assert qml.math.allclose(offdiag[0], self.two_term_recipe) assert qml.math.allclose(offdiag[1], self.four_term_recipe) assert offdiag[2] == (None, None, None) def test_with_other_argnum(self): """Test that a custom boolean argnum is considered correctly.""" argnum = qml.math.array([[True, True, False], [True, False, True], [False, True, True]]) diag, offdiag = _collect_recipes(self.tape, argnum, ("A",) * 3, None, None) for i, (res, exp) in enumerate(zip(diag, self.expected_diag_recipes)): if i == 1: assert res is None else: assert qml.math.allclose(res, exp) assert qml.math.allclose(offdiag[0], self.two_term_recipe) assert qml.math.allclose(offdiag[1], self.four_term_recipe) assert qml.math.allclose(offdiag[2], self.four_term_recipe) # pylint: disable=too-few-public-methods class TestGenerateOffDiagTapes: """Test some special features of `_generate_offdiag_tapes`.""" @pytest.mark.parametrize("add_unshifted", [True, False]) def test_with_zero_shifts(self, add_unshifted): """Test that zero shifts are taken into account in _generate_offdiag_tapes.""" with qml.queuing.AnnotatedQueue() as q: qml.RX(np.array(0.2), wires=[0]) qml.RY(np.array(0.9), wires=[0]) tape = qml.tape.QuantumScript.from_queue(q) recipe_0 = np.array([[-0.5, 1.0, 0.0], [0.5, 1.0, np.pi]]) recipe_1 = np.array([[-0.25, 1.0, 0.0], [0.25, 1.0, np.pi]]) t, c = [], [] new_add_unshifted, unshifted_coeff = _generate_offdiag_tapes( tape, (0, 1), [recipe_0, recipe_1], add_unshifted, t, c ) assert len(t) == 3 + int(add_unshifted) # Four tapes of which the first is not shifted assert np.allclose(c, [-0.125, -0.125, 0.125]) assert np.isclose(unshifted_coeff, 0.125) assert not new_add_unshifted orig_cls = [orig_op.__class__ for orig_op in tape.operations] expected_pars = list(product([0.2, 0.2 + np.pi], [0.9, 0.9 + np.pi])) if not add_unshifted: expected_pars = expected_pars[1:] for exp_par, h_tape in zip(expected_pars, t): assert len(h_tape.operations) == 2 assert all(op.__class__ == cls for op, cls in zip(h_tape.operations, orig_cls)) assert np.allclose(h_tape.get_parameters(), exp_par) class TestParameterShiftHessian: """Test the general functionality of the param_shift_hessian method on the tape level""" def test_single_expval(self): """Test that the correct hessian is calculated for a tape with single RX operator and single expectation value output""" dev = qml.device("default.qubit", wires=2) x = np.array(0.1, requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x, wires=0) qml.CNOT(wires=[0, 1]) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) expected = -np.cos(x) tapes, fn = qml.gradients.param_shift_hessian(tape) hessian = fn(qml.execute(tapes, dev, gradient_fn=None)) assert isinstance(hessian, np.ndarray) assert hessian.shape == () assert np.allclose(expected, hessian) def test_single_probs(self): """Test that the correct hessian is calculated for a tape with single RX operator and single probability output""" dev = qml.device("default.qubit", wires=2) x = np.array(0.1, requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x, wires=0) qml.CNOT(wires=[0, 1]) qml.probs(wires=[0, 1]) tape = qml.tape.QuantumScript.from_queue(q) expected = 0.5 * np.cos(x) * np.array([-1, 0, 0, 1]) tapes, fn = qml.gradients.param_shift_hessian(tape) hessian = fn(qml.execute(tapes, dev, gradient_fn=None)) assert isinstance(hessian, np.ndarray) assert hessian.shape == (4,) assert np.allclose(expected, hessian) def test_multi_expval(self): """Test that the correct hessian is calculated for a tape with single RX operator and multiple expval outputs""" dev = qml.device("default.qubit", wires=2) x = np.array(0.1, requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x, wires=0) qml.CNOT(wires=[0, 1]) qml.expval(qml.PauliZ(0)) qml.expval(qml.Hadamard(1)) tape = qml.tape.QuantumScript.from_queue(q) expected = (-np.cos(x), -np.cos(x) / np.sqrt(2)) tapes, fn = qml.gradients.param_shift_hessian(tape) hessian = fn(qml.execute(tapes, dev, gradient_fn=None)) assert isinstance(hessian, tuple) assert len(hessian) == 2 for hess, exp in zip(hessian, expected): assert isinstance(hess, np.ndarray) assert hess.shape == () assert np.allclose(hess, exp) def test_multi_expval_probs(self): """Test that the correct hessian is calculated for a tape with single RX operator and both expval and probability outputs""" dev = qml.device("default.qubit", wires=2) x = np.array(0.1, requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x, wires=0) qml.CNOT(wires=[0, 1]) qml.expval(qml.PauliZ(0)) qml.probs(wires=[0, 1]) tape = qml.tape.QuantumScript.from_queue(q) expected = (-np.cos(x), 0.5 * np.cos(x) * np.array([-1, 0, 0, 1])) tapes, fn = qml.gradients.param_shift_hessian(tape) hessian = fn(qml.execute(tapes, dev, gradient_fn=None)) assert isinstance(hessian, tuple) assert len(hessian) == 2 for hess, exp in zip(hessian, expected): assert isinstance(hess, np.ndarray) assert hess.shape == exp.shape assert np.allclose(hess, exp) def test_multi_probs(self): """Test that the correct hessian is calculated for a tape with single RX operator and multiple probability outputs""" dev = qml.device("default.qubit", wires=2) x = np.array(0.1, requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x, wires=0) qml.CNOT(wires=[0, 1]) qml.probs(wires=[0]) qml.probs(wires=[0, 1]) tape = qml.tape.QuantumScript.from_queue(q) expected = (0.5 * np.cos(x) * np.array([-1, 1]), 0.5 * np.cos(x) * np.array([-1, 0, 0, 1])) tapes, fn = qml.gradients.param_shift_hessian(tape) hessian = fn(qml.execute(tapes, dev, gradient_fn=None)) assert isinstance(hessian, tuple) assert len(hessian) == 2 for hess, exp in zip(hessian, expected): assert isinstance(hess, np.ndarray) assert hess.shape == exp.shape assert np.allclose(hess, exp) def test_single_expval_multi_params(self): """Test that the correct hessian is calculated for a tape with multiple operators and single expectation value output""" dev = qml.device("default.qubit", wires=2) x = np.array([0.1, 0.4], requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x[0], wires=0) qml.RY(x[1], wires=1) qml.CNOT(wires=[0, 1]) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) expected = ((-np.cos(x[0]), 0), (0, 0)) tapes, fn = qml.gradients.param_shift_hessian(tape) hessian = fn(qml.execute(tapes, dev, gradient_fn=None)) assert isinstance(hessian, tuple) assert len(hessian) == 2 assert all(isinstance(hess, tuple) for hess in hessian) assert all(len(hess) == 2 for hess in hessian) assert all( all(isinstance(h, np.ndarray) and h.shape == () for h in hess) for hess in hessian ) assert np.allclose(hessian, expected) def test_single_probs_multi_params(self): """Test that the correct hessian is calculated for a tape with multiple operators and single probability output""" dev = qml.device("default.qubit", wires=2) x = np.array([0.1, 0.4], requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x[0], wires=0) qml.RY(x[1], wires=1) qml.CNOT(wires=[0, 1]) qml.probs(wires=[0, 1]) tape = qml.tape.QuantumScript.from_queue(q) a = [ np.cos(x[0] / 2) ** 2, np.sin(x[0] / 2) ** 2, np.cos(x[1] / 2) ** 2, np.sin(x[1] / 2) ** 2, ] expected = ( ( 0.5 * np.cos(x[0]) * np.array([-a[2], -a[3], a[3], a[2]]), 0.25 * np.sin(x[0]) * np.sin(x[1]) * np.array([1, -1, 1, -1]), ), ( 0.25 * np.sin(x[0]) * np.sin(x[1]) * np.array([1, -1, 1, -1]), 0.5 * np.cos(x[1]) * np.array([-a[0], a[0], a[1], -a[1]]), ), ) tapes, fn = qml.gradients.param_shift_hessian(tape) hessian = fn(qml.execute(tapes, dev, gradient_fn=None)) assert isinstance(hessian, tuple) assert len(hessian) == 2 assert all(isinstance(hess, tuple) for hess in hessian) assert all(len(hess) == 2 for hess in hessian) assert all( all(isinstance(h, np.ndarray) and h.shape == (4,) for h in hess) for hess in hessian ) assert np.allclose(hessian, expected) def test_multi_expval_multi_params(self): """Test that the correct hessian is calculated for a tape with multiple operators and multiple expval outputs""" dev = qml.device("default.qubit", wires=2) x = np.array([0.1, 0.4], requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x[0], wires=0) qml.RY(x[1], wires=1) qml.CNOT(wires=[0, 1]) qml.expval(qml.PauliZ(0)) qml.expval(qml.Hadamard(1)) tape = qml.tape.QuantumScript.from_queue(q) expected = ( ((-np.cos(x[0]), 0), (0, 0)), ( ( -np.cos(x[0]) * np.cos(x[1]) / np.sqrt(2), np.sin(x[0]) * np.sin(x[1]) / np.sqrt(2), ), ( np.sin(x[0]) * np.sin(x[1]) / np.sqrt(2), (-np.sin(x[1]) - np.cos(x[0]) * np.cos(x[1])) / np.sqrt(2), ), ), ) tapes, fn = qml.gradients.param_shift_hessian(tape) hessian = fn(qml.execute(tapes, dev, gradient_fn=None)) assert isinstance(hessian, tuple) assert len(hessian) == 2 for hess, exp in zip(hessian, expected): assert isinstance(hess, tuple) assert len(hess) == 2 assert all(isinstance(h, tuple) for h in hess) assert all(len(h) == 2 for h in hess) assert all(all(isinstance(h_, np.ndarray) and h_.shape == () for h_ in h) for h in hess) assert np.allclose(hess, exp) def test_multi_expval_probs_multi_params(self): """Test that the correct hessian is calculated for a tape with multiple operators and both expval and probability outputs""" dev = qml.device("default.qubit", wires=2) x = np.array([0.1, 0.4], requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x[0], wires=0) qml.RY(x[1], wires=1) qml.CNOT(wires=[0, 1]) qml.expval(qml.PauliZ(0)) qml.probs(wires=[0, 1]) tape = qml.tape.QuantumScript.from_queue(q) a = [ np.cos(x[0] / 2) ** 2, np.sin(x[0] / 2) ** 2, np.cos(x[1] / 2) ** 2, np.sin(x[1] / 2) ** 2, ] expected = ( ((-np.cos(x[0]), 0), (0, 0)), ( ( 0.5 * np.cos(x[0]) * np.array([-a[2], -a[3], a[3], a[2]]), 0.25 * np.sin(x[0]) * np.sin(x[1]) * np.array([1, -1, 1, -1]), ), ( 0.25 * np.sin(x[0]) * np.sin(x[1]) * np.array([1, -1, 1, -1]), 0.5 * np.cos(x[1]) * np.array([-a[0], a[0], a[1], -a[1]]), ), ), ) tapes, fn = qml.gradients.param_shift_hessian(tape) hessian = fn(qml.execute(tapes, dev, gradient_fn=None)) assert isinstance(hessian, tuple) assert len(hessian) == 2 for hess, exp in zip(hessian, expected): assert isinstance(hess, tuple) assert len(hess) == 2 assert all(isinstance(h, tuple) for h in hess) assert all(len(h) == 2 for h in hess) assert all( all(isinstance(h_, np.ndarray) and h_.shape == exp[0][0].shape for h_ in h) for h in hess ) assert np.allclose(hess, exp) def test_multi_probs_multi_params(self): """Test that the correct hessian is calculated for a tape with multiple operators and multiple probability outputs""" dev = qml.device("default.qubit", wires=2) x = np.array([0.1, 0.4], requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x[0], wires=0) qml.RY(x[1], wires=1) qml.CNOT(wires=[0, 1]) qml.probs(wires=[1]) qml.probs(wires=[0, 1]) tape = qml.tape.QuantumScript.from_queue(q) a = [ np.cos(x[0] / 2) ** 2, np.sin(x[0] / 2) ** 2, np.cos(x[1] / 2) ** 2, np.sin(x[1] / 2) ** 2, ] expected = ( ( ( 0.5 * np.cos(x[0]) * np.cos(x[1]) * np.array([-1, 1]), 0.5 * np.sin(x[0]) * np.sin(x[1]) * np.array([1, -1]), ), ( 0.5 * np.sin(x[0]) * np.sin(x[1]) * np.array([1, -1]), 0.5 * np.cos(x[0]) * np.cos(x[1]) * np.array([-1, 1]), ), ), ( ( 0.5 * np.cos(x[0]) * np.array([-a[2], -a[3], a[3], a[2]]), 0.25 * np.sin(x[0]) * np.sin(x[1]) * np.array([1, -1, 1, -1]), ), ( 0.25 * np.sin(x[0]) * np.sin(x[1]) * np.array([1, -1, 1, -1]), 0.5 * np.cos(x[1]) * np.array([-a[0], a[0], a[1], -a[1]]), ), ), ) tapes, fn = qml.gradients.param_shift_hessian(tape) hessian = fn(qml.execute(tapes, dev, gradient_fn=None)) assert isinstance(hessian, tuple) assert len(hessian) == 2 for hess, exp in zip(hessian, expected): assert isinstance(hess, tuple) assert len(hess) == 2 assert all(isinstance(h, tuple) for h in hess) assert all(len(h) == 2 for h in hess) assert all( all(isinstance(h_, np.ndarray) and h_.shape == exp[0][0].shape for h_ in h) for h in hess ) assert np.allclose(hess, exp) def test_multi_params_argnum(self): """Test that the correct hessian is calculated for a tape with multiple operators but not all parameters trainable""" dev = qml.device("default.qubit", wires=2) x = np.array([0.1, 0.4, 0.7], requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x[0], wires=0) qml.RY(x[1], wires=1) qml.RY(x[2], wires=0) qml.CNOT(wires=[0, 1]) qml.expval(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) expected = ((0, 0, 0), (0, 0, 0), (0, 0, -np.cos(x[2] + x[0]))) tapes, fn = qml.gradients.param_shift_hessian(tape, argnum=(1, 2)) hessian = fn(qml.execute(tapes, dev, gradient_fn=None)) assert isinstance(hessian, tuple) assert len(hessian) == 3 assert all(isinstance(hess, tuple) for hess in hessian) assert all(len(hess) == 3 for hess in hessian) assert all( all(isinstance(h, np.ndarray) and h.shape == () for h in hess) for hess in hessian ) assert np.allclose(hessian, expected) def test_state_error(self): """Test that an error is raised when computing the gradient of a tape that returns state""" x = np.array(0.1, requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x, wires=0) qml.CNOT(wires=[0, 1]) qml.state() tape = qml.tape.QuantumScript.from_queue(q) msg = "Computing the Hessian of circuits that return the state is not supported" with pytest.raises(ValueError, match=msg): qml.gradients.param_shift_hessian(tape) def test_variance_error(self): """Test that an error is raised when computing the gradient of a tape that returns variance""" x = np.array(0.1, requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RY(x, wires=0) qml.CNOT(wires=[0, 1]) qml.var(qml.PauliZ(0)) tape = qml.tape.QuantumScript.from_queue(q) msg = "Computing the Hessian of circuits that return variances is currently not supported" with pytest.raises(ValueError, match=msg): qml.gradients.param_shift_hessian(tape) @pytest.mark.parametrize("num_measurements", [1, 2]) def test_no_trainable_params(self, num_measurements): """Test that the correct output and warning is generated in the absence of any trainable parameters""" dev = qml.device("default.qubit", wires=2) weights = [0.1, 0.2] with qml.queuing.AnnotatedQueue() as q: qml.RX(weights[0], wires=0) qml.RY(weights[1], wires=0) for _ in range(num_measurements): qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = [] msg = "Attempted to compute the Hessian of a tape with no trainable parameters" with pytest.warns(UserWarning, match=msg): tapes, fn = qml.gradients.param_shift_hessian(tape) res = fn(qml.execute(tapes, dev, None)) if num_measurements == 1: res = (res,) assert tapes == [] assert isinstance(res, tuple) assert len(res) == num_measurements assert all(isinstance(r, np.ndarray) and r.shape == (0,) for r in res) @pytest.mark.parametrize("num_measurements", [1, 2]) def test_all_zero_grads(self, num_measurements): """Test that the transform works correctly when the diff method for every parameter is identified to be 0, and that no tapes were generated.""" dev = qml.device("default.qubit", wires=2) # pylint: disable=too-few-public-methods class DummyOp(qml.CRZ): """A custom variant of qml.CRZ with zero grad_method.""" grad_method = "0" x = np.array(0.1, requires_grad=True) with qml.queuing.AnnotatedQueue() as q: DummyOp(x, wires=[0, 1]) for _ in range(num_measurements): qml.probs(wires=[0, 1]) tape = qml.tape.QuantumScript.from_queue(q) tapes, fn = qml.gradients.param_shift_hessian(tape) res = fn(qml.execute(tapes, dev, None)) if num_measurements == 1: res = (res,) assert tapes == [] assert isinstance(res, tuple) assert len(res) == num_measurements assert all( isinstance(r, np.ndarray) and np.allclose(r, np.array([0, 0, 0, 0])) for r in res ) def test_error_unsupported_op(self): """Test that the correct error is thrown for unsupported operations""" # pylint: disable=too-few-public-methods class DummyOp(qml.CRZ): """A custom variant of qml.CRZ with grad_method "F".""" grad_method = "F" x = np.array([0.1, 0.2, 0.3], requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) DummyOp(x[2], wires=[0, 1]) qml.probs(wires=1) tape = qml.tape.QuantumScript.from_queue(q) msg = "The parameter-shift Hessian currently does not support the operations" with pytest.raises(ValueError, match=msg): qml.gradients.param_shift_hessian(tape, argnum=[0, 1, 2])(x) @pytest.mark.parametrize("argnum", [None, (0,)]) def test_error_wrong_diagonal_shifts(self, argnum): """Test that an error is raised if the number of diagonal shifts does not match the required number (`len(trainable_params)` or `len(argnum)`).""" with qml.queuing.AnnotatedQueue() as q: qml.RX(0.4, wires=0) qml.CRY(0.9, wires=[0, 1]) tape = qml.tape.QuantumScript.from_queue(q) with pytest.raises(ValueError, match="sets of shift values for diagonal entries"): qml.gradients.param_shift_hessian(tape, argnum=argnum, diagonal_shifts=[]) @pytest.mark.parametrize("argnum", [None, (0, 1)]) def test_error_wrong_offdiagonal_shifts(self, argnum): """Test that an error is raised if the number of offdiagonal shifts does not match the required number (`len(trainable_params)` or `len(argnum)`).""" with qml.queuing.AnnotatedQueue() as q: qml.RX(0.4, wires=0) qml.CRY(0.9, wires=[0, 1]) qml.RX(-0.4, wires=0) tape = qml.tape.QuantumScript.from_queue(q) with pytest.raises(ValueError, match="sets of shift values for off-diagonal entries"): qml.gradients.param_shift_hessian(tape, argnum=argnum, off_diagonal_shifts=[]) # pylint: disable=too-many-public-methods class TestParameterShiftHessianQNode: """Test the general functionality of the param_shift_hessian method with QNodes on the default interface (autograd)""" def test_single_two_term_gate(self): """Test that the correct hessian is calculated for a QNode with single RX operator and single expectation value output (0d -> 0d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x, wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) x = np.array(0.1, requires_grad=True) expected = qml.jacobian(qml.grad(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(expected, hessian) def test_fixed_params(self): """Test that the correct hessian is calculated for a QNode with single RX operator and single expectation value output (0d -> 0d) where some fixed parameters gate are added""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RZ(0.1, wires=0) qml.RZ(-0.1, wires=0) qml.RX(x, wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) x = np.array(0.1, requires_grad=True) expected = qml.jacobian(qml.grad(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(expected, hessian) def test_gate_without_impact(self): """Test that the correct hessian is calculated for a QNode with an operator that does not have any impact on the QNode output.""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x[0], wires=0) qml.RX(x[1], wires=1) return qml.expval(qml.PauliZ(0)) x = np.array([0.1, 0.2], requires_grad=True) expected = qml.jacobian(qml.grad(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(expected, hessian) @pytest.mark.filterwarnings("ignore:Output seems independent of input.") def test_no_gate_with_impact(self): """Test that the correct hessian is calculated for a QNode without any operators that have an impact on the QNode output.""" dev = qml.device("default.qubit", wires=3) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x[0], wires=2) qml.RX(x[1], wires=1) return qml.expval(qml.PauliZ(0)) x = np.array([0.1, 0.2], requires_grad=True) expected = qml.jacobian(qml.grad(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(expected, hessian) def test_single_multi_term_gate(self): """Test that the correct hessian is calculated for a QNode with single operation with more than two terms in the shift rule, parameter frequencies defined, and single expectation value output (0d -> 0d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.Hadamard(wires=1) qml.CRX(x, wires=[1, 0]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) x = np.array(0.1, requires_grad=True) expected = qml.jacobian(qml.grad(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(expected, hessian) def test_single_gate_custom_recipe(self): """Test that the correct hessian is calculated for a QNode with single operation with more than two terms in the shift rule, parameter frequencies defined, and single expectation value output (0d -> 0d)""" dev = qml.device("default.qubit", wires=2) c, s = qml.gradients.generate_shift_rule((0.5, 1)).T recipe = list(zip(c, np.ones_like(c), s)) # pylint: disable=too-few-public-methods class DummyOp(qml.CRX): """A custom variant of qml.CRX with a specific gradient recipe.""" grad_recipe = (recipe,) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.Hadamard(wires=1) DummyOp(x, wires=[1, 0]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) x = np.array(0.1, requires_grad=True) expected = qml.jacobian(qml.grad(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(expected, hessian) def test_single_two_term_gate_vector_output(self): """Test that the correct hessian is calculated for a QNode with single RY operator and probabilies as output (0d -> 1d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RY(x, wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0, 1]) x = np.array(0.1, requires_grad=True) expected = qml.jacobian(qml.jacobian(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(expected, hessian) def test_multiple_two_term_gates(self): """Test that the correct hessian is calculated for a QNode with two rotation operators and one expectation value output (1d -> 0d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) qml.CNOT(wires=[0, 1]) qml.RY(x[2], wires=1) return qml.expval(qml.PauliZ(1)) x = np.array([0.1, 0.2, -0.8], requires_grad=True) expected = qml.jacobian(qml.jacobian(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(expected, hessian) def test_multiple_two_term_gates_vector_output(self): """Test that the correct hessian is calculated for a QNode with two rotation operators and probabilities output (1d -> 1d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) qml.CNOT(wires=[0, 1]) qml.RY(x[2], wires=1) return qml.probs(wires=1) x = np.array([0.1, 0.2, -0.8], requires_grad=True) expected = qml.jacobian(qml.jacobian(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(qml.math.transpose(expected, (2, 1, 0)), hessian) def test_quantum_hessian_shape_vector_input_vector_output(self): """Test that the purely "quantum" hessian has the correct shape (1d -> 1d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) qml.CNOT(wires=[0, 1]) qml.RZ(x[2], wires=1) qml.Rot(x[0], x[1], x[2], wires=1) return qml.probs(wires=[0, 1]) x = np.array([0.1, 0.2, 0.3], requires_grad=True) shape = (3, 3, 4) # (num_args, num_args, num_output_vals) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert qml.math.shape(hessian) == shape def test_multiple_two_term_gates_reusing_parameters(self): """Test that the correct hessian is calculated when reusing parameters (1d -> 1d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) qml.CNOT(wires=[0, 1]) qml.RZ(x[2], wires=1) qml.Rot(x[0], x[1], x[2], wires=1) return qml.probs(wires=[0, 1]) x = np.array([0.1, 0.2, 0.3], requires_grad=True) expected = qml.jacobian(qml.jacobian(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(qml.math.transpose(expected, (2, 1, 0)), hessian) def test_multiple_two_term_gates_classical_processing(self): """Test that the correct hessian is calculated when manipulating parameters (1d -> 1d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x[0] + x[1] + x[2], wires=0) qml.RY(x[1] - x[0] + 3 * x[2], wires=0) qml.CNOT(wires=[0, 1]) qml.RZ(x[2] / x[0] - x[1], wires=1) return qml.probs(wires=[0, 1]) x = np.array([0.1, 0.2, 0.3], requires_grad=True) expected = qml.jacobian(qml.jacobian(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(qml.math.transpose(expected, (2, 1, 0)), hessian) def test_multiple_two_term_gates_matrix_output(self): """Test that the correct hessian is calculated for higher dimensional QNode outputs (1d -> 2d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2) def circuit(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=0), qml.probs(wires=1) def cost(x): return qml.math.stack(circuit(x)) x = np.ones([2], requires_grad=True) expected = qml.jacobian(qml.jacobian(cost))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(qml.math.transpose(expected, (0, 3, 2, 1)), hessian) def test_multiple_two_term_gates_matrix_input(self): """Test that the correct hessian is calculated for higher dimensional cl. jacobians (2d -> 2d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2) def circuit(x): qml.RX(x[0, 0], wires=0) qml.RY(x[0, 1], wires=0) qml.CNOT(wires=[0, 1]) qml.RX(x[0, 2], wires=0) qml.RY(x[0, 0], wires=0) return qml.probs(wires=0), qml.probs(wires=1) def cost(x): return qml.math.stack(circuit(x)) x = np.ones([1, 3], requires_grad=True) expected = qml.jacobian(qml.jacobian(cost))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(qml.math.transpose(expected, (0, 2, 3, 4, 5, 1)), hessian) def test_multiple_qnode_arguments_scalar(self): """Test that the correct Hessian is calculated with multiple QNode arguments (0D->1D)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2) def circuit(x, y, z): qml.RX(x, wires=0) qml.RY(y, wires=1) qml.SingleExcitation(z, wires=[1, 0]) qml.RY(y, wires=0) qml.RX(x, wires=0) return qml.probs(wires=[0, 1]) def wrapper(X): return circuit(*X) x = np.array(0.1, requires_grad=True) y = np.array(0.5, requires_grad=True) z = np.array(0.3, requires_grad=True) X = qml.math.stack([x, y, z]) expected = qml.jacobian(qml.jacobian(wrapper))(X) expected = tuple(expected[:, i, i] for i in range(3)) circuit.interface = "autograd" hessian = qml.gradients.param_shift_hessian(circuit)(x, y, z) assert np.allclose(expected, hessian) def test_multiple_qnode_arguments_vector(self): """Test that the correct Hessian is calculated with multiple QNode arguments (1D->1D)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2) def circuit(x, y, z): qml.RX(x[0], wires=1) qml.RY(y[0], wires=0) qml.CRZ(z[0] + z[1], wires=[1, 0]) qml.RY(y[1], wires=1) qml.RX(x[1], wires=0) return qml.probs(wires=[0, 1]) def wrapper(X): return circuit(*X) x = np.array([0.1, 0.3], requires_grad=True) y = np.array([0.5, 0.7], requires_grad=True) z = np.array([0.3, 0.2], requires_grad=True) X = qml.math.stack([x, y, z]) expected = qml.jacobian(qml.jacobian(wrapper))(X) expected = tuple(expected[:, i, :, i] for i in range(3)) circuit.interface = "autograd" hessian = qml.gradients.param_shift_hessian(circuit)(x, y, z) assert np.allclose(qml.math.transpose(expected, (0, 2, 3, 1)), hessian) def test_multiple_qnode_arguments_matrix(self): """Test that the correct Hessian is calculated with multiple QNode arguments (2D->1D)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x, y, z): qml.RX(x[0, 0], wires=0) qml.RY(y[0, 0], wires=1) qml.CRZ(z[0, 0] + z[1, 1], wires=[1, 0]) qml.RY(y[1, 0], wires=0) qml.RX(x[1, 0], wires=1) return qml.probs(wires=[0, 1]) def wrapper(X): return circuit(*X) x = np.array([[0.1, 0.3], [0.2, 0.4]], requires_grad=True) y = np.array([[0.5, 0.7], [0.2, 0.4]], requires_grad=True) z = np.array([[0.3, 0.2], [0.2, 0.4]], requires_grad=True) X = qml.math.stack([x, y, z]) expected = qml.jacobian(qml.jacobian(wrapper))(X) expected = tuple(expected[:, i, :, :, i] for i in range(3)) circuit.interface = "autograd" hessian = qml.gradients.param_shift_hessian(circuit)(x, y, z) assert np.allclose(qml.math.transpose(expected, (0, 2, 3, 4, 5, 1)), hessian) def test_multiple_qnode_arguments_mixed(self): """Test that the correct Hessian is calculated with multiple mixed-shape QNode arguments""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2) def circuit(x, y, z): qml.RX(x, wires=0) qml.RY(z[0] + z[1], wires=0) qml.CNOT(wires=[0, 1]) qml.RX(y[1, 0], wires=0) qml.CRY(y[0, 1], wires=[0, 1]) return qml.probs(wires=0), qml.probs(wires=1) def cost(x, y, z): return qml.math.stack(circuit(x, y, z)) x = np.array(0.1, requires_grad=True) y = np.array([[0.5, 0.6], [0.2, 0.1]], requires_grad=True) z = np.array([0.3, 0.4], requires_grad=True) expected = tuple( qml.jacobian(qml.jacobian(cost, argnum=i), argnum=i)(x, y, z) for i in range(3) ) hessian = qml.gradients.param_shift_hessian(circuit)(x, y, z) assert np.allclose(expected[0], hessian[0]) assert np.allclose(qml.math.transpose(expected[1], (0, 2, 3, 4, 5, 1)), hessian[1]) assert np.allclose(qml.math.transpose(expected[2], (0, 2, 3, 1)), hessian[2]) def test_with_channel(self): """Test that the Hessian is correctly computed for circuits that contain quantum channels.""" dev = qml.device("default.mixed", wires=2) @qml.qnode(dev, max_diff=2) def circuit(x): qml.RX(x[1], wires=0) qml.RY(x[0], wires=0) qml.DepolarizingChannel(x[2], wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0, 1]) x = np.array([-0.4, 0.9, 0.1], requires_grad=True) expected = qml.jacobian(qml.jacobian(circuit))(x) hessian = qml.gradients.param_shift_hessian(circuit)(x) assert np.allclose(qml.math.transpose(expected, (2, 1, 0)), hessian) def test_hessian_transform_is_differentiable(self): """Test that the 3rd derivate can be calculated via auto-differentiation (1d -> 1d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=3) def circuit(x): qml.RX(x[1], wires=0) qml.RY(x[0], wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0, 1]) x = np.array([0.1, 0.2], requires_grad=True) expected = qml.jacobian(qml.jacobian(qml.jacobian(circuit)))(x) def cost_fn(x): hess = qml.gradients.param_shift_hessian(circuit)(x) hess = qml.math.stack([qml.math.stack(row) for row in hess]) return hess derivative = qml.jacobian(cost_fn)(x) assert np.allclose(qml.math.transpose(expected, (1, 2, 0, 3)), derivative) # Some bounds on the efficiency (device executions) of the hessian for 2-term shift rules: # - < jacobian(jacobian()) # - <= 2^d * (m+d-1)C(d) see arXiv:2008.06517 p. 4 # - <= 3^m see arXiv:2008.06517 p. 4 # here d=2 is the derivative order, m is the number of variational parameters (w.r.t. gate args) def test_fewer_device_invocations_scalar_input(self): """Test that the hessian invokes less hardware executions than double differentiation (0d -> 0d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x, wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(1)) x = np.array(0.1, requires_grad=True) with qml.Tracker(dev) as tracker: hessian = qml.gradients.param_shift_hessian(circuit)(x) hessian_qruns = tracker.totals["executions"] expected = qml.jacobian(qml.jacobian(circuit))(x) jacobian_qruns = tracker.totals["executions"] - hessian_qruns assert np.allclose(hessian, expected) assert hessian_qruns < jacobian_qruns assert hessian_qruns <= 2**2 * 1 # 1 = (1+2-1)C(2) assert hessian_qruns <= 3**1 def test_fewer_device_invocations_vector_input(self): """Test that the hessian invokes less hardware executions than double differentiation (1d -> 0d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x[0], wires=0) qml.CNOT(wires=[0, 1]) qml.RY(x[1], wires=0) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) x = np.array([0.1, 0.2], requires_grad=True) with qml.Tracker(dev) as tracker: hessian = qml.gradients.param_shift_hessian(circuit)(x) hessian_qruns = tracker.totals["executions"] expected = qml.jacobian(qml.jacobian(circuit))(x) jacobian_qruns = tracker.totals["executions"] - hessian_qruns assert np.allclose(hessian, expected) assert hessian_qruns < jacobian_qruns assert hessian_qruns <= 2**2 * 3 # 3 = (2+2-1)C(2) assert hessian_qruns <= 3**2 @pytest.mark.xfail(reason="Update tracker for new return types") def test_fewer_device_invocations_vector_output(self): """Test that the hessian invokes less hardware executions than double differentiation (1d -> 1d)""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x[0], wires=0) qml.CNOT(wires=[0, 1]) qml.RY(x[1], wires=0) qml.RZ(x[2], wires=1) return qml.probs(wires=[0, 1]) x = np.array([0.1, 0.2, 0.3], requires_grad=True) with qml.Tracker(dev) as tracker: hessian = qml.gradients.param_shift_hessian(circuit)(x) hessian_qruns = tracker.totals["executions"] expected = qml.jacobian(qml.jacobian(circuit))(x) jacobian_qruns = tracker.totals["executions"] - hessian_qruns assert np.allclose(hessian, expected) assert hessian_qruns < jacobian_qruns assert hessian_qruns <= 2**2 * 6 # 6 = (3+2-1)C(2) assert hessian_qruns <= 3**3 def test_error_unsupported_operation_without_argnum(self): """Test that the correct error is thrown for unsupported operations when no argnum is given.""" dev = qml.device("default.qubit", wires=2) # pylint: disable=too-few-public-methods class DummyOp(qml.CRZ): """A custom variant of qml.CRZ with grad_method "F".""" grad_method = "F" @qml.qnode(dev, max_diff=2, diff_method="parameter-shift") def circuit(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) DummyOp(x[2], wires=[0, 1]) return qml.probs(wires=1) x = np.array([0.1, 0.2, 0.3], requires_grad=True) with pytest.raises( ValueError, match=r"The analytic gradient method cannot be used with the parameter\(s\)", ): qml.gradients.param_shift_hessian(circuit)(x) def test_error_unsupported_variance_measurement(self): """Test that the correct error is thrown for variance measurements""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2, diff_method="parameter-shift") def circuit(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) qml.CRZ(x[2], wires=[0, 1]) return qml.var(qml.PauliZ(1)) x = np.array([0.1, 0.2, 0.3], requires_grad=True) with pytest.raises( ValueError, match="Computing the Hessian of circuits that return variances is currently not supported.", ): qml.gradients.param_shift_hessian(circuit)(x) def test_error_unsupported_state_measurement(self): """Test that the correct error is thrown for state measurements""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2, diff_method="parameter-shift") def circuit(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) qml.CRZ(x[2], wires=[0, 1]) return qml.state() x = np.array([0.1, 0.2, 0.3], requires_grad=True) with pytest.raises( ValueError, match="Computing the Hessian of circuits that return the state is not supported.", ): qml.gradients.param_shift_hessian(circuit)(x) def test_no_error_nondifferentiable_unsupported_operation(self): """Test that no error is thrown for operations that are not marked differentiable""" # pylint: disable=too-few-public-methods class DummyOp(qml.CRZ): """A custom variant of qml.CRZ with grad_method "F".""" grad_method = "F" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2, diff_method="parameter-shift") def circuit(x, y, z): qml.RX(x, wires=0) qml.RY(y, wires=0) DummyOp(z, wires=[0, 1]) return qml.probs(wires=1) x = np.array(0.1, requires_grad=True) y = np.array(0.2, requires_grad=True) z = np.array(0.3, requires_grad=False) qml.gradients.param_shift_hessian(circuit)(x, y, z) @pytest.mark.autograd def test_no_trainable_params_qnode_autograd(self): """Test that the correct ouput and warning is generated in the absence of any trainable parameters""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface="autograd", diff_method="parameter-shift") def circuit(weights): qml.RX(weights[0], wires=0) qml.RY(weights[1], wires=0) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) weights = [0.1, 0.2] with pytest.raises(qml.QuantumFunctionError, match="No trainable parameters."): qml.gradients.param_shift_hessian(circuit)(weights) @pytest.mark.torch def test_no_trainable_params_qnode_torch(self): """Test that the correct ouput and warning is generated in the absence of any trainable parameters""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface="torch", diff_method="parameter-shift") def circuit(weights): qml.RX(weights[0], wires=0) qml.RY(weights[1], wires=0) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) weights = [0.1, 0.2] with pytest.raises(qml.QuantumFunctionError, match="No trainable parameters."): qml.gradients.param_shift_hessian(circuit)(weights) @pytest.mark.tf def test_no_trainable_params_qnode_tf(self): """Test that the correct ouput and warning is generated in the absence of any trainable parameters""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface="tf", diff_method="parameter-shift") def circuit(weights): qml.RX(weights[0], wires=0) qml.RY(weights[1], wires=0) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) weights = [0.1, 0.2] with pytest.raises(qml.QuantumFunctionError, match="No trainable parameters."): qml.gradients.param_shift_hessian(circuit)(weights) @pytest.mark.jax def test_no_trainable_params_qnode_jax(self): """Test that the correct ouput and warning is generated in the absence of any trainable parameters""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface="jax", diff_method="parameter-shift") def circuit(weights): qml.RX(weights[0], wires=0) qml.RY(weights[1], wires=0) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) weights = [0.1, 0.2] with pytest.raises(qml.QuantumFunctionError, match="No trainable parameters."): qml.gradients.param_shift_hessian(circuit)(weights) def test_all_zero_diff_methods(self): """Test that the transform works correctly when the diff method for every parameter is identified to be 0, and that no tapes were generated.""" dev = qml.device("default.qubit", wires=4) @qml.qnode(dev, diff_method="parameter-shift") def circuit(params): qml.Rot(*params, wires=0) return qml.probs([2, 3]) params = np.array([0.5, 0.5, 0.5], requires_grad=True) circuit(params) result = qml.gradients.param_shift_hessian(circuit)(params) assert np.allclose(result, np.zeros((3, 3, 4)), atol=0, rtol=0) tapes, _ = qml.gradients.param_shift_hessian(circuit.qtape) assert tapes == [] @pytest.mark.xfail(reason="Update tracker for new return types") def test_f0_argument(self): """Test that we can provide the results of a QNode to save on quantum invocations""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2) def circuit(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=1) x = np.array([0.1, 0.2], requires_grad=True) res = circuit(x) with qml.Tracker(dev) as tracker: hessian1 = qml.gradients.param_shift_hessian(circuit, f0=res)(x) qruns1 = tracker.totals["executions"] hessian2 = qml.gradients.param_shift_hessian(circuit)(x) qruns2 = tracker.totals["executions"] - qruns1 assert np.allclose(hessian1, hessian2) assert qruns1 < qruns2 def test_output_shape_matches_qnode(self): """Test that the transform output shape matches that of the QNode.""" dev = qml.device("default.qubit", wires=4) def cost1(x): qml.Rot(*x, wires=0) return qml.expval(qml.PauliZ(0)) def cost2(x): qml.Rot(*x, wires=0) return [qml.expval(qml.PauliZ(0))] def cost3(x): qml.Rot(*x, wires=0) return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))] def cost4(x): qml.Rot(*x, wires=0) return qml.probs([0, 1]) def cost5(x): qml.Rot(*x, wires=0) return [qml.probs([0, 1])] def cost6(x): qml.Rot(*x, wires=0) return [qml.probs([0, 1]), qml.probs([2, 3])] x = np.random.rand(3) circuits = [qml.QNode(cost, dev) for cost in (cost1, cost2, cost3, cost4, cost5, cost6)] transform = [qml.math.shape(qml.gradients.param_shift_hessian(c)(x)) for c in circuits] expected = [(3, 3), (1, 3, 3), (2, 3, 3), (3, 3, 4), (1, 3, 3, 4), (2, 3, 3, 4)] assert all(t == e for t, e in zip(transform, expected)) class TestParamShiftHessianWithKwargs: """Test the parameter-shift Hessian computation when manually providing parameter shifts or `argnum`.""" @pytest.mark.parametrize( "diagonal_shifts", ( [(np.pi / 3,), (np.pi / 2,)], [(np.pi / 3,), None], ), ) def test_with_diagonal_shifts(self, diagonal_shifts): """Test that diagonal shifts are used and yield the correct Hessian.""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2) def circuit(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=0) x = np.array([0.6, -0.2], requires_grad=True) expected = qml.math.transpose(qml.jacobian(qml.jacobian(circuit))(x), (1, 2, 0)) circuit(x) tapes, fn = qml.gradients.param_shift_hessian( circuit.qtape, diagonal_shifts=diagonal_shifts ) # We expect the following tapes: # - 1 without shifts (used for second diagonal), # - 2 for first diagonal, # - 4 for off-diagonal, # - 1 for second diagonal. assert len(tapes) == 1 + 2 + 4 + 1 assert np.allclose(tapes[0].get_parameters(), x) assert np.allclose(tapes[1].get_parameters(), x + np.array([2 * np.pi / 3, 0.0])) assert np.allclose(tapes[2].get_parameters(), x + np.array([-2 * np.pi / 3, 0.0])) assert np.allclose(tapes[-1].get_parameters(), x + np.array([0.0, -np.pi])) expected_shifts = np.array([[1, 1], [1, -1], [-1, 1], [-1, -1]]) * (np.pi / 2) for _tape, exp_shift in zip(tapes[3:-1], expected_shifts): assert np.allclose(_tape.get_parameters(), x + exp_shift) hessian = fn(qml.execute(tapes, dev, gradient_fn=qml.gradients.param_shift)) assert np.allclose(expected, hessian) @pytest.mark.parametrize( "off_diagonal_shifts", ( [(np.pi / 2,), (0.3, 0.6)], [None, (0.3, 0.6)], ), ) def test_with_offdiagonal_shifts(self, off_diagonal_shifts): """Test that off-diagonal shifts are used and yield the correct Hessian.""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2) def circuit(x): qml.RX(x[0], wires=0) qml.CRY(x[1], wires=[0, 1]) qml.CNOT(wires=[0, 1]) return qml.probs(wires=0) x = np.array([0.6, -0.2], requires_grad=True) expected = qml.math.transpose(qml.jacobian(qml.jacobian(circuit))(x), (1, 2, 0)) circuit(x) tapes, fn = qml.gradients.param_shift_hessian( circuit.qtape, off_diagonal_shifts=off_diagonal_shifts ) # We expect the following tapes: # - 1 without shifts (used for diagonals), # - 1 for first diagonal, # - 8 for off-diagonal, # - 3 for second diagonal. assert len(tapes) == 1 + 1 + 8 + 3 assert np.allclose(tapes[0].get_parameters(), x) # Check that the vanilla diagonal rule is used for the first diagonal entry assert np.allclose(tapes[1].get_parameters(), x + np.array([-np.pi, 0.0])) # Check that the provided off-diagonal shift values are used expected_shifts = np.array( [[1, 1], [1, -1], [1, 2], [1, -2], [-1, 1], [-1, -1], [-1, 2], [-1, -2]] ) * np.array([[np.pi / 2, 0.3]]) for _tape, exp_shift in zip(tapes[2:10], expected_shifts): assert np.allclose(_tape.get_parameters(), x + exp_shift) # Check that the vanilla diagonal rule is used for the second diagonal entry shift_order = [1, -1, -2] for mult, _tape in zip(shift_order, tapes[10:]): assert np.allclose(_tape.get_parameters(), x + np.array([0.0, np.pi * mult])) hessian = fn(qml.execute(tapes, dev, gradient_fn=qml.gradients.param_shift)) assert np.allclose(expected, hessian) @pytest.mark.parametrize("argnum", [(0,), (1,), (0, 1)]) def test_with_1d_argnum(self, argnum): """Test that providing an argnum to indicate differentiable parameters works.""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2, diff_method="parameter-shift") def circuit(x, y): qml.RX(x, wires=0) qml.CRY(y, wires=[0, 1]) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0, 1]) def wrapper(X): return circuit(*X) X = np.array([0.6, -0.2], requires_grad=True) expected = qml.jacobian(qml.jacobian(wrapper))(X) # Extract "diagonal" across arguments expected = np.array([np.diag(sub) for i, sub in enumerate(expected)]) # Set non-argnum argument entries to 0 for i in range(len(X)): if i not in argnum: expected[:, i] = 0.0 hessian = qml.gradients.param_shift_hessian(circuit, argnum=argnum)(*X) assert np.allclose(hessian, expected.T) @pytest.mark.parametrize( "argnum", [ qml.math.eye(3, dtype=bool), qml.math.array([[True, False, False], [False, False, True], [False, True, True]]), qml.math.array([[False, False, True], [False, False, False], [True, False, False]]), ], ) def test_with_2d_argnum(self, argnum): """Test that providing an argnum to indicated differentiable parameters works.""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2) def circuit(par): qml.RX(par[0], wires=0) qml.CRY(par[1], wires=[0, 1]) qml.CNOT(wires=[0, 1]) qml.CRY(par[2], wires=[0, 1]) return qml.probs(wires=[0, 1]) par = np.array([0.6, -0.2, 0.8], requires_grad=True) expected = qml.jacobian(qml.jacobian(circuit))(par) # Set non-argnum argument entries to 0 expected = qml.math.transpose( expected * qml.math.array(argnum, dtype=float)[None], (1, 2, 0) ) hessian = qml.gradients.param_shift_hessian(circuit, argnum=argnum)(par) assert np.allclose(hessian, expected) @pytest.mark.parametrize("argnum", [(0,), (1,), (0, 1)]) def test_with_argnum_and_shifts(self, argnum): """Test that providing an argnum to indicated differentiable parameters works.""" diagonal_shifts = [(0.1,), (0.9, 1.1)] off_diagonal_shifts = [(0.4,), (0.3, 2.1)] dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2, diff_method="parameter-shift") def circuit(x, y): qml.RX(x, wires=0) qml.CRY(y, wires=[0, 1]) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0, 1]) def wrapper(X): return circuit(*X) X = np.array([0.6, -0.2], requires_grad=True) expected = qml.jacobian(qml.jacobian(wrapper))(X) # Extract "diagonal" across arguments expected = np.array([np.diag(sub) for i, sub in enumerate(expected)]) # Set non-argnum argument entries to 0 for i in range(len(X)): if i not in argnum: expected[:, i] = 0.0 d_shifts = [diagonal_shifts[arg] for arg in argnum] od_shifts = [off_diagonal_shifts[arg] for arg in argnum if len(argnum) > 1] hessian = qml.gradients.param_shift_hessian( circuit, argnum=argnum, diagonal_shifts=d_shifts, off_diagonal_shifts=od_shifts )(*X) assert np.allclose(hessian, expected.T) class TestInterfaces: """Test the param_shift_hessian method on different interfaces""" @pytest.mark.skip("Requires Torch integration for new return types") @pytest.mark.torch def test_hessian_transform_with_torch(self): """Test that the Hessian transform can be used with Torch (1d -> 1d)""" import torch dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(x): qml.RX(x[1], wires=0) qml.RY(x[0], wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0, 1]) x_np = np.array([0.1, 0.2], requires_grad=True) x_torch = torch.tensor([0.1, 0.2], dtype=torch.float64, requires_grad=True) expected = qml.jacobian(qml.jacobian(circuit))(x_np) circuit.interface = "torch" hess = qml.gradients.param_shift_hessian(circuit)(x_torch)[0] assert np.allclose(expected, hess.detach()) @pytest.mark.skip("Requires Torch integration for new return types") @pytest.mark.torch def test_hessian_transform_is_differentiable_torch(self): """Test that the 3rd derivate can be calculated via auto-differentiation in Torch (1d -> 1d)""" import torch dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method="parameter-shift", max_diff=3) def circuit(x): qml.RX(x[1], wires=0) qml.RY(x[0], wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0, 1]) x = np.array([0.1, 0.2], requires_grad=True) x_torch = torch.tensor([0.1, 0.2], dtype=torch.float64, requires_grad=True) expected = qml.jacobian(qml.jacobian(qml.jacobian(circuit)))(x) circuit.interface = "torch" jacobian_fn = torch.autograd.functional.jacobian torch_deriv = jacobian_fn(qml.gradients.param_shift_hessian(circuit), x_torch)[0] assert np.allclose(expected, torch_deriv) @pytest.mark.jax @pytest.mark.slow def test_hessian_transform_with_jax(self): """Test that the Hessian transform can be used with JAX (1d -> 1d)""" import jax dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2) def circuit(x): qml.RX(x[1], wires=0) qml.RY(x[0], wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0, 1]) x_np = np.array([0.1, 0.2], requires_grad=True) x_jax = jax.numpy.array([0.1, 0.2]) expected = qml.jacobian(qml.jacobian(circuit))(x_np) circuit.interface = "jax" hess = qml.gradients.param_shift_hessian(circuit, argnums=[0])(x_jax) assert np.allclose(qml.math.transpose(expected, (1, 2, 0)), hess) @pytest.mark.jax @pytest.mark.slow def test_hessian_transform_is_differentiable_jax(self): """Test that the 3rd derivate can be calculated via auto-differentiation in JAX (1d -> 1d)""" import jax dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=3) def circuit(x): qml.RX(x[1], wires=0) qml.RY(x[0], wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0, 1]) x = np.array([0.1, 0.2], requires_grad=True) x_jax = jax.numpy.array([0.1, 0.2]) expected = qml.jacobian(qml.jacobian(qml.jacobian(circuit)))(x) def cost_fn(x): hess = qml.gradients.param_shift_hessian(circuit)(x) hess = qml.math.stack([qml.math.stack(row) for row in hess]) return hess circuit.interface = "jax" jax_deriv = jax.jacobian(cost_fn)(x_jax) assert np.allclose(qml.math.transpose(expected, (1, 2, 0, 3)), jax_deriv) @pytest.mark.tf @pytest.mark.slow def test_hessian_transform_with_tensorflow(self): """Test that the Hessian transform can be used with TensorFlow (1d -> 1d)""" import tensorflow as tf dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=2) def circuit(x): qml.RX(x[1], wires=0) qml.RY(x[0], wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0, 1]) x_np = np.array([0.1, 0.2], requires_grad=True) x_tf = tf.Variable([0.1, 0.2], dtype=tf.float64) expected = qml.jacobian(qml.jacobian(circuit))(x_np) circuit.interface = "tf" with tf.GradientTape(): hess = qml.gradients.param_shift_hessian(circuit)(x_tf) assert np.allclose(qml.math.transpose(expected, (1, 2, 0)), hess) @pytest.mark.tf @pytest.mark.slow def test_hessian_transform_is_differentiable_tensorflow(self): """Test that the 3rd derivate can be calculated via auto-differentiation in Tensorflow (1d -> 1d)""" import tensorflow as tf dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, max_diff=3) def circuit(x): qml.RX(x[1], wires=0) qml.RY(x[0], wires=0) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0, 1]) x = np.array([0.1, 0.2], requires_grad=True) x_tf = tf.Variable([0.1, 0.2], dtype=tf.float64) expected = qml.jacobian(qml.jacobian(qml.jacobian(circuit)))(x) circuit.interface = "tf" with tf.GradientTape() as tf_tape: hessian = qml.gradients.param_shift_hessian(circuit)(x_tf)[0] hessian = qml.math.stack([qml.math.stack(row) for row in hessian]) tensorflow_deriv = tf_tape.jacobian(hessian, x_tf) assert np.allclose(qml.math.transpose(expected, (1, 2, 0, 3)), tensorflow_deriv)
pennylane/tests/gradients/parameter_shift/test_parameter_shift_hessian.py/0
{ "file_path": "pennylane/tests/gradients/parameter_shift/test_parameter_shift_hessian.py", "repo_id": "pennylane", "token_count": 36036 }
80
# Copyright 2022 Xanadu Quantum Technologies Inc. # 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. """Integration tests for using the TF interface with shot vectors and with a QNode""" # pylint: disable=too-many-arguments import pytest import pennylane as qml from pennylane import numpy as np from pennylane import qnode pytestmark = pytest.mark.tf tf = pytest.importorskip("tensorflow") shots_and_num_copies = [(((5, 2), 1, 10), 4), ((1, 10, (5, 2)), 4)] shots_and_num_copies_hess = [((10, (5, 1)), 2)] qubit_device_and_diff_method = [ ["default.qubit.legacy", "finite-diff", {"h": 10e-2}], ["default.qubit.legacy", "parameter-shift", {}], ["default.qubit.legacy", "spsa", {"h": 10e-2, "num_directions": 20}], ] TOLS = { "finite-diff": 0.3, "parameter-shift": 2e-2, "spsa": 0.5, } interface_and_qubit_device_and_diff_method = [ ["tf"] + inner_list for inner_list in qubit_device_and_diff_method ] @pytest.mark.parametrize("shots,num_copies", shots_and_num_copies) @pytest.mark.parametrize( "interface,dev_name,diff_method,gradient_kwargs", interface_and_qubit_device_and_diff_method ) class TestReturnWithShotVectors: """Class to test the shape of the Grad/Jacobian/Hessian with different return types and shot vectors.""" def test_jac_single_measurement_param( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """For one measurement and one param, the gradient is a float.""" dev = qml.device(dev_name, wires=1, shots=shots) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(a): qml.RY(a, wires=0) qml.RX(0.2, wires=0) return qml.expval(qml.PauliZ(0)) a = tf.Variable(0.1) with tf.GradientTape() as tape: res = circuit(a) res = qml.math.stack(res) jac = tape.jacobian(res, a) assert isinstance(jac, tf.Tensor) assert jac.shape == (num_copies,) def test_jac_single_measurement_multiple_param( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """For one measurement and multiple param, the gradient is a tuple of arrays.""" dev = qml.device(dev_name, wires=1, shots=shots) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=0) return qml.expval(qml.PauliZ(0)) a = tf.Variable(0.1) b = tf.Variable(0.2) with tf.GradientTape() as tape: res = circuit(a, b) res = qml.math.stack(res) jac = tape.jacobian(res, (a, b)) assert isinstance(jac, tuple) assert len(jac) == 2 for j in jac: assert isinstance(j, tf.Tensor) assert j.shape == (num_copies,) def test_jacobian_single_measurement_multiple_param_array( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """For one measurement and multiple param as a single array params, the gradient is an array.""" dev = qml.device(dev_name, wires=1, shots=shots) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(a): qml.RY(a[0], wires=0) qml.RX(a[1], wires=0) return qml.expval(qml.PauliZ(0)) a = tf.Variable([0.1, 0.2]) with tf.GradientTape() as tape: res = circuit(a) res = qml.math.stack(res) jac = tape.jacobian(res, a) assert isinstance(jac, tf.Tensor) assert jac.shape == (num_copies, 2) def test_jacobian_single_measurement_param_probs( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """For a multi dimensional measurement (probs), check that a single array is returned with the correct dimension""" dev = qml.device(dev_name, wires=2, shots=shots) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(a): qml.RY(a, wires=0) qml.RX(0.2, wires=0) return qml.probs(wires=[0, 1]) a = tf.Variable(0.1) with tf.GradientTape() as tape: res = circuit(a) res = qml.math.stack(res) jac = tape.jacobian(res, a) assert isinstance(jac, tf.Tensor) assert jac.shape == (num_copies, 4) def test_jacobian_single_measurement_probs_multiple_param( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """For a multi dimensional measurement (probs), check that a single tuple is returned containing arrays with the correct dimension""" dev = qml.device(dev_name, wires=2, shots=shots) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=0) return qml.probs(wires=[0, 1]) a = tf.Variable(0.1) b = tf.Variable(0.2) with tf.GradientTape() as tape: res = circuit(a, b) res = qml.math.stack(res) jac = tape.jacobian(res, (a, b)) assert isinstance(jac, tuple) assert len(jac) == 2 for j in jac: assert isinstance(j, tf.Tensor) assert j.shape == (num_copies, 4) def test_jacobian_single_measurement_probs_multiple_param_single_array( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """For a multi dimensional measurement (probs), check that a single tuple is returned containing arrays with the correct dimension""" dev = qml.device(dev_name, wires=2, shots=shots) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(a): qml.RY(a[0], wires=0) qml.RX(a[1], wires=0) return qml.probs(wires=[0, 1]) a = tf.Variable([0.1, 0.2]) with tf.GradientTape() as tape: res = circuit(a) res = qml.math.stack(res) jac = tape.jacobian(res, a) assert isinstance(jac, tf.Tensor) assert jac.shape == (num_copies, 4, 2) def test_jacobian_expval_expval_multiple_params( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """The gradient of multiple measurements with multiple params return a tuple of arrays.""" dev = qml.device(dev_name, wires=2, shots=shots) par_0 = tf.Variable(0.1) par_1 = tf.Variable(0.2) @qnode(dev, diff_method=diff_method, interface=interface, max_diff=1, **gradient_kwargs) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)), qml.expval(qml.PauliZ(0)) with tf.GradientTape() as tape: res = circuit(par_0, par_1) res = qml.math.stack([qml.math.stack(r) for r in res]) jac = tape.jacobian(res, (par_0, par_1)) assert isinstance(jac, tuple) assert len(jac) == 2 for j in jac: assert isinstance(j, tf.Tensor) assert j.shape == (num_copies, 2) def test_jacobian_expval_expval_multiple_params_array( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """The jacobian of multiple measurements with a multiple params array return a single array.""" dev = qml.device(dev_name, wires=2, shots=shots) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(a): qml.RY(a[0], wires=0) qml.RX(a[1], wires=0) qml.RY(a[2], wires=0) return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)), qml.expval(qml.PauliZ(0)) a = tf.Variable([0.1, 0.2, 0.3]) with tf.GradientTape() as tape: res = circuit(a) res = qml.math.stack([qml.math.stack(r) for r in res]) jac = tape.jacobian(res, a) assert isinstance(jac, tf.Tensor) assert jac.shape == (num_copies, 2, 3) def test_jacobian_multiple_measurement_single_param( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """The jacobian of multiple measurements with a single params return an array.""" dev = qml.device(dev_name, wires=2, shots=shots) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(a): qml.RY(a, wires=0) qml.RX(0.2, wires=0) return qml.expval(qml.PauliZ(0)), qml.probs(wires=[0, 1]) a = tf.Variable(0.1) with tf.GradientTape() as tape: res = circuit(a) res = qml.math.stack([tf.experimental.numpy.hstack(r) for r in res]) jac = tape.jacobian(res, a) assert isinstance(jac, tf.Tensor) assert jac.shape == (num_copies, 5) def test_jacobian_multiple_measurement_multiple_param( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """The jacobian of multiple measurements with a multiple params return a tuple of arrays.""" dev = qml.device(dev_name, wires=2, shots=shots) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=0) return qml.expval(qml.PauliZ(0)), qml.probs(wires=[0, 1]) a = tf.Variable(0.1) b = tf.Variable(0.2) with tf.GradientTape() as tape: res = circuit(a, b) res = qml.math.stack([tf.experimental.numpy.hstack(r) for r in res]) jac = tape.jacobian(res, (a, b)) assert isinstance(jac, tuple) assert len(jac) == 2 for j in jac: assert isinstance(j, tf.Tensor) assert j.shape == (num_copies, 5) def test_jacobian_multiple_measurement_multiple_param_array( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """The jacobian of multiple measurements with a multiple params array return a single array.""" dev = qml.device(dev_name, wires=2, shots=shots) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(a): qml.RY(a[0], wires=0) qml.RX(a[1], wires=0) return qml.expval(qml.PauliZ(0)), qml.probs(wires=[0, 1]) a = tf.Variable([0.1, 0.2]) with tf.GradientTape() as tape: res = circuit(a) res = qml.math.stack([tf.experimental.numpy.hstack(r) for r in res]) jac = tape.jacobian(res, a) assert isinstance(jac, tf.Tensor) assert jac.shape == (num_copies, 5, 2) @pytest.mark.slow @pytest.mark.parametrize("shots,num_copies", shots_and_num_copies_hess) @pytest.mark.parametrize( "interface,dev_name,diff_method,gradient_kwargs", interface_and_qubit_device_and_diff_method ) class TestReturnShotVectorHessian: """Class to test the shape of the Hessian with different return types and shot vectors.""" def test_hessian_expval_multiple_params( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """The hessian of a single measurement with multiple params return a tuple of arrays.""" dev = qml.device(dev_name, wires=2, shots=shots) par_0 = tf.Variable(0.1, dtype=tf.float64) par_1 = tf.Variable(0.2, dtype=tf.float64) @qnode(dev, diff_method=diff_method, interface=interface, max_diff=2, **gradient_kwargs) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)) with tf.GradientTape() as tape1: with tf.GradientTape(persistent=True) as tape2: res = circuit(par_0, par_1) res = qml.math.stack(res) jac = tape2.jacobian(res, (par_0, par_1), experimental_use_pfor=False) jac = qml.math.stack(jac) hess = tape1.jacobian(jac, (par_0, par_1)) assert isinstance(hess, tuple) assert len(hess) == 2 for h in hess: assert isinstance(h, tf.Tensor) assert h.shape == (2, num_copies) def test_hessian_expval_multiple_param_array( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """The hessian of single measurement with a multiple params array return a single array.""" dev = qml.device(dev_name, wires=2, shots=shots) params = tf.Variable([0.1, 0.2], dtype=tf.float64) @qnode(dev, diff_method=diff_method, interface=interface, max_diff=2, **gradient_kwargs) def circuit(x): qml.RX(x[0], wires=[0]) qml.RY(x[1], wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)) with tf.GradientTape() as tape1: with tf.GradientTape(persistent=True) as tape2: res = circuit(params) res = qml.math.stack(res) jac = tape2.jacobian(res, params, experimental_use_pfor=False) hess = tape1.jacobian(jac, params) assert isinstance(hess, tf.Tensor) assert hess.shape == (num_copies, 2, 2) def test_hessian_probs_expval_multiple_params( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """The hessian of multiple measurements with multiple params return a tuple of arrays.""" dev = qml.device(dev_name, wires=2, shots=shots) par_0 = tf.Variable(0.1, dtype=tf.float64) par_1 = tf.Variable(0.2, dtype=tf.float64) @qnode(dev, diff_method=diff_method, interface=interface, max_diff=2, **gradient_kwargs) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)), qml.probs(wires=[0]) with tf.GradientTape() as tape1: with tf.GradientTape(persistent=True) as tape2: res = circuit(par_0, par_1) res = qml.math.stack([tf.experimental.numpy.hstack(r) for r in res]) jac = tape2.jacobian(res, (par_0, par_1), experimental_use_pfor=False) jac = qml.math.stack(jac) hess = tape1.jacobian(jac, (par_0, par_1)) assert isinstance(hess, tuple) assert len(hess) == 2 for h in hess: assert isinstance(h, tf.Tensor) assert h.shape == (2, num_copies, 3) def test_hessian_expval_probs_multiple_param_array( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """The hessian of multiple measurements with a multiple param array return a single array.""" dev = qml.device(dev_name, wires=2, shots=shots) params = tf.Variable([0.1, 0.2], dtype=tf.float64) @qnode(dev, diff_method=diff_method, interface=interface, max_diff=2, **gradient_kwargs) def circuit(x): qml.RX(x[0], wires=[0]) qml.RY(x[1], wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)), qml.probs(wires=[0]) with tf.GradientTape() as tape1: with tf.GradientTape(persistent=True) as tape2: res = circuit(params) res = qml.math.stack([tf.experimental.numpy.hstack(r) for r in res]) jac = tape2.jacobian(res, params, experimental_use_pfor=False) hess = tape1.jacobian(jac, params) assert isinstance(hess, tf.Tensor) assert hess.shape == (num_copies, 3, 2, 2) shots_and_num_copies = [((20000, 18000, 16000), 3), ((20000, (18000, 2)), 3)] @pytest.mark.parametrize("shots,num_copies", shots_and_num_copies) @pytest.mark.parametrize( "interface,dev_name,diff_method,gradient_kwargs", interface_and_qubit_device_and_diff_method ) class TestReturnShotVectorIntegration: """Tests for the integration of shots with the TF interface.""" def test_single_expectation_value( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """Tests correct output shape and evaluation for a tape with a single expval output""" dev = qml.device(dev_name, wires=2, shots=shots) x = tf.Variable(0.543) y = tf.Variable(-0.654) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)) with tf.GradientTape() as tape: res = circuit(x, y) res = qml.math.stack(res) all_res = tape.jacobian(res, (x, y)) assert isinstance(all_res, tuple) assert len(all_res) == 2 expected = np.array([-np.sin(y) * np.sin(x), np.cos(y) * np.cos(x)]) tol = TOLS[diff_method] for res, exp in zip(all_res, expected): assert isinstance(res, tf.Tensor) assert res.shape == (num_copies,) assert np.allclose(res, exp, atol=tol, rtol=0) def test_prob_expectation_values( self, dev_name, diff_method, gradient_kwargs, shots, num_copies, interface ): """Tests correct output shape and evaluation for a tape with prob and expval outputs""" dev = qml.device(dev_name, wires=2, shots=shots) x = tf.Variable(0.543) y = tf.Variable(-0.654) @qnode(dev, diff_method=diff_method, interface=interface, **gradient_kwargs) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)), qml.probs(wires=[0, 1]) with tf.GradientTape() as tape: res = circuit(x, y) res = qml.math.stack([tf.experimental.numpy.hstack(r) for r in res]) all_res = tape.jacobian(res, (x, y)) assert isinstance(all_res, tuple) assert len(all_res) == 2 expected = np.array( [ [ -np.sin(x), -(np.cos(y / 2) ** 2 * np.sin(x)) / 2, -(np.sin(x) * np.sin(y / 2) ** 2) / 2, (np.sin(x) * np.sin(y / 2) ** 2) / 2, (np.cos(y / 2) ** 2 * np.sin(x)) / 2, ], [ 0, -(np.cos(x / 2) ** 2 * np.sin(y)) / 2, (np.cos(x / 2) ** 2 * np.sin(y)) / 2, (np.sin(x / 2) ** 2 * np.sin(y)) / 2, -(np.sin(x / 2) ** 2 * np.sin(y)) / 2, ], ] ) tol = TOLS[diff_method] for res, exp in zip(all_res, expected): assert isinstance(res, tf.Tensor) assert res.shape == (num_copies, 5) assert np.allclose(res, exp, atol=tol, rtol=0)
pennylane/tests/interfaces/legacy_devices_integration/test_tensorflow_qnode_shot_vector_legacy.py/0
{ "file_path": "pennylane/tests/interfaces/legacy_devices_integration/test_tensorflow_qnode_shot_vector_legacy.py", "repo_id": "pennylane", "token_count": 9535 }
81
# Copyright 2022 Xanadu Quantum Technologies Inc. # 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. """Unit tests for matrix expand functions.""" # pylint: disable=too-few-public-methods,too-many-public-methods from functools import reduce import numpy as np import pytest from gate_data import CNOT, II, SWAP, I, Toffoli from scipy.sparse import csr_matrix import pennylane as qml from pennylane import numpy as pnp # Define a list of dtypes to test dtypes = ["complex64", "complex128"] ml_frameworks_list = [ "numpy", pytest.param("autograd", marks=pytest.mark.autograd), pytest.param("jax", marks=pytest.mark.jax), pytest.param("torch", marks=pytest.mark.torch), pytest.param("tensorflow", marks=pytest.mark.tf), ] Toffoli_broadcasted = np.tensordot([0.1, -4.2j], Toffoli, axes=0) CNOT_broadcasted = np.tensordot([1.4], CNOT, axes=0) I_broadcasted = I[pnp.newaxis] class TestExpandMatrix: """Tests for the expand_matrix helper function.""" base_matrix_1 = np.arange(1, 5).reshape((2, 2)) base_matrix_1_broadcasted = np.arange(1, 13).reshape((3, 2, 2)) base_matrix_2 = np.arange(1, 17).reshape((4, 4)) base_matrix_2_broadcasted = np.arange(1, 49).reshape((3, 4, 4)) def test_no_expansion(self): """Tests the case where the original matrix is not changed""" res = qml.math.expand_matrix(self.base_matrix_2, wires=[0, 2], wire_order=[0, 2]) assert np.allclose(self.base_matrix_2, res) def test_no_wire_order_returns_base_matrix(self): """Test the case where the wire_order is None it returns the original matrix""" res = qml.math.expand_matrix(self.base_matrix_2, wires=[0, 2]) assert np.allclose(self.base_matrix_2, res) def test_no_expansion_broadcasted(self): """Tests the case where the broadcasted original matrix is not changed""" res = qml.math.expand_matrix( self.base_matrix_2_broadcasted, wires=[0, 2], wire_order=[0, 2] ) assert np.allclose(self.base_matrix_2_broadcasted, res) def test_permutation(self): """Tests the case where the original matrix is permuted""" res = qml.math.expand_matrix(self.base_matrix_2, wires=[0, 2], wire_order=[2, 0]) expected = np.array([[1, 3, 2, 4], [9, 11, 10, 12], [5, 7, 6, 8], [13, 15, 14, 16]]) assert np.allclose(expected, res) def test_permutation_broadcasted(self): """Tests the case where the broadcasted original matrix is permuted""" res = qml.math.expand_matrix( self.base_matrix_2_broadcasted, wires=[0, 2], wire_order=[2, 0] ) perm = [0, 2, 1, 3] expected = self.base_matrix_2_broadcasted[:, perm][:, :, perm] assert np.allclose(expected, res) def test_expansion(self): """Tests the case where the original matrix is expanded""" res = qml.math.expand_matrix(self.base_matrix_1, wires=[2], wire_order=[0, 2]) expected = np.array([[1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 2], [0, 0, 3, 4]]) assert np.allclose(expected, res) res = qml.math.expand_matrix(self.base_matrix_1, wires=[2], wire_order=[2, 0]) expected = np.array([[1, 0, 2, 0], [0, 1, 0, 2], [3, 0, 4, 0], [0, 3, 0, 4]]) assert np.allclose(expected, res) def test_expansion_broadcasted(self): """Tests the case where the broadcasted original matrix is expanded""" res = qml.math.expand_matrix(self.base_matrix_1_broadcasted, wires=[2], wire_order=[0, 2]) expected = np.array( [ [ [1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 2], [0, 0, 3, 4], ], [ [5, 6, 0, 0], [7, 8, 0, 0], [0, 0, 5, 6], [0, 0, 7, 8], ], [ [9, 10, 0, 0], [11, 12, 0, 0], [0, 0, 9, 10], [0, 0, 11, 12], ], ] ) assert np.allclose(expected, res) res = qml.math.expand_matrix(self.base_matrix_1_broadcasted, wires=[2], wire_order=[2, 0]) expected = np.array( [ [ [1, 0, 2, 0], [0, 1, 0, 2], [3, 0, 4, 0], [0, 3, 0, 4], ], [ [5, 0, 6, 0], [0, 5, 0, 6], [7, 0, 8, 0], [0, 7, 0, 8], ], [ [9, 0, 10, 0], [0, 9, 0, 10], [11, 0, 12, 0], [0, 11, 0, 12], ], ] ) assert np.allclose(expected, res) @staticmethod def func_for_autodiff(mat): """Expand a single-qubit matrix to two qubits where the matrix acts on the latter qubit.""" return qml.math.expand_matrix(mat, wires=[2], wire_order=[0, 2]) # the entries should be mapped by func_for_autodiff via # source -> destinations # (0, 0) -> (0, 0), (2, 2) # (0, 1) -> (0, 1), (2, 3) # (1, 0) -> (1, 0), (3, 2) # (1, 1) -> (1, 1), (3, 3) # so that the expected Jacobian is 0 everywhere except for the entries # (dest, source) from the above list, where it is 1. expected_autodiff_nobatch = np.zeros((4, 4, 2, 2), dtype=float) indices = [ (0, 0, 0, 0), (2, 2, 0, 0), (0, 1, 0, 1), (2, 3, 0, 1), (1, 0, 1, 0), (3, 2, 1, 0), (1, 1, 1, 1), (3, 3, 1, 1), ] for ind in indices: expected_autodiff_nobatch[ind] = 1.0 # When using broadcasting, the expected Jacobian # of func_for_autodiff is diagonal in the dimensions 0 and 3 expected_autodiff_broadcasted = np.zeros((3, 4, 4, 3, 2, 2), dtype=float) for ind in indices: expected_autodiff_broadcasted[:, ind[0], ind[1], :, ind[2], ind[3]] = np.eye(3) expected_autodiff = [expected_autodiff_nobatch, expected_autodiff_broadcasted] @pytest.mark.autograd @pytest.mark.parametrize( "i, base_matrix", [ (0, [[0.2, 1.1], [-1.3, 1.9]]), (1, [[[0.2, 0.5], [1.2, 1.1]], [[-0.3, -0.2], [-1.3, 1.9]], [[0.2, 0.1], [0.2, 0.7]]]), ], ) def test_autograd(self, i, base_matrix, tol): """Tests differentiation in autograd by computing the Jacobian of the expanded matrix with respect to the canonical matrix.""" base_matrix = pnp.array(base_matrix, requires_grad=True) jac_fn = qml.jacobian(self.func_for_autodiff) jac = jac_fn(base_matrix) assert np.allclose(jac, self.expected_autodiff[i], atol=tol) @pytest.mark.torch @pytest.mark.parametrize( "i, base_matrix", [ (0, [[0.2, 1.1], [-1.3, 1.9]]), (1, [[[0.2, 0.5], [1.2, 1.1]], [[-0.3, -0.2], [-1.3, 1.9]], [[0.2, 0.1], [0.2, 0.7]]]), ], ) def test_torch(self, i, base_matrix, tol): """Tests differentiation in torch by computing the Jacobian of the expanded matrix with respect to the canonical matrix.""" import torch base_matrix = torch.tensor(base_matrix, requires_grad=True) jac = torch.autograd.functional.jacobian(self.func_for_autodiff, base_matrix) assert np.allclose(jac, self.expected_autodiff[i], atol=tol) @pytest.mark.jax @pytest.mark.parametrize( "i, base_matrix", [ (0, [[0.2, 1.1], [-1.3, 1.9]]), (1, [[[0.2, 0.5], [1.2, 1.1]], [[-0.3, -0.2], [-1.3, 1.9]], [[0.2, 0.1], [0.2, 0.7]]]), ], ) def test_jax(self, i, base_matrix, tol): """Tests differentiation in jax by computing the Jacobian of the expanded matrix with respect to the canonical matrix.""" import jax base_matrix = jax.numpy.array(base_matrix) jac_fn = jax.jacobian(self.func_for_autodiff) jac = jac_fn(base_matrix) assert np.allclose(jac, self.expected_autodiff[i], atol=tol) @pytest.mark.tf @pytest.mark.parametrize( "i, base_matrix", [ (0, [[0.2, 1.1], [-1.3, 1.9]]), (1, [[[0.2, 0.5], [1.2, 1.1]], [[-0.3, -0.2], [-1.3, 1.9]], [[0.2, 0.1], [0.2, 0.7]]]), ], ) def test_tf(self, i, base_matrix, tol): """Tests differentiation in TensorFlow by computing the Jacobian of the expanded matrix with respect to the canonical matrix.""" import tensorflow as tf base_matrix = tf.Variable(base_matrix) with tf.GradientTape() as tape: res = self.func_for_autodiff(base_matrix) jac = tape.jacobian(res, base_matrix) assert np.allclose(jac, self.expected_autodiff[i], atol=tol) def test_expand_one(self, tol): """Test that a 1 qubit gate correctly expands to 3 qubits.""" U = np.array( [ [0.83645892 - 0.40533293j, -0.20215326 + 0.30850569j], [-0.23889780 - 0.28101519j, -0.88031770 - 0.29832709j], ] ) # test applied to wire 0 res = qml.math.expand_matrix(U, [0], [0, 4, 9]) expected = np.kron(np.kron(U, I), I) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 4 res = qml.math.expand_matrix(U, [4], [0, 4, 9]) expected = np.kron(np.kron(I, U), I) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 9 res = qml.math.expand_matrix(U, [9], [0, 4, 9]) expected = np.kron(np.kron(I, I), U) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_one_broadcasted(self, tol): """Test that a broadcasted 1 qubit gate correctly expands to 3 qubits.""" U = np.array( [ [0.83645892 - 0.40533293j, -0.20215326 + 0.30850569j], [-0.23889780 - 0.28101519j, -0.88031770 - 0.29832709j], ] ) # outer product with batch vector U = np.tensordot([0.14, -0.23, 1.3j], U, axes=0) # test applied to wire 0 res = qml.math.expand_matrix(U, [0], [0, 4, 9]) expected = np.kron(np.kron(U, I_broadcasted), I_broadcasted) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 4 res = qml.math.expand_matrix(U, [4], [0, 4, 9]) expected = np.kron(np.kron(I_broadcasted, U), I_broadcasted) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 9 res = qml.math.expand_matrix(U, [9], [0, 4, 9]) expected = np.kron(np.kron(I_broadcasted, I_broadcasted), U) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_two_consecutive_wires(self, tol): """Test that a 2 qubit gate on consecutive wires correctly expands to 4 qubits.""" U2 = np.array([[0, 1, 1, 1], [1, 0, 1, -1], [1, -1, 0, 1], [1, 1, -1, 0]]) / np.sqrt(3) # test applied to wire 0+1 res = qml.math.expand_matrix(U2, [0, 1], [0, 1, 2, 3]) expected = np.kron(np.kron(U2, I), I) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 1+2 res = qml.math.expand_matrix(U2, [1, 2], [0, 1, 2, 3]) expected = np.kron(np.kron(I, U2), I) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 2+3 res = qml.math.expand_matrix(U2, [2, 3], [0, 1, 2, 3]) expected = np.kron(np.kron(I, I), U2) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_two_consecutive_wires_broadcasted(self, tol): """Test that a broadcasted 2 qubit gate on consecutive wires correctly expands to 4 qubits.""" U2 = np.array([[0, 1, 1, 1], [1, 0, 1, -1], [1, -1, 0, 1], [1, 1, -1, 0]]) / np.sqrt(3) U2 = np.tensordot([2.31, 1.53, 0.7 - 1.9j], U2, axes=0) # test applied to wire 0+1 res = qml.math.expand_matrix(U2, [0, 1], [0, 1, 2, 3]) expected = np.kron(np.kron(U2, I_broadcasted), I_broadcasted) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 1+2 res = qml.math.expand_matrix(U2, [1, 2], [0, 1, 2, 3]) expected = np.kron(np.kron(I_broadcasted, U2), I_broadcasted) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 2+3 res = qml.math.expand_matrix(U2, [2, 3], [0, 1, 2, 3]) expected = np.kron(np.kron(I_broadcasted, I_broadcasted), U2) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_two_reversed_wires(self, tol): """Test that a 2 qubit gate on reversed consecutive wires correctly expands to 4 qubits.""" # CNOT with target on wire 1 res = qml.math.expand_matrix(CNOT, [1, 0], [0, 1, 2, 3]) rows = np.array([0, 2, 1, 3]) expected = np.kron(np.kron(CNOT[:, rows][rows], I), I) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_two_reversed_wires_broadcasted(self, tol): """Test that a broadcasted 2 qubit gate on reversed consecutive wires correctly expands to 4 qubits.""" # CNOT with target on wire 1 and a batch dimension of size 1 res = qml.math.expand_matrix(CNOT_broadcasted, [1, 0], [0, 1, 2, 3]) rows = [0, 2, 1, 3] expected = np.kron( np.kron(CNOT_broadcasted[:, :, rows][:, rows], I_broadcasted), I_broadcasted ) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_three_consecutive_wires(self, tol): """Test that a 3 qubit gate on consecutive wires correctly expands to 4 qubits.""" # test applied to wire 0,1,2 res = qml.math.expand_matrix(Toffoli, [0, 1, 2], [0, 1, 2, 3]) expected = np.kron(Toffoli, I) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 1,2,3 res = qml.math.expand_matrix(Toffoli, [1, 2, 3], [0, 1, 2, 3]) expected = np.kron(I, Toffoli) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_three_consecutive_wires_broadcasted(self, tol): """Test that a broadcasted 3 qubit gate on consecutive wires correctly expands to 4 qubits.""" # test applied to wire 0,1,2 res = qml.math.expand_matrix(Toffoli_broadcasted, [0, 1, 2], [0, 1, 2, 3]) expected = np.kron(Toffoli_broadcasted, I_broadcasted) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 1,2,3 res = qml.math.expand_matrix(Toffoli_broadcasted, [1, 2, 3], [0, 1, 2, 3]) expected = np.kron(I_broadcasted, Toffoli_broadcasted) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_three_nonconsecutive_ascending_wires(self, tol): """Test that a 3 qubit gate on non-consecutive but ascending wires correctly expands to 4 qubits.""" # test applied to wire 0,2,3 res = qml.math.expand_matrix(Toffoli, [0, 2, 3], [0, 1, 2, 3]) expected = np.kron(SWAP, II) @ np.kron(I, Toffoli) @ np.kron(SWAP, II) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 0,1,3 res = qml.math.expand_matrix(Toffoli, [0, 1, 3], [0, 1, 2, 3]) expected = np.kron(II, SWAP) @ np.kron(Toffoli, I) @ np.kron(II, SWAP) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_three_nonconsecutive_ascending_wires_broadcasted(self, tol): """Test that a broadcasted 3 qubit gate on non-consecutive but ascending wires correctly expands to 4 qubits.""" # test applied to wire 0,2,3 res = qml.math.expand_matrix(Toffoli_broadcasted[:1], [0, 2, 3], [0, 1, 2, 3]) expected = np.tensordot( np.tensordot( np.kron(SWAP, II), np.kron(I_broadcasted, Toffoli_broadcasted[:1]), axes=[[1], [1]], ), np.kron(SWAP, II), axes=[[2], [0]], ) expected = np.moveaxis(expected, 0, -2) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 0,1,3 res = qml.math.expand_matrix(Toffoli_broadcasted, [0, 1, 3], [0, 1, 2, 3]) expected = np.tensordot( np.tensordot( np.kron(II, SWAP), np.kron(Toffoli_broadcasted, I_broadcasted), axes=[[1], [1]], ), np.kron(II, SWAP), axes=[[2], [0]], ) expected = np.moveaxis(expected, 0, -2) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_three_nonconsecutive_nonascending_wires(self, tol): """Test that a 3 qubit gate on non-consecutive non-ascending wires correctly expands to 4 qubits""" # test applied to wire 3, 1, 2 res = qml.math.expand_matrix(Toffoli, [3, 1, 2], [0, 1, 2, 3]) # change the control qubit on the Toffoli gate rows = [0, 4, 1, 5, 2, 6, 3, 7] Toffoli_perm = Toffoli[:, rows][rows] expected = np.kron(I, Toffoli_perm) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 3, 0, 2 res = qml.math.expand_matrix(Toffoli, [3, 0, 2], [0, 1, 2, 3]) # change the control qubit on the Toffoli gate expected = np.kron(SWAP, II) @ np.kron(I, Toffoli_perm) @ np.kron(SWAP, II) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_three_nonconsecutive_nonascending_wires_broadcasted(self, tol): """Test that a broadcasted 3 qubit gate on non-consecutive non-ascending wires correctly expands to 4 qubits""" # test applied to wire 3, 1, 2 res = qml.math.expand_matrix(Toffoli_broadcasted, [3, 1, 2], [0, 1, 2, 3]) # change the control qubit on the Toffoli gate rows = [0, 4, 1, 5, 2, 6, 3, 7] Toffoli_broadcasted_perm = Toffoli_broadcasted[:, :, rows][:, rows] expected = np.kron(I_broadcasted, Toffoli_broadcasted_perm) assert np.allclose(res, expected, atol=tol, rtol=0) # test applied to wire 3, 0, 2 res = qml.math.expand_matrix(Toffoli_broadcasted, [3, 0, 2], [0, 1, 2, 3]) # change the control qubit on the Toffoli gate expected = np.tensordot( np.tensordot( np.kron(SWAP, II), np.kron(I_broadcasted, Toffoli_broadcasted_perm), axes=[[1], [1]], ), np.kron(SWAP, II), axes=[[2], [0]], ) expected = np.moveaxis(expected, 0, -2) assert np.allclose(res, expected, atol=tol, rtol=0) def test_expand_matrix_usage_in_operator_class(self, tol): """Tests that the method is used correctly by defining a dummy operator and checking the permutation/expansion.""" perm = [0, 2, 1, 3] permuted_matrix = self.base_matrix_2[perm][:, perm] expanded_matrix = np.array( [ [1, 2, 0, 0, 3, 4, 0, 0], [5, 6, 0, 0, 7, 8, 0, 0], [0, 0, 1, 2, 0, 0, 3, 4], [0, 0, 5, 6, 0, 0, 7, 8], [9, 10, 0, 0, 11, 12, 0, 0], [13, 14, 0, 0, 15, 16, 0, 0], [0, 0, 9, 10, 0, 0, 11, 12], [0, 0, 13, 14, 0, 0, 15, 16], ] ) class DummyOp(qml.operation.Operator): """Dummy operator for testing the expand_matrix method.""" num_wires = 2 @staticmethod def compute_matrix(): return self.base_matrix_2 op = DummyOp(wires=[0, 2]) assert np.allclose(op.matrix(), self.base_matrix_2, atol=tol) assert np.allclose(op.matrix(wire_order=[2, 0]), permuted_matrix, atol=tol) assert np.allclose(op.matrix(wire_order=[0, 1, 2]), expanded_matrix, atol=tol) def test_expand_matrix_usage_in_operator_class_broadcasted(self, tol): """Tests that the method is used correctly with a broadcasted matrix by defining a dummy operator and checking the permutation/expansion.""" perm = [0, 2, 1, 3] permuted_matrix = self.base_matrix_2_broadcasted[:, perm][:, :, perm] expanded_matrix = np.tensordot( np.tensordot( np.kron(SWAP, I), np.kron(I_broadcasted, self.base_matrix_2_broadcasted), axes=[[1], [1]], ), np.kron(SWAP, I), axes=[[2], [0]], ) expanded_matrix = np.moveaxis(expanded_matrix, 0, -2) class DummyOp(qml.operation.Operator): """Dummy operator for testing the expand_matrix method.""" num_wires = 2 # pylint: disable=arguments-differ @staticmethod def compute_matrix(): """Compute the matrix of the DummyOp.""" return self.base_matrix_2_broadcasted op = DummyOp(wires=[0, 2]) assert np.allclose(op.matrix(), self.base_matrix_2_broadcasted, atol=tol) assert np.allclose(op.matrix(wire_order=[2, 0]), permuted_matrix, atol=tol) assert np.allclose(op.matrix(wire_order=[0, 1, 2]), expanded_matrix, atol=tol) class TestExpandMatrixSparse: """Tests for the _sparse_expand_matrix function.""" base_matrix_1 = csr_matrix(np.arange(1, 5).reshape((2, 2))) base_matrix_2 = csr_matrix(np.arange(1, 17).reshape((4, 4))) def test_wires_pl_wires(self): """Tests the case wires is wires.Wires object""" mat = csr_matrix([[0, 1], [1, 0]]) res = qml.math.expand_matrix(mat, wires=qml.wires.Wires([0]), wire_order=[0, 1]) res.sort_indices() expected = csr_matrix(np.array([[0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) def test_wires_tuple(self): """Tests the case wires is a tuple""" mat = csr_matrix([[0, 1], [1, 0]]) res = qml.math.expand_matrix(mat, wires=(0,), wire_order=[0, 1]) res.sort_indices() expected = csr_matrix(np.array([[0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) def test_no_expansion(self): """Tests the case where the original matrix is not changed""" res = qml.math.expand_matrix(self.base_matrix_2, wires=[0, 2], wire_order=[0, 2]) assert isinstance(res, type(self.base_matrix_2)) assert all(res.data == self.base_matrix_2.data) assert all(res.indices == self.base_matrix_2.indices) def test_permutation(self): """Tests the case where the original matrix is permuted""" res = qml.math.expand_matrix(self.base_matrix_2, wires=[0, 2], wire_order=[2, 0]) res.sort_indices() expected = csr_matrix( np.array([[1, 3, 2, 4], [9, 11, 10, 12], [5, 7, 6, 8], [13, 15, 14, 16]]) ) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) def test_expansion(self): """Tests the case where the original matrix is expanded""" res = qml.math.expand_matrix(self.base_matrix_1, wires=[2], wire_order=[0, 2]) res.sort_indices() expected = csr_matrix(np.array([[1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 2], [0, 0, 3, 4]])) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) res = qml.math.expand_matrix(self.base_matrix_1, wires=[2], wire_order=[2, 0]) res.sort_indices() expected = csr_matrix(np.array([[1, 0, 2, 0], [0, 1, 0, 2], [3, 0, 4, 0], [0, 3, 0, 4]])) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) def test_expand_one(self): """Test that a 1 qubit gate correctly expands to 3 qubits.""" U = np.array( [ [0.83645892 - 0.40533293j, -0.20215326 + 0.30850569j], [-0.23889780 - 0.28101519j, -0.88031770 - 0.29832709j], ] ) U_sparse = csr_matrix(U) # test applied to wire 0 res = qml.math.expand_matrix(U_sparse, [0], [0, 4, 9]) res.sort_indices() expected = csr_matrix(np.kron(np.kron(U, I), I)) assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) # test applied to wire 4 res = qml.math.expand_matrix(U_sparse, [4], [0, 4, 9]) res.sort_indices() expected = csr_matrix(np.kron(np.kron(I, U), I)) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) # test applied to wire 9 res = qml.math.expand_matrix(U_sparse, [9], [0, 4, 9]) expected = csr_matrix(np.kron(np.kron(I, I), U)) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) def test_expand_two_consecutive_wires(self): """Test that a 2 qubit gate on consecutive wires correctly expands to 4 qubits.""" U2 = np.array([[0, 1, 1, 1], [1, 0, 1, -1], [1, -1, 0, 1], [1, 1, -1, 0]]) / np.sqrt(3) U2_sparse = csr_matrix(U2) # test applied to wire 0+1 res = qml.math.expand_matrix(U2_sparse, [0, 1], [0, 1, 2, 3]) res.sort_indices() expected = csr_matrix(np.kron(np.kron(U2, I), I)) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) # test applied to wire 1+2 res = qml.math.expand_matrix(U2_sparse, [1, 2], [0, 1, 2, 3]) res.sort_indices() expected = csr_matrix(np.kron(np.kron(I, U2), I)) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) # test applied to wire 2+3 res = qml.math.expand_matrix(U2_sparse, [2, 3], [0, 1, 2, 3]) res.sort_indices() expected = csr_matrix(np.kron(np.kron(I, I), U2)) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) def test_expand_two_reversed_wires(self): """Test that a 2 qubit gate on reversed consecutive wires correctly expands to 4 qubits.""" # CNOT with target on wire 1 res = qml.math.expand_matrix(csr_matrix(CNOT), [1, 0], [0, 1, 2, 3]) res.sort_indices() rows = np.array([0, 2, 1, 3]) expected = csr_matrix(np.kron(np.kron(CNOT[:, rows][rows], I), I)) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) def test_expand_three_consecutive_wires(self): """Test that a 3 qubit gate on consecutive wires correctly expands to 4 qubits.""" # test applied to wire 0,1,2 res = qml.math.expand_matrix(csr_matrix(Toffoli), [0, 1, 2], [0, 1, 2, 3]) res.sort_indices() expected = csr_matrix(np.kron(Toffoli, I)) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) # test applied to wire 1,2,3 res = qml.math.expand_matrix(csr_matrix(Toffoli), [1, 2, 3], [0, 1, 2, 3]) res.sort_indices() expected = csr_matrix(np.kron(I, Toffoli)) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) def test_expand_three_nonconsecutive_ascending_wires(self): """Test that a 3 qubit gate on non-consecutive but ascending wires correctly expands to 4 qubits.""" # test applied to wire 0,2,3 res = qml.math.expand_matrix(csr_matrix(Toffoli), [0, 2, 3], [0, 1, 2, 3]) res.sort_indices() expected = csr_matrix(np.kron(SWAP, II) @ np.kron(I, Toffoli) @ np.kron(SWAP, II)) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) # test applied to wire 0,1,3 res = qml.math.expand_matrix(csr_matrix(Toffoli), [0, 1, 3], [0, 1, 2, 3]) res.sort_indices() expected = csr_matrix(np.kron(II, SWAP) @ np.kron(Toffoli, I) @ np.kron(II, SWAP)) expected.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) def test_expand_three_nonconsecutive_nonascending_wires(self): """Test that a 3 qubit gate on non-consecutive non-ascending wires correctly expands to 4 qubits""" # test applied to wire 3, 1, 2 res = qml.math.expand_matrix(csr_matrix(Toffoli), [3, 1, 2], [0, 1, 2, 3]) # change the control qubit on the Toffoli gate rows = [0, 4, 1, 5, 2, 6, 3, 7] Toffoli_perm = Toffoli[:, rows][rows] expected = csr_matrix(np.kron(I, Toffoli_perm)) expected.sort_indices() res.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) # test applied to wire 3, 0, 2 res = qml.math.expand_matrix(csr_matrix(Toffoli), [3, 0, 2], [0, 1, 2, 3]) # change the control qubit on the Toffoli gate expected = csr_matrix(np.kron(SWAP, II) @ np.kron(I, Toffoli_perm) @ np.kron(SWAP, II)) expected.sort_indices() res.sort_indices() assert isinstance(res, type(expected)) assert all(res.data == expected.data) assert all(res.indices == expected.indices) def test_sparse_swap_mat(self): """Test the swap matrix generated is as expected.""" # pylint: disable=protected-access n = 4 for i in range(n): for j in range(n): if i != j: expected_mat = qml.SWAP(wires=[i, j]).matrix() expected_mat = qml.math.expand_matrix(expected_mat, [i, j], wire_order=range(n)) computed_mat = qml.math.matrix_manipulation._sparse_swap_mat(i, j, n).toarray() assert np.allclose(expected_mat, computed_mat) def test_sparse_swap_mat_same_index(self): """Test that if the indices are the same then the identity is returned.""" # pylint: disable=protected-access computed_mat = qml.math.matrix_manipulation._sparse_swap_mat(2, 2, 3).toarray() expected_mat = np.eye(8) assert np.allclose(expected_mat, computed_mat) class TestReduceMatrices: """Tests for the reduce_matrices function.""" op_list = [ qml.PauliX(0), qml.RX(1, 0), qml.CNOT([3, 4]), qml.PauliZ(0), qml.RX(2, 7), qml.Toffoli([4, 1, 7]), ] def test_sum_matrices(self): """Test the reduce_matrices function with the add method.""" mats_and_wires_gen = ((op.matrix(), op.wires) for op in self.op_list) reduced_mat, final_wires = qml.math.reduce_matrices(mats_and_wires_gen, qml.math.add) expected_wires = reduce(lambda x, y: x + y, [op.wires for op in self.op_list]) expected_matrix = reduce( qml.math.add, (op.matrix(wire_order=expected_wires) for op in self.op_list) ) assert final_wires == expected_wires assert qml.math.allclose(reduced_mat, expected_matrix) assert reduced_mat.shape == (2**5, 2**5) def test_prod_matrices(self): """Test the reduce_matrices function with the dot method.""" mats_and_wires_gen = ((op.matrix(), op.wires) for op in self.op_list) reduced_mat, final_wires = qml.math.reduce_matrices(mats_and_wires_gen, qml.math.dot) expected_wires = reduce(lambda x, y: x + y, [op.wires for op in self.op_list]) expected_matrix = reduce( qml.math.dot, (op.matrix(wire_order=expected_wires) for op in self.op_list) ) assert final_wires == expected_wires assert qml.math.allclose(reduced_mat, expected_matrix) assert reduced_mat.shape == (2**5, 2**5) @pytest.mark.parametrize("ml_framework", ml_frameworks_list) class TestPartialTrace: """Unit tests for the partial_trace function.""" @pytest.mark.parametrize("c_dtype", dtypes) def test_single_density_matrix(self, ml_framework, c_dtype): """Test partial trace on a single density matrix.""" # Define a 2-qubit density matrix rho = qml.math.asarray( np.array([[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]), like=ml_framework ) # Expected result after tracing out the second qubit expected = qml.math.asarray(np.array([[[1, 0], [0, 0]]], dtype=c_dtype), like=ml_framework) # Perform the partial trace result = qml.math.quantum.partial_trace(rho, [0], c_dtype=c_dtype) assert qml.math.allclose(result, expected) @pytest.mark.parametrize("c_dtype", dtypes) def test_batched_density_matrices(self, ml_framework, c_dtype): """Test partial trace on a batch of density matrices.""" # Define a batch of 2-qubit density matrices rho = qml.math.asarray( np.array( [ [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], ] ), like=ml_framework, ) # rho = qml.math.asarrays(rho) # Expected result after tracing out the first qubit for each matrix expected = qml.math.asarray( np.array([[[1, 0], [0, 0]], [[1, 0], [0, 0]]], dtype=c_dtype), like=ml_framework ) # Perform the partial trace result = qml.math.quantum.partial_trace(rho, [1], c_dtype=c_dtype) assert qml.math.allclose(result, expected) @pytest.mark.parametrize("c_dtype", dtypes) def test_partial_trace_over_no_wires(self, ml_framework, c_dtype): """Test that tracing over no wires returns the original matrix.""" # Define a 2-qubit density matrix rho = qml.math.asarray( np.array([[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]], dtype=c_dtype), like=ml_framework, ) # Perform the partial trace over no wires result = qml.math.quantum.partial_trace(rho, [], c_dtype=c_dtype) assert qml.math.allclose(result, rho) @pytest.mark.parametrize("c_dtype", dtypes) def test_partial_trace_over_all_wires(self, ml_framework, c_dtype): """Test that tracing over all wires returns the trace of the matrix.""" # Define a 2-qubit density matrix rho = qml.math.asarray( np.array([[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]), like=ml_framework ) # Expected result after tracing out all qubits expected = qml.math.asarray(np.array([1], dtype=c_dtype), like=ml_framework) # Perform the partial trace over all wires result = qml.math.quantum.partial_trace(rho, [0, 1], c_dtype=c_dtype) assert qml.math.allclose(result, expected) @pytest.mark.parametrize("c_dtype", dtypes) def test_invalid_wire_selection(self, ml_framework, c_dtype): """Test that an error is raised for an invalid wire selection.""" # Define a 2-qubit density matrix rho = qml.math.asarray( np.array([[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]), like=ml_framework ) # Attempt to trace over an invalid wire with pytest.raises(Exception) as e: import tensorflow as tf # pylint: disable=Import outside toplevel (tensorflow) (import-outside-toplevel) qml.math.quantum.partial_trace(rho, [2], c_dtype=c_dtype) assert e.type in ( ValueError, IndexError, tf.python.framework.errors_impl.InvalidArgumentError, ) @pytest.mark.parametrize("c_dtype", dtypes) def test_partial_trace_single_matrix(self, ml_framework, c_dtype): """Test that partial_trace works on a single matrix.""" # Define a 2-qubit density matrix rho = qml.math.asarray( np.array([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]), like=ml_framework ) result = qml.math.quantum.partial_trace(rho, [0], c_dtype=c_dtype) expected = qml.math.asarray(np.array([[1, 0], [0, 0]], dtype=c_dtype), like=ml_framework) assert qml.math.allclose(result, expected)
pennylane/tests/math/test_matrix_manipulation.py/0
{ "file_path": "pennylane/tests/math/test_matrix_manipulation.py", "repo_id": "pennylane", "token_count": 18960 }
82
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # 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. """Unit tests for the expval module""" import copy import numpy as np import pytest import pennylane as qml from pennylane.measurements import Expectation from pennylane.measurements.expval import ExpectationMP def test_expval_identity_nowires_DQ(): """Test that attempting to measure qml.Identity() with no wires raises an explicit error in default.qubit""" # temporary solution to merge https://github.com/PennyLaneAI/pennylane/pull/5106 @qml.qnode(qml.device("default.qubit")) def qnode(): return qml.expval(qml.Identity()) with pytest.raises(NotImplementedError, match="Expectation values of qml.Identity()"): _ = qnode() def test_expval_identity_nowires_LQ(): """Test that attempting to measure qml.Identity() with no wires raises an explicit error in lightning.qubit""" # temporary solution to merge https://github.com/PennyLaneAI/pennylane/pull/5106 @qml.qnode(qml.device("lightning.qubit", wires=[0])) def qnode(): return qml.expval(qml.Identity()) with pytest.raises(NotImplementedError, match="Expectation values of qml.Identity()"): _ = qnode() class TestExpval: """Tests for the expval function""" @pytest.mark.parametrize("shots", [None, 1111, [1111, 1111]]) def test_value(self, tol, shots): """Test that the expval interface works""" dev = qml.device("default.qubit", wires=2, shots=shots) @qml.qnode(dev, diff_method="parameter-shift") def circuit(x): qml.RX(x, wires=0) return qml.expval(qml.PauliY(0)) x = 0.54 res = circuit(x) expected = -np.sin(x) atol = tol if shots is None else 0.05 rtol = 0 if shots is None else 0.05 assert np.allclose(res, expected, atol=atol, rtol=rtol) r_dtype = np.float64 if isinstance(res, tuple): assert res[0].dtype == r_dtype assert res[1].dtype == r_dtype else: assert res.dtype == r_dtype def test_observable_return_type_is_expectation(self): """Test that the return type of the observable is :attr:`ObservableReturnTypes.Expectation`""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(): res = qml.expval(qml.PauliZ(0)) assert res.return_type is Expectation return res circuit() @pytest.mark.parametrize("shots", [None, 1111, [1111, 1111]]) @pytest.mark.parametrize("phi", np.arange(0, 2 * np.pi, np.pi / 3)) def test_observable_is_measurement_value( self, shots, phi, tol, tol_stochastic ): # pylint: disable=too-many-arguments """Test that expectation values for mid-circuit measurement values are correct for a single measurement value.""" dev = qml.device("default.qubit", wires=2, shots=shots) @qml.qnode(dev) def circuit(phi): qml.RX(phi, 0) m0 = qml.measure(0) return qml.expval(m0) atol = tol if shots is None else tol_stochastic for func in [circuit, qml.defer_measurements(circuit)]: res = func(phi) assert np.allclose(np.array(res), np.sin(phi / 2) ** 2, atol=atol, rtol=0) @pytest.mark.parametrize("shots", [None, 1111, [1111, 1111]]) @pytest.mark.parametrize("phi", np.arange(0, 2 * np.pi, np.pi / 3)) def test_observable_is_composite_measurement_value( self, shots, phi, tol, tol_stochastic ): # pylint: disable=too-many-arguments """Test that expectation values for mid-circuit measurement values are correct for a composite measurement value.""" dev = qml.device("default.qubit", seed=123) @qml.qnode(dev) def circuit(phi): qml.RX(phi, 0) m0 = qml.measure(0) qml.RX(0.5 * phi, 1) m1 = qml.measure(1) qml.RX(2 * phi, 2) m2 = qml.measure(2) return qml.expval(m0 * m1 + m2) @qml.qnode(dev) def expected_circuit(phi): qml.RX(phi, 0) qml.RX(0.5 * phi, 1) qml.RX(2 * phi, 2) return ( qml.expval(qml.Projector([1], 0)), qml.expval(qml.Projector([1], 1)), qml.expval(qml.Projector([1], 2)), ) evals = expected_circuit(phi) expected = evals[0] * evals[1] + evals[2] atol = tol if shots is None else tol_stochastic for func in [circuit, qml.defer_measurements(circuit)]: res = func(phi, shots=shots) assert np.allclose(np.array(res), expected, atol=atol, rtol=0) def test_eigvals_instead_of_observable(self): """Tests process samples with eigvals instead of observables""" shots = 100 rng = np.random.default_rng(123) samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) expected = qml.expval(qml.PauliZ(0)).process_samples(samples, [0, 1]) assert ( ExpectationMP(eigvals=[1, -1], wires=[0]).process_samples(samples, [0, 1]) == expected ) def test_measurement_value_list_not_allowed(self): """Test that measuring a list of measurement values raises an error.""" m0 = qml.measure(0) m1 = qml.measure(1) with pytest.raises( ValueError, match="qml.expval does not support measuring sequences of measurements" ): _ = qml.expval([m0, m1]) @pytest.mark.parametrize( "obs", [qml.PauliZ(0), qml.Hermitian(np.diag([1, 2]), 0), qml.Hermitian(np.diag([1.0, 2.0]), 0)], ) def test_numeric_type(self, obs): """Test that the numeric type is correct.""" res = qml.expval(obs) assert res.numeric_type is float @pytest.mark.parametrize( "obs", [qml.PauliZ(0), qml.Hermitian(np.diag([1, 2]), 0), qml.Hermitian(np.diag([1.0, 2.0]), 0)], ) def test_shape(self, obs): """Test that the shape is correct.""" res = qml.expval(obs) # pylint: disable=use-implicit-booleaness-not-comparison assert res.shape(None, 1) == () assert res.shape(100, 1) == () @pytest.mark.parametrize("state", [np.array([0, 0, 0]), np.array([1, 0, 0, 0, 0, 0, 0, 0])]) @pytest.mark.parametrize("shots", [None, 1000, [1000, 1111]]) def test_projector_expval(self, state, shots): """Tests that the expectation of a ``Projector`` object is computed correctly for both of its subclasses.""" dev = qml.device("default.qubit", wires=3, shots=shots, seed=123) @qml.qnode(dev) def circuit(): qml.Hadamard(0) return qml.expval(qml.Projector(state, wires=range(3))) res = circuit() expected = [0.5, 0.5] if isinstance(shots, list) else 0.5 assert np.allclose(res, expected, atol=0.02, rtol=0.02) def test_permuted_wires(self): """Test that the expectation value of an operator with permuted wires is the same.""" obs = qml.prod(qml.PauliZ(8), qml.s_prod(2, qml.PauliZ(10)), qml.s_prod(3, qml.PauliZ("h"))) obs_2 = qml.prod( qml.s_prod(3, qml.PauliZ("h")), qml.PauliZ(8), qml.s_prod(2, qml.PauliZ(10)) ) dev = qml.device("default.qubit", wires=["h", 8, 10]) @qml.qnode(dev) def circuit(): qml.RX(1.23, wires=["h"]) qml.RY(2.34, wires=[8]) return qml.expval(obs) @qml.qnode(dev) def circuit2(): qml.RX(1.23, wires=["h"]) qml.RY(2.34, wires=[8]) return qml.expval(obs_2) assert circuit() == circuit2() def test_copy_observable(self): """Test that the observable is copied if present.""" m = qml.expval(qml.PauliX(0)) copied_m = copy.copy(m) assert m.obs is not copied_m.obs qml.assert_equal(m.obs, copied_m.obs) def test_copy_eigvals(self): """Test that the eigvals value is just assigned to new mp without copying.""" # pylint: disable=protected-access m = ExpectationMP(eigvals=[-0.5, 0.5], wires=qml.wires.Wires(0)) copied_m = copy.copy(m) assert m._eigvals is copied_m._eigvals def test_standard_obs(self): """Check that the hash of an expectation value of an observable can distinguish different observables.""" o1 = qml.prod(qml.PauliX(0), qml.PauliY(1)) o2 = qml.prod(qml.PauliX(0), qml.PauliZ(1)) assert qml.expval(o1).hash == qml.expval(o1).hash assert qml.expval(o2).hash == qml.expval(o2).hash assert qml.expval(o1).hash != qml.expval(o2).hash o3 = qml.sum(qml.PauliX("a"), qml.PauliY("b")) assert qml.expval(o1).hash != qml.expval(o3).hash def test_eigvals(self): """Test that the eigvals property controls the hash property.""" m1 = ExpectationMP(eigvals=[-0.5, 0.5], wires=qml.wires.Wires(0)) m2 = ExpectationMP(eigvals=[-0.5, 0.5], wires=qml.wires.Wires(0), id="something") assert m1.hash == m2.hash m3 = ExpectationMP(eigvals=[-0.5, 0.5], wires=qml.wires.Wires(1)) assert m1.hash != m3.hash m4 = ExpectationMP(eigvals=[-1, 1], wires=qml.wires.Wires(1)) assert m1.hash != m4.hash assert m3.hash != m4.hash @pytest.mark.tf @pytest.mark.parametrize( "state,expected", [ ([1.0, 0.0], 1.0), ([[1.0, 0.0], [0.0, 1.0]], [1.0, -1.0]), ], ) def test_tf_function(self, state, expected): """Test that tf.function does not break process_state""" import tensorflow as tf @tf.function def compute_expval(s): mp = ExpectationMP(obs=qml.PauliZ(0)) return mp.process_state(s, wire_order=qml.wires.Wires([0])) state = tf.Variable(state, dtype=tf.float64) assert qml.math.allequal(compute_expval(state), expected) def test_batched_hamiltonian(self): """Test that the expval interface works""" dev = qml.device("default.qubit") ops = (qml.Hadamard(0), qml.PauliZ(0) @ qml.PauliY(1) @ qml.PauliY(2) @ qml.PauliX(3)) H = qml.Hamiltonian([0.5, 1.0], ops) @qml.qnode(dev, interface="autograd", diff_method="parameter-shift") def cost_circuit(params): qml.RX(params, 0) qml.CNOT([0, 1]) return qml.expval(H) rng = np.random.default_rng(42) params = rng.normal(0, np.pi, 4) energy = [cost_circuit(p) for p in params] energy_batched = cost_circuit(params) assert qml.math.allequal(energy_batched, energy) @pytest.mark.parametrize( "wire, expected", [ (0, 0.0), (1, 1.0), ], ) def test_estimate_expectation_with_counts(self, wire, expected): """Test that the expectation value of an observable is estimated correctly using counts""" counts = {"000": 100, "100": 100} wire_order = qml.wires.Wires((0, 1, 2)) res = qml.expval(qml.Z(wire)).process_counts(counts=counts, wire_order=wire_order) assert np.allclose(res, expected)
pennylane/tests/measurements/test_expval.py/0
{ "file_path": "pennylane/tests/measurements/test_expval.py", "repo_id": "pennylane", "token_count": 5598 }
83
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # 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. """ Pytest configuration file for ops.functions submodule. Generates parametrizations of operators to test in test_assert_valid.py. """ from inspect import getmembers, isclass import numpy as np import pytest import pennylane as qml from pennylane.operation import ( Channel, MatrixUndefinedError, Observable, Operation, Operator, Tensor, ) from pennylane.ops.op_math.adjoint import Adjoint, AdjointObs, AdjointOperation, AdjointOpObs from pennylane.ops.op_math.pow import PowObs, PowOperation, PowOpObs _INSTANCES_TO_TEST = [ qml.sum(qml.PauliX(0), qml.PauliZ(0)), qml.sum(qml.X(0), qml.X(0), qml.Z(0), qml.Z(0)), qml.BasisState([1], wires=[0]), qml.ControlledQubitUnitary(np.eye(2), control_wires=1, wires=0), qml.QubitStateVector([0, 1], wires=0), qml.QubitChannel([np.array([[1, 0], [0, 0.8]]), np.array([[0, 0.6], [0, 0]])], wires=0), qml.MultiControlledX(wires=[0, 1]), qml.Projector([1], 0), # the state-vector version is already tested qml.SpecialUnitary([1, 1, 1], 0), qml.IntegerComparator(1, wires=[0, 1]), qml.PauliRot(1.1, "X", wires=[0]), qml.StatePrep([0, 1], 0), qml.PCPhase(0.27, dim=2, wires=[0, 1]), qml.BlockEncode([[0.1, 0.2], [0.3, 0.4]], wires=[0, 1]), qml.adjoint(qml.PauliX(0)), qml.adjoint(qml.RX(1.1, 0)), Tensor(qml.PauliX(0), qml.PauliX(1)), qml.operation.convert_to_legacy_H(qml.Hamiltonian([1.1, 2.2], [qml.PauliX(0), qml.PauliZ(0)])), qml.ops.LinearCombination([1.1, 2.2], [qml.PauliX(0), qml.PauliZ(0)]), qml.s_prod(1.1, qml.RX(1.1, 0)), qml.prod(qml.PauliX(0), qml.PauliY(1), qml.PauliZ(0)), qml.ctrl(qml.RX(1.1, 0), 1), qml.exp(qml.PauliX(0), 1.1), qml.pow(qml.IsingXX(1.1, [0, 1]), 2.5), qml.ops.Evolution(qml.PauliX(0), 5.2), qml.QutritBasisState([1, 2, 0], wires=[0, 1, 2]), qml.resource.FirstQuantization(1, 2, 1), qml.prod(qml.RX(1.1, 0), qml.RY(2.2, 0), qml.RZ(3.3, 1)), qml.Snapshot(measurement=qml.expval(qml.Z(0)), tag="hi"), qml.Snapshot(tag="tag"), ] """Valid operator instances that could not be auto-generated.""" _INSTANCES_TO_FAIL = [ ( qml.SparseHamiltonian(qml.Hamiltonian([1.1], [qml.PauliX(0)]).sparse_matrix(), [0]), AssertionError, # each data element must be tensorlike ), ( qml.PauliError("X", 0.5, wires=0), AssertionError, # each data element must be tensorlike ), ( qml.THermitian(np.eye(3), wires=0), (AssertionError, ValueError), # qutrit ops fail validation ), ( qml.ops.qubit.special_unitary.TmpPauliRot(1.1, "X", [0]), AssertionError, # private type with has_matrix=False despite having one ), ( qml.ops.Conditional(qml.measure(1), qml.S(0)), AssertionError, # needs flattening helpers to be updated, also cannot be pickled ), ( qml.Identity(0), MatrixUndefinedError, # empty decomposition, matrix differs from decomp's matrix ), ( qml.GlobalPhase(1.1), MatrixUndefinedError, # empty decomposition, matrix differs from decomp's matrix ), ( qml.pulse.ParametrizedEvolution(qml.PauliX(0) + sum * qml.PauliZ(0)), ValueError, # binding parameters fail, and more ), ( qml.resource.DoubleFactorization(np.eye(2), np.arange(16).reshape((2,) * 4)), TypeError, # op.eigvals is a list (overwritten in the init) ), ] """ List[Tuple[Operator, Type[Exception]]]: List of tuples containing Operator instances that could not be auto-generated, along with the exception type raised when trying to assert its validity. These operators need to break PL conventions, and each one's reason is specified in a comment. """ _ABSTRACT_OR_META_TYPES = { Adjoint, AdjointOpObs, AdjointOperation, AdjointObs, Operator, Operation, Observable, Channel, qml.ops.SymbolicOp, qml.ops.ScalarSymbolicOp, qml.ops.Pow, qml.ops.CompositeOp, qml.ops.Controlled, qml.ops.ControlledOp, qml.ops.qubit.BasisStateProjector, qml.ops.qubit.StateVectorProjector, qml.ops.qubit.StatePrepBase, qml.resource.ResourcesOperation, qml.resource.ErrorOperation, PowOpObs, PowOperation, PowObs, } """Types that should not have actual instances created.""" def get_all_classes(c): """Recursive function to generate a flat list of all child classes of ``c``. (first called with ``Operator``).""" if c.__module__[:10] != "pennylane.": return [] subs = c.__subclasses__() classes = [] if c in _ABSTRACT_OR_META_TYPES else [c] for sub in subs: classes.extend(get_all_classes(sub)) return classes _CLASSES_TO_TEST = ( set(get_all_classes(Operator)) - {i[1] for i in getmembers(qml.templates) if isclass(i[1]) and issubclass(i[1], Operator)} - {type(op) for op in _INSTANCES_TO_TEST} - {type(op) for (op, _) in _INSTANCES_TO_FAIL} ) """All operators, except those tested manually, abstract/meta classes, and templates.""" @pytest.fixture(params=sorted(_CLASSES_TO_TEST, key=lambda op: op.__name__)) def class_to_validate(request): yield request.param @pytest.fixture(params=_INSTANCES_TO_TEST) def valid_instance(request): yield request.param @pytest.fixture(params=_INSTANCES_TO_FAIL) def invalid_instance_and_error(request): yield request.param
pennylane/tests/ops/functions/conftest.py/0
{ "file_path": "pennylane/tests/ops/functions/conftest.py", "repo_id": "pennylane", "token_count": 2557 }
84
# Copyright 2018-2022 Xanadu Quantum Technologies Inc. # 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. """Tests for the Adjoint operator wrapper and the adjoint constructor.""" import pickle import numpy as np import pytest import pennylane as qml from pennylane import numpy as np from pennylane.ops.op_math.adjoint import Adjoint, AdjointOperation, adjoint # pylint: disable=too-few-public-methods class PlainOperator(qml.operation.Operator): """just an operator.""" @pytest.mark.parametrize("target", (qml.PauliZ(0), qml.Rot(1.2, 2.3, 3.4, wires=0))) def test_basic_validity(target): """Run basic operator validity fucntions.""" op = qml.adjoint(target) qml.ops.functions.assert_valid(op) class TestInheritanceMixins: """Test inheritance structure and mixin addition through dynamic __new__ method.""" def test_plain_operator(self): """Test when base directly inherits from Operator, Adjoint only inherits from Adjoint and Operator.""" base = PlainOperator(1.234, wires=0) op = Adjoint(base) assert isinstance(op, Adjoint) assert isinstance(op, qml.operation.Operator) assert not isinstance(op, qml.operation.Operation) assert not isinstance(op, qml.operation.Observable) assert not isinstance(op, AdjointOperation) # checking we can call `dir` without problems assert "num_params" in dir(op) def test_operation(self): """When the operation inherits from `Operation`, the `AdjointOperation` mixin is added and the Adjoint has Operation functionality.""" # pylint: disable=too-few-public-methods class CustomOp(qml.operation.Operation): num_wires = 1 num_params = 1 base = CustomOp(1.234, wires=0) op = Adjoint(base) assert isinstance(op, Adjoint) assert isinstance(op, qml.operation.Operator) assert isinstance(op, qml.operation.Operation) assert not isinstance(op, qml.operation.Observable) assert isinstance(op, AdjointOperation) # check operation-specific properties made it into the mapping assert "grad_recipe" in dir(op) assert "control_wires" in dir(op) @pytest.mark.usefixtures("use_legacy_opmath") def test_observable(self): """Test that when the base is an Observable, Adjoint will also inherit from Observable.""" # pylint: disable=too-few-public-methods class CustomObs(qml.operation.Observable): num_wires = 1 num_params = 0 base = CustomObs(wires=0) ob = Adjoint(base) assert isinstance(ob, Adjoint) assert isinstance(ob, qml.operation.Operator) assert not isinstance(ob, qml.operation.Operation) assert isinstance(ob, qml.operation.Observable) assert not isinstance(ob, AdjointOperation) # Check some basic observable functionality assert ob.compare(ob) with pytest.warns(UserWarning, match="Tensor object acts on overlapping"): assert isinstance(1.0 * ob @ ob, qml.Hamiltonian) # check the dir assert "grad_recipe" not in dir(ob) @pytest.mark.parametrize( "op", ( PlainOperator(1.2, wires=0), qml.RX(1.2, wires=0), qml.operation.Tensor(qml.PauliX(0), qml.PauliX(1)), qml.PauliX(0), ), ) def test_pickling(self, op): """Test that pickling works for all inheritance combinations.""" adj_op = Adjoint(op) pickled_adj_op = pickle.dumps(adj_op) unpickled_op = pickle.loads(pickled_adj_op) assert type(adj_op) is type(unpickled_op) qml.assert_equal(adj_op, unpickled_op) class TestInitialization: """Test the initialization process and standard properties.""" # pylint: disable=use-implicit-booleaness-not-comparison def test_nonparametric_ops(self): """Test adjoint initialization for a non parameteric operation.""" base = qml.PauliX("a") op = Adjoint(base, id="something") assert op.base is base assert op.hyperparameters["base"] is base assert op.name == "Adjoint(PauliX)" assert op.id == "something" assert op.num_params == 0 assert op.parameters == [] assert op.data == () assert op.wires == qml.wires.Wires("a") def test_parametric_ops(self): """Test adjoint initialization for a standard parametric operation.""" params = [1.2345, 2.3456, 3.4567] base = qml.Rot(*params, wires="b") op = Adjoint(base, id="id") assert op.base is base assert op.hyperparameters["base"] is base assert op.name == "Adjoint(Rot)" assert op.id == "id" assert op.num_params == 3 assert qml.math.allclose(params, op.parameters) assert qml.math.allclose(params, op.data) assert op.wires == qml.wires.Wires("b") def test_template_base(self): """Test adjoint initialization for a template.""" rng = np.random.default_rng(seed=42) shape = qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=2) params = rng.random(shape) base = qml.StronglyEntanglingLayers(params, wires=[0, 1]) op = Adjoint(base) assert op.base is base assert op.hyperparameters["base"] is base assert op.name == "Adjoint(StronglyEntanglingLayers)" assert op.num_params == 1 assert qml.math.allclose(params, op.parameters[0]) assert qml.math.allclose(params, op.data[0]) assert op.wires == qml.wires.Wires((0, 1)) @pytest.mark.usefixtures("use_legacy_opmath") def test_hamiltonian_base(self): """Test adjoint initialization for a hamiltonian.""" with pytest.warns(UserWarning, match="Tensor object acts on overlapping"): base = 2.0 * qml.PauliX(0) @ qml.PauliY(0) + qml.PauliZ("b") op = Adjoint(base) assert op.base is base assert op.hyperparameters["base"] is base assert op.name == "Adjoint(Hamiltonian)" assert op.num_params == 2 assert qml.math.allclose(op.parameters, [2.0, 1.0]) assert qml.math.allclose(op.data, [2.0, 1.0]) assert op.wires == qml.wires.Wires([0, "b"]) class TestProperties: """Test Adjoint properties.""" def test_data(self): """Test base data can be get and set through Adjoint class.""" x = np.array(1.234) base = qml.RX(x, wires="a") adj = Adjoint(base) assert adj.data == (x,) # update parameters through adjoint x_new = np.array(2.3456) adj.data = (x_new,) assert base.data == (x_new,) assert adj.data == (x_new,) # update base data updates Adjoint data x_new2 = np.array(3.456) base.data = (x_new2,) assert adj.data == (x_new2,) def test_has_matrix_true(self): """Test `has_matrix` property carries over when base op defines matrix.""" base = qml.PauliX(0) op = Adjoint(base) assert op.has_matrix is True def test_has_matrix_false(self): """Test has_matrix property carries over when base op does not define a matrix.""" base = qml.StatePrep([1, 0], wires=0) op = Adjoint(base) assert op.has_matrix is False def test_has_decomposition_true_via_base_adjoint(self): """Test `has_decomposition` property is activated because the base operation defines an `adjoint` method.""" base = qml.PauliX(0) op = Adjoint(base) assert op.has_decomposition is True def test_has_decomposition_true_via_base_decomposition(self): """Test `has_decomposition` property is activated because the base operation defines a `decomposition` method.""" # pylint: disable=too-few-public-methods class MyOp(qml.operation.Operation): num_wires = 1 def decomposition(self): return [qml.RX(0.2, self.wires)] base = MyOp(0) op = Adjoint(base) assert op.has_decomposition is True def test_has_decomposition_false(self): """Test `has_decomposition` property is not activated if the base neither `has_adjoint` nor `has_decomposition`.""" # pylint: disable=too-few-public-methods class MyOp(qml.operation.Operation): num_wires = 1 base = MyOp(0) op = Adjoint(base) assert op.has_decomposition is False def test_has_adjoint_true_always(self): """Test `has_adjoint` property to always be true, irrespective of the base.""" # pylint: disable=too-few-public-methods class MyOp(qml.operation.Operation): """Operation that does not define `adjoint` and hence has `has_adjoint=False`.""" num_wires = 1 base = MyOp(0) op = Adjoint(base) assert op.has_adjoint is True assert op.base.has_adjoint is False base = qml.PauliX(0) op = Adjoint(base) assert op.has_adjoint is True assert op.base.has_adjoint is True def test_has_diagonalizing_gates_true_via_base_diagonalizing_gates(self): """Test `has_diagonalizing_gates` property is activated because the base operation defines a `diagonalizing_gates` method.""" op = Adjoint(qml.PauliX(0)) assert op.has_diagonalizing_gates is True def test_has_diagonalizing_gates_false(self): """Test `has_diagonalizing_gates` property is not activated if the base neither `has_adjoint` nor `has_diagonalizing_gates`.""" # pylint: disable=too-few-public-methods class MyOp(qml.operation.Operation): num_wires = 1 has_diagonalizing_gates = False op = Adjoint(MyOp(0)) assert op.has_diagonalizing_gates is False def test_queue_category(self): """Test that the queue category `"_ops"` carries over.""" op = Adjoint(qml.PauliX(0)) assert op._queue_category == "_ops" # pylint: disable=protected-access @pytest.mark.usefixtures("use_legacy_opmath") def test_queue_category_None(self): """Test that the queue category `None` for some observables carries over.""" op = Adjoint(qml.PauliX(0) @ qml.PauliY(1)) assert op._queue_category is None # pylint: disable=protected-access @pytest.mark.parametrize("value", (True, False)) def test_is_hermitian(self, value): """Test `is_hermitian` property mirrors that of the base.""" # pylint: disable=too-few-public-methods class DummyOp(qml.operation.Operator): num_wires = 1 is_hermitian = value op = Adjoint(DummyOp(0)) assert op.is_hermitian == value def test_batching_properties(self): """Test the batching properties and methods.""" base = qml.RX(np.array([1.2, 2.3, 3.4]), 0) op = Adjoint(base) assert op.batch_size == 3 assert op.ndim_params == (0,) class TestSimplify: """Test Adjoint simplify method and depth property.""" def test_depth_property(self): """Test depth property.""" adj_op = Adjoint(Adjoint(qml.RZ(1.32, wires=0))) assert adj_op.arithmetic_depth == 2 def test_simplify_method(self): """Test that the simplify method reduces complexity to the minimum.""" adj_op = Adjoint(Adjoint(Adjoint(qml.RZ(1.32, wires=0)))) final_op = qml.RZ(4 * np.pi - 1.32, wires=0) simplified_op = adj_op.simplify() # TODO: Use qml.equal when supported for nested operators assert isinstance(simplified_op, qml.RZ) assert final_op.data == simplified_op.data assert final_op.wires == simplified_op.wires assert final_op.arithmetic_depth == simplified_op.arithmetic_depth def test_simplify_adj_of_sums(self): """Test that the simplify methods converts an adjoint of sums to a sum of adjoints.""" adj_op = Adjoint(qml.sum(qml.RX(1, 0), qml.RY(1, 0), qml.RZ(1, 0))) sum_op = qml.sum( qml.RX(4 * np.pi - 1, 0), qml.RY(4 * np.pi - 1, 0), qml.RZ(4 * np.pi - 1, 0) ) simplified_op = adj_op.simplify() # TODO: Use qml.equal when supported for nested operators assert isinstance(simplified_op, qml.ops.Sum) assert sum_op.data == simplified_op.data assert sum_op.wires == simplified_op.wires assert sum_op.arithmetic_depth == simplified_op.arithmetic_depth for s1, s2 in zip(sum_op.operands, simplified_op.operands): assert s1.name == s2.name assert s1.wires == s2.wires assert s1.data == s2.data assert s1.arithmetic_depth == s2.arithmetic_depth def test_simplify_adj_of_prod(self): """Test that the simplify method converts an adjoint of products to a (reverse) product of adjoints.""" adj_op = Adjoint(qml.prod(qml.RX(1, 0), qml.RY(1, 0), qml.RZ(1, 0))) final_op = qml.prod( qml.RZ(4 * np.pi - 1, 0), qml.RY(4 * np.pi - 1, 0), qml.RX(4 * np.pi - 1, 0) ) simplified_op = adj_op.simplify() assert isinstance(simplified_op, qml.ops.Prod) assert final_op.data == simplified_op.data assert final_op.wires == simplified_op.wires assert final_op.arithmetic_depth == simplified_op.arithmetic_depth for s1, s2 in zip(final_op.operands, simplified_op.operands): assert s1.name == s2.name assert s1.wires == s2.wires assert s1.data == s2.data assert s1.arithmetic_depth == s2.arithmetic_depth def test_simplify_with_adjoint_not_defined(self): """Test the simplify method with an operator that has not defined the op.adjoint method.""" op = Adjoint(qml.T(0)) simplified_op = op.simplify() assert isinstance(simplified_op, Adjoint) assert op.data == simplified_op.data assert op.wires == simplified_op.wires assert op.arithmetic_depth == simplified_op.arithmetic_depth class TestMiscMethods: """Test miscellaneous small methods on the Adjoint class.""" def test_repr(self): """Test __repr__ method.""" assert repr(Adjoint(qml.S(0))) == "Adjoint(S(wires=[0]))" base = qml.S(0) + qml.T(0) op = Adjoint(base) assert repr(op) == "Adjoint(S(wires=[0]) + T(wires=[0]))" def test_label(self): """Test that the label method for the adjoint class adds a † to the end.""" base = qml.Rot(1.2345, 2.3456, 3.4567, wires="b") op = Adjoint(base) assert op.label(decimals=2) == "Rot\n(1.23,\n2.35,\n3.46)†" base = qml.S(0) + qml.T(0) op = Adjoint(base) assert op.label() == "(S+T)†" def test_adjoint_of_adjoint(self): """Test that the adjoint of an adjoint is the original operation.""" base = qml.PauliX(0) op = Adjoint(base) assert op.adjoint() is base def test_diagonalizing_gates(self): """Assert that the diagonalizing gates method gives the base's diagonalizing gates.""" base = qml.Hadamard(0) diag_gate = Adjoint(base).diagonalizing_gates()[0] assert isinstance(diag_gate, qml.RY) assert qml.math.allclose(diag_gate.data[0], -np.pi / 4) # pylint: disable=protected-access def test_flatten_unflatten(self): """Test the flatten and unflatten methods.""" # pylint: disable=too-few-public-methods class CustomOp(qml.operation.Operator): pass op = CustomOp(1.2, 2.3, wires=0) adj_op = Adjoint(op) data, metadata = adj_op._flatten() assert len(data) == 1 assert data[0] is op assert metadata == tuple() new_op = type(adj_op)._unflatten(*adj_op._flatten()) qml.assert_equal(adj_op, new_op) class TestAdjointOperation: """Test methods in the AdjointOperation mixin.""" def test_has_generator_true(self): """Test `has_generator` property carries over when base op defines generator.""" base = qml.RX(0.5, 0) op = Adjoint(base) assert op.has_generator is True def test_has_generator_false(self): """Test `has_generator` property carries over when base op does not define a generator.""" base = qml.PauliX(0) op = Adjoint(base) assert op.has_generator is False @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_generator(self): """Assert that the generator of an Adjoint is -1.0 times the base generator.""" base = qml.RX(1.23, wires=0) op = Adjoint(base) qml.assert_equal(base.generator(), -1.0 * op.generator()) def test_no_generator(self): """Test that an adjointed non-Operation raises a GeneratorUndefinedError.""" with pytest.raises(qml.operation.GeneratorUndefinedError): Adjoint(1.0 * qml.PauliX(0)).generator() def test_single_qubit_rot_angles(self): param = 1.234 base = qml.RX(param, wires=0) op = Adjoint(base) base_angles = base.single_qubit_rot_angles() angles = op.single_qubit_rot_angles() for angle1, angle2 in zip(angles, reversed(base_angles)): assert angle1 == -angle2 @pytest.mark.parametrize( "base, basis", ( (qml.RX(1.234, wires=0), "X"), (qml.PauliY("a"), "Y"), (qml.PhaseShift(4.56, wires="b"), "Z"), (qml.SX(-1), "X"), ), ) def test_basis_property(self, base, basis): op = Adjoint(base) assert op.basis == basis def test_control_wires(self): """Test the control_wires of an adjoint are the same as the base op.""" op = Adjoint(qml.CNOT(wires=("a", "b"))) assert op.control_wires == qml.wires.Wires("a") class TestAdjointOperationDiffInfo: """Test differention related properties and methods of AdjointOperation.""" def test_grad_method_None(self): """Test grad_method copies base grad_method when it is None.""" base = qml.PauliX(0) op = Adjoint(base) assert op.grad_method is None @pytest.mark.parametrize("op", (qml.RX(1.2, wires=0),)) def test_grad_method_not_None(self, op): """Make sure the grad_method property of a Adjoint op is the same as the base op.""" assert Adjoint(op).grad_method == op.grad_method @pytest.mark.parametrize( "base", (qml.PauliX(0), qml.RX(1.234, wires=0), qml.Rotation(1.234, wires=0)) ) def test_grad_recipe(self, base): """Test that the grad_recipe of the Adjoint is the same as the grad_recipe of the base.""" assert Adjoint(base).grad_recipe == base.grad_recipe @pytest.mark.parametrize( "base", (qml.RX(1.23, wires=0), qml.Rot(1.23, 2.345, 3.456, wires=0), qml.CRX(1.234, wires=(0, 1))), ) def test_parameter_frequencies(self, base): """Test that the parameter frequencies of an Adjoint are the same as those of the base.""" assert Adjoint(base).parameter_frequencies == base.parameter_frequencies class TestQueueing: """Test that Adjoint operators queue and update base metadata""" def test_queueing(self): """Test queuing and metadata when both Adjoint and base defined inside a recording context.""" with qml.queuing.AnnotatedQueue() as q: base = qml.Rot(1.2345, 2.3456, 3.4567, wires="b") _ = Adjoint(base) assert base not in q assert len(q) == 1 def test_queuing_base_defined_outside(self): """Test that base isn't added to queue if it's defined outside the recording context.""" base = qml.Rot(1.2345, 2.3456, 3.4567, wires="b") with qml.queuing.AnnotatedQueue() as q: op = Adjoint(base) assert len(q) == 1 assert q.queue[0] is op class TestMatrix: """Test the matrix method for a variety of interfaces.""" def test_batching_support(self): """Test that adjoint matrix has batching support.""" x = qml.numpy.array([0.1, 0.2, 0.3]) base = qml.RX(x, wires=0) op = Adjoint(base) mat = op.matrix() compare = qml.RX(-x, wires=0) assert qml.math.allclose(mat, compare.matrix()) assert mat.shape == (3, 2, 2) def check_matrix(self, x, interface): """Compares matrices in a interface independent manner.""" base = qml.RX(x, wires=0) base_matrix = base.matrix() expected = qml.math.conj(qml.math.transpose(base_matrix)) mat = Adjoint(base).matrix() assert qml.math.allclose(expected, mat) assert qml.math.get_interface(mat) == interface @pytest.mark.autograd def test_matrix_autograd(self): """Test the matrix of an Adjoint operator with an autograd parameter.""" self.check_matrix(np.array(1.2345), "autograd") @pytest.mark.jax def test_matrix_jax(self): """Test the matrix of an adjoint operator with a jax parameter.""" import jax.numpy as jnp self.check_matrix(jnp.array(1.2345), "jax") @pytest.mark.torch def test_matrix_torch(self): """Test the matrix of an adjoint oeprator with a torch parameter.""" import torch self.check_matrix(torch.tensor(1.2345), "torch") @pytest.mark.tf def test_matrix_tf(self): """Test the matrix of an adjoint opreator with a tensorflow parameter.""" import tensorflow as tf self.check_matrix(tf.Variable(1.2345), "tensorflow") def test_no_matrix_defined(self): """Test that if the base has no matrix defined, then Adjoint.matrix also raises a MatrixUndefinedError.""" rng = np.random.default_rng(seed=42) shape = qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=2) params = rng.random(shape) base = qml.StronglyEntanglingLayers(params, wires=[0, 1]) with pytest.raises(qml.operation.MatrixUndefinedError): Adjoint(base).matrix() @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_adj_hamiltonian(self): """Test that a we can take the adjoint of a hamiltonian.""" U = qml.Hamiltonian([1.0], [qml.PauliX(wires=0) @ qml.PauliZ(wires=1)]) adj_op = Adjoint(base=U) # hamiltonian = hermitian = self-adjoint mat = adj_op.matrix() true_mat = qml.matrix(U) assert np.allclose(mat, true_mat) def test_sparse_matrix(): """Test that the spare_matrix method returns the adjoint of the base sparse matrix.""" from scipy.sparse import coo_matrix, csr_matrix H = np.array([[6 + 0j, 1 - 2j], [1 + 2j, -1]]) H = csr_matrix(H) base = qml.SparseHamiltonian(H, wires=0) op = Adjoint(base) base_sparse_mat = base.sparse_matrix() base_conj_T = qml.numpy.conj(qml.numpy.transpose(base_sparse_mat)) op_sparse_mat = op.sparse_matrix() assert isinstance(op_sparse_mat, csr_matrix) assert isinstance(op.sparse_matrix(format="coo"), coo_matrix) assert qml.math.allclose(base_conj_T.toarray(), op_sparse_mat.toarray()) class TestEigvals: """Test the Adjoint class adjoint methods.""" @pytest.mark.parametrize( "base", (qml.PauliX(0), qml.Hermitian(np.array([[6 + 0j, 1 - 2j], [1 + 2j, -1]]), wires=0)) ) def test_hermitian_eigvals(self, base): """Test adjoint's eigvals are the same as base eigvals when op is Hermitian.""" base_eigvals = base.eigvals() adj_eigvals = Adjoint(base).eigvals() assert qml.math.allclose(base_eigvals, adj_eigvals) def test_non_hermitian_eigvals(self): """Test that the Adjoint eigvals are the conjugate of the base's eigvals.""" base = qml.SX(0) base_eigvals = base.eigvals() adj_eigvals = Adjoint(base).eigvals() assert qml.math.allclose(qml.math.conj(base_eigvals), adj_eigvals) def test_batching_eigvals(self): """Test that eigenvalues work with batched parameters.""" x = np.array([1.2, 2.3, 3.4]) base = qml.RX(x, 0) adj = Adjoint(base) compare = qml.RX(-x, 0) # eigvals might have different orders assert qml.math.allclose(adj.eigvals()[:, 0], compare.eigvals()[:, 1]) assert qml.math.allclose(adj.eigvals()[:, 1], compare.eigvals()[:, 0]) def test_no_matrix_defined_eigvals(self): """Test that if the base does not define eigvals, The Adjoint raises the same error.""" base = qml.StatePrep([1, 0], wires=0) with pytest.raises(qml.operation.EigvalsUndefinedError): Adjoint(base).eigvals() class TestDecompositionExpand: """Test the decomposition and expand methods for the Adjoint class.""" def test_decomp_custom_adjoint_defined(self): """Test decomposition method when a custom adjoint is defined.""" decomp = Adjoint(qml.Hadamard(0)).decomposition() assert len(decomp) == 1 assert isinstance(decomp[0], qml.Hadamard) def test_expand_custom_adjoint_defined(self): """Test expansion method when a custom adjoint is defined.""" base = qml.Hadamard(0) tape = qml.tape.QuantumScript(Adjoint(base).decomposition()) assert len(tape) == 1 assert isinstance(tape[0], qml.Hadamard) def test_decomp(self): """Test decomposition when base has decomposition but no custom adjoint.""" base = qml.SX(0) base_decomp = base.decomposition() decomp = Adjoint(base).decomposition() for adj_op, base_op in zip(decomp, reversed(base_decomp)): assert isinstance(adj_op, Adjoint) assert adj_op.base.__class__ == base_op.__class__ assert qml.math.allclose(adj_op.data, base_op.data) def test_expand(self): """Test expansion when base has decomposition but no custom adjoint.""" base = qml.SX(0) base_tape = qml.tape.QuantumScript(base.decomposition()) tape = qml.tape.QuantumScript(Adjoint(base).decomposition()) for base_op, adj_op in zip(reversed(base_tape), tape): assert isinstance(adj_op, Adjoint) assert base_op.__class__ == adj_op.base.__class__ assert qml.math.allclose(adj_op.data, base_op.data) def test_no_base_gate_decomposition(self): """Test that when the base gate doesn't have a decomposition, the Adjoint decomposition method raises the proper error.""" nr_wires = 2 rho = np.zeros((2**nr_wires, 2**nr_wires), dtype=np.complex128) rho[0, 0] = 1 # initialize the pure state density matrix for the |0><0| state base = qml.QubitDensityMatrix(rho, wires=(0, 1)) with pytest.raises(qml.operation.DecompositionUndefinedError): Adjoint(base).decomposition() def test_adjoint_of_adjoint(self): """Test that the adjoint an adjoint returns the base operator through both decomposition and expand.""" base = qml.PauliX(0) adj1 = Adjoint(base) adj2 = Adjoint(adj1) assert adj2.decomposition()[0] is base tape = qml.tape.QuantumScript(adj2.decomposition()) assert tape.circuit[0] is base class TestIntegration: """Test the integration of the Adjoint class with qnodes and gradients.""" @pytest.mark.parametrize( "diff_method", ("parameter-shift", "finite-diff", "adjoint", "backprop") ) def test_gradient_adj_rx(self, diff_method): @qml.qnode(qml.device("default.qubit", wires=1), diff_method=diff_method) def circuit(x): Adjoint(qml.RX(x, wires=0)) return qml.expval(qml.PauliY(0)) x = np.array(1.2345, requires_grad=True) res = circuit(x) expected = np.sin(x) assert qml.math.allclose(res, expected) grad = qml.grad(circuit)(x) expected_grad = np.cos(x) assert qml.math.allclose(grad, expected_grad) def test_adj_batching(self): """Test execution of the adjoint of an operation with batched parameters.""" dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def circuit(x): Adjoint(qml.RX(x, wires=0)) return qml.expval(qml.PauliY(0)) x = qml.numpy.array([1.234, 2.34, 3.456]) res = circuit(x) expected = np.sin(x) assert qml.math.allclose(res, expected) ##### TESTS FOR THE ADJOINT CONSTRUCTOR ###### noncallable_objects = [ [qml.Hadamard(1), qml.RX(-0.2, wires=1)], qml.tape.QuantumScript(), ] @pytest.mark.parametrize("obj", noncallable_objects) def test_error_adjoint_on_noncallable(obj): """Test that an error is raised if qml.adjoint is applied to an object that is not callable, as it silently does not have any effect on those.""" with pytest.raises(ValueError, match=f"{type(obj)} is not callable."): adjoint(obj) class TestAdjointConstructorPreconstructedOp: """Test providing an already initalized operator to the transform.""" @pytest.mark.parametrize( "base", (qml.IsingXX(1.23, wires=("c", "d")), qml.QFT(wires=(0, 1, 2))) ) def test_single_op(self, base): """Test passing a single preconstructed op in a queuing context.""" with qml.queuing.AnnotatedQueue() as q: base.queue() out = adjoint(base) assert len(q) == 1 assert q.queue[0] is out def test_single_op_defined_outside_queue_eager(self): """Test if base is defined outside context and the function eagerly simplifies the adjoint, the base is not added to queue.""" base = qml.RX(1.2, wires=0) with qml.queuing.AnnotatedQueue() as q: out = adjoint(base, lazy=False) assert len(q) == 1 assert q.queue[0] is out @pytest.mark.usefixtures("use_legacy_opmath") def test_single_observable(self): """Test passing a single preconstructed observable in a queuing context.""" with qml.queuing.AnnotatedQueue() as q: base = qml.PauliX(0) @ qml.PauliY(1) out = adjoint(base) assert len(q) == 1 assert q.queue[0] is out assert out.base is base assert isinstance(out, Adjoint) qs = qml.tape.QuantumScript.from_queue(q) assert len(qs) == 0 class TestAdjointConstructorDifferentCallableTypes: """Test the adjoint transform on a variety of possible inputs.""" def test_adjoint_single_op_function(self): """Test the adjoint transform on a single operation.""" with qml.queuing.AnnotatedQueue() as q: out = adjoint(qml.RX)(1.234, wires="a") tape = qml.tape.QuantumScript.from_queue(q) assert out is tape[0] assert isinstance(out, Adjoint) qml.assert_equal(out.base, qml.RX(1.234, "a")) def test_adjoint_template(self): """Test the adjoint transform on a template.""" with qml.queuing.AnnotatedQueue() as q: out = adjoint(qml.QFT)(wires=(0, 1, 2)) tape = qml.tape.QuantumScript.from_queue(q) assert len(tape) == 1 assert out is tape[0] assert isinstance(out, Adjoint) assert out.base.__class__ is qml.QFT assert out.wires == qml.wires.Wires((0, 1, 2)) def test_adjoint_on_function(self): """Test adjoint transform on a function""" def func(x, y, z): qml.RX(x, wires=0) qml.RY(y, wires=0) qml.RZ(z, wires=0) x = 1.23 y = 2.34 z = 3.45 with qml.queuing.AnnotatedQueue() as q: out = adjoint(func)(x, y, z) tape = qml.tape.QuantumScript.from_queue(q) assert out == tape.circuit for op in tape: assert isinstance(op, Adjoint) # check order reversed assert tape[0].base.__class__ is qml.RZ assert tape[1].base.__class__ is qml.RY assert tape[2].base.__class__ is qml.RX # check parameters assigned correctly assert tape[0].data == (z,) assert tape[1].data == (y,) assert tape[2].data == (x,) def test_nested_adjoint(self): """Test the adjoint transform on an adjoint transform.""" x = 4.321 with qml.queuing.AnnotatedQueue() as q: out = adjoint(adjoint(qml.RX))(x, wires="b") tape = qml.tape.QuantumScript.from_queue(q) assert out is tape[0] assert isinstance(out, Adjoint) assert isinstance(out.base, Adjoint) assert out.base.base.__class__ is qml.RX assert out.data == (x,) assert out.wires == qml.wires.Wires("b") class TestAdjointConstructorNonLazyExecution: """Test the lazy=False keyword.""" def test_single_decomposeable_op(self): """Test lazy=False for a single op that gets decomposed.""" x = 1.23 with qml.queuing.AnnotatedQueue() as q: base = qml.RX(x, wires="b") out = adjoint(base, lazy=False) assert len(q) == 1 assert q.queue[0] is out assert isinstance(out, qml.RX) assert out.data == (-1.23,) def test_single_nondecomposable_op(self): """Test lazy=false for a single op that can't be decomposed.""" with qml.queuing.AnnotatedQueue() as q: base = qml.S(0) out = adjoint(base, lazy=False) assert len(q) == 1 assert q.queue[0] is out assert isinstance(out, Adjoint) assert isinstance(out.base, qml.S) def test_single_decomposable_op_function(self): """Test lazy=False for a single op callable that gets decomposed.""" x = 1.23 with qml.queuing.AnnotatedQueue() as q: out = adjoint(qml.RX, lazy=False)(x, wires="b") tape = qml.tape.QuantumScript.from_queue(q) assert out is tape[0] assert not isinstance(out, Adjoint) assert isinstance(out, qml.RX) assert out.data == (-x,) def test_single_nondecomposable_op_function(self): """Test lazy=False for a single op function that can't be decomposed.""" with qml.queuing.AnnotatedQueue() as q: out = adjoint(qml.S, lazy=False)(0) tape = qml.tape.QuantumScript.from_queue(q) assert out is tape[0] assert isinstance(out, Adjoint) assert isinstance(out.base, qml.S) def test_mixed_function(self): """Test lazy=False with a function that applies operations of both types.""" x = 1.23 def qfunc(x): qml.RZ(x, wires="b") qml.T("b") with qml.queuing.AnnotatedQueue() as q: out = adjoint(qfunc, lazy=False)(x) tape = qml.tape.QuantumScript.from_queue(q) assert len(tape) == len(out) == 2 assert isinstance(tape[0], Adjoint) assert isinstance(tape[0].base, qml.T) assert isinstance(tape[1], qml.RZ) assert tape[1].data[0] == -x class TestAdjointConstructorOutsideofQueuing: """Test the behaviour of the adjoint transform when not called in a queueing context.""" def test_single_op(self): """Test providing a single op outside of a queuing context.""" x = 1.234 out = adjoint(qml.RZ(x, wires=0)) assert isinstance(out, Adjoint) assert out.base.__class__ is qml.RZ assert out.data == (1.234,) assert out.wires == qml.wires.Wires(0) def test_single_op_eager(self): """Test a single op that can be decomposed in eager mode outside of a queuing context.""" x = 1.234 base = qml.RX(x, wires=0) out = adjoint(base, lazy=False) assert isinstance(out, qml.RX) assert out.data == (-x,) def test_observable(self): """Test providing a preconstructed Observable outside of a queuing context.""" base = 1.0 * qml.PauliX(0) obs = adjoint(base) assert isinstance(obs, Adjoint) assert isinstance(base, qml.operation.Observable) == isinstance( obs, qml.operation.Observable ) assert obs.base is base def test_single_op_function(self): """Test the transform on a single op as a callable outside of a queuing context.""" x = 1.234 out = adjoint(qml.IsingXX)(x, wires=(0, 1)) assert isinstance(out, Adjoint) assert out.base.__class__ is qml.IsingXX assert out.data == (1.234,) assert out.wires == qml.wires.Wires((0, 1)) def test_function(self): """Test the transform on a function outside of a queuing context.""" def func(wire): qml.S(wire) qml.SX(wire) wire = 1.234 out = adjoint(func)(wire) assert len(out) == 2 assert all(isinstance(op, Adjoint) for op in out) assert all(op.wires == qml.wires.Wires(wire) for op in out) def test_nonlazy_op_function(self): """Test non-lazy mode on a simplifiable op outside of a queuing context.""" out = adjoint(qml.PauliX, lazy=False)(0) assert not isinstance(out, Adjoint) assert isinstance(out, qml.PauliX) class TestAdjointConstructorIntegration: """Test circuit execution and gradients with the adjoint transform.""" def test_single_op(self): """Test the adjoint of a single op against analytically expected results.""" @qml.qnode(qml.device("default.qubit", wires=1)) def circ(): qml.PauliX(0) adjoint(qml.S)(0) return qml.state() res = circ() expected = np.array([0, -1j]) assert np.allclose(res, expected) @pytest.mark.autograd @pytest.mark.parametrize("diff_method", ("backprop", "adjoint", "parameter-shift")) def test_gradient_autograd(self, diff_method): """Test gradients through the adjoint transform with autograd.""" import autograd @qml.qnode(qml.device("default.qubit", wires=1), diff_method=diff_method) def circ(x): adjoint(qml.RX)(x, wires=0) return qml.expval(qml.PauliY(0)) x = autograd.numpy.array(0.234) expected_res = np.sin(x) expected_grad = np.cos(x) assert qml.math.allclose(circ(x), expected_res) assert qml.math.allclose( autograd.grad(circ)(x), expected_grad # pylint: disable=no-value-for-parameter ) @pytest.mark.jax @pytest.mark.parametrize("diff_method", ("backprop", "adjoint", "parameter-shift")) def test_gradient_jax(self, diff_method): """Test gradients through the adjoint transform with jax.""" import jax @qml.qnode(qml.device("default.qubit", wires=1), diff_method=diff_method) def circ(x): adjoint(qml.RX)(x, wires=0) return qml.expval(qml.PauliY(0)) x = jax.numpy.array(0.234) expected_res = jax.numpy.sin(x) expected_grad = jax.numpy.cos(x) assert qml.math.allclose(circ(x), expected_res) assert qml.math.allclose(jax.grad(circ)(x), expected_grad) @pytest.mark.torch @pytest.mark.parametrize("diff_method", ("backprop", "adjoint", "parameter-shift")) def test_gradient_torch(self, diff_method): """Test gradients through the adjoint transform with torch.""" import torch @qml.qnode(qml.device("default.qubit", wires=1), diff_method=diff_method) def circ(x): adjoint(qml.RX)(x, wires=0) return qml.expval(qml.PauliY(0)) x = torch.tensor(0.234, requires_grad=True) y = circ(x) y.backward() assert qml.math.allclose(y, torch.sin(x)) assert qml.math.allclose(x.grad, torch.cos(x)) @pytest.mark.tf @pytest.mark.parametrize("diff_method", ("backprop", "adjoint", "parameter-shift")) def test_gradient_tf(self, diff_method): """Test gradients through the adjoint transform with tensorflow.""" import tensorflow as tf @qml.qnode(qml.device("default.qubit", wires=1), diff_method=diff_method) def circ(x): adjoint(qml.RX)(x, wires=0) return qml.expval(qml.PauliY(0)) x = tf.Variable(0.234, dtype=tf.float64) with tf.GradientTape() as tape: y = circ(x) grad = tape.gradient(y, x) assert qml.math.allclose(y, tf.sin(x)) assert qml.math.allclose(grad, tf.cos(x))
pennylane/tests/ops/op_math/test_adjoint.py/0
{ "file_path": "pennylane/tests/ops/op_math/test_adjoint.py", "repo_id": "pennylane", "token_count": 18334 }
85
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """ Unit tests for the available built-in discrete-variable quantum operations. Only tests over multiple types of operations should exist in this file. Type-specific tests should go in the more specific file. """ # pylint: disable=too-few-public-methods import pytest from gate_data import I import pennylane as qml class TestOperations: """Tests for the operations""" @pytest.mark.parametrize( "op", [ (qml.Hadamard(wires=0)), (qml.PauliX(wires=0)), (qml.PauliY(wires=0)), (qml.PauliZ(wires=0)), (qml.S(wires=0)), (qml.T(wires=0)), (qml.SX(wires=0)), (qml.RX(0.3, wires=0)), (qml.RY(0.3, wires=0)), (qml.RZ(0.3, wires=0)), (qml.PhaseShift(0.3, wires=0)), (qml.Rot(0.3, 0.4, 0.5, wires=0)), ], ) def test_single_qubit_rot_angles(self, op): """Tests that the Rot gates yielded by single_qubit_rot_angles are equivalent to the true operations up to a global phase.""" angles = op.single_qubit_rot_angles() obtained_mat = qml.Rot(*angles, wires=0).matrix() # Check whether the two matrices are each others conjugate transposes mat_product = qml.math.dot(op.matrix(), qml.math.conj(obtained_mat.T)) mat_product /= mat_product[0, 0] assert qml.math.allclose(mat_product, I)
pennylane/tests/ops/qubit/test_all_qubit_ops.py/0
{ "file_path": "pennylane/tests/ops/qubit/test_all_qubit_ops.py", "repo_id": "pennylane", "token_count": 832 }
86
# Copyright 2018-2022 Xanadu Quantum Technologies Inc. # 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. """ Unit tests for the available built-in parametric qutrit operations. """ # pylint: disable=unnecessary-lambda-assignment, too-few-public-methods, too-many-arguments import copy from functools import reduce import numpy as np import pytest from gate_data import TCLOCK, TSHIFT import pennylane as qml from pennylane import numpy as npp from pennylane.ops.qutrit import validate_subspace from pennylane.wires import Wires PARAMETRIZED_OPERATIONS = [ qml.TRX(0.123, wires=0, subspace=(0, 1)), qml.TRX(0.123, wires=0, subspace=(0, 2)), qml.TRX(0.123, wires=0, subspace=(1, 2)), qml.TRY(0.123, wires=0, subspace=(0, 1)), qml.TRY(0.123, wires=0, subspace=(0, 2)), qml.TRY(0.123, wires=0, subspace=(1, 2)), qml.TRZ(0.123, wires=0, subspace=(0, 1)), qml.TRZ(0.123, wires=0, subspace=(0, 2)), qml.TRZ(0.123, wires=0, subspace=(1, 2)), qml.QutritUnitary(TSHIFT, wires=0), qml.ControlledQutritUnitary(TCLOCK, wires=[0], control_wires=[2]), ] BROADCASTED_OPERATIONS = [ qml.TRX(np.array([0.142, -0.61, 2.3]), wires=0, subspace=(1, 2)), qml.TRY(np.array([0.142, -0.61, 2.3]), wires=0, subspace=(0, 2)), qml.TRZ(np.array([0.142, -0.61, 2.3]), wires=0, subspace=(0, 1)), qml.QutritUnitary(np.array([TSHIFT, TCLOCK]), wires=0), qml.ControlledQutritUnitary(np.array([TSHIFT, TCLOCK]), wires=[0], control_wires=[2]), ] NON_PARAMETRIZED_OPERATIONS = [ qml.TShift(wires=0), qml.TClock(wires=0), qml.TAdd(wires=[0, 1]), qml.TSWAP(wires=[0, 1]), ] ALL_OPERATIONS = NON_PARAMETRIZED_OPERATIONS + PARAMETRIZED_OPERATIONS dot_broadcasted = lambda a, b: np.einsum("...ij,...jk->...ik", a, b) multi_dot_broadcasted = lambda matrices: reduce(dot_broadcasted, matrices) class TestOperations: @pytest.mark.parametrize("op", ALL_OPERATIONS + BROADCASTED_OPERATIONS) def test_parametrized_op_copy(self, op, tol): """Tests that copied parametrized ops function as expected""" copied_op = copy.copy(op) assert np.allclose(op.matrix(), copied_op.matrix(), atol=tol) op = qml.adjoint(op) copied_op2 = copy.copy(op) assert np.allclose(op.matrix(), copied_op2.matrix(), atol=tol) @pytest.mark.parametrize("op", PARAMETRIZED_OPERATIONS) def test_adjoint_unitaries(self, op, tol): """Test that matrices of adjoint operations behave correctly""" op_d = op.adjoint() res1 = np.dot(op.matrix(), op_d.matrix()) res2 = np.dot(op_d.matrix(), op.matrix()) assert np.allclose(res1, np.eye(3 ** len(op.wires)), atol=tol) assert np.allclose(res2, np.eye(3 ** len(op.wires)), atol=tol) assert op.wires == op_d.wires @pytest.mark.parametrize("op", BROADCASTED_OPERATIONS) def test_adjoint_unitaries_broadcasted(self, op, tol): """Test that matrices of adjoint operations with broadcasting behave correctly""" op_d = op.adjoint() res1 = dot_broadcasted(op.matrix(), op_d.matrix()) res2 = dot_broadcasted(op_d.matrix(), op.matrix()) I = [np.eye(3 ** len(op.wires))] * op.batch_size assert np.allclose(res1, I, atol=tol) assert np.allclose(res2, I, atol=tol) assert op.wires == op_d.wires class TestParameterFrequencies: @pytest.mark.parametrize("op", PARAMETRIZED_OPERATIONS) def test_parameter_frequencies_match_generator(self, op, tol): """Check that parameter frequencies of parametrized operations are defined correctly.""" if not qml.operation.has_gen(op): pytest.skip(f"Operation {op.name} does not have a generator defined to test against.") gen = op.generator() mat = gen.matrix() gen_eigvals = np.round(np.linalg.eigvalsh(mat), 8) freqs_from_gen = qml.gradients.eigvals_to_frequencies(tuple(gen_eigvals)) freqs = op.parameter_frequencies assert np.allclose(freqs, freqs_from_gen, atol=tol) # TODO: Add tests for decompositions matrix_data = [ (qml.TRX, 0, (0, 1), np.eye(3)), (qml.TRX, 0, (1, 2), np.eye(3)), (qml.TRX, 0, (0, 2), np.eye(3)), (qml.TRY, 0, (0, 1), np.eye(3)), (qml.TRY, 0, (1, 2), np.eye(3)), (qml.TRY, 0, (0, 2), np.eye(3)), (qml.TRZ, 0, (0, 1), np.eye(3)), (qml.TRZ, 0, (1, 2), np.eye(3)), (qml.TRZ, 0, (0, 2), np.eye(3)), ( qml.TRX, np.pi / 2, (0, 1), np.array([[1, -1j, 0], [-1j, 1, 0], [0, 0, np.sqrt(2)]]) / np.sqrt(2), ), ( qml.TRX, np.pi / 2, (1, 2), np.array([[np.sqrt(2), 0, 0], [0, 1, -1j], [0, -1j, 1]]) / np.sqrt(2), ), ( qml.TRX, np.pi / 2, (0, 2), np.array([[1, 0, -1j], [0, np.sqrt(2), 0], [-1j, 0, 1]]) / np.sqrt(2), ), ( qml.TRY, np.pi / 2, (0, 1), np.array([[1, -1, 0], [1, 1, 0], [0, 0, np.sqrt(2)]]) / np.sqrt(2), ), ( qml.TRY, np.pi / 2, (1, 2), np.array([[np.sqrt(2), 0, 0], [0, 1, -1], [0, 1, 1]]) / np.sqrt(2), ), ( qml.TRY, np.pi / 2, (0, 2), np.array([[1, 0, -1], [0, np.sqrt(2), 0], [1, 0, 1]]) / np.sqrt(2), ), ( qml.TRZ, np.pi / 2, (0, 1), np.diag(np.exp([-1j * np.pi / 4, 1j * np.pi / 4, 0])), ), ( qml.TRZ, np.pi / 2, (1, 2), np.diag(np.exp([0, -1j * np.pi / 4, 1j * np.pi / 4])), ), ( qml.TRZ, np.pi / 2, (0, 2), np.diag(np.exp([-1j * np.pi / 4, 0, 1j * np.pi / 4])), ), (qml.TRX, np.pi, (0, 1), -1j * np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1j]])), (qml.TRX, np.pi, (1, 2), -1j * np.array([[1j, 0, 0], [0, 0, 1], [0, 1, 0]])), (qml.TRX, np.pi, (0, 2), -1j * np.array([[0, 0, 1], [0, 1j, 0], [1, 0, 0]])), (qml.TRY, np.pi, (0, 1), np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]])), (qml.TRY, np.pi, (1, 2), np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]])), (qml.TRY, np.pi, (0, 2), np.array([[0, 0, -1], [0, 1, 0], [1, 0, 0]])), (qml.TRZ, np.pi, (0, 1), -1j * np.diag([1, -1, 1j])), (qml.TRZ, np.pi, (1, 2), -1j * np.diag([1j, 1, -1])), (qml.TRZ, np.pi, (0, 2), -1j * np.diag([1, 1j, -1])), ( qml.TRX, np.array([np.pi / 2] * 2), (0, 1), np.tensordot( [1, 1], np.array([[1, -1j, 0], [-1j, 1, 0], [0, 0, np.sqrt(2)]]) / np.sqrt(2), axes=0 ), ), ( qml.TRX, np.array([np.pi / 2] * 2), (1, 2), np.tensordot( [1, 1], np.array([[np.sqrt(2), 0, 0], [0, 1, -1j], [0, -1j, 1]]) / np.sqrt(2), axes=0 ), ), ( qml.TRX, np.array([np.pi / 2] * 2), (0, 2), np.tensordot( [1, 1], np.array([[1, 0, -1j], [0, np.sqrt(2), 0], [-1j, 0, 1]]) / np.sqrt(2), axes=0 ), ), ( qml.TRY, np.array([np.pi / 2] * 2), (0, 1), np.tensordot( [1, 1], np.array([[1, -1, 0], [1, 1, 0], [0, 0, np.sqrt(2)]]) / np.sqrt(2), axes=0 ), ), ( qml.TRY, np.array([np.pi / 2] * 2), (1, 2), np.tensordot( [1, 1], np.array([[np.sqrt(2), 0, 0], [0, 1, -1], [0, 1, 1]]) / np.sqrt(2), axes=0 ), ), ( qml.TRY, np.array([np.pi / 2] * 2), (0, 2), np.tensordot( [1, 1], np.array([[1, 0, -1], [0, np.sqrt(2), 0], [1, 0, 1]]) / np.sqrt(2), axes=0 ), ), ( qml.TRZ, np.array([np.pi / 2] * 2), (0, 1), np.tensordot([1, 1], np.diag(np.exp([-1j * np.pi / 4, 1j * np.pi / 4, 0])), axes=0), ), ( qml.TRZ, np.array([np.pi / 2] * 2), (1, 2), np.tensordot([1, 1], np.diag(np.exp([0, -1j * np.pi / 4, 1j * np.pi / 4])), axes=0), ), ( qml.TRZ, np.array([np.pi / 2] * 2), (0, 2), np.tensordot([1, 1], np.diag(np.exp([-1j * np.pi / 4, 0, 1j * np.pi / 4])), axes=0), ), ] @pytest.mark.parametrize("op, theta, subspace, expected", matrix_data) class TestMatrix: """Tests for the matrix of parametrized qutrit operations.""" def test_matrix(self, op, theta, subspace, expected, tol): """Test that matrices of parametric qutrit operations are correct""" assert np.allclose(op.compute_matrix(theta, subspace=subspace), expected, atol=tol, rtol=0) assert np.allclose( op(theta, wires=0, subspace=subspace).matrix(), expected, atol=tol, rtol=0 ) @pytest.mark.tf def test_matrix_tf(self, op, theta, subspace, expected, tol): """Test that compute_matrix works with tensorflow variables""" import tensorflow as tf theta = tf.Variable(theta, dtype="float64") expected = tf.convert_to_tensor(expected, dtype="complex128") assert qml.math.allclose( op.compute_matrix(theta, subspace=subspace), expected, atol=tol, rtol=0 ) assert qml.math.allclose( op(theta, wires=0, subspace=subspace).matrix(), expected, atol=tol, rtol=0 ) label_data = [ (qml.TRX(1.23456, wires=0), "TRX", "TRX\n(1.23)", "TRX\n(1)", "TRX\n(1)†"), (qml.TRY(1.23456, wires=0), "TRY", "TRY\n(1.23)", "TRY\n(1)", "TRY\n(1)†"), (qml.TRZ(1.23456, wires=0), "TRZ", "TRZ\n(1.23)", "TRZ\n(1)", "TRZ\n(1)†"), ] label_data_broadcasted = [ (qml.TRX(np.array([1.23, 4.56]), wires=0), "TRX", "TRX", "TRX", "TRX†"), (qml.TRY(np.array([1.23, 4.56]), wires=0), "TRY", "TRY", "TRY", "TRY†"), (qml.TRZ(np.array([1.23, 4.56]), wires=0), "TRZ", "TRZ", "TRZ", "TRZ†"), ] class TestLabel: """Test the label method on parametric ops""" @pytest.mark.parametrize("op, label1, label2, label3, label4", label_data) def test_label_method(self, op, label1, label2, label3, label4): """Test label method with plain scalars.""" assert op.label() == label1 assert op.label(decimals=2) == label2 assert op.label(decimals=0) == label3 op = qml.adjoint(op) assert op.label(decimals=0) == label4 @pytest.mark.parametrize("op, label1, label2, label3, label4", label_data_broadcasted) def test_label_method_broadcasted(self, op, label1, label2, label3, label4): """Test broadcasted label method with plain scalars.""" assert op.label() == label1 assert op.label(decimals=2) == label2 assert op.label(decimals=0) == label3 op = qml.adjoint(op) assert op.label(decimals=0) == label4 @pytest.mark.tf def test_label_tf(self): """Test label methods work with tensorflow variables""" import tensorflow as tf op1 = qml.TRX(tf.Variable(0.123456), wires=0) assert op1.label(decimals=2) == "TRX\n(0.12)" @pytest.mark.torch def test_label_torch(self): """Test label methods work with torch tensors""" import torch op1 = qml.TRX(torch.tensor(1.23456), wires=0) assert op1.label(decimals=2) == "TRX\n(1.23)" @pytest.mark.jax def test_label_jax(self): """Test the label method works with jax""" import jax op1 = qml.TRX(jax.numpy.array(1.23456), wires=0) assert op1.label(decimals=2) == "TRX\n(1.23)" def test_string_parameter(self): """Test labelling works if variable is a string instead of a float.""" op1 = qml.TRX("x", wires=0) assert op1.label() == "TRX" assert op1.label(decimals=0) == "TRX\n(x)" def test_string_parameter_broadcasted(self): """Test labelling works (i.e. does not raise an Error) if variable is a string instead of a float.""" op1 = qml.TRX(np.array(["x0", "x1", "x2"]), wires=0) assert op1.label() == "TRX" assert op1.label(decimals=0) == "TRX" pow_parametric_ops = ( qml.TRX(1.234, wires=0), qml.TRY(1.234, wires=0), qml.TRZ(1.234, wires=0), ) class TestParametricPow: """Test that the `pow` method works for parametric qutrit operations.""" @pytest.mark.parametrize("op", pow_parametric_ops) @pytest.mark.parametrize("n", (2, -1, 0.2631, -0.987)) def test_pow_method_parametric_ops(self, op, n): """Assert that a matrix raised to a power is the same as multiplying the data by n for relevant ops.""" pow_op = op.pow(n) assert len(pow_op) == 1 assert pow_op[0].__class__ is op.__class__ assert all((qml.math.allclose(d1, d2 * n) for d1, d2 in zip(pow_op[0].data, op.data))) @pytest.mark.parametrize("op", pow_parametric_ops) @pytest.mark.parametrize("n", (3, -2)) def test_pow_matrix(self, op, n): """Test that the matrix of an op first raised to a power is the same as the matrix raised to the power. This test only can work for integer powers.""" op_mat = qml.matrix(op) # Can't use qml.matrix(op.pow)(n) because qml.matrix is hardcoded to work with qubits # TODO: update this test once qml.matrix is updated pow_mat = op.pow(n)[0].matrix() assert qml.math.allclose(qml.math.linalg.matrix_power(op_mat, n), pow_mat) control_data = [ (qml.TRX(1.234, wires=0), Wires([])), (qml.TRY(1.234, wires=0), Wires([])), (qml.TRZ(1.234, wires=0), Wires([])), ] @pytest.mark.parametrize("op, control_wires", control_data) def test_control_wires(op, control_wires): """Test the ``control_wires`` attribute for parametrized operations.""" assert op.control_wires == control_wires qutrit_subspace_error_data = [ ([1, 1], "Elements of subspace list must be unique."), ([1, 2, 3], "The subspace must be a sequence with"), ([3, 1], "Elements of the subspace must be 0, 1, or 2."), ([3, 3], "Elements of the subspace must be 0, 1, or 2."), ([1], "The subspace must be a sequence with"), (0, "The subspace must be a sequence with two unique"), ] @pytest.mark.parametrize("subspace, err_msg", qutrit_subspace_error_data) def test_qutrit_subspace_op_errors(subspace, err_msg): """Test that the correct errors are raised when subspace is incorrectly defined""" with pytest.raises(ValueError, match=err_msg): _ = validate_subspace(subspace) @pytest.mark.parametrize( "op, obs, grad_fn", [ (qml.TRX, qml.GellMann(0, 3), lambda phi: -np.sin(phi)), (qml.TRY, qml.GellMann(0, 1), np.cos), (qml.TRZ, qml.GellMann(0, 1), lambda phi: -np.sin(phi)), ], ) class TestGrad: """Test that the gradients for qutrit parametrized operations are correct""" # ``default.qutrit`` doesn't currently support device, adjoint, or backprop diff methods diff_methods = ["parameter-shift", "finite-diff", "best", "backprop"] @pytest.mark.autograd @pytest.mark.parametrize("phi", npp.linspace(0, 2 * np.pi, 7, requires_grad=True)) @pytest.mark.parametrize("diff_method", diff_methods) def test_differentiability(self, op, obs, grad_fn, phi, diff_method, tol): """Test that parametrized rotations are differentiable and the gradient is correct""" dev = qml.device("default.qutrit", wires=1) @qml.qnode(dev, diff_method=diff_method) def circuit(phi): if op is qml.TRZ: # Without Hadamard the derivative is always 0 qml.THadamard(wires=0, subspace=(0, 1)) op(phi, wires=0) return qml.expval(obs) grad = np.squeeze(qml.grad(circuit)(phi)) assert np.isclose(grad, grad_fn(phi), atol=tol, rtol=0) @pytest.mark.autograd @pytest.mark.parametrize("diff_method", diff_methods) def test_differentiability_broadcasted(self, op, obs, grad_fn, diff_method, tol): """Test that differentiation of parametrized operations with broadcasting works.""" if diff_method in ("finite-diff", "parameter-shift"): pytest.xfail() phi = npp.linspace(0, 2 * np.pi, 7, requires_grad=True) dev = qml.device("default.qutrit", wires=1) @qml.qnode(dev, diff_method=diff_method) def circuit(phi): if op is qml.TRZ: # Without Hadamard the derivative is always 0 qml.THadamard(wires=0, subspace=(0, 1)) op(phi, wires=0) return qml.expval(obs) jac = qml.jacobian(circuit)(phi) assert np.allclose(jac, np.diag(grad_fn(phi)), atol=tol, rtol=0) @pytest.mark.jax @pytest.mark.parametrize("phi", npp.linspace(0, 2 * np.pi, 7)) @pytest.mark.parametrize("diff_method", diff_methods) def test_differentiability_jax(self, op, obs, grad_fn, phi, diff_method, tol): """Test that parametrized operations are differentiable with JAX and the gradient is correct""" import jax import jax.numpy as jnp dev = qml.device("default.qutrit", wires=1) @qml.qnode(dev, diff_method=diff_method) def circuit(phi): if op is qml.TRZ: # Without Hadamard the derivative is always 0 qml.THadamard(wires=0, subspace=(0, 1)) op(phi, wires=0) return qml.expval(obs) phi = jnp.array(phi) grad = np.squeeze(jax.grad(circuit)(phi)) assert np.isclose(grad, grad_fn(phi), atol=tol, rtol=0) @pytest.mark.jax @pytest.mark.parametrize("diff_method", diff_methods) def test_differentiability_jax_broadcasted(self, op, obs, grad_fn, diff_method, tol): """Test that differentiation of parametrized operations in JAX with broadcasting works.""" if diff_method in ("finite-diff", "parameter-shift"): pytest.xfail() import jax import jax.numpy as jnp dev = qml.device("default.qutrit", wires=1) @qml.qnode(dev, diff_method=diff_method) def circuit(phi): if op is qml.TRZ: # Without Hadamard the derivative is always 0 qml.THadamard(wires=0, subspace=(0, 1)) op(phi, wires=0) return qml.expval(obs) phi = jnp.linspace(0, 2 * np.pi, 7) jac = jax.jacobian(circuit)(phi) assert np.allclose(jac, np.diag(grad_fn(phi)), atol=tol, rtol=0) @pytest.mark.torch @pytest.mark.parametrize("phi", npp.linspace(0, 2 * np.pi, 7)) @pytest.mark.parametrize("diff_method", diff_methods) def test_differentiability_torch(self, op, obs, grad_fn, phi, diff_method, tol): """Test that parametrized operations are differentiable with Torch and the gradient is correct""" import torch dev = qml.device("default.qutrit", wires=1) @qml.qnode(dev, diff_method=diff_method) def circuit(phi): if op is qml.TRZ: # Without Hadamard the derivative is always 0 qml.THadamard(wires=0, subspace=(0, 1)) op(phi, wires=0) return qml.expval(obs) phi_torch = torch.tensor(phi, requires_grad=True, dtype=torch.float64) grad = torch.autograd.grad(circuit(phi_torch), phi_torch) assert qml.math.isclose(grad, grad_fn(phi), atol=tol, rtol=0) @pytest.mark.torch @pytest.mark.parametrize("diff_method", diff_methods) def test_differentiability_torch_broadcasted(self, op, obs, grad_fn, diff_method, tol): """Test that differentiation of parametrized operations in Torch with broadcasting works.""" if diff_method in ("finite-diff", "parameter-shift"): pytest.xfail() import torch dev = qml.device("default.qutrit", wires=1) @qml.qnode(dev, diff_method=diff_method) def circuit(phi): if op is qml.TRZ: # Without Hadamard the derivative is always 0 qml.THadamard(wires=0, subspace=(0, 1)) op(phi, wires=0) return qml.expval(obs) phi_torch = torch.linspace(0, 2 * np.pi, 7, requires_grad=True, dtype=torch.float64) jac = torch.autograd.functional.jacobian(circuit, phi_torch) phi = phi_torch.detach().numpy() assert qml.math.allclose(jac, np.diag(grad_fn(phi)), atol=tol, rtol=0) @pytest.mark.tf @pytest.mark.parametrize("phi", npp.linspace(0, 2 * np.pi, 7)) @pytest.mark.parametrize("diff_method", diff_methods) def test_differentiability_tf(self, op, obs, grad_fn, phi, diff_method, tol): """Test that parametrized operations are differentiable with TensorFlow and the gradient is correct""" import tensorflow as tf dev = qml.device("default.qutrit", wires=1) @qml.qnode(dev, diff_method=diff_method) def circuit(phi): if op is qml.TRZ: # Without Hadamard the derivative is always 0 qml.THadamard(wires=0, subspace=(0, 1)) op(phi, wires=0) return qml.expval(obs) phi_tf = tf.Variable(phi) with tf.GradientTape() as tape: result = circuit(phi_tf) res = tape.gradient(result, phi_tf) assert qml.math.isclose(res, grad_fn(phi), atol=tol, rtol=0) @pytest.mark.tf @pytest.mark.parametrize("diff_method", diff_methods) def test_differentiability_tf_broadcasted(self, op, obs, grad_fn, diff_method, tol): """Test that differentiation of parametrized operations in TensorFlow with broadcasting works.""" if diff_method in ("finite-diff", "parameter-shift"): pytest.xfail() import tensorflow as tf dev = qml.device("default.qutrit", wires=1) @qml.qnode(dev, diff_method=diff_method) def circuit(phi): if op is qml.TRZ: # Without Hadamard the derivative is always 0 qml.THadamard(wires=0, subspace=(0, 1)) op(phi, wires=0) return qml.expval(obs) phi = np.linspace(0, 2 * np.pi, 7) phi_tf = tf.Variable(phi) with tf.GradientTape() as tape: result = circuit(phi_tf) res = tape.jacobian(result, phi_tf) expected = tf.Variable(np.diag(grad_fn(phi))) assert qml.math.allclose(res, expected, atol=tol, rtol=0)
pennylane/tests/ops/qutrit/test_qutrit_parametric_ops.py/0
{ "file_path": "pennylane/tests/ops/qutrit/test_qutrit_parametric_ops.py", "repo_id": "pennylane", "token_count": 11131 }
87
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """ Unit tests for the ``RiemannianGradientOptimizer``. """ import numpy as np import pytest from scipy.sparse.linalg import expm import pennylane as qml from pennylane.optimize import RiemannianGradientOptimizer def circuit_1(): """Simple circuit.""" qml.Hadamard(wires=[0]) qml.Hadamard(wires=[1]) def circuit_2(): """Simply parameterized circuit.""" qml.RX(0.1, wires=[0]) qml.RY(0.5, wires=[1]) qml.CNOT(wires=[0, 1]) qml.RY(0.6, wires=[0]) def circuit_3(): """Three-qubit circuit.""" qml.RY(0.5, wires=[0]) qml.RY(0.6, wires=[1]) qml.RY(0.7, wires=[2]) qml.CNOT(wires=[0, 1]) qml.CNOT(wires=[1, 2]) qml.RX(-0.6, wires=[0]) qml.RX(-0.3, wires=[1]) qml.RX(-0.2, wires=[2]) hamiltonian_1 = qml.Hamiltonian( coeffs=[-1.0] * 3, observables=[qml.PauliX(0), qml.PauliZ(1), qml.PauliY(0) @ qml.PauliX(1)], ) hamiltonian_2 = qml.Hamiltonian( coeffs=[-0.2, 0.3, -0.15], observables=[ qml.PauliY(1), qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliX(0) @ qml.PauliX(1), ], ) hamiltonian_3 = qml.Hamiltonian( coeffs=[-2.0], observables=[qml.PauliY(0) @ qml.PauliY(1) @ qml.PauliY(2)] ) @pytest.mark.parametrize( "circuit,hamiltonian", [ (circuit_1, hamiltonian_1), (circuit_1, hamiltonian_2), (circuit_2, hamiltonian_1), (circuit_2, hamiltonian_2), (circuit_3, hamiltonian_3), ], ) def test_riemannian_gradient_omegas(circuit, hamiltonian): """Test that we calculate the Riemannian gradient coefficients Tr{[rho, H] P_j} correctly.""" # pylint: disable=no-member nqubits = max(max(ps.wires) for ps in hamiltonian.ops) + 1 wires = range(nqubits) dev = qml.device("default.qubit", wires=nqubits) @qml.qnode(dev) def get_state(): circuit() return qml.state() @qml.qnode(dev) def test_circuit(): circuit() return qml.expval(hamiltonian) phi = get_state() rho = np.outer(phi, phi.conj()) hamiltonian_np = hamiltonian.sparse_matrix(wire_order=wires).toarray() riemannian_gradient_np = hamiltonian_np @ rho - rho @ hamiltonian_np opt = RiemannianGradientOptimizer(circuit=test_circuit) ops = opt.get_su_n_operators(None)[0] omegas_np = [] for op in ops: op = qml.math.expand_matrix(op.matrix(), op.wires, wires) omegas_np.append(1j * np.trace(riemannian_gradient_np @ op)) omegas = opt.get_omegas() assert np.allclose(omegas, omegas_np) @pytest.mark.parametrize( "circuit,hamiltonian", [ (circuit_1, hamiltonian_1), (circuit_1, hamiltonian_2), (circuit_2, hamiltonian_1), (circuit_2, hamiltonian_2), (circuit_3, hamiltonian_3), ], ) def test_riemannian_gradient_omegas_restricted(circuit, hamiltonian): """Test that we calculate the (restricted) Riemannian gradient coefficients correctly.""" # pylint: disable=no-member nqubits = max(max(ps.wires) for ps in hamiltonian.ops) + 1 wires = range(nqubits) dev = qml.device("default.qubit", wires=nqubits) @qml.qnode(dev) def get_state(): circuit() return qml.state() @qml.qnode(dev) def test_circuit(): circuit() return qml.expval(hamiltonian) phi = get_state() rho = np.outer(phi, phi.conj()) hamiltonian_np = hamiltonian.sparse_matrix(wire_order=wires).toarray() riemannian_gradient_np = hamiltonian_np @ rho - rho @ hamiltonian_np restriction = qml.Hamiltonian( coeffs=[1.0] * 3, observables=[qml.PauliX(0), qml.PauliY(1), qml.PauliY(0) @ qml.PauliY(1)], ) opt = RiemannianGradientOptimizer(circuit=test_circuit, restriction=restriction) ops = opt.get_su_n_operators(restriction)[0] omegas_np = [] for op in ops: op = qml.math.expand_matrix(op.matrix(), op.wires, wires) omegas_np.append(1j * np.trace(riemannian_gradient_np @ op)) omegas = opt.get_omegas() assert np.allclose(omegas, omegas_np) @pytest.mark.parametrize( "circuit,hamiltonian", [ (circuit_1, hamiltonian_1), (circuit_1, hamiltonian_2), (circuit_2, hamiltonian_1), (circuit_3, hamiltonian_3), ], ) def test_riemannian_gradient_evolution(circuit, hamiltonian): """Test that the optimizer produces the correct unitary to append.""" # pylint: disable=no-member nqubits = max(max(ps.wires) for ps in hamiltonian.ops) + 1 wires = range(nqubits) dev = qml.device("default.qubit", wires=nqubits) @qml.qnode(dev) def get_state(): circuit() return qml.state() @qml.qnode(dev) def test_circuit(): circuit() return qml.expval(hamiltonian) phi = get_state() rho = np.outer(phi, phi.conj()) hamiltonian_np = hamiltonian.sparse_matrix(wire_order=wires).toarray() riemannian_gradient_np = hamiltonian_np @ rho - rho @ hamiltonian_np phi_exact = expm(-0.1 * riemannian_gradient_np * 2**nqubits) @ phi rho_exact = np.outer(phi_exact, phi_exact.conj()) opt = RiemannianGradientOptimizer(circuit=test_circuit, stepsize=0.1, exact=True) opt.step_and_cost() cost_pl = opt.circuit() cost_exact = np.trace(rho_exact @ hamiltonian_np) assert np.allclose(cost_pl, cost_exact, atol=1e-4) @pytest.mark.parametrize( "circuit,hamiltonian", [ (circuit_1, hamiltonian_1), (circuit_1, hamiltonian_2), (circuit_2, hamiltonian_1), (circuit_2, hamiltonian_2), (circuit_3, hamiltonian_3), ], ) def test_riemannian_gradient_step(circuit, hamiltonian): """Test that we can take subsequent steps with the optimizer.""" nqubits = max(max(ps.wires) for ps in hamiltonian.ops) + 1 dev = qml.device("default.qubit", wires=nqubits) @qml.qnode(dev) def test_circuit(): circuit() return qml.expval(hamiltonian) opt = RiemannianGradientOptimizer(circuit=test_circuit) opt.step() opt.step() @pytest.mark.parametrize( "circuit,hamiltonian", [ (circuit_1, hamiltonian_1), (circuit_1, hamiltonian_2), (circuit_2, hamiltonian_1), (circuit_2, hamiltonian_2), (circuit_3, hamiltonian_3), ], ) def test_riemannian_gradient_step_trotterstep(circuit, hamiltonian): """Test that we can take subsequent steps with the optimizer.""" nqubits = max(max(ps.wires) for ps in hamiltonian.ops) + 1 dev = qml.device("default.qubit", wires=nqubits) @qml.qnode(dev) def test_circuit(): circuit() return qml.expval(hamiltonian) opt = RiemannianGradientOptimizer(circuit=test_circuit, trottersteps=3) opt.step() opt.step() def test_riemannian_gradient_circuit_input_1_check(): """Test that a type error is raise for non-QNode circuits.""" def circuit(): qml.RY(0.5, wires=0) with pytest.raises(TypeError, match="circuit must be a QNode"): RiemannianGradientOptimizer(circuit=circuit, stepsize=0.001) def test_riemannian_gradient_hamiltonian_input_1_check(): """Test that a type error is raise for non-QNode circuits.""" @qml.qnode(qml.device("default.qubit", wires=3)) def circuit(): qml.RY(0.5, wires=0) return qml.state() with pytest.raises( TypeError, match="circuit must return the expectation value of a Hamiltonian", ): RiemannianGradientOptimizer(circuit=circuit, stepsize=0.001) def test_riemannian_gradient_nqubits_check(): """Test that we warn if the system is too big.""" @qml.qnode(qml.device("default.qubit", wires=5)) def circuit(): qml.RY(0.5, wires=0) return qml.expval(qml.Hamiltonian(coeffs=[-1.0], observables=[qml.PauliX(0)])) with pytest.warns(UserWarning, match="The exact Riemannian gradient is exponentially"): RiemannianGradientOptimizer(circuit=circuit, stepsize=0.001) def test_riemannian_gradient_restriction_check(): """Test that a type error is raise for non-QNode circuits.""" @qml.qnode(qml.device("default.qubit", wires=3)) def circuit(): qml.RY(0.5, wires=0) return qml.expval(qml.Hamiltonian(coeffs=[-1.0], observables=[qml.PauliX(0)])) restriction = "not_a_hamiltonian" with pytest.raises( TypeError, match="restriction must be a Hamiltonian", ): RiemannianGradientOptimizer(circuit=circuit, restriction=restriction, stepsize=0.001) @pytest.mark.slow def test_docstring_example(): """Test the docstring example with Trotterized evolution.""" hamiltonian = qml.Hamiltonian( coeffs=[-1.0] * 3, observables=[qml.PauliX(0), qml.PauliZ(1), qml.PauliY(0) @ qml.PauliX(1)], ) @qml.qnode(qml.device("default.qubit", wires=2)) def quant_fun(): qml.RX(0.1, wires=[0]) qml.RY(0.5, wires=[1]) qml.CNOT(wires=[0, 1]) qml.RY(0.6, wires=[0]) return qml.expval(hamiltonian) opt = RiemannianGradientOptimizer(circuit=quant_fun, stepsize=0.1) for _ in range(12): circuit, cost = opt.step_and_cost() circuit() assert np.isclose(cost, -2.236068, atol=1e-3) def test_docstring_example_exact(): """Test that the optimizer works with matrix exponential.""" hamiltonian = qml.Hamiltonian( coeffs=[-1.0] * 3, observables=[qml.PauliX(0), qml.PauliZ(1), qml.PauliY(0) @ qml.PauliX(1)], ) @qml.qnode(qml.device("default.qubit", wires=2)) def quant_fun(): qml.RX(0.1, wires=[0]) qml.RY(0.5, wires=[1]) qml.CNOT(wires=[0, 1]) qml.RY(0.6, wires=[0]) return qml.expval(hamiltonian) opt = RiemannianGradientOptimizer(circuit=quant_fun, stepsize=0.1, exact=True) for _ in range(12): circuit, cost = opt.step_and_cost() circuit() assert np.isclose(cost, -2.236068, atol=1e-3) def test_example_shots(): """Test that the optimizer works with finite shots.""" hamiltonian = qml.Hamiltonian( coeffs=[-1.0] * 3, observables=[qml.PauliX(0), qml.PauliZ(1), qml.PauliY(0) @ qml.PauliX(1)], ) @qml.qnode(qml.device("default.qubit", wires=2, shots=1000), diff_method=None) def quant_fun(): qml.RX(0.1, wires=[0]) qml.RY(0.5, wires=[1]) qml.CNOT(wires=[0, 1]) qml.RY(0.6, wires=[0]) return qml.expval(hamiltonian) opt = RiemannianGradientOptimizer(circuit=quant_fun, stepsize=0.1, exact=False) for _ in range(3): opt.step_and_cost()
pennylane/tests/optimize/test_riemannian_gradient_optimizer.py/0
{ "file_path": "pennylane/tests/optimize/test_riemannian_gradient_optimizer.py", "repo_id": "pennylane", "token_count": 5105 }
88
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """ Unit tests for the :mod:`pauli` utility functions in ``pauli/utils.py``. """ # pylint: disable=too-few-public-methods,too-many-public-methods import numpy as np import pytest import pennylane as qml from pennylane import ( RX, RY, U3, Hadamard, Hamiltonian, Hermitian, Identity, PauliX, PauliY, PauliZ, is_commuting, ) from pennylane.operation import Tensor from pennylane.pauli import ( are_identical_pauli_words, are_pauli_words_qwc, binary_to_pauli, diagonalize_pauli_word, diagonalize_qwc_pauli_words, is_pauli_word, is_qwc, observables_to_binary_matrix, partition_pauli_group, pauli_group, pauli_to_binary, pauli_word_to_matrix, pauli_word_to_string, qwc_complement_adj_matrix, qwc_rotation, simplify, string_to_pauli_word, ) non_pauli_words = [ PauliX(0) @ Hadamard(1) @ Identity(2), Hadamard("a"), U3(0.1, 1, 1, wires="a"), Hermitian(np.array([[3.2, 1.1 + 0.6j], [1.1 - 0.6j, 3.2]]), wires="a") @ PauliX("b"), ] def _make_pauli_word_strings(): return [ (PauliX(0), {0: 0}, "X"), (Identity(0), {0: 0}, "I"), (PauliZ(0) @ PauliY(1), {0: 0, 1: 1}, "ZY"), (PauliX(1), {0: 0, 1: 1}, "IX"), (PauliX(1), None, "X"), (PauliX(1), {1: 0, 0: 1}, "XI"), (PauliZ("a") @ PauliY("b") @ PauliZ("d"), {"a": 0, "b": 1, "c": 2, "d": 3}, "ZYIZ"), (PauliZ("a") @ PauliY("b") @ PauliZ("d"), None, "ZYZ"), (PauliX("a") @ PauliY("b") @ PauliZ("d"), {"d": 0, "c": 1, "b": 2, "a": 3}, "ZIYX"), (4.5 * PauliX(0), {0: 0}, "X"), (qml.prod(PauliX(0), PauliY(1)), {0: 0, 1: 1}, "XY"), (PauliX(0) @ PauliZ(0), {0: 0}, "Y"), (3 * PauliZ(0) @ PauliY(3), {0: 0, 3: 1}, "ZY"), (qml.s_prod(8, qml.PauliX(0) @ qml.PauliZ(1)), {0: 0, 1: 1}, "XZ"), (qml.Hamiltonian([1], [qml.X(0) @ qml.Y(1)]), None, "XY"), ] class TestGroupingUtils: """Basic usage and edge-case tests for the measurement optimization utility functions.""" ops_to_vecs_explicit_wires = [ (PauliX(0) @ PauliY(1) @ PauliZ(2), np.array([1, 1, 0, 0, 1, 1])), (PauliZ(0) @ PauliY(2), np.array([0, 1, 1, 1])), (PauliY(1) @ PauliX(2), np.array([1, 1, 1, 0])), (Identity(0), np.zeros(2)), (qml.prod(qml.PauliX(0), qml.PauliZ(1), qml.PauliY(2)), np.array([1, 0, 1, 0, 1, 1])), (qml.s_prod(1.5, qml.PauliZ(0)), np.array([0, 1])), (qml.sum(qml.PauliX(0), qml.PauliX(0), qml.PauliX(0)), np.array([1, 0])), ] @pytest.mark.parametrize("op,vec", ops_to_vecs_explicit_wires) def test_pauli_to_binary_no_wire_map(self, op, vec): """Test conversion of Pauli word from operator to binary vector representation when no ``wire_map`` is specified.""" assert (pauli_to_binary(op) == vec).all() ops_to_vecs_abstract_wires = [ (PauliX("a") @ PauliZ("b") @ Identity("c"), np.array([1, 0, 0, 0, 0, 1, 0, 0])), (PauliY(6) @ PauliZ("a") @ PauliZ("b"), np.array([0, 0, 0, 1, 1, 1, 0, 1])), (PauliX("b") @ PauliY("c"), np.array([0, 1, 1, 0, 0, 0, 1, 0])), (Identity("a") @ Identity(6), np.zeros(8)), ( qml.prod(qml.PauliX("a"), qml.PauliZ("b"), qml.PauliY(6)), np.array([1, 0, 0, 1, 0, 1, 0, 1]), ), (qml.s_prod(1.5, qml.PauliZ(6)), np.array([0, 0, 0, 0, 0, 0, 0, 1])), ( qml.sum(qml.PauliX("b"), qml.PauliX("b"), qml.PauliX("b")), np.array([0, 1, 0, 0, 0, 0, 0, 0]), ), ] @pytest.mark.parametrize("op,vec", ops_to_vecs_abstract_wires) def test_pauli_to_binary_with_wire_map(self, op, vec): """Test conversion of Pauli word from operator to binary vector representation if a ``wire_map`` is specified.""" wire_map = {"a": 0, "b": 1, "c": 2, 6: 3} assert (pauli_to_binary(op, wire_map=wire_map) == vec).all() vecs_to_ops_explicit_wires = [ (np.array([1, 0, 1, 0, 0, 1]), PauliX(0) @ PauliY(2)), (np.array([1, 1, 1, 1, 1, 1]), PauliY(0) @ PauliY(1) @ PauliY(2)), (np.array([1, 0, 1, 0, 1, 1]), PauliX(0) @ PauliZ(1) @ PauliY(2)), (np.zeros(6), Identity(0)), ] @pytest.mark.parametrize("non_pauli_word", non_pauli_words) def test_pauli_to_binary_non_pauli_word_catch(self, non_pauli_word): """Tests TypeError raise for when non Pauli-word Pennylane operations/operators are given as input to pauli_to_binary.""" assert pytest.raises(TypeError, pauli_to_binary, non_pauli_word) def test_pauli_to_binary_incompatable_wire_map_n_qubits(self): """Tests ValueError raise when n_qubits is not high enough to support the highest wire_map value.""" pauli_word = PauliX("a") @ PauliY("b") @ PauliZ("c") wire_map = {"a": 0, "b": 1, "c": 3} n_qubits = 3 assert pytest.raises(ValueError, pauli_to_binary, pauli_word, n_qubits, wire_map) @pytest.mark.parametrize("pauli_word,binary_pauli", ops_to_vecs_explicit_wires) def test_pauli_to_binary_no_check(self, pauli_word, binary_pauli): """Tests that pauli_to_binary runs well when pauli words are provided and check_is_pauli_word is False.""" assert (pauli_to_binary(pauli_word, check_is_pauli_word=False) == binary_pauli).all() @pytest.mark.parametrize("vec,op", vecs_to_ops_explicit_wires) def test_binary_to_pauli_no_wire_map(self, vec, op): """Test conversion of Pauli in binary vector representation to operator form when no ``wire_map`` is specified.""" assert are_identical_pauli_words(binary_to_pauli(vec), op) vecs_to_ops_abstract_wires = [ (np.array([1, 0, 1, 0, 0, 1]), PauliX("alice") @ PauliY("ancilla")), (np.array([1, 1, 1, 1, 1, 1]), PauliY("alice") @ PauliY("bob") @ PauliY("ancilla")), (np.array([1, 0, 1, 0, 1, 0]), PauliX("alice") @ PauliZ("bob") @ PauliX("ancilla")), (np.zeros(6), Identity("alice")), ] @pytest.mark.parametrize("vec,op", vecs_to_ops_abstract_wires) def test_binary_to_pauli_with_wire_map(self, vec, op): """Test conversion of Pauli in binary vector representation to operator form when ``wire_map`` is specified.""" wire_map = {"alice": 0, "bob": 1, "ancilla": 2} assert are_identical_pauli_words(binary_to_pauli(vec, wire_map=wire_map), op) binary_vecs_with_invalid_wire_maps = [ ([1, 0], {"a": 1}), ([1, 1, 1, 0], {"a": 0}), ([1, 0, 1, 0, 1, 1], {"a": 0, "b": 2, "c": 3}), ([1, 0, 1, 0], {"a": 0, "b": 2}), ] @pytest.mark.parametrize("binary_vec,wire_map", binary_vecs_with_invalid_wire_maps) def test_binary_to_pauli_invalid_wire_map(self, binary_vec, wire_map): """Tests ValueError raise when wire_map values are not integers 0 to N, for input 2N dimensional binary vector.""" assert pytest.raises(ValueError, binary_to_pauli, binary_vec, wire_map) not_binary_symplectic_vecs = [[1, 0, 1, 1, 0], [1], [2, 0, 0, 1], [0.1, 4.3, 2.0, 1.3]] @pytest.mark.parametrize("not_binary_symplectic", not_binary_symplectic_vecs) def test_binary_to_pauli_with_illegal_vectors(self, not_binary_symplectic): """Test ValueError raise for when non even-dimensional binary vectors are given to binary_to_pauli.""" assert pytest.raises(ValueError, binary_to_pauli, not_binary_symplectic) def test_observables_to_binary_matrix(self): """Test conversion of list of Pauli word operators to representation as a binary matrix.""" observables = [Identity(1), PauliX(1), PauliZ(0) @ PauliZ(1)] binary_observables = np.array( [[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]] ).T assert (observables_to_binary_matrix(observables) == binary_observables).all() def test_observables_to_binary_matrix_n_qubits_arg(self): """Tests if ValueError is raised when specified n_qubits is not large enough to support the number of distinct wire labels in input observables.""" observables = [Identity(1) @ PauliZ("a"), PauliX(1), PauliZ(0) @ PauliZ(2)] n_qubits_invalid = 3 assert pytest.raises( ValueError, observables_to_binary_matrix, observables, n_qubits_invalid ) @pytest.mark.usefixtures("use_legacy_opmath") def test_is_qwc(self): """Determining if two Pauli words are qubit-wise commuting.""" wire_map = {0: 0, "a": 1, "b": 2} p1_vec = pauli_to_binary(PauliX(0) @ PauliY("a"), wire_map=wire_map) p2_vec = pauli_to_binary(PauliX(0) @ Identity("a") @ PauliX("b"), wire_map=wire_map) p3_vec = pauli_to_binary(PauliX(0) @ PauliZ("a") @ Identity("b"), wire_map=wire_map) identity = pauli_to_binary(Identity("a") @ Identity(0), wire_map=wire_map) assert is_qwc(p1_vec, p2_vec) assert not is_qwc(p1_vec, p3_vec) assert is_qwc(p2_vec, p3_vec) assert ( is_qwc(p1_vec, identity) == is_qwc(p2_vec, identity) == is_qwc(p3_vec, identity) == is_qwc(identity, identity) == True ) obs_lsts = [ ([qml.PauliZ(0) @ qml.PauliX(1), qml.PauliY(2), qml.PauliX(1) @ qml.PauliY(2)], True), ([qml.PauliZ(0) @ qml.Identity(1), qml.PauliY(2), qml.PauliX(2) @ qml.PauliY(1)], False), ( [ qml.PauliZ(0) @ qml.PauliX(1), qml.PauliY(2), qml.Identity(1) @ qml.PauliY(2), qml.Identity(0), ], True, ), # multi I ([qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(2), qml.PauliX(1) @ qml.PauliY(2)], False), # The following are use cases for `expand_tape`, so should be tested, even though Hadamard is not a Pauli op ([qml.Hadamard(0) @ qml.PauliX(1), qml.Identity(0)], True), ([qml.Hadamard(0) @ qml.PauliX(1), qml.PauliZ(0)], False), ] @pytest.mark.parametrize("obs_lst, expected_qwc", obs_lsts) def test_are_qwc_pauli_words(self, obs_lst, expected_qwc): """Given a list of Pauli words test that this function accurately determines if they are pairwise qubit-wise commuting.""" qwc = are_pauli_words_qwc(obs_lst) assert qwc == expected_qwc @pytest.mark.parametrize( "ops", ( [qml.PauliX(0), qml.sum(qml.PauliX(2), qml.PauliZ(1))], [qml.sum(qml.prod(qml.PauliX(0), qml.PauliY(1)), 2 * qml.PauliZ(0))], [qml.sum(qml.PauliY(0), qml.PauliX(1), qml.PauliZ(2))], [qml.prod(qml.sum(qml.PauliX(0), qml.PauliY(1)), 2 * qml.PauliZ(0)), qml.PauliZ(0)], ), ) def test_are_pauli_words_qwc_sum_false(self, ops): """Test that using operators with pauli rep containing more than one term with are_pauli_words_qwc always returns False.""" assert are_pauli_words_qwc(ops) is False def test_is_qwc_not_equal_lengths(self): """Tests ValueError is raised when input Pauli vectors are not of equal length.""" pauli_vec_1 = [0, 1, 0, 1] pauli_vec_2 = [1, 1, 0, 1, 0, 1] assert pytest.raises(ValueError, is_qwc, pauli_vec_1, pauli_vec_2) def test_is_qwc_not_even_lengths(self): """Tests ValueError is raised when input Pauli vectors are not of even length.""" pauli_vec_1 = [1, 0, 1] pauli_vec_2 = [1, 1, 1] assert pytest.raises(ValueError, is_qwc, pauli_vec_1, pauli_vec_2) def test_is_qwc_not_binary_vectors(self): """Tests ValueError is raised when input Pauli vectors do not have binary components.""" pauli_vec_1 = [1, 3.2, 1, 1 + 2j] pauli_vec_2 = [1, 0, 0, 0] assert pytest.raises(ValueError, is_qwc, pauli_vec_1, pauli_vec_2) obs_pw_status = ( (PauliX(0), True), (PauliZ(1) @ PauliX(2) @ PauliZ(4), True), (PauliX(1) @ Hadamard(4), False), (Hadamard(0), False), (Hamiltonian([], []), False), (Hamiltonian([0.5], [PauliZ(1) @ PauliX(2)]), True), (Hamiltonian([0.5], [PauliZ(1) @ PauliX(1)]), True), (Hamiltonian([1.0], [Hadamard(0)]), False), (Hamiltonian([1.0, 0.5], [PauliX(0), PauliZ(1) @ PauliX(2)]), False), (qml.prod(qml.PauliX(0), qml.PauliY(0)), True), (qml.prod(qml.PauliX(0), qml.PauliY(1)), True), (qml.prod(qml.PauliX(0), qml.Hadamard(1)), False), (qml.s_prod(5, qml.PauliX(0) @ qml.PauliZ(1)), True), (qml.s_prod(5, qml.Hadamard(0)), False), (qml.sum(qml.PauliX(0), qml.PauliY(0)), False), (qml.sum(qml.s_prod(0.5, qml.PauliX(1)), qml.PauliX(1)), True), (qml.sum(qml.s_prod(0.5, qml.Hadamard(1)), qml.PauliX(1)), False), (qml.sum(qml.Hadamard(0), qml.Hadamard(0)), False), ) @pytest.mark.parametrize("ob, is_pw", obs_pw_status) def test_is_pauli_word(self, ob, is_pw): """Test for determining whether input ``Observable`` instance is a Pauli word.""" assert is_pauli_word(ob) == is_pw def test_is_pauli_word_non_observable(self): """Test that non-observables are not Pauli Words.""" class DummyOp(qml.operation.Operator): num_wires = 1 assert not is_pauli_word(DummyOp(1)) def test_are_identical_pauli_words(self): """Tests for determining if two Pauli words have the same ``wires`` and ``name`` attributes.""" pauli_word_1 = Tensor(PauliX(0)) pauli_word_2 = PauliX(0) assert are_identical_pauli_words(pauli_word_1, pauli_word_2) assert are_identical_pauli_words(pauli_word_2, pauli_word_1) pauli_word_1 = PauliX(0) @ PauliY(1) pauli_word_2 = PauliY(1) @ PauliX(0) pauli_word_3 = Tensor(PauliX(0), PauliY(1)) pauli_word_4 = PauliX(1) @ PauliZ(2) pauli_word_5 = qml.s_prod(1.5, qml.PauliX(0)) pauli_word_6 = qml.sum(qml.s_prod(0.5, qml.PauliX(0)), qml.s_prod(1.0, qml.PauliX(0))) pauli_word_7 = qml.s_prod(2.2, qml.prod(qml.PauliX(0), qml.PauliY(1))) assert are_identical_pauli_words(pauli_word_1, pauli_word_2) assert are_identical_pauli_words(pauli_word_1, pauli_word_3) assert not are_identical_pauli_words(pauli_word_1, pauli_word_4) assert not are_identical_pauli_words(pauli_word_3, pauli_word_4) assert are_identical_pauli_words(pauli_word_5, pauli_word_6) assert are_identical_pauli_words(pauli_word_7, pauli_word_1) assert not are_identical_pauli_words(pauli_word_7, pauli_word_4) assert not are_identical_pauli_words(pauli_word_6, pauli_word_4) @pytest.mark.usefixtures("use_legacy_opmath") def test_are_identical_pauli_words_hamiltonian_unsupported(self): """Test that using Hamiltonians that are valid Pauli words with are_identical_pauli_words always returns False""" pauli_word_1 = qml.Hamiltonian([1.0], [qml.PauliX(0)]) pauli_word_2 = qml.PauliX(0) assert not are_identical_pauli_words(pauli_word_1, pauli_word_2) def test_identities_always_pauli_words(self): """Tests that identity terms are always identical.""" assert are_identical_pauli_words(qml.Identity(0), qml.Identity("a")) assert are_identical_pauli_words(qml.Identity((-2, -3)), qml.Identity("wire")) @pytest.mark.parametrize("non_pauli_word", non_pauli_words) def test_are_identical_pauli_words_non_pauli_word_catch(self, non_pauli_word): """Tests TypeError raise for when non-Pauli word Pennylane operators/operations are given as input to are_identical_pauli_words.""" with pytest.raises(TypeError): are_identical_pauli_words(non_pauli_word, PauliZ(0) @ PauliZ(1)) with pytest.raises(TypeError): are_identical_pauli_words(non_pauli_word, PauliZ(0) @ PauliZ(1)) with pytest.raises(TypeError): are_identical_pauli_words(PauliX("a") @ Identity("b"), non_pauli_word) with pytest.raises(TypeError): are_identical_pauli_words(non_pauli_word, non_pauli_word) def test_qwc_complement_adj_matrix(self): """Tests that the ``qwc_complement_adj_matrix`` function returns the correct adjacency matrix.""" binary_observables = np.array( [ [1.0, 0.0, 1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 1.0, 1.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0, 0.0, 0.0], ] ) adj = qwc_complement_adj_matrix(binary_observables) expected = np.array([[0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) assert np.all(adj == expected) binary_obs_list = list(binary_observables) adj = qwc_complement_adj_matrix(binary_obs_list) assert np.all(adj == expected) binary_obs_tuple = tuple(binary_observables) adj = qwc_complement_adj_matrix(binary_obs_tuple) assert np.all(adj == expected) def test_qwc_complement_adj_matrix_exception(self): """Tests that the ``qwc_complement_adj_matrix`` function raises an exception if the matrix is not binary.""" not_binary_observables = np.array( [ [1.1, 0.5, 1.0, 0.0, 0.0, 1.0], [0.0, 1.3, 1.0, 1.0, 0.0, 1.0], [2.2, 0.0, 0.0, 1.0, 0.0, 0.0], ] ) with pytest.raises(ValueError, match="Expected a binary array, instead got"): qwc_complement_adj_matrix(not_binary_observables) PAULI_WORD_STRINGS = _make_pauli_word_strings() @pytest.mark.usefixtures("use_legacy_and_new_opmath") @pytest.mark.parametrize("pauli_word,wire_map,expected_string", PAULI_WORD_STRINGS) def test_pauli_word_to_string(self, pauli_word, wire_map, expected_string): """Test that Pauli words are correctly converted into strings.""" obtained_string = pauli_word_to_string(pauli_word, wire_map) assert obtained_string == expected_string def test_pauli_word_to_string_tensor(self): """Test pauli_word_to_string with tensor instances.""" op = qml.operation.Tensor(qml.X(0), qml.Y(1)) assert pauli_word_to_string(op) == "XY" op = qml.operation.Tensor(qml.Z(0), qml.Y(1), qml.X(2)) assert pauli_word_to_string(op) == "ZYX" with qml.operation.disable_new_opmath_cm(): PAULI_WORD_STRINGS_LEGACY = _make_pauli_word_strings() @pytest.mark.usefixtures("use_legacy_opmath") @pytest.mark.parametrize("pauli_word,wire_map,expected_string", PAULI_WORD_STRINGS_LEGACY) def test_pauli_word_to_string_legacy_opmath(self, pauli_word, wire_map, expected_string): """Test that Pauli words are correctly converted into strings.""" obtained_string = pauli_word_to_string(pauli_word, wire_map) assert obtained_string == expected_string @pytest.mark.parametrize("non_pauli_word", non_pauli_words) def test_pauli_word_to_string_invalid_input(self, non_pauli_word): """Ensure invalid inputs are handled properly when converting Pauli words to strings.""" with pytest.raises(TypeError): pauli_word_to_string(non_pauli_word) @pytest.mark.usefixtures("use_new_opmath") @pytest.mark.parametrize( "pauli_string,wire_map,expected_pauli", [ ("I", {"a": 0}, Identity("a")), ("X", {0: 0}, PauliX(0)), ("XI", {1: 0, 0: 1}, PauliX(1)), ("II", {0: 0, 1: 1}, Identity(0)), ("ZYIZ", {"a": 0, "b": 1, "c": 2, "d": 3}, PauliZ("a") @ PauliY("b") @ PauliZ("d")), ("ZYZ", None, PauliZ(0) @ PauliY(1) @ PauliZ(2)), ("ZIYX", {"d": 0, "c": 1, "b": 2, "a": 3}, PauliZ("d") @ PauliY("b") @ PauliX("a")), ], ) def test_string_to_pauli_word(self, pauli_string, wire_map, expected_pauli): """Test that valid strings are correctly converted into Pauli words.""" obtained_pauli = string_to_pauli_word(pauli_string, wire_map) qml.assert_equal(obtained_pauli, expected_pauli) @pytest.mark.parametrize( "non_pauli_string,wire_map,error_type,error_message", [ (Identity("a"), None, TypeError, "must be string"), ("XAYZ", None, ValueError, "Invalid characters encountered"), ("XYYZ", {0: 0, 1: 1, 2: 2}, ValueError, "must have the same length"), ], ) def test_string_to_pauli_word_invalid_input( self, non_pauli_string, wire_map, error_type, error_message ): """Ensure invalid inputs are handled properly when converting strings to Pauli words.""" with pytest.raises(error_type, match=error_message): string_to_pauli_word(non_pauli_string, wire_map) @pytest.mark.parametrize( "pauli_word,wire_map,expected_matrix", [ (PauliX(0), {0: 0}, PauliX(0).matrix()), # ( # Identity(0), # {0: 0}, # np.eye(2), # ), # TODO update PauliSentence.to_mat to handle Identities better https://github.com/PennyLaneAI/pennylane/issues/5354 ( PauliZ(0) @ PauliY(1), {0: 0, 1: 1}, np.array([[0, -1j, 0, 0], [1j, 0, 0, 0], [0, 0, 0, 1j], [0, 0, -1j, 0]]), ), ( PauliY(1) @ PauliZ(0), {0: 0, 1: 1}, np.array([[0, -1j, 0, 0], [1j, 0, 0, 0], [0, 0, 0, 1j], [0, 0, -1j, 0]]), ), ( PauliY(1) @ PauliZ(0), {1: 0, 0: 1}, np.array([[0, 0, -1j, 0], [0, 0, 0, 1j], [1j, 0, 0, 0], [0, -1j, 0, 0]]), ), # (Identity(0), {0: 0, 1: 1}, np.eye(4)), # TODO update PauliSentence.to_mat to handle Identities better https://github.com/PennyLaneAI/pennylane/issues/5354 (PauliX(2), None, PauliX(2).matrix()), ( PauliX(2), {0: 0, 1: 1, 2: 2}, np.array( [ [0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], ] ), ), ( PauliZ("a") @ PauliX(2), {"a": 0, 1: 1, 2: 2}, np.array( [ [0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, 0, 0], [0, 0, 0, 0, -1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, -1], [0, 0, 0, 0, 0, 0, -1, 0], ] ), ), ( PauliX(2) @ PauliZ("a"), {"a": 0, 1: 1, 2: 2}, np.array( [ [0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, 0, 0], [0, 0, 0, 0, -1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, -1], [0, 0, 0, 0, 0, 0, -1, 0], ] ), ), ], ) def test_pauli_word_to_matrix(self, pauli_word, wire_map, expected_matrix): """Test that Pauli words are correctly converted into matrices.""" obtained_matrix = pauli_word_to_matrix(pauli_word, wire_map) assert np.allclose(obtained_matrix, expected_matrix) @pytest.mark.parametrize("non_pauli_word", non_pauli_words) def test_pauli_word_to_matrix_invalid_input(self, non_pauli_word): """Ensure invalid inputs are handled properly when converting Pauli words to matrices.""" with pytest.raises(TypeError): pauli_word_to_matrix(non_pauli_word) class TestPauliGroup: """Testing for Pauli group construction and manipulation functions.""" def test_pauli_group_size(self): """Test that the size of the returned Pauli group is correct.""" for n_qubits in range(1, 5): pg = list(pauli_group(n_qubits)) assert len(pg) == 4**n_qubits def test_pauli_group_invalid_input(self): """Test that invalid inputs to the Pauli group are handled correctly.""" with pytest.raises(TypeError, match="Must specify an integer number"): pauli_group("3") with pytest.raises(ValueError, match="Number of qubits must be at least 1"): pauli_group(-1) def test_one_qubit_pauli_group_integer_wire_map(self): """Test that the single-qubit Pauli group is constructed correctly with a wire labeled by an integer.""" expected_pg_1 = [Identity(0), PauliZ(0), PauliX(0), PauliY(0)] pg_1 = list(pauli_group(1)) assert all(expected.compare(obtained) for expected, obtained in zip(expected_pg_1, pg_1)) def test_one_qubit_pauli_group_valid_float_input(self): """Test that the single-qubit Pauli group is constructed correctly when a float that represents an integer is passed.""" expected_pg_1 = [Identity(0), PauliZ(0), PauliX(0), PauliY(0)] pg_1 = list(pauli_group(1.0)) assert all(expected.compare(obtained) for expected, obtained in zip(expected_pg_1, pg_1)) def test_one_qubit_pauli_group_string_wire_map(self): """Test that the single-qubit Pauli group is constructed correctly with a wire labeled by a string.""" wire_map = {"qubit": 0} expected_pg_1_wires = [ Identity("qubit"), PauliZ("qubit"), PauliX("qubit"), PauliY("qubit"), ] pg_1_wires = list(pauli_group(1, wire_map=wire_map)) assert all(exp.compare(ob) for exp, ob in zip(expected_pg_1_wires, pg_1_wires)) def test_two_qubit_pauli_group(self): """Test that the two-qubit Pauli group is constructed correctly.""" # With no wire map; ordering is based on construction from binary representation wire_map = {"a": 0, "b": 1} expected_pg_2 = [ Identity("a"), PauliZ("b"), PauliZ("a"), PauliZ("a") @ PauliZ("b"), PauliX("b"), PauliY("b"), PauliZ("a") @ PauliX("b"), PauliZ("a") @ PauliY("b"), PauliX("a"), PauliX("a") @ PauliZ("b"), PauliY("a"), PauliY("a") @ PauliZ("b"), PauliX("a") @ PauliX("b"), PauliX("a") @ PauliY("b"), PauliY("a") @ PauliX("b"), PauliY("a") @ PauliY("b"), ] pg_2 = list(pauli_group(2, wire_map=wire_map)) for expected, obtained in zip(expected_pg_2, pg_2): qml.assert_equal(obtained, expected) @pytest.mark.parametrize( "pauli_word_1,pauli_word_2,expected_product", [ (PauliX(0), Identity(0), PauliX(0)), (PauliZ(0), PauliY(0), PauliX(0)), (PauliZ(0), PauliZ(0), Identity(0)), (Identity("a"), Identity("b"), Identity(["a", "b"])), (PauliZ("b") @ PauliY("a"), PauliZ("b") @ PauliY("a"), Identity(["b", "a"])), ( PauliZ("b") @ PauliY("a"), PauliZ("b") @ PauliY("a"), Identity(["b", "a"]), ), ( PauliZ(0) @ PauliY(1), PauliX(0) @ PauliZ(1), PauliY(0) @ PauliX(1), ), (PauliZ(0) @ PauliY(1), PauliX(1) @ PauliY(0), PauliX(0) @ PauliZ(1)), ( PauliZ(0) @ PauliY(3) @ PauliZ(1), PauliX(1) @ PauliX(2) @ PauliY(0), PauliX(0) @ PauliY(1) @ PauliX(2) @ PauliY(3), ), ( PauliX(0) @ PauliX(2), PauliX(0) @ PauliZ(2), PauliY(2), ), (PauliZ("a"), PauliX("b"), PauliZ("a") @ PauliX("b")), ( PauliZ("a"), PauliX("e"), PauliZ("a") @ PauliX("e"), ), (PauliZ("a"), PauliY("e"), PauliZ("a") @ PauliY("e")), ( PauliZ(0) @ PauliZ(2) @ PauliZ(4), PauliZ(0) @ PauliY(1) @ PauliX(3), PauliZ(2) @ PauliY(1) @ PauliZ(4) @ PauliX(3), ), ( PauliZ(0) @ PauliZ(4) @ PauliZ(2), PauliZ(0) @ PauliY(1) @ PauliX(3), PauliZ(2) @ PauliY(1) @ PauliZ(4) @ PauliX(3), ), ( PauliZ(0) @ PauliY(3) @ PauliZ(1), PauliX(1) @ PauliX(2) @ PauliY(0), PauliX(0) @ PauliY(3) @ PauliY(1) @ PauliX(2), ), ], ) def test_pauli_mult_using_prod(self, pauli_word_1, pauli_word_2, expected_product): """Test that Pauli words are multiplied together correctly.""" obtained_product = qml.prod(pauli_word_1, pauli_word_2).simplify() if isinstance(obtained_product, qml.ops.SProd): # don't care about phase here obtained_product = obtained_product.base assert obtained_product == qml.operation.convert_to_opmath(expected_product) @pytest.mark.parametrize( "pauli_word_1,pauli_word_2,expected_phase", [ (PauliX(0), Identity(0), 1), (PauliZ(0), PauliY(0), -1j), (PauliZ(0), PauliZ(0), 1), (Identity("a"), Identity("b"), 1), (PauliZ("b") @ PauliY("a"), PauliZ("b") @ PauliY("a"), 1), (PauliZ(0), PauliY("b"), 1), (PauliZ("a") @ PauliY("b"), PauliX("a") @ PauliZ("b"), -1), (PauliX(0) @ PauliX(2), PauliX(0) @ PauliZ(2), -1j), (PauliX(0) @ PauliY(1) @ PauliZ(2), PauliY(0) @ PauliY(1), 1j), (PauliZ(0) @ PauliY(1), PauliX(1) @ PauliY(0), -1), (PauliZ(0) @ PauliY(1), PauliX(1) @ PauliY(0), -1), (PauliZ(0) @ PauliY(3) @ PauliZ(1), PauliX(1) @ PauliX(2) @ PauliY(0), 1), ], ) def test_pauli_mult_with_phase_using_prod(self, pauli_word_1, pauli_word_2, expected_phase): """Test that multiplication including phases works as expected.""" prod = qml.prod(pauli_word_1, pauli_word_2).simplify() obtained_phase = prod.scalar if isinstance(prod, qml.ops.SProd) else 1 assert obtained_phase == expected_phase class TestPartitionPauliGroup: """Tests for the partition_pauli_group function""" def test_expected_answer(self): """Test if we get the expected answer for 3 qubits""" expected = [ ["III", "IIZ", "IZI", "IZZ", "ZII", "ZIZ", "ZZI", "ZZZ"], ["IIX", "IZX", "ZIX", "ZZX"], ["IIY", "IZY", "ZIY", "ZZY"], ["IXI", "IXZ", "ZXI", "ZXZ"], ["IXX", "ZXX"], ["IXY", "ZXY"], ["IYI", "IYZ", "ZYI", "ZYZ"], ["IYX", "ZYX"], ["IYY", "ZYY"], ["XII", "XIZ", "XZI", "XZZ"], ["XIX", "XZX"], ["XIY", "XZY"], ["XXI", "XXZ"], ["XXX"], ["XXY"], ["XYI", "XYZ"], ["XYX"], ["XYY"], ["YII", "YIZ", "YZI", "YZZ"], ["YIX", "YZX"], ["YIY", "YZY"], ["YXI", "YXZ"], ["YXX"], ["YXY"], ["YYI", "YYZ"], ["YYX"], ["YYY"], ] assert expected == partition_pauli_group(3.0) @pytest.mark.parametrize("n", range(1, 9)) def test_scaling(self, n): """Test if the number of groups is equal to 3**n""" assert len(partition_pauli_group(n)) == 3**n @pytest.mark.usefixtures("use_legacy_opmath") @pytest.mark.parametrize("n", range(1, 6)) def test_is_qwc_legacy_opmath(self, n): """Test if each group contains only qubit-wise commuting terms""" for group in partition_pauli_group(n): size = len(group) for i in range(size): for j in range(i, size): s1 = group[i] s2 = group[j] w1 = string_to_pauli_word(s1) w2 = string_to_pauli_word(s2) assert is_commuting(w1, w2) @pytest.mark.parametrize("n", range(2, 6)) def test_is_qwc(self, n): """Test if each group contains only qubit-wise commuting terms""" for group in partition_pauli_group(n): size = len(group) for i in range(size): for j in range(i, size): s1 = group[i] s2 = group[j] w1 = string_to_pauli_word(s1) w2 = string_to_pauli_word(s2) assert is_commuting(w1, w2) def test_invalid_input(self): """Test that invalid inputs are handled correctly.""" with pytest.raises(TypeError, match="Must specify an integer number"): partition_pauli_group("3") with pytest.raises(ValueError, match="Number of qubits must be at least 0"): partition_pauli_group(-1) def test_zero(self): """Test if [[""]] is returned with zero qubits""" assert partition_pauli_group(0) == [[""]] class TestMeasurementTransformations: """Tests for the functions involved in obtaining post-rotations necessary in the measurement optimization schemes implemented in :mod:`grouping`.""" def are_identical_rotation_gates(self, gate_1, gate_2, param_tol=1e-6): """Checks whether the two input gates are identical up to a certain threshold in their parameters. Arguments: gate_1 (Union[RX, RY, RZ]): the first single-qubit rotation gate gate_2 (Union[RX, RY, RZ]): the second single-qubit rotation gate Keyword arguments: param_tol (float): the absolute tolerance for considering whether two gates parameter values are the same Returns: bool: whether the input rotation gates are identical up to the parameter tolerance """ return ( gate_1.wires == gate_2.wires and np.allclose(gate_1.parameters, gate_2.parameters, atol=param_tol, rtol=0) and gate_1.name == gate_2.name ) qwc_rotation_io = [ ([PauliX(0), PauliZ(1), PauliZ(3)], [RY(-np.pi / 2, wires=[0])]), ([Identity(0), PauliZ(1)], []), ( [PauliX(2), PauliY(0), Identity(1)], [RY(-np.pi / 2, wires=[2]), RX(np.pi / 2, wires=[0])], ), ( [PauliZ("a"), PauliX("b"), PauliY(0)], [RY(-np.pi / 2, wires=["b"]), RX(np.pi / 2, wires=[0])], ), ] @pytest.mark.parametrize("pauli_ops,qwc_rot_sol", qwc_rotation_io) def test_qwc_rotation(self, pauli_ops, qwc_rot_sol): """Tests that the correct single-qubit post-rotation gates are obtained for the input list of Pauli operators.""" qwc_rot = qwc_rotation(pauli_ops) assert all( self.are_identical_rotation_gates(qwc_rot[i], qwc_rot_sol[i]) for i in range(len(qwc_rot)) ) invalid_qwc_rotation_inputs = [ [PauliX(0), PauliY(1), Hadamard(2)], [PauliX(0) @ PauliY(1), PauliZ(1), Identity(2)], [RX(1, wires="a"), PauliX("b")], ] @pytest.mark.parametrize("bad_input", invalid_qwc_rotation_inputs) def test_invalid_qwc_rotation_input_catch(self, bad_input): """Verifies that a TypeError is raised when the input to qwc_rotations is not a list of single Pauli operators.""" assert pytest.raises(TypeError, qwc_rotation, bad_input) diagonalized_paulis = [ (Identity("a"), Identity("a")), (PauliX(1) @ Identity(2) @ PauliZ("b"), PauliZ(1) @ PauliZ("b")), (PauliZ(1) @ PauliZ(2), PauliZ(1) @ PauliZ(2)), (PauliX("a") @ PauliY("b") @ PauliY("c"), PauliZ("a") @ PauliZ("b") @ PauliZ("c")), ] @pytest.mark.parametrize("pauli_word, diag_pauli_word", diagonalized_paulis) def test_diagonalize_pauli_word(self, pauli_word, diag_pauli_word): """Tests `diagonalize_pauli_word` returns the correct diagonal Pauli word in computational basis for a given Pauli word.""" assert are_identical_pauli_words(diagonalize_pauli_word(pauli_word), diag_pauli_word) non_pauli_words = [ PauliX(0) @ Hadamard(1) @ Identity(2), Hadamard("a"), U3(0.1, 1, 1, wires="a"), Hermitian(np.array([[3.2, 1.1 + 0.6j], [1.1 - 0.6j, 3.2]]), wires="a") @ PauliX("b"), ] @pytest.mark.parametrize("non_pauli_word", non_pauli_words) def test_diagonalize_pauli_word_catch_non_pauli_word(self, non_pauli_word): assert pytest.raises(TypeError, diagonalize_pauli_word, non_pauli_word) qwc_diagonalization_io = [ ( [PauliX(0) @ PauliY(1), PauliX(0) @ PauliZ(2)], ( [RY(-np.pi / 2, wires=[0]), RX(np.pi / 2, wires=[1])], [PauliZ(wires=[0]) @ PauliZ(wires=[1]), PauliZ(wires=[0]) @ PauliZ(wires=[2])], ), ), ( [PauliX(2) @ Identity(0), PauliY(1), PauliZ(0) @ PauliY(1), PauliX(2) @ PauliY(1)], ( [RY(-np.pi / 2, wires=[2]), RX(np.pi / 2, wires=[1])], [ PauliZ(wires=[2]), PauliZ(wires=[1]), PauliZ(wires=[0]) @ PauliZ(wires=[1]), PauliZ(wires=[2]) @ PauliZ(wires=[1]), ], ), ), ( [PauliZ("a") @ PauliY("b") @ PauliZ("c"), PauliY("b") @ PauliZ("d")], ( [RX(np.pi / 2, wires=["b"])], [ PauliZ(wires=["a"]) @ PauliZ(wires=["b"]) @ PauliZ(wires=["c"]), PauliZ(wires=["b"]) @ PauliZ(wires=["d"]), ], ), ), ([PauliX("a")], ([RY(-np.pi / 2, wires=["a"])], [PauliZ(wires=["a"])])), ( [PauliX(0), PauliX(1) @ PauliX(0)], ( [RY(-1.5707963267948966, wires=[0]), RY(-1.5707963267948966, wires=[1])], [PauliZ(wires=[0]), PauliZ(wires=[1]) @ PauliZ(wires=[0])], ), ), ] @pytest.mark.parametrize("convert_to_opmath", (True, False)) @pytest.mark.parametrize("qwc_grouping,qwc_sol_tuple", qwc_diagonalization_io) def test_diagonalize_qwc_pauli_words(self, qwc_grouping, qwc_sol_tuple, convert_to_opmath): """Tests for validating diagonalize_qwc_pauli_words solutions.""" if convert_to_opmath: qwc_grouping = [qml.operation.convert_to_opmath(o) for o in qwc_grouping] diag_terms = [qml.operation.convert_to_opmath(o) for o in qwc_sol_tuple[1]] qwc_sol_tuple = (qwc_sol_tuple[0], diag_terms) qwc_rot, diag_qwc_grouping = diagonalize_qwc_pauli_words(qwc_grouping) qwc_rot_sol, diag_qwc_grouping_sol = qwc_sol_tuple assert all( self.are_identical_rotation_gates(qwc_rot[i], qwc_rot_sol[i]) for i in range(len(qwc_rot)) ) for diag_op, expected in zip(diag_qwc_grouping, diag_qwc_grouping_sol): qml.assert_equal(diag_op, expected) not_qwc_groupings = [ [PauliX("a"), PauliY("a")], [PauliZ(0) @ Identity(1), PauliZ(0) @ PauliZ(1), PauliX(0) @ Identity(1)], [PauliX("a") @ PauliX(0), PauliZ(0) @ PauliZ("a")], [PauliZ("a") @ PauliY(1), PauliZ(1) @ PauliY("a")], [qml.prod(qml.PauliZ(0), qml.PauliX(1)), qml.prod(qml.PauliZ(1), qml.PauliX(0))], ] @pytest.mark.parametrize("not_qwc_grouping", not_qwc_groupings) def test_diagonalize_qwc_pauli_words_catch_when_not_qwc(self, not_qwc_grouping): """Test for ValueError raise when diagonalize_qwc_pauli_words is not given a list of qubit-wise commuting Pauli words.""" assert pytest.raises(ValueError, diagonalize_qwc_pauli_words, not_qwc_grouping) @pytest.mark.usefixtures( "use_legacy_opmath" ) # Handling a LinearCombination is not a problem under new opmath anymore def test_diagonalize_qwc_pauli_words_catch_invalid_type(self): """Test for ValueError raise when diagonalize_qwc_pauli_words is given a list containing invalid operator types.""" invalid_ops = [qml.PauliX(0), qml.Hamiltonian([1.0], [qml.PauliZ(1)])] with pytest.raises(ValueError, match="This function only supports pauli words."): _ = diagonalize_qwc_pauli_words(invalid_ops) class TestObservableHF: with qml.operation.disable_new_opmath_cm(): HAMILTONIAN_SIMPLIFY = [ ( qml.Hamiltonian( np.array([0.5, 0.5]), [qml.PauliX(0) @ qml.PauliY(1), qml.PauliX(0) @ qml.PauliY(1)], ), qml.Hamiltonian(np.array([1.0]), [qml.PauliX(0) @ qml.PauliY(1)]), ), ( qml.Hamiltonian( np.array([0.5, -0.5]), [qml.PauliX(0) @ qml.PauliY(1), qml.PauliX(0) @ qml.PauliY(1)], ), qml.Hamiltonian([], []), ), ( qml.Hamiltonian( np.array([0.0, -0.5]), [qml.PauliX(0) @ qml.PauliY(1), qml.PauliX(0) @ qml.PauliZ(1)], ), qml.Hamiltonian(np.array([-0.5]), [qml.PauliX(0) @ qml.PauliZ(1)]), ), ( qml.Hamiltonian( np.array([0.25, 0.25, 0.25, -0.25]), [ qml.PauliX(0) @ qml.PauliY(1), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliX(0) @ qml.PauliY(1), qml.PauliX(0) @ qml.PauliY(1), ], ), qml.Hamiltonian( np.array([0.25, 0.25]), [qml.PauliX(0) @ qml.PauliY(1), qml.PauliX(0) @ qml.PauliZ(1)], ), ), ] @pytest.mark.usefixtures("use_legacy_opmath") @pytest.mark.parametrize(("hamiltonian", "result"), HAMILTONIAN_SIMPLIFY) def test_simplify(self, hamiltonian, result): r"""Test that simplify returns the correct hamiltonian.""" h = simplify(hamiltonian) assert h.compare(result) class TestTapering: with qml.operation.disable_new_opmath_cm(): terms_bin_mat_data = [ ( [ qml.Identity(wires=[0]), qml.PauliZ(wires=[0]), qml.PauliZ(wires=[1]), qml.PauliZ(wires=[2]), qml.PauliZ(wires=[3]), qml.PauliZ(wires=[0]) @ qml.PauliZ(wires=[1]), qml.PauliY(wires=[0]) @ qml.PauliX(wires=[1]) @ qml.PauliX(wires=[2]) @ qml.PauliY(wires=[3]), qml.PauliY(wires=[0]) @ qml.PauliY(wires=[1]) @ qml.PauliX(wires=[2]) @ qml.PauliX(wires=[3]), qml.PauliX(wires=[0]) @ qml.PauliX(wires=[1]) @ qml.PauliY(wires=[2]) @ qml.PauliY(wires=[3]), qml.PauliX(wires=[0]) @ qml.PauliY(wires=[1]) @ qml.PauliY(wires=[2]) @ qml.PauliX(wires=[3]), qml.PauliZ(wires=[0]) @ qml.PauliZ(wires=[2]), qml.PauliZ(wires=[0]) @ qml.PauliZ(wires=[3]), qml.PauliZ(wires=[1]) @ qml.PauliZ(wires=[2]), qml.PauliZ(wires=[1]) @ qml.PauliZ(wires=[3]), qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[3]), ], 4, np.array( [ [0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1], [0, 1, 1, 0, 1, 1, 1, 1], [1, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 1, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0], ] ), ), ( [ qml.PauliZ(wires=["a"]) @ qml.PauliX(wires=["b"]), qml.PauliZ(wires=["a"]) @ qml.PauliY(wires=["c"]), qml.PauliX(wires=["a"]) @ qml.PauliY(wires=["d"]), ], 4, np.array( [[1, 0, 0, 0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 1, 1, 0, 0, 1]] ), ), ] @pytest.mark.usefixtures("use_legacy_opmath") @pytest.mark.parametrize(("terms", "num_qubits", "result"), terms_bin_mat_data) def test_binary_matrix_from_pws(self, terms, num_qubits, result): r"""Test that _binary_matrix_from_pws returns the correct result.""" # pylint: disable=protected-access pws_lst = [list(qml.pauli.pauli_sentence(t))[0] for t in terms] binary_matrix = qml.pauli.utils._binary_matrix_from_pws(pws_lst, num_qubits) assert (binary_matrix == result).all()
pennylane/tests/pauli/test_pauli_utils.py/0
{ "file_path": "pennylane/tests/pauli/test_pauli_utils.py", "repo_id": "pennylane", "token_count": 25817 }
89
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # 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. """ Unit tests for the ``dipole_of`` function. """ # pylint: disable=too-many-arguments import numpy as np import pytest import pennylane as qml h2 = ["H", "H"] x_h2 = np.array([0.0, 0.0, -0.661, 0.0, 0.0, 0.661]) coeffs_h2 = [] coeffs_h2.append([0.0]) coeffs_h2.append([0.0]) coeffs_h2.append([0.45445016, 0.45445016, 0.45445016, 0.45445016]) ops_h2 = [] ops_h2.append([qml.Identity(wires=[0])]) ops_h2.append([qml.Identity(wires=[0])]) ops_h2.append( [ qml.PauliY(wires=[0]) @ qml.PauliZ(wires=[1]) @ qml.PauliY(wires=[2]), qml.PauliX(wires=[0]) @ qml.PauliZ(wires=[1]) @ qml.PauliX(wires=[2]), qml.PauliY(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliY(wires=[3]), qml.PauliX(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliX(wires=[3]), ] ) h3p = ["H", "H", "H"] x_h3p = np.array([0.028, 0.054, 0.0, 0.986, 1.610, 0.0, 1.855, 0.002, 0.0]) coeffs_h3p = [] coeffs_h3p.append( [ 0.47811232, 0.47811232, -0.39136385, -0.39136385, -0.39136385, -0.39136385, 0.26611147, 0.26611147, 0.26611147, 0.26611147, 0.71447791, 0.71447791, -0.11734959, -0.11734959, -0.11734959, -0.11734959, 0.24190978, 0.24190978, ] ) coeffs_h3p.append( [ 0.27769368, 0.27769368, 0.26614699, 0.26614699, 0.26614699, 0.26614699, 0.39131162, 0.39131162, 0.39131162, 0.39131162, 0.16019825, 0.16019825, -0.23616713, -0.23616713, -0.23616713, -0.23616713, 0.39510807, 0.39510807, ] ) coeffs_h3p.append([0.0]) ops_h3p = [] ops_h3p.append( [ qml.PauliZ(wires=[0]), qml.PauliZ(wires=[1]), qml.PauliY(wires=[0]) @ qml.PauliZ(wires=[1]) @ qml.PauliY(wires=[2]), qml.PauliX(wires=[0]) @ qml.PauliZ(wires=[1]) @ qml.PauliX(wires=[2]), qml.PauliY(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliY(wires=[3]), qml.PauliX(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliX(wires=[3]), qml.PauliY(wires=[0]) @ qml.PauliZ(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliY(wires=[4]), qml.PauliX(wires=[0]) @ qml.PauliZ(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliX(wires=[4]), qml.PauliY(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliZ(wires=[4]) @ qml.PauliY(wires=[5]), qml.PauliX(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliZ(wires=[4]) @ qml.PauliX(wires=[5]), qml.PauliZ(wires=[2]), qml.PauliZ(wires=[3]), qml.PauliY(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliY(wires=[4]), qml.PauliX(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliX(wires=[4]), qml.PauliY(wires=[3]) @ qml.PauliZ(wires=[4]) @ qml.PauliY(wires=[5]), qml.PauliX(wires=[3]) @ qml.PauliZ(wires=[4]) @ qml.PauliX(wires=[5]), qml.PauliZ(wires=[4]), qml.PauliZ(wires=[5]), ] ) ops_h3p.append( [ qml.PauliZ(wires=[0]), qml.PauliZ(wires=[1]), qml.PauliY(wires=[0]) @ qml.PauliZ(wires=[1]) @ qml.PauliY(wires=[2]), qml.PauliX(wires=[0]) @ qml.PauliZ(wires=[1]) @ qml.PauliX(wires=[2]), qml.PauliY(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliY(wires=[3]), qml.PauliX(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliX(wires=[3]), qml.PauliY(wires=[0]) @ qml.PauliZ(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliY(wires=[4]), qml.PauliX(wires=[0]) @ qml.PauliZ(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliX(wires=[4]), qml.PauliY(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliZ(wires=[4]) @ qml.PauliY(wires=[5]), qml.PauliX(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliZ(wires=[4]) @ qml.PauliX(wires=[5]), qml.PauliZ(wires=[2]), qml.PauliZ(wires=[3]), qml.PauliY(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliY(wires=[4]), qml.PauliX(wires=[2]) @ qml.PauliZ(wires=[3]) @ qml.PauliX(wires=[4]), qml.PauliY(wires=[3]) @ qml.PauliZ(wires=[4]) @ qml.PauliY(wires=[5]), qml.PauliX(wires=[3]) @ qml.PauliZ(wires=[4]) @ qml.PauliX(wires=[5]), qml.PauliZ(wires=[4]), qml.PauliZ(wires=[5]), ] ) ops_h3p.append([qml.Identity(wires=[0])]) h2o = ["H", "H", "O"] x_h2o = np.array([0.0, 1.431, -0.887, 0.0, -1.431, -0.887, 0.0, 0.0, 0.222]) coeffs_h2o = [] coeffs_h2o.append([-0.03700797, 0.03700797, 0.03700797, -0.03700797]) coeffs_h2o.append([0.0]) coeffs_h2o.append([0.28530461, 0.111, 0.111, -0.3710174, -0.3710174]) ops_h2o = [] ops_h2o.append( [ qml.PauliX(wires=[0]) @ qml.PauliY(wires=[1]) @ qml.PauliY(wires=[2]), qml.PauliY(wires=[0]) @ qml.PauliY(wires=[1]) @ qml.PauliX(wires=[2]), qml.PauliZ(wires=[0]) @ qml.PauliX(wires=[1]) @ qml.PauliZ(wires=[3]), qml.PauliX(wires=[1]) @ qml.PauliZ(wires=[2]), ] ) ops_h2o.append([qml.Identity(wires=[0])]) ops_h2o.append( [ qml.Identity(wires=[0]), qml.PauliZ(wires=[0]), qml.PauliZ(wires=[0]) @ qml.PauliZ(wires=[1]), qml.PauliZ(wires=[2]), qml.PauliZ(wires=[1]) @ qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[3]), ] ) @pytest.mark.parametrize( ("symbols", "coords", "charge", "core", "active", "mapping", "coeffs", "ops"), [ (h2, x_h2, 0, None, None, "jordan_wigner", coeffs_h2, ops_h2), (h3p, x_h3p, 1, None, None, "jordan_wigner", coeffs_h3p, ops_h3p), (h2o, x_h2o, 0, range(4), [4, 5], "bravyi_kitaev", coeffs_h2o, ops_h2o), ], ) @pytest.mark.usefixtures("skip_if_no_openfermion_support", "use_legacy_and_new_opmath") def test_dipole_obs(symbols, coords, charge, core, active, mapping, coeffs, ops, tol, tmpdir): r"""Tests the correctness of the dipole observable computed by the ``dipole`` function.""" dip = qml.qchem.dipole_of( symbols, coords, charge=charge, core=core, active=active, mapping=mapping, outpath=tmpdir.strpath, ) assert len(dip) == len(ops) for i, _dip in enumerate(dip): d_coeffs, d_ops = _dip.terms() calc_coeffs = np.array(d_coeffs) exp_coeffs = np.array(coeffs[i]) assert np.allclose(calc_coeffs, exp_coeffs, **tol) r_ops = ops[i] if not qml.operation.active_new_opmath(): r_ops = [ ( qml.operation.Tensor(*obs.simplify()) if isinstance(obs.simplify(), (qml.ops.op_math.Prod)) else obs.simplify() ) for obs in ops[i] ] assert all(isinstance(o1, o2.__class__) for o1, o2 in zip(d_ops, r_ops)) for o1, o2 in zip(d_ops, r_ops): qml.assert_equal(o1, o2) @pytest.mark.parametrize( ("symbols", "coords", "charge", "hf_state", "exp_dipole"), [ (h2, x_h2, 0, np.array([1, 1, 0, 0]), np.array([0.0, 0.0, 0.0])), (h3p, x_h3p, 1, np.array([1, 1, 0, 0, 0, 0]), np.array([0.95655073, 0.55522528, 0.0])), ], ) @pytest.mark.usefixtures("skip_if_no_openfermion_support") def test_dipole(symbols, coords, charge, hf_state, exp_dipole, tol, tmpdir): r"""Tests the correctness of the computed dipole moment.""" dev = qml.device("default.qubit") dip_obs = qml.qchem.dipole_of(symbols, coords, charge=charge, outpath=tmpdir.strpath) @qml.qnode(dev) def circuit(hf_state, obs): qml.BasisState(hf_state, wires=range(len(hf_state))) return qml.expval(obs) dipole = np.array([circuit(hf_state, obs) for obs in dip_obs]) assert np.allclose(dipole, exp_dipole, **tol) @pytest.mark.parametrize( ("symbols", "coords", "mult", "msg_match"), [ (["H", "H"], x_h2, 2, "this functionality is constrained to Hartree-Fock states"), (["H", "Cx"], x_h2, 1, "Requested element Cx doesn't exist"), ], ) @pytest.mark.usefixtures("skip_if_no_openfermion_support") def test_exceptions_dipole(symbols, coords, mult, msg_match): """Test exceptions of the ``dipole`` function.""" with pytest.raises(ValueError, match=msg_match): qml.qchem.dipole_of(symbols, coords, mult=mult)
pennylane/tests/qchem/openfermion_pyscf_tests/test_dipole_of.py/0
{ "file_path": "pennylane/tests/qchem/openfermion_pyscf_tests/test_dipole_of.py", "repo_id": "pennylane", "token_count": 5185 }
90
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """ Unit tests for generating basis set default parameters. """ # pylint: disable=too-many-arguments import sys import pytest from pennylane import numpy as np from pennylane import qchem class TestBasis: """Tests for generating basis set default parameters""" @pytest.mark.parametrize( ("_", "__", "l", "alpha", "coeff", "r"), [ ( "sto-3g", "H", (0, 0, 0), # data manually copied from https://www.basissetexchange.org/ [0.3425250914e01, 0.6239137298e00, 0.1688554040e00], [0.1543289673e00, 0.5353281423e00, 0.4446345422e00], [0.0000000000e00, 0.0000000000e00, -0.694349000e00], ), ], ) def test_basisfunction(self, _, __, l, alpha, coeff, r): """Test that BasisFunction class creates basis function objects correctly.""" basis_function = qchem.BasisFunction(l, alpha, coeff, r) assert np.allclose(np.array(basis_function.alpha), np.array(alpha)) assert np.allclose(np.array(basis_function.coeff), np.array(coeff)) assert np.allclose(np.array(basis_function.r), np.array(r)) assert np.allclose(basis_function.params[0], alpha) assert np.allclose(basis_function.params[1], coeff) assert np.allclose(basis_function.params[2], r) @pytest.mark.parametrize( ("basis_name", "atom_name", "params_ref"), [ # data manually copied from https://www.basissetexchange.org/ ( "sto-3g", "H", ( [ ( (0, 0, 0), # l [0.3425250914e01, 0.6239137298e00, 0.1688554040e00], # alpha [0.1543289673e00, 0.5353281423e00, 0.4446345422e00], # coeff ) ] ), ), ( "6-31g", "H", ( ( (0, 0, 0), # l [0.1873113696e02, 0.2825394365e01, 0.6401216923e00], # alpha [0.3349460434e-01, 0.2347269535e00, 0.8137573261e00], # coeff ), ( (0, 0, 0), # l [0.1612777588e00], # alpha [1.0000000], # coeff ), ), ), ( "6-31g", "O", ( ( (0, 0, 0), # l [ 0.5484671660e04, 0.8252349460e03, 0.1880469580e03, 0.5296450000e02, 0.1689757040e02, 0.5799635340e01, ], # alpha [ 0.1831074430e-02, 0.1395017220e-01, 0.6844507810e-01, 0.2327143360e00, 0.4701928980e00, 0.3585208530e00, ], # coeff ), ( (0, 0, 0), # l [0.1553961625e02, 0.3599933586e01, 0.1013761750e01], # alpha [-0.1107775495e00, -0.1480262627e00, 0.1130767015e01], # coeff ), ( (1, 0, 0), # l [0.1553961625e02, 0.3599933586e01, 0.1013761750e01], # alpha [0.7087426823e-01, 0.3397528391e00, 0.7271585773e00], # coeff ), ( (0, 1, 0), # l [0.1553961625e02, 0.3599933586e01, 0.1013761750e01], # alpha [0.7087426823e-01, 0.3397528391e00, 0.7271585773e00], # coeff ), ( (0, 0, 1), # l [0.1553961625e02, 0.3599933586e01, 0.1013761750e01], # alpha [0.7087426823e-01, 0.3397528391e00, 0.7271585773e00], # coeff ), ( (0, 0, 0), # l [0.2700058226e00], # alpha [0.1000000000e01], # coeff ), ( (1, 0, 0), # l [0.2700058226e00], # alpha [0.1000000000e01], # coeff ), ( (0, 1, 0), # l [0.2700058226e00], # alpha [0.1000000000e01], # coeff ), ( (0, 0, 1), # l [0.2700058226e00], # alpha [0.1000000000e01], # coeff ), ), ), ( "6-311g", "O", ( ( (0, 0, 0), # l [8588.5, 1297.23, 299.296, 87.3771, 25.6789, 3.74004], # alpha [0.00189515, 0.0143859, 0.070732, 0.240001, 0.594797, 0.280802], # coeff ), ( (0, 0, 0), # l [42.11750, 9.628370, 2.853320], # alpha [0.113889, 0.920811, -0.00327447], # coeff ), ( (1, 0, 0), # l [42.11750, 9.628370, 2.853320], # alpha [0.0365114, 0.237153, 0.819702], # coeff ), ( (0, 1, 0), # l [42.11750, 9.628370, 2.853320], # alpha [0.0365114, 0.237153, 0.819702], # coeff ), ( (0, 0, 1), # l [42.11750, 9.628370, 2.853320], # alpha [0.0365114, 0.237153, 0.819702], # coeff ), ( (0, 0, 0), # l [0.905661], # alpha [1.000000], # coeff ), ( (1, 0, 0), # l [0.905661], # alpha [1.000000], # coeff ), ( (0, 1, 0), # l [0.905661], # alpha [1.000000], # coeff ), ( (0, 0, 1), # l [0.905661], # alpha [1.000000], # coeff ), ( (0, 0, 0), # l [0.255611], # alpha [1.000000], # coeff ), ( (1, 0, 0), # l [0.255611], # alpha [1.000000], # coeff ), ( (0, 1, 0), # l [0.255611], # alpha [1.000000], # coeff ), ( (0, 0, 1), # l [0.255611], # alpha [1.000000], # coeff ), ), ), ( "cc-pvdz", "O", ( ( (0, 0, 0), # l [ 1.172000e04, 1.759000e03, 4.008000e02, 1.137000e02, 3.703000e01, 1.327000e01, 5.025000e00, 1.013000e00, 3.023000e-01, ], # alpha [ 7.100000e-04, 5.470000e-03, 2.783700e-02, 1.048000e-01, 2.830620e-01, 4.487190e-01, 2.709520e-01, 1.545800e-02, -2.585000e-03, ], # coeff ), ( (0, 0, 0), # l [ 1.172000e04, 1.759000e03, 4.008000e02, 1.137000e02, 3.703000e01, 1.327000e01, 5.025000e00, 1.013000e00, 3.023000e-01, ], # alpha [ -1.600000e-04, -1.263000e-03, -6.267000e-03, -2.571600e-02, -7.092400e-02, -1.654110e-01, -1.169550e-01, 5.573680e-01, 5.727590e-01, ], # coeff ), ( (0, 0, 0), # l [ 1.172000e04, 1.759000e03, 4.008000e02, 1.137000e02, 3.703000e01, 1.327000e01, 5.025000e00, 1.013000e00, 3.023000e-01, ], # alpha [ 0.000000e00, 0.000000e00, 0.000000e00, 0.000000e00, 0.000000e00, 0.000000e00, 0.000000e00, 0.000000e00, 1.000000e00, ], # coeff ), ( (1, 0, 0), # l [1.770000e01, 3.854000e00, 1.046000e00, 2.753000e-01], # alpha [4.301800e-02, 2.289130e-01, 5.087280e-01, 4.605310e-01], # coeff ), ( (0, 1, 0), # l [1.770000e01, 3.854000e00, 1.046000e00, 2.753000e-01], # alpha [4.301800e-02, 2.289130e-01, 5.087280e-01, 4.605310e-01], # coeff ), ( (0, 0, 1), # l [1.770000e01, 3.854000e00, 1.046000e00, 2.753000e-01], # alpha [4.301800e-02, 2.289130e-01, 5.087280e-01, 4.605310e-01], # coeff ), ( (1, 0, 0), # l [1.770000e01, 3.854000e00, 1.046000e00, 2.753000e-01], # alpha [0.000000e00, 0.000000e00, 0.000000e00, 1.000000e00], # coeff ), ( (0, 1, 0), # l [1.770000e01, 3.854000e00, 1.046000e00, 2.753000e-01], # alpha [0.000000e00, 0.000000e00, 0.000000e00, 1.000000e00], # coeff ), ( (0, 0, 1), # l [1.770000e01, 3.854000e00, 1.046000e00, 2.753000e-01], # alpha [0.000000e00, 0.000000e00, 0.000000e00, 1.000000e00], # coeff ), ( (1, 1, 0), # l [1.185000e00], # alpha [1.0000000], # coeff ), ( (1, 0, 1), # l [1.185000e00], # alpha [1.0000000], # coeff ), ( (0, 1, 1), # l [1.185000e00], # alpha [1.0000000], # coeff ), ( (2, 0, 0), # l [1.185000e00], # alpha [1.0000000], # coeff ), ( (0, 2, 0), # l [1.185000e00], # alpha [1.0000000], # coeff ), ( (0, 0, 2), # l [1.185000e00], # alpha [1.0000000], # coeff ), ), ), ], ) def test_atom_basis_data(self, basis_name, atom_name, params_ref): """Test that correct basis set parameters are generated for a given atom.""" params = qchem.atom_basis_data(basis_name, atom_name) l = [p[0] for p in params] l_ref = [p[0] for p in params_ref] alpha = [p[1] for p in params] alpha_ref = [p[1] for p in params_ref] coeff = [p[2] for p in params] coeff_ref = [p[2] for p in params_ref] assert l == l_ref assert alpha == alpha_ref assert coeff == coeff_ref @pytest.mark.parametrize( ("basis_name", "atom_name"), [ ( "sto-3g", "H", ), ( "6-311g", "C", ), ( "cc-pvdz", "O", ), ], ) def test_data_basis_set_exchange(self, basis_name, atom_name): """Test that correct basis set parameters are loaded from basis_set_exchange library.""" pytest.importorskip("basis_set_exchange") data_load = qchem.atom_basis_data(basis_name, atom_name, load_data=True) data_read = qchem.atom_basis_data(basis_name, atom_name, load_data=False) assert data_load == data_read basis_data_HF = [ ( "sto-3g", ["H", "F"], [1, 5], ( ( (0, 0, 0), [0.3425250914e01, 0.6239137298e00, 0.1688554040e00], [0.1543289673e00, 0.5353281423e00, 0.4446345422e00], ), ( (0, 0, 0), [0.1666791340e03, 0.3036081233e02, 0.8216820672e01], [0.1543289673e00, 0.5353281423e00, 0.4446345422e00], ), ( (0, 0, 0), [0.6464803249e01, 0.1502281245e01, 0.4885884864e00], [-0.9996722919e-01, 0.3995128261e00, 0.7001154689e00], ), ( (1, 0, 0), [0.6464803249e01, 0.1502281245e01, 0.4885884864e00], [0.1559162750e00, 0.6076837186e00, 0.3919573931e00], ), ( (0, 1, 0), [0.6464803249e01, 0.1502281245e01, 0.4885884864e00], [0.1559162750e00, 0.6076837186e00, 0.3919573931e00], ), ( (0, 0, 1), [0.6464803249e01, 0.1502281245e01, 0.4885884864e00], [0.1559162750e00, 0.6076837186e00, 0.3919573931e00], ), ), ) ] @pytest.mark.parametrize("basis_data", basis_data_HF) def test_mol_basis_data(self, basis_data): """Test that correct basis set parameters are generated for a given molecule represented as a list of atoms.""" basis, symbols, n_ref, params_ref = basis_data n_basis, params = qchem.mol_basis_data(basis, symbols) assert n_basis == n_ref assert np.allclose(params, params_ref) def test_mol_basis_data_error(self): """Test that correct error is raised if the element is not present in the internal basis-sets""" with pytest.raises(ValueError, match="The requested basis set data is not available for"): qchem.basis_set.atom_basis_data(name="sto-3g", atom="Os") with pytest.raises(ValueError, match="Requested element Ox doesn't exist"): qchem.basis_data.load_basisset(basis="sto-3g", element="Ox") class TestLoadBasis: """Tests for loading data from external libraries.""" @pytest.mark.parametrize( ("basis_name", "atom_name", "params_ref"), [ # data manually copied from https://www.basissetexchange.org/ ( "sto-3g", "H", ( [ ( "S", # l [0.3425250914e01, 0.6239137298e00, 0.1688554040e00], # alpha [0.1543289673e00, 0.5353281423e00, 0.4446345422e00], # coeff ) ] ), ), ( "6-31g", "H", ( ( "S", # l [0.1873113696e02, 0.2825394365e01, 0.6401216923e00], # alpha [0.3349460434e-01, 0.2347269535e00, 0.8137573261e00], # coeff ), ( "S", # l [0.1612777588e00], # alpha [1.0000000], # coeff ), ), ), ( "6-31g", "O", ( ( "S", # l [ 0.5484671660e04, 0.8252349460e03, 0.1880469580e03, 0.5296450000e02, 0.1689757040e02, 0.5799635340e01, ], # alpha [ 0.1831074430e-02, 0.1395017220e-01, 0.6844507810e-01, 0.2327143360e00, 0.4701928980e00, 0.3585208530e00, ], # coeff ), ( "S", # l [0.1553961625e02, 0.3599933586e01, 0.1013761750e01], # alpha [-0.1107775495e00, -0.1480262627e00, 0.1130767015e01], # coeff ), ( "P", # l [0.1553961625e02, 0.3599933586e01, 0.1013761750e01], # alpha [0.7087426823e-01, 0.3397528391e00, 0.7271585773e00], # coeff ), ( "S", # l [0.2700058226e00], # alpha [0.1000000000e01], # coeff ), ( "P", # l [0.2700058226e00], # alpha [0.1000000000e01], # coeff ), ), ), ( "6-311g", "O", ( ( "S", # l [8588.5, 1297.23, 299.296, 87.3771, 25.6789, 3.74004], # alpha [0.00189515, 0.0143859, 0.070732, 0.240001, 0.594797, 0.280802], # coeff ), ( "S", # l [42.11750, 9.628370, 2.853320], # alpha [0.113889, 0.920811, -0.00327447], # coeff ), ( "P", # l [42.11750, 9.628370, 2.853320], # alpha [0.0365114, 0.237153, 0.819702], # coeff ), ( "S", # l [0.905661], # alpha [1.000000], # coeff ), ( "P", # l [0.905661], # alpha [1.000000], # coeff ), ( "S", # l [0.255611], # alpha [1.000000], # coeff ), ( "P", # l [0.255611], # alpha [1.000000], # coeff ), ), ), ( "cc-pvdz", "O", ( ( "S", # l [ 1.172000e04, 1.759000e03, 4.008000e02, 1.137000e02, 3.703000e01, 1.327000e01, 5.025000e00, 1.013000e00, 3.023000e-01, ], # alpha [ 7.100000e-04, 5.470000e-03, 2.783700e-02, 1.048000e-01, 2.830620e-01, 4.487190e-01, 2.709520e-01, 1.545800e-02, -2.585000e-03, ], # coeff ), ( "S", # l [ 1.172000e04, 1.759000e03, 4.008000e02, 1.137000e02, 3.703000e01, 1.327000e01, 5.025000e00, 1.013000e00, 3.023000e-01, ], # alpha [ -1.600000e-04, -1.263000e-03, -6.267000e-03, -2.571600e-02, -7.092400e-02, -1.654110e-01, -1.169550e-01, 5.573680e-01, 5.727590e-01, ], # coeff ), ( "S", # l [ 1.172000e04, 1.759000e03, 4.008000e02, 1.137000e02, 3.703000e01, 1.327000e01, 5.025000e00, 1.013000e00, 3.023000e-01, ], # alpha [ 0.000000e00, 0.000000e00, 0.000000e00, 0.000000e00, 0.000000e00, 0.000000e00, 0.000000e00, 0.000000e00, 1.000000e00, ], # coeff ), ( "P", # l [1.770000e01, 3.854000e00, 1.046000e00, 2.753000e-01], # alpha [4.301800e-02, 2.289130e-01, 5.087280e-01, 4.605310e-01], # coeff ), ( "P", # l [1.770000e01, 3.854000e00, 1.046000e00, 2.753000e-01], # alpha [0.000000e00, 0.000000e00, 0.000000e00, 1.000000e00], # coeff ), ( "D", # l [1.185000e00], # alpha [1.0000000], # coeff ), ), ), ( "6-31+G*", "B", ( ( "S", # l [ 0.2068882250e04, 0.3106495700e03, 0.7068303300e02, 0.1986108030e02, 0.6299304840e01, 0.2127026970e01, ], # alpha [ 0.1866274590e-02, 0.1425148170e-01, 0.6955161850e-01, 0.2325729330e00, 0.4670787120e00, 0.3634314400e00, ], # coeff ), ( "S", # l [0.4727971071e01, 0.1190337736e01, 0.3594116829e00], # alpha [-0.1303937974e00, -0.1307889514e00, 0.1130944484e01], # coeff ), ( "P", # l [0.4727971071e01, 0.1190337736e01, 0.3594116829e00], # alpha [0.7459757992e-01, 0.3078466771e00, 0.7434568342e00], # coeff ), ( "S", # l [0.1267512469e00], # alpha [0.1000000000e01], # coeff ), ( "P", # l [0.1267512469e00], # alpha [0.1000000000e01], # coeff ), ( "D", # l [0.6000000000e00], # alpha [1.0000000], # coeff ), ( "S", # l [0.3150000000e-01], # alpha [0.1000000000e01], # coeff ), ( "P", # l [0.3150000000e-01], # alpha [0.1000000000e01], # coeff ), ), ), ( "sto-3g", "Ag", ( ( "S", # l [4744.521634, 864.2205383, 233.8918045], # alpha [0.1543289673, 0.5353281423, 0.4446345422], # coeff ), ( "S", # l [414.9652069, 96.42898995, 31.36170035], # alpha [-0.09996722919, 0.3995128261, 0.7001154689], # coeff ), ( "P", # l [414.9652069, 96.42898995, 31.36170035], # alpha [0.155916275, 0.6076837186, 0.3919573931], # coeff ), ( "S", # l [5.29023045, 2.059988316, 0.9068119281], # alpha [-0.3306100626, 0.05761095338, 1.115578745], # coeff ), ( "P", # l [5.29023045, 2.059988316, 0.9068119281], # alpha [-0.1283927634, 0.5852047641, 0.543944204], # coeff ), ( "S", # l [0.4370804803, 0.2353408164, 0.1039541771], # alpha [-0.3842642608, -0.1972567438, 1.375495512], # coeff ), ( "P", # l [0.4370804803, 0.2353408164, 0.1039541771], # alpha [-0.3481691526, 0.629032369, 0.6662832743], # coeff ), ( "SPD", # l [49.41048605, 15.07177314, 5.815158634], # alpha [-0.2277635023, 0.2175436044, 0.9166769611], # coeff ), ( "SPD", # l [49.41048605, 15.07177314, 5.815158634], # alpha [0.004951511155, 0.5777664691, 0.4846460366], # coeff ), ( "SPD", # l [49.41048605, 15.07177314, 5.815158634], # alpha [0.2197679508, 0.6555473627, 0.286573259], # coeff ), ( "D", # l [3.283395668, 1.278537254, 0.5628152469], # alpha [0.1250662138, 0.6686785577, 0.3052468245], # coeff ), ), ), ], ) def test_load_basis_data(self, basis_name, atom_name, params_ref): """Test that correct basis set parameters are loaded for a given atom.""" pytest.importorskip("basis_set_exchange") data = qchem.load_basisset(basis_name, atom_name) l_ref = [p[0] for p in params_ref] alpha_ref = [p[1] for p in params_ref] coeff_ref = [p[2] for p in params_ref] assert data["orbitals"] == l_ref assert data["exponents"] == alpha_ref assert data["coefficients"] == coeff_ref def test_fail_import(self, monkeypatch): """Test if an ImportError is raised when basis_set_exchange is requested but not installed.""" pytest.importorskip("basis_set_exchange") with monkeypatch.context() as m: m.setitem(sys.modules, "basis_set_exchange", None) with pytest.raises(ImportError, match="This feature requires basis_set_exchange"): qchem.load_basisset("sto-3g", "H")
pennylane/tests/qchem/test_basis_set.py/0
{ "file_path": "pennylane/tests/qchem/test_basis_set.py", "repo_id": "pennylane", "token_count": 24006 }
91
# Copyright 2022 Xanadu Quantum Technologies Inc. # 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. """Unit tests for differentiable quantum fidelity transform.""" # pylint: disable=too-many-public-methods import pytest import pennylane as qml from pennylane import numpy as np def expected_fidelity_rx_pauliz(param): """Return the analytical fidelity for the RX and PauliZ.""" return (np.cos(param / 2)) ** 2 def expected_grad_fidelity_rx_pauliz(param): """Return the analytical gradient of the fidelity for the RX and PauliZ.""" return -np.sin(param) / 2 class TestFidelityQnode: """Tests for Fidelity function between two QNodes.""" devices = ["default.qubit", "lightning.qubit", "default.mixed"] @pytest.mark.parametrize("device", devices) def test_not_same_number_wires(self, device): """Test that wires must have the same length.""" dev = qml.device(device, wires=2) @qml.qnode(dev) def circuit0(): return qml.state() @qml.qnode(dev) def circuit1(): return qml.state() with pytest.raises( qml.QuantumFunctionError, match="The two states must have the same number of wires" ): qml.qinfo.fidelity(circuit0, circuit1, wires0=[0, 1], wires1=[0])() @pytest.mark.parametrize("device", devices) def test_fidelity_qnodes_rxs(self, device): """Test the fidelity between two Rx circuits""" dev = qml.device(device, wires=1) @qml.qnode(dev) def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev) def circuit1(y): qml.RX(y, wires=0) return qml.state() fid = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])((0.1), (0.1)) assert qml.math.allclose(fid, 1.0) @pytest.mark.parametrize("device", devices) def test_fidelity_qnodes_rxrz_ry(self, device): """Test the fidelity between two circuit Rx Rz and Ry.""" dev = qml.device(device, wires=1) @qml.qnode(dev) def circuit0(x, y): qml.RX(x, wires=0) qml.RY(y, wires=0) return qml.state() @qml.qnode(dev) def circuit1(y): qml.RY(y, wires=0) return qml.state() fid = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])((0.0, 0.2), (0.2)) assert qml.math.allclose(fid, 1.0) @pytest.mark.parametrize("device", devices) def test_fidelity_qnodes_rx_state(self, device): """Test the fidelity between RX and state(1,0).""" dev = qml.device(device, wires=1) @qml.qnode(dev) def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev) def circuit1(): return qml.state() fid = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])((np.pi)) assert qml.math.allclose(fid, 0.0) @pytest.mark.parametrize("device", devices) def test_fidelity_qnodes_state_rx(self, device): """Test the fidelity between state (1,0) and RX circuit.""" dev = qml.device(device, wires=1) @qml.qnode(dev) def circuit0(): return qml.state() @qml.qnode(dev) def circuit1(x): qml.RX(x, wires=0) return qml.state() fid = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])(all_args1=(np.pi)) assert qml.math.allclose(fid, 0.0) @pytest.mark.parametrize("device", devices) def test_fidelity_qnodes_rxrz_rxry(self, device): """Test the fidelity between two circuit with multiple arguments.""" dev = qml.device(device, wires=1) @qml.qnode(dev) def circuit0(x, y): qml.RX(x, wires=0) qml.RZ(y, wires=0) return qml.state() @qml.qnode(dev) def circuit1(x, y): qml.RX(x, wires=0) qml.RY(y, wires=0) return qml.state() fid_args = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])( (0.0, np.pi), (0.0, 0.0) ) fid_arg_kwarg = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])( (0.0, {"y": np.pi}), (0.0, {"y": 0}) ) fid_kwargs = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])( ({"x": 0, "y": np.pi}), ({"x": 0, "y": 0}) ) assert qml.math.allclose(fid_args, 1.0) assert qml.math.allclose(fid_arg_kwarg, 1.0) assert qml.math.allclose(fid_kwargs, 1.0) parameters = np.linspace(0, 2 * np.pi, 20) wires = [1, 2] @pytest.mark.parametrize("device", devices) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) def test_fidelity_qnodes_rx_pauliz(self, device, param, wire): """Test the fidelity between Rx and PauliZ circuits.""" dev = qml.device(device, wires=[wire]) @qml.qnode(dev) def circuit0(x): qml.RX(x, wires=wire) return qml.state() @qml.qnode(dev) def circuit1(): qml.PauliZ(wires=wire) return qml.state() fid = qml.qinfo.fidelity(circuit0, circuit1, wires0=[wire], wires1=[wire])((param)) expected_fid = expected_fidelity_rx_pauliz(param) assert qml.math.allclose(fid, expected_fid) @pytest.mark.autograd @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) def test_fidelity_qnodes_rx_pauliz_grad(self, param, wire): """Test the gradient of the fidelity between Rx and PauliZ circuits.""" dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface="autograd", diff_method="backprop") def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface="autograd", diff_method="backprop") def circuit1(): qml.PauliZ(wires=0) return qml.state() fid_grad = qml.grad(qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0]))( (qml.numpy.array(param, requires_grad=True)) ) expected_fid = expected_grad_fidelity_rx_pauliz(param) assert qml.math.allclose(fid_grad, expected_fid) @pytest.mark.parametrize("device", devices) def test_fidelity_wire_labels(self, device, tol): """Test that fidelity is correct with custom wire labels""" param = np.array([0.678, 1.234]) wires = ["a", 8] dev = qml.device(device, wires=wires) @qml.qnode(dev) def circuit(x): qml.PauliX(wires=wires[0]) qml.IsingXX(x, wires=wires) return qml.state() fid_circuit = qml.qinfo.fidelity(circuit, circuit, [wires[0]], [wires[1]]) actual = fid_circuit((param[0],), (param[1],)) expected = ( np.sin(param[0] / 2) * np.cos(param[1] / 2) + np.sin(param[1] / 2) * np.cos(param[0] / 2) ) ** 2 assert np.allclose(actual, expected, atol=tol) interfaces = ["auto", "autograd"] @pytest.mark.autograd @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_pauliz_rx_grad(self, param, wire, interface): """Test the gradient of the fidelity between PauliZ and Rx circuits.""" dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit0(): qml.PauliZ(wires=0) return qml.state() @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit1(x): qml.RX(x, wires=0) return qml.state() fid_grad = qml.grad(qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0]))( None, (qml.numpy.array(param, requires_grad=True)) ) expected_fid = expected_grad_fidelity_rx_pauliz(param) assert qml.math.allclose(fid_grad, expected_fid) @pytest.mark.autograd @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_tworx_grad(self, param, wire, interface): """Test the gradient of the fidelity between two trainable circuits.""" dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit(x): qml.RX(x, wires=0) return qml.state() fid_grad = qml.grad(qml.qinfo.fidelity(circuit, circuit, wires0=[0], wires1=[0]))( (qml.numpy.array(param, requires_grad=True)), (qml.numpy.array(2 * param, requires_grad=True)), ) expected = expected_grad_fidelity_rx_pauliz(param) expected_fid = [-expected, expected] assert qml.math.allclose(fid_grad, expected_fid) interfaces = ["torch"] @pytest.mark.torch @pytest.mark.parametrize("device", devices) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_torch(self, device, param, wire, interface): """Test the fidelity between Rx and PauliZ circuits with Torch.""" import torch dev = qml.device(device, wires=wire) @qml.qnode(dev, interface=interface) def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface="torch") def circuit1(): qml.PauliZ(wires=0) return qml.state() fid = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])((torch.tensor(param))) expected_fid = expected_fidelity_rx_pauliz(param) assert qml.math.allclose(fid, expected_fid) @pytest.mark.torch @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_torch_grad(self, param, wire, interface): """Test the gradient of fidelity between Rx and PauliZ circuits with Torch.""" import torch dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface="torch", diff_method="backprop") def circuit1(): qml.PauliZ(wires=0) return qml.state() expected_fid_grad = expected_grad_fidelity_rx_pauliz(param) param = torch.tensor(param, dtype=torch.float64, requires_grad=True) fid = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])((param)) fid.backward() fid_grad = param.grad assert qml.math.allclose(fid_grad, expected_fid_grad) @pytest.mark.torch @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_pauliz_rx_torch_grad(self, param, wire, interface): """Test the gradient of the fidelity between PauliZ and Rx circuits with Torch.""" import torch dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface="torch", diff_method="backprop") def circuit0(): qml.PauliZ(wires=0) return qml.state() @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit1(x): qml.RX(x, wires=0) return qml.state() expected_fid = expected_grad_fidelity_rx_pauliz(param) param = torch.tensor(param, dtype=torch.float64, requires_grad=True) fid = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])(None, (param)) fid.backward() fid_grad = param.grad assert qml.math.allclose(fid_grad, expected_fid) @pytest.mark.torch @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_tworx_torch_grad(self, param, wire, interface): """Test the gradient of the fidelity between two trainable circuits with Torch.""" import torch dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit(x): qml.RX(x, wires=0) return qml.state() expected = expected_grad_fidelity_rx_pauliz(param) expected_fid = [-expected, expected] params = ( torch.tensor(param, dtype=torch.float64, requires_grad=True), torch.tensor(2 * param, dtype=torch.float64, requires_grad=True), ) fid = qml.qinfo.fidelity(circuit, circuit, wires0=[0], wires1=[0])(*params) fid.backward() fid_grad = [p.grad for p in params] assert qml.math.allclose(fid_grad, expected_fid) interfaces = ["tf"] @pytest.mark.tf @pytest.mark.parametrize("device", devices) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_tf(self, device, param, wire, interface): """Test the fidelity between Rx and PauliZ circuits with Tensorflow.""" import tensorflow as tf dev = qml.device(device, wires=wire) @qml.qnode(dev, interface=interface) def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface="tf") def circuit1(): qml.PauliZ(wires=0) return qml.state() fid = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])((tf.Variable(param))) expected_fid = expected_fidelity_rx_pauliz(param) assert qml.math.allclose(fid, expected_fid) @pytest.mark.tf @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_tf_grad(self, param, wire, interface): """Test the gradient of fidelity between Rx and PauliZ circuits with Tensorflow.""" import tensorflow as tf dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface) def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface="tf") def circuit1(): qml.PauliZ(wires=0) return qml.state() expected_grad_fid = expected_grad_fidelity_rx_pauliz(param) param = tf.Variable(param) with tf.GradientTape() as tape: entropy = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])((param)) fid_grad = tape.gradient(entropy, param) assert qml.math.allclose(fid_grad, expected_grad_fid) @pytest.mark.tf @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_pauliz_rx_tf_grad(self, param, wire, interface): """Test the gradient of the fidelity between PauliZ and Rx circuits with Tensorflow.""" import tensorflow as tf dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface="tf") def circuit0(): qml.PauliZ(wires=0) return qml.state() @qml.qnode(dev, interface=interface) def circuit1(x): qml.RX(x, wires=0) return qml.state() expected_fid = expected_grad_fidelity_rx_pauliz(param) param = tf.Variable(param) with tf.GradientTape() as tape: entropy = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])(None, (param)) fid_grad = tape.gradient(entropy, param) assert qml.math.allclose(fid_grad, expected_fid) @pytest.mark.tf @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_tworx_tf_grad(self, param, wire, interface): """Test the gradient of the fidelity between two trainable circuits with Tensorflow.""" import tensorflow as tf dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit(x): qml.RX(x, wires=0) return qml.state() expected = expected_grad_fidelity_rx_pauliz(param) expected_fid = [-expected, expected] params = (tf.Variable(param), tf.Variable(2 * param)) with tf.GradientTape() as tape: fid = qml.qinfo.fidelity(circuit, circuit, wires0=[0], wires1=[0])(*params) fid_grad = tape.gradient(fid, params) assert qml.math.allclose(fid_grad, expected_fid) interfaces = ["jax"] @pytest.mark.jax @pytest.mark.parametrize("device", devices) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_jax(self, device, param, wire, interface): """Test the fidelity between Rx and PauliZ circuits with Jax.""" import jax dev = qml.device(device, wires=wire) @qml.qnode(dev, interface=interface) def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface="jax") def circuit1(): qml.PauliZ(wires=0) return qml.state() fid = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])( (jax.numpy.array(param)) ) expected_fid = expected_fidelity_rx_pauliz(param) assert qml.math.allclose(fid, expected_fid, rtol=1e-03, atol=1e-04) @pytest.mark.jax @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) def test_fidelity_qnodes_rx_pauliz_jax_jit(self, param, wire): """Test the fidelity between Rx and PauliZ circuits with Jax jit.""" import jax # TODO: add default mixed dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface="jax-jit") def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface="jax") def circuit1(): qml.PauliZ(wires=0) return qml.state() fid = jax.jit(qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0]))( (jax.numpy.array(param)) ) expected_fid = expected_fidelity_rx_pauliz(param) assert qml.math.allclose(fid, expected_fid, rtol=1e-03, atol=1e-04) @pytest.mark.jax @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_jax_grad(self, param, wire, interface): """Test the gradient of the fidelity between Rx and PauliZ circuits.""" import jax dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface) def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface="jax") def circuit1(): qml.PauliZ(wires=0) return qml.state() fid_grad = jax.grad(qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0]))( (jax.numpy.array(param)) ) expected_fid = expected_grad_fidelity_rx_pauliz(param) assert qml.math.allclose(fid_grad, expected_fid, rtol=1e-04, atol=1e-03) @pytest.mark.jax @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_jax_grad_jit(self, param, interface): """Test the gradient of the fidelity between Rx and PauliZ circuits.""" import jax dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface) def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface="jax") def circuit1(): qml.PauliZ(wires=0) return qml.state() fid_grad = jax.jit( jax.grad(qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])) )((jax.numpy.array(param))) expected_fid = expected_grad_fidelity_rx_pauliz(param) assert qml.math.allclose(fid_grad, expected_fid, rtol=1e-04, atol=1e-03) @pytest.mark.jax @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_pauliz_rx_jax_grad(self, param, wire, interface): """Test the gradient of the fidelity between PauliZ and Rx circuits with Jax.""" import jax dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface="jax") def circuit0(): qml.PauliZ(wires=0) return qml.state() @qml.qnode(dev, interface=interface) def circuit1(x): qml.RX(x, wires=0) return qml.state() fid_grad = jax.grad( qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0]), argnums=1 )(None, (jax.numpy.array(param))) expected_fid = expected_grad_fidelity_rx_pauliz(param) assert qml.math.allclose(fid_grad, expected_fid, rtol=1e-04, atol=1e-03) @pytest.mark.jax @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_pauliz_rx_jax_grad_jit(self, param, interface): """Test the gradient of the fidelity between PauliZ and Rx circuits with Jax.""" import jax dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface="jax") def circuit0(): qml.PauliZ(wires=0) return qml.state() @qml.qnode(dev, interface=interface) def circuit1(x): qml.RX(x, wires=0) return qml.state() fid_grad = jax.jit( jax.grad(qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0]), argnums=1) )(None, (jax.numpy.array(param))) expected_fid = expected_grad_fidelity_rx_pauliz(param) assert qml.math.allclose(fid_grad, expected_fid, rtol=1e-04, atol=1e-03) @pytest.mark.jax @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_tworx_jax_grad(self, param, wire, interface): """Test the gradient of the fidelity between two trainable circuits with Jax.""" import jax dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface) def circuit(x): qml.RX(x, wires=0) return qml.state() fid_grad = jax.grad( qml.qinfo.fidelity(circuit, circuit, wires0=[0], wires1=[0]), argnums=[0, 1] )( (jax.numpy.array(param)), (jax.numpy.array(2 * param)), ) expected = expected_grad_fidelity_rx_pauliz(param) expected_fid = [-expected, expected] assert qml.math.allclose(fid_grad, expected_fid, rtol=1e-04, atol=1e-03) @pytest.mark.jax @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_tworx_jax_grad_jit(self, param, interface): """Test the gradient of the fidelity between two trainable circuits with Jax.""" import jax dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface) def circuit(x): qml.RX(x, wires=0) return qml.state() fid_grad = jax.jit( jax.grad(qml.qinfo.fidelity(circuit, circuit, wires0=[0], wires1=[0]), argnums=[0, 1]) )((jax.numpy.array(param)), (jax.numpy.array(2 * param))) expected = expected_grad_fidelity_rx_pauliz(param) expected_fid = [-expected, expected] assert qml.math.allclose(fid_grad, expected_fid, rtol=1e-04, atol=1e-03) interfaces = ["auto", "autograd"] @pytest.mark.autograd @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_grad_two_params(self, param, wire, interface): """Test the gradient of the fidelity between Rx and PauliZ circuits with two parameters.""" dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit1(x): qml.RX(x, wires=0) qml.RX(-x, wires=0) qml.PauliZ(wires=0) return qml.state() fid_grad = qml.grad(qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0]))( (qml.numpy.array(param, requires_grad=True)), (qml.numpy.array(2.0, requires_grad=True)) ) expected_fid_grad = expected_grad_fidelity_rx_pauliz(param) assert qml.math.allclose(fid_grad, (expected_fid_grad, 0.0)) interfaces = ["torch"] @pytest.mark.torch @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_torch_grad_two_params(self, param, wire, interface): """Test the gradient of fidelity between Rx and PauliZ circuits with Torch and two parameters.""" import torch dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit1(x): qml.RX(x, wires=0) qml.RX(-x, wires=0) qml.PauliZ(wires=0) return qml.state() expected_fid_grad = expected_grad_fidelity_rx_pauliz(param) param = torch.tensor(param, dtype=torch.float64, requires_grad=True) param2 = torch.tensor(0, dtype=torch.float64, requires_grad=True) fid = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])((param), (param2)) fid.backward() fid_grad = (param.grad, param2.grad) assert qml.math.allclose(fid_grad, (expected_fid_grad, 0.0)) interfaces = ["tf"] @pytest.mark.tf @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_tf_grad_two_params(self, param, wire, interface): """Test the gradient of fidelity between Rx and PauliZ circuits with Tensorflow and two parameters.""" import tensorflow as tf dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface) def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface=interface) def circuit1(x): qml.RX(x, wires=0) qml.RX(-x, wires=0) qml.PauliZ(wires=0) return qml.state() expected_fid_grad = expected_grad_fidelity_rx_pauliz(param) param1 = tf.Variable(param) params2 = tf.Variable(0.0) with tf.GradientTape() as tape: entropy = qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0])( (param1), (params2) ) fid_grad = tape.gradient(entropy, [param1, params2]) assert qml.math.allclose(fid_grad, (expected_fid_grad, 0.0)) interfaces = ["jax"] @pytest.mark.jax @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_jax_grad_two_params(self, param, wire, interface): """Test the gradient of the fidelity between Rx and PauliZ circuits with Jax and two params.""" import jax dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface) def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface=interface) def circuit1(x): qml.RX(x, wires=0) qml.RX(-x, wires=0) qml.PauliZ(wires=0) return qml.state() fid_grad = jax.grad( qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0]), argnums=[0, 1] )((jax.numpy.array(param)), (jax.numpy.array(2.0))) expected_fid_grad = expected_grad_fidelity_rx_pauliz(param) assert qml.math.allclose(fid_grad, (expected_fid_grad, 0.0), rtol=1e-03, atol=1e-04) interfaces = ["jax"] @pytest.mark.jax @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("wire", wires) @pytest.mark.parametrize("interface", interfaces) def test_fidelity_qnodes_rx_pauliz_jax_jit_grad_two_params(self, param, wire, interface): """Test the gradient of the fidelity between Rx and PauliZ circuits with Jax Jit and two params.""" import jax dev = qml.device("default.qubit", wires=wire) @qml.qnode(dev, interface=interface) def circuit0(x): qml.RX(x, wires=0) return qml.state() @qml.qnode(dev, interface=interface) def circuit1(x): qml.RX(x, wires=0) qml.RX(-x, wires=0) qml.PauliZ(wires=0) return qml.state() fid_grad = jax.jit( jax.grad(qml.qinfo.fidelity(circuit0, circuit1, wires0=[0], wires1=[0]), argnums=[0, 1]) )((jax.numpy.array(param)), (jax.numpy.array(2.0))) expected_fid_grad = expected_grad_fidelity_rx_pauliz(param) assert qml.math.allclose(fid_grad, (expected_fid_grad, 0.0), rtol=1e-03, atol=1e-04) @pytest.mark.parametrize("device", ["default.qubit", "default.mixed"]) def test_broadcasting(device): """Test that the fidelity transform supports broadcasting""" dev = qml.device(device, wires=2) @qml.qnode(dev) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() x = np.array([0.4, 0.6, 0.8]) y = np.array([0.6, 0.8, 1.0]) fid = qml.qinfo.fidelity(circuit_state, circuit_state, wires0=[0], wires1=[1])(x, y) expected = 0.5 * (np.sin(x) * np.sin(y) + np.cos(x) * np.cos(y) + 1) assert qml.math.allclose(fid, expected)
pennylane/tests/qinfo/test_fidelity.py/0
{ "file_path": "pennylane/tests/qinfo/test_fidelity.py", "repo_id": "pennylane", "token_count": 15009 }
92
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """Unit tests for the specs transform""" from collections import defaultdict from contextlib import nullcontext import pytest import pennylane as qml from pennylane import numpy as pnp from pennylane.tape import QuantumScript, QuantumScriptBatch from pennylane.typing import PostprocessingFn with pytest.warns(qml.PennyLaneDeprecationWarning): devices_list = [ (qml.device("default.qubit"), 1), (qml.device("default.qubit", wires=2), 2), (qml.device("default.qubit.legacy", wires=2), 2), ] class TestSpecsTransform: """Tests for the transform specs using the QNode""" def sample_circuit(self): @qml.transforms.merge_rotations @qml.transforms.undo_swaps @qml.transforms.cancel_inverses @qml.qnode(qml.device("default.qubit"), diff_method="parameter-shift", shifts=pnp.pi / 4) def circuit(x): qml.RandomLayers(qml.numpy.array([[1.0, 2.0]]), wires=(0, 1)) qml.RX(x, wires=0) qml.RX(-x, wires=0) qml.SWAP((0, 1)) qml.X(0) qml.X(0) return qml.expval(qml.sum(qml.X(0), qml.Y(1))) return circuit def test_max_expansion_throws_warning(self): dev = qml.device("default.qubit", wires=1) @qml.qnode(dev, diff_method="backprop") def circ(): return qml.expval(qml.PauliZ(0)) with pytest.warns(qml.PennyLaneDeprecationWarning, match="'max_expansion' has no effect"): qml.specs(circ, max_expansion=10)() def test_only_one_of_level_or_expansion_strategy_passed(self): dev = qml.device("default.qubit", wires=1) @qml.qnode(dev, diff_method="backprop") def circ(): return qml.expval(qml.PauliZ(0)) with pytest.raises(ValueError, match="Either 'level' or 'expansion_strategy'"): qml.specs(circ, level="device", expansion_strategy="gradient") def test_disallow_pos_args(self): circ = self.sample_circuit() with pytest.raises(TypeError, match="takes 1 positional argument"): qml.specs(circ, "device")(0.1) @pytest.mark.parametrize( "level,expected_gates,exptected_train_params", [(0, 6, 1), (1, 4, 3), (2, 3, 3), (3, 1, 1), (None, 2, 2)], ) def test_int_specs_level(self, level, expected_gates, exptected_train_params): circ = self.sample_circuit() specs = qml.specs(circ, level=level)(0.1) assert specs["level"] == level assert specs["resources"].num_gates == expected_gates assert specs["num_trainable_params"] == exptected_train_params @pytest.mark.parametrize( "level1,level2", [ ("top", 0), (0, slice(0, 0)), ("user", 3), ("user", slice(0, 3)), (None, slice(0, None)), (-1, slice(0, -1)), ("device", slice(0, None)), ], ) def test_equivalent_levels(self, level1, level2): circ = self.sample_circuit() specs1 = qml.specs(circ, level=level1)(0.1) specs2 = qml.specs(circ, level=level2)(0.1) del specs1["level"] del specs2["level"] assert specs1 == specs2 @pytest.mark.parametrize( "diff_method, len_info", [("backprop", 13), ("parameter-shift", 14), ("adjoint", 13)] ) def test_empty(self, diff_method, len_info): dev = qml.device("default.qubit", wires=1) @qml.qnode(dev, diff_method=diff_method) def circ(): return qml.expval(qml.PauliZ(0)) with ( pytest.warns(UserWarning, match="gradient of a tape with no trainable parameters") if diff_method == "parameter-shift" else nullcontext() ): info_func = qml.specs(circ) info = info_func() assert len(info) == len_info expected_resources = qml.resource.Resources(num_wires=1, gate_types=defaultdict(int)) assert info["resources"] == expected_resources assert info["num_observables"] == 1 assert info["num_diagonalizing_gates"] == 0 assert info["num_device_wires"] == 1 assert info["diff_method"] == diff_method assert info["num_trainable_params"] == 0 assert info["device_name"] == dev.name assert info["level"] == "gradient" if diff_method == "parameter-shift": assert info["num_gradient_executions"] == 0 assert info["gradient_fn"] == "pennylane.gradients.parameter_shift.param_shift" @pytest.mark.parametrize( "diff_method, len_info", [("backprop", 13), ("parameter-shift", 14), ("adjoint", 13)] ) def test_specs(self, diff_method, len_info): """Test the specs transforms works in standard situations""" dev = qml.device("default.qubit", wires=4) @qml.qnode(dev, diff_method=diff_method) def circuit(x, y, add_RY=True): qml.RX(x[0], wires=0) qml.Toffoli(wires=(0, 1, 2)) qml.CRY(x[1], wires=(0, 1)) qml.Rot(x[2], x[3], y, wires=2) if add_RY: qml.RY(x[4], wires=1) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliX(1)) x = pnp.array([0.05, 0.1, 0.2, 0.3, 0.5], requires_grad=True) y = pnp.array(0.1, requires_grad=False) info = qml.specs(circuit)(x, y, add_RY=False) assert len(info) == len_info gate_sizes = defaultdict(int, {1: 2, 3: 1, 2: 1}) gate_types = defaultdict(int, {"RX": 1, "Toffoli": 1, "CRY": 1, "Rot": 1}) expected_resources = qml.resource.Resources( num_wires=3, num_gates=4, gate_types=gate_types, gate_sizes=gate_sizes, depth=3 ) assert info["resources"] == expected_resources assert info["num_observables"] == 2 assert info["num_diagonalizing_gates"] == 1 assert info["num_device_wires"] == 4 assert info["diff_method"] == diff_method assert info["num_trainable_params"] == 4 assert info["device_name"] == dev.name assert info["level"] == "gradient" if diff_method == "parameter-shift": assert info["num_gradient_executions"] == 6 @pytest.mark.parametrize( "diff_method, len_info", [("backprop", 13), ("parameter-shift", 14), ("adjoint", 13)] ) def test_specs_state(self, diff_method, len_info): """Test specs works when state returned""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method=diff_method) def circuit(): return qml.state() info = qml.specs(circuit)() assert len(info) == len_info assert info["resources"] == qml.resource.Resources(gate_types=defaultdict(int)) assert info["num_observables"] == 1 assert info["num_diagonalizing_gates"] == 0 assert info["level"] == "gradient" def test_splitting_transforms(self): coeffs = [0.2, -0.543, 0.1] obs = [qml.X(0) @ qml.Z(1), qml.Z(0) @ qml.Y(2), qml.Y(0) @ qml.X(2)] H = qml.Hamiltonian(coeffs, obs) @qml.transforms.split_non_commuting @qml.transforms.merge_rotations @qml.qnode(qml.device("default.qubit"), diff_method="parameter-shift", shifts=pnp.pi / 4) def circuit(x): qml.RandomLayers(qml.numpy.array([[1.0, 2.0]]), wires=(0, 1)) qml.RX(x, wires=0) qml.RX(-x, wires=0) qml.SWAP((0, 1)) qml.X(0) qml.X(0) return qml.expval(H) specs_instance = qml.specs(circuit, level=1)(pnp.array([1.23, -1])) assert isinstance(specs_instance, dict) specs_list = qml.specs(circuit, level=2)(pnp.array([1.23, -1])) assert len(specs_list) == len(H) assert specs_list[0]["num_diagonalizing_gates"] == 1 assert specs_list[1]["num_diagonalizing_gates"] == 3 assert specs_list[2]["num_diagonalizing_gates"] == 4 assert specs_list[0]["num_device_wires"] == specs_list[0]["num_tape_wires"] == 2 assert specs_list[1]["num_device_wires"] == specs_list[1]["num_tape_wires"] == 3 assert specs_list[2]["num_device_wires"] == specs_list[1]["num_tape_wires"] == 3 def make_qnode_and_params(self, initial_expansion_strategy): """Generates a qnode and params for use in other tests""" n_layers = 2 n_wires = 5 dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev, expansion_strategy=initial_expansion_strategy) def circuit(params): qml.BasicEntanglerLayers(params, wires=range(n_wires)) return qml.expval(qml.PauliZ(0)) params_shape = qml.BasicEntanglerLayers.shape(n_layers=n_layers, n_wires=n_wires) rng = pnp.random.default_rng(seed=10) params = rng.standard_normal(params_shape) # pylint:disable=no-member return circuit, params @pytest.mark.xfail(reason="DefaultQubit2 does not support custom expansion depths") def test_max_expansion(self): """Test that a user can calculate specifications for a different max expansion parameter.""" circuit, params = self.make_qnode_and_params("device") assert circuit.max_expansion == 10 with pytest.warns(UserWarning, match="'max_expansion' has no effect"): info = qml.specs(circuit, max_expansion=0)(params) assert circuit.max_expansion == 10 assert len(info) == 11 gate_sizes = defaultdict(int, {5: 1}) gate_types = defaultdict(int, {"BasicEntanglerLayers": 1}) expected_resources = qml.resource.Resources( num_wires=5, num_gates=1, gate_types=gate_types, gate_sizes=gate_sizes, depth=1 ) assert info["resources"] == expected_resources assert info["num_observables"] == 1 assert info["num_device_wires"] == 5 assert info["device_name"] == "default.qubit" assert info["diff_method"] == "best" assert info["gradient_fn"] == "backprop" def test_expansion_strategy(self): """Test that a user can calculate specs for different expansion strategies.""" with pytest.warns( qml.PennyLaneDeprecationWarning, match="'expansion_strategy' attribute is deprecated" ): circuit, params = self.make_qnode_and_params("gradient") assert circuit.expansion_strategy == "gradient" with pytest.warns( qml.PennyLaneDeprecationWarning, match="'expansion_strategy' argument is deprecated" ): info = qml.specs(circuit, expansion_strategy="device")(params) assert circuit.expansion_strategy == "gradient" assert len(info) == 13 def test_gradient_transform(self): """Test that a gradient transform is properly labelled""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, diff_method=qml.gradients.param_shift) def circuit(): return qml.probs(wires=0) with pytest.warns(UserWarning, match="gradient of a tape with no trainable parameters"): info = qml.specs(circuit)() assert info["diff_method"] == "pennylane.gradients.parameter_shift.param_shift" assert info["gradient_fn"] == "pennylane.gradients.parameter_shift.param_shift" def test_custom_gradient_transform(self): """Test that a custom gradient transform is properly labelled""" dev = qml.device("default.qubit", wires=2) @qml.transform def my_transform(tape: QuantumScript) -> tuple[QuantumScriptBatch, PostprocessingFn]: return tape, None @qml.qnode(dev, diff_method=my_transform) def circuit(): return qml.probs(wires=0) info = qml.specs(circuit)() assert info["diff_method"] == "test_specs.my_transform" assert info["gradient_fn"] == "test_specs.my_transform" @pytest.mark.parametrize( "device,num_wires", devices_list, ) def test_num_wires_source_of_truth(self, device, num_wires): """Tests that num_wires behaves differently on old and new devices.""" @qml.qnode(device) def circuit(): qml.PauliX(0) return qml.state() info = qml.specs(circuit)() assert info["num_device_wires"] == num_wires def test_no_error_contents_on_device_level(self): coeffs = [0.25, 0.75] ops = [qml.X(0), qml.Z(0)] H = qml.dot(coeffs, ops) @qml.qnode(qml.device("default.qubit")) def circuit(): qml.Hadamard(0) qml.TrotterProduct(H, time=2.4, order=2) return qml.state() top_specs = qml.specs(circuit, level="top")() dev_specs = qml.specs(circuit, level="device")() assert "SpectralNormError" in top_specs["errors"] assert pnp.allclose(top_specs["errors"]["SpectralNormError"].error, 13.824) # At the device level, approximations don't exist anymore and therefore # we should expect an empty errors dictionary. assert dev_specs["errors"] == {}
pennylane/tests/resource/test_specs.py/0
{ "file_path": "pennylane/tests/resource/test_specs.py", "repo_id": "pennylane", "token_count": 6216 }
93
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """ Tests for the AllSinglesDoubles template. """ import numpy as np # pylint: disable=too-many-arguments,too-few-public-methods import pytest import pennylane as qml from pennylane import numpy as pnp def test_standard_validity(): """Run standard tests of operation validity.""" op = qml.AllSinglesDoubles( [1, 2], wires=range(4), hf_state=np.array([1, 1, 0, 0]), singles=[[0, 1]], doubles=[[0, 1, 2, 3]], ) qml.ops.functions.assert_valid(op) class TestDecomposition: """Tests that the template defines the correct decomposition.""" @pytest.mark.parametrize( ("singles", "doubles", "weights", "ref_gates"), [ ( [[0, 2], [0, 4], [1, 3], [1, 5]], [[0, 1, 2, 3], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 4, 5]], np.array( [ -0.39926835, 2.24302631, -1.87369867, 2.66863856, 0.08284505, -1.90970947, 1.70143771, -1.0404567, ] ), [ [0, qml.BasisState, [0, 1, 2, 3, 4, 5], [np.array([1, 1, 0, 0, 0, 0])]], [5, qml.SingleExcitation, [0, 2], [-0.39926835]], [6, qml.SingleExcitation, [0, 4], [2.24302631]], [7, qml.SingleExcitation, [1, 3], [-1.87369867]], [8, qml.SingleExcitation, [1, 5], [2.66863856]], [1, qml.DoubleExcitation, [0, 1, 2, 3], [0.08284505]], [2, qml.DoubleExcitation, [0, 1, 2, 5], [-1.90970947]], [3, qml.DoubleExcitation, [0, 1, 3, 4], [1.70143771]], [4, qml.DoubleExcitation, [0, 1, 4, 5], [-1.0404567]], ], ), ( [[1, 5]], [], np.array([3.815]), [ [0, qml.BasisState, [0, 1, 2, 3, 4, 5], [np.array([1, 1, 0, 0, 0, 0])]], [1, qml.SingleExcitation, [1, 5], [3.815]], ], ), ( [], [[0, 1, 4, 5]], np.array([4.866]), [ [0, qml.BasisState, [0, 1, 2, 3, 4, 5], [np.array([1, 1, 0, 0, 0, 0])]], [1, qml.DoubleExcitation, [0, 1, 4, 5], [4.866]], ], ), ], ) def test_allsinglesdoubles_operations(self, singles, doubles, weights, ref_gates): """Test the correctness of the AllSinglesDoubles template including the gate count and order, the wires the operation acts on and the correct use of parameters in the circuit.""" N = 6 wires = range(N) hf_state = np.array([1, 1, 0, 0, 0, 0]) op = qml.AllSinglesDoubles(weights, wires, hf_state, singles=singles, doubles=doubles) queue = op.decomposition() assert len(queue) == len(singles) + len(doubles) + 1 for gate in ref_gates: idx = gate[0] exp_gate = gate[1] res_gate = queue[idx] assert isinstance(res_gate, exp_gate) exp_wires = gate[2] res_wires = queue[idx].wires assert res_wires.tolist() == exp_wires exp_weight = gate[3] res_weight = queue[idx].parameters assert np.allclose(res_weight, exp_weight) def test_custom_wire_labels(self, tol): """Test that template can deal with non-numeric, nonconsecutive wire labels.""" weights = [0.1, 0.2] dev = qml.device("default.qubit", wires=4) dev2 = qml.device("default.qubit", wires=["z", "a", "k", "e"]) @qml.qnode(dev) def circuit(): qml.AllSinglesDoubles( weights, wires=range(4), hf_state=np.array([1, 1, 0, 0]), singles=[[0, 1]], doubles=[[0, 1, 2, 3]], ) return qml.expval(qml.Identity(0)), qml.state() @qml.qnode(dev2) def circuit2(): qml.AllSinglesDoubles( weights, wires=["z", "a", "k", "e"], hf_state=np.array([1, 1, 0, 0]), singles=[["z", "a"]], doubles=[["z", "a", "k", "e"]], ) return qml.expval(qml.Identity("z")), qml.state() res1, state1 = circuit() res2, state2 = circuit2() assert np.allclose(res1, res2, atol=tol, rtol=0) assert np.allclose(state1, state2, atol=tol, rtol=0) class TestInputs: """Test inputs and pre-processing.""" @pytest.mark.parametrize( ("weights", "wires", "singles", "doubles", "hf_state", "msg_match"), [ ( np.array([-2.8]), range(4), [[0, 2]], None, np.array([1.2, 1, 0, 0]), "Elements of 'hf_state' must be integers", ), ( np.array([-2.8]), range(4), None, None, np.array([1, 1, 0, 0]), "'singles' and 'doubles' lists can not be both empty", ), ( np.array([-2.8]), range(4), [], [], np.array([1, 1, 0, 0]), "'singles' and 'doubles' lists can not be both empty", ), ( np.array([-2.8]), range(4), None, [[0, 1, 2, 3, 4]], np.array([1, 1, 0, 0]), "Expected entries of 'doubles' to be of size 4", ), ( np.array([-2.8]), range(4), [[0, 2, 3]], None, np.array([1, 1, 0, 0]), "Expected entries of 'singles' to be of size 2", ), ( np.array([-2.8, 0.5]), range(4), [[0, 2]], [[0, 1, 2, 3]], np.array([1, 1, 0, 0, 0]), "State must be of length 4", ), ( np.array([-2.8, 1.6]), range(4), [[0, 2]], None, np.array([1, 1, 0, 0]), "'weights' tensor must be of shape", ), ( np.array([-2.8, 1.6]), range(4), None, [[0, 1, 2, 3]], np.array([1, 1, 0, 0]), "'weights' tensor must be of shape", ), ( np.array([-2.8, 1.6]), range(4), [[0, 2], [1, 3]], [[0, 1, 2, 3]], np.array([1, 1, 0, 0]), "'weights' tensor must be of shape", ), ( np.array([-2.8, 1.6]), range(4), None, [[0, 1, 2, 3]], np.array([1, 1, 0, 0]), "'weights' tensor must be of shape", ), ( np.array([-2.8, 1.6]), range(4), [[0, 2]], None, np.array([1, 1, 0, 0]), "'weights' tensor must be of shape", ), ( np.array([-2.8, 1.6]), range(1), [[0, 2]], None, np.array([1, 1, 0, 0]), "can not be less than 2", ), ], ) def test_allsinglesdoubles_exceptions( self, weights, wires, singles, doubles, hf_state, msg_match ): """Test that AllSinglesDoubles throws an exception if the parameters have illegal shapes, types or values.""" dev = qml.device("default.qubit", wires=len(wires)) def circuit( weights=weights, wires=wires, hf_state=hf_state, singles=singles, doubles=doubles ): qml.AllSinglesDoubles( weights=weights, wires=wires, hf_state=hf_state, singles=singles, doubles=doubles, ) return qml.expval(qml.PauliZ(0)) qnode = qml.QNode(circuit, dev) with pytest.raises(ValueError, match=msg_match): qnode( weights=weights, wires=wires, hf_state=hf_state, singles=singles, doubles=doubles, ) def test_id(self): """Tests that the id attribute can be set.""" template = qml.AllSinglesDoubles( [1, 2], wires=range(4), hf_state=np.array([1, 1, 0, 0]), singles=[[0, 1]], doubles=[[0, 1, 2, 3]], id="a", ) assert template.id == "a" class TestAttributes: """Tests additional methods and attributes""" @pytest.mark.parametrize( "singles, doubles, expected_shape", [ ([[0, 2], [1, 3]], [[0, 1, 2, 3], [4, 5, 6, 7]], (4,)), ([[0, 2], [1, 3]], None, (2,)), ([[0, 2], [1, 3]], [], (2,)), (None, [[0, 1, 2, 3], [4, 5, 6, 7]], (2,)), ([], [[0, 1, 2, 3], [4, 5, 6, 7]], (2,)), ], ) def test_shape(self, singles, doubles, expected_shape): """Test that the shape method returns the correct shape of the weights tensor""" shape = qml.AllSinglesDoubles.shape(singles, doubles) assert shape == expected_shape def circuit_template(weights): qml.AllSinglesDoubles( weights, wires=range(4), hf_state=np.array([1, 1, 0, 0]), singles=[[0, 1]], doubles=[[0, 1, 2, 3]], ) return qml.expval(qml.PauliZ(0)) def circuit_decomposed(weights): qml.BasisState(np.array([1, 1, 0, 0]), wires=range(4)) qml.DoubleExcitation(weights[1], wires=[0, 1, 2, 3]) qml.SingleExcitation(weights[0], wires=[0, 1]) return qml.expval(qml.PauliZ(0)) class TestInterfaces: """Tests that the template is compatible with all interfaces, including the computation of gradients.""" def test_list_and_tuples(self, tol): """Tests common iterables as inputs.""" weights = list(range(2)) dev = qml.device("default.qubit", wires=4) circuit = qml.QNode(circuit_template, dev) circuit2 = qml.QNode(circuit_decomposed, dev) res = circuit(weights) res2 = circuit2(weights) assert qml.math.allclose(res, res2, atol=tol, rtol=0) @pytest.mark.autograd def test_autograd(self, tol): """Tests the autograd interface.""" weights = pnp.array(np.random.random(size=(2,)), requires_grad=True) dev = qml.device("default.qubit", wires=4) circuit = qml.QNode(circuit_template, dev) circuit2 = qml.QNode(circuit_decomposed, dev) res = circuit(weights) res2 = circuit2(weights) assert qml.math.allclose(res, res2, atol=tol, rtol=0) grad_fn = qml.grad(circuit) grads = grad_fn(weights) grad_fn2 = qml.grad(circuit2) grads2 = grad_fn2(weights) assert np.allclose(grads, grads2, atol=tol, rtol=0) @pytest.mark.jax def test_jax(self, tol): """Tests the jax interface.""" import jax import jax.numpy as jnp weights = jnp.array(np.random.random(size=(2,))) dev = qml.device("default.qubit", wires=4) circuit = qml.QNode(circuit_template, dev) circuit2 = qml.QNode(circuit_decomposed, dev) res = circuit(weights) res2 = circuit2(weights) assert qml.math.allclose(res, res2, atol=tol, rtol=0) grad_fn = jax.grad(circuit) grads = grad_fn(weights) grad_fn2 = jax.grad(circuit2) grads2 = grad_fn2(weights) assert np.allclose(grads[0], grads2[0], atol=tol, rtol=0) @pytest.mark.tf def test_tf(self, tol): """Tests the tf interface.""" import tensorflow as tf weights = tf.Variable(np.random.random(size=(2,))) dev = qml.device("default.qubit", wires=4) circuit = qml.QNode(circuit_template, dev) circuit2 = qml.QNode(circuit_decomposed, dev) res = circuit(weights) res2 = circuit2(weights) assert qml.math.allclose(res, res2, atol=tol, rtol=0) with tf.GradientTape() as tape: res = circuit(weights) grads = tape.gradient(res, [weights]) with tf.GradientTape() as tape2: res2 = circuit2(weights) grads2 = tape2.gradient(res2, [weights]) assert np.allclose(grads[0], grads2[0], atol=tol, rtol=0) @pytest.mark.torch def test_torch(self, tol): """Tests the torch interface.""" import torch weights = torch.tensor(np.random.random(size=(2,)), requires_grad=True) dev = qml.device("default.qubit", wires=4) circuit = qml.QNode(circuit_template, dev) circuit2 = qml.QNode(circuit_decomposed, dev) res = circuit(weights) res2 = circuit2(weights) assert qml.math.allclose(res, res2, atol=tol, rtol=0) res = circuit(weights) res.backward() grads = [weights.grad] res2 = circuit2(weights) res2.backward() grads2 = [weights.grad] assert np.allclose(grads[0], grads2[0], atol=tol, rtol=0)
pennylane/tests/templates/test_subroutines/test_all_singles_doubles.py/0
{ "file_path": "pennylane/tests/templates/test_subroutines/test_all_singles_doubles.py", "repo_id": "pennylane", "token_count": 8063 }
94
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # 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. """ Tests for the Multiplier template. """ import numpy as np import pytest import pennylane as qml from pennylane.templates.subroutines.multiplier import _mul_out_k_mod def test_standard_validity_Multiplier(): """Check the operation using the assert_valid function.""" k = 6 mod = 11 x_wires = [0, 1, 2, 3] work_wires = [4, 5, 6, 7, 8, 9] op = qml.Multiplier(k, x_wires=x_wires, mod=mod, work_wires=work_wires) qml.ops.functions.assert_valid(op) def test_mul_out_k_mod(): """Test the _mul_out_k_mod function.""" op = _mul_out_k_mod(2, [0, 1], 4, None, [4, 5]) assert op[0].name == "QFT" assert op[1].name == "ControlledSequence" assert op[2].name == "Adjoint(QFT)" print(op[1].base) assert qml.equal(op[1].base, qml.PhaseAdder(2, x_wires=[4, 5])) class TestMultiplier: """Test the qml.Multiplier template.""" @pytest.mark.parametrize( ("k", "x_wires", "mod", "work_wires", "x"), [ ( 5, [0, 1, 2], 8, [4, 5, 6, 7, 8], 3, ), ( 1, [0, 1, 2], 3, [3, 4, 5, 6, 7], 2, ), ( -12, [0, 1, 2, 3, 4], 23, [5, 6, 7, 8, 9, 10, 11], 1, ), ( 5, [0, 1, 2, 3, 4], None, [5, 6, 7, 8, 9, 10, 11], 0, ), ( 5, [0, 1, 2, 3, 4], None, [5, 6, 7, 8, 9], 1, ), ], ) def test_operation_result( self, k, x_wires, mod, work_wires, x ): # pylint: disable=too-many-arguments """Test the correctness of the Multiplier template output.""" dev = qml.device("default.qubit", shots=1) @qml.qnode(dev) def circuit(x): qml.BasisEmbedding(x, wires=x_wires) qml.Multiplier(k, x_wires, mod, work_wires) return qml.sample(wires=x_wires) if mod is None: mod = 2 ** len(x_wires) assert np.allclose( sum(bit * (2**i) for i, bit in enumerate(reversed(circuit(x)))), (x * k) % mod ) @pytest.mark.parametrize( ("k", "x_wires", "mod", "work_wires", "msg_match"), [ ( 6, [0, 1], 7, [3, 4, 5, 6], "Multiplier must have enough wires to represent mod.", ), ( 2, [0, 1, 2], 6, [3, 4, 5, 6, 7], "The operator cannot be built because k has no inverse modulo mod", ), ( 3, [0, 1, 2, 3, 4], 11, [4, 5], "None of the wire in work_wires should be included in x_wires.", ), ( 3, [0, 1, 2, 3, 4], 11, [5, 6, 7, 8, 9, 10], "Multiplier needs as many work_wires as x_wires plus two.", ), ( 3, [0, 1, 2, 3], 16, [5, 6, 7], "Multiplier needs as many work_wires as x_wires.", ), ], ) def test_operation_and_wires_error( self, k, x_wires, mod, work_wires, msg_match ): # pylint: disable=too-many-arguments """Test an error is raised when k or mod don't meet the requirements""" with pytest.raises(ValueError, match=msg_match): qml.Multiplier(k, x_wires, mod, work_wires) def test_decomposition(self): """Test that compute_decomposition and decomposition work as expected.""" k, x_wires, mod, work_wires = 4, [0, 1, 2], 7, [3, 4, 5, 6, 7] multiplier_decomposition = qml.Multiplier( k, x_wires, mod, work_wires ).compute_decomposition(k, x_wires, mod, work_wires) op_list = [] if mod != 2 ** len(x_wires): work_wire_aux = work_wires[:1] wires_aux = work_wires[1:] wires_aux_swap = wires_aux[1:] else: work_wire_aux = None wires_aux = work_wires[:3] wires_aux_swap = wires_aux op_list.extend(_mul_out_k_mod(k, x_wires, mod, work_wire_aux, wires_aux)) for x_wire, aux_wire in zip(x_wires, wires_aux_swap): op_list.append(qml.SWAP(wires=[x_wire, aux_wire])) inv_k = pow(k, -1, mod) op_list.extend(qml.adjoint(_mul_out_k_mod)(inv_k, x_wires, mod, work_wire_aux, wires_aux)) for op1, op2 in zip(multiplier_decomposition, op_list): qml.assert_equal(op1, op2) @pytest.mark.jax def test_jit_compatible(self): """Test that the template is compatible with the JIT compiler.""" import jax jax.config.update("jax_enable_x64", True) x = 2 k = 6 mod = 7 x_wires = [0, 1, 2] work_wires = [4, 5, 6, 7, 8] dev = qml.device("default.qubit", shots=1) @jax.jit @qml.qnode(dev) def circuit(): qml.BasisEmbedding(x, wires=x_wires) qml.Multiplier(k, x_wires, mod, work_wires) return qml.sample(wires=x_wires) assert jax.numpy.allclose( sum(bit * (2**i) for i, bit in enumerate(reversed(circuit()))), (x * k) % mod )
pennylane/tests/templates/test_subroutines/test_multiplier.py/0
{ "file_path": "pennylane/tests/templates/test_subroutines/test_multiplier.py", "repo_id": "pennylane", "token_count": 3495 }
95
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # 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. """ Tests for the TrotterProduct template and helper functions. """ # pylint: disable=private-access, protected-access import copy from collections import defaultdict from functools import reduce import pytest import pennylane as qml from pennylane import numpy as qnp from pennylane.math import allclose, get_interface from pennylane.resource import Resources from pennylane.resource.error import SpectralNormError from pennylane.templates.subroutines.trotter import _recursive_expression, _scalar test_hamiltonians = ( qml.dot([1, 1, 1], [qml.PauliX(0), qml.PauliY(0), qml.PauliZ(1)]), qml.dot( [1.23, -0.45], [qml.s_prod(0.1, qml.PauliX(0)), qml.prod(qml.PauliX(0), qml.PauliZ(1))] ), # op arith qml.dot( [1, -0.5, 0.5], [qml.Identity(wires=[0, 1]), qml.PauliZ(0), qml.PauliZ(0)] ), # H = Identity qml.dot([2, 2, 2], [qml.PauliX(0), qml.PauliY(0), qml.PauliZ(1)]), ) p_4 = (4 - 4 ** (1 / 3)) ** -1 test_decompositions = ( { # (hamiltonian_index, order): decomposition assuming t = 4.2, computed by hand (0, 1): [ qml.exp(qml.PauliX(0), 4.2j), qml.exp(qml.PauliY(0), 4.2j), qml.exp(qml.PauliZ(1), 4.2j), ], (0, 2): [ qml.exp(qml.PauliX(0), 4.2j / 2), qml.exp(qml.PauliY(0), 4.2j / 2), qml.exp(qml.PauliZ(1), 4.2j / 2), qml.exp(qml.PauliZ(1), 4.2j / 2), qml.exp(qml.PauliY(0), 4.2j / 2), qml.exp(qml.PauliX(0), 4.2j / 2), ], (0, 4): [ qml.exp(qml.PauliX(0), p_4 * 4.2j / 2), qml.exp(qml.PauliY(0), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(1), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(1), p_4 * 4.2j / 2), qml.exp(qml.PauliY(0), p_4 * 4.2j / 2), qml.exp(qml.PauliX(0), p_4 * 4.2j / 2), qml.exp(qml.PauliX(0), p_4 * 4.2j / 2), qml.exp(qml.PauliY(0), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(1), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(1), p_4 * 4.2j / 2), qml.exp(qml.PauliY(0), p_4 * 4.2j / 2), qml.exp(qml.PauliX(0), p_4 * 4.2j / 2), # S_2(p * t) ^ 2 qml.exp(qml.PauliX(0), (1 - 4 * p_4) * 4.2j / 2), qml.exp(qml.PauliY(0), (1 - 4 * p_4) * 4.2j / 2), qml.exp(qml.PauliZ(1), (1 - 4 * p_4) * 4.2j / 2), qml.exp(qml.PauliZ(1), (1 - 4 * p_4) * 4.2j / 2), qml.exp(qml.PauliY(0), (1 - 4 * p_4) * 4.2j / 2), qml.exp(qml.PauliX(0), (1 - 4 * p_4) * 4.2j / 2), # S_2((1 - 4p) * t) qml.exp(qml.PauliX(0), p_4 * 4.2j / 2), qml.exp(qml.PauliY(0), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(1), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(1), p_4 * 4.2j / 2), qml.exp(qml.PauliY(0), p_4 * 4.2j / 2), qml.exp(qml.PauliX(0), p_4 * 4.2j / 2), qml.exp(qml.PauliX(0), p_4 * 4.2j / 2), qml.exp(qml.PauliY(0), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(1), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(1), p_4 * 4.2j / 2), qml.exp(qml.PauliY(0), p_4 * 4.2j / 2), qml.exp(qml.PauliX(0), p_4 * 4.2j / 2), # S_2(p * t) ^ 2 ], (1, 1): [ qml.exp(qml.s_prod(0.1, qml.PauliX(0)), 1.23 * 4.2j), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), -0.45 * 4.2j), ], (1, 2): [ qml.exp(qml.s_prod(0.1, qml.PauliX(0)), 1.23 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), -0.45 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), -0.45 * 4.2j / 2), qml.exp(qml.s_prod(0.1, qml.PauliX(0)), 1.23 * 4.2j / 2), ], (1, 4): [ qml.exp(qml.s_prod(0.1, qml.PauliX(0)), p_4 * 1.23 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), p_4 * -0.45 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), p_4 * -0.45 * 4.2j / 2), qml.exp(qml.s_prod(0.1, qml.PauliX(0)), p_4 * 1.23 * 4.2j / 2), qml.exp(qml.s_prod(0.1, qml.PauliX(0)), p_4 * 1.23 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), p_4 * -0.45 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), p_4 * -0.45 * 4.2j / 2), qml.exp(qml.s_prod(0.1, qml.PauliX(0)), p_4 * 1.23 * 4.2j / 2), qml.exp(qml.s_prod(0.1, qml.PauliX(0)), (1 - 4 * p_4) * 1.23 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), (1 - 4 * p_4) * -0.45 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), (1 - 4 * p_4) * -0.45 * 4.2j / 2), qml.exp(qml.s_prod(0.1, qml.PauliX(0)), (1 - 4 * p_4) * 1.23 * 4.2j / 2), qml.exp(qml.s_prod(0.1, qml.PauliX(0)), p_4 * 1.23 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), p_4 * -0.45 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), p_4 * -0.45 * 4.2j / 2), qml.exp(qml.s_prod(0.1, qml.PauliX(0)), p_4 * 1.23 * 4.2j / 2), qml.exp(qml.s_prod(0.1, qml.PauliX(0)), p_4 * 1.23 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), p_4 * -0.45 * 4.2j / 2), qml.exp(qml.prod(qml.PauliX(0), qml.PauliZ(1)), p_4 * -0.45 * 4.2j / 2), qml.exp(qml.s_prod(0.1, qml.PauliX(0)), p_4 * 1.23 * 4.2j / 2), ], (2, 1): [ qml.exp(qml.Identity(wires=[0, 1]), 4.2j), qml.exp(qml.PauliZ(0), -0.5 * 4.2j), qml.exp(qml.PauliZ(0), 0.5 * 4.2j), ], (2, 2): [ qml.exp(qml.Identity(wires=[0, 1]), 4.2j / 2), qml.exp(qml.PauliZ(0), -0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), -0.5 * 4.2j / 2), qml.exp(qml.Identity(wires=[0, 1]), 4.2j / 2), ], (2, 4): [ qml.exp(qml.Identity(wires=[0, 1]), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * -0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * -0.5 * 4.2j / 2), qml.exp(qml.Identity(wires=[0, 1]), p_4 * 4.2j / 2), qml.exp(qml.Identity(wires=[0, 1]), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * -0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * -0.5 * 4.2j / 2), qml.exp(qml.Identity(wires=[0, 1]), p_4 * 4.2j / 2), qml.exp(qml.Identity(wires=[0, 1]), (1 - 4 * p_4) * 4.2j / 2), qml.exp(qml.PauliZ(0), (1 - 4 * p_4) * -0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), (1 - 4 * p_4) * 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), (1 - 4 * p_4) * 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), (1 - 4 * p_4) * -0.5 * 4.2j / 2), qml.exp(qml.Identity(wires=[0, 1]), (1 - 4 * p_4) * 4.2j / 2), qml.exp(qml.Identity(wires=[0, 1]), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * -0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * -0.5 * 4.2j / 2), qml.exp(qml.Identity(wires=[0, 1]), p_4 * 4.2j / 2), qml.exp(qml.Identity(wires=[0, 1]), p_4 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * -0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * 0.5 * 4.2j / 2), qml.exp(qml.PauliZ(0), p_4 * -0.5 * 4.2j / 2), qml.exp(qml.Identity(wires=[0, 1]), p_4 * 4.2j / 2), ], (3, 1): [ qml.exp(qml.PauliX(0), 8.4j), qml.exp(qml.PauliY(0), 8.4j), qml.exp(qml.PauliZ(1), 8.4j), ], (3, 2): [ qml.exp(qml.PauliX(0), 8.4j / 2), qml.exp(qml.PauliY(0), 8.4j / 2), qml.exp(qml.PauliZ(1), 8.4j / 2), qml.exp(qml.PauliZ(1), 8.4j / 2), qml.exp(qml.PauliY(0), 8.4j / 2), qml.exp(qml.PauliX(0), 8.4j / 2), ], (3, 4): [ qml.exp(qml.PauliX(0), p_4 * 8.4j / 2), qml.exp(qml.PauliY(0), p_4 * 8.4j / 2), qml.exp(qml.PauliZ(1), p_4 * 8.4j / 2), qml.exp(qml.PauliZ(1), p_4 * 8.4j / 2), qml.exp(qml.PauliY(0), p_4 * 8.4j / 2), qml.exp(qml.PauliX(0), p_4 * 8.4j / 2), qml.exp(qml.PauliX(0), p_4 * 8.4j / 2), qml.exp(qml.PauliY(0), p_4 * 8.4j / 2), qml.exp(qml.PauliZ(1), p_4 * 8.4j / 2), qml.exp(qml.PauliZ(1), p_4 * 8.4j / 2), qml.exp(qml.PauliY(0), p_4 * 8.4j / 2), qml.exp(qml.PauliX(0), p_4 * 8.4j / 2), # S_2(p * t) ^ 2 qml.exp(qml.PauliX(0), (1 - 4 * p_4) * 8.4j / 2), qml.exp(qml.PauliY(0), (1 - 4 * p_4) * 8.4j / 2), qml.exp(qml.PauliZ(1), (1 - 4 * p_4) * 8.4j / 2), qml.exp(qml.PauliZ(1), (1 - 4 * p_4) * 8.4j / 2), qml.exp(qml.PauliY(0), (1 - 4 * p_4) * 8.4j / 2), qml.exp(qml.PauliX(0), (1 - 4 * p_4) * 8.4j / 2), # S_2((1 - 4p) * t) qml.exp(qml.PauliX(0), p_4 * 8.4j / 2), qml.exp(qml.PauliY(0), p_4 * 8.4j / 2), qml.exp(qml.PauliZ(1), p_4 * 8.4j / 2), qml.exp(qml.PauliZ(1), p_4 * 8.4j / 2), qml.exp(qml.PauliY(0), p_4 * 8.4j / 2), qml.exp(qml.PauliX(0), p_4 * 8.4j / 2), qml.exp(qml.PauliX(0), p_4 * 8.4j / 2), qml.exp(qml.PauliY(0), p_4 * 8.4j / 2), qml.exp(qml.PauliZ(1), p_4 * 8.4j / 2), qml.exp(qml.PauliZ(1), p_4 * 8.4j / 2), qml.exp(qml.PauliY(0), p_4 * 8.4j / 2), qml.exp(qml.PauliX(0), p_4 * 8.4j / 2), # S_2(p * t) ^ 2 ], } ) test_resources_data = { # (hamiltonian_index, order): Resources computed by hand (0, 1): Resources( num_wires=2, num_gates=3, gate_types=defaultdict(int, {"Exp": 3}), gate_sizes=defaultdict(int, {1: 3}), depth=2, ), (0, 2): Resources( num_wires=2, num_gates=6, gate_types=defaultdict(int, {"Exp": 6}), gate_sizes=defaultdict(int, {1: 6}), depth=4, ), (0, 4): Resources( num_wires=2, num_gates=30, gate_types=defaultdict(int, {"Exp": 30}), gate_sizes=defaultdict(int, {1: 30}), depth=20, ), (1, 1): Resources( num_wires=2, num_gates=2, gate_types=defaultdict(int, {"Exp": 2}), gate_sizes=defaultdict(int, {1: 1, 2: 1}), depth=2, ), (1, 2): Resources( num_wires=2, num_gates=4, gate_types=defaultdict(int, {"Exp": 4}), gate_sizes=defaultdict(int, {1: 2, 2: 2}), depth=4, ), (1, 4): Resources( num_wires=2, num_gates=20, gate_types=defaultdict(int, {"Exp": 20}), gate_sizes=defaultdict(int, {1: 10, 2: 10}), depth=20, ), (2, 1): Resources( num_wires=2, num_gates=3, gate_types=defaultdict(int, {"Exp": 3}), gate_sizes=defaultdict(int, {1: 2, 2: 1}), depth=3, ), (2, 2): Resources( num_wires=2, num_gates=6, gate_types=defaultdict(int, {"Exp": 6}), gate_sizes=defaultdict(int, {1: 4, 2: 2}), depth=6, ), (2, 4): Resources( num_wires=2, num_gates=30, gate_types=defaultdict(int, {"Exp": 30}), gate_sizes=defaultdict(int, {1: 20, 2: 10}), depth=30, ), (3, 1): Resources( num_wires=2, num_gates=3, gate_types=defaultdict(int, {"Exp": 3}), gate_sizes=defaultdict(int, {1: 3}), depth=2, ), (3, 2): Resources( num_wires=2, num_gates=6, gate_types=defaultdict(int, {"Exp": 6}), gate_sizes=defaultdict(int, {1: 6}), depth=4, ), (3, 4): Resources( num_wires=2, num_gates=30, gate_types=defaultdict(int, {"Exp": 30}), gate_sizes=defaultdict(int, {1: 30}), depth=20, ), } def _generate_simple_decomp(coeffs, ops, time, order, n): """Given coeffs, ops and a time argument in a given framework, generate the Trotter product for order and number of trotter steps.""" decomp = [] if order == 1: decomp.extend(qml.exp(op, coeff * (time / n) * 1j) for coeff, op in zip(coeffs, ops)) coeffs_ops = zip(coeffs, ops) if get_interface(coeffs) == "torch": import torch coeffs_ops_reversed = zip(torch.flip(coeffs, dims=(0,)), ops[::-1]) else: coeffs_ops_reversed = zip(coeffs[::-1], ops[::-1]) if order == 2: decomp.extend(qml.exp(op, coeff * (time / n) * 1j / 2) for coeff, op in coeffs_ops) decomp.extend(qml.exp(op, coeff * (time / n) * 1j / 2) for coeff, op in coeffs_ops_reversed) if order == 4: s_2 = [] s_2_p = [] for coeff, op in coeffs_ops: s_2.append(qml.exp(op, (p_4 * coeff) * (time / n) * 1j / 2)) s_2_p.append(qml.exp(op, ((1 - (4 * p_4)) * coeff) * (time / n) * 1j / 2)) for coeff, op in coeffs_ops_reversed: s_2.append(qml.exp(op, (p_4 * coeff) * (time / n) * 1j / 2)) s_2_p.append(qml.exp(op, ((1 - (4 * p_4)) * coeff) * (time / n) * 1j / 2)) decomp = (s_2 * 2) + s_2_p + (s_2 * 2) return decomp * n class TestInitialization: """Test the TrotterProduct class initializes correctly.""" @pytest.mark.parametrize( "hamiltonian, raise_error", ( (qml.PauliX(0), True), (qml.prod(qml.PauliX(0), qml.PauliZ(1)), True), (qml.Hamiltonian([1.23, 3.45], [qml.PauliX(0), qml.PauliZ(1)]), False), (qml.dot([1.23, 3.45], [qml.PauliX(0), qml.PauliZ(1)]), False), ), ) def test_error_type(self, hamiltonian, raise_error): """Test an error is raised of an incorrect type is passed""" if raise_error: with pytest.raises( TypeError, match="The given operator must be a PennyLane ~.Hamiltonian, ~.Sum or ~.SProd", ): qml.TrotterProduct(hamiltonian, time=1.23) else: try: qml.TrotterProduct(hamiltonian, time=1.23) except TypeError: assert False # test should fail if an error was raised when we expect it not to @pytest.mark.parametrize( "hamiltonian", ( qml.Hamiltonian([1.23, 4 + 5j], [qml.PauliX(0), qml.PauliZ(1)]), qml.dot([1.23, 4 + 5j], [qml.PauliX(0), qml.PauliZ(1)]), qml.dot([1.23, 0.5], [qml.RY(1.23, 0), qml.RZ(3.45, 1)]), ), ) def test_error_hermiticity(self, hamiltonian): """Test that an error is raised if any terms in the Hamiltonian are not Hermitian and check_hermitian is True.""" with pytest.raises( ValueError, match="One or more of the terms in the Hamiltonian may not be Hermitian" ): qml.TrotterProduct(hamiltonian, time=0.5) try: qml.TrotterProduct(hamiltonian, time=0.5, check_hermitian=False) except ValueError: assert False # No error should be raised if the check_hermitian flag is disabled @pytest.mark.parametrize( "hamiltonian", ( qml.Hamiltonian([1.0], [qml.PauliX(0)]), qml.dot([2.0], [qml.PauliY(0)]), ), ) def test_error_hamiltonian(self, hamiltonian): """Test that an error is raised if the input Hamiltonian has only 1 term.""" with pytest.raises( ValueError, match="There should be at least 2 terms in the Hamiltonian." ): qml.TrotterProduct(hamiltonian, 1.23, n=2, order=4) @pytest.mark.parametrize("order", (-1, 0, 0.5, 3, 7.0)) def test_error_order(self, order): """Test that an error is raised if 'order' is not one or positive even number.""" time = 0.5 hamiltonian = qml.dot([1.23, 3.45], [qml.PauliX(0), qml.PauliZ(1)]) with pytest.raises( ValueError, match="The order of a TrotterProduct must be 1 or a positive even integer," ): qml.TrotterProduct(hamiltonian, time, order=order) @pytest.mark.parametrize("hamiltonian", test_hamiltonians) def test_init_correctly(self, hamiltonian): """Test that all of the attributes are initalized correctly.""" time, n, order = (4.2, 10, 4) op = qml.TrotterProduct(hamiltonian, time, n=n, order=order, check_hermitian=False) if isinstance(hamiltonian, qml.ops.op_math.SProd): hamiltonian = hamiltonian.simplify() assert op.wires == hamiltonian.wires assert op.parameters == [*hamiltonian.data, time] assert op.data == (*hamiltonian.data, time) assert op.hyperparameters == { "base": hamiltonian, "n": n, "order": order, "check_hermitian": False, } @pytest.mark.parametrize("n", (1, 2, 5, 10)) @pytest.mark.parametrize("time", (0.5, 1.2)) @pytest.mark.parametrize("order", (1, 2, 4)) @pytest.mark.parametrize("hamiltonian", test_hamiltonians) def test_copy(self, hamiltonian, time, n, order): """Test that we can make deep and shallow copies of TrotterProduct correctly.""" op = qml.TrotterProduct(hamiltonian, time, n=n, order=order) new_op = copy.copy(op) assert op.wires == new_op.wires assert op.parameters == new_op.parameters assert op.data == new_op.data assert op.hyperparameters == new_op.hyperparameters assert op is not new_op @pytest.mark.parametrize("hamiltonian", test_hamiltonians) def test_standard_validity(self, hamiltonian): """Test standard validity criteria using assert_valid.""" time, n, order = (4.2, 10, 4) op = qml.TrotterProduct(hamiltonian, time, n=n, order=order) qml.ops.functions.assert_valid(op) # TODO: Remove test when we deprecate ApproxTimeEvolution @pytest.mark.parametrize("n", (1, 2, 5, 10)) @pytest.mark.parametrize("time", (0.5, 1.2)) def test_convention_approx_time_evolv(self, time, n): """Test that TrotterProduct matches ApproxTimeEvolution""" hamiltonian = qml.Hamiltonian( [1.23, -0.45, 6], [qml.PauliX(0), qml.PauliY(0), qml.PauliZ(0)] ) op1 = qml.TrotterProduct(hamiltonian, time, order=1, n=n) op2 = qml.adjoint(qml.ApproxTimeEvolution(hamiltonian, time, n=n)) assert qnp.allclose( qml.matrix(op1, wire_order=hamiltonian.wires), qml.matrix(op2, wire_order=hamiltonian.wires), ) op1 = qml.adjoint(qml.TrotterProduct(hamiltonian, time, order=1, n=n)) op2 = qml.ApproxTimeEvolution(hamiltonian, time, n=n) assert qnp.allclose( qml.matrix(op1, wire_order=hamiltonian.wires), qml.matrix(op2, wire_order=hamiltonian.wires), ) @pytest.mark.parametrize( "make_H", [ lambda: qml.Hamiltonian([1, 1], [qml.PauliX(0), qml.PauliY(1)]), lambda: qml.sum(qml.PauliX(0), qml.PauliY(1)), lambda: qml.s_prod(1.2, qml.PauliX(0) + qml.PauliY(1)), ], ) def test_queuing(self, make_H): """Test that the target operator is removed from the queue.""" with qml.queuing.AnnotatedQueue() as q: H = make_H() op = qml.TrotterProduct(H, time=2) assert len(q.queue) == 1 assert q.queue[0] is op class TestPrivateFunctions: """Test the private helper functions.""" @pytest.mark.parametrize( "order, result", ( (4, 0.4144907717943757), (6, 0.3730658277332728), (8, 0.35958464934999224), ), ) # Computed by hand def test_private_scalar(self, order, result): """Test the _scalar function correctly computes the parameter scalar.""" s = _scalar(order) assert qnp.isclose(s, result) expected_expansions = ( # for H = X0 + Y0 + Z1, t = 1.23, computed by hand [ # S_1(t) qml.exp(qml.PauliX(0), 1.23j), qml.exp(qml.PauliY(0), 1.23j), qml.exp(qml.PauliZ(1), 1.23j), ], [ # S_2(t) qml.exp(qml.PauliX(0), 1.23j / 2), qml.exp(qml.PauliY(0), 1.23j / 2), qml.exp(qml.PauliZ(1), 1.23j / 2), qml.exp(qml.PauliZ(1), 1.23j / 2), qml.exp(qml.PauliY(0), 1.23j / 2), qml.exp(qml.PauliX(0), 1.23j / 2), ], [ # S_4(t) qml.exp(qml.PauliX(0), p_4 * 1.23j / 2), qml.exp(qml.PauliY(0), p_4 * 1.23j / 2), qml.exp(qml.PauliZ(1), p_4 * 1.23j / 2), qml.exp(qml.PauliZ(1), p_4 * 1.23j / 2), qml.exp(qml.PauliY(0), p_4 * 1.23j / 2), qml.exp(qml.PauliX(0), p_4 * 1.23j / 2), qml.exp(qml.PauliX(0), p_4 * 1.23j / 2), qml.exp(qml.PauliY(0), p_4 * 1.23j / 2), qml.exp(qml.PauliZ(1), p_4 * 1.23j / 2), qml.exp(qml.PauliZ(1), p_4 * 1.23j / 2), qml.exp(qml.PauliY(0), p_4 * 1.23j / 2), qml.exp(qml.PauliX(0), p_4 * 1.23j / 2), # S_2(p * t) ^ 2 qml.exp(qml.PauliX(0), (1 - 4 * p_4) * 1.23j / 2), qml.exp(qml.PauliY(0), (1 - 4 * p_4) * 1.23j / 2), qml.exp(qml.PauliZ(1), (1 - 4 * p_4) * 1.23j / 2), qml.exp(qml.PauliZ(1), (1 - 4 * p_4) * 1.23j / 2), qml.exp(qml.PauliY(0), (1 - 4 * p_4) * 1.23j / 2), qml.exp(qml.PauliX(0), (1 - 4 * p_4) * 1.23j / 2), # S_2((1 - 4p) * t) qml.exp(qml.PauliX(0), p_4 * 1.23j / 2), qml.exp(qml.PauliY(0), p_4 * 1.23j / 2), qml.exp(qml.PauliZ(1), p_4 * 1.23j / 2), qml.exp(qml.PauliZ(1), p_4 * 1.23j / 2), qml.exp(qml.PauliY(0), p_4 * 1.23j / 2), qml.exp(qml.PauliX(0), p_4 * 1.23j / 2), qml.exp(qml.PauliX(0), p_4 * 1.23j / 2), qml.exp(qml.PauliY(0), p_4 * 1.23j / 2), qml.exp(qml.PauliZ(1), p_4 * 1.23j / 2), qml.exp(qml.PauliZ(1), p_4 * 1.23j / 2), qml.exp(qml.PauliY(0), p_4 * 1.23j / 2), qml.exp(qml.PauliX(0), p_4 * 1.23j / 2), # S_2(p * t) ^ 2 ], ) @pytest.mark.parametrize("order, expected_expansion", zip((1, 2, 4), expected_expansions)) def test_recursive_expression_no_queue(self, order, expected_expansion): """Test the _recursive_expression function correctly generates the decomposition""" ops = [qml.PauliX(0), qml.PauliY(0), qml.PauliZ(1)] with qml.tape.QuantumTape() as tape: decomp = _recursive_expression(1.23, order, ops) assert tape.operations == [] # No queuing! for op1, op2 in zip(decomp, expected_expansion): qml.assert_equal(op1, op2) class TestError: """Test the error method of the TrotterProduct class""" @pytest.mark.parametrize("fast", (True, False)) def test_invalid_method(self, fast): """Test that passing an invalid method raises an error.""" method = "crazy" op = qml.TrotterProduct(qml.sum(qml.X(0), qml.Y(0)), 1.23) with pytest.raises(ValueError, match=f"The '{method}' method is not supported"): _ = op.error(method, fast=fast) def test_one_norm_error_method(self): """Test that the one-norm error method works as expected.""" op = qml.TrotterProduct(qml.sum(qml.X(0), qml.Y(0)), time=0.05, order=4) expected_error = ((10**5 + 1) / 120) * (0.1**5) for computed_error in ( op.error(method="one-norm-bound"), op.error(method="one-norm-bound", fast=False), ): assert isinstance(computed_error, SpectralNormError) assert qnp.isclose(computed_error.error, expected_error) def test_commutator_error_method(self): """Test that the commutator error method works as expected.""" op = qml.TrotterProduct(qml.sum(qml.X(0), qml.Y(0)), time=0.05, order=2, n=10) expected_error = (32 / 3) * (0.05**3) * (1 / 100) for computed_error in ( op.error(method="commutator-bound"), op.error(method="commutator-bound", fast=False), ): assert isinstance(computed_error, SpectralNormError) assert qnp.isclose(computed_error.error, expected_error) @pytest.mark.all_interfaces @pytest.mark.parametrize( "method, expected_error", (("one-norm-bound", 0.001265625), ("commutator-bound", 0.001)) ) @pytest.mark.parametrize("interface", ("autograd", "jax", "torch")) def test_error_interfaces(self, method, interface, expected_error): """Test that the error method works with all interfaces""" time = qml.math.array(0.1, like=interface) coeffs = qml.math.array([1.0, 0.5], like=interface) hamiltonian = qml.dot(coeffs, [qml.X(0), qml.Y(0)]) op = qml.TrotterProduct(hamiltonian, time, n=2, order=2) computed_error = op.error(method=method) assert isinstance(computed_error, SpectralNormError) assert qml.math.get_interface(computed_error.error) == interface assert qnp.isclose(computed_error.error, qml.math.array(expected_error, like=interface)) @pytest.mark.tf def test_tensorflow_interface(self): """Test that an error is raised if a TrotterProduct with tensorflow parameters is used to compute error.""" coeffs = qml.math.array([1.0, 0.5], like="tensorflow") hamiltonian = qml.dot(coeffs, [qml.X(0), qml.Y(0)]) op = qml.TrotterProduct(hamiltonian, 1.23, order=2, n=5) with pytest.raises(TypeError, match="Calculating error bound for Tensorflow objects"): _ = op.error() class TestResources: """Test the resources method of the TrotterProduct class""" def test_resources_no_queuing(self): """Test that no operations are queued when computing resources.""" time = 0.5 hamiltonian = qml.sum(qml.PauliX(0), qml.PauliZ(0)) op = qml.TrotterProduct(hamiltonian, time, n=5, order=2) with qml.queuing.AnnotatedQueue() as q: _ = op.resources() assert len(q.queue) == 0 @pytest.mark.parametrize("order", (1, 2, 4)) @pytest.mark.parametrize("hamiltonian_index, hamiltonian", enumerate(test_hamiltonians)) def test_resources(self, hamiltonian, hamiltonian_index, order): """Test that the resources are tracked accurately.""" op = qml.TrotterProduct(hamiltonian, 4.2, order=order) tracked_resources = op.resources() expected_resources = test_resources_data[(hamiltonian_index, order)] assert expected_resources == tracked_resources @pytest.mark.parametrize("n", (1, 5, 10)) def test_resources_with_trotter_steps(self, n): """Test that the resources are tracked accurately with number of steps.""" order = 2 hamiltonian_index = 0 op = qml.TrotterProduct(test_hamiltonians[hamiltonian_index], 0.5, order=order, n=n) tracked_resources = op.resources() expected_resources = Resources( num_wires=2, num_gates=6 * n, gate_types=defaultdict(int, {"Exp": 6 * n}), gate_sizes=defaultdict(int, {1: 6 * n}), depth=4 * n, ) assert expected_resources == tracked_resources def test_resources_integration(self): """Test that the resources integrate well with qml.tracker and qml.specs resource tracking.""" time = 0.5 hamiltonian = qml.sum(qml.X(0), qml.Y(0), qml.Z(1)) dev = qml.device("default.qubit") @qml.qnode(dev) def circ(): qml.TrotterProduct(hamiltonian, time, n=5, order=2) return qml.expval(qml.Z(0)) expected_resources = Resources( num_wires=2, num_gates=30, gate_types=defaultdict(int, {"Exp": 30}), gate_sizes=defaultdict(int, {1: 30}), depth=20, ) with qml.Tracker(dev) as tracker: circ() spec_resources = qml.specs(circ)()["resources"] tracker_resources = tracker.history["resources"][0] assert expected_resources == spec_resources assert expected_resources == tracker_resources def test_resources_and_error(self): """Test that we can compute the resources and error together""" time = 0.1 coeffs = qml.math.array([1.0, 0.5]) hamiltonian = qml.dot(coeffs, [qml.X(0), qml.Y(0)]) dev = qml.device("default.qubit") @qml.qnode(dev) def circ(): qml.TrotterProduct(hamiltonian, time, n=2, order=2) return qml.expval(qml.Z(0)) specs = qml.specs(circ)() computed_error = (specs["errors"])["SpectralNormError"] computed_resources = specs["resources"] # Expected resources and errors (computed by hand) expected_resources = Resources( num_wires=1, num_gates=8, gate_types=defaultdict(int, {"Exp": 8}), gate_sizes=defaultdict(int, {1: 8}), depth=8, ) expected_error = 0.001 assert computed_resources == expected_resources assert isinstance(computed_error, SpectralNormError) assert qnp.isclose(computed_error.error, qml.math.array(expected_error)) class TestDecomposition: """Test the decomposition of the TrotterProduct class.""" @pytest.mark.parametrize("order", (1, 2, 4)) @pytest.mark.parametrize("hamiltonian_index, hamiltonian", enumerate(test_hamiltonians)) def test_compute_decomposition(self, hamiltonian, hamiltonian_index, order): """Test the decomposition is correct and queues""" op = qml.TrotterProduct(hamiltonian, 4.2, order=order) with qml.tape.QuantumTape() as tape: decomp = op.compute_decomposition(*op.parameters, **op.hyperparameters) assert decomp == tape.operations # queue matches decomp with circuit ordering decomp = [qml.simplify(op) for op in decomp] true_decomp = [ qml.simplify(op) for op in test_decompositions[(hamiltonian_index, order)][::-1] ] for op1, op2 in zip(decomp, true_decomp): qml.assert_equal(op1, op2) @pytest.mark.parametrize("order", (1, 2)) @pytest.mark.parametrize("num_steps", (1, 2, 3)) def test_compute_decomposition_n_steps(self, num_steps, order): """Test the decomposition is correct when we set the number of trotter steps""" time = 0.5 hamiltonian = qml.sum(qml.PauliX(0), qml.PauliZ(0)) if order == 1: base_decomp = [ qml.exp(qml.PauliZ(0), 0.5j / num_steps), qml.exp(qml.PauliX(0), 0.5j / num_steps), ] if order == 2: base_decomp = [ qml.exp(qml.PauliX(0), 0.25j / num_steps), qml.exp(qml.PauliZ(0), 0.25j / num_steps), qml.exp(qml.PauliZ(0), 0.25j / num_steps), qml.exp(qml.PauliX(0), 0.25j / num_steps), ] true_decomp = base_decomp * num_steps op = qml.TrotterProduct(hamiltonian, time, n=num_steps, order=order) decomp = op.compute_decomposition(*op.parameters, **op.hyperparameters) for op1, op2 in zip(decomp, true_decomp): qml.assert_equal(op1, op2) class TestIntegration: """Test that the TrotterProduct can be executed and differentiated through all interfaces.""" # Circuit execution tests: @pytest.mark.parametrize("order", (1, 2, 4)) @pytest.mark.parametrize("hamiltonian_index, hamiltonian", enumerate(test_hamiltonians)) def test_execute_circuit(self, hamiltonian, hamiltonian_index, order): """Test that the gate executes correctly in a circuit.""" wires = hamiltonian.wires dev = qml.device("default.qubit", wires=wires) @qml.qnode(dev) def circ(): qml.TrotterProduct(hamiltonian, time=4.2, order=order) return qml.state() initial_state = qnp.zeros(2 ** (len(wires))) initial_state[0] = 1 expected_state = ( reduce( lambda x, y: x @ y, [ qml.matrix(op, wire_order=wires) for op in test_decompositions[(hamiltonian_index, order)] ], ) @ initial_state ) state = circ() assert qnp.allclose(expected_state, state) @pytest.mark.parametrize("order", (1, 2)) @pytest.mark.parametrize("num_steps", (1, 2, 3)) def test_execute_circuit_n_steps(self, num_steps, order): """Test that the circuit executes as expected when we set the number of trotter steps""" time = 0.5 hamiltonian = qml.sum(qml.PauliX(0), qml.PauliZ(0)) if order == 1: base_decomp = [ qml.exp(qml.PauliZ(0), 0.5j / num_steps), qml.exp(qml.PauliX(0), 0.5j / num_steps), ] if order == 2: base_decomp = [ qml.exp(qml.PauliX(0), 0.25j / num_steps), qml.exp(qml.PauliZ(0), 0.25j / num_steps), qml.exp(qml.PauliZ(0), 0.25j / num_steps), qml.exp(qml.PauliX(0), 0.25j / num_steps), ] true_decomp = base_decomp * num_steps wires = hamiltonian.wires dev = qml.device("default.qubit", wires=wires) @qml.qnode(dev) def circ(): qml.TrotterProduct(hamiltonian, time, n=num_steps, order=order) return qml.state() initial_state = qnp.zeros(2 ** (len(wires))) initial_state[0] = 1 expected_state = ( reduce( lambda x, y: x @ y, [qml.matrix(op, wire_order=wires) for op in true_decomp[::-1]] ) @ initial_state ) state = circ() assert qnp.allclose(expected_state, state) @pytest.mark.jax @pytest.mark.parametrize("time", (0.5, 1, 2)) def test_jax_execute(self, time): """Test that the gate executes correctly in the jax interface.""" from jax import numpy as jnp time = jnp.array(time) coeffs = jnp.array([1.23, -0.45]) terms = [qml.PauliX(0), qml.PauliZ(0)] dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circ(time, coeffs): h = qml.dot(coeffs, terms) qml.TrotterProduct(h, time, n=2, order=2) return qml.state() initial_state = jnp.array([1.0, 0.0, 0.0, 0.0]) expected_product_sequence = _generate_simple_decomp(coeffs, terms, time, order=2, n=2) expected_state = ( reduce( lambda x, y: x @ y, [qml.matrix(op, wire_order=range(2)) for op in expected_product_sequence], ) @ initial_state ) state = circ(time, coeffs) assert allclose(expected_state, state) @pytest.mark.jax @pytest.mark.parametrize("time", (0.5, 1, 2)) def test_jaxjit_execute(self, time): """Test that the gate executes correctly in the jax interface with jit.""" import jax from jax import numpy as jnp time = jnp.array(time) c1 = jnp.array(1.23) c2 = jnp.array(-0.45) terms = [qml.PauliX(0), qml.PauliZ(0)] dev = qml.device("default.qubit", wires=2) @jax.jit @qml.qnode(dev, interface="jax") def circ(time, c1, c2): h = qml.sum( qml.s_prod(c1, terms[0]), qml.s_prod(c2, terms[1]), ) qml.TrotterProduct(h, time, n=2, order=2, check_hermitian=False) return qml.state() initial_state = jnp.array([1.0, 0.0, 0.0, 0.0]) expected_product_sequence = _generate_simple_decomp([c1, c2], terms, time, order=2, n=2) expected_state = ( reduce( lambda x, y: x @ y, [qml.matrix(op, wire_order=range(2)) for op in expected_product_sequence], ) @ initial_state ) state = circ(time, c1, c2) assert allclose(expected_state, state) @pytest.mark.tf @pytest.mark.parametrize("time", (0.5, 1, 2)) def test_tf_execute(self, time): """Test that the gate executes correctly in the tensorflow interface.""" import tensorflow as tf time = tf.Variable(time, dtype=tf.complex128) coeffs = tf.Variable([1.23, -0.45], dtype=tf.complex128) terms = [qml.PauliX(0), qml.PauliZ(0)] dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circ(time, coeffs): h = qml.sum( qml.s_prod(coeffs[0], terms[0]), qml.s_prod(coeffs[1], terms[1]), ) qml.TrotterProduct(h, time, n=2, order=2) return qml.state() initial_state = tf.Variable([1.0, 0.0, 0.0, 0.0], dtype=tf.complex128) expected_product_sequence = _generate_simple_decomp(coeffs, terms, time, order=2, n=2) expected_state = tf.linalg.matvec( reduce( lambda x, y: x @ y, [qml.matrix(op, wire_order=range(2)) for op in expected_product_sequence], ), initial_state, ) state = circ(time, coeffs) assert allclose(expected_state, state) @pytest.mark.torch @pytest.mark.parametrize("time", (0.5, 1, 2)) def test_torch_execute(self, time): """Test that the gate executes correctly in the torch interface.""" import torch time = torch.tensor(time, dtype=torch.complex64, requires_grad=True) coeffs = torch.tensor([1.23, -0.45], dtype=torch.complex64, requires_grad=True) terms = [qml.PauliX(0), qml.PauliZ(0)] dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circ(time, coeffs): h = qml.dot(coeffs, terms) qml.TrotterProduct(h, time, n=2, order=2) return qml.state() initial_state = torch.tensor([1.0, 0.0, 0.0, 0.0], dtype=torch.complex64) expected_product_sequence = _generate_simple_decomp(coeffs, terms, time, order=2, n=2) expected_state = ( reduce( lambda x, y: x @ y, [qml.matrix(op, wire_order=range(2)) for op in expected_product_sequence], ) @ initial_state ) state = circ(time, coeffs) assert allclose(expected_state, state) @pytest.mark.autograd @pytest.mark.parametrize("time", (0.5, 1, 2)) def test_autograd_execute(self, time): """Test that the gate executes correctly in the autograd interface.""" time = qnp.array(time) coeffs = qnp.array([1.23, -0.45]) terms = [qml.PauliX(0), qml.PauliZ(0)] dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circ(time, coeffs): h = qml.dot(coeffs, terms) qml.TrotterProduct(h, time, n=2, order=2) return qml.state() initial_state = qnp.array([1.0, 0.0, 0.0, 0.0]) expected_product_sequence = _generate_simple_decomp(coeffs, terms, time, order=2, n=2) expected_state = ( reduce( lambda x, y: x @ y, [qml.matrix(op, wire_order=range(2)) for op in expected_product_sequence], ) @ initial_state ) state = circ(time, coeffs) assert qnp.allclose(expected_state, state) @pytest.mark.autograd @pytest.mark.parametrize("order, n", ((1, 1), (1, 2), (2, 1), (4, 1))) def test_autograd_gradient(self, order, n): """Test that the gradient is computed correctly""" time = qnp.array(1.5) coeffs = qnp.array([1.23, -0.45]) terms = [qml.PauliX(0), qml.PauliZ(0)] dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def circ(time, coeffs): h = qml.dot(coeffs, terms) qml.TrotterProduct(h, time, n=n, order=order) return qml.expval(qml.Hadamard(0)) @qml.qnode(dev) def reference_circ(time, coeffs): with qml.QueuingManager.stop_recording(): decomp = _generate_simple_decomp(coeffs, terms, time, order, n) for op in decomp[::-1]: qml.apply(op) return qml.expval(qml.Hadamard(0)) measured_time_grad, measured_coeff_grad = qml.grad(circ)(time, coeffs) reference_time_grad, reference_coeff_grad = qml.grad(reference_circ)(time, coeffs) assert allclose(measured_time_grad, reference_time_grad) assert allclose(measured_coeff_grad, reference_coeff_grad) @pytest.mark.torch @pytest.mark.parametrize("order, n", ((1, 1), (1, 2), (2, 1), (4, 1))) def test_torch_gradient(self, order, n): """Test that the gradient is computed correctly using torch""" import torch time = torch.tensor(1.5, dtype=torch.complex64, requires_grad=True) coeffs = torch.tensor([1.23, -0.45], dtype=torch.complex64, requires_grad=True) time_reference = torch.tensor(1.5, dtype=torch.complex64, requires_grad=True) coeffs_reference = torch.tensor([1.23, -0.45], dtype=torch.complex64, requires_grad=True) terms = [qml.PauliX(0), qml.PauliZ(0)] dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def circ(time, coeffs): h = qml.dot(coeffs, terms) qml.TrotterProduct(h, time, n=n, order=order) return qml.expval(qml.Hadamard(0)) @qml.qnode(dev) def reference_circ(time, coeffs): with qml.QueuingManager.stop_recording(): decomp = _generate_simple_decomp(coeffs, terms, time, order, n) for op in decomp[::-1]: qml.apply(op) return qml.expval(qml.Hadamard(0)) res_circ = circ(time, coeffs) res_circ.backward() measured_time_grad = time.grad measured_coeff_grad = coeffs.grad ref_circ = reference_circ(time_reference, coeffs_reference) ref_circ.backward() reference_time_grad = time_reference.grad reference_coeff_grad = coeffs_reference.grad assert allclose(measured_time_grad, reference_time_grad) assert allclose(measured_coeff_grad, reference_coeff_grad) @pytest.mark.tf @pytest.mark.parametrize("order, n", ((1, 1), (1, 2), (2, 1), (4, 1))) def test_tf_gradient(self, order, n): """Test that the gradient is computed correctly using tensorflow""" import tensorflow as tf time = tf.Variable(1.5, dtype=tf.complex128) coeffs = tf.Variable([1.23, -0.45], dtype=tf.complex128) terms = [qml.PauliX(0), qml.PauliZ(0)] dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def circ(time, coeffs): h = qml.sum( qml.s_prod(coeffs[0], terms[0]), qml.s_prod(coeffs[1], terms[1]), ) qml.TrotterProduct(h, time, n=n, order=order) return qml.expval(qml.Hadamard(0)) @qml.qnode(dev) def reference_circ(time, coeffs): with qml.QueuingManager.stop_recording(): decomp = _generate_simple_decomp(coeffs, terms, time, order, n) for op in decomp[::-1]: qml.apply(op) return qml.expval(qml.Hadamard(0)) with tf.GradientTape() as tape: result = circ(time, coeffs) measured_time_grad, measured_coeff_grad = tape.gradient(result, (time, coeffs)) with tf.GradientTape() as tape: result = reference_circ(time, coeffs) reference_time_grad, reference_coeff_grad = tape.gradient(result, (time, coeffs)) assert allclose(measured_time_grad, reference_time_grad) assert allclose(measured_coeff_grad, reference_coeff_grad) @pytest.mark.jax @pytest.mark.parametrize("order, n", ((1, 1), (1, 2), (2, 1), (4, 1))) def test_jax_gradient(self, order, n): """Test that the gradient is computed correctly""" import jax from jax import numpy as jnp time = jnp.array(1.5) coeffs = jnp.array([1.23, -0.45]) terms = [qml.PauliX(0), qml.PauliZ(0)] dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def circ(time, coeffs): h = qml.dot(coeffs, terms) qml.TrotterProduct(h, time, n=n, order=order) return qml.expval(qml.Hadamard(0)) @qml.qnode(dev) def reference_circ(time, coeffs): with qml.QueuingManager.stop_recording(): decomp = _generate_simple_decomp(coeffs, terms, time, order, n) for op in decomp[::-1]: qml.apply(op) return qml.expval(qml.Hadamard(0)) measured_time_grad, measured_coeff_grad = jax.grad(circ, argnums=[0, 1])(time, coeffs) reference_time_grad, reference_coeff_grad = jax.grad(reference_circ, argnums=[0, 1])( time, coeffs ) assert allclose(measured_time_grad, reference_time_grad) assert allclose(measured_coeff_grad, reference_coeff_grad)
pennylane/tests/templates/test_subroutines/test_trotter.py/0
{ "file_path": "pennylane/tests/templates/test_subroutines/test_trotter.py", "repo_id": "pennylane", "token_count": 25049 }
96
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # 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. """ Unit tests for the :mod:`pennylane.qaoa` submodule. """ import itertools import networkx as nx import numpy as np import pytest import rustworkx as rx from networkx import Graph from scipy.linalg import expm from scipy.sparse import csc_matrix, kron import pennylane as qml from pennylane import qaoa from pennylane.qaoa.cycle import ( _inner_net_flow_constraint_hamiltonian, _inner_out_flow_constraint_hamiltonian, _partial_cycle_mixer, _square_hamiltonian_terms, cycle_mixer, edges_to_wires, loss_hamiltonian, net_flow_constraint, out_flow_constraint, wires_to_edges, ) ##################################################### line_graph = Graph() line_graph.add_nodes_from([0, 1, 2]) line_graph.add_edges_from([(0, 1), (1, 2)]) graph_rx = rx.PyGraph() graph_rx.add_nodes_from([0, 1, 2]) graph_rx.add_edges_from([(0, 1, ""), (1, 2, "")]) non_consecutive_graph = Graph([(0, 4), (3, 4), (2, 1), (2, 0)]) non_consecutive_graph_rx = rx.PyGraph() non_consecutive_graph_rx.add_nodes_from([0, 1, 2, 3, 4]) non_consecutive_graph_rx.add_edges_from([(0, 4, ""), (0, 2, ""), (4, 3, ""), (2, 1, "")]) g1 = Graph([(0, 1), (1, 2)]) g1_rx = rx.PyGraph() g1_rx.add_nodes_from([0, 1, 2]) g1_rx.add_edges_from([(0, 1, ""), (1, 2, "")]) g2 = nx.Graph([(0, 1), (1, 2), (2, 3)]) g2_rx = rx.PyGraph() g2_rx.add_nodes_from([0, 1, 2, 3]) g2_rx.add_edges_from([(0, 1, ""), (1, 2, ""), (2, 3, "")]) b_rx = rx.PyGraph() b_rx.add_nodes_from(["b", 1, 0.3]) b_rx.add_edges_from([(0, 1, ""), (1, 2, ""), (0, 2, "")]) def lollipop_graph_rx(mesh_nodes: int, path_nodes: int, to_directed: bool = False): if to_directed: g = rx.generators.directed_mesh_graph(weights=[*range(mesh_nodes)]) else: g = rx.generators.mesh_graph(weights=[*range(mesh_nodes)]) if path_nodes < 1: return g for i in range(path_nodes): g.add_node(mesh_nodes + i) g.add_edges_from([(mesh_nodes + i - 1, mesh_nodes + i, "")]) if to_directed: g.add_edges_from([(mesh_nodes + i, mesh_nodes + i - 1, "")]) return g def matrix(hamiltonian: qml.Hamiltonian, n_wires: int) -> csc_matrix: r"""Calculates the matrix representation of an input Hamiltonian in the standard basis. Args: hamiltonian (qml.Hamiltonian): the input Hamiltonian n_wires (int): the total number of wires Returns: csc_matrix: a sparse matrix representation """ ops_matrices = [] for op in hamiltonian.ops: if isinstance(op, qml.ops.Prod): op_matrix = op.sparse_matrix(wire_order=list(range(n_wires))) else: op_wires = np.array(op.wires.tolist()) op_list = op.non_identity_obs if isinstance(op, qml.operation.Tensor) else [op] op_matrices = [] for wire in range(n_wires): loc = np.argwhere(op_wires == wire).flatten() mat = np.eye(2) if len(loc) == 0 else op_list[loc[0]].matrix() mat = csc_matrix(mat) op_matrices.append(mat) op_matrix = op_matrices.pop(0) for mat in op_matrices: op_matrix = kron(op_matrix, mat) ops_matrices.append(op_matrix) mat = sum(coeff * op_mat for coeff, op_mat in zip(hamiltonian.coeffs, ops_matrices)) return csc_matrix(mat) def make_xy_mixer_test_cases(): return [ ( g2, qml.Hamiltonian( [0.5, 0.5, 0.5, 0.5, 0.5, 0.5], [ qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliY(1), qml.PauliX(1) @ qml.PauliX(2), qml.PauliY(1) @ qml.PauliY(2), qml.PauliX(2) @ qml.PauliX(3), qml.PauliY(2) @ qml.PauliY(3), ], ), ), ( line_graph, qml.Hamiltonian( [0.5, 0.5, 0.5, 0.5], [ qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliY(1), qml.PauliX(1) @ qml.PauliX(2), qml.PauliY(1) @ qml.PauliY(2), ], ), ), ( non_consecutive_graph, qml.Hamiltonian( [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], [ qml.PauliX(0) @ qml.PauliX(4), qml.PauliY(0) @ qml.PauliY(4), qml.PauliX(0) @ qml.PauliX(2), qml.PauliY(0) @ qml.PauliY(2), qml.PauliX(4) @ qml.PauliX(3), qml.PauliY(4) @ qml.PauliY(3), qml.PauliX(2) @ qml.PauliX(1), qml.PauliY(2) @ qml.PauliY(1), ], ), ), ( g2_rx, qml.Hamiltonian( [0.5, 0.5, 0.5, 0.5, 0.5, 0.5], [ qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliY(1), qml.PauliX(1) @ qml.PauliX(2), qml.PauliY(1) @ qml.PauliY(2), qml.PauliX(2) @ qml.PauliX(3), qml.PauliY(2) @ qml.PauliY(3), ], ), ), ( graph_rx, qml.Hamiltonian( [0.5, 0.5, 0.5, 0.5], [ qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliY(1), qml.PauliX(1) @ qml.PauliX(2), qml.PauliY(1) @ qml.PauliY(2), ], ), ), ( non_consecutive_graph_rx, qml.Hamiltonian( [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], [ qml.PauliX(0) @ qml.PauliX(4), qml.PauliY(0) @ qml.PauliY(4), qml.PauliX(0) @ qml.PauliX(2), qml.PauliY(0) @ qml.PauliY(2), qml.PauliX(4) @ qml.PauliX(3), qml.PauliY(4) @ qml.PauliY(3), qml.PauliX(2) @ qml.PauliX(1), qml.PauliY(2) @ qml.PauliY(1), ], ), ), ( Graph((np.array([0, 1]), np.array([1, 2]), np.array([2, 0]))), qml.Hamiltonian( [0.5, 0.5, 0.5, 0.5, 0.5, 0.5], [ qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliY(1), qml.PauliX(0) @ qml.PauliX(2), qml.PauliY(0) @ qml.PauliY(2), qml.PauliX(1) @ qml.PauliX(2), qml.PauliY(1) @ qml.PauliY(2), ], ), ), ] def make_bit_flip_mixer_test_cases(): return [ ( Graph([(0, 1)]), 1, qml.Hamiltonian( [0.5, -0.5, 0.5, -0.5], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliX(1), qml.PauliX(1) @ qml.PauliZ(0), ], ), ), ( g1, 0, qml.Hamiltonian( [0.5, 0.5, 0.25, 0.25, 0.25, 0.25, 0.5, 0.5], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliX(1), qml.PauliX(1) @ qml.PauliZ(2), qml.PauliX(1) @ qml.PauliZ(0), qml.PauliX(1) @ qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliX(2), qml.PauliX(2) @ qml.PauliZ(1), ], ), ), ( g1_rx, 0, qml.Hamiltonian( [0.5, 0.5, 0.25, 0.25, 0.25, 0.25, 0.5, 0.5], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliX(1), qml.PauliX(1) @ qml.PauliZ(2), qml.PauliX(1) @ qml.PauliZ(0), qml.PauliX(1) @ qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliX(2), qml.PauliX(2) @ qml.PauliZ(1), ], ), ), ( Graph([("b", 1), (1, 0.3), (0.3, "b")]), 1, qml.Hamiltonian( [0.25, -0.25, -0.25, 0.25, 0.25, -0.25, -0.25, 0.25, 0.25, -0.25, -0.25, 0.25], [ qml.PauliX("b"), qml.PauliX("b") @ qml.PauliZ(0.3), qml.PauliX("b") @ qml.PauliZ(1), qml.PauliX("b") @ qml.PauliZ(1) @ qml.PauliZ(0.3), qml.PauliX(1), qml.PauliX(1) @ qml.PauliZ(0.3), qml.PauliX(1) @ qml.PauliZ("b"), qml.PauliX(1) @ qml.PauliZ("b") @ qml.PauliZ(0.3), qml.PauliX(0.3), qml.PauliX(0.3) @ qml.PauliZ("b"), qml.PauliX(0.3) @ qml.PauliZ(1), qml.PauliX(0.3) @ qml.PauliZ(1) @ qml.PauliZ("b"), ], ), ), ( b_rx, 1, qml.Hamiltonian( [0.25, -0.25, -0.25, 0.25, 0.25, -0.25, -0.25, 0.25, 0.25, -0.25, -0.25, 0.25], [ qml.PauliX("b"), qml.PauliX("b") @ qml.PauliZ(0.3), qml.PauliX("b") @ qml.PauliZ(1), qml.PauliX("b") @ qml.PauliZ(1) @ qml.PauliZ(0.3), qml.PauliX(1), qml.PauliX(1) @ qml.PauliZ(0.3), qml.PauliX(1) @ qml.PauliZ("b"), qml.PauliX(1) @ qml.PauliZ("b") @ qml.PauliZ(0.3), qml.PauliX(0.3), qml.PauliX(0.3) @ qml.PauliZ(1), qml.PauliX(0.3) @ qml.PauliZ("b"), qml.PauliX(0.3) @ qml.PauliZ("b") @ qml.PauliZ(1), ], ), ), ] class TestMixerHamiltonians: """Tests that the mixer Hamiltonians are being generated correctly""" @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_x_mixer_output(self): """Tests that the output of the Pauli-X mixer is correct""" wires = range(4) mixer_hamiltonian = qaoa.x_mixer(wires) expected_hamiltonian = qml.Hamiltonian( [1, 1, 1, 1], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2), qml.PauliX(3)], ) assert mixer_hamiltonian.compare(expected_hamiltonian) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_x_mixer_grouping(self): """Tests that the grouping information is set and correct""" wires = range(4) mixer_hamiltonian = qaoa.x_mixer(wires) # check that all observables commute assert all(qml.is_commuting(o, mixer_hamiltonian.ops[0]) for o in mixer_hamiltonian.ops[1:]) # check that the 1-group grouping information was set assert mixer_hamiltonian.grouping_indices is not None assert mixer_hamiltonian.grouping_indices == ((0, 1, 2, 3),) def test_xy_mixer_type_error(self): """Tests that the XY mixer throws the correct error""" graph = [(0, 1), (1, 2)] with pytest.raises( ValueError, match=r"Input graph must be a nx.Graph or rx.PyGraph object, got list" ): qaoa.xy_mixer(graph) @pytest.mark.usefixtures("use_legacy_and_new_opmath") @pytest.mark.parametrize(("graph", "target_hamiltonian"), make_xy_mixer_test_cases()) def test_xy_mixer_output(self, graph, target_hamiltonian): """Tests that the output of the XY mixer is correct""" if not qml.operation.active_new_opmath(): target_hamiltonian = qml.operation.convert_to_legacy_H(target_hamiltonian) hamiltonian = qaoa.xy_mixer(graph) assert hamiltonian.compare(target_hamiltonian) def test_bit_flip_mixer_errors(self): """Tests that the bit-flip mixer throws the correct errors""" graph = [(0, 1), (1, 2)] with pytest.raises( ValueError, match=r"Input graph must be a nx.Graph or rx.PyGraph object" ): qaoa.bit_flip_mixer(graph, 0) n = 2 with pytest.raises(ValueError, match=r"'b' must be either 0 or 1"): qaoa.bit_flip_mixer(Graph(graph), n) @pytest.mark.parametrize( ("graph", "n", "target_hamiltonian"), make_bit_flip_mixer_test_cases(), ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_bit_flip_mixer_output(self, graph, n, target_hamiltonian): """Tests that the output of the bit-flip mixer is correct""" if not qml.operation.active_new_opmath(): target_hamiltonian = qml.operation.convert_to_legacy_H(target_hamiltonian) hamiltonian = qaoa.bit_flip_mixer(graph, n) assert hamiltonian.compare(target_hamiltonian) GRAPHS = [ g1, g1_rx, Graph((np.array([0, 1]), np.array([1, 2]), np.array([0, 2]))), line_graph, graph_rx, ] def make_max_cut_test_cases(): """Generates test cases for the maxcut problem""" cost_coeffs = [ [0.5, 0.5, -1.0], [0.5, 0.5, -1.0], [0.5, 0.5, 0.5, -1.5], [0.5, 0.5, -1.0], [0.5, 0.5, -1.0], ] cost_terms = [ [qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(1) @ qml.PauliZ(2), qml.Identity(0)], [qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(1) @ qml.PauliZ(2), qml.Identity(0)], [ qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliZ(1) @ qml.PauliZ(2), qml.Identity(0), ], [qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(1) @ qml.PauliZ(2), qml.Identity(0)], [qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(1) @ qml.PauliZ(2), qml.Identity(0)], ] cost_hamiltonians = [qml.Hamiltonian(cost_coeffs[i], cost_terms[i]) for i in range(5)] mixer_coeffs = [ [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], ] mixer_terms = [ [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], ] mixer_hamiltonians = [qml.Hamiltonian(mixer_coeffs[i], mixer_terms[i]) for i in range(5)] return list(zip(GRAPHS, cost_hamiltonians, mixer_hamiltonians)) CONSTRAINED = [ True, True, True, False, False, ] def make_max_independent_test_cases(): """Generates test cases for the max independent set problem""" cost_coeffs = [ [1, 1, 1], [1, 1, 1], [1, 1, 1], [0.75, 0.25, -0.5, 0.75, 0.25], [0.75, 0.25, -0.5, 0.75, 0.25], ] cost_terms = [ [qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2)], [qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2)], [qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2)], [ qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(1) @ qml.PauliZ(2), qml.PauliZ(2), ], # [qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2)], [ qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(1) @ qml.PauliZ(2), qml.PauliZ(2), ], ] cost_hamiltonians = [qml.Hamiltonian(cost_coeffs[i], cost_terms[i]) for i in range(5)] mixer_coeffs = [ [0.5, 0.5, 0.25, 0.25, 0.25, 0.25, 0.5, 0.5], [0.5, 0.5, 0.25, 0.25, 0.25, 0.25, 0.5, 0.5], [0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25], [1, 1, 1], [1, 1, 1], ] mixer_terms = [ [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliX(1), qml.PauliX(1) @ qml.PauliZ(2), qml.PauliX(1) @ qml.PauliZ(0), qml.PauliX(1) @ qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliX(2), qml.PauliX(2) @ qml.PauliZ(1), ], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliX(1), qml.PauliX(1) @ qml.PauliZ(2), qml.PauliX(1) @ qml.PauliZ(0), qml.PauliX(1) @ qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliX(2), qml.PauliX(2) @ qml.PauliZ(1), ], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(2), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliX(0) @ qml.PauliZ(1) @ qml.PauliZ(2), qml.PauliX(1), qml.PauliX(1) @ qml.PauliZ(2), qml.PauliX(1) @ qml.PauliZ(0), qml.PauliX(1) @ qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliX(2), qml.PauliX(2) @ qml.PauliZ(0), qml.PauliX(2) @ qml.PauliZ(1), qml.PauliX(2) @ qml.PauliZ(1) @ qml.PauliZ(0), ], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], ] mixer_hamiltonians = [qml.Hamiltonian(mixer_coeffs[i], mixer_terms[i]) for i in range(5)] return list(zip(GRAPHS, CONSTRAINED, cost_hamiltonians, mixer_hamiltonians)) def make_min_vertex_cover_test_cases(): """Generates the test cases for the min vertex cover problem""" cost_coeffs = [ [-1, -1, -1], [-1, -1, -1], [-1, -1, -1], [0.75, -0.25, 0.5, 0.75, -0.25], [0.75, -0.25, 0.5, 0.75, -0.25], ] cost_terms = [ [qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2)], [qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2)], [qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2)], [ qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(1) @ qml.PauliZ(2), qml.PauliZ(2), ], [ qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(1) @ qml.PauliZ(2), qml.PauliZ(2), ], ] cost_hamiltonians = [qml.Hamiltonian(cost_coeffs[i], cost_terms[i]) for i in range(5)] mixer_coeffs = [ [0.5, -0.5, 0.25, -0.25, -0.25, 0.25, 0.5, -0.5], [0.5, -0.5, 0.25, -0.25, -0.25, 0.25, 0.5, -0.5], [0.25, -0.25, -0.25, 0.25, 0.25, -0.25, -0.25, 0.25, 0.25, -0.25, -0.25, 0.25], [1, 1, 1], [1, 1, 1], ] mixer_terms = [ [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliX(1), qml.PauliX(1) @ qml.PauliZ(2), qml.PauliX(1) @ qml.PauliZ(0), qml.PauliX(1) @ qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliX(2), qml.PauliX(2) @ qml.PauliZ(1), ], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliX(1), qml.PauliX(1) @ qml.PauliZ(2), qml.PauliX(1) @ qml.PauliZ(0), qml.PauliX(1) @ qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliX(2), qml.PauliX(2) @ qml.PauliZ(1), ], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(2), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliX(0) @ qml.PauliZ(1) @ qml.PauliZ(2), qml.PauliX(1), qml.PauliX(1) @ qml.PauliZ(2), qml.PauliX(1) @ qml.PauliZ(0), qml.PauliX(1) @ qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliX(2), qml.PauliX(2) @ qml.PauliZ(0), qml.PauliX(2) @ qml.PauliZ(1), qml.PauliX(2) @ qml.PauliZ(1) @ qml.PauliZ(0), ], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], ] mixer_hamiltonians = [qml.Hamiltonian(mixer_coeffs[i], mixer_terms[i]) for i in range(5)] return list(zip(GRAPHS, CONSTRAINED, cost_hamiltonians, mixer_hamiltonians)) def make_max_clique_test_cases(): """Generates the test cases for the max clique problem""" cost_coeffs = [ [1, 1, 1], [1, 1, 1], [1, 1, 1], [0.75, 0.25, 0.25, 1], [0.75, 0.25, 0.25, 1], ] cost_terms = [ [qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2)], [qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2)], [qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2)], [qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliZ(0), qml.PauliZ(2), qml.PauliZ(1)], [qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliZ(0), qml.PauliZ(2), qml.PauliZ(1)], ] cost_hamiltonians = [qml.Hamiltonian(cost_coeffs[i], cost_terms[i]) for i in range(5)] mixer_coeffs = [ [0.5, 0.5, 1.0, 0.5, 0.5], [0.5, 0.5, 1.0, 0.5, 0.5], [1.0, 1.0, 1.0], [1, 1, 1], [1, 1, 1], ] mixer_terms = [ [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(2), qml.PauliX(1), qml.PauliX(2), qml.PauliX(2) @ qml.PauliZ(0), ], [ qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(2), qml.PauliX(1), qml.PauliX(2), qml.PauliX(2) @ qml.PauliZ(0), ], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], [qml.PauliX(0), qml.PauliX(1), qml.PauliX(2)], ] mixer_hamiltonians = [qml.Hamiltonian(mixer_coeffs[i], mixer_terms[i]) for i in range(5)] return list(zip(GRAPHS, CONSTRAINED, cost_hamiltonians, mixer_hamiltonians)) def make_edge_driver_cost_test_cases(): """Generates the test cases for the edge driver cost Hamiltonian""" graphs = GRAPHS[1:-2] graphs.append(line_graph) graphs.append(Graph([("b", 1), (1, 2.3)])) graphs.append(graph_rx) b1_rx = rx.PyGraph() b1_rx.add_nodes_from(["b", 1, 2.3]) b1_rx.add_edges_from([(0, 1, ""), (1, 2, "")]) graphs.append(b1_rx) rewards = [ ["00"], ["00", "11"], ["00", "11", "01", "10"], ["00", "01", "10"], ["00", "11", "01", "10"], ["00", "01", "10"], ] hamiltonians = [ qml.Hamiltonian( [-0.25, -0.25, -0.25, -0.25, -0.25, -0.25], [ qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(1) @ qml.PauliZ(2), qml.PauliZ(1), qml.PauliZ(2), ], ), qml.Hamiltonian( [-0.5, -0.5, -0.5], [ qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliZ(1) @ qml.PauliZ(2), ], ), qml.Hamiltonian([1, 1, 1], [qml.Identity(0), qml.Identity(1), qml.Identity(2)]), qml.Hamiltonian( [0.25, -0.25, -0.25, 0.25, -0.25, -0.25], [ qml.PauliZ("b") @ qml.PauliZ(1), qml.PauliZ("b"), qml.PauliZ(1), qml.PauliZ(1) @ qml.PauliZ(2.3), qml.PauliZ(1), qml.PauliZ(2.3), ], ), qml.Hamiltonian([1, 1, 1], [qml.Identity(0), qml.Identity(1), qml.Identity(2)]), qml.Hamiltonian( [0.25, -0.25, -0.25, 0.25, -0.25, -0.25], [ qml.PauliZ("b") @ qml.PauliZ(1), qml.PauliZ("b"), qml.PauliZ(1), qml.PauliZ(1) @ qml.PauliZ(2.3), qml.PauliZ(1), qml.PauliZ(2.3), ], ), ] return zip(graphs, rewards, hamiltonians) def make_max_weighted_cycle_test_cases(): """Generates the test cases for the maximum weighted cycle problem""" digraph_complete = nx.complete_graph(3).to_directed() complete_edge_weight_data = { edge: (i + 1) * 0.5 for i, edge in enumerate(digraph_complete.edges) } for _k, _v in complete_edge_weight_data.items(): digraph_complete[_k[0]][_k[1]]["weight"] = _v digraph_complete_rx = rx.generators.directed_mesh_graph(3, [0, 1, 2]) complete_edge_weight_data = { edge: (i + 1) * 0.5 for i, edge in enumerate(sorted(digraph_complete_rx.edge_list())) } for _k, _v in complete_edge_weight_data.items(): digraph_complete_rx.update_edge(_k[0], _k[1], {"weight": _v}) digraphs = [digraph_complete] * 2 mwc_constrained = [True, False] cost_coeffs = [ [ -0.6931471805599453, 0.0, 0.4054651081081644, 0.6931471805599453, 0.9162907318741551, 1.0986122886681098, ], [ -6.693147180559945, -6.0, -5.594534891891835, -5.306852819440055, -5.083709268125845, -4.90138771133189, 54, 12, -12, -6, -6, -12, 6, 12, -6, -6, -12, 6, 12, -6, -6, 6, ], ] cost_terms = [ [ qml.PauliZ(wires=[0]), qml.PauliZ(wires=[1]), qml.PauliZ(wires=[2]), qml.PauliZ(wires=[3]), qml.PauliZ(wires=[4]), qml.PauliZ(wires=[5]), ], [ qml.PauliZ(wires=[0]), qml.PauliZ(wires=[1]), qml.PauliZ(wires=[2]), qml.PauliZ(wires=[3]), qml.PauliZ(wires=[4]), qml.PauliZ(wires=[5]), qml.Identity(wires=[0]), qml.PauliZ(wires=[0]) @ qml.PauliZ(wires=[1]), qml.PauliZ(wires=[0]) @ qml.PauliZ(wires=[2]), qml.PauliZ(wires=[0]) @ qml.PauliZ(wires=[4]), qml.PauliZ(wires=[1]) @ qml.PauliZ(wires=[2]), qml.PauliZ(wires=[1]) @ qml.PauliZ(wires=[4]), qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[4]), qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[3]), qml.PauliZ(wires=[2]) @ qml.PauliZ(wires=[5]), qml.PauliZ(wires=[0]) @ qml.PauliZ(wires=[3]), qml.PauliZ(wires=[3]) @ qml.PauliZ(wires=[5]), qml.PauliZ(wires=[0]) @ qml.PauliZ(wires=[5]), qml.PauliZ(wires=[4]) @ qml.PauliZ(wires=[5]), qml.PauliZ(wires=[3]) @ qml.PauliZ(wires=[4]), qml.PauliZ(wires=[1]) @ qml.PauliZ(wires=[5]), qml.PauliZ(wires=[1]) @ qml.PauliZ(wires=[3]), ], ] cost_hamiltonians = [qml.Hamiltonian(cost_coeffs[i], cost_terms[i]) for i in range(2)] mixer_coeffs = [ [ 0.25, 0.25, 0.25, -0.25, 0.25, 0.25, 0.25, -0.25, 0.25, 0.25, 0.25, -0.25, 0.25, 0.25, 0.25, -0.25, 0.25, 0.25, 0.25, -0.25, 0.25, 0.25, 0.25, -0.25, ], [1] * 6, ] mixer_terms = [ [ qml.PauliX(wires=[0]) @ qml.PauliX(wires=[1]) @ qml.PauliX(wires=[5]), qml.PauliY(wires=[0]) @ qml.PauliY(wires=[1]) @ qml.PauliX(wires=[5]), qml.PauliY(wires=[0]) @ qml.PauliX(wires=[1]) @ qml.PauliY(wires=[5]), qml.PauliX(wires=[0]) @ qml.PauliY(wires=[1]) @ qml.PauliY(wires=[5]), qml.PauliX(wires=[1]) @ qml.PauliX(wires=[0]) @ qml.PauliX(wires=[3]), qml.PauliY(wires=[1]) @ qml.PauliY(wires=[0]) @ qml.PauliX(wires=[3]), qml.PauliY(wires=[1]) @ qml.PauliX(wires=[0]) @ qml.PauliY(wires=[3]), qml.PauliX(wires=[1]) @ qml.PauliY(wires=[0]) @ qml.PauliY(wires=[3]), qml.PauliX(wires=[2]) @ qml.PauliX(wires=[3]) @ qml.PauliX(wires=[4]), qml.PauliY(wires=[2]) @ qml.PauliY(wires=[3]) @ qml.PauliX(wires=[4]), qml.PauliY(wires=[2]) @ qml.PauliX(wires=[3]) @ qml.PauliY(wires=[4]), qml.PauliX(wires=[2]) @ qml.PauliY(wires=[3]) @ qml.PauliY(wires=[4]), qml.PauliX(wires=[3]) @ qml.PauliX(wires=[2]) @ qml.PauliX(wires=[1]), qml.PauliY(wires=[3]) @ qml.PauliY(wires=[2]) @ qml.PauliX(wires=[1]), qml.PauliY(wires=[3]) @ qml.PauliX(wires=[2]) @ qml.PauliY(wires=[1]), qml.PauliX(wires=[3]) @ qml.PauliY(wires=[2]) @ qml.PauliY(wires=[1]), qml.PauliX(wires=[4]) @ qml.PauliX(wires=[5]) @ qml.PauliX(wires=[2]), qml.PauliY(wires=[4]) @ qml.PauliY(wires=[5]) @ qml.PauliX(wires=[2]), qml.PauliY(wires=[4]) @ qml.PauliX(wires=[5]) @ qml.PauliY(wires=[2]), qml.PauliX(wires=[4]) @ qml.PauliY(wires=[5]) @ qml.PauliY(wires=[2]), qml.PauliX(wires=[5]) @ qml.PauliX(wires=[4]) @ qml.PauliX(wires=[0]), qml.PauliY(wires=[5]) @ qml.PauliY(wires=[4]) @ qml.PauliX(wires=[0]), qml.PauliY(wires=[5]) @ qml.PauliX(wires=[4]) @ qml.PauliY(wires=[0]), qml.PauliX(wires=[5]) @ qml.PauliY(wires=[4]) @ qml.PauliY(wires=[0]), ], [qml.PauliX(wires=i) for i in range(6)], ] mixer_hamiltonians = [qml.Hamiltonian(mixer_coeffs[i], mixer_terms[i]) for i in range(2)] mappings = [qaoa.cycle.wires_to_edges(digraph_complete)] * 2 return list(zip(digraphs, mwc_constrained, cost_hamiltonians, mixer_hamiltonians, mappings)) class TestCostHamiltonians: """Tests that the cost Hamiltonians are being generated correctly""" def test_bit_driver_error(self): """Tests that the bit driver Hamiltonian throws the correct error""" with pytest.raises(ValueError, match=r"'b' must be either 0 or 1"): qaoa.bit_driver(range(3), 2) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_bit_driver_output(self): """Tests that the bit driver Hamiltonian has the correct output""" H = qaoa.bit_driver(range(3), 1) hamiltonian = qml.Hamiltonian([1, 1, 1], [qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2)]) assert hamiltonian.compare(H) def test_edge_driver_errors(self): """Tests that the edge driver Hamiltonian throws the correct errors""" with pytest.raises( ValueError, match=r"Encountered invalid entry in 'reward', expected 2-bit bitstrings." ): qaoa.edge_driver(g1, ["10", "11", 21, "g"]) with pytest.raises( ValueError, match=r"'reward' cannot contain either '10' or '01', must contain neither or both.", ): qaoa.edge_driver(g1, ["11", "00", "01"]) with pytest.raises(ValueError, match=r"Input graph must be a nx.Graph or rx.PyGraph"): qaoa.edge_driver([(0, 1), (1, 2)], ["00", "11"]) @pytest.mark.usefixtures("use_legacy_and_new_opmath") @pytest.mark.parametrize(("graph", "reward", "hamiltonian"), make_edge_driver_cost_test_cases()) def test_edge_driver_output(self, graph, reward, hamiltonian): """Tests that the edge driver Hamiltonian throws the correct errors""" if not qml.operation.active_new_opmath(): hamiltonian = qml.operation.convert_to_legacy_H(hamiltonian) H = qaoa.edge_driver(graph, reward) assert hamiltonian.compare(H) def test_max_weight_cycle_errors(self): """Tests that the max weight cycle Hamiltonian throws the correct errors""" with pytest.raises( ValueError, match=r"Input graph must be a nx.Graph or rx.PyGraph or rx.PyDiGraph" ): qaoa.max_weight_cycle([(0, 1), (1, 2)]) def test_cost_graph_error(self): """Tests that the cost Hamiltonians throw the correct error""" graph = [(0, 1), (1, 2)] with pytest.raises(ValueError, match=r"Input graph must be a nx\.Graph or rx\.PyGraph"): qaoa.maxcut(graph) with pytest.raises(ValueError, match=r"Input graph must be a nx\.Graph or rx\.PyGraph"): qaoa.max_independent_set(graph) with pytest.raises(ValueError, match=r"Input graph must be a nx\.Graph or rx\.PyGraph"): qaoa.min_vertex_cover(graph) with pytest.raises(ValueError, match=r"Input graph must be a nx\.Graph or rx\.PyGraph"): qaoa.max_clique(graph) @pytest.mark.parametrize( ("graph", "cost_hamiltonian", "mixer_hamiltonian"), make_max_cut_test_cases() ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_maxcut_output(self, graph, cost_hamiltonian, mixer_hamiltonian): """Tests that the output of the MaxCut method is correct""" if not qml.operation.active_new_opmath(): cost_hamiltonian = qml.operation.convert_to_legacy_H(cost_hamiltonian) mixer_hamiltonian = qml.operation.convert_to_legacy_H(mixer_hamiltonian) cost_h, mixer_h = qaoa.maxcut(graph) assert cost_h.compare(cost_hamiltonian) assert mixer_h.compare(mixer_hamiltonian) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_maxcut_grouping(self): """Tests that the grouping information is set and correct""" maxcut = make_max_cut_test_cases() graph = maxcut[0][0] cost_h, _ = qaoa.maxcut(graph) # check that all observables commute assert all(qml.is_commuting(o, cost_h.ops[0]) for o in cost_h.ops[1:]) # check that the 1-group grouping information was set assert cost_h.grouping_indices is not None assert cost_h.grouping_indices == (tuple(range(len(cost_h.ops))),) @pytest.mark.parametrize( ("graph", "constrained", "cost_hamiltonian", "mixer_hamiltonian"), make_max_independent_test_cases(), ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_mis_output(self, graph, constrained, cost_hamiltonian, mixer_hamiltonian): """Tests that the output of the Max Indepenent Set method is correct""" if not qml.operation.active_new_opmath(): cost_hamiltonian = qml.operation.convert_to_legacy_H(cost_hamiltonian) mixer_hamiltonian = qml.operation.convert_to_legacy_H(mixer_hamiltonian) cost_h, mixer_h = qaoa.max_independent_set(graph, constrained=constrained) assert cost_h.compare(cost_hamiltonian) assert mixer_h.compare(mixer_hamiltonian) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_mis_grouping(self): """Tests that the grouping information is set and correct""" mis = make_max_independent_test_cases() graph = mis[0][0] cost_h, _ = qaoa.max_independent_set(graph) # check that all observables commute assert all(qml.is_commuting(o, cost_h.ops[0]) for o in cost_h.ops[1:]) # check that the 1-group grouping information was set assert cost_h.grouping_indices is not None assert cost_h.grouping_indices == (tuple(range(len(cost_h.ops))),) @pytest.mark.parametrize( ("graph", "constrained", "cost_hamiltonian", "mixer_hamiltonian"), make_min_vertex_cover_test_cases(), ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_mvc_output(self, graph, constrained, cost_hamiltonian, mixer_hamiltonian): """Tests that the output of the Min Vertex Cover method is correct""" if not qml.operation.active_new_opmath(): cost_hamiltonian = qml.operation.convert_to_legacy_H(cost_hamiltonian) mixer_hamiltonian = qml.operation.convert_to_legacy_H(mixer_hamiltonian) cost_h, mixer_h = qaoa.min_vertex_cover(graph, constrained=constrained) assert cost_h.compare(cost_hamiltonian) assert mixer_h.compare(mixer_hamiltonian) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_mvc_grouping(self): """Tests that the grouping information is set and correct""" mvc = make_min_vertex_cover_test_cases() graph = mvc[0][0] cost_h, _ = qaoa.min_vertex_cover(graph) # check that all observables commute assert all(qml.is_commuting(o, cost_h.ops[0]) for o in cost_h.ops[1:]) # check that the 1-group grouping information was set assert cost_h.grouping_indices is not None assert cost_h.grouping_indices == (tuple(range(len(cost_h.ops))),) @pytest.mark.parametrize( ("graph", "constrained", "cost_hamiltonian", "mixer_hamiltonian"), make_max_clique_test_cases(), ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_max_clique_output(self, graph, constrained, cost_hamiltonian, mixer_hamiltonian): """Tests that the output of the Maximum Clique method is correct""" if not qml.operation.active_new_opmath(): cost_hamiltonian = qml.operation.convert_to_legacy_H(cost_hamiltonian) mixer_hamiltonian = qml.operation.convert_to_legacy_H(mixer_hamiltonian) cost_h, mixer_h = qaoa.max_clique(graph, constrained=constrained) assert cost_h.compare(cost_hamiltonian) assert mixer_h.compare(mixer_hamiltonian) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_max_clique_grouping(self): """Tests that the grouping information is set and correct""" maxclique = make_max_clique_test_cases() graph = maxclique[0][0] cost_h, _ = qaoa.max_clique(graph) # check that all observables commute assert all(qml.is_commuting(o, cost_h.ops[0]) for o in cost_h.ops[1:]) # check that the 1-group grouping information was set assert cost_h.grouping_indices is not None assert cost_h.grouping_indices == (tuple(range(len(cost_h.ops))),) # pylint: disable=too-many-arguments @pytest.mark.parametrize( ("graph", "constrained", "cost_hamiltonian", "mixer_hamiltonian", "mapping"), make_max_weighted_cycle_test_cases(), ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_max_weight_cycle_output( self, graph, constrained, cost_hamiltonian, mixer_hamiltonian, mapping ): """Tests that the output of the maximum weighted cycle method is correct""" if not qml.operation.active_new_opmath(): cost_hamiltonian = qml.operation.convert_to_legacy_H(cost_hamiltonian) mixer_hamiltonian = qml.operation.convert_to_legacy_H(mixer_hamiltonian) cost_h, mixer_h, m = qaoa.max_weight_cycle(graph, constrained=constrained) assert cost_h.compare(cost_hamiltonian) assert mixer_h.compare(mixer_hamiltonian) assert mapping == m @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_max_weight_cycle_grouping(self): """Tests that the grouping information is set and correct""" mwc = make_max_weighted_cycle_test_cases() graph = mwc[0][0] cost_h, _, _ = qaoa.max_weight_cycle(graph) # check that all observables commute assert all(qml.is_commuting(o, cost_h.ops[0]) for o in cost_h.ops[1:]) # check that the 1-group grouping information was set assert cost_h.grouping_indices is not None assert cost_h.grouping_indices == (tuple(range(len(cost_h.ops))),) # pylint: disable=too-few-public-methods class TestUtils: """Tests that the utility functions are working properly""" # pylint: disable=protected-access @pytest.mark.usefixtures("use_legacy_opmath") @pytest.mark.parametrize( ("hamiltonian", "value"), ( (qml.Hamiltonian([1, 1], [qml.PauliZ(0), qml.PauliZ(1)]), True), (qml.Hamiltonian([1, 1], [qml.PauliX(0), qml.PauliZ(1)]), False), (qml.Hamiltonian([1, 1], [qml.PauliZ(0) @ qml.Identity(1), qml.PauliZ(1)]), True), (qml.Hamiltonian([1, 1], [qml.PauliZ(0), qml.PauliX(0) @ qml.PauliZ(1)]), False), ), ) def test_diagonal_terms(self, hamiltonian, value): hamiltonian = qml.operation.convert_to_legacy_H(hamiltonian) assert qaoa.layers._diagonal_terms(hamiltonian) == value def make_mixer_layer_test_cases(): return [ [ qml.Hamiltonian([1, 1], [qml.PauliX(0), qml.PauliX(1)]), [qml.PauliRot(2, "X", wires=[0]), qml.PauliRot(2, "X", wires=[1])], ], [ qml.X(0) + qml.X(1), [qml.PauliRot(2, "X", wires=[0]), qml.PauliRot(2, "X", wires=[1])], ], [ qaoa.xy_mixer(Graph([(0, 1), (1, 2), (2, 0)])), [ qml.PauliRot(1.0, "XX", wires=[0, 1]), qml.PauliRot(1.0, "YY", wires=[0, 1]), qml.PauliRot(1.0, "XX", wires=[0, 2]), qml.PauliRot(1.0, "YY", wires=[0, 2]), qml.PauliRot(1.0, "XX", wires=[1, 2]), qml.PauliRot(1.0, "YY", wires=[1, 2]), ], ], ] def make_cost_layer_test_cases(): return [ [ qml.Hamiltonian([1, 1], [qml.PauliZ(0), qml.PauliZ(1)]), [qml.PauliRot(2, "Z", wires=[0]), qml.PauliRot(2, "Z", wires=[1])], ], [ qml.Z(0) + qml.Z(1), [qml.PauliRot(2, "Z", wires=[0]), qml.PauliRot(2, "Z", wires=[1])], ], [ qaoa.maxcut(Graph([(0, 1), (1, 2), (2, 0)]))[0], [ qml.PauliRot(1.0, "ZZ", wires=[0, 1]), qml.PauliRot(1.0, "ZZ", wires=[0, 2]), qml.PauliRot(1.0, "ZZ", wires=[1, 2]), ], ], ] class TestLayers: """Tests that the cost and mixer layers are being constructed properly""" def test_mixer_layer_errors(self): """Tests that the mixer layer is throwing the correct errors""" hamiltonian = [[1, 1], [1, 1]] with pytest.raises( ValueError, match=r"hamiltonian must be a linear combination of pauli words" ): qaoa.mixer_layer(0.1, hamiltonian) def test_cost_layer_errors(self): """Tests that the cost layer is throwing the correct errors""" hamiltonian = [[1, 1], [1, 1]] with pytest.raises( ValueError, match=r"hamiltonian must be a linear combination of pauli words" ): qaoa.cost_layer(0.1, hamiltonian) hamiltonian = qml.Hamiltonian([1, 1], [qml.PauliZ(0), qml.PauliX(1)]) with pytest.raises( ValueError, match=r"hamiltonian must be written only in terms of PauliZ and Identity gates", ): qaoa.cost_layer(0.1, hamiltonian) mixer_layer_test_cases = make_mixer_layer_test_cases() @pytest.mark.parametrize(("mixer", "gates"), mixer_layer_test_cases) def test_mixer_layer_output(self, mixer, gates): """Tests that the gates of the mixer layer are correct""" alpha = 1 with qml.tape.OperationRecorder() as rec: qaoa.mixer_layer(alpha, mixer) rec = rec.expand() for i, j in zip(rec.operations, gates): prep = [i.name, i.parameters, i.wires] target = [j.name, j.parameters, j.wires] assert prep == target with qml.operation.disable_new_opmath_cm(): mixer_layer_test_cases_legacy = make_mixer_layer_test_cases() @pytest.mark.usefixtures("use_legacy_opmath") @pytest.mark.parametrize(("mixer", "gates"), mixer_layer_test_cases_legacy) def test_mixer_layer_output_legacy_opmath(self, mixer, gates): """Tests that the gates of the mixer layer are correct""" alpha = 1 with qml.tape.OperationRecorder() as rec: qaoa.mixer_layer(alpha, mixer) rec = rec.expand() for i, j in zip(rec.operations, gates): prep = [i.name, i.parameters, i.wires] target = [j.name, j.parameters, j.wires] assert prep == target cost_layer_test_cases = make_cost_layer_test_cases() @pytest.mark.parametrize( ("cost", "gates"), cost_layer_test_cases, ) def test_cost_layer_output(self, cost, gates): """Tests that the gates of the cost layer is correct""" gamma = 1 with qml.queuing.AnnotatedQueue() as q: out = qaoa.cost_layer(gamma, cost) expected = qml.ApproxTimeEvolution(cost, gamma, 1) qml.assert_equal(out, expected) assert q.queue[0] is out assert len(q) == 1 decomp = out.decomposition() for i, j in zip(decomp, gates): qml.assert_equal(i, j) with qml.operation.disable_new_opmath_cm(): cost_layer_test_cases_legacy = make_cost_layer_test_cases() @pytest.mark.usefixtures("use_legacy_opmath") @pytest.mark.parametrize(("cost", "gates"), cost_layer_test_cases_legacy) def test_cost_layer_output_legacy_opmath(self, cost, gates): """Tests that the gates of the cost layer is correct""" gamma = 1 with qml.tape.OperationRecorder() as rec: cost = qml.operation.convert_to_legacy_H(cost) qaoa.cost_layer(gamma, cost) rec = rec.expand() for i, j in zip(rec.operations, gates): prep = [i.name, i.parameters, i.wires] target = [j.name, j.parameters, j.wires] assert prep == target class TestIntegration: """Test integration of the QAOA module with PennyLane""" @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_module_example(self, tol): """Test the example in the QAOA module docstring""" # Defines the wires and the graph on which MaxCut is being performed wires = range(3) graph = Graph([(0, 1), (1, 2), (2, 0)]) # Defines the QAOA cost and mixer Hamiltonians cost_h, mixer_h = qaoa.maxcut(graph) # Defines a layer of the QAOA ansatz from the cost and mixer Hamiltonians def qaoa_layer(gamma, alpha): qaoa.cost_layer(gamma, cost_h) qaoa.mixer_layer(alpha, mixer_h) # Repeatedly applies layers of the QAOA ansatz # pylint: disable=unused-argument def circuit(params, **kwargs): for w in wires: qml.Hadamard(wires=w) qml.layer(qaoa_layer, 2, params[0], params[1]) # Defines the device and the QAOA cost function dev = qml.device("default.qubit", wires=len(wires)) @qml.qnode(dev) def cost_function(params): circuit(params) return qml.expval(cost_h) res = cost_function([[1, 1], [1, 1]]) expected = -1.8260274380964299 assert np.allclose(res, expected, atol=tol, rtol=0) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_module_example_rx(self, tol): """Test the example in the QAOA module docstring""" # Defines the wires and the graph on which MaxCut is being performed wires = range(3) graph = rx.PyGraph() graph.add_nodes_from([0, 1, 2]) graph.add_edges_from([(0, 1, ""), (1, 2, ""), (2, 0, "")]) # Defines the QAOA cost and mixer Hamiltonians cost_h, mixer_h = qaoa.maxcut(graph) # Defines a layer of the QAOA ansatz from the cost and mixer Hamiltonians def qaoa_layer(gamma, alpha): qaoa.cost_layer(gamma, cost_h) qaoa.mixer_layer(alpha, mixer_h) # Repeatedly applies layers of the QAOA ansatz # pylint: disable=unused-argument def circuit(params, **kwargs): for w in wires: qml.Hadamard(wires=w) qml.layer(qaoa_layer, 2, params[0], params[1]) # Defines the device and the QAOA cost function dev = qml.device("default.qubit", wires=len(wires)) @qml.qnode(dev) def cost_function(params): circuit(params) return qml.expval(cost_h) res = cost_function([[1, 1], [1, 1]]) expected = -1.8260274380964299 assert np.allclose(res, expected, atol=tol, rtol=0) # pylint: disable=too-many-public-methods class TestCycles: """Tests that ``cycle`` module functions are behaving correctly""" @pytest.mark.parametrize("g", [nx.lollipop_graph(4, 1), lollipop_graph_rx(4, 1)]) def test_edges_to_wires(self, g): """Test that edges_to_wires returns the correct mapping""" r = edges_to_wires(g) assert r == {(0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 2): 3, (1, 3): 4, (2, 3): 5, (3, 4): 6} def test_edges_to_wires_error(self): """Test that edges_to_wires raises ValueError""" g = [1, 1, 1, 1] with pytest.raises( ValueError, match=r"Input graph must be a nx.Graph or rx.PyGraph or rx.PyDiGraph" ): edges_to_wires(g) def test_edges_to_wires_rx(self): """Test that edges_to_wires returns the correct mapping""" g = rx.generators.directed_mesh_graph(4, [0, 1, 2, 3]) r = edges_to_wires(g) assert r == { (0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 0): 3, (1, 2): 4, (1, 3): 5, (2, 0): 6, (2, 1): 7, (2, 3): 8, (3, 0): 9, (3, 1): 10, (3, 2): 11, } @pytest.mark.parametrize("g", [nx.lollipop_graph(4, 1), lollipop_graph_rx(4, 1)]) def test_wires_to_edges(self, g): """Test that wires_to_edges returns the correct mapping""" r = wires_to_edges(g) assert r == {0: (0, 1), 1: (0, 2), 2: (0, 3), 3: (1, 2), 4: (1, 3), 5: (2, 3), 6: (3, 4)} def test_wires_to_edges_error(self): """Test that wires_to_edges raises ValueError""" g = [1, 1, 1, 1] with pytest.raises( ValueError, match=r"Input graph must be a nx.Graph or rx.PyGraph or rx.PyDiGraph" ): wires_to_edges(g) def test_wires_to_edges_rx(self): """Test that wires_to_edges returns the correct mapping""" g = rx.generators.directed_mesh_graph(4, [0, 1, 2, 3]) r = wires_to_edges(g) assert r == { 0: (0, 1), 1: (0, 2), 2: (0, 3), 3: (1, 0), 4: (1, 2), 5: (1, 3), 6: (2, 0), 7: (2, 1), 8: (2, 3), 9: (3, 0), 10: (3, 1), 11: (3, 2), } @pytest.mark.parametrize( "g", [nx.complete_graph(4).to_directed(), rx.generators.directed_mesh_graph(4, [0, 1, 2, 3])], ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_partial_cycle_mixer_complete(self, g): """Test if the _partial_cycle_mixer function returns the expected Hamiltonian for a fixed example""" edge = (0, 1) h = _partial_cycle_mixer(g, edge) ops_expected = [ qml.PauliX(0) @ qml.PauliX(1) @ qml.PauliX(7), qml.PauliY(0) @ qml.PauliY(1) @ qml.PauliX(7), qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliY(7), qml.PauliX(0) @ qml.PauliY(1) @ qml.PauliY(7), qml.PauliX(0) @ qml.PauliX(2) @ qml.PauliX(10), qml.PauliY(0) @ qml.PauliY(2) @ qml.PauliX(10), qml.PauliY(0) @ qml.PauliX(2) @ qml.PauliY(10), qml.PauliX(0) @ qml.PauliY(2) @ qml.PauliY(10), ] coeffs_expected = [0.25, 0.25, 0.25, -0.25, 0.25, 0.25, 0.25, -0.25] assert h.coeffs == coeffs_expected assert all(op.wires == op_e.wires for op, op_e in zip(h.ops, ops_expected)) assert all(op.name == op_e.name for op, op_e in zip(h.ops, ops_expected)) @pytest.mark.parametrize( "g", [nx.complete_graph(4).to_directed(), rx.generators.directed_mesh_graph(4, [0, 1, 2, 3])], ) def test_partial_cycle_mixer_incomplete(self, g): """Test if the _partial_cycle_mixer function returns the expected Hamiltonian for a fixed example""" g.remove_edge(2, 1) # remove an egde to make graph incomplete edge = (0, 1) h = _partial_cycle_mixer(g, edge) ops_expected = [ qml.PauliX(0) @ qml.PauliX(2) @ qml.PauliX(9), qml.PauliY(0) @ qml.PauliY(2) @ qml.PauliX(9), qml.PauliY(0) @ qml.PauliX(2) @ qml.PauliY(9), qml.PauliX(0) @ qml.PauliY(2) @ qml.PauliY(9), ] coeffs_expected = [0.25, 0.25, 0.25, -0.25] assert h.coeffs == coeffs_expected assert all(op.wires == op_e.wires for op, op_e in zip(h.ops, ops_expected)) assert all(op.name == op_e.name for op, op_e in zip(h.ops, ops_expected)) @pytest.mark.usefixtures("use_legacy_opmath") @pytest.mark.parametrize( "g", [nx.complete_graph(4).to_directed(), rx.generators.directed_mesh_graph(4, [0, 1, 2, 3])], ) def test_partial_cycle_mixer_incomplete_legacy_opmath(self, g): """Test if the _partial_cycle_mixer function returns the expected Hamiltonian for a fixed example""" g.remove_edge(2, 1) # remove an egde to make graph incomplete edge = (0, 1) h = _partial_cycle_mixer(g, edge) ops_expected = [ qml.PauliX(0) @ qml.PauliX(2) @ qml.PauliX(9), qml.PauliY(0) @ qml.PauliY(2) @ qml.PauliX(9), qml.PauliY(0) @ qml.PauliX(2) @ qml.PauliY(9), qml.PauliX(0) @ qml.PauliY(2) @ qml.PauliY(9), ] coeffs_expected = [0.25, 0.25, 0.25, -0.25] assert h.coeffs == coeffs_expected assert all(op.wires == op_e.wires for op, op_e in zip(h.ops, ops_expected)) assert all(op.name == op_e.name for op, op_e in zip(h.ops, ops_expected)) @pytest.mark.parametrize("g", [nx.complete_graph(4), rx.generators.mesh_graph(4, [0, 1, 2, 3])]) def test_partial_cycle_mixer_error(self, g): """Test if the _partial_cycle_mixer raises ValueError""" g.remove_edge(2, 1) # remove an egde to make graph incomplete edge = (0, 1) # Find Hamiltonian and its matrix representation with pytest.raises(ValueError, match="Input graph must be a nx.DiGraph or rx.PyDiGraph"): _partial_cycle_mixer(g, edge) @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])], ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_cycle_mixer(self, g): """Test if the cycle_mixer Hamiltonian maps valid cycles to valid cycles""" n_nodes = 3 m = wires_to_edges(g) n_wires = len(g.edge_list() if isinstance(g, rx.PyDiGraph) else g.edges) # Find Hamiltonian and its matrix representation h = cycle_mixer(g) h_matrix = np.real_if_close(matrix(h, n_wires).toarray()) # Decide which bitstrings are valid and which are invalid valid_bitstrings_indx = [] invalid_bitstrings_indx = [] for indx, bitstring in enumerate(itertools.product([0, 1], repeat=n_wires)): wires = [i for i, bit in enumerate(bitstring) if bit == 1] edges = [m[wire] for wire in wires] flows = [0 for i in range(n_nodes)] for start, end in edges: flows[start] += 1 flows[end] -= 1 # A bitstring is valid if the net flow is zero and we aren't the empty set or the set # of all edges. Note that the max out-flow constraint is not imposed, which means we can # pass through nodes more than once if sum(np.abs(flows)) == 0 and 0 < len(edges) < n_wires: valid_bitstrings_indx.append(indx) else: invalid_bitstrings_indx.append(indx) # Check that valid bitstrings map to a subset of the valid bitstrings for indx in valid_bitstrings_indx: column = h_matrix[:, indx] destination_indxs = set(np.argwhere(column != 0).flatten()) assert destination_indxs.issubset(valid_bitstrings_indx) # Check that invalid bitstrings map to a subset of the invalid bitstrings for indx in invalid_bitstrings_indx: column = h_matrix[:, indx] destination_indxs = set(np.argwhere(column != 0).flatten()) assert destination_indxs.issubset(invalid_bitstrings_indx) # Now consider a unitary generated by the Hamiltonian h_matrix_e = expm(1j * h_matrix) # We expect non-zero transitions among the set of valid bitstrings, and no transitions # outside for indx in valid_bitstrings_indx: column = h_matrix_e[:, indx] destination_indxs = np.argwhere(column != 0).flatten().tolist() assert destination_indxs == valid_bitstrings_indx # Check that invalid bitstrings transition within the set of invalid bitstrings for indx in invalid_bitstrings_indx: column = h_matrix_e[:, indx] destination_indxs = set(np.argwhere(column != 0).flatten().tolist()) assert destination_indxs.issubset(invalid_bitstrings_indx) @pytest.mark.parametrize( "g", [nx.complete_graph(3), rx.generators.mesh_graph(3, [0, 1, 2])], ) def test_cycle_mixer_error(self, g): """Test if the cycle_mixer raises ValueError""" # Find Hamiltonian and its matrix representation with pytest.raises(ValueError, match="Input graph must be a nx.DiGraph or rx.PyDiGraph"): cycle_mixer(g) @pytest.mark.parametrize("g", [nx.lollipop_graph(3, 1), lollipop_graph_rx(3, 1)]) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_matrix(self, g): """Test that the matrix function works as expected on a fixed example""" h = qml.qaoa.bit_flip_mixer(g, 0) mat = matrix(h, 4) mat_expected = np.array( [ [0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] ) assert np.allclose(mat.toarray(), mat_expected) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_matrix_rx(self): """Test that the matrix function works as expected on a fixed example""" g = rx.generators.star_graph(4, [0, 1, 2, 3]) h = qml.qaoa.bit_flip_mixer(g, 0) mat = matrix(h, 4) mat_expected = np.array( [ [0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] ) assert np.allclose(mat.toarray(), mat_expected) @pytest.mark.parametrize( "g", [nx.lollipop_graph(4, 1).to_directed(), lollipop_graph_rx(4, 1, to_directed=True)] ) def test_edges_to_wires_directed(self, g): """Test that edges_to_wires returns the correct mapping on a directed graph""" r = edges_to_wires(g) assert r == { (0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 0): 3, (1, 2): 4, (1, 3): 5, (2, 0): 6, (2, 1): 7, (2, 3): 8, (3, 0): 9, (3, 1): 10, (3, 2): 11, (3, 4): 12, (4, 3): 13, } @pytest.mark.parametrize( "g", [nx.lollipop_graph(4, 1).to_directed(), lollipop_graph_rx(4, 1, to_directed=True)] ) def test_wires_to_edges_directed(self, g): """Test that wires_to_edges returns the correct mapping on a directed graph""" r = wires_to_edges(g) assert r == { 0: (0, 1), 1: (0, 2), 2: (0, 3), 3: (1, 0), 4: (1, 2), 5: (1, 3), 6: (2, 0), 7: (2, 1), 8: (2, 3), 9: (3, 0), 10: (3, 1), 11: (3, 2), 12: (3, 4), 13: (4, 3), } @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_loss_hamiltonian_complete(self, g): """Test if the loss_hamiltonian function returns the expected result on a manually-calculated example of a 3-node complete digraph""" if isinstance(g, rx.PyDiGraph): edge_weight_data = {edge: (i + 1) * 0.5 for i, edge in enumerate(sorted(g.edge_list()))} for k, v in edge_weight_data.items(): g.update_edge(k[0], k[1], {"weight": v}) else: edge_weight_data = {edge: (i + 1) * 0.5 for i, edge in enumerate(g.edges)} for k, v in edge_weight_data.items(): g[k[0]][k[1]]["weight"] = v h = loss_hamiltonian(g) expected_ops = [ qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2), qml.PauliZ(3), qml.PauliZ(4), qml.PauliZ(5), ] expected_coeffs = [np.log(0.5), np.log(1), np.log(1.5), np.log(2), np.log(2.5), np.log(3)] assert np.allclose(expected_coeffs, h.coeffs) assert all(op.wires == exp.wires for op, exp in zip(h.ops, expected_ops)) assert all(type(op) is type(exp) for op, exp in zip(h.ops, expected_ops)) def test_loss_hamiltonian_error(self): """Test if the loss_hamiltonian function raises ValueError""" with pytest.raises( ValueError, match=r"Input graph must be a nx.Graph or rx.PyGraph or rx.PyDiGraph" ): loss_hamiltonian([(0, 1), (1, 2), (0, 2)]) @pytest.mark.parametrize( "g", [nx.lollipop_graph(4, 1).to_directed(), lollipop_graph_rx(4, 1, to_directed=True)] ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_loss_hamiltonian_incomplete(self, g): """Test if the loss_hamiltonian function returns the expected result on a manually-calculated example of a 4-node incomplete digraph""" if isinstance(g, rx.PyDiGraph): edge_weight_data = {edge: (i + 1) * 0.5 for i, edge in enumerate(sorted(g.edge_list()))} for k, v in edge_weight_data.items(): g.update_edge(k[0], k[1], {"weight": v}) else: edge_weight_data = {edge: (i + 1) * 0.5 for i, edge in enumerate(g.edges)} for k, v in edge_weight_data.items(): g[k[0]][k[1]]["weight"] = v h = loss_hamiltonian(g) expected_ops = [ qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(2), qml.PauliZ(3), qml.PauliZ(4), qml.PauliZ(5), qml.PauliZ(6), qml.PauliZ(7), qml.PauliZ(8), qml.PauliZ(9), qml.PauliZ(10), qml.PauliZ(11), qml.PauliZ(12), qml.PauliZ(13), ] expected_coeffs = [ np.log(0.5), np.log(1), np.log(1.5), np.log(2), np.log(2.5), np.log(3), np.log(3.5), np.log(4), np.log(4.5), np.log(5), np.log(5.5), np.log(6), np.log(6.5), np.log(7), ] assert np.allclose(expected_coeffs, h.coeffs) assert all(op.wires == exp.wires for op, exp in zip(h.ops, expected_ops)) assert all(type(op) is type(exp) for op, exp in zip(h.ops, expected_ops)) @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) def test_self_loop_raises_error(self, g): """Test graphs with self loop raises ValueError""" digraph_complete = nx.complete_graph(3).to_directed() complete_edge_weight_data = { edge: (i + 1) * 0.5 for i, edge in enumerate(digraph_complete.edges) } for _k, _v in complete_edge_weight_data.items(): digraph_complete[_k[0]][_k[1]]["weight"] = _v digraph_complete_rx = rx.generators.directed_mesh_graph(3, [0, 1, 2]) complete_edge_weight_data = { edge: (i + 1) * 0.5 for i, edge in enumerate(sorted(digraph_complete_rx.edge_list())) } if isinstance(g, rx.PyDiGraph): edge_weight_data = {edge: (i + 1) * 0.5 for i, edge in enumerate(g.edges())} for k, v in complete_edge_weight_data.items(): g.update_edge(k[0], k[1], {"weight": v}) g.add_edge(1, 1, "") # add self loop else: edge_weight_data = {edge: (i + 1) * 0.5 for i, edge in enumerate(g.edges)} for k, v in edge_weight_data.items(): g[k[0]][k[1]]["weight"] = v g.add_edge(1, 1) # add self loop with pytest.raises(ValueError, match="Graph contains self-loops"): loss_hamiltonian(g) def test_missing_edge_weight_data_raises_error(self): """Test graphs with no edge weight data raises `KeyError`""" g = nx.complete_graph(3).to_directed() with pytest.raises(KeyError, match="does not contain weight data"): loss_hamiltonian(g) def test_missing_edge_weight_data_without_weights(self): """Test graphs with no edge weight data raises `KeyError`""" g = rx.generators.mesh_graph(3, [0, 1, 2]) with pytest.raises(TypeError, match="does not contain weight data"): loss_hamiltonian(g) @pytest.mark.usefixtures("use_legacy_and_new_opmath") def test_square_hamiltonian_terms(self): """Test if the _square_hamiltonian_terms function returns the expected result on a fixed example""" coeffs = [1, -1, -1, 1] ops = [qml.Identity(0), qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(3)] expected_coeffs = [ 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, ] expected_ops = [ qml.Identity(0), qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(3), qml.PauliZ(0), qml.Identity(0), qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(3), qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(1), qml.Identity(0), qml.PauliZ(1) @ qml.PauliZ(3), qml.PauliZ(3), qml.PauliZ(0) @ qml.PauliZ(3), qml.PauliZ(1) @ qml.PauliZ(3), qml.Identity(0), ] squared_coeffs, squared_ops = _square_hamiltonian_terms(coeffs, ops) assert squared_coeffs == expected_coeffs assert all( op1.name == op2.name and op1.wires == op2.wires for op1, op2 in zip(expected_ops, squared_ops) ) @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) def test_inner_out_flow_constraint_hamiltonian(self, g): """Test if the _inner_out_flow_constraint_hamiltonian function returns the expected result on a manually-calculated example of a 3-node complete digraph relative to the 0 node""" h = _inner_out_flow_constraint_hamiltonian(g, 0) expected_ops = [ qml.Identity(0), qml.PauliZ(1) @ qml.PauliZ(0), qml.PauliZ(0), qml.PauliZ(1), ] expected_coeffs = [2, 2, -2, -2] expected_hamiltonian = qml.Hamiltonian(expected_coeffs, expected_ops) assert h.compare(expected_hamiltonian) @pytest.mark.usefixtures("use_legacy_opmath") @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) def test_inner_out_flow_constraint_hamiltonian_legacy_opmath(self, g): """Test if the _inner_out_flow_constraint_hamiltonian function returns the expected result on a manually-calculated example of a 3-node complete digraph relative to the 0 node""" h = _inner_out_flow_constraint_hamiltonian(g, 0) expected_ops = [ qml.Identity(0), qml.PauliZ(1) @ qml.PauliZ(0), qml.PauliZ(0), qml.PauliZ(1), ] expected_coeffs = [2, 2, -2, -2] expected_hamiltonian = qml.Hamiltonian(expected_coeffs, expected_ops) assert h.compare(expected_hamiltonian) @pytest.mark.parametrize("g", [nx.complete_graph(3), rx.generators.mesh_graph(3, [0, 1, 2])]) def test_inner_out_flow_constraint_hamiltonian_error(self, g): """Test if the _inner_out_flow_constraint_hamiltonian function raises ValueError""" with pytest.raises(ValueError, match=r"Input graph must be a nx.DiGraph or rx.PyDiGraph"): _inner_out_flow_constraint_hamiltonian(g, 0) @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) def test_inner_net_flow_constraint_hamiltonian(self, g): """Test if the _inner_net_flow_constraint_hamiltonian function returns the expected result on a manually-calculated example of a 3-node complete digraph relative to the 0 node""" h = _inner_net_flow_constraint_hamiltonian(g, 0) expected_ops = [ qml.Identity(0), qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliZ(0) @ qml.PauliZ(4), qml.PauliZ(1) @ qml.PauliZ(2), qml.PauliZ(1) @ qml.PauliZ(4), qml.PauliZ(2) @ qml.PauliZ(4), ] expected_coeffs = [4, 2, -2, -2, -2, -2, 2] _, ops = h.terms() non_zero_terms = [(coeff, op) for coeff, op in zip(h.coeffs, ops) if coeff != 0] coeffs = [term[0] for term in non_zero_terms] assert qml.math.allclose(coeffs, expected_coeffs) non_zero_ops = [term[1] for term in non_zero_terms] for op, expected_op in zip(non_zero_ops, expected_ops): assert op.pauli_rep == expected_op.pauli_rep @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) @pytest.mark.usefixtures("use_legacy_opmath") def test_inner_net_flow_constraint_hamiltonian_legacy_opmath(self, g): """Test if the _inner_net_flow_constraint_hamiltonian function returns the expected result on a manually-calculated example of a 3-node complete digraph relative to the 0 node""" h = _inner_net_flow_constraint_hamiltonian(g, 0) expected_ops = [ qml.Identity(0), qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(2), qml.PauliZ(0) @ qml.PauliZ(4), qml.PauliZ(1) @ qml.PauliZ(2), qml.PauliZ(1) @ qml.PauliZ(4), qml.PauliZ(2) @ qml.PauliZ(4), ] expected_coeffs = [4, 2, -2, -2, -2, -2, 2] assert np.allclose(expected_coeffs, h.coeffs) for i, expected_op in enumerate(expected_ops): assert str(h.ops[i]) == str(expected_op) assert all(op.wires == exp.wires for op, exp in zip(h.ops, expected_ops)) @pytest.mark.parametrize("g", [nx.complete_graph(3), rx.generators.mesh_graph(3, [0, 1, 2])]) def test_inner_net_flow_constraint_hamiltonian_error(self, g): """Test if the _inner_net_flow_constraint_hamiltonian function returns raises ValueError""" with pytest.raises(ValueError, match=r"Input graph must be a nx.DiGraph or rx.PyDiGraph"): _inner_net_flow_constraint_hamiltonian(g, 0) @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) @pytest.mark.usefixtures("use_new_opmath") def test_inner_out_flow_constraint_hamiltonian_non_complete(self, g): """Test if the _inner_out_flow_constraint_hamiltonian function returns the expected result on a manually-calculated example of a 3-node complete digraph relative to the 0 node, with the (0, 1) edge removed""" g.remove_edge(0, 1) h = _inner_out_flow_constraint_hamiltonian(g, 0) h = h.simplify() expected_ops = [qml.Identity(0), qml.PauliZ(wires=[0])] expected_coeffs = [0, 0] coeffs, ops = h.terms() assert qml.math.allclose(expected_coeffs, coeffs) for op, expected_op in zip(ops, expected_ops): assert op.pauli_rep == expected_op.pauli_rep @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) @pytest.mark.usefixtures("use_legacy_opmath") def test_inner_out_flow_constraint_hamiltonian_non_complete_legacy_opmath(self, g): """Test if the _inner_out_flow_constraint_hamiltonian function returns the expected result on a manually-calculated example of a 3-node complete digraph relative to the 0 node, with the (0, 1) edge removed""" g.remove_edge(0, 1) h = _inner_out_flow_constraint_hamiltonian(g, 0) expected_ops = [qml.PauliZ(wires=[0])] expected_coeffs = [0] assert np.allclose(expected_coeffs, h.coeffs) for i, expected_op in enumerate(expected_ops): assert str(h.ops[i]) == str(expected_op) assert all(op.wires == exp.wires for op, exp in zip(h.ops, expected_ops)) @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) def test_inner_net_flow_constraint_hamiltonian_non_complete(self, g): """Test if the _inner_net_flow_constraint_hamiltonian function returns the expected result on a manually-calculated example of a 3-node complete digraph relative to the 0 node, with the (1, 0) edge removed""" g.remove_edge(1, 0) h = _inner_net_flow_constraint_hamiltonian(g, 0) h = h.simplify() expected_ops = [ qml.Identity(0), qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(3), qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(3), qml.PauliZ(1) @ qml.PauliZ(3), ] expected_coeffs = [4, -2, -2, 2, 2, -2, -2] coeffs, ops = h.terms() assert qml.math.allclose(coeffs, expected_coeffs) for op, expected_op in zip(ops, expected_ops): assert op.pauli_rep == expected_op.pauli_rep @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) @pytest.mark.usefixtures("use_legacy_opmath") def test_inner_net_flow_constraint_hamiltonian_non_complete_legacy_opmath(self, g): """Test if the _inner_net_flow_constraint_hamiltonian function returns the expected result on a manually-calculated example of a 3-node complete digraph relative to the 0 node, with the (1, 0) edge removed""" g.remove_edge(1, 0) h = _inner_net_flow_constraint_hamiltonian(g, 0) expected_ops = [ qml.Identity(0), qml.PauliZ(0), qml.PauliZ(1), qml.PauliZ(3), qml.PauliZ(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(3), qml.PauliZ(1) @ qml.PauliZ(3), ] expected_coeffs = [4, -2, -2, 2, 2, -2, -2] assert np.allclose(expected_coeffs, h.coeffs) for i, expected_op in enumerate(expected_ops): assert str(h.ops[i]) == str(expected_op) assert all(op.wires == exp.wires for op, exp in zip(h.ops, expected_ops)) def test_out_flow_constraint_raises(self): """Test the out-flow constraint function may raise an error.""" # pylint: disable=super-init-not-called class OtherDirectedGraph(nx.DiGraph): def __init__(self, *args, **kwargs): pass g = OtherDirectedGraph() with pytest.raises(ValueError, match="must be directed"): out_flow_constraint(g) @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) def test_out_flow_constraint(self, g): """Test the out-flow constraint Hamiltonian is minimised by states that correspond to subgraphs that only ever have 0 or 1 edge leaving each node """ h = out_flow_constraint(g) m = wires_to_edges(g) wires = len(g.edge_list() if isinstance(g, rx.PyDiGraph) else g.edges) # We use PL to find the energies corresponding to each possible bitstring dev = qml.device("default.qubit", wires=wires) # pylint: disable=unused-argument def states(basis_state, **kwargs): qml.BasisState(basis_state, wires=range(wires)) @qml.qnode(dev) def cost(params): states(params) return qml.expval(h) # Calculate the set of all bitstrings bitstrings = itertools.product([0, 1], repeat=wires) # Calculate the corresponding energies energies_bitstrings = ((cost(np.array(bitstring)), bitstring) for bitstring in bitstrings) for energy, bs in energies_bitstrings: # convert binary string to wires then wires to edges wires_ = tuple(i for i, s in enumerate(bs) if s != 0) edges = tuple(m[w] for w in wires_) # find the number of edges leaving each node if isinstance(g, rx.PyDiGraph): num_edges_leaving_node = {node: 0 for node in g.nodes()} else: num_edges_leaving_node = {node: 0 for node in g.nodes} for e in edges: num_edges_leaving_node[e[0]] += 1 # check that if the max number of edges is <=1 it corresponds to a state that minimizes # the out_flow_constraint Hamiltonian if max(num_edges_leaving_node.values()) > 1: assert energy > min(energies_bitstrings)[0] elif max(num_edges_leaving_node.values()) <= 1: assert energy == min(energies_bitstrings)[0] @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) @pytest.mark.usefixtures("use_legacy_opmath") def test_out_flow_constraint_legacy_opmath(self, g): """Test the out-flow constraint Hamiltonian is minimised by states that correspond to subgraphs that only ever have 0 or 1 edge leaving each node """ h = out_flow_constraint(g) m = wires_to_edges(g) wires = len(g.edge_list() if isinstance(g, rx.PyDiGraph) else g.edges) # We use PL to find the energies corresponding to each possible bitstring dev = qml.device("default.qubit", wires=wires) # pylint: disable=unused-argument def states(basis_state, **kwargs): qml.BasisState(basis_state, wires=range(wires)) @qml.qnode(dev) def cost(params): states(params) return qml.expval(h) # Calculate the set of all bitstrings bitstrings = itertools.product([0, 1], repeat=wires) # Calculate the corresponding energies energies_bitstrings = ((cost(np.array(bitstring)), bitstring) for bitstring in bitstrings) for energy, bs in energies_bitstrings: # convert binary string to wires then wires to edges wires_ = tuple(i for i, s in enumerate(bs) if s != 0) edges = tuple(m[w] for w in wires_) # find the number of edges leaving each node if isinstance(g, rx.PyDiGraph): num_edges_leaving_node = {node: 0 for node in g.nodes()} else: num_edges_leaving_node = {node: 0 for node in g.nodes} for e in edges: num_edges_leaving_node[e[0]] += 1 # check that if the max number of edges is <=1 it corresponds to a state that minimizes # the out_flow_constraint Hamiltonian if max(num_edges_leaving_node.values()) > 1: assert energy > min(energies_bitstrings)[0] elif max(num_edges_leaving_node.values()) <= 1: assert energy == min(energies_bitstrings)[0] @pytest.mark.parametrize("g", [nx.complete_graph(3), rx.generators.mesh_graph(3, [0, 1, 2])]) def test_out_flow_constraint_undirected_raises_error(self, g): """Test `out_flow_constraint` raises ValueError if input graph is not directed""" with pytest.raises(ValueError): out_flow_constraint(g) @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) def test_net_flow_constraint(self, g): """Test if the net_flow_constraint Hamiltonian is minimized by states that correspond to a collection of edges with zero flow""" h = net_flow_constraint(g) m = wires_to_edges(g) wires = len(g.edge_list() if isinstance(g, rx.PyDiGraph) else g.edges) # We use PL to find the energies corresponding to each possible bitstring dev = qml.device("default.qubit", wires=wires) @qml.qnode(dev) def cost(basis_state): qml.BasisState(basis_state, wires=range(wires)) return qml.expval(h) # Calculate the set of all bitstrings states = itertools.product([0, 1], repeat=wires) # Calculate the corresponding energies energies_states = ((cost(np.array(state)), state) for state in states) # We now have the energies of each bitstring/state. We also want to calculate the net flow of # the corresponding edges for energy, state in energies_states: # This part converts from a binary string of wires selected to graph edges wires_ = tuple(i for i, s in enumerate(state) if s != 0) edges = tuple(m[w] for w in wires_) # Calculates the number of edges entering and leaving a given node if isinstance(g, rx.PyDiGraph): in_flows = np.zeros(len(g.nodes())) out_flows = np.zeros(len(g.nodes())) else: in_flows = np.zeros(len(g.nodes)) out_flows = np.zeros(len(g.nodes)) for e in edges: in_flows[e[0]] += 1 out_flows[e[1]] += 1 net_flow = np.sum(np.abs(in_flows - out_flows)) # The test requires that a set of edges with zero net flow must have a corresponding # bitstring that minimized the energy of the Hamiltonian if net_flow == 0: assert energy == min(energies_states)[0] else: assert energy > min(energies_states)[0] @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) @pytest.mark.usefixtures("use_legacy_opmath") def test_net_flow_constraint_legacy_opmath(self, g): """Test if the net_flow_constraint Hamiltonian is minimized by states that correspond to a collection of edges with zero flow""" h = net_flow_constraint(g) m = wires_to_edges(g) wires = len(g.edge_list() if isinstance(g, rx.PyDiGraph) else g.edges) # We use PL to find the energies corresponding to each possible bitstring dev = qml.device("default.qubit", wires=wires) @qml.qnode(dev) def cost(basis_state): qml.BasisState(basis_state, wires=range(wires)) return qml.expval(h) # Calculate the set of all bitstrings states = itertools.product([0, 1], repeat=wires) # Calculate the corresponding energies energies_states = ((cost(np.array(state)), state) for state in states) # We now have the energies of each bitstring/state. We also want to calculate the net flow of # the corresponding edges for energy, state in energies_states: # This part converts from a binary string of wires selected to graph edges wires_ = tuple(i for i, s in enumerate(state) if s != 0) edges = tuple(m[w] for w in wires_) # Calculates the number of edges entering and leaving a given node if isinstance(g, rx.PyDiGraph): in_flows = np.zeros(len(g.nodes())) out_flows = np.zeros(len(g.nodes())) else: in_flows = np.zeros(len(g.nodes)) out_flows = np.zeros(len(g.nodes)) for e in edges: in_flows[e[0]] += 1 out_flows[e[1]] += 1 net_flow = np.sum(np.abs(in_flows - out_flows)) # The test requires that a set of edges with zero net flow must have a corresponding # bitstring that minimized the energy of the Hamiltonian if net_flow == 0: assert energy == min(energies_states)[0] else: assert energy > min(energies_states)[0] @pytest.mark.parametrize("g", [nx.complete_graph(3), rx.generators.mesh_graph(3, [0, 1, 2])]) def test_net_flow_constraint_wrong_graph_type_raises_error(self, g): """Test `net_flow_constraint` raises ValueError if input graph is not the correct graph type""" with pytest.raises(ValueError, match="Input graph must be"): net_flow_constraint(g) def test_net_flow_constraint_undirected_raises_error(self): """Test the net-flow constraint function may raise an error.""" # pylint: disable=super-init-not-called class OtherDirectedGraph(nx.DiGraph): def __init__(self, *args, **kwargs): pass g = OtherDirectedGraph() with pytest.raises(ValueError, match="must be directed"): net_flow_constraint(g) @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) def test_net_flow_and_out_flow_constraint(self, g): """Test the combined net-flow and out-flow constraint Hamiltonian is minimised by states that correspond to subgraphs that qualify as simple_cycles """ g = nx.complete_graph(3).to_directed() h = net_flow_constraint(g) + out_flow_constraint(g) m = wires_to_edges(g) wires = len(g.edge_list() if isinstance(g, rx.PyDiGraph) else g.edges) # Find the energies corresponding to each possible bitstring dev = qml.device("default.qubit", wires=wires) # pylint: disable=unused-argument def states(basis_state, **kwargs): qml.BasisState(basis_state, wires=range(wires)) @qml.qnode(dev) def cost(params): states(params) return qml.expval(h) # Calculate the set of all bitstrings bitstrings = itertools.product([0, 1], repeat=wires) # Calculate the corresponding energies energies_bitstrings = ((cost(np.array(bitstring)), bitstring) for bitstring in bitstrings) def find_simple_cycle(list_of_edges): """Returns True if list_of_edges contains a permutation corresponding to a simple cycle""" permutations = list(itertools.permutations(list_of_edges)) for edges in permutations: if edges[0][0] != edges[-1][-1]: # check first node is equal to last node continue all_nodes = [] for edge in edges: for n in edge: all_nodes.append(n) inner_nodes = all_nodes[ 1:-1 ] # find all nodes in all edges excluding the first and last nodes nodes_out = [ inner_nodes[i] for i in range(len(inner_nodes)) if i % 2 == 0 ] # find the nodes each edge is leaving node_in = [ inner_nodes[i] for i in range(len(inner_nodes)) if i % 2 != 0 ] # find the nodes each edge is entering if nodes_out == node_in and ( len([all_nodes[0]] + nodes_out) == len(set([all_nodes[0]] + nodes_out)) ): # check that each edge connect to the next via a common node and that no node is crossed more than once return True return False for energy, bs in energies_bitstrings: # convert binary string to wires then wires to edges wires_ = tuple(i for i, s in enumerate(bs) if s != 0) edges = tuple(m[w] for w in wires_) if len(edges) > 0 and find_simple_cycle(edges): assert energy == min(energies_bitstrings)[0] elif len(edges) > 0 and not find_simple_cycle(edges): assert energy > min(energies_bitstrings)[0] @pytest.mark.parametrize( "g", [nx.complete_graph(3).to_directed(), rx.generators.directed_mesh_graph(3, [0, 1, 2])] ) @pytest.mark.usefixtures("use_legacy_opmath") def test_net_flow_and_out_flow_constraint_legacy_opmath(self, g): """Test the combined net-flow and out-flow constraint Hamiltonian is minimised by states that correspond to subgraphs that qualify as simple_cycles """ g = nx.complete_graph(3).to_directed() h = net_flow_constraint(g) + out_flow_constraint(g) m = wires_to_edges(g) wires = len(g.edge_list() if isinstance(g, rx.PyDiGraph) else g.edges) # Find the energies corresponding to each possible bitstring dev = qml.device("default.qubit", wires=wires) # pylint: disable=unused-argument def states(basis_state, **kwargs): qml.BasisState(basis_state, wires=range(wires)) @qml.qnode(dev) def cost(params): states(params) return qml.expval(h) # Calculate the set of all bitstrings bitstrings = itertools.product([0, 1], repeat=wires) # Calculate the corresponding energies energies_bitstrings = ((cost(np.array(bitstring)), bitstring) for bitstring in bitstrings) def find_simple_cycle(list_of_edges): """Returns True if list_of_edges contains a permutation corresponding to a simple cycle""" permutations = list(itertools.permutations(list_of_edges)) for edges in permutations: if edges[0][0] != edges[-1][-1]: # check first node is equal to last node continue all_nodes = [] for edge in edges: for n in edge: all_nodes.append(n) inner_nodes = all_nodes[ 1:-1 ] # find all nodes in all edges excluding the first and last nodes nodes_out = [ inner_nodes[i] for i in range(len(inner_nodes)) if i % 2 == 0 ] # find the nodes each edge is leaving node_in = [ inner_nodes[i] for i in range(len(inner_nodes)) if i % 2 != 0 ] # find the nodes each edge is entering if nodes_out == node_in and ( len([all_nodes[0]] + nodes_out) == len(set([all_nodes[0]] + nodes_out)) ): # check that each edge connect to the next via a common node and that no node is crossed more than once return True return False for energy, bs in energies_bitstrings: # convert binary string to wires then wires to edges wires_ = tuple(i for i, s in enumerate(bs) if s != 0) edges = tuple(m[w] for w in wires_) if len(edges) > 0 and find_simple_cycle(edges): assert energy == min(energies_bitstrings)[0] elif len(edges) > 0 and not find_simple_cycle(edges): assert energy > min(energies_bitstrings)[0]
pennylane/tests/test_qaoa.py/0
{ "file_path": "pennylane/tests/test_qaoa.py", "repo_id": "pennylane", "token_count": 51041 }
97
# Copyright 2023 Xanadu Quantum Technologies Inc. # 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. """Unit and integration tests for the transform dispatcher.""" import inspect from collections.abc import Callable, Sequence from functools import partial import pytest import pennylane as qml from pennylane.tape import QuantumScript, QuantumScriptBatch, QuantumTape from pennylane.transforms.core import TransformContainer, TransformError, transform from pennylane.typing import PostprocessingFn, TensorLike dev = qml.device("default.qubit", wires=2) with QuantumTape() as tape_circuit: qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.PauliX(wires=0) qml.RZ(0.42, wires=1) qml.expval(qml.PauliZ(wires=0)) def qfunc_circuit(a: qml.typing.TensorLike): """Qfunc circuit/""" qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.PauliX(wires=0) qml.RZ(a, wires=1) return qml.expval(qml.PauliZ(wires=0)) ########################################## # Non-valid transforms non_callable = tape_circuit def no_tape_transform( circuit: QuantumScript, index: int ) -> tuple[QuantumScriptBatch, PostprocessingFn]: """Transform without tape.""" circuit = circuit.copy() circuit._ops.pop(index) # pylint:disable=protected-access return [circuit], lambda x: x def no_quantum_tape_transform( tape: qml.operation.Operator, index: int ) -> tuple[QuantumScriptBatch, PostprocessingFn]: """Transform with wrong hinting.""" tape = tape.copy() tape._ops.pop(index) # pylint:disable=protected-access return [tape], lambda x: x def no_processing_fn_transform(tape: QuantumScript) -> QuantumScriptBatch: """Transform without processing fn.""" tape_copy = tape.copy() return [tape, tape_copy] def no_tape_sequence_transform(tape: QuantumScript) -> tuple[QuantumScript, PostprocessingFn]: """Transform wihtout Sequence return.""" return tape, lambda x: x def no_callable_return(tape: QuantumScript) -> tuple[QuantumScriptBatch, QuantumScript]: """Transform without callable return.""" return list(tape), tape non_valid_transforms = [ non_callable, no_processing_fn_transform, no_tape_sequence_transform, no_tape_transform, no_quantum_tape_transform, no_callable_return, ] ########################################## # Valid transforms def first_valid_transform( tape: QuantumScript, index: int ) -> tuple[QuantumScriptBatch, PostprocessingFn]: """A valid transform.""" tape = tape.copy() tape._ops.pop(index) # pylint:disable=protected-access _ = (qml.PauliX(0), qml.S(0)) return [tape], lambda x: x def second_valid_transform( tape: QuantumScript, index: int ) -> tuple[QuantumScriptBatch, PostprocessingFn]: """A valid trasnform.""" tape1 = tape.copy() tape2 = tape.copy() tape._ops.pop(index) # pylint:disable=protected-access def fn(results): return qml.math.sum(results) return [tape1, tape2], fn valid_transforms = [first_valid_transform, second_valid_transform] ########################################## # Valid expand transform def expand_transform( tape: QuantumScript, index: int ) -> tuple[QuantumScriptBatch, PostprocessingFn]: """Multiple args expand fn.""" tape._ops.pop(index) # pylint:disable=protected-access return [tape], lambda x: x # Non-valid expand transform def non_valid_expand_transform(tape: QuantumScript) -> tuple[QuantumScriptBatch, PostprocessingFn]: """A valid expand transform.""" return [tape], lambda x: x ########################################## # Valid informative transform def informative_transform(tape: QuantumScript) -> tuple[QuantumScriptBatch, PostprocessingFn]: """A valid informative transform""" def fn(results): return len(results[0].operations) return [tape], fn class TestTransformContainer: """Tests for the TransformContainer dataclass.""" def test_repr(self): """Tests for the repr of a transform container.""" t1 = qml.transforms.core.TransformContainer( qml.transforms.compile.transform, kwargs={"num_passes": 2, "expand_depth": 1} ) assert repr(t1) == "<compile([], {'num_passes': 2, 'expand_depth': 1})>" def test_equality(self): """Tests that we can compare TransformContainer objects with the '==' and '!=' operators.""" t1 = TransformContainer( qml.transforms.compile.transform, kwargs={"num_passes": 2, "expand_depth": 1} ) t2 = TransformContainer( qml.transforms.compile.transform, kwargs={"num_passes": 2, "expand_depth": 1} ) t3 = TransformContainer( qml.transforms.transpile.transform, kwargs={"coupling_map": [(0, 1), (1, 2)]} ) t4 = TransformContainer( qml.transforms.compile.transform, kwargs={"num_passes": 2, "expand_depth": 2} ) t5 = TransformContainer(qml.transforms.merge_rotations.transform, args=(1e-6,)) t6 = TransformContainer(qml.transforms.merge_rotations.transform, args=(1e-7,)) # test for equality of identical transformers assert t1 == t2 # test for inequality of different transformers assert t1 != t3 assert t2 != t3 assert t1 != 2 assert t1 != t4 assert t5 != t6 assert t5 != t1 # Test equality with the same args t5_copy = TransformContainer(qml.transforms.merge_rotations.transform, args=(1e-6,)) assert t5 == t5_copy def test_the_transform_container_attributes(self): """Test the transform container attributes.""" container = qml.transforms.core.TransformContainer( first_valid_transform, args=[0], kwargs={}, classical_cotransform=None ) q_transform, args, kwargs, cotransform, is_informative, final_transform = container assert q_transform is first_valid_transform assert args == [0] assert kwargs == {} assert cotransform is None assert not is_informative assert not final_transform assert container.transform is first_valid_transform assert container.args == [0] assert not container.kwargs assert container.classical_cotransform is None assert not container.is_informative assert not container.final_transform class TestTransformDispatcher: # pylint: disable=too-many-public-methods """Test the transform function (validate and dispatch).""" @pytest.mark.catalyst @pytest.mark.external def test_error_on_qjit(self): """Test that an error is raised on when applying a transform to a qjit object.""" pytest.importorskip("catalyst") @qml.qjit @qml.qnode(qml.device("lightning.qubit", wires=1)) def cost(): qml.RY(0.1, wires=0) qml.RY(0.1, wires=0) return qml.expval(qml.Z(0)) dispatched_transform = transform(first_valid_transform) with pytest.raises( TransformError, match=r"Functions that are wrapped / decorated with qjit cannot subsequently", ): dispatched_transform(cost) @pytest.mark.parametrize("valid_transform", valid_transforms) def test_integration_dispatcher_with_valid_transform(self, valid_transform): """Test that no error is raised with the transform function and that the transform dispatcher returns the right object.""" dispatched_transform = transform(valid_transform) # Applied on a tape tapes, fn = dispatched_transform(tape_circuit, 0) assert isinstance(tapes, Sequence) assert callable(fn) # Applied on a qfunc (return a qfunc) qfunc = dispatched_transform(qfunc_circuit, 0) assert callable(qfunc) # Applied on a qnode (return a qnode with populated the program) @qml.qnode(device=dev) def qnode_circuit(a): """QNode circuit.""" qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.PauliX(wires=0) qml.RZ(a, wires=1) return qml.expval(qml.PauliZ(wires=0)) qnode_transformed = dispatched_transform(qnode_circuit, 0) assert not qnode_circuit.transform_program assert qnode_transformed.device is qnode_circuit.device with dev.tracker: qnode_circuit(0.1) assert dev.tracker.totals["executions"] == 1 assert isinstance(qnode_transformed, qml.QNode) assert isinstance(qnode_transformed.transform_program, qml.transforms.core.TransformProgram) assert isinstance( qnode_transformed.transform_program.pop_front(), qml.transforms.core.TransformContainer ) assert dispatched_transform.is_informative is False def test_integration_dispatcher_with_informative_transform(self): """Test that no error is raised with the transform function and that the transform dispatcher returns the right object when an informative transform is applied.""" dispatched_transform = transform(informative_transform, is_informative=True) # Applied on a tape (return processed results) expected = len(tape_circuit.operations) num_ops = dispatched_transform(tape_circuit) assert num_ops == expected # Applied on a qfunc (return a qfunc) qfunc = dispatched_transform(qfunc_circuit) assert callable(qfunc) # Applied on a qnode (return a qnode with populated the program) @qml.qnode(device=dev) def qnode_circuit(a): """QNode circuit.""" qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.PauliX(wires=0) qml.RZ(a, wires=1) return qml.expval(qml.PauliZ(wires=0)) qnode_transformed = dispatched_transform(qnode_circuit) assert not qnode_circuit.transform_program assert qnode_transformed(0.1) == 4 assert isinstance(qnode_transformed, qml.QNode) assert isinstance(qnode_transformed.transform_program, qml.transforms.core.TransformProgram) assert isinstance( qnode_transformed.transform_program.pop_front(), qml.transforms.core.TransformContainer ) assert dispatched_transform.is_informative @pytest.mark.parametrize("valid_transform", valid_transforms) def test_integration_dispatcher_with_valid_transform_decorator_partial(self, valid_transform): """Test that no error is raised with the transform function and that the transform dispatcher returns the right object.""" dispatched_transform = transform(valid_transform) targs = [0] @partial(dispatched_transform, targs=targs) @qml.qnode(device=dev) def qnode_circuit(a): """QNode circuit.""" qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.PauliX(wires=0) qml.RZ(a, wires=1) return qml.expval(qml.PauliZ(wires=0)) assert isinstance(qnode_circuit, qml.QNode) assert isinstance(qnode_circuit.transform_program, qml.transforms.core.TransformProgram) assert isinstance( qnode_circuit.transform_program.pop_front(), qml.transforms.core.TransformContainer ) @pytest.mark.parametrize("valid_transform", valid_transforms) def test_integration_dispatcher_with_valid_transform_decorator_fails(self, valid_transform): """Test that an error is raised with the transform function.""" dispatched_transform = transform(valid_transform) targs = [0] msg = r"Decorating a QNode with @transform_fn\(\*\*transform_kwargs\) has been removed" with pytest.raises(TransformError, match=msg): @dispatched_transform(targs) @qml.qnode(device=dev) def qnode_circuit(a): # pylint:disable=unused-variable """QNode circuit.""" qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.PauliX(wires=0) qml.RZ(a, wires=1) return qml.expval(qml.PauliZ(wires=0)) def test_queuing_qfunc_transform(self): """Test that queuing works with the transformed quantum function.""" dispatched_transform = transform(first_valid_transform) # Applied on a tape tapes, fn = dispatched_transform(tape_circuit, 0) assert isinstance(tapes, Sequence) assert callable(fn) # Applied on a qfunc (return a qfunc) qfunc_transformed = dispatched_transform(qfunc_circuit, 0) assert callable(qfunc_transformed) assert inspect.signature(qfunc_transformed) == inspect.signature(qfunc_circuit) with QuantumTape() as transformed_tape: qfunc_transformed(0.42) assert isinstance(transformed_tape, QuantumScript) assert transformed_tape.circuit is not None assert len(transformed_tape.circuit) == 4 with QuantumTape() as tape: qfunc_circuit(0.42) assert isinstance(transformed_tape, QuantumScript) assert tape.circuit is not None assert len(tape.circuit) == 5 def test_qnode_with_expand_transform(self): """Test qnode with a transform program and expand transform.""" dispatched_transform = transform(first_valid_transform, expand_transform=expand_transform) # Applied on a tape tapes, fn = dispatched_transform(tape_circuit, 0) assert isinstance(tapes, Sequence) assert callable(fn) @qml.qnode(device=dev) def qnode_circuit(a): """QNode circuit.""" qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.PauliX(wires=0) qml.RZ(a, wires=1) return qml.expval(qml.PauliZ(wires=0)) # Applied on a qfunc (return a qfunc) qnode_transformed = dispatched_transform(qnode_circuit, 0) assert isinstance(qnode_transformed.transform_program, qml.transforms.core.TransformProgram) expand_transform_container = qnode_transformed.transform_program.pop_front() assert isinstance(expand_transform_container, qml.transforms.core.TransformContainer) assert expand_transform_container.args == [0] assert expand_transform_container.kwargs == {} assert expand_transform_container.classical_cotransform is None assert not expand_transform_container.is_informative transform_container = qnode_transformed.transform_program.pop_front() assert isinstance(transform_container, qml.transforms.core.TransformContainer) assert transform_container.args == [0] assert transform_container.kwargs == {} assert transform_container.classical_cotransform is None assert not expand_transform_container.is_informative @pytest.mark.parametrize("valid_transform", valid_transforms) def test_dispatcher_signature_classical_cotransform(self, valid_transform): """Test that valid transforms with non-valid co transform raises a Transform error.""" with pytest.raises( TransformError, match="The classical co-transform must be a valid Python function." ): transform(valid_transform, classical_cotransform=3) def test_error_not_callable_transform(self): """Test that a non-callable is not a valid transforms.""" with pytest.raises(TransformError, match="The function to register, "): transform(non_callable) def test_expand_transform_not_callable(self): """Test that an expand transform must be a callable otherwise it is not valid.""" with pytest.raises( TransformError, match="The expand function must be a valid Python function." ): transform(first_valid_transform, expand_transform=non_callable) def test_multiple_args_expand_transform(self): """Test that an expand transform must match the signature of the transform""" with pytest.raises( TransformError, match="The expand transform must have the same signature as the transform", ): transform(first_valid_transform, expand_transform=non_valid_expand_transform) def test_qfunc_transform_multiple_tapes(self): """Test that quantum function is not compatible with multiple tapes.""" dispatched_transform = transform(second_valid_transform) with pytest.raises( TransformError, match="Impossible to dispatch your transform on quantum function" ): dispatched_transform(qfunc_circuit, 0)(0.42) def test_informative_transform_tape_return(self): """Test that disaptched informative transforms return processed results instead of a list of tapes and processing function.""" tape = qml.tape.QuantumScript( [qml.PauliX(0), qml.CNOT([0, 1]), qml.RX(0.234, 1), qml.Hadamard(1)] ) dispatched_transform = transform(informative_transform, is_informative=True) num_ops = dispatched_transform(tape) assert num_ops == 4 def test_dispatched_transform_attribute(self): """Test the dispatcher attributes.""" dispatched_transform = transform(first_valid_transform) assert dispatched_transform.transform is first_valid_transform assert dispatched_transform.expand_transform is None assert dispatched_transform.classical_cotransform is None @pytest.mark.parametrize("valid_transform", valid_transforms) @pytest.mark.parametrize("batch_type", (tuple, list)) def test_batch_transform(self, valid_transform, batch_type, num_margin=1e-8): """Test that dispatcher can dispatch onto a batch of tapes.""" def check_batch(batch): return isinstance(batch, Sequence) and all( isinstance(tape, qml.tape.QuantumScript) for tape in batch ) def comb_postproc(results: TensorLike, fn1: Callable, fn2: Callable): return fn1(fn2(results)) # Create a simple device and tape tmp_dev = qml.device("default.qubit", wires=3) H = qml.Hamiltonian( [0.5, 1.0, 1.0], [qml.PauliZ(2), qml.PauliY(2) @ qml.PauliZ(1), qml.PauliZ(1)] ) measur = [qml.expval(H)] ops = [qml.Hadamard(0), qml.RX(0.2, 0), qml.RX(0.6, 0), qml.CNOT((0, 1))] tape = QuantumScript(ops, measur) ############################################################ ### Test with two elementary user-defined transforms ############################################################ dispatched_transform1 = transform(valid_transform) dispatched_transform2 = transform(valid_transform) batch1, fn1 = dispatched_transform1(tape, index=0) assert check_batch(batch1) batch2, fn2 = dispatched_transform2(batch1, index=0) assert check_batch(batch2) result = tmp_dev.execute(batch2) assert isinstance(result, TensorLike) ############################################################ ### Test with two `concrete` transforms ############################################################ tape = QuantumScript(ops, measur) batch1, fn1 = qml.transforms.split_non_commuting(tape) assert check_batch(batch1) batch2, fn2 = qml.transforms.merge_rotations(batch1) assert check_batch(batch2) result = tmp_dev.execute(batch2) assert isinstance(result, TensorLike) # check that final batch and post-processing functions are what we expect after the two transforms fin_ops = [qml.Hadamard(0), qml.RX(0.8, 0), qml.CNOT([0, 1])] tp1 = QuantumScript(fin_ops, [qml.expval(qml.PauliZ(2)), qml.expval(qml.PauliZ(1))]) tp2 = QuantumScript(fin_ops, [qml.expval(qml.PauliY(2) @ qml.PauliZ(1))]) fin_batch = batch_type([tp1, tp2]) for tapeA, tapeB in zip(fin_batch, batch2): qml.assert_equal(tapeA, tapeB) assert abs(comb_postproc(result, fn1, fn2).item() - 0.5) < num_margin @pytest.mark.parametrize("valid_transform", valid_transforms) def test_custom_qnode_transform(self, valid_transform): """Test that the custom qnode transform is correctly executed""" dispatched_transform = transform(valid_transform) history = [] @dispatched_transform.custom_qnode_transform def _custom_qnode_transform(self, qnode, targs, tkwargs): history.append((targs, tkwargs)) return self.default_qnode_transform(qnode, targs, tkwargs) @partial(dispatched_transform, index=0) @qml.qnode(dev) def qnode1(): """QNode circuit.""" qml.Hadamard(wires=0) return qml.expval(qml.PauliZ(wires=0)) assert isinstance(qnode1, qml.QNode) assert isinstance(qnode1.transform_program, qml.transforms.core.TransformProgram) assert isinstance( qnode1.transform_program.pop_front(), qml.transforms.core.TransformContainer ) @qml.qnode(dev) def qnode2(): """QNode circuit.""" qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(wires=0)) qnode2 = dispatched_transform(qnode2, 1) assert isinstance(qnode2, qml.QNode) assert isinstance(qnode2.transform_program, qml.transforms.core.TransformProgram) assert isinstance( qnode2.transform_program.pop_front(), qml.transforms.core.TransformContainer ) # check that the custom qnode transform was called assert history == [([], {"index": 0}), ([1], {})] @pytest.mark.parametrize( "fn, type_", [(list, list), (tuple, tuple), (qml.numpy.array, qml.numpy.ndarray)], ) def test_qfunc_transform_multiple_measurements(self, fn, type_): """Ensure that return type is preserved with qfunc transforms.""" def qfunc(): qml.Hadamard(0) qml.CNOT([0, 1]) qml.PauliZ(1) return fn([qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))]) dispatched_transform = transform(first_valid_transform) transformed_qfunc = dispatched_transform(qfunc, 2) qnode = qml.QNode(transformed_qfunc, qml.device("default.qubit")) result = qnode() assert isinstance(result, type_) @pytest.mark.parametrize("valid_transform", valid_transforms) def test_device_transform(self, valid_transform): """Test a device transform.""" dispatched_transform = transform(valid_transform) new_dev = dispatched_transform(dev, index=0) assert new_dev.original_device is dev assert repr(new_dev).startswith("Transformed Device") program, _ = dev.preprocess() new_program, _ = new_dev.preprocess() assert isinstance(program, qml.transforms.core.TransformProgram) assert isinstance(new_program, qml.transforms.core.TransformProgram) assert len(program) == 4 assert len(new_program) == 5 assert new_program[-1].transform is valid_transform @qml.qnode(new_dev) def circuit(): qml.PauliX(0) return qml.state() circuit() @pytest.mark.parametrize("valid_transform", valid_transforms) def test_old_device_transform(self, valid_transform): """Test a device transform.""" dev = qml.device("default.mixed", wires=2) # pylint: disable=redefined-outer-name dispatched_transform = transform(valid_transform) new_dev = dispatched_transform(dev, index=0) assert new_dev.original_device is dev assert repr(new_dev).startswith("Transformed Device") program, _ = dev.preprocess() new_program, _ = new_dev.preprocess() assert isinstance(program, qml.transforms.core.TransformProgram) assert isinstance(new_program, qml.transforms.core.TransformProgram) assert len(program) == 3 assert len(new_program) == 4 assert new_program[-1].transform is valid_transform @qml.qnode(new_dev) def circuit(): qml.PauliX(0) return qml.state() circuit() @pytest.mark.parametrize("valid_transform", valid_transforms) def test_device_transform_error(self, valid_transform): """Test that the device transform returns errors.""" with pytest.raises( TransformError, match="Device transform does not support informative transforms." ): dispatched_transform = transform(valid_transform, is_informative=True) dispatched_transform(dev, index=0) with pytest.raises( TransformError, match="Device transform does not support final transforms." ): dispatched_transform = transform(valid_transform, final_transform=True) dispatched_transform(dev, index=0) with pytest.raises( TransformError, match="Device transform does not support expand transforms." ): dispatched_transform = transform(valid_transform, expand_transform=valid_transform) dispatched_transform(dev, index=0) @pytest.mark.parametrize("valid_transform", valid_transforms) def test_old_device_transform_error(self, valid_transform): """Test that the old device transform returns errors.""" device = qml.device("default.mixed", wires=2) with pytest.raises( TransformError, match="Device transform does not support informative transforms." ): dispatched_transform = transform(valid_transform, is_informative=True) dispatched_transform(device, index=0) with pytest.raises( TransformError, match="Device transform does not support final transforms." ): dispatched_transform = transform(valid_transform, final_transform=True) dispatched_transform(device, index=0) with pytest.raises( TransformError, match="Device transform does not support expand transforms." ): dispatched_transform = transform(valid_transform, expand_transform=valid_transform) dispatched_transform(device, index=0) def test_sphinx_build(self, monkeypatch): """Test that transforms are not created during Sphinx builds""" monkeypatch.setenv("SPHINX_BUILD", "1") with pytest.warns(UserWarning, match="Transforms have been disabled, as a Sphinx"): @qml.transform def custom_transform( # pylint:disable=unused-variable tape: QuantumScript, index: int ) -> tuple[QuantumScriptBatch, PostprocessingFn]: """A valid transform.""" tape = tape.copy() tape._ops.pop(index) # pylint:disable=protected-access return [tape], lambda x: x
pennylane/tests/transforms/core/test_transform_dispatcher.py/0
{ "file_path": "pennylane/tests/transforms/core/test_transform_dispatcher.py", "repo_id": "pennylane", "token_count": 11151 }
98
# Copyright 2021 Xanadu Quantum Technologies Inc. # 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. """ Tests for the insert transform. """ from functools import partial import numpy as np import pytest import pennylane as qml from pennylane.measurements import Expectation from pennylane.tape import QuantumScript from pennylane.transforms.insert_ops import insert class TestInsert: """Tests for the insert function using input tapes""" with qml.queuing.AnnotatedQueue() as q_tape: qml.RX(0.9, wires=0) qml.RY(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(0.5, wires=0) qml.RX(0.6, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape = QuantumScript.from_queue(q_tape) with qml.queuing.AnnotatedQueue() as q_tape_with_prep: qml.StatePrep([1, 0], wires=0) qml.RX(0.9, wires=0) qml.RY(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(0.5, wires=0) qml.RX(0.6, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape_with_prep = QuantumScript.from_queue(q_tape_with_prep) with qml.queuing.AnnotatedQueue() as q_custom_tape: qml.RX(0.9, wires=0) qml.RY(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(0.5, wires=0) qml.PauliZ(wires=1) qml.Identity(wires=2) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) custom_tape = QuantumScript.from_queue(q_custom_tape) def test_multiwire_op(self): """Tests if a ValueError is raised when multiqubit operations are requested""" with pytest.raises(ValueError, match="Only single-qubit operations can be inserted into"): insert(self.tape, qml.CNOT, []) @pytest.mark.parametrize("pos", [1, ["all", qml.RY, int], "ABC", str]) def test_invalid_position(self, pos): """Test if a ValueError is raised when an invalid position is requested""" with pytest.raises(ValueError, match="Position must be either 'start', 'end', or 'all'"): insert(self.tape, qml.AmplitudeDamping, 0.4, position=pos) def test_start(self): """Test if the expected tape is returned when the start position is requested""" tapes, _ = insert(self.tape, qml.AmplitudeDamping, 0.4, position="start") tape = tapes[0] with qml.queuing.AnnotatedQueue() as q_tape_exp: qml.AmplitudeDamping(0.4, wires=0) qml.AmplitudeDamping(0.4, wires=1) qml.RX(0.9, wires=0) qml.RY(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(0.5, wires=0) qml.RX(0.6, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape_exp = QuantumScript.from_queue(q_tape_exp) assert all(o1.name == o2.name for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all(o1.wires == o2.wires for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all( np.allclose(o1.parameters, o2.parameters) for o1, o2 in zip(tape.operations, tape_exp.operations) ) assert len(tape.measurements) == 1 assert ( tape.observables[0].name == "Prod" if qml.operation.active_new_opmath() else ["PauliZ", "PauliZ"] ) assert tape.observables[0].wires.tolist() == [0, 1] assert tape.measurements[0].return_type is Expectation def test_all(self): """Test if the expected tape is returned when the all position is requested""" tapes, _ = insert(self.tape, qml.PhaseDamping, 0.4, position="all") tape = tapes[0] with qml.queuing.AnnotatedQueue() as q_tape_exp: qml.RX(0.9, wires=0) qml.PhaseDamping(0.4, wires=0) qml.RY(0.4, wires=1) qml.PhaseDamping(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseDamping(0.4, wires=0) qml.PhaseDamping(0.4, wires=1) qml.RY(0.5, wires=0) qml.PhaseDamping(0.4, wires=0) qml.RX(0.6, wires=1) qml.PhaseDamping(0.4, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape_exp = QuantumScript.from_queue(q_tape_exp) assert all(o1.name == o2.name for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all(o1.wires == o2.wires for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all( np.allclose(o1.parameters, o2.parameters) for o1, o2 in zip(tape.operations, tape_exp.operations) ) assert len(tape.measurements) == 1 assert ( tape.observables[0].name == "Prod" if qml.operation.active_new_opmath() else ["PauliZ", "PauliZ"] ) assert tape.observables[0].wires.tolist() == [0, 1] assert tape.measurements[0].return_type is Expectation def test_before(self): """Test if the expected tape is returned when the before argument is True""" tapes, _ = insert(self.tape, qml.PhaseDamping, 0.4, position="all", before=True) tape = tapes[0] with qml.queuing.AnnotatedQueue() as q_tape_exp: qml.PhaseDamping(0.4, wires=0) qml.RX(0.9, wires=0) qml.PhaseDamping(0.4, wires=1) qml.RY(0.4, wires=1) qml.PhaseDamping(0.4, wires=0) qml.PhaseDamping(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseDamping(0.4, wires=0) qml.RY(0.5, wires=0) qml.PhaseDamping(0.4, wires=1) qml.RX(0.6, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape_exp = QuantumScript.from_queue(q_tape_exp) assert all(o1.name == o2.name for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all(o1.wires == o2.wires for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all( np.allclose(o1.parameters, o2.parameters) for o1, o2 in zip(tape.operations, tape_exp.operations) ) assert len(tape.measurements) == 1 assert ( tape.observables[0].name == "Prod" if qml.operation.active_new_opmath() else ["PauliZ", "PauliZ"] ) assert tape.observables[0].wires.tolist() == [0, 1] assert tape.measurements[0].return_type is Expectation op_lst = [qml.RX, qml.PauliZ, qml.Identity] @pytest.mark.parametrize("op", op_lst) def test_operation_as_position(self, op): """Test if expected tape is returned when an operation is passed in position""" tapes, _ = insert(self.custom_tape, qml.PhaseDamping, 0.4, position=op, before=True) tape = tapes[0] with qml.queuing.AnnotatedQueue() as q_tape_exp: if op == qml.RX: qml.PhaseDamping(0.4, wires=0) qml.RX(0.9, wires=0) qml.RY(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(0.5, wires=0) if op == qml.PauliZ: qml.PhaseDamping(0.4, wires=1) qml.PauliZ(wires=1) if op == qml.Identity: qml.PhaseDamping(0.4, wires=2) qml.Identity(wires=2) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape_exp = QuantumScript.from_queue(q_tape_exp) assert all(o1.name == o2.name for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all(o1.wires == o2.wires for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all( np.allclose(o1.parameters, o2.parameters) for o1, o2 in zip(tape.operations, tape_exp.operations) ) assert len(tape.measurements) == 1 assert ( tape.observables[0].name == "Prod" if qml.operation.active_new_opmath() else ["PauliZ", "PauliZ"] ) assert tape.observables[0].wires.tolist() == [0, 1] assert tape.measurements[0].return_type is Expectation def test_operation_list_as_position(self): """Test if expected tape is returned when an operation list is passed in position""" tapes, _ = insert(self.tape, qml.PhaseDamping, 0.4, position=[qml.RX, qml.RY]) tape = tapes[0] with qml.queuing.AnnotatedQueue() as q_tape_exp: qml.RX(0.9, wires=0) qml.PhaseDamping(0.4, wires=0) qml.RY(0.4, wires=1) qml.PhaseDamping(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(0.5, wires=0) qml.PhaseDamping(0.4, wires=0) qml.RX(0.6, wires=1) qml.PhaseDamping(0.4, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape_exp = QuantumScript.from_queue(q_tape_exp) assert all(o1.name == o2.name for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all(o1.wires == o2.wires for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all( np.allclose(o1.parameters, o2.parameters) for o1, o2 in zip(tape.operations, tape_exp.operations) ) assert len(tape.measurements) == 1 assert ( tape.observables[0].name == "Prod" if qml.operation.active_new_opmath() else ["PauliZ", "PauliZ"] ) assert tape.observables[0].wires.tolist() == [0, 1] assert tape.measurements[0].return_type is Expectation def test_end(self): """Test if the expected tape is returned when the end position is requested""" tapes, _ = insert(self.tape, qml.GeneralizedAmplitudeDamping, [0.4, 0.5], position="end") tape = tapes[0] with qml.queuing.AnnotatedQueue() as q_tape_exp: qml.RX(0.9, wires=0) qml.RY(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(0.5, wires=0) qml.RX(0.6, wires=1) qml.GeneralizedAmplitudeDamping(0.4, 0.5, wires=0) qml.GeneralizedAmplitudeDamping(0.4, 0.5, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape_exp = QuantumScript.from_queue(q_tape_exp) assert all(o1.name == o2.name for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all(o1.wires == o2.wires for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all( np.allclose(o1.parameters, o2.parameters) for o1, o2 in zip(tape.operations, tape_exp.operations) ) assert len(tape.measurements) == 1 assert ( tape.observables[0].name == "Prod" if qml.operation.active_new_opmath() else ["PauliZ", "PauliZ"] ) assert tape.observables[0].wires.tolist() == [0, 1] assert tape.measurements[0].return_type is Expectation def test_start_with_state_prep(self): """Test if the expected tape is returned when the start position is requested in a tape that has state preparation""" tapes, _ = insert(self.tape_with_prep, qml.AmplitudeDamping, 0.4, position="start") tape = tapes[0] with qml.queuing.AnnotatedQueue() as q_tape_exp: qml.StatePrep([1, 0], wires=0) qml.AmplitudeDamping(0.4, wires=0) qml.AmplitudeDamping(0.4, wires=1) qml.RX(0.9, wires=0) qml.RY(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(0.5, wires=0) qml.RX(0.6, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape_exp = QuantumScript.from_queue(q_tape_exp) assert all(o1.name == o2.name for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all(o1.wires == o2.wires for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all( np.allclose(o1.parameters, o2.parameters) for o1, o2 in zip(tape.operations, tape_exp.operations) ) assert len(tape.measurements) == 1 assert ( tape.observables[0].name == "Prod" if qml.operation.active_new_opmath() else ["PauliZ", "PauliZ"] ) assert tape.observables[0].wires.tolist() == [0, 1] assert tape.measurements[0].return_type is Expectation def test_all_with_state_prep(self): """Test if the expected tape is returned when the all position is requested in a tape that has state preparation""" tapes, _ = insert(self.tape_with_prep, qml.PhaseDamping, 0.4, position="all") tape = tapes[0] with qml.queuing.AnnotatedQueue() as q_tape_exp: qml.StatePrep([1, 0], wires=0) qml.RX(0.9, wires=0) qml.PhaseDamping(0.4, wires=0) qml.RY(0.4, wires=1) qml.PhaseDamping(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseDamping(0.4, wires=0) qml.PhaseDamping(0.4, wires=1) qml.RY(0.5, wires=0) qml.PhaseDamping(0.4, wires=0) qml.RX(0.6, wires=1) qml.PhaseDamping(0.4, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape_exp = QuantumScript.from_queue(q_tape_exp) assert all(o1.name == o2.name for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all(o1.wires == o2.wires for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all( np.allclose(o1.parameters, o2.parameters) for o1, o2 in zip(tape.operations, tape_exp.operations) ) assert len(tape.measurements) == 1 assert ( tape.observables[0].name == "Prod" if qml.operation.active_new_opmath() else ["PauliZ", "PauliZ"] ) assert tape.observables[0].wires.tolist() == [0, 1] assert tape.measurements[0].return_type is Expectation def test_end_with_state_prep(self): """Test if the expected tape is returned when the end position is requested in a tape that has state preparation""" tapes, _ = insert( self.tape_with_prep, qml.GeneralizedAmplitudeDamping, [0.4, 0.5], position="end" ) tape = tapes[0] with qml.queuing.AnnotatedQueue() as q_tape_exp: qml.StatePrep([1, 0], wires=0) qml.RX(0.9, wires=0) qml.RY(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(0.5, wires=0) qml.RX(0.6, wires=1) qml.GeneralizedAmplitudeDamping(0.4, 0.5, wires=0) qml.GeneralizedAmplitudeDamping(0.4, 0.5, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape_exp = QuantumScript.from_queue(q_tape_exp) assert all(o1.name == o2.name for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all(o1.wires == o2.wires for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all( np.allclose(o1.parameters, o2.parameters) for o1, o2 in zip(tape.operations, tape_exp.operations) ) assert len(tape.measurements) == 1 assert ( tape.observables[0].name == "Prod" if qml.operation.active_new_opmath() else ["PauliZ", "PauliZ"] ) assert tape.observables[0].wires.tolist() == [0, 1] assert tape.measurements[0].return_type is Expectation def test_with_qfunc_op(self): """Test if the transform works as expected if the operation is a qfunc rather than single operation""" def op(x, y, wires): qml.RX(x, wires=wires) qml.PhaseShift(y, wires=wires) tapes, _ = insert(self.tape, op=op, op_args=[0.4, 0.5], position="end") tape = tapes[0] with qml.queuing.AnnotatedQueue() as q_tape_exp: qml.RX(0.9, wires=0) qml.RY(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(0.5, wires=0) qml.RX(0.6, wires=1) qml.RX(0.4, wires=0) qml.PhaseShift(0.5, wires=0) qml.RX(0.4, wires=1) qml.PhaseShift(0.5, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tape_exp = QuantumScript.from_queue(q_tape_exp) assert all(o1.name == o2.name for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all(o1.wires == o2.wires for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all( np.allclose(o1.parameters, o2.parameters) for o1, o2 in zip(tape.operations, tape_exp.operations) ) assert len(tape.measurements) == 1 assert ( tape.observables[0].name == "Prod" if qml.operation.active_new_opmath() else ["PauliZ", "PauliZ"] ) assert tape.observables[0].wires.tolist() == [0, 1] assert tape.measurements[0].return_type is Expectation def test_insert_qnode(): """Test that a QNode with the insert decorator gives a different result than one without.""" dev = qml.device("default.mixed", wires=2) @partial(insert, op=qml.AmplitudeDamping, op_args=0.2, position="end") @qml.qnode(dev) def f_noisy(w, x, y, z): qml.RX(w, wires=0) qml.RY(x, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(y, wires=0) qml.RX(z, wires=1) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) @qml.qnode(dev) def f(w, x, y, z): qml.RX(w, wires=0) qml.RY(x, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(y, wires=0) qml.RX(z, wires=1) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) args = [0.1, 0.2, 0.3, 0.4] assert not np.isclose(f_noisy(*args), f(*args)) @pytest.mark.parametrize("dev_name", ["default.qubit", "default.mixed"]) def test_insert_dev(dev_name): """Test if an device transformed by the insert function does successfully add noise to subsequent circuit executions""" with qml.queuing.AnnotatedQueue() as q_in_tape: qml.RX(0.9, wires=0) qml.RY(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.RY(0.5, wires=0) qml.RX(0.6, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) qml.expval(qml.PauliZ(0)) in_tape = QuantumScript.from_queue(q_in_tape) dev = qml.device(dev_name, wires=2) program, _ = dev.preprocess() res_without_noise = qml.execute( [in_tape], dev, qml.gradients.param_shift, transform_program=program ) new_dev = insert(dev, qml.PhaseShift, 0.4) new_program, _ = new_dev.preprocess() tapes, _ = new_program([in_tape]) tape = tapes[0] res_with_noise = qml.execute([in_tape], new_dev, qml.gradients, transform_program=new_program) with qml.queuing.AnnotatedQueue() as q_tape_exp: qml.RX(0.9, wires=0) qml.PhaseShift(0.4, wires=0) qml.RY(0.4, wires=1) qml.PhaseShift(0.4, wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseShift(0.4, wires=0) qml.PhaseShift(0.4, wires=1) qml.RY(0.5, wires=0) qml.PhaseShift(0.4, wires=0) qml.RX(0.6, wires=1) qml.PhaseShift(0.4, wires=1) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) qml.expval(qml.PauliZ(0)) tape_exp = QuantumScript.from_queue(q_tape_exp) assert all(o1.name == o2.name for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all(o1.wires == o2.wires for o1, o2 in zip(tape.operations, tape_exp.operations)) assert all( np.allclose(o1.parameters, o2.parameters) for o1, o2 in zip(tape.operations, tape_exp.operations) ) assert len(tape.measurements) == 2 assert ( tape.observables[0].name == "Prod" if qml.operation.active_new_opmath() else ["PauliZ", "PauliZ"] ) assert tape.observables[0].wires.tolist() == [0, 1] assert tape.measurements[0].return_type is Expectation assert tape.observables[1].name == "PauliZ" assert tape.observables[1].wires.tolist() == [0] assert tape.measurements[1].return_type is Expectation assert not np.allclose(res_without_noise, res_with_noise) def test_insert_template(): """Test that ops are inserted correctly into a decomposed template""" dev = qml.device("default.mixed", wires=2) @partial(insert, op=qml.PhaseDamping, op_args=0.3, position="all") @qml.qnode(dev) def f1(w1, w2): qml.SimplifiedTwoDesign(w1, w2, wires=[0, 1]) return qml.expval(qml.PauliZ(0)) @qml.qnode(dev) def f2(w1, w2): qml.RY(w1[0], wires=0) qml.PhaseDamping(0.3, wires=0) qml.RY(w1[1], wires=1) qml.PhaseDamping(0.3, wires=1) qml.CZ(wires=[0, 1]) qml.PhaseDamping(0.3, wires=0) qml.PhaseDamping(0.3, wires=1) qml.RY(w2[0][0][0], wires=0) qml.PhaseDamping(0.3, wires=0) qml.RY(w2[0][0][1], wires=1) qml.PhaseDamping(0.3, wires=1) return qml.expval(qml.PauliZ(0)) w1 = np.random.random(2) w2 = np.random.random((1, 1, 2)) assert np.allclose(f1(w1, w2), f2(w1, w2)) def test_insert_transform_works_with_non_qwc_obs(): """Test that the insert transform catches and reports errors from the enclosed function.""" def op(noise_param, wires): # pylint: disable=unused-argument qml.CRX(noise_param, wires=[0, 1]) qml.CNOT(wires=[1, 0]) dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) @partial(insert, op=op, op_args=0.3, position="all") def noisy_circuit(circuit_param): qml.RY(circuit_param, wires=0) qml.Hadamard(wires=0) qml.T(wires=0) return qml.expval(qml.PauliX(0)), qml.expval(qml.PauliY(0)), qml.expval(qml.PauliZ(0)) @qml.qnode(dev) def explicit_circuit(circuit_param): qml.RY(circuit_param, wires=0) op(0.3, None) qml.Hadamard(wires=0) op(0.3, None) qml.T(wires=0) op(0.3, None) return qml.expval(qml.PauliX(0)), qml.expval(qml.PauliY(0)), qml.expval(qml.PauliZ(0)) assert np.allclose(noisy_circuit(0.4), explicit_circuit(0.4))
pennylane/tests/transforms/test_insert_ops.py/0
{ "file_path": "pennylane/tests/transforms/test_insert_ops.py", "repo_id": "pennylane", "token_count": 11626 }
99