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 |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 45