text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct IoK8sApiNetworkingV1beta1IngressTLS <: SwaggerModel
    hosts::Any # spec type: Union{ Nothing, Vector{String} } # spec name: hosts
    secretName::Any # spec type: Union{ Nothing, String } # spec name: secretName

    function IoK8sApiNetworkingV1beta1IngressTLS(;hosts=nothing, secretName=nothing)
        o = new()
        validate_property(IoK8sApiNetworkingV1beta1IngressTLS, Symbol("hosts"), hosts)
        setfield!(o, Symbol("hosts"), hosts)
        validate_property(IoK8sApiNetworkingV1beta1IngressTLS, Symbol("secretName"), secretName)
        setfield!(o, Symbol("secretName"), secretName)
        o
    end
end # type IoK8sApiNetworkingV1beta1IngressTLS

const _property_map_IoK8sApiNetworkingV1beta1IngressTLS = Dict{Symbol,Symbol}(Symbol("hosts")=>Symbol("hosts"), Symbol("secretName")=>Symbol("secretName"))
const _property_types_IoK8sApiNetworkingV1beta1IngressTLS = Dict{Symbol,String}(Symbol("hosts")=>"Vector{String}", Symbol("secretName")=>"String")
Base.propertynames(::Type{ IoK8sApiNetworkingV1beta1IngressTLS }) = collect(keys(_property_map_IoK8sApiNetworkingV1beta1IngressTLS))
Swagger.property_type(::Type{ IoK8sApiNetworkingV1beta1IngressTLS }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_IoK8sApiNetworkingV1beta1IngressTLS[name]))}
Swagger.field_name(::Type{ IoK8sApiNetworkingV1beta1IngressTLS }, property_name::Symbol) =  _property_map_IoK8sApiNetworkingV1beta1IngressTLS[property_name]

function check_required(o::IoK8sApiNetworkingV1beta1IngressTLS)
    true
end

function validate_property(::Type{ IoK8sApiNetworkingV1beta1IngressTLS }, name::Symbol, val)
end


text:
# MetBrewer
# Blake Robert Mills
# https://github.com/BlakeRMills/MetBrewer
# Palettes inspired by works at the Metropolitan Museum of Art
# in New York. All pieces selected come from various time
# periods, regions, and mediums.

loadcolorscheme(
    :Archambault,
    [
        colorant"#88a0dc",
        colorant"#381a61",
        colorant"#7c4b73",
        colorant"#ed968c",
        colorant"#ab3329",
        colorant"#e78429",
        colorant"#f9d14a",
    ],
    "MetBrewer",
    "Woman’s Dress and Accessories, 2005, Jodi Archambault, Hunkpapa Lakota (Teton Sioux), cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Austria,
    [
        colorant"#a40000",
        colorant"#16317d",
        colorant"#007e2f",
        colorant"#ffcd12",
        colorant"#b86092",
        colorant"#721b3e",
        colorant"#00b7a7",
    ],
    "MetBrewer",
    "Adoration of the Magi from Seven Scenes from the Life of Christ, 1390, Artists Unknown, Austrian",
)

loadcolorscheme(
    :Benedictus,
    [
        colorant"#9a133d",
        colorant"#b93961",
        colorant"#d8527c",
        colorant"#f28aaa",
        colorant"#f9b4c9",
        colorant"#f9e0e8",
        colorant"#ffffff",
        colorant"#eaf3ff",
        colorant"#c5daf6",
        colorant"#a1c2ed",
        colorant"#6996e3",
        colorant"#4060c8",
        colorant"#1a318b",
    ],
    "MetBrewer",
    "Relais, 1930 : quinze planches donnant quarante-deux motifs décoratifs : enluminure d'art de J. Saudé : préliminaires de Y. Rambosson, 1930, Edouard Bénedictus, French",
)

loadcolorscheme(
    :Cassatt1,
    [
        colorant"#b1615c",
        colorant"#d88782",
        colorant"#e3aba7",
        colorant"#edd7d9",
        colorant"#c9c9dd",
        colorant"#9d9dc7",
        colorant"#8282aa",
        colorant"#5a5a83",
    ],
    "MetBrewer",
    "The Cup of Tea, 1880-1881, Mary Cassatt, American, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Cassatt2,
    [
        colorant"#2d223c",
        colorant"#574571",
        colorant"#90719f",
        colorant"#b695bc",
        colorant"#dec5da",
        colorant"#c1d1aa",
        colorant"#7fa074",
        colorant"#466c4b",
        colorant"#2c4b27",
        colorant"#0e2810",
    ],
    "MetBrewer",
    "Lilacs in a Window (Vase de Lilas a la Fenetre), 1880–83, Mary Cassatt, American, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Cross,
    [
        colorant"#c969a1",
        colorant"#ce4441",
        colorant"#ee8577",
        colorant"#eb7926",
        colorant"#ffbb44",
        colorant"#859b6c",
        colorant"#62929a",
        colorant"#004f63",
        colorant"#122451",
    ],
    "MetBrewer",
    "Cap Nègre, 1909, Henri-Edmond Cross, French",
)

loadcolorscheme(
    :Degas,
    [
        colorant"#591d06",
        colorant"#96410e",
        colorant"#e5a335",
        colorant"#556219",
        colorant"#418979",
        colorant"#2b614e",
        colorant"#053c29",
    ],
    "MetBrewer",
    "The Rehearsal of the Ballet Onstage, 1874, Edgar Degas, French",
)

loadcolorscheme(
    :Demuth,
    [
        colorant"#591c19",
        colorant"#9b332b",
        colorant"#b64f32",
        colorant"#d39a2d",
        colorant"#f7c267",
        colorant"#b9b9b8",
        colorant"#8b8b99",
        colorant"#5d6174",
        colorant"#41485f",
        colorant"#262d42",
    ],
    "MetBrewer",
    "I Saw the Figure 5 in Gold, 1928, Charles Demuth, American, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Derain,
    [
        colorant"#efc86e",
        colorant"#97c684",
        colorant"#6f9969",
        colorant"#aab5d5",
        colorant"#808fe1",
        colorant"#5c66a8",
        colorant"#454a74",
    ],
    "MetBrewer",
    "The Palace of Westminster, 1906–1907, André Derain, French, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Egypt,
    [colorant"#dd5129", colorant"#0f7ba2", colorant"#43b284", colorant"#fab255"],
    "MetBrewer",
    "The King with Isis, Tomb of Haremhab, A.D. 1910–1911; original ca. 1323–1295 B.C., Twentieth Century; original New Kingdom, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Gauguin,
    [
        colorant"#b04948",
        colorant"#811e18",
        colorant"#9e4013",
        colorant"#c88a2c",
        colorant"#4c6216",
        colorant"#1a472a",
    ],
    "MetBrewer",
    "A Farm in Brittany, 1874, Paul Gauguin, French",
)

loadcolorscheme(
    :Greek,
    [
        colorant"#3c0d03",
        colorant"#8d1c06",
        colorant"#e67424",
        colorant"#ed9b49",
        colorant"#f5c34d",
    ],
    "MetBrewer",
    "Terracotta neck-amphora (jar), ca. 550–540 B.C., Greek, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Hiroshige,
    [
        colorant"#e76254",
        colorant"#ef8a47",
        colorant"#f7aa58",
        colorant"#ffd06f",
        colorant"#ffe6b7",
        colorant"#aadce0",
        colorant"#72bcd5",
        colorant"#528fad",
        colorant"#376795",
        colorant"#1e466e",
    ],
    "MetBrewer",
    "Sailing Boats Returning to Yabase, Lake Biwa, 1835, Utagawa Hiroshige, Japanese, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Hokusai1,
    [
        colorant"#6d2f20",
        colorant"#b75347",
        colorant"#df7e66",
        colorant"#e09351",
        colorant"#edc775",
        colorant"#94b594",
        colorant"#224b5e",
    ],
    "MetBrewer",
    "Poem by Gon-Chūnagon Sadaie, from the series One Hundred Poems Explained by the Nurse (Hyakunin isshu uba ga etoki), 1760–1849, Katsushika Hokusai, Japanese",
)

loadcolorscheme(
    :Hokusai2,
    [
        colorant"#abc9c8",
        colorant"#72aeb6",
        colorant"#4692b0",
        colorant"#2f70a1",
        colorant"#134b73",
        colorant"#0a3351",
    ],
    "MetBrewer",
    "Lake Suwa in Shinano Province (Shinshū Suwako), from the series Thirty-six Views of Mount Fuji (Fugaku sanjūrokkei), 1830-32, Katsushika Hokusai, Japanese, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Hokusai3,
    [
        colorant"#d8d97a",
        colorant"#95c36e",
        colorant"#74c8c3",
        colorant"#5a97c1",
        colorant"#295384",
        colorant"#0a2e57",
    ],
    "MetBrewer",
    "Yōrō Waterfall in Mino Province (Mino no Yōrō no taki), from the series A Tour of Waterfalls in Various Provinces (Shokoku taki meguri), 1832, Katsushika Hokusai, Japanese, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Homer1,
    [
        colorant"#551f00",
        colorant"#a62f00",
        colorant"#df7700",
        colorant"#f5b642",
        colorant"#fff179",
        colorant"#c3f4f6",
        colorant"#6ad5e8",
        colorant"#32b2da",
    ],
    "MetBrewer",
    "The Veteran in a New Field, 1865, Winslow Homer, American",
)

loadcolorscheme(
    :Homer2,
    [
        colorant"#bf3626",
        colorant"#e9724c",
        colorant"#e9851d",
        colorant"#f9c53b",
        colorant"#aeac4c",
        colorant"#788f33",
        colorant"#165d43",
    ],
    "MetBrewer",
    "Flower Garden and Bungalow, Bermuda, 1899, Winslow Homer, American",
)

loadcolorscheme(
    :Ingres,
    [
        colorant"#041d2c",
        colorant"#06314e",
        colorant"#18527e",
        colorant"#2e77ab",
        colorant"#d1b252",
        colorant"#a97f2f",
        colorant"#7e5522",
        colorant"#472c0b",
    ],
    "MetBrewer",
    "Joséphine-Éléonore-Marie-Pauline de Galard de Brassac de Béarn (1825–1860), Princesse de Broglie, 1851–53, Jean Auguste Dominique Ingres, French, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Isfahan1,
    [
        colorant"#4e3910",
        colorant"#845d29",
        colorant"#d8c29d",
        colorant"#4fb6ca",
        colorant"#178f92",
        colorant"#175f5d",
        colorant"#1d1f54",
    ],
    "MetBrewer",
    "Mihrab (Prayer Niche), dated A.H. 755/ A.D. 1354–55, From Iran, Isfahan, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Isfahan2,
    [
        colorant"#d7aca1",
        colorant"#ddc000",
        colorant"#79ad41",
        colorant"#34b6c6",
        colorant"#4063a3",
    ],
    "MetBrewer",
    "Garden Gathering, 1640–50, From Iran, Isfahan, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Java,
    [
        colorant"#663171",
        colorant"#cf3a36",
        colorant"#ea7428",
        colorant"#e2998a",
        colorant"#0c7156",
    ],
    "MetBrewer",
    "Skirt, 20th Century, Javanese People, Javanese, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Johnson,
    [
        colorant"#a00e00",
        colorant"#d04e00",
        colorant"#f6c200",
        colorant"#0086a8",
        colorant"#132b69",
    ],
    "MetBrewer",
    "Jitterbugs V, 1941–42, William Henry Johnson, American, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Juarez,
    [
        colorant"#a82203",
        colorant"#208cc0",
        colorant"#f1af3a",
        colorant"#cf5e4e",
        colorant"#637b31",
        colorant"#003967",
    ],
    "MetBrewer",
    "The Entombment of Christ, 1702, Juan Rodríguez Juárez, Mexican",
)

loadcolorscheme(
    :Kandinsky,
    [colorant"#3b7c70", colorant"#ce9642", colorant"#898e9f", colorant"#3b3a3e"],
    "MetBrewer",
    "Kleine Welten IV (Small Worlds IV), 1922, Vasily Kandinsky, French, born Russia, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Klimt,
    [
        colorant"#df9ed4",
        colorant"#c93f55",
        colorant"#eacc62",
        colorant"#469d76",
        colorant"#3c4b99",
        colorant"#924099",
    ],
    "MetBrewer",
    "Mäda Primavesi (1903–2000), 1912-13, Gustav Klimt, Austria",
)

loadcolorscheme(
    :Lakota,
    [
        colorant"#04a3bd",
        colorant"#f0be3d",
        colorant"#931e18",
        colorant"#da7901",
        colorant"#247d3f",
        colorant"#20235b",
    ],
    "MetBrewer",
    "Dress, 1870, Lakota/Teton Sioux, Native American",
)

loadcolorscheme(
    :Manet,
    [
        colorant"#3b2319",
        colorant"#80521c",
        colorant"#d29c44",
        colorant"#ebc174",
        colorant"#ede2cc",
        colorant"#7ec5f4",
        colorant"#4585b7",
        colorant"#225e92",
        colorant"#183571",
        colorant"#43429b",
        colorant"#5e65be",
    ],
    "MetBrewer",
    "Boating, 1874, Edouard Manet, French",
)

loadcolorscheme(
    :Monet,
    [
        colorant"#4e6d58",
        colorant"#749e89",
        colorant"#abccbe",
        colorant"#e3cacf",
        colorant"#c399a2",
        colorant"#9f6e71",
        colorant"#41507b",
        colorant"#7d87b2",
        colorant"#c2cae3",
    ],
    "MetBrewer",
    "Bridge over a Pond of Water Lilies, 1899, Claude Monet, French",
)

loadcolorscheme(
    :Moreau,
    [
        colorant"#421600",
        colorant"#792504",
        colorant"#bc7524",
        colorant"#8dadca",
        colorant"#527baa",
        colorant"#104839",
        colorant"#082844",
    ],
    "MetBrewer",
    "Oedipus and the Sphinx, 1864, Gustave Moreau, French",
)

loadcolorscheme(
    :Morgenstern,
    [
        colorant"#7c668c",
        colorant"#b08ba5",
        colorant"#dfbbc8",
        colorant"#ffc680",
        colorant"#ffb178",
        colorant"#db8872",
        colorant"#a56457",
    ],
    "MetBrewer",
    "Jungfrau, Mönch, and Eiger, 1851, Carl Morgenstern, German, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Nattier,
    [
        colorant"#52271c",
        colorant"#944839",
        colorant"#c08e39",
        colorant"#7f793c",
        colorant"#565c33",
        colorant"#184948",
        colorant"#022a2a",
    ],
    "MetBrewer",
    "Madame Bergeret de Frouville as Diana, 1756, Jean Marc Nattier, French",
)

loadcolorscheme(
    :Navajo,
    [
        colorant"#660d20",
        colorant"#e59a52",
        colorant"#edce79",
        colorant"#094568",
        colorant"#e1c59a",
    ],
    "MetBrewer",
    "Serape, 1865–70, Navajo",
)

loadcolorscheme(
    :NewKingdom,
    [
        colorant"#e1846c",
        colorant"#9eb4e0",
        colorant"#e6bb9e",
        colorant"#9c6849",
        colorant"#735852",
    ],
    "MetBrewer",
    "Blue-Painted Ibex Amphora from Malqata, ca. 1390–1353 B.C., New Kingdom",
)

loadcolorscheme(
    :Nizami,
    [
        colorant"#dd7867",
        colorant"#b83326",
        colorant"#c8570d",
        colorant"#edb144",
        colorant"#8cc8bc",
        colorant"#7da7ea",
        colorant"#5773c0",
        colorant"#1d4497",
    ],
    "MetBrewer",
    "\"Laila and Majnun in School\", Folio 129 from a Khamsa (Quintet) of Nizami of Ganja, A.H. 931/A.D. 1524–25, Nizami, Made in present-day Afghanistan, Herat",
)

loadcolorscheme(
    :OKeeffe1,
    [
        colorant"#6b200c",
        colorant"#973d21",
        colorant"#da6c42",
        colorant"#ee956a",
        colorant"#fbc2a9",
        colorant"#f6f2ee",
        colorant"#bad6f9",
        colorant"#7db0ea",
        colorant"#447fdd",
        colorant"#225bb2",
        colorant"#133e7e",
    ],
    "MetBrewer",
    "From the Faraway, Nearby, 1937, Georgia O'Keeffe, American, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :OKeeffe2,
    [
        colorant"#fbe3c2",
        colorant"#f2c88f",
        colorant"#ecb27d",
        colorant"#e69c6b",
        colorant"#d37750",
        colorant"#b9563f",
        colorant"#92351e",
    ],
    "MetBrewer",
    "Red and Yellow Cliffs, 1940, Georgia O'Keeffe, American, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Paquin,
    [
        colorant"#831818",
        colorant"#c62320",
        colorant"#f05b43",
        colorant"#f78462",
        colorant"#feac81",
        colorant"#f7dea3",
        colorant"#ced1af",
        colorant"#98ab76",
        colorant"#748f46",
        colorant"#47632a",
        colorant"#275024",
    ],
    "MetBrewer",
    "Evening Dress, 1937, House of Paquin by Ana de Pombo, French House, Spanish Designer",
)

loadcolorscheme(
    :Peru1,
    [
        colorant"#b5361c",
        colorant"#e35e28",
        colorant"#1c9d7c",
        colorant"#31c7ba",
        colorant"#369cc9",
        colorant"#3a507f",
    ],
    "MetBrewer",
    "Ear Ornament, Winged Runner, A.D. 400–700, Moche, Peruvian",
)

loadcolorscheme(
    :Peru2,
    [
        colorant"#65150b",
        colorant"#961f1f",
        colorant"#c0431f",
        colorant"#b36c06",
        colorant"#f19425",
        colorant"#c59349",
        colorant"#533d14",
    ],
    "MetBrewer",
    "Tunic with Confronting Catfish, A.D. 800–850, Nasca-Wari, Peruvian",
)

loadcolorscheme(
    :Pillement,
    [
        colorant"#a9845b",
        colorant"#697852",
        colorant"#738e8e",
        colorant"#44636f",
        colorant"#2b4655",
        colorant"#0f252f",
    ],
    "MetBrewer",
    "A Shipwreck in a Storm, 1782, Jean Pillement, French, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Pissaro,
    [
        colorant"#134130",
        colorant"#4c825d",
        colorant"#8cae9e",
        colorant"#8dc7dc",
        colorant"#508ca7",
        colorant"#1a5270",
        colorant"#0e2a4d",
    ],
    "MetBrewer",
    "Washerwoman, Study, 1880, Camille Pissarro, French",
)

loadcolorscheme(
    :Redon,
    [
        colorant"#5b859e",
        colorant"#1e395f",
        colorant"#75884b",
        colorant"#1e5a46",
        colorant"#df8d71",
        colorant"#af4f2f",
        colorant"#d48f90",
        colorant"#732f30",
        colorant"#ab84a5",
        colorant"#59385c",
        colorant"#d8b847",
        colorant"#b38711",
    ],
    "MetBrewer",
    "Pandora, 1914, Odilon Redon, French",
)

loadcolorscheme(
    :Renoir,
    [
        colorant"#17154f",
        colorant"#2f357c",
        colorant"#6c5d9e",
        colorant"#9d9cd5",
        colorant"#b0799a",
        colorant"#f6b3b0",
        colorant"#e48171",
        colorant"#bf3729",
        colorant"#e69b00",
        colorant"#f5bb50",
        colorant"#ada43b",
        colorant"#355828",
    ],
    "MetBrewer",
    "Nini in the Garden (Nini Lopez), 1876, Auguste Renoir, French",
)

loadcolorscheme(
    :Robert,
    [
        colorant"#11341a",
        colorant"#375624",
        colorant"#6ca4a0",
        colorant"#487a7c",
        colorant"#18505f",
        colorant"#062e3d",
    ],
    "MetBrewer",
    "The Bathing Pool, Hubert Robert, French",
)

loadcolorscheme(
    :Signac,
    [
        colorant"#fbe183",
        colorant"#f4c40f",
        colorant"#fe9b00",
        colorant"#d8443c",
        colorant"#9b3441",
        colorant"#de597c",
        colorant"#e87b89",
        colorant"#e6a2a6",
        colorant"#aa7aa1",
        colorant"#9f5691",
        colorant"#633372",
        colorant"#1f6e9c",
        colorant"#2b9b81",
        colorant"#92c051",
    ],
    "MetBrewer",
    "Notre-Dame-de-la-Garde (La Bonne-Mère), Marseilles, 1905-06, Paul Signac, French",
)

loadcolorscheme(
    :Stevens,
    [
        colorant"#042e4e",
        colorant"#307d7f",
        colorant"#598c4c",
        colorant"#ba5c3f",
        colorant"#a13213",
        colorant"#470c00",
    ],
    "MetBrewer",
    "The Japanese Robe, 1872, Alfred Stevens, Belgian",
)

loadcolorscheme(
    :Tam,
    [
        colorant"#ffd353",
        colorant"#ffb242",
        colorant"#ef8737",
        colorant"#de4f33",
        colorant"#bb292c",
        colorant"#9f2d55",
        colorant"#62205f",
        colorant"#341648",
    ],
    "MetBrewer",
    "Dragon Robe, 1998, Vivienne Tam, American, born China, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Tara,
    [
        colorant"#eab1c6",
        colorant"#d35e17",
        colorant"#e18a1f",
        colorant"#e9b109",
        colorant"#829d44",
    ],
    "MetBrewer",
    "Maharana Sarup Singh Inspects a Prize Stallion, 1845–46, Tara, Western India, Rajasthan, Mewar",
)

loadcolorscheme(
    :Thomas,
    [
        colorant"#b24422",
        colorant"#c44d76",
        colorant"#4457a5",
        colorant"#13315f",
        colorant"#b1a1cc",
        colorant"#59386c",
        colorant"#447861",
        colorant"#7caf5c",
    ],
    "MetBrewer",
    "Formes et couleurs: vingt planches en couleurs contenant soixante-sept motifs decoratifs, 1921, Auguste H. Thomas, French",
)

loadcolorscheme(
    :Tiepolo,
    [
        colorant"#802417",
        colorant"#c06636",
        colorant"#ce9344",
        colorant"#e8b960",
        colorant"#646e3b",
        colorant"#2b5851",
        colorant"#508ea2",
        colorant"#17486f",
    ],
    "MetBrewer",
    "The Glorification of the Barbaro Family, 1750, Giovanni Battista Tiepolo, Italian",
)

loadcolorscheme(
    :Troy,
    [
        colorant"#421401",
        colorant"#6c1d0e",
        colorant"#8b3a2b",
        colorant"#c27668",
        colorant"#7ba0b4",
        colorant"#44728c",
        colorant"#235070",
        colorant"#0a2d46",
    ],
    "MetBrewer",
    "The Declaration of Love, 1724, Jean François de Troy, French, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Tsimshian,
    [
        colorant"#582310",
        colorant"#aa361d",
        colorant"#82c45f",
        colorant"#318f49",
        colorant"#0cb4bb",
        colorant"#2673a3",
        colorant"#473d7d",
    ],
    "MetBrewer",
    "Headdress frontlet, 1820–40, Tsimshian, Native American (Canadian)",
)

loadcolorscheme(
    :VanGogh1,
    [
        colorant"#2c2d54",
        colorant"#434475",
        colorant"#6b6ca3",
        colorant"#969bc7",
        colorant"#87bcbd",
        colorant"#89ab7c",
        colorant"#6f9954",
    ],
    "MetBrewer",
    "Cypresses, 1889, Vincent van Gogh, Dutch",
)

loadcolorscheme(
    :VanGogh2,
    [
        colorant"#bd3106",
        colorant"#d9700e",
        colorant"#e9a00e",
        colorant"#eebe04",
        colorant"#5b7314",
        colorant"#c3d6ce",
        colorant"#89a6bb",
        colorant"#454b87",
    ],
    "MetBrewer",
    "Self-Portrait with a Straw Hat (obverse: The Potato Peeler), 1887, Vincent van Gogh, Dutch",
)

loadcolorscheme(
    :VanGogh3,
    [
        colorant"#e7e5cc",
        colorant"#c2d6a4",
        colorant"#9cc184",
        colorant"#669d62",
        colorant"#447243",
        colorant"#1f5b25",
        colorant"#1e3d14",
        colorant"#192813",
    ],
    "MetBrewer",
    "First Steps, after Millet, 1890, Vincent van Gogh, Dutch, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Veronese,
    [
        colorant"#67322e",
        colorant"#99610a",
        colorant"#c38f16",
        colorant"#6e948c",
        colorant"#2c6b67",
        colorant"#175449",
        colorant"#122c43",
    ],
    "MetBrewer",
    "Mars and Venus United by Love, 1570s, Paolo Veronese, Italian, cvd friendly, color blind friendly",
)

loadcolorscheme(
    :Wissing,
    [
        colorant"#4b1d0d",
        colorant"#7c291e",
        colorant"#ba7233",
        colorant"#3a4421",
        colorant"#2d5380",
    ],
    "MetBrewer",
    "Portrait of a Woman, 1687, Willem Wissing, Dutch",
)

ext: jl

max_stars_repo_name: cormullion/ColorSchemes

max_issues_repo_name: cormullion/ColorSchemes

max_forks_repo_name: cormullion/ColorSchemes


text:
# UnitCommitment.jl: Optimization Package for Security-Constrained Unit Commitment
# Copyright (C) 2020, UChicago Argonne, LLC. All rights reserved.
# Released under the modified BSD license. See COPYING.md for more details.

using UnitCommitment, LinearAlgebra, Cbc, JuMP, JSON, GZip

@testset "slice" begin
    instance = UnitCommitment.read_benchmark("test/case14")
    modified = UnitCommitment.slice(instance, 1:2)

    # Should update all time-dependent fields
    @test modified.time == 2
    @test length(modified.power_balance_penalty) == 2
    @test length(modified.reserves.spinning) == 2
    for u in modified.units
        @test length(u.max_power) == 2
        @test length(u.min_power) == 2
        @test length(u.must_run) == 2
        @test length(u.min_power_cost) == 2
        @test length(u.provides_spinning_reserves) == 2
        for s in u.cost_segments
            @test length(s.mw) == 2
            @test length(s.cost) == 2
        end
    end
    for b in modified.buses
        @test length(b.load) == 2
    end
    for l in modified.lines
        @test length(l.normal_flow_limit) == 2
        @test length(l.emergency_flow_limit) == 2
        @test length(l.flow_limit_penalty) == 2
    end
    for ps in modified.price_sensitive_loads
        @test length(ps.demand) == 2
        @test length(ps.revenue) == 2
    end

    # Should be able to build model without errors
    optimizer = optimizer_with_attributes(Cbc.Optimizer, "logLevel" => 0)
    model = UnitCommitment.build_model(
        instance = modified,
        optimizer = optimizer,
        variable_names = true,
    )
end


text:
struct Equation{DT <: Number, FT <: Function}
    f::FT
    x₀::Array{DT,2}

    function Equation(f::FT, x₀::AbstractArray{DT,2}) where {DT,FT}
        new{DT,FT}(f, Array(x₀))
    end
end

ndims(equ::Equation) = length(axes(equ.x₀,1))
nsamples(equ::Equation) = length(axes(equ.x₀,2))

max_stars_repo_name: michakraus/JuliaAtHomeAssignments

max_issues_repo_name: michakraus/JuliaAtHomeAssignments

max_forks_repo_name: michakraus/JuliaAtHomeAssignments


text:
# ---
# title: 1008. Construct Binary Search Tree from Preorder Traversal
# id: problem1008
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Tree
# link: <https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/description/>
# hidden: true
# ---
#
# Return the root node of a binary **search** tree that matches the given
# `preorder` traversal.
#
# _(Recall that a binary search tree  is a binary tree where for every node, any
# descendant of `node.left` has a value `<` `node.val`, and any descendant of
# `node.right` has a value `>` `node.val`.  Also recall that a preorder
# traversal displays the value of the `node` first, then traverses `node.left`,
# then traverses `node.right`.)_
#
# It's guaranteed that for the given test cases there is always possible to find
# a binary search tree with the given requirements.
#
# **Example 1:**
#
#
#
#     Input: [8,5,1,7,10,12]
#     Output: [8,5,10,1,7,null,12]
#     ![](https://assets.leetcode.com/uploads/2019/03/06/1266.png)
#
#
#
#
# **Constraints:**
#
#   * `1 <= preorder.length <= 100`
#   * `1 <= preorder[i] <= 10^8`
#   * The values of `preorder` are distinct.
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
function save_result!(res::AbstractString;
        data = nothing,
        comment::Union{Void,AbstractString} = nothing,
        sources::Union{Void,Vector} = nothing,
        new_version::Bool = false,
        overwrite::Bool = false,
        version_num::Union{Void,Int} = nothing)

    # Repo
    repo = parse_repo(res);

    # Chekig keywords
    if overwrite && new_version error("'overwrite' and 'new_version' can't be both true!!!") end
    if new_version && version_num != nothing
        error("'new_version' can't be true if you specify a 'version_num'!!!") end

    # Creating or updating
    if Core.repo_exist(repo) # repo_exist (true)
        if overwrite # overwrite (true)
            update_res_repo!(repo, data, comment, sources);
            println("Repo $(repo.res_dir) updated!!!");
            return repo;
        else # overwrite (false)
            error("Repo $(repo.res_dir) already exist, "*
                "Use 'overwrite' keyword for update it!!!");
        end # end overwrite
    else # repo_exist (false)
        if Core.has_versions(repo) # has_versions (true)
            if new_version # new_version (true)
                create_res_repo!(repo, data, comment, sources);
                println("New version of '$(repo.res_name)' created: $(repo.res_dir)!!!")
                return repo;
            else # new_version (false)
                if version_num != nothing # given version_num (true)
                    version = get_version(repo.res_name, version_num);
                    update_res_repo!(version, data, comment, sources);
                    println("Update repo version $(version_num): $(version.res_dir)")
                    return version;
                else # given version_num (false)
                    if overwrite # overwrite (true)
                        last_version = get_last_version(repo.res_name);
                        update_res_repo!(last_version, data, comment, sources);
                        println("Updated last version: $(last_version.res_dir)");
                        return last_version;
                    else # overwrite (false)
                        error("Res name '$(repo.res_name)' has many versions, "*
                                "Use 'overwrite' keyword for update the last one, or "*
                                "the 'version_num' keyword to specify the version number you "*
                                "wants to update!!!.")
                    end # end overwrite
                end # end given version_num
            end # end new version
        else # has_versions (false)
            create_res_repo!(repo, data, comment, sources);
            println("New version of '$(repo.res_name)' created: $(repo.res_dir)!!!")
            return repo;
        end # end has_versions
    end # end repo_exist
end

function update_res_repo!(res_repo, data, comment, sources)

    # desc
    res_desc = Core.load_res_desc(res_repo);
    Core.add_desc_log_line!(res_desc, "-----------------------");
    Core.add_desc_log_line!(res_desc, "Updating Repo!!!");
    change = false;

    # data
    if data != nothing
        Core.save_res_data!(res_repo, data);
        Core.add_desc_log_line!(res_desc, "Data size, after update: $(sizeof(data)) byte(s)");
        change = true;
    end

    # desc_comment
    if comment != nothing
        if comment != Core.get_desc_comment(res_desc)
            Core.set_desc_comment!(res_desc, comment);
            Core.add_desc_log_line!(res_desc, "New comment: $(comment)");
            change = true;
        end
    end

    # sources
    if sources != nothing
        Core.set_res_source!(res_repo, sources);
        Core.add_desc_log_line!(res_desc, "Sources updated, links: $(sources)");
        change = true;
    end

    !change && Core.add_desc_log_line!(res_desc, "Nothing updated!!!");
    Core.save_res_desc!(res_repo, res_desc);
end

function create_res_repo!(new_repo, data, comment, sources)

    # Cheking
    if new_repo.time_tag <= Core.find_used_max_time_tag(working_dir);
        error("Something was wrong with the time_tag!!! "*
        "The currect system time is not compatible with the time_tags of "*
        " the stored res repos!!!"); end
    if data == nothing error("nothing to save!!!, use the 'data' "*
        "keyword to save somthing different to nothing") end

    # Description
    res_desc = Core.ResDesc();
    if comment == nothing comment = "Nothing to comment!!!" end
    Core.set_desc_comment!(res_desc, comment);
    Core.add_desc_log_line!(res_desc, "REPO CREATED!!!");
    Core.add_desc_log_line!(res_desc, "First Comment: $(comment)");
    Core.add_desc_log_line!(res_desc, "Data size: $(sizeof(data)) byte(s)");
    Core.add_desc_log_line!(res_desc, "Sources linked: $(sources)");

    # Creating
    mkpath(new_repo.res_dir);
    mkpath(new_repo.source_dir);
    Core.save_res_desc!(new_repo, res_desc);
    Core.save_res_data!(new_repo, data);
    sources != nothing && Core.set_res_source!(new_repo, sources);
    return new_repo;
end


text:
#EasyPlot display facilities
#-------------------------------------------------------------------------------

#==Types
===============================================================================#
const PlotOrColl = Union{Plot, PlotCollection}

abstract type AbstractPlotDisplay{T<:AbstractBuilder} <: AbstractDisplay end

struct GUIDisplay{T} <: AbstractPlotDisplay{T}
	builder::T
end

#Not implemented:
#-------------------------------------------------------------------------------
struct FileDisplay{T} <: AbstractPlotDisplay{T}; end #Render image to file
struct SocketDisplay{T} <: AbstractPlotDisplay{T}; end #Render image to listener (is there a useful protocol for this?)
#Find way to only load GUI libraries if needed:
struct WindowDisplay{T} <: AbstractPlotDisplay{T}; end #Render image to a pop-up window

#==Constructors
===============================================================================#
GUIDisplay(builderid::Symbol, args...; kwargs...) =
	GUIDisplay(getbuilder(:gui, builderid, args...; kwargs...))

#==displaygui() interface (user-facing)
===============================================================================#
#`displaygui()` used instead of `Base.display` so as to not break Juila display system.

displaygui(nativeplot::T) where T =
	throw("displaygui: no support for plots of type $T.")

function displaygui(b::AbstractBuilder, pcoll::PlotCollection)
	plotgui = displaygui(build(b, pcoll))
	postproc(b, plotgui)
end
function displaygui(b::AbstractBuilder, plot::Plot)
	plotgui = displaygui(b, push!(PlotCollection(ncolumns = 1), plot))
	postproc(b, plotgui)
end

displaygui(bid::Symbol, plot::PlotOrColl) =
	displaygui(GUIDisplay(bid).builder, plot)

function displaygui(plot::PlotOrColl)
	if isnothing(defaults.guibuilder)
		@warn("EasyPlot.defaults.guibuilder not initialized.")
		return
	end
	displaygui(defaults.guibuilder, plot)
end

#==Implement Base.display() interface:
===============================================================================#
Base.display(d::GUIDisplay, plot::PlotOrColl) = displaygui(d.builder, plot)

#Last line


text:
include("DataFS.jl")
include("ConstantsFS.jl")
include("StateFS.jl")
include("TunersFS.jl")

include("update_p_feature_select.jl")
include("update_omega_feature_select.jl")
include("update_W_feature_select.jl")
include("update_r_feature_select.jl")
include("update_lam_feature_select.jl")

include("compute_marg_loglike.jl")
include("update_feature_select.jl")
include("fit_feature_select.jl")

include("swap_chains.jl")
include("fit_feature_select_pt.jl")

include("sample_minibatch.jl")
include("update_via_trained_prior.jl")
include("fit_feature_select_train_prior.jl")
include("fit_feature_select_imcmc_pt.jl")


text:
function sieve(limit::Integer)

end


text:
function serialize_instance!(db::SQLite.DB, serialize_path, graphs_path, name, scenario, source_type, source_path)
    println("Serializing instance network and graph: ($name, $scenario)")
    pfn_path = abspath(joinpath(serialize_path, "$(name)_$(scenario)_network.bin"))
    graph_path = abspath(joinpath(graphs_path, "$(name)_$(scenario)_graph.lgz"))
    network = PowerFlowNetwork(source_path, source_type)
    g = SimpleGraph(network)
    serialize(pfn_path, network)
    savegraph(graph_path, g)
    query = "UPDATE instances SET pfn_path = '$pfn_path', graph_path = '$graph_path' WHERE name = '$name' AND scenario = $scenario"
    execute_query(db, query)
end

function serialize_instance_dfrow!(db::SQLite.DB, serialize_path, graphs_path, row)
    serialize_instance!(db, serialize_path, graphs_path, row[:name], row[:scenario], row[:source_type], row[:source_path])
end

function serialize_instances!(db::SQLite.DB;
                              serialize_path, graphs_path,
                              min_nv=typemin(Int), max_nv=typemax(Int), recompute=false,
                              subset=nothing)
    !isdir(serialize_path) && mkpath(serialize_path)
    !isdir(graphs_path) && mkpath(graphs_path)
    query = "SELECT name, scenario, source_type, source_path FROM instances WHERE nbus >= $min_nv AND nbus <= $max_nv"
    if !recompute
        query *= " AND (pfn_path IS NULL OR graph_path IS NULL)"
    end
    if !isnothing(subset)
        query *= " AND id IN ($(join(subset, ',')))"
    end
    println("Serialize instance network and graph config: min_nv=$min_nv, max_nv=$max_nv, recompute=$recompute")
    println("subset\n$subset\nend subset")
    results = DBInterface.execute(db, query) |> DataFrame
    serialize_function!(row) = serialize_instance_dfrow!(db, serialize_path, graphs_path, row)
    serialize_function!.(eachrow(results[!, [:name, :scenario, :source_type, :source_path]]))
end

max_stars_repo_name: charlyalizadeh/PowerFlowNetworks

max_issues_repo_name: charlyalizadeh/PowerFlowNetworks

max_forks_repo_name: charlyalizadeh/PowerFlowNetworks


text:
#####################################
## Bayesian logistic regression demo

using PyPlot, PyCall
using Distributions
push!(LOAD_PATH, ".")
import LogisticRegression

"""
Visualize prediction via surface (only for 2D inputs.)
"""
function visualize_surface(mu, rho, X, Y, text)
    N = 100
    R = 100
    xmin = minimum(X[1,:])
    xmax = maximum(X[1,:])
    ymin = minimum(X[2,:])
    ymax = maximum(X[2,:])
    lx = xmax - xmin
    ly = ymax - ymin
    xmin = xmin - 0.25 * lx
    xmax = xmax + 0.25 * lx
    ymin = ymin - 0.25 * ly
    ymax = ymax + 0.25 * ly

    x1 = linspace(xmin,xmax,R)
    x2 = linspace(ymin,ymax,R)
    x1grid = repmat(x1, 1, R)
    x2grid = repmat(x2', R, 1)
    val = [x1grid[:] x2grid[:]]'

    z_list = []
    sigma = log.(1 + exp.(rho))
    for n in 1 : N
        W = rand(MvNormal(mu, diagm(sigma.^2)))
        z_tmp = [LogisticRegression.sigmoid(W'*val[:,i]) for i in 1 : size(val, 2)]
        push!(z_list, z_tmp)
    end
    z = mean(z_list)
    zgrid = reshape(z, R, R)

    # 3D plot
    figure("surface")
    clf()
    plot_surface(x1grid, x2grid, zgrid, alpha=0.5)
    scatter3D(X[1,Y.==1], X[2,Y.==1], Y[Y.==1]+0.01, c="r", depthshade=true)
    scatter3D(X[1,Y.==0], X[2,Y.==0], Y[Y.==0], c="b", depthshade=true)
    xlim([xmin, xmax])
    ylim([ymin, ymax])
    zlim([0, 1])
    title(text)
end

"""
Visualize prediction via contour (only for 2D inputs.)
"""
function visualize_contour(mu, rho, X, Y)
    N = 100
    R = 100
    xmin = 2*minimum(X[1,:])
    xmax = 2*maximum(X[1,:])
    ymin = minimum(X[2,:])
    ymax = maximum(X[2,:])

    x1 = linspace(xmin,xmax,R)
    x2 = linspace(ymin,ymax,R)
    x1grid = repmat(x1, 1, R)
    x2grid = repmat(x2', R, 1)
    val = [x1grid[:] x2grid[:]]'

    z_list = []
    W_list = []
    sigma = log.(1 + exp.(rho))
    for n in 1 : N
        W = rand(MvNormal(mu, diagm(sigma.^2)))
        z_tmp = [LogisticRegression.sigmoid(W'*val[:,i]) for i in 1 : size(val, 2)]
        push!(W_list, W)
        push!(z_list, z_tmp)
    end
    z = mean(z_list)
    zgrid = reshape(z, R, R)

    # precition
    figure("contour")
    clf()
    contour(x1grid, x2grid, zgrid, alpha=0.5, cmap=get_cmap("bwr"))
    scatter(X[1,Y.==1], X[2,Y.==1], c="r")
    scatter(X[1,Y.==0], X[2,Y.==0], c="b")
    xlim([xmin, xmax])
    ylim([ymin, ymax])
    title("prediction")

    # parameter samples
    figure("samples")
    clf()
    for n in 1 : 10
        draw_line(W_list[n], xmin, xmax)
    end
    scatter(X[1,Y.==1]', X[2,Y.==1]', c="r")
    scatter(X[1,Y.==0]', X[2,Y.==0]', c="b")
    xlim([xmin, xmax])
    ylim([ymin, ymax])
    title("parameter samples")
end

function draw_line(W, xmin, xmax)
    y1 = - xmin*W[1]/W[2]
    y2 = - xmax*W[1]/W[2]
    plot([xmin, xmax], [y1, y2], c="k")
end

########################
# create model

M = 2 # input dimension
Sigma_w = 100.0 * eye(M) # prior on W

########################
# create toy-data using prior model

N = 50 # num of data points
X = 2 * rand(M, N) - 1.0 # input values

# sample observation Y
Y, _ = LogisticRegression.sample_data(X, Sigma_w)

########################
# inference
alpha = 1.0e-4 # learning rate
max_iter = 100000 # VI maximum iterations

# learn variational parameters (mu & rho)
mu, rho = LogisticRegression.VI(Y, X, M, Sigma_w, alpha, max_iter)

########################
# visualize (only for M=2)
visualize_surface(mu, rho, X, Y, "prediction")
visualize_contour(mu, rho, X, Y)
show()


text:
include(joinpath(pwd(), "src/direct_policy_optimization/dpo.jl"))
include(joinpath(@__DIR__, "rocket_nominal.jl"))
include(joinpath(@__DIR__, "rocket_slosh.jl"))

# DPO
N = 2 * model_slosh.n
D = 2 * model_slosh.d

β = 1.0
δ = 1.0e-3

# initial samples
x1_sample = resample(x1_slosh, Diagonal(ones(model_slosh.n)), 1.0e-3)

prob_nom = prob_nominal.prob

# mean problem
prob_mean = trajectory_optimization(
				model_slosh,
				EmptyObjective(),
				T,
				dynamics = false,
				con = con_free_time
				)

# sample problems
prob_sample = [trajectory_optimization(
				model_slosh,
				EmptyObjective(),
				T,
				xl = state_bounds(model_slosh, T, x1 = x1_sample[i])[1],
				xu = state_bounds(model_slosh, T, x1 = x1_sample[i])[2],
				ul = ul,
				uu = uu,
				dynamics = false,
				con = con_free_time
				) for i = 1:N]

# sample objective
Q = [(t < T ? Diagonal([1.0; 10.0; 1.0; 1.0; 10.0; 1.0])
	: Diagonal([10.0; 100.0; 10.0; 10.0; 100.0; 10.0])) for t = 1:T]
R = [Diagonal([1.0e-1; 1.0e-1; 1.0]) for t = 1:T-1]

obj_sample = sample_objective(Q, R)
policy = linear_feedback(6, 2,
	idx_input = collect([1, 2, 3, 5, 6, 7]),
	idx_input_nom = (1:6),
	idx_output = (1:2))
dist = disturbances([Diagonal(δ * ones(model_slosh.n)) for t = 1:T-1])
sample = sample_params(β, T)

prob_dpo = dpo_problem(
	prob_nom, prob_mean, prob_sample,
	obj_sample,
	policy,
	dist,
	sample)

# TVLQR policy
X̄_nom, Ū_nom = unpack(Z̄, prob_nominal)
X̄_slosh, Ū_slosh = unpack(Z̄_slosh, prob_slosh)

K = tvlqr(model_nom, X̄_nom, Ū_nom, Q, R, 0.0)

z0_dpo = zeros(prob_dpo.num_var)
z0_dpo[prob_dpo.prob.idx.nom] = pack(X̄_nom, Ū_nom, prob_nom)
z0_dpo[prob_dpo.prob.idx.mean] = pack(X̄_slosh, Ū_slosh, prob_slosh)
for i = 1:N
	z0_dpo[prob_dpo.prob.idx.sample[i]] = pack(X̄_slosh, Ū_slosh, prob_slosh)
end
for j = 1:(N + D)
	z0_dpo[prob_dpo.prob.idx.slack[j]] = vcat(X̄_slosh[2:end]...)
end
for t = 1:T-1
	z0_dpo[prob_dpo.prob.idx.policy[prob_dpo.prob.idx.θ[t]]] = vec(copy(K[t]))
end

include("/home/taylor/.julia/dev/SNOPT7/src/SNOPT7.jl")

# Solve
Z = solve(prob_dpo, copy(z0_dpo),
	nlp = :SNOPT7,
	tol = 1.0e-2, c_tol = 1.0e-2,
	time_limit = 60 * 60 * 12)

# TVLQR policy
Q_lqr = [(t < T ? Diagonal([100.0*ones(nq_nom); 100.0*ones(nq_nom)])
   : Diagonal([1000.0*ones(nq_nom); 1000.0*ones(nq_nom)])) for t = 1:T]
R_lqr = [Diagonal(1.0*ones(model_nom.nu)) for t = 1:T-1]
H_lqr = [100.0 for t = 1:T-1]

K = TVLQR_gains(model_nom,X_nom,U_nom,[H_nom[1] for t = 1:T-1],Q_lqr,R_lqr)

# Simulate TVLQR (no slosh)
using Distributions

model_sim = model_nom
x1_sim = copy(x1)
T_sim = 10*T

W = Distributions.MvNormal(zeros(model_sim.nx),
	Diagonal(1.0e-5*ones(model_sim.nx)))
w = rand(W,T_sim)

W0 = Distributions.MvNormal(zeros(model_sim.nx),
	Diagonal(1.0e-5*ones(model_sim.nx)))
w0 = rand(W0,1)

z0_sim = vec(copy(x1_sim) + w0)

t_nom = range(0,stop=sum(H_nom),length=T)
t_sim_nom = range(0,stop=sum(H_nom),length=T_sim)

# simulate
z_tvlqr, u_tvlqr, J_tvlqr, Jx_tvlqr, Ju_tvlqr = simulate_linear_controller(K,
    X_nom,U_nom,model_sim,Q_lqr,R_lqr,T_sim,H_nom[1],z0_sim,w,_norm=2,
	ul=ul,uu=uu)

# plot states
plt_x = plot(t_nom,hcat(X_nom...)[1:model_nom.nx,:]',
	legend=:topright,color=:red,
    label="",width=2.0,xlabel="time (s)",
    title="Rocket",ylabel="state")
plt_x = plot!(t_sim_nom,hcat(z_tvlqr...)[1:model_nom.nx,:]',color=:black,label="",
    width=1.0)

# plot COM
plot_traj = plot(hcat(X_nom...)[1,:],hcat(X_nom...)[2,:],
	legend=:topright,color=:red,
    label="",width=2.0,xlabel="y",ylabel="z",
    title="Rocket")
plot_traj = plot!(hcat(z_tvlqr...)[1,:],hcat(z_tvlqr...)[2,:],
	color=:black,
    label="",width=1.0)

plot(t_nom[1:end-1],hcat(U_nom...)',
	linetype=:steppost,color=:red,width=2.0)
plot!(t_sim_nom[1:end-1],hcat(u_tvlqr...)',
	linetype=:steppost,color=:black,width=1.0)

# objective value
J_tvlqr

# state tracking
Jx_tvlqr

# control tracking
Ju_tvlqr

# Fuel-slosh model
x1_slosh = [x1[1:3];0.0;x1[4:6]...;0.0]
xT_slosh = [xT[1:3];0.0;xT[4:6]...;0.0]

# optimize slosh model

# xl <= x <= xl
xl_slosh = -Inf*ones(model_slosh.nx)
xl_slosh[2] = model_slosh.l1
xu_slosh = Inf*ones(model_slosh.nx)

xl_traj_slosh = [copy(xl_slosh) for t = 1:T]
xu_traj_slosh = [copy(xu_slosh) for t = 1:T]

xl_traj_slosh[1] = copy(x1_slosh)
xu_traj_slosh[1] = copy(x1_slosh)

xl_traj_slosh[T] = copy(xT_slosh)
xu_traj_slosh[T] = copy(xT_slosh)

xl_traj_slosh[T][4] = -Inf
xu_traj_slosh[T][4] = Inf

xl_traj_slosh[T][8] = -Inf
xu_traj_slosh[T][8] = Inf

xl_traj_slosh[T][1] = -r_pad
xu_traj_slosh[T][1] = r_pad
xl_traj_slosh[T][2] = xT[2]-0.001
xu_traj_slosh[T][2] = xT[2]+0.001
xl_traj_slosh[T][3] = -1.0*pi/180.0
xu_traj_slosh[T][3] = 1.0*pi/180.0
xl_traj_slosh[T][5] = -0.001
xu_traj_slosh[T][5] = 0.001
xl_traj_slosh[T][6] = -0.001
xu_traj_slosh[T][6] = 0.001
xl_traj_slosh[T][7] = -0.01*pi/180.0
xu_traj_slosh[T][7] = 0.01*pi/180.0

Q_slosh = [(t != T ? Diagonal([1.0;10.0;1.0;0.1;1.0;10.0;1.0;0.1])
    : Diagonal([10.0;100.0;10.0;0.1;10.0;100.0;10.0;0.1])) for t = 1:T]
obj_slosh = QuadraticTrackingObjective(Q_slosh,R,c,
    [xT_slosh for t=1:T],[zeros(model_slosh.nu) for t=1:T])

# Problem
prob_slosh = init_problem(model_slosh.nx,model_slosh.nu,T,model_slosh,obj_slosh,
                    xl=xl_traj_slosh,
                    xu=xu_traj_slosh,
                    ul=[ul for t=1:T-1],
                    uu=[uu for t=1:T-1],
                    hl=[hl for t=1:T-1],
                    hu=[hu for t=1:T-1],
                    )

# MathOptInterface problem
prob_moi_slosh = init_MOI_Problem(prob_slosh)

# Trajectory initialization
X0_slosh = linear_interp(x1_slosh,xT_slosh,T) # linear interpolation on state
U0_slosh = [ones(model_slosh.nu) for t = 1:T-1] # random controls

# Pack trajectories into vector
Z0_slosh = pack(X0_slosh,U0_slosh,h0,prob_slosh)

#NOTE: may need to run examples multiple times to get good trajectories
# Solve nominal problem
@time Z_nominal_slosh = solve(prob_moi_slosh,copy(Z0_slosh),nlp=:SNOPT7,time_limit=300)
X_nom_slosh, U_nom_slosh, H_nom_slosh = unpack(Z_nominal_slosh,prob_slosh)

plot(hcat(U_nom_slosh...)',linetype=:steppost)
sum(H_nom_slosh) # should be 2.73/2.76
sum(H_nom) # should be 2.72

# simulate slosh with TVLQR controller from nominal model
model_sim = model_slosh
W = Distributions.MvNormal(zeros(model_sim.nx),Diagonal(0.0*ones(model_sim.nx)))
w = rand(W,T_sim)

W0 = Distributions.MvNormal(zeros(model_sim.nx),Diagonal(0.0*ones(model_sim.nx)))
w0 = rand(W0,1)

x1_slosh_sim = x1_slosh
z0_sim = vec(copy(x1_slosh_sim) + w0)

t_nom = range(0,stop=sum(H_nom),length=T)
t_sim_nom = range(0,stop=sum(H_nom),length=T_sim)
dt_sim_nom = sum(H_nom)/(T_sim-1)

z_tvlqr, u_tvlqr, J_tvlqr, Jx_tvlqr, Ju_tvlqr = simulate_linear_controller(K,
    X_nom,U_nom,model_sim,Q_lqr,R_lqr,T_sim,H_nom[1],z0_sim,w,_norm=2,
	controller=:policy,ul=ul,uu=uu)

plt_x = plot(t_nom,hcat(X_nom...)[1:model_nom.nx,:]',
	legend=:topright,color=:red,
    label="",width=2.0,xlabel="time (s)",
    title="Rocket",ylabel="state")
plt_x = plot!(t_sim_nom,hcat(z_tvlqr...)[[(1:3)...,(5:7)...],:]',
	color=:black,label="",
    width=1.0)

plot_traj = plot(hcat(X_nom...)[1,:],hcat(X_nom...)[2,:],
	legend=:topright,color=:red,
    label="",width=2.0,xlabel="y",ylabel="z",
    title="Rocket")
plot_traj = plot!(hcat(z_tvlqr...)[1,:],hcat(z_tvlqr...)[2,:],
	color=:black,
    label="",width=1.0)

# objective value
J_tvlqr

# state tracking
Jx_tvlqr

# control tracking
Ju_tvlqr

visualize!(vis,model_slosh,z_tvlqr,Δt=dt_sim_nom)

# DPO
N = 2*model_slosh.nx
models = [model_slosh for i = 1:N]
β = 1.0
w = 1.0e-3*ones(model_slosh.nx)
γ = N

x1_sample = resample([x1_slosh for i = 1:N],β=β,w=w)

xl_traj_sample = [[-Inf*ones(model_slosh.nx) for t = 1:T] for i = 1:N]
xu_traj_sample = [[Inf*ones(model_slosh.nx) for t = 1:T] for i = 1:N]

for i = 1:N
    xl_traj_sample[i][1] = copy(x1_sample[i])
    xu_traj_sample[i][1] = copy(x1_sample[i])

	# xl_traj_sample[i][T] = copy(xT_slosh)
	# xu_traj_sample[i][T] = copy(xT_slosh)

	# xl_traj_sample[i][T][4] = -Inf
	# xu_traj_sample[i][T][4] = Inf
	#
	# xl_traj_sample[i][T][8] = -Inf
	# xu_traj_sample[i][T][8] = Inf
	#
	# xl_traj_sample[i][T][1] = -0.25
	# xu_traj_sample[i][T][1] = 0.25
	# xl_traj_sample[i][T][2] = xT[2]-0.01
	# xu_traj_sample[i][T][2] = xT[2]+0.01
	# xl_traj_sample[i][T][3] = -1.0*pi/180.0
	# xu_traj_sample[i][T][3] = 1.0*pi/180.0
	# xl_traj_sample[i][T][5] = -0.001
	# xu_traj_sample[i][T][5] = 0.001
	# xl_traj_sample[i][T][6] = -0.001
	# xu_traj_sample[i][T][6] = 0.001
	# xl_traj_sample[i][T][7] = -0.01*pi/180.0
	# xu_traj_sample[i][T][7] = 0.01*pi/180.0
end

ul_traj_sample = [[-Inf*ones(model_slosh.nu) for t = 1:T-1] for i = 1:N]
uu_traj_sample = [[Inf*ones(model_slosh.nu) for t = 1:T-1] for i = 1:N]

prob_sample = init_sample_problem(prob_nom,models,Q_lqr,R_lqr,H_lqr,
	β=β,w=w,γ=γ,
    xl=xl_traj_sample,
    xu=xu_traj_sample,
    n_features=model_slosh.nx-2,
    )

prob_sample_moi = init_MOI_Problem(prob_sample)

Z0_sample = zeros(prob_sample_moi.n)

Z0_sample[prob_sample.idx_nom_z] = pack(X_nom,U_nom,H_nom[1],prob_nom)

for t = 1:T
	for i = 1:N
		Z0_sample[prob_sample.idx_sample[i].x[t]] = X_nom_slosh[t]
		t==T && continue
		Z0_sample[prob_sample.idx_sample[i].u[t]] = U_nom_slosh[t]
		Z0_sample[prob_sample.idx_sample[i].h[t]] = H_nom_slosh[1]
		Z0_sample[prob_sample.idx_x_tmp[i].x[t]] = X_nom_slosh[t+1]
	end
end

for t = 1:T-1
	Z0_sample[prob_sample.idx_K[t]] = vec(K[t])
end

# Solve
# Z_sample_sol = solve(prob_sample_moi,copy(Z0_sample),nlp=:SNOPT7,
# 	time_limit=60*60,tol=1.0e-2,c_tol=1.0e-2)
#
using JLD
# @save joinpath(pwd(),"examples/trajectories/","rocket_fuel_slosh.jld") Z_sample_sol
@load joinpath(pwd(),"examples/trajectories/","rocket_fuel_slosh.jld") Z_sample_sol

X_nom_sample, U_nom_sample, H_nom_sample, X_sample, U_sample, H_sample = unpack(Z_sample_sol,prob_sample)
sum(H_nom_sample) # should be 2.89/2.9
sum(H_nom)

# get policy
Θ = [Z_sample_sol[prob_sample.idx_K[t]] for t = 1:T-1]
Θ_mat = [reshape(Θ[t],model_nom.nu,model_nom.nx) for t = 1:T-1]
t_nom_sample = range(0,stop=sum(H_nom_sample),length=T)
t_sim_nom_sample = range(0,stop=sum(H_nom_sample),length=T_sim)

dt_sim_sample = sum(H_nom_sample)/(T_sim-1)

W = Distributions.MvNormal(zeros(model_sim.nx),Diagonal(0.0*ones(model_sim.nx)))
w = rand(W,T_sim)

W0 = Distributions.MvNormal(zeros(model_sim.nx),Diagonal(0.0*ones(model_sim.nx)))
w0 = rand(W0,1)

z0_sim = vec(copy(x1_slosh_sim) + w0)

z_tvlqr, u_tvlqr, J_tvlqr, Jx_tvlqr, Ju_tvlqr = simulate_linear_controller(K,
    X_nom,U_nom,model_sim,Q_lqr,R_lqr,T_sim,H_nom[1],z0_sim,w,_norm=2,
	controller=:policy,ul=ul,uu=uu)

plt_x = plot(t_nom,hcat(X_nom...)[1:model_nom.nx,:]',legend=:topright,color=:red,
    label="",width=2.0,xlabel="time (s)",
    title="Rocket",ylabel="state")
plt_x = plot!(t_sim_nom,hcat(z_tvlqr...)[[(1:3)...,(5:7)...],:]',color=:black,label="",
    width=1.0)

plot_traj = plot(hcat(X_nom...)[1,:],hcat(X_nom...)[2,:],legend=:topright,color=:red,
    label="",width=2.0,xlabel="y",ylabel="z",
    title="Rocket")
plot_traj = plot!(hcat(z_tvlqr...)[1,:],hcat(z_tvlqr...)[2,:],color=:black,
    label="",width=1.0)

z_sample, u_sample, J_sample, Jx_sample, Ju_sample= simulate_linear_controller(Θ,
    X_nom_sample,U_nom_sample,model_sim,Q_lqr,R_lqr,T_sim,H_nom_sample[1],z0_sim,
	w,_norm=2,
	controller=:policy,ul=ul,uu=uu)

plt_x = plot(t_nom_sample,hcat(X_nom_sample...)[1:model_nom.nx,:]',legend=:topright,color=:red,
    label="",width=2.0,xlabel="time (s)",
    title="Rocket",ylabel="state")
plt_x = plot!(t_sim_nom_sample,hcat(z_sample...)[[(1:3)...,(5:7)...],:]',color=:black,label="",
    width=1.0)

plot_traj = plot(hcat(X_nom_sample...)[1,:],hcat(X_nom_sample...)[2,:],legend=:topright,color=:red,
    label="",width=2.0,xlabel="y",ylabel="z",
    title="Rocket")
plot_traj = plot!(hcat(z_sample...)[1,:],hcat(z_sample...)[2,:],color=:black,
    label="",width=1.0)

# objective value
J_sample
J_tvlqr

# state tracking
Jx_sample
Jx_tvlqr

# control tracking
Ju_sample
Ju_tvlqr

plot_traj = plot(hcat(X_nom...)[1,:],hcat(X_nom...)[2,:],legend=:topright,color=:cyan,
    label="",width=2.0,xlabel="y",ylabel="z",
    title="Rocket")

plot_traj = plot!(hcat(X_nom_sample...)[1,:],hcat(X_nom_sample...)[2,:],legend=:topright,color=:orange,
    label="",width=2.0,xlabel="y",ylabel="z",
    title="Rocket")

for i = 1:N
	plot_traj = plot!(hcat(X_sample[i]...)[1,:],hcat(X_sample[i]...)[2,:],label="")
end
display(plot_traj)

# orientation tracking
plt_x = plot(t_nom,hcat(X_nom...)[3,:],legend=:topright,color=:red,
    label="",width=2.0,xlabel="time (s)",
    title="Rocket",ylabel="state")
plt_x = plot!(t_sim_nom,hcat(z_tvlqr...)[3,:],color=:black,label="",
    width=1.0)

plt_x = plot(t_nom_sample,hcat(X_nom_sample...)[3,:],legend=:topright,color=:red,
    label="",width=2.0,xlabel="time (s)",
    title="Rocket",ylabel="state")
plt_x = plot!(t_sim_nom_sample,hcat(z_sample...)[3,:],color=:black,label="",
    width=1.0)

sum(H_nom_sample)
sum(H_nom)

visualize!(vis,model_nom,z_tvlqr,Δt=dt_sim_nom)
visualize!(vis,model_nom,z_sample,Δt=dt_sim_sample)
using PGFPlots
const PGF = PGFPlots

p_traj_nom = PGF.Plots.Linear(hcat(X_nom...)[1,:],hcat(X_nom...)[2,:],
	mark="",style="color=cyan, line width = 2pt",legendentry="TO")
p_traj_sample = PGF.Plots.Linear(hcat(X_nom_sample...)[1,:],hcat(X_nom_sample...)[2,:],
	mark="",style="color=orange, line width = 2pt",legendentry="DPO")

a = Axis([p_traj_nom;p_traj_sample],
    axisEqualImage=false,
    hideAxis=false,
	ylabel="z",
	xlabel="y",
	legendStyle="{at={(0.01,0.99)},anchor=north west}",
	)

# Save to tikz format
dir = joinpath(@__DIR__,"results")
PGF.save(joinpath(dir,"rocket_traj.tikz"), a, include_preamble=false)

# orientation tracking
plt_x = plot(t_nom,hcat(X_nom...)[3,:],legend=:topright,color=:red,
    label="",width=2.0,xlabel="time (s)",
    title="Rocket",ylabel="state")
plt_x = plot!(t_sim_nom,hcat(z_tvlqr...)[3,:],color=:black,label="",
    width=1.0)

plt_x = plot(t_nom_sample,hcat(X_nom_sample...)[3,:],legend=:topright,color=:red,
    label="",width=2.0,xlabel="time (s)",
    title="Rocket",ylabel="state")
plt_x = plot!(t_sim_nom_sample,hcat(z_sample...)[3,:],color=:black,label="",
    width=1.0)

p_nom_orientation = PGF.Plots.Linear(t_nom,hcat(X_nom...)[3,:],
	mark="",style="color=cyan, line width = 2pt",legendentry="TO")
p_nom_sim_orientation = PGF.Plots.Linear(t_sim_nom,hcat(z_tvlqr...)[3,:],
	mark="",style="color=black, line width = 1pt")

p_sample_orientation = PGF.Plots.Linear(t_nom_sample,hcat(X_nom_sample...)[3,:],
	mark="",style="color=orange, line width = 2pt",legendentry="DPO")
p_sample_sim_orientation = PGF.Plots.Linear(t_sim_nom_sample,hcat(z_sample...)[3,:],
	mark="",style="color=black, line width = 1pt")

a = Axis([p_nom_orientation;p_nom_sim_orientation],
    axisEqualImage=false,
    hideAxis=false,
	ylabel="orientation",
	xlabel="time",
	legendStyle="{at={(0.5,0.99)},anchor=north}",
	)

# Save to tikz format
dir = joinpath(@__DIR__,"results")
PGF.save(joinpath(dir,"rocket_tvlqr_orientation.tikz"), a, include_preamble=false)

a = Axis([p_sample_orientation;p_sample_sim_orientation],
    axisEqualImage=false,
    hideAxis=false,
	ylabel="orientation",
	xlabel="time",
	legendStyle="{at={(0.5,0.99)},anchor=north}",
	)

# Save to tikz format
dir = joinpath(@__DIR__,"results")
PGF.save(joinpath(dir,"rocket_dpo_orientation.tikz"), a, include_preamble=false)

# eigen value analysis
C = Diagonal(ones(model_slosh.nx))[1:model_nom.nx,:]
# nominal
A_nom, B_nom = nominal_jacobians(model_nom,X_nom,U_nom,H_nom)
A_nom_cl = [(A_nom[t] - B_nom[t]*K[t]) for t = 1:T-1]
sv_nom = [norm.(eigen(A_nom_cl[t]).values) for t = 1:T-1]
plt_nom = plot(hcat(sv_nom...)',xlabel="time step t",ylabel="eigen value norm",
	title="TVLQR nominal model",linetype=:steppost,
	ylims=(-3,3),labels="")

# slosh nominal
X_nom_slosh = [[copy(X_nom[t]);0.0;0.0] for t = 1:T]
A_nom_slosh, B_nom_slosh = nominal_jacobians(model_slosh,X_nom_slosh,U_nom,H_nom)
A_nom_slosh_cl = [(A_nom_slosh[t] - B_nom_slosh[t]*K[t]*C) for t = 1:T-1]
sv_nom_slosh = [norm.(eigen(A_nom_slosh_cl[t]).values) for t = 1:T-1]
plt_nom_slosh = plot(hcat(sv_nom_slosh...)',xlabel="time step t",ylabel="eigen value norm",
	title="TVLQR slosh model",linetype=:steppost,
	ylims=(-3,3),labels="")

# slosh
A_dpo, B_dpo = nominal_jacobians(model_nom,X_nom_sample,U_nom_sample,H_nom_sample)
A_dpo_cl = [(A_dpo[t] - B_dpo[t]*Θ_mat[t]) for t = 1:T-1]
sv_dpo = [norm.(eigen(A_dpo_cl[t]).values) for t = 1:T-1]
plt_dpo_nom = plot(hcat(sv_dpo...)',xlabel="time step t",ylabel="singular value",
	title="DPO nominal model",linetype=:steppost,
	ylims=(-1,3),labels="")

X_dpo_slosh = [[copy(X_nom_sample[t]);0.0;0.0] for t = 1:T]
A_dpo_slosh, B_dpo_slosh = nominal_jacobians(model_slosh,X_dpo_slosh,U_nom_sample,H_nom_sample)
A_dpo_slosh_cl = [(A_dpo_slosh[t] - B_dpo_slosh[t]*Θ_mat[t]*C) for t = 1:T-1]
sv_dpo_slosh = [norm.(eigen(A_dpo_slosh_cl[t]).values) for t = 1:T-1]
plt_dpo_slosh = plot(hcat(sv_dpo_slosh...)',xlabel="time step t",ylabel="eigen value norm",
	title="DPO slosh model",linetype=:steppost,
	ylims=(-1.0,3.0),labels="")

plot(plt_nom,plt_dpo_nom,layout=(2,1))

plot(plt_nom_slosh,plt_dpo_slosh,layout=(2,1))

plot(t_nom,hcat(X_nom...)[1:6,:]',color=:cyan,label=["y" "z" "ϕ"])
plot!(t_nom_sample, hcat(X_nom_sample...)[1:6,:]',color=:orange,label=["y" "z" "ϕ"])

max_stars_repo_name: zacmanchester/DirectMotionPlanning

max_issues_repo_name: zacmanchester/DirectMotionPlanning

max_forks_repo_name: zacmanchester/DirectMotionPlanning


text:
mutable struct MultiPtsTurningDriver <: MultiPtsDriver
    Δt::Float64
    siji::AccSteerDriver
    N::Int #number of points
    Pts::Matrix{Float64}  # 2×N
    steermax::Float64 # pi/2;
    steerdotmax::Float64 # 20;
    accmax::Float64 # 10;

    commands::Array{Float64} #4x1
    index::Int
    subindex::Int
    laneNum_desire::Int
    acc_desire::Float64
    v_desire::Float64
    v_max::Float64 #20m/s
    v_min::Float64 #0
    turning_direction::Int

    color::Colorant

    MultiPtsTurningDriver(Δt::Float64; siji::AccSteerDriver=AccSteerDriver(0.0,0.0),N::Int=20,Pts::Matrix{Float64}=zeros(2,20),steermax::Float64=pi/4,steerdotmax::Float64=20.0,accmax::Float64=10.0,commands::Array{Float64}=zeros(4),index::Int=0,subindex::Int=0,laneNum_desire::Int=1,acc_desire::Float64=0.0,v_desire::Float64=0.0,v_max::Float64=20.0,v_min::Float64=0.0,turning_direction::Int=1,color::Colorant=RGB(1, 0, 0))=new(Δt,siji,N,Pts,steermax,steerdotmax,accmax,commands,index,subindex,laneNum_desire,acc_desire,v_desire,v_max,v_min,turning_direction,color)
end

AutomotiveDrivingModels.get_name(model::MultiPtsTurningDriver) = "MultiPtsTurningDriver"

Base.rand(model::MultiPtsTurningDriver) = rand(model.siji)
Distributions.pdf(model::MultiPtsTurningDriver, a::Float64) = a == model.siji.acc ? Inf : 0.0
Distributions.logpdf(model::MultiPtsTurningDriver, a::Float64) = a == model.siji.acc ? Inf : -Inf

function excute_action!(model::MultiPtsTurningDriver,acc::Float64,direction::Int,scene::Union{Scene,Frame{Entity{VehicleState, BicycleModel, Int}}}, roadway::Roadway, ego_index::Int)
    veh=scene[ego_index]
    laneNum=veh.state.posF.roadind.tag.lane
    model.acc_desire=acc
    model.laneNum_desire=laneNum+direction
    model.v_desire=veh.state.v
    model.index=0
    model.subindex=0
end

function set_pts!(model::MultiPtsTurningDriver,PtsIn::Matrix{Float64})
    model.Pts=PtsIn
    model.index=0
    model.subindex=0
    model
end

function AutomotiveDrivingModels.observe!(model::MultiPtsTurningDriver, scene::Union{Scene,Frame{Entity{VehicleState, BicycleModel, Int}}}, roadway::Roadway, egoid::Int)
    ego_index = findfirst(scene, egoid)
    get_acc_steer!(model,scene,roadway,ego_index)
    model
end

function get_acc_steer!(model::MultiPtsTurningDriver,scene::Union{Scene,Frame{Entity{VehicleState, BicycleModel, Int}}}, roadway::Roadway, ego_index::Int)
    if model.index==6 || model.index>model.N
    #if model.index>model.N
        #println("index reach ", model.index)
        set_lane_changing_pts_with_direction!(model, scene, roadway, ego_index,model.turning_direction)
    end
    if model.index==0
        #println("index is 0!")
        set_lane_changing_pts_with_direction!(model, scene, roadway, ego_index,model.turning_direction)
    else
        if model.subindex==0
            #compute new command
            get_commands!(model,scene, roadway,ego_index)
            model.siji.acc=model.commands[1]
            model.siji.steer=model.commands[3]
            model.siji.direction=model.turning_direction
            model.subindex=1
        elseif model.subindex==1
            #follow the commands
            model.siji.acc=model.commands[2]
            model.siji.steer=model.commands[4]
            model.siji.direction=model.turning_direction
            model.subindex=0
            model.index=model.index+1
        end
    end
end


text:
# Disjoint-Set

############################################################
#
#   A forest of disjoint sets of integers
#
#   Since each element is an integer, we can use arrays
#   instead of dictionary (for efficiency)
#
#   Disjoint sets over other key types can be implemented
#   based on an IntDisjointSet through a map from the key
#   to an integer index
#
############################################################
_intdisjointset_bounds_err_msg(T) = "the maximum number of elements in IntDisjointSet{$T} is $(typemax(T))"

abstract type Scalarness end
struct Scalar <: Scalarness end
struct NotScalar <: Scalarness end

isscalar(::Type{Any}) = NotScalar() # if we don't know the type we can't really know if scalar or not
isscalar(::Type{<:AbstractString}) = NotScalar() # We consider strings to be nonscalar
isscalar(::Type{<:Number}) = Scalar() # We consider Numbers to be scalar
isscalar(::Type{Char}) = Scalar() # We consider Character to be scalar
isscalar(::Type{Symbol}) = Scalar()
isscalar(::Type{T}) where T = hasmethod(iterate, (T,)) ? NotScalar() : Scalar()
"""
    IntDisjointSet{T<:Integer}(n::Integer)
A forest of disjoint sets of integers, which is a data structure
(also called a union–find data structure or merge–find set)
that tracks a set of elements partitioned
into a number of disjoint (non-overlapping) subsets.
"""
mutable struct IntDisjointSet{T<:Integer}
    parents::Vector{T}
    ranks::Vector{T}
    ngroups::T
end

IntDisjointSet(n::T) where {T<:Integer} = IntDisjointSet{T}(collect(Base.OneTo(n)), zeros(T, n), n)
IntDisjointSet{T}(n::Integer) where {T<:Integer} = IntDisjointSet{T}(collect(Base.OneTo(T(n))), zeros(T, T(n)), T(n))
Base.length(s::IntDisjointSet) = length(s.parents)

"""
    num_groups(s::IntDisjointSet)
Get a number of groups.
"""
num_groups(s::IntDisjointSet) = s.ngroups
Base.eltype(::Type{IntDisjointSet{T}}) where {T<:Integer} = T

# find the root element of the subset that contains x
# path compression is implemented here
function find_root_impl!(parents::Vector{T}, x::Integer) where {T<:Integer}
    p = parents[x]
    @inbounds if parents[p] != p
        parents[x] = p = _find_root_impl!(parents, p)
    end
    return p
end

# unsafe version of the above
function _find_root_impl!(parents::Vector{T}, x::Integer) where {T<:Integer}
    @inbounds p = parents[x]
    @inbounds if parents[p] != p
        parents[x] = p = _find_root_impl!(parents, p)
    end
    return p
end

"""
    find_root!(s::IntDisjointSet{T}, x::T)
Find the root element of the subset that contains an member x.
Path compression is implemented here.
"""
find_root!(s::IntDisjointSet{T}, x::T) where {T<:Integer} = find_root_impl!(s.parents, x)

"""
    in_same_set(s::IntDisjointSet{T}, x::T, y::T)
Returns `true` if `x` and `y` belong to the same subset in `s` and `false` otherwise.
"""
in_same_set(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer} = find_root!(s, x) == find_root!(s, y)

"""
    union!(s::IntDisjointSet{T}, x::T, y::T)
Merge the subset containing x and that containing y into one
and return the root of the new set.
"""
function Base.union!(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer}
    parents = s.parents
    xroot = find_root_impl!(parents, x)
    yroot = find_root_impl!(parents, y)
    xroot != yroot ? root_union!(s, xroot, yroot) : xroot
end

"""
    root_union!(s::IntDisjointSet{T}, x::T, y::T)
Form a new set that is the union of the two sets whose root elements are
x and y and return the root of the new set.
Assume x ≠ y (unsafe).
"""
function root_union!(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer}
    parents = s.parents
    rks = s.ranks
    @inbounds xrank = rks[x]
    @inbounds yrank = rks[y]

    if xrank < yrank
        x, y = y, x
    elseif xrank == yrank
        rks[x] += one(T)
    end
    @inbounds parents[y] = x
    s.ngroups -= one(T)
    return x
end

"""
    push!(s::IntDisjointSet{T})
Make a new subset with an automatically chosen new element x.
Returns the new element. Throw an `ArgumentError` if the
capacity of the set would be exceeded.
"""
function Base.push!(s::IntDisjointSet{T}) where {T<:Integer}
    l = length(s)
    l < typemax(T) || throw(ArgumentError(_intdisjointset_bounds_err_msg(T)))
    x = l + one(T)
    push!(s.parents, x)
    push!(s.ranks, zero(T))
    s.ngroups += one(T)
    return x
end

"""
    DisjointSet{T}(xs)
A forest of disjoint sets of arbitrary value type T.
It is a wrapper of IntDisjointSet{Int}, which uses a
dictionary to map the input value to an internal index.
"""
mutable struct DisjointSet{T} <: AbstractSet{T}
    intmap::Dict{T,Int}
    revmap::Vector{T}
    internal::IntDisjointSet{Int}
    DisjointSet{T}() where T = new{T}(Dict{T,Int}(), Vector{T}(), IntDisjointSet(0))

    function DisjointSet{T}(xs) where T    # xs must be iterable
        imap = Dict{T,Int}()
        rmap = Vector{T}()
        if(typeof(isscalar(typeof(xs)))!=Scalar)
            n = length(xs)
            sizehint!(imap, n)
            sizehint!(rmap, n)
            id = 0
            for x in xs
                imap[x] = (id += 1)
                push!(rmap,x)
            end
            new{T}(imap, rmap, IntDisjointSet(n))
        else
            id = 0
            imap[xs] = (id += 1)
            push!(rmap,xs)
            new{T}(imap, rmap, IntDisjointSet(1))

        end
    end
end

DisjointSet() = DisjointSet{Any}()
DisjointSet(xs) = _DisjointSet(xs, Base.IteratorEltype(xs))
_DisjointSet(xs, ::Base.HasEltype) = DisjointSet{eltype(xs)}(xs)
function _DisjointSet(xs, ::Base.EltypeUnknown)
    T = Base.@default_eltype(xs)
    (isconcretetype(T) || T === Union{}) || return Base.grow_to!(DisjointSet{T}(), xs)
    return DisjointSet{T}(xs)
end

Base.iterate(s::DisjointSet) = iterate(s.revmap)
Base.iterate(s::DisjointSet, i) = iterate(s.revmap, i)

Base.length(s::DisjointSet) = length(s.internal)

"""
    num_groups(s::DisjointSet)
Get a number of groups.
"""
num_groups(s::DisjointSet) = num_groups(s.internal)
Base.eltype(::Type{DisjointSet{T}}) where T = T
Base.empty(s::DisjointSet{T}, ::Type{U}=T) where {T,U} = DisjointSet{U}()
function Base.sizehint!(s::DisjointSet, n::Integer)
    sizehint!(s.intmap, n)
    sizehint!(s.revmap, n)
    return s
end

"""
    find_root!{T}(s::DisjointSet{T}, x::T)
Finds the root element of the subset in `s` which has the element `x` as a member.
"""
find_root!(s::DisjointSet{T}, x::T) where {T} = s.revmap[find_root!(s.internal, s.intmap[x])]

"""
    in_same_set(s::DisjointSet{T}, x::T, y::T)
Returns `true` if `x` and `y` belong to the same subset in `s` and `false` otherwise.
"""
in_same_set(s::DisjointSet{T}, x::T, y::T) where {T} = in_same_set(s.internal, s.intmap[x], s.intmap[y])

"""
    union!(s::DisjointSet{T}, x::T, y::T)
Merge the subset containing x and that containing y into one
and return the root of the new set.
"""
Base.union!(s::DisjointSet{T}, x::T, y::T) where {T} = s.revmap[union!(s.internal, s.intmap[x], s.intmap[y])]

"""
    root_union!(s::DisjointSet{T}, x::T, y::T)
Form a new set that is the union of the two sets whose root elements are
x and y and return the root of the new set.
Assume x ≠ y (unsafe).
"""
root_union!(s::DisjointSet{T}, x::T, y::T) where {T} = s.revmap[root_union!(s.internal, s.intmap[x], s.intmap[y])]

"""

    push!(s::DisjointSet{T}, x::T)
Make a new subset with an automatically chosen new element x.
Returns the new element.

"""
function Base.push!(s::DisjointSet{T}, x::T) where T
    haskey(s.intmap, x) && return x
    id = push!(s.internal)
    s.intmap[x] = id
    push!(s.revmap, x) # Note, this assumes invariant: length(s.revmap) == id
    return x
end


text:
"""
A `MultiDict` is the concatenation of several dictionaries. The components are contained
in an indexable set, such as a tuple or an array. In case of an array, the number
of dictionaries may be large.

The native representation of a `MultiDict` is a `BlockVector`, of which each element
is the native representation of the corresponding element of the multidict.

Evaluation of an expansion at a point is defined by summing the evaluation of all
functions in the set at that point.
"""
struct MultiDict{DICTS,S,T} <: CompositeDict{S,T}
    dicts   ::  DICTS
    offsets ::  Vector{Int}

    function MultiDict{DICTS,S,T}(dicts) where {DICTS,S,T}
        offsets = compute_offsets(dicts)
        new(dicts, offsets)
    end
end

# Is this constructor type-stable? Probably not, even if T is given, because
# of the use of dimension below.
function MultiDict(dicts, S, T)
    for dict in dicts
        # Is this the right check here?
        @assert promote_type(domaintype(dict), S) == S
        @assert promote_type(codomaintype(dict), T) == T
    end
    MultiDict{typeof(dicts),S,T}(dicts)
end

function MultiDict(dicts)
    S = reduce(promote_type, map(domaintype, dicts))
    T = reduce(promote_type, map(codomaintype, dicts))
    C = reduce(promote_type, map(coefficienttype, dicts))
    MultiDict(map(dict->ensure_coefficienttype(C, dict), dicts), S, T)
end

similardictionary(set::MultiDict, dicts) = MultiDict(dicts)

multidict(dict::Dictionary) = dict

# When manipulating multidicts, we create Array's of dicts by default
multidict(d1::Dictionary, d2::Dictionary) = MultiDict([d1,d2])
multidict(d1::MultiDict, d2::MultiDict) = MultiDict(vcat(components(d1), components(d2)))
multidict(d1::MultiDict, d2::Dictionary) = MultiDict(vcat(components(d1), d2))
multidict(d1::Dictionary, d2::MultiDict) = MultiDict(vcat(d1, components(d2)))

multidict(d1::Dictionary, d2::Dictionary, dicts::Dictionary...) =
    multidict(multidict(d1,d2), dicts...)

function multidict(dicts::AbstractArray)
    if length(dicts) == 1
        multidict(dicts[1])
    else
        MultiDict(flatten(MultiDict, dicts, Dictionary{domaintype(dicts[1]),codomaintype(dicts[1])}))
    end
end

multispan(spans::Span...) = Span(multidict(map(dictionary, spans)...))

multispan(spans::AbstractArray) = Span(multidict(map(dictionary, spans)))

# Perhaps we don't want this behaviour, that [b;b] creates a MultiDict, rather
# than an array of Dictionary's
# vcat(s1::Dictionary, s2::Dictionary) = multidict(s1,s2)

vcat(dicts::Dictionary...) = multidict(dicts...)
⊕(dicts::Dictionary...) = multidict(dicts...)

for op in (:isbasis, :isframe)
    # Redirect the calls to multiple_isbasis with the elements as extra arguments,
    # and that method can decide whether the property holds for the multidict.
    fname = Symbol("multiple_$(op)")
    @eval $op(s::MultiDict) = ($fname)(s, components(s)...)
    # By default, multidicts do not have these properties:
    @eval ($fname)(s, components...) = false
end

for op in (:isorthogonal, :isbiorthogonal)
    # Redirect the calls to multiple_isbasis with the elements as extra arguments,
    # and that method can decide whether the property holds for the multidict.
    fname = Symbol("multiple_$(op)")
    @eval $op(s::MultiDict, m::Measure) = ($fname)(s, m, components(s)...)
    # By default, multidicts do not have these properties:
    @eval ($fname)(s, m::Measure, components...) = false
end

for op in (:hasinterpolationgrid, :hastransform)
    fname = Symbol("multiple_$(op)")
    @eval $op(s::MultiDict) = ($fname)(s, components(s)...)
    @eval ($fname)(s, components...) = false
end

# Try to return ranges of an underlying set, if possible
function sub(dict::MultiDict, idx::OrdinalRange{Int})
    i1 = multilinear_index(dict, first(idx))
    i2 = multilinear_index(dict, last(idx))
    # Check whether the range lies fully in one set
    if outerindex(i1) == outerindex(i2)
        sub(component(dict, outerindex(i1)), innerindex(i1):step(idx):innerindex(i2))
    else
        defaultsub(dict, idx)
    end
end

for op in (:support, :moment, :norm)
    @eval $op(set::MultiDict, idx::Int) = $op(set, multilinear_index(set, idx))
    # Pass along a linear or a native index to the subset
    @eval function $op(set::MultiDict, idx::Union{MultilinearIndex,Tuple{Int,Any}})
        $op(set.dicts[outerindex(idx)], innerindex(idx))
    end
end

support(set::MultiDict) = union(map(support,components(set))...)

measure(dict::MultiDict) = measure(component(dict, 1))

resize(d::MultiDict, n::Int) = resize(d, approx_length(d, n))

approx_length(d::MultiDict, n::Int) = ceil(Int, n/ncomponents(d)) * ones(Int,ncomponents(d))

## Differentiation

diff(Φ::MultiDict, order; options...) =
    multidict([diff(dict, order; options...) for dict in components(Φ)]...)
derivative_dict(Φ::MultiDict, order; options...) =
    MultiDict(map(d-> derivative_dict(d, order; options...), components(Φ)))

antiderivative_dict(Φ::MultiDict, order; options...) =
    MultiDict(map(d-> antiderivative_dict(d, order; options...), components(Φ)))

for op in (:differentiation, :antidifferentiation)
    @eval function $op(::Type{T}, src::MultiDict, dest::MultiDict, order; options...) where {T}
        if ncomponents(src) == ncomponents(dest)
            BlockDiagonalOperator{T}([$op(component(src,i), component(dest, i), order; options...) for i in 1:ncomponents(src)], src, dest)
        else
            # We have a situation because the sizes of the multidicts don't match.
            # The derivative set may have been a nested multidict that was flattened. This
            # case occurs for example in multidicts involving an AugmentedSet, because the
            # derivative of a single AugmentedSet may be a MultiDict.
            # The problem is we don't know which elements of src to match with which elements of dest.
            # Resolve the situation by looking at the standard derivative sets of each element of src.
            # This may not be correct if one of the elements has multiple derivative sets, and
            # the user had chosen a non-standard one.
            ops = DictionaryOperator{T}[$op(el, order; options...) for el in components(src)]
            BlockDiagonalOperator{T}(ops, src, dest)
        end
    end
end

evaluation(::Type{T}, dict::MultiDict, gb::GridBasis, grid::AbstractGrid; options...) where {T} =
    block_row_operator( DictionaryOperator{T}[evaluation(T, el, gb, grid; options...) for el in components(dict)], dict, gb)

function gramdual(dict::MultiDict, measure::Measure; options...)
    @debug "Are you sure you want `gramdual` and not `weightedsumdual`?"
    default_gramdual(dict, measure; options...)
end

## Rescaling

mapped_dict(s::MultiDict, m) = multidict(map( t-> mapped_dict(t, m), components(s)))

## Projecting
function project(s::MultiDict, f::Function; options...)
    Z = BlockArray{T}(undef,[length(e) for e in components(s)])
    for (i,el) in enumerate(components(s))
        Z[Block(i)] = project(el, f; options...)
        # setblock!(Z, project(el, f; options...), i)
    end
    Z
end

## Printing

Display.combinationsymbol(d::MultiDict) = Display.Symbol('⊕')


text:
# Bogumił Kamiński, 2019-03-25

using DelimitedFiles, Random

Random.seed!(1234)
x = rand(10, 10)

open("x.txt", "w") do f
    writedlm(f, x)
end

x2 = readdlm("x.txt")

max_stars_repo_path: 8. IO/ioexample_2.jl

max_issues_repo_path: 8. IO/ioexample_2.jl

max_forks_repo_path: 8. IO/ioexample_2.jl


text:
function _population(pop::Population, ids)
  x = Float64[]
  y = Float64[]
  for i in ids
    push!(x, pop.risks[i, :x])
    push!(y, pop.risks[i, :y])
  end
  return x, y
end

function _ids_by_state(events::Events{T},
                       state::DiseaseState,
                       time::Float64) where T <: DiseaseStateSequence
  if time < 0.0
    @error "Time must be ≥ 0.0"
  elseif state ∉ convert(DiseaseStates, T)
    @error "Invalid state specified"
  end
  ids = Int64[]
  if state == convert(DiseaseStates, T)[1] # S
    nextstate = advance(state, T) # Either E or I
    append!(ids, findall(events[nextstate] .> Ref(time))) # E/I after `time`
    append!(ids, findall(isnan.(events[nextstate]))) # Never E/I
  elseif state in convert(DiseaseStates, T)[2:end-1]
    nextstate = advance(state, T) # Either I or R
    append!(ids, findall((events[state] .<= Ref(time)) .& (events[nextstate] .> Ref(time)))) # E/I at or before time and I/R after time
    append!(ids, findall((events[state] .<= Ref(time)) .& isnan.(events[nextstate]))) # E/I at or before time and never I/R
  elseif state == convert(DiseaseStates, T)[end] # I or R
    append!(ids, findall(events[state] .<= Ref(time))) # I/R at or before time
  end
  @debug "Individual(s) in state $state at t = $time" Individuals = ids
  return ids
end

@recipe function f(pop::Population)
  xguide --> ""
  yguide --> ""
  legend --> :none
  xlims --> extrema(pop.risks[!, :x]) .+ (sum(extrema(pop.risks[!, :x]).*(-1,1)) .* (-0.05, 0.05))
  ylims --> extrema(pop.risks[!, :y]) .+ (sum(extrema(pop.risks[!, :y]).*(-1,1)) .* (-0.05, 0.05))
  aspect_ratio := :equal
  seriestype := :scatter
  markerstrokecolor --> :black
  markercolor --> :black
  markersize --> 2.75
  axis --> nothing
  titlefontcolor --> :black
  framestyle --> :none
  _population(pop, 1:individuals(pop))
end

@recipe function f(pop::Population,
                   events::Events{S},
                   time::Float64) where S <: DiseaseStateSequence
  xguide --> ""
  yguide --> ""
  legend --> :topright
  xlims --> extrema(pop.risks[!, :x]) .+ (sum(extrema(pop.risks[!, :x]).*(-1,1)) .* (-0.05, 0.05))
  ylims --> extrema(pop.risks[!, :y]) .+ (sum(extrema(pop.risks[!, :y]).*(-1,1)) .* (-0.05, 0.05))
  aspect_ratio := :equal
  markerstrokecolor --> :black
  markersize --> 2.75
  axis --> nothing
  framestyle --> :none
  seriestype := :scatter
  for s in convert(Tuple, S)
    @series begin
      label --> convert(Char, s)
      markercolor --> _state_color(s)
      _population(pop, _ids_by_state(events, s, time))
    end
  end
end


text:
using CompScienceMeshes
using Test

#include(Pkg.dir("CompScienceMeshes","examples","matlab_patches.jl"))
for T in [Float32, Float64]
    sphere = readmesh(joinpath(dirname(@__FILE__),"assets","sphere2.in"),T=T)
    index_in_sphere = mapper(sphere)
    for (i,_c) in enumerate(cells(sphere))
        @eval @test $index_in_sphere[$_c] == $i
    end

    isdownbelow(c) = center(chart(sphere,c))[3] < 0
    southern_hemisphere = submesh(isdownbelow, sphere)

    # build the restriction operator
    R = spzeros(Int, numcells(southern_hemisphere), numcells(sphere))
    for (i,_c) in enumerate(cells(southern_hemisphere))
        j = index_in_sphere[_c]
        R[i,j] = 1
    end

    @test nnz(R) == numcells(southern_hemisphere)

    rect = meshrectangle(T(1.0), T(1.0), T(1.0), 3)
    @test numcells(rect) == 2
    tri = Mesh(rect.vertices, rect.faces[1:1])
    @test numcells(tri) == 1

    R = restriction(tri, rect)
    @test R == [1 0]
end

max_stars_repo_name: krcools/CompScienceMeshes

max_issues_repo_name: krcools/CompScienceMeshes

max_forks_repo_name: krcools/CompScienceMeshes


text:
# les N reines

# renvoie l'entier 00...0011..11 (n bits faibles à n)
# c'est-à-dire l'ensemble {0,1,...,n-1}
# version inefficace de ^(^0 << n)
function full(n)
    if n == 0
	0
    else
	full(n-1) * 2 + 1
    end
end

# le plus petit élément de x
# version inefficace de x & -x
function lowestbit(x)
    if x == 1
	1
    else
	2 * lowestbit(div(x, 2))
    end
end

# différence ensembliste
# version inefficace de x &^ y
function andnot(x, y)
    if x == 0
	return 0
    end
    z = 2 * andnot(div(x, 2), div(y, 2))
    if x % 2 == 1 && y % 2 == 0
	z + 1
    else
	z
    end
end

function t(a, b, c)
    if a == 0
	return 1
    end
    f = 0;
    e = andnot(andnot(a, b), c)
    while e > 0
	d = lowestbit(e)
	f = f + t(a - d, (b+d)*2, div(c+d,2))
	e = e - d
    end
    f
end

function queens(n)
    t(full(n), 0, 0)
end

for n = 0:10
    print(n)
    print(" ")
    print(queens(n))
    print("\n")
end

max_stars_repo_name: gabriel-doriath-dohler/pjulia

max_issues_repo_name: gabriel-doriath-dohler/pjulia

max_forks_repo_name: gabriel-doriath-dohler/pjulia