licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
102
include("fixedwings/fixedwings.jl") include("actuators/actuators.jl") include("missiles/missiles.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
319
using FSimZoo using Test using FSimBase function main() t = 0.0 ΞΆ = 0.7 Ο‰ = 150 env = SecondOrderActuator(ΞΆ, Ο‰) x1, x2 = rand(2) X = State(env)(x1, x2) Ξ΄_cmd = 0.0 dX = deepcopy(X) Dynamics!(env)(dX, X, [], t; Ξ΄_cmd=Ξ΄_cmd) end @testset "SecondOrderActuator" begin main() end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
34
include("SecondOrderActuator.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
557
using FSimZoo using Test using FSimBase function test_elzebdawingrock() t = 0.0 env = ElzebdaWingRock() x1, x2 = rand(2) X = State(env)(x1, x2) u = 0.0 dX = deepcopy(X) Dynamics!(env)(dX, X, [], t; u=u) end function test_tarnwingrock() t = 0.0 env = TarnWingRock() x1, x2 = deg2rad.(10*rand(2)) X = State(env)(x1, x2) u = 0.0 dX = deepcopy(X) Dynamics!(env)(dX, X, [], t; u=u) end function main() test_elzebdawingrock() test_tarnwingrock() end @testset "wingrock" begin main() end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
260
using FSimZoo using Test using FSimBase function main() env = MissileLongitudinal() t = 0.0 X = State(env)() Ξ΄ = deg2rad(10) dX = deepcopy(X) Dynamics!(env)(dX, X, [], t; Ξ΄=Ξ΄) end @testset "MissileLongitudinal" begin main() end
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
code
34
include("MissileLongitudinal.jl")
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
docs
1485
### Changes in v0.11 - The state variable of multicopter has changed from DCM to unit quaternion. - Conversion to other rotation representations are now supported (e.g., `quat2dcm`, `dcm2euler`, `euler2quat`, etc.). # Changes in v0.4.0 - `GeometricTrackingController` is added for multicopter position/attitude tracking control. - Dependency `UnPack` is removed. # Changes in v0.3.7 - `BacksteppingPositionController`'s transient response is improved (faster) by adjusting the parameters of reference model (`RefModel`) - `LeeHexacopter`'s rotor limit is changed following the reference (written in the code). # Changes in v0.3.5 - A new discrete-time system, `TwoDimensionalNonlinearDTSystem`, is now added. # Changes in v0.3.4 - `TwoDimensionalNonlinearPolynomialSystem` is now `@Loggable`. # Changes in v0.3.3 - The interface of `TwoDimensionalNonlinearOscillator` has been changed; the input `u` is now an `Array`, e.g., `[1.0]`, not a `Number`. # Changes in v0.3.2 - Environments are added and made to be loggable (thanks to [@hnlee77](https://github.com/hnlee77)!). - `SingleIntegrator` - `LinearSystem_SingleIntegrator` # Changes in v0.3.1 - Bug fix: `TwoDimensionalNonlinearOscillator <: AbstractEnv` # Changes in v0.3.0 - `TwoDimensionalNonlinearOscillator` is added. # Changes in v0.2.0 - Predefined stuffs' names are changed. # Changes in v0.1.0 - Environments and controllers are detached from [FlightSims.jl](https://github.com/JinraeKim/FlightSims.jl).
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.11.1
8d0c82db196a2d46506d4433996b11f35edf3041
docs
3168
# FSimZoo [FSimZoo.jl](https://github.com/JinraeKim/FSimZoo.jl) contains predefined environments and controllers for [FlightSims.jl](https://github.com/JinraeKim/FlightSims.jl). ## Breaking changes in v0.11 See `NEWS.md`. ## Examples - Examples include <details> <summary>basics</summary> - (Linear system) `LinearSystem` - (A simple integrator) `SingleIntegrator` - (Reference model) `ReferenceModel` - (Nonlinear polynomial system) `TwoDimensionalNonlinearPolynomialSystem` - [T. Bian and Z.-P. Jiang, β€œValue Iteration, Adaptive Dynamic Programming, and Optimal Control of Nonlinear Systems,” in 2016 IEEE 55th Conference on Decision and Control (CDC), Las Vegas, NV, USA, Dec. 2016, pp. 3375–3380. doi: 10.1109/CDC.2016.7798777.](https://ieeexplore.ieee.org/document/7798777) - (Nonlinear oscillator) `TwoDimensionalNonlinearOscillator` - [J. A. Primbs, β€œNonlinear Optimal Control: A Receding Horizon Approach,” California Institute of Technology, Pasadena, California, 1999.](https://thesis.library.caltech.edu/4124/) - (Multiple Envs) `MultipleEnvs` for multi-agent simulation </details> <details> <summary>Actuators</summary> - `SecondOrderActuator` </details> <details> <summary>fixed wings</summary> - (Wing Rock phenomenon) `TarnWingRock`, `ElzebdaWingRock` </details> <details> <summary>multicopters</summary> - (Hexacopter) `LeeHexacopter`, `LeeQuadcopter`, `GoodarziAgileQuadcopter` (**currently maintained**) - (Quadcopter) `IslamQuadcopter`, `GoodarziQuadcopter` </details> <details> <summary>allocators</summary> - (Moore-Penrose pseudo inverse control allocation) `PseudoInverseAllocator` </details> <details> <summary>controllers</summary> - (Linear quadratic regulator) `LQR` - (Proportional-Integral-Derivative controller) `PID` - Note that the derivative term is obtained via second-order filter. - (Pure proportional navigation guidance) `PPNG` - (For multicopter position tracking) - `BacksteppingPositionController` (control input: `T_dot`, `M`) - `GeometricTrackingController` (control input: `T`, `M`) - `InnerLoopGeometricTrackingController` and `OuterLoopGeometricTrackingController` (based on `GeometricTrackingController` but seperated for a hierarchical structure) - (Safety filters via control barrier functions (CBFs)) - (Position CBF for input-affine systems) `InputAffinePositionCBF` </details> <details> <summary>integrated_environments</summary> - (Backstepping Position Controller + Static Allocator + Multicopter) `BacksteppingPositionController_StaticAllocator_Multicopter` - For example, `BacksteppingPositionController` (backstepping position controller) + `PseudoInverseAllocator` (pseudo-inverse allocator, a static allocator) + `LeeHexacopter` (hexacopter, a multicopter) - (Linear system + single integrator) `LinearSystem_SingleIntegrator` (WIP) - See `src/environments/integrated_environments`. </details> ## Utilities - `ned2enu` and `enu2ned`: coordinate transformation
FSimZoo
https://github.com/JinraeKim/FSimZoo.jl.git
[ "MIT" ]
0.1.1
f147af01d49f3fb0fb3eca72f0719a76ea87e984
code
93
push!(LOAD_PATH, "../src/") using Documenter, KiteConnect makedocs(sitename="KiteConnect")
KiteConnect
https://github.com/arcofdescent/KiteConnect.jl.git
[ "MIT" ]
0.1.1
f147af01d49f3fb0fb3eca72f0719a76ea87e984
code
1470
""" KiteConnect Julia module to interface with Zerodha's KiteConnect API """ module KiteConnect export init, gen_access_token using HTTP using JSON using SHA const API_ENDPOINT = "https://api.kite.trade" API_KEY = "" API_SECRET = "" ACCESS_TOKEN = "" """ `init(api_key::String, api_secret::String)` Setup your KiteConnect session by providing your API key and API secret which you get from Zerodha """ function init(api_key::String, api_secret::String) global API_KEY = api_key global API_SECRET = api_secret end function get_http_headers() [ "X-Kite-Version" => "3", "Authorization" => "token $API_KEY:$ACCESS_TOKEN", ] end function http_get(url_fragment::String) url = "$API_ENDPOINT/$url_fragment" r = HTTP.request("GET", url, get_http_headers()) r.body |> String |> JSON.parse end """ `gen_access_token(request_token::String)` Generate the access token by passing in yout request token """ function gen_access_token(request_token::String) checksum = (API_KEY * request_token * API_SECRET) |> sha256 |> bytes2hex url = "$API_ENDPOINT/session/token" headers = [ "X-Kite-Version" => "3", "Content-Type" => "application/x-www-form-urlencoded", ] body = "api_key=$API_KEY&request_token=$request_token&checksum=$checksum" res = HTTP.request("POST", url, headers, body) r = res.body |> String |> JSON.parse global ACCESS_TOKEN = r["data"]["access_token"] end include("quote.jl") export ltp end # module
KiteConnect
https://github.com/arcofdescent/KiteConnect.jl.git
[ "MIT" ]
0.1.1
f147af01d49f3fb0fb3eca72f0719a76ea87e984
code
437
""" ltp(instrument::String) Get LTP of trading symbol `instrument` should be in EXCHANGE:TRADINGSYMBOL format, eg. "NSE:INFY" """ function ltp(instrument::String) parts = split(instrument, ":") if (length(parts) != 2) throw(ArgumentError("instrument should be in EXCHANGE:TRADINGSYMBOL format")) end url_fragment = "quote/ltp?i=$instrument" res = http_get(url_fragment) res["data"][instrument]["last_price"] end
KiteConnect
https://github.com/arcofdescent/KiteConnect.jl.git
[ "MIT" ]
0.1.1
f147af01d49f3fb0fb3eca72f0719a76ea87e984
code
71
using KiteConnect using Test @test_throws ArgumentError ltp("INFY")
KiteConnect
https://github.com/arcofdescent/KiteConnect.jl.git
[ "MIT" ]
0.1.1
f147af01d49f3fb0fb3eca72f0719a76ea87e984
docs
286
# KiteConnect.jl A Julia module to interface with Zerodha's KiteConnect API ## Installation Using Julia's package manager ``` pkg> add KiteConnect ``` ## Get LTP of an instrument ``` using KiteConnect init(api_key, api_secret) gen_access_token(request_token) ltp("NSE:INFY") ```
KiteConnect
https://github.com/arcofdescent/KiteConnect.jl.git
[ "MIT" ]
0.1.1
f147af01d49f3fb0fb3eca72f0719a76ea87e984
docs
85
# KiteConnect Documentation ```@docs init(api_key::String, api_secret::String) ```
KiteConnect
https://github.com/arcofdescent/KiteConnect.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1537
using PlutoDevMacros using Documenter DocMeta.setdocmeta!(PlutoDevMacros, :DocTestSetup, :(using PlutoDevMacros); recursive=true) makedocs(; modules= Module[], authors="Alberto Mengali <[email protected]>", repo="https://github.com/disberd/PlutoDevMacros.jl/blob/{commit}{path}#{line}", sitename="PlutoDevMacros.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", edit_link="master", assets=String[], ), pages=[ "Home" => "index.md", "@frompackage/@fromparent" => Any[ "Introduction" => "frompackage/introduction.md", "Basic Use" => "frompackage/basic_use.md", "Supported import statements" => "frompackage/import_statements.md", "Skipping Package Parts" => "frompackage/skipping_parts.md", "Use with PlutoPkg" => "frompackage/use_with_plutopkg.md", "Package Extensions" => "frompackage/package_extensions.md", "Custom Settings" => "frompackage/custom_settings.md", ], "Other Exports" => "other_functions.md", # "PlutoHTLCombine" => "htl_combine.md", ], ) # This controls whether or not deployment is attempted. It is based on the value # of the `SHOULD_DEPLOY` ENV variable, which defaults to the `CI` ENV variables or # false if not present. should_deploy = get(ENV,"SHOULD_DEPLOY", get(ENV, "CI", "") === "true") if should_deploy @info "Deploying" deploydocs( repo = "github.com/disberd/PlutoDevMacros.jl.git", ) end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
2641
### A Pluto.jl notebook ### # v0.17.2 # using Markdown # using InteractiveUtils # ╔═║ ab7fc0f6-d065-4c03-aeb5-64a49214399e const default_exprlist = [Symbol("@md_str"), Symbol("@benchmark"), :(using Markdown), :PLUTO_MANIFEST_TOML_CONTENTS, :PLUTO_PROJECT_TOML_CONTENTS] # ╔═║ 2ac5f3c6-96f8-4f24-8022-1f0470672383 # ╠═║ skip_as_script = true #=╠═║ """ hasexpr(expr, exprlist) Simple expression match; will return `true` if one of the exprs listed in `exprlist` can be found inside `expr`. Checking for macrocalls can be done by including the `Symbol` of the macro among the expression list ```julia hasexpr(:(@benchmark 3+2), Symbol("@benchmark")) == true ``` """ function hasexpr(ex, exprlist::AbstractVector) result = false MacroTools.postwalk(ex) do y if y in exprlist result = true end return y end return result end ╠═║ =# # ╔═║ 1663bd40-4a0c-42cd-b716-4583d0a1bb66 # Fallback for when a single element is provided hasexpr(ex,exprlist) = hasexpr(ex,[exprlist]) # ╔═║ b42062a6-5bca-4c47-835c-caaeee1ceac6 """ include_mapexpr([exprlist])::Function Returns a function that can be used as first argument (`mapexpr`) of [`include`](@ref) calls to avoid including some of the expressions inside a Pluto notebook. When applied to an expression `ex`, the output function traverse `ex` recursively and returns `nothing` if `ex ∈ exprlist` and `ex` otherwise. The expression walk is performed with [`MacroTools.postwalk`](@ref) so for example the name of macros can be used to filter out nested expr which contains the macro call. When called without arguments, the value of `exprlist` defaults to a vector containing some filtering entries for Pluto notebooks: default_exprlist = $default_exprlist ```julia include_mapexpr()(:(md"asd")) == nothing include_mapexpr()(:(3 + 2)) == :(3+2) include_mapexpr([3])(:(3 + 2)) == nothing ``` """ include_mapexpr(exprlist=default_exprlist) = ex -> hasexpr(ex,exprlist) ? nothing : ex # ╔═║ b0f0df45-ed36-454a-9a9d-215f8c23836a export include_mapexpr # ╔═║ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] """ # ╔═║ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.7.0-rc2" manifest_format = "2.0" [deps] """ # ╔═║ Cell order: # ╠═ab7fc0f6-d065-4c03-aeb5-64a49214399e # ╠═b0f0df45-ed36-454a-9a9d-215f8c23836a # ╠═2ac5f3c6-96f8-4f24-8022-1f0470672383 # ╠═1663bd40-4a0c-42cd-b716-4583d0a1bb66 # ╠═b42062a6-5bca-4c47-835c-caaeee1ceac6 # β•Ÿβ”€00000000-0000-0000-0000-000000000001 # β•Ÿβ”€00000000-0000-0000-0000-000000000002
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
11382
### A Pluto.jl notebook ### # v0.17.2 # using Markdown # using InteractiveUtils # ╔═║ ea96e5d7-7bc0-45cf-8bf1-4acfaf5507c9 # ╠═║ skip_as_script = true #=╠═║ include("basics.jl") ╠═║ =# # ╔═║ 0ba0aae0-5c29-449a-81db-a389baddf0dc # ╠═║ skip_as_script = true #=╠═║ #using PlutoDevMacros ╠═║ =# # ╔═║ 2307b8e6-6308-4902-9921-135b85273f65 # ╠═║ skip_as_script = true #=╠═║ import WhereTraits ╠═║ =# # ╔═║ 9b6c7d3b-b70a-4cd4-9a77-f9b8d8501b9e import MacroTools # ╔═║ 4495c328-5bff-41ec-97f3-2422ee8c7339 function _plutotraits(ex::Expr) if ex.head === :block && length(ex.args) == 2 return _plutotraits(ex.args[2]) elseif ex.head === :macrocall && ex.args[1] isa GlobalRef && ex.args[1].name === Symbol("@doc") ex.args[end], fname = _plutotraits(ex.args[end]) return ex, fname else # We try to see if this expression is a function definition defdict = MacroTools.splitdef(ex) # If we reach this point, the expression is a funcdef or splitdef would error # Extract the linenumbernode from the definition body = defdict[:body] ln = body.args[1] # If the second arg is also a linenumbernode, remove the first on if body.args[2] isa LineNumberNode popfirst!(body.args) end # Add the call to traits # ex = Expr(:macrocall, Expr(:(.),:WhereTraits,QuoteNode(Symbol("@traits"))), ln, ex) ex = :(WhereTraits.@traits $(ex)) # Change the line ex.args[2] = ln # push!(ex.args, ln, ex) return ex, defdict[:name] end error("The provided expression was not of the valid type") end # ╔═║ b810a742-dda2-4bd0-b9d3-8b0b5ee7356c """ @plutotraits f(args...;kwargs...) where {wargs..} = body... Macro that allows to use the `WhereTraits.@traits` macro inside Pluto notebooks. When ran inside a notebook, this reconstructs the expression `expr` one would get by calling `WhereTraits.@traits f(args...;kwargs...) where {wargs..} = body...` but evaluates it in the top-level of the current workspace/module (using `Core.eval(__module__,Expr(:toplevel, expr))`).\\ This is needed to avoid Pluto's internal expression explorer throwing an error if multiple functions with the same name but different conditions are defined with `@traits` in separate cells. The usual Pluto workaround of wrapping multiple definitions in a begin ... end does not work with @traits as every call to the @traits macro has to be executed at the top level.\\ This has the side-effect that function calls within the notebook are not re-computed automatically if the definition with `@plutotraits` is changed within the notebook. When called outside of Pluto (or included in Pluto from another notebook using `@plutoinclude`), the macro simply resorts to calling directly the `Where.@traits` expression without resorting to the `Core.eval` call within the macro body. See [`WhereTraits.@traits`](@ref) or [`https://github.com/schlichtanders/WhereTraits.jl`](https://github.com/schlichtanders/WhereTraits.jl) for understanding how to use the underlying `@traits` macro. """ macro plutotraits(expr) # Meta.dump(expr) ex, fname = try _plutotraits(expr) catch e # error("The macro only supports a single call to the `@traits` macro with optional docstrings (wrapped in a begin...end block))") error(e) end if is_notebook_local(String(__source__.file)) Core.eval(__module__, Expr(:toplevel, ex)) esc(fname) else esc(ex) end end # ╔═║ 8f354575-6ca2-4f0f-9880-f50d785de8f9 export @plutotraits # ╔═║ d6e472a7-bbd3-4f18-aa27-7289e6c23eab # ╠═║ skip_as_script = true #=╠═║ @plutotraits begin "Test Documentation" g(a) where {iseven(a)} = "EVEN" end ╠═║ =# # ╔═║ e3c59dc8-6894-487a-ae98-62594fd149ef # ╠═║ skip_as_script = true #=╠═║ @plutotraits g(a) where {isodd(a)} = "ODD" ╠═║ =# # ╔═║ 51bdae6a-7749-4bee-a6d0-b1055fab5ece # ╠═║ skip_as_script = true #=╠═║ g(2) ╠═║ =# # ╔═║ c826aa1b-fd70-452c-9716-3bfc6066e590 # ╠═║ skip_as_script = true #=╠═║ g(1) ╠═║ =# # ╔═║ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] MacroTools = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" WhereTraits = "c9d4e05b-6318-49cb-9b56-e0e2b0ceadd8" [compat] MacroTools = "~0.5.9" WhereTraits = "~1.0.0" """ # ╔═║ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.7.0-rc2" manifest_format = "2.0" [[deps.ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" [[deps.Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[deps.Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[deps.Compat]] deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"] git-tree-sha1 = "dce3e3fea680869eaa0b774b2e8343e9ff442313" uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" version = "3.40.0" [[deps.CompilerSupportLibraries_jll]] deps = ["Artifacts", "Libdl"] uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" [[deps.ConstructionBase]] deps = ["LinearAlgebra"] git-tree-sha1 = "f74e9d5388b8620b4cee35d4c5a618dd4dc547f4" uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9" version = "1.3.0" [[deps.DataTypesBasic]] deps = ["Compat"] git-tree-sha1 = "4cff12742dcd7a8639da323abaf6bd4722abc312" uuid = "83eed652-29e8-11e9-12da-a7c29d64ffc9" version = "1.0.0" [[deps.Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[deps.DelimitedFiles]] deps = ["Mmap"] uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" [[deps.Distributed]] deps = ["Random", "Serialization", "Sockets"] uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b" [[deps.Downloads]] deps = ["ArgTools", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" [[deps.ExprParsers]] deps = ["Compat", "ProxyInterfaces", "SimpleMatch", "StructEquality"] git-tree-sha1 = "03d3f97dad4bd2b10ca0febca5db6bef5e0b320a" uuid = "c5caad1f-83bd-4ce8-ac8e-4b29921e994e" version = "1.1.0" [[deps.Future]] deps = ["Random"] uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820" [[deps.InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[deps.LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" [[deps.LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" [[deps.LibGit2]] deps = ["Base64", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[deps.LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" [[deps.Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[deps.LinearAlgebra]] deps = ["Libdl", "libblastrampoline_jll"] uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" [[deps.Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[deps.MacroTools]] deps = ["Markdown", "Random"] git-tree-sha1 = "3d3e902b31198a27340d0bf00d6ac452866021cf" uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" version = "0.5.9" [[deps.Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[deps.MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" [[deps.Mmap]] uuid = "a63ad114-7e13-5084-954f-fe012c677804" [[deps.MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" [[deps.NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" [[deps.OpenBLAS_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" [[deps.Pkg]] deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" [[deps.Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[deps.ProxyInterfaces]] deps = ["Compat"] git-tree-sha1 = "d85fef4db37288bd756c71d223e34406055b7414" uuid = "9b3bf0c4-f070-48bc-ae01-f2584e9c23bc" version = "1.0.0" [[deps.REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[deps.Random]] deps = ["SHA", "Serialization"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[deps.Requires]] deps = ["UUIDs"] git-tree-sha1 = "4036a3bd08ac7e968e27c203d45f5fff15020621" uuid = "ae029012-a4dd-5104-9daa-d747884805df" version = "1.1.3" [[deps.SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" [[deps.Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[deps.Setfield]] deps = ["ConstructionBase", "Future", "MacroTools", "Requires"] git-tree-sha1 = "fca29e68c5062722b5b4435594c3d1ba557072a3" uuid = "efcf1570-3423-57d1-acb7-fd33fddbac46" version = "0.7.1" [[deps.SharedArrays]] deps = ["Distributed", "Mmap", "Random", "Serialization"] uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383" [[deps.SimpleMatch]] deps = ["Compat"] git-tree-sha1 = "c1cc22bbe259ea4a159e30ff2cf5f01d378262e8" uuid = "a3ae8450-d22f-11e9-3fe0-77240e25996f" version = "1.0.0" [[deps.Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[deps.SparseArrays]] deps = ["LinearAlgebra", "Random"] uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" [[deps.Statistics]] deps = ["LinearAlgebra", "SparseArrays"] uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" [[deps.StructEquality]] deps = ["Compat"] git-tree-sha1 = "6e951cd0585cbe8f4ceb1cb09d69332b9484fec9" uuid = "6ec83bb0-ed9f-11e9-3b4c-2b04cb4e219c" version = "1.1.0" [[deps.Suppressor]] git-tree-sha1 = "a819d77f31f83e5792a76081eee1ea6342ab8787" uuid = "fd094767-a336-5f1f-9728-57cf17d0bbfb" version = "0.2.0" [[deps.TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" [[deps.Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" [[deps.Test]] deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [[deps.UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[deps.Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[deps.WhereTraits]] deps = ["Compat", "DataTypesBasic", "ExprParsers", "Markdown", "ProxyInterfaces", "Setfield", "SimpleMatch", "StructEquality", "Suppressor"] git-tree-sha1 = "cb13380b76dbe6e68c433dcd097aca3325a26470" uuid = "c9d4e05b-6318-49cb-9b56-e0e2b0ceadd8" version = "1.0.0" [[deps.Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" [[deps.libblastrampoline_jll]] deps = ["Artifacts", "Libdl", "OpenBLAS_jll"] uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" [[deps.nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" [[deps.p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" """ # ╔═║ Cell order: # ╠═0ba0aae0-5c29-449a-81db-a389baddf0dc # ╠═2307b8e6-6308-4902-9921-135b85273f65 # ╠═9b6c7d3b-b70a-4cd4-9a77-f9b8d8501b9e # ╠═ea96e5d7-7bc0-45cf-8bf1-4acfaf5507c9 # ╠═8f354575-6ca2-4f0f-9880-f50d785de8f9 # ╠═b810a742-dda2-4bd0-b9d3-8b0b5ee7356c # ╠═4495c328-5bff-41ec-97f3-2422ee8c7339 # ╠═d6e472a7-bbd3-4f18-aa27-7289e6c23eab # ╠═e3c59dc8-6894-487a-ae98-62594fd149ef # ╠═51bdae6a-7749-4bee-a6d0-b1055fab5ece # ╠═c826aa1b-fd70-452c-9716-3bfc6066e590 # β•Ÿβ”€00000000-0000-0000-0000-000000000001 # β•Ÿβ”€00000000-0000-0000-0000-000000000002
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
16270
### A Pluto.jl notebook ### # v0.19.25 using Markdown using InteractiveUtils # This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error). macro bind(def, element) quote local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end local el = $(esc(element)) global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el) el end end # ╔═║ 661e0d86-9675-4c24-a898-5ffee2e32029 begin using MacroTools end # ╔═║ e3d5c718-d98c-4d53-8fc9-911be34c9f2d # ╠═║ skip_as_script = true #=╠═║ begin using BenchmarkTools import PlutoDevMacros end ╠═║ =# # ╔═║ 47c42d27-88f1-4a27-bda9-54a2439b09a1 # ╠═║ skip_as_script = true #=╠═║ include("basics.jl") ╠═║ =# # ╔═║ 5089d8dd-6587-4172-9ffd-13cf43e8c341 # ╠═║ skip_as_script = true #=╠═║ md""" ## Main Functions """ ╠═║ =# # ╔═║ b87d12be-a37b-4202-9426-3eef14d8253c function ingredients(path::String) # this is from the Julia source code (evalfile in base/loading.jl) # but with the modification that it returns the module instead of the last object name = Symbol("#plutoinclude_",basename(path)) m = Module(name) Core.eval(m, Expr(:toplevel, :(eval(x) = $(Expr(:core, :eval))($name, x)), :(include(x) = $(Expr(:top, :include))($name, x)), :(include(mapexpr::Function, x) = $(Expr(:top, :include))(mapexpr, $name, x)), :(using PlutoDevMacros: @plutoinclude), # This is needed for nested @plutoinclude calls :(include($path)))) m end # ╔═║ 57efc195-6a2f-4ad3-94fd-53e884838789 # ╠═║ skip_as_script = true #=╠═║ md""" # Other Ingredients Helpers """ ╠═║ =# # ╔═║ aa28b5d8-e0d7-4b97-9220-b61a0c5f4fc4 html_reload_button() = html""" <div class="plutoinclude_banner"> Reload @pluto_include </div> <script> const cell = currentScript.closest('pluto-cell') const onClick = (e) => { console.log(e) if (e.ctrlKey) { history.pushState({},'') cell.scrollIntoView({ behavior: 'smooth', block: 'center', }) } else { cell.querySelector('button.runcell').click() } } const banner = cell.querySelector(".plutoinclude_banner") banner.addEventListener('click',onClick) invalidation.then(() => banner.removeEventListener('click',onClick)) </script> <style> .plutoinclude_banner { height: 20px; position: fixed; top: 40px; right: 10px; margin-top: 5px; padding-right: 5px; z-index: 200; background: #ffffff; padding: 5px 8px; border: 3px solid #e3e3e3; border-radius: 12px; height: 35px; font-family: "Segoe UI Emoji", "Roboto Mono", monospace; font-size: 0.75rem; } .plutoinclude_banner:hover { font-weight: 800; cursor: pointer; } body.disable_ui .plutoinclude_banner { display: none; } main </style> """ # ╔═║ 98b1fa0d-fad1-4c4f-88a0-9452d492c4cb function include_expr(from::Module,kwargstrs::String...; to::Module) modname = Symbol("#plutoincluded_module") ex = Expr(:block, :(const $modname = $from)) kwargs = (Symbol(s) => true for s ∈ kwargstrs if s ∈ ("all","imported")) varnames = names(from;kwargs...) # Remove the symbols that start with a '#' (still to check what is the impact) filter!(!Base.isgensym,varnames) # Symbols to always exclude from imports exclude_names = ( nameof(from), :eval, :include, Symbol("@bind"), Symbol("@plutoinclude"), # Since we included this in the module ) for s ∈ varnames if s βˆ‰ exclude_names if getfield(from,s) isa Function # _copymethods!(ex, s; to, from, importedlist = varnames, fromname = modname) ret_types = Base.return_types(getfield(from,s)) candidate_type = ret_types[1] # Get the eventual docstring docstring = Base.doc(Base.Docs.Binding(from, s)) if all(x -> x === candidate_type, ret_types) && Base.isconcretetype(candidate_type) push!(ex.args, :(@doc ($docstring) $s(args...; kwargs...)::$candidate_type = $modname.$s(args...; kwargs...))) else push!(ex.args, :(@doc ($docstring) $s(args...; kwargs...) = $modname.$s(args...; kwargs...))) end else push!(ex.args,:(const $s = $modname.$s)) end end end # Add the html to re-run the cell push!(ex.args,:($(html_reload_button()))) ex end # ╔═║ 872bd88e-dded-4789-85ef-145f16003351 """ @plutoinclude path nameskwargs... @plutoinclude modname=path namekwargs... This macro is used to include external julia files inside a pluto notebook and is inspired by the discussion on [this Pluto issue](https://github.com/fonsp/Pluto.jl/issues/1101). It requires Pluto >= v0.17.0 and includes and external file, taking care of putting in the caller namespace all varnames that are tagged with `export varname` inside the included file. The macro relies on the use of [`names`](@ref) to get the variable names to be exported, and support providing the names of the keyword arguments of `names` to be set to true as additional strings When called from outside Pluto, it simply returns nothing """ macro plutoinclude(ex,kwargstrs...) path = ex isa String ? ex : Base.eval(__module__,ex) if is_notebook_local(__source__.file::Symbol |> String) # If this is called directly from the notebook, do the hack to export the various variables from the module m = ingredients(path) esc(include_expr(m,kwargstrs...; to = __module__)) elseif first(nameof(__module__) |> String, 13) == "#plutoinclude" # We are in a chained plutoinclude, simply include the subfile :(include($path)) |> esc else # We are not in the notebook and not in a chained include, so do nothing nothing end end # ╔═║ 748b8eab-2f3d-4afd-bfb4-fee3240d391b export @plutoinclude # ╔═║ 1f291bd2-9ab1-4fd2-bf50-49253726058f # ╠═║ skip_as_script = true #=╠═║ md""" ## Example Use """ ╠═║ =# # ╔═║ cf0d13ea-7562-4b8c-b7e6-fb2f1de119a7 # ╠═║ skip_as_script = true #=╠═║ md""" The cells below assume to also have the test notebook `ingredients_include_test.jl` from PlutoUtils in the same folder, download it and put it in the same folder in case you didn't already """ ╠═║ =# # ╔═║ bd3b021f-db44-4aa1-97b2-04002f76aeff # ╠═║ skip_as_script = true #=╠═║ notebook_path = "./plutoinclude_test.jl" ╠═║ =# # ╔═║ 0e3eb73f-091a-4683-8ccb-592b8ccb1bee # ╠═║ skip_as_script = true #=╠═║ md""" Try changing the content of the included notebook by removing some exported variables and re-execute (**using Shift-Enter**) the cell below containing the @plutoinclude call to see that variables are correctly updated. You can also try leaving some variable unexported and still export all that is defined in the notebook by using ```julia @plutoinclude notebook_path "all" ``` Finally, you can also assign the full imported module in a specific variable by doing ```julia @plutoinclude varname = notebook_path ``` """ ╠═║ =# # ╔═║ d2ac4955-d2a0-48b5-afcb-32baa59ade21 # ╠═║ skip_as_script = true #=╠═║ @plutoinclude notebook_path "all" ╠═║ =# # ╔═║ 0d1f5079-a886-4a07-9e99-d73e0b8a2eec # ╠═║ skip_as_script = true #=╠═║ @macroexpand @plutoinclude notebook_path "all" ╠═║ =# # ╔═║ 50759ca2-45ca-4005-9182-058a5cb68359 # ╠═║ skip_as_script = true #=╠═║ const mm = ingredients(notebook_path) ╠═║ =# # ╔═║ 4cec781b-c6d7-4fd7-bbe3-f7db0f973698 # ╠═║ skip_as_script = true #=╠═║ a ╠═║ =# # ╔═║ a7e7123f-0e7a-4771-9b9b-d0da97fefcef # ╠═║ skip_as_script = true #=╠═║ b ╠═║ =# # ╔═║ 2c41234e-e1b8-4ad8-9134-85cd65a75a2d # ╠═║ skip_as_script = true #=╠═║ c ╠═║ =# # ╔═║ ce2a2025-a6e0-44ab-8631-8d308be734a9 # ╠═║ skip_as_script = true #=╠═║ d ╠═║ =# # ╔═║ d8be6b4c-a02b-43ec-b176-de6f64fefd87 # ╠═║ skip_as_script = true #=╠═║ # Extending the method asd(s::String) = "STRING" ╠═║ =# # ╔═║ 8090dd72-a47b-4d9d-85df-ceb0c1bcedf5 # ╠═║ skip_as_script = true #=╠═║ asd(3) ╠═║ =# # ╔═║ 61924e22-f052-43a5-84b1-5512d222af26 # ╠═║ skip_as_script = true #=╠═║ @benchmark asd(TestStruct()) ╠═║ =# # ╔═║ d1fbe484-dcd0-456e-8ec1-c68acd708a08 # ╠═║ skip_as_script = true #=╠═║ asd(TestStruct()) ╠═║ =# # ╔═║ 8df0f262-faf2-4f99-98e2-6b2a47e5ca31 # ╠═║ skip_as_script = true #=╠═║ asd(TestStruct(),3,4) ╠═║ =# # ╔═║ 1754fdcf-de3d-4d49-a2f0-9e3f4aa3498e # ╠═║ skip_as_script = true #=╠═║ asd("S") ╠═║ =# # ╔═║ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" MacroTools = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" PlutoDevMacros = "a0499f29-c39b-4c5c-807c-88074221b949" [compat] BenchmarkTools = "~1.3.2" MacroTools = "~0.5.10" PlutoDevMacros = "~0.5.0" """ # ╔═║ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.9.0-rc3" manifest_format = "2.0" project_hash = "b329ce92ad28a8475022c6a7c95009120252febc" [[deps.ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" version = "1.1.1" [[deps.Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[deps.Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[deps.BenchmarkTools]] deps = ["JSON", "Logging", "Printf", "Profile", "Statistics", "UUIDs"] git-tree-sha1 = "d9a9701b899b30332bbcb3e1679c41cce81fb0e8" uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" version = "1.3.2" [[deps.CompilerSupportLibraries_jll]] deps = ["Artifacts", "Libdl"] uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" version = "1.0.2+0" [[deps.Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[deps.Downloads]] deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" version = "1.6.0" [[deps.FileWatching]] uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" [[deps.HypertextLiteral]] deps = ["Tricks"] git-tree-sha1 = "c47c5fa4c5308f27ccaac35504858d8914e102f9" uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2" version = "0.9.4" [[deps.InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[deps.JSON]] deps = ["Dates", "Mmap", "Parsers", "Unicode"] git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a" uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" version = "0.21.4" [[deps.LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" version = "0.6.3" [[deps.LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" version = "7.84.0+0" [[deps.LibGit2]] deps = ["Base64", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[deps.LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" version = "1.10.2+0" [[deps.Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[deps.LinearAlgebra]] deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"] uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" [[deps.Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[deps.MacroTools]] deps = ["Markdown", "Random"] git-tree-sha1 = "42324d08725e200c23d4dfb549e0d5d89dede2d2" uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" version = "0.5.10" [[deps.Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[deps.MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" version = "2.28.2+0" [[deps.Mmap]] uuid = "a63ad114-7e13-5084-954f-fe012c677804" [[deps.MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" version = "2022.10.11" [[deps.NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" version = "1.2.0" [[deps.OpenBLAS_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" version = "0.3.21+4" [[deps.Parsers]] deps = ["Dates", "SnoopPrecompile"] git-tree-sha1 = "478ac6c952fddd4399e71d4779797c538d0ff2bf" uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" version = "2.5.8" [[deps.Pkg]] deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" version = "1.9.0" [[deps.PlutoDevMacros]] deps = ["HypertextLiteral", "InteractiveUtils", "MacroTools", "Markdown", "Random", "Requires"] git-tree-sha1 = "fa04003441d7c80b4812bd7f9678f721498259e7" uuid = "a0499f29-c39b-4c5c-807c-88074221b949" version = "0.5.0" [[deps.Preferences]] deps = ["TOML"] git-tree-sha1 = "47e5f437cc0e7ef2ce8406ce1e7e24d44915f88d" uuid = "21216c6a-2e73-6563-6e65-726566657250" version = "1.3.0" [[deps.Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[deps.Profile]] deps = ["Printf"] uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79" [[deps.REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[deps.Random]] deps = ["SHA", "Serialization"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[deps.Requires]] deps = ["UUIDs"] git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7" uuid = "ae029012-a4dd-5104-9daa-d747884805df" version = "1.3.0" [[deps.SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" version = "0.7.0" [[deps.Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[deps.SnoopPrecompile]] deps = ["Preferences"] git-tree-sha1 = "e760a70afdcd461cf01a575947738d359234665c" uuid = "66db9d55-30c0-4569-8b51-7e840670fc0c" version = "1.0.3" [[deps.Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[deps.SparseArrays]] deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"] uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" [[deps.Statistics]] deps = ["LinearAlgebra", "SparseArrays"] uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" version = "1.9.0" [[deps.SuiteSparse_jll]] deps = ["Artifacts", "Libdl", "Pkg", "libblastrampoline_jll"] uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c" version = "5.10.1+6" [[deps.TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" version = "1.0.3" [[deps.Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" version = "1.10.0" [[deps.Tricks]] git-tree-sha1 = "aadb748be58b492045b4f56166b5188aa63ce549" uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775" version = "0.1.7" [[deps.UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[deps.Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[deps.Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" version = "1.2.13+0" [[deps.libblastrampoline_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" version = "5.7.0+0" [[deps.nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" version = "1.48.0+0" [[deps.p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" version = "17.4.0+0" """ # ╔═║ Cell order: # ╠═661e0d86-9675-4c24-a898-5ffee2e32029 # ╠═e3d5c718-d98c-4d53-8fc9-911be34c9f2d # ╠═748b8eab-2f3d-4afd-bfb4-fee3240d391b # ╠═47c42d27-88f1-4a27-bda9-54a2439b09a1 # β•Ÿβ”€5089d8dd-6587-4172-9ffd-13cf43e8c341 # ╠═b87d12be-a37b-4202-9426-3eef14d8253c # β•Ÿβ”€57efc195-6a2f-4ad3-94fd-53e884838789 # ╠═98b1fa0d-fad1-4c4f-88a0-9452d492c4cb # ╠═872bd88e-dded-4789-85ef-145f16003351 # ╠═aa28b5d8-e0d7-4b97-9220-b61a0c5f4fc4 # β•Ÿβ”€1f291bd2-9ab1-4fd2-bf50-49253726058f # β•Ÿβ”€cf0d13ea-7562-4b8c-b7e6-fb2f1de119a7 # ╠═bd3b021f-db44-4aa1-97b2-04002f76aeff # β•Ÿβ”€0e3eb73f-091a-4683-8ccb-592b8ccb1bee # ╠═d2ac4955-d2a0-48b5-afcb-32baa59ade21 # ╠═0d1f5079-a886-4a07-9e99-d73e0b8a2eec # ╠═8090dd72-a47b-4d9d-85df-ceb0c1bcedf5 # ╠═61924e22-f052-43a5-84b1-5512d222af26 # ╠═50759ca2-45ca-4005-9182-058a5cb68359 # ╠═4cec781b-c6d7-4fd7-bbe3-f7db0f973698 # ╠═a7e7123f-0e7a-4771-9b9b-d0da97fefcef # ╠═2c41234e-e1b8-4ad8-9134-85cd65a75a2d # ╠═ce2a2025-a6e0-44ab-8631-8d308be734a9 # ╠═d1fbe484-dcd0-456e-8ec1-c68acd708a08 # ╠═8df0f262-faf2-4f99-98e2-6b2a47e5ca31 # ╠═d8be6b4c-a02b-43ec-b176-de6f64fefd87 # ╠═1754fdcf-de3d-4d49-a2f0-9e3f4aa3498e # β•Ÿβ”€00000000-0000-0000-0000-000000000001 # β•Ÿβ”€00000000-0000-0000-0000-000000000002
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1975
### A Pluto.jl notebook ### # v0.17.1 using Markdown using InteractiveUtils # ╔═║ e7d3f8f0-bb20-4b41-b482-a1d4d051b20b a = 5152 # ╔═║ 722a2090-c956-4733-a3a0-4e776b43853d b = 251 # ╔═║ a5425f17-8e08-443a-8451-a5231e3144a6 c = 142 # ╔═║ ba9665b9-f9f4-4a69-960d-5fe40ef708a8 d = 3 # ╔═║ 8cb5cd6b-b84d-4a12-823b-b5d247d6eb2c Base.@kwdef struct TestStruct a::Int = 5 end # ╔═║ b5efd50a-1bf2-4634-93b8-ee6c5d7a4a3f export TestStruct # ╔═║ 3951f4a5-c112-4f35-bd4f-ecff125406e3 export a # ╔═║ e69da1bf-c376-4760-be05-e866ccc09b2f export b # ╔═║ 2d487920-1fd7-4fee-bbed-435ad883bed8 # export c, d # ╔═║ 849be81a-9e1a-48ff-9056-2b4648e22e5a asd(x::Int) = "INT" # ╔═║ 58ddadeb-1032-41c9-be45-0087671b1524 asd(x::Float64) = "FLOAT" # ╔═║ 9ebec3d9-4809-46ae-8d9f-f55f3b4323a3 asd(::Real, c::Int64) = "DUAL" # ╔═║ d5d563a1-cde7-407a-8863-689f7dfd1a1e asd(t::TestStruct) = "THIS IS A TESTSTRUCT" # ╔═║ 8bb2f880-d650-4c0f-afe8-536e75fcce5b asd(t::TestStruct, args...) = "TESTSTRUCT WITH VARARGS" # ╔═║ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] """ # ╔═║ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.7.0-rc2" manifest_format = "2.0" [deps] """ # ╔═║ Cell order: # ╠═e7d3f8f0-bb20-4b41-b482-a1d4d051b20b # ╠═722a2090-c956-4733-a3a0-4e776b43853d # ╠═a5425f17-8e08-443a-8451-a5231e3144a6 # ╠═ba9665b9-f9f4-4a69-960d-5fe40ef708a8 # ╠═8cb5cd6b-b84d-4a12-823b-b5d247d6eb2c # ╠═b5efd50a-1bf2-4634-93b8-ee6c5d7a4a3f # ╠═3951f4a5-c112-4f35-bd4f-ecff125406e3 # ╠═e69da1bf-c376-4760-be05-e866ccc09b2f # ╠═2d487920-1fd7-4fee-bbed-435ad883bed8 # ╠═849be81a-9e1a-48ff-9056-2b4648e22e5a # ╠═58ddadeb-1032-41c9-be45-0087671b1524 # ╠═9ebec3d9-4809-46ae-8d9f-f55f3b4323a3 # ╠═d5d563a1-cde7-407a-8863-689f7dfd1a1e # ╠═8bb2f880-d650-4c0f-afe8-536e75fcce5b # β•Ÿβ”€00000000-0000-0000-0000-000000000001 # β•Ÿβ”€00000000-0000-0000-0000-000000000002
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
989
### A Pluto.jl notebook ### # v0.17.2 # using Markdown # using InteractiveUtils # ╔═║ bb26cad0-4720-11ec-20c0-6538c8fcc18f # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate("..") end ╠═║ =# # ╔═║ c0e30b73-0973-47c8-b57c-3a0b9c534ec5 using BenchmarkTools # ╔═║ 82ace475-cc8d-4f3d-84bd-91a49c141648 using PlutoDevMacros # ╔═║ 8c251cd4-3050-4809-80a3-07e9aab558ab struct TestStruct1 end # ╔═║ 8145c16e-0a16-4e8b-a073-8e1774273bb4 asd(x::Int) = "INTSSS" # ╔═║ 354605a3-297e-4647-b4cf-f0aea4987f9e """ asd(::TestStruct1) This is a magical docstring """ asd(::TestStruct1) = "TESTSTRUCT1" # ╔═║ 9e1468e5-beda-486a-9cde-9c498f77999e @benchmark asd(TestStruct1()) # ╔═║ Cell order: # ╠═bb26cad0-4720-11ec-20c0-6538c8fcc18f # ╠═c0e30b73-0973-47c8-b57c-3a0b9c534ec5 # ╠═82ace475-cc8d-4f3d-84bd-91a49c141648 # ╠═8c251cd4-3050-4809-80a3-07e9aab558ab # ╠═8145c16e-0a16-4e8b-a073-8e1774273bb4 # ╠═354605a3-297e-4647-b4cf-f0aea4987f9e # ╠═9e1468e5-beda-486a-9cde-9c498f77999e
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1585
### A Pluto.jl notebook ### # v0.17.2 # using Markdown # using InteractiveUtils # ╔═║ f9eff180-3c4d-49c2-9f4e-e3f425a96966 # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate("..") end ╠═║ =# # ╔═║ 941fa912-61d4-4847-8bb2-5e83eb31ca34 begin using Revise using PlutoDevMacros end # ╔═║ f73c9b70-4c68-4d3b-be3e-067a118681e8 # ╠═║ skip_as_script = true #=╠═║ using BenchmarkTools ╠═║ =# # ╔═║ d9b0ef51-60cc-4a30-9f8b-f6b6b2dbeec5 @macroexpand @plutoinclude "test1.jl" "all" # ╔═║ e2ac5a43-d683-486b-a2a1-f26f48313c47 @plutoinclude "test1.jl" "all" # ╔═║ f3287e4b-c92a-4eef-8b79-78346a55803b asd(x::Float64) = "FLOAT" # ╔═║ 4d8e68cb-910f-4f6c-89cd-2bf2da7b5a70 struct TestStruct2 end # ╔═║ 53ec02f7-ca14-41d9-b3b7-757c36f526f7 asd(::TestStruct2) = "TESTSTRUCT2" # ╔═║ f5b8ccdd-ad66-4ae4-b3e9-82452464168b # ╠═║ skip_as_script = true #=╠═║ asd(3) ╠═║ =# # ╔═║ a33fdee5-037c-41de-aeec-bc4383fe4826 # ╠═║ skip_as_script = true #=╠═║ @benchmark asd(TestStruct2()) ╠═║ =# # ╔═║ a646c602-529e-45c1-a170-3650318c1c2d # ╠═║ skip_as_script = true #=╠═║ @benchmark asd(TestStruct1()) ╠═║ =# # ╔═║ Cell order: # ╠═f9eff180-3c4d-49c2-9f4e-e3f425a96966 # ╠═941fa912-61d4-4847-8bb2-5e83eb31ca34 # ╠═f73c9b70-4c68-4d3b-be3e-067a118681e8 # ╠═d9b0ef51-60cc-4a30-9f8b-f6b6b2dbeec5 # ╠═e2ac5a43-d683-486b-a2a1-f26f48313c47 # ╠═f5b8ccdd-ad66-4ae4-b3e9-82452464168b # ╠═f3287e4b-c92a-4eef-8b79-78346a55803b # ╠═4d8e68cb-910f-4f6c-89cd-2bf2da7b5a70 # ╠═53ec02f7-ca14-41d9-b3b7-757c36f526f7 # ╠═a33fdee5-037c-41de-aeec-bc4383fe4826 # ╠═a646c602-529e-45c1-a170-3650318c1c2d
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1998
### A Pluto.jl notebook ### # v0.17.2 # using Markdown # using InteractiveUtils # ╔═║ a1e38635-d1cb-4184-8e77-dab98a057e4c # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate("..") end ╠═║ =# # ╔═║ 24ee155b-af1a-4915-a23b-3ff16e7ba844 begin using Revise using PlutoDevMacros end # ╔═║ fa2b4748-4ec4-475a-a255-40b16cee11be # ╠═║ skip_as_script = true #=╠═║ using BenchmarkTools ╠═║ =# # ╔═║ c5a1f2f0-c2b8-4ff7-b33c-467495b2317c @plutoinclude "test2.jl" "all" # ╔═║ 7f9edbbe-2f8d-4b94-8199-6debf0143cca # ╠═║ skip_as_script = true #=╠═║ struct TestStruct3 end ╠═║ =# # ╔═║ 25c3a29c-3a29-4de6-b66b-aaeb7c788d29 # ╠═║ skip_as_script = true #=╠═║ asd(::TestStruct3) = "TESTSTRUCT3" ╠═║ =# # ╔═║ 6630b18d-b98b-49b8-a416-e793a1d3b474 # ╠═║ skip_as_script = true #=╠═║ asd(1) ╠═║ =# # ╔═║ 0542d7f4-4104-4884-b79e-d94d3fd3041c # ╠═║ skip_as_script = true #=╠═║ asd(1.0) ╠═║ =# # ╔═║ 25924828-2ec2-4df0-8afd-3bcb6e3aad28 # ╠═║ skip_as_script = true #=╠═║ asd(TestStruct1()) ╠═║ =# # ╔═║ c0448179-1dac-4c61-9fb3-5b2c14f44f30 # ╠═║ skip_as_script = true #=╠═║ asd(TestStruct2()) ╠═║ =# # ╔═║ 0d7ab7ce-1ce5-4249-b8de-8aeed5bec07e # ╠═║ skip_as_script = true #=╠═║ asd(TestStruct3()) ╠═║ =# # ╔═║ 720caf23-72de-4161-a7b0-0a10d690f0c3 # ╠═║ skip_as_script = true #=╠═║ asd(TestStruct2()) ╠═║ =# # ╔═║ 26b39429-5766-45a5-a173-ad632c31718c # ╠═║ skip_as_script = true #=╠═║ @benchmark asd(TestStruct1()) ╠═║ =# # ╔═║ Cell order: # ╠═a1e38635-d1cb-4184-8e77-dab98a057e4c # ╠═24ee155b-af1a-4915-a23b-3ff16e7ba844 # ╠═fa2b4748-4ec4-475a-a255-40b16cee11be # ╠═c5a1f2f0-c2b8-4ff7-b33c-467495b2317c # ╠═6630b18d-b98b-49b8-a416-e793a1d3b474 # ╠═0542d7f4-4104-4884-b79e-d94d3fd3041c # ╠═25924828-2ec2-4df0-8afd-3bcb6e3aad28 # ╠═c0448179-1dac-4c61-9fb3-5b2c14f44f30 # ╠═7f9edbbe-2f8d-4b94-8199-6debf0143cca # ╠═25c3a29c-3a29-4de6-b66b-aaeb7c788d29 # ╠═0d7ab7ce-1ce5-4249-b8de-8aeed5bec07e # ╠═720caf23-72de-4161-a7b0-0a10d690f0c3 # ╠═26b39429-5766-45a5-a173-ad632c31718c
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
340
module PlutoDevMacros using MacroTools: shortdef # This are from basics.jl export @only_in_nb, @only_out_nb, plutodump, @current_pluto_cell_id, @current_pluto_notebook_file, @addmethod include("basics.jl") include("html_helpers.jl") include("frompackage/FromPackage.jl") using .FromPackage export @fromparent, @frompackage end # module
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
4813
function _cell_data(filesrc::String) names = split(filesrc,"#==#") if length(names) > 1 return names else return names[1], "" end end _cell_data(file::Symbol) = _cell_data(String(file)) _cell_data(lnn::LineNumberNode) = _cell_data(lnn.file) """ is_notebook_local(filesrc::AbstractString)::Bool Returns `true` if Pluto is loaded and if the `filesrc` points to the currently running Pluto cell_id To be fed the result of `@__FILE__` (or `__source__.file` used inside macros) as `filesrc`.\\ This works because the `@__FILE__` information contains the name of the Pluto notebook followed the string `#==#` and by the cell UUID in case this is called directly in a notebook (and not included from outside) """ function is_notebook_local(filesrc)::Bool # If this is ran from the notebook it is defined in Pluto, the output of __source__.file or @__FILE__ is split into filepath and cell_id with a #==# separator file, cell_id = _cell_data(filesrc) return isempty(cell_id) ? false : true end function is_notebook_local() cell_id = try Main.PlutoRunner.currently_running_cell_id[] catch e return false end caller = stacktrace()[2] # We get the function calling this function calling_file = caller.file |> string return endswith(calling_file, string(cell_id)) end """ plutodump(x::Union{Symbol, Expr}; maxdepth = 8) Dumps a symbol or expression directly as text on the pluto cell output instead of in the stdout See also: [`Meta.dump`](@ref) """ function plutodump(x::Union{Symbol, Expr}; maxdepth = 8) i = IOBuffer() Meta.dump(i, x; maxdepth) String(take!(i)) |> Text end ## Macros ## """ @current_pluto_cell_id() Returns the cell_id (as a string) of the cell where the macro is called. If not ran from within the pluto notebook containing the call, returns an empty string """ macro current_pluto_cell_id() _, cell_id = _cell_data(__source__.file::Symbol |> String) return isempty(cell_id) ? "" : string(cell_id) end """ @current_pluto_notebook_file() Returns the path of the notebook file of the cell where the macro is called. If not ran from within the pluto notebook containing the call, returns an empty string """ macro current_pluto_notebook_file() nbfile, cell_id = _cell_data(__source__.file::Symbol |> String) return isempty(cell_id) ? "" : string(nbfile) end """ only_in_nb(ex) Executes the expression `ex` only if the macro is called from a running Pluto instance and ran directly from the source notebook file. This is more strict than `PlutoHooks.@skip_as_script` as including a notebook with `@skip_as_script ex` from another notebook would still execute `ex`.\\ `@only_in_nb ex` instead only evaluates `ex` if the calling notebook is the original source notebook file. See also: [`@only_out_nb`](@ref). [`PlutoHooks.@skip_as_script`](@ref). """ macro only_in_nb(ex) is_notebook_local(String(__source__.file::Symbol)) ? esc(ex) : nothing end """ only_out_nb(ex) Opposite of `@only_in_nb` See also: [`@only_in_nb`](@ref). [`PlutoHooks.@only_as_script`](@ref). """ macro only_out_nb(ex) is_notebook_local(String(__source__.file::Symbol)) ? nothing : esc(ex) end """ @addmethod func(args...;kwargs...) = body @addmethod function func(args...;kwargs...) body end This simple macro modifies a function definition expression (only when called from a Pluto notebook) to prepend the name of the module defining the function (here called `DefiningModule`) to the method definition. So the code ```julia @addmethod func(args...;kwargs...) = something ``` is simply translated to ```julia DefiningModule.func(args...;kwargs...) = something ``` when called from a Pluto notebook, and to: ```julia func(args...;kwargs...) = something ``` when called outside of Pluto. This is useful to avoid multiple definition errors inside Pluto but has the caveat that defining a method with `@addmethod` does not trigger a reactive run of all cells that call the modified function. This also mean that when removing the cell with the `@addmethod` call, the actual method added to the `DefiningModule` will not be automatically erased by Pluto and will still accessible until it is not overwritten with another method with the same signature. This is easy to fix in the case of adding methods to modules loaded with `@frompackage`/`@fromparent` as reloading the module is sufficient to remove the hanging method. See this video for an example: ![Link to Video](https://user-images.githubusercontent.com/12846528/236472989-da86a311-4501-4966-9f0b-1298bbd9d53b.mp4) See also: [`@frompackage`](@ref), [`@fromparent`](@ref) """ macro addmethod(ex) if is_notebook_local(String(__source__.file::Symbol)) def = shortdef(ex) fname = def.args[1].args[1] # Switch it to (::typeof(fname)) def.args[1].args[1] = :(::typeof($fname)) esc(def) else esc(ex) end end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
4165
# This function just makes a random alphanumeric id always starting with letter R randid() = "R" * string(rand(UInt32); base = 62) # This function, if appearing inside a capture log message in Pluto (not with # println, just the @info, @warn, etc ones), will hide itself. It is mostly used # in combination with other scripts to inject some javascript in the notebook # without having an ugly empty log below the cell """ hide_this_log(html_content::AbstractString = "") hide_this_log(html::Docs.HTML) Simple function that returns a `Docs.HTML` object which when sent to Pluto logs with e.g. `@info` (or any other loggin macro), will hide the log from view. It is mostly intended to send some javascript to the logs for execution but avoid having an empty log box hanging around below the cell. The output of this function contains a script which will hide the specific log that contains it, and if no other logs are present, will also hide the log container in Pluto. The function also optionally accept some content that will be inserted just before the script for hiding the log. The custom input can be provided as an AbstractString, or directly as an HTML object of type `Docs.HTML`, in which case it will simply extract the HTML contents as `String` from the `contents` field. The provided content will be directly interpreted as HTML, meaning that any script will have to be surrounded by `<script>` tags. This function is used inside PlutoDevMacros to create the `reload @fromparent` button also via logs for redundancy. # Example Suppose you are inside a Pluto notebook and you want to execute some custom javascript from a cell, but for some reason you don't want to have the javascript to be the final output of your cell. You can exploit logs for this (assuming you didn't disable logging for the cell in question). The following snippet can be inserted in a cell to send a custom message on the javascript developer console while still having a non-javascript cell output. ```julia julia_output = let @info PlutoDevMacros.hide_this_log(html"<script>console.log('message')</script>") 3 end ``` Which will correctly send the message to the console even if the cell output is not the javascript script: ![hide_this_log example gif](https://github.com/disberd/PlutoDevMacros.jl/assets/12846528/8208243b-62ce-437a-ae87-97e63ca94e12) """ function hide_this_log(content = ""; id = randid()) #! format: off this_contents = "<script id = '$id' class='hide-this-log'> const logs_positioner = currentScript.closest('pluto-log-dot-positioner') if (logs_positioner == undefined) { return } const logs = logs_positioner.parentElement const logs_container = logs.parentElement const style = html`<style> pluto-logs-container[hidden] { height: 0px; padding: 0px; visibility: hidden; } pluto-log-dot-positioner[hidden] { height: 0px; margin: 0px; visibility: hidden; } </style>` function callBack(mutationList, observer) { let hide_container = true for (const child of logs.children) { const should_hide = child.querySelector('script.hide-this-log') != undefined child.toggleAttribute('hidden', should_hide) hide_container = hide_container && should_hide } // We eventualy hide the container logs_container.toggleAttribute('hidden', hide_container) } const observer = new MutationObserver(callBack) observer.observe(logs, { subtree: true, attributes: true, childList: true }) logs_positioner.toggleAttribute('hidden', true) invalidation.then(() => { console.log('invalidation of logs hider script') callBack() observer.disconnect() }) return style </script>" #! format: on simple_html_cat(content, this_contents) end extract_html_content(x::AbstractString) = x extract_html_content(html::Docs.HTML) = html.content function simple_html_cat(args...) Docs.HTML() do io for arg in args content = extract_html_content(arg) content isa Function ? content(io) : print(io, content) end end end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
625
module FromPackage import ..PlutoDevMacros: @addmethod, _cell_data, is_notebook_local import ..PlutoDevMacros: hide_this_log, simple_html_cat import Pkg import Pkg.Types: Context, EnvCache import TOML using MacroTools: postwalk, flatten, MacroTools, isdef, longdef using JuliaInterpreter: ExprSplitter using Logging export @fromparent, @addmethod, @frompackage include("types.jl") include("consts.jl") include("imports_helpers.jl") include("helpers.jl") include("code_parsing.jl") include("loading.jl") include("input_parsing.jl") include("macro.jl") end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
3786
function extract_file_ast(filename) code = read(filename, String) ast = Meta.parseall(code; filename) @assert Meta.isexpr(ast, :toplevel) return ast end ## custom_walk! ## # This function is inspired by MacroTools.walk (and prewalk/postwalk). It allows to specify custom way of parsing the expressions of an included file/package. The first method is used to process the include statement as the `mapexpr` in the two-argument `include` method (i.e. `include(mapexpr, file)`) function custom_walk!(p::AbstractEvalController) @nospecialize function mapexpr(ex) out = custom_walk!(p, ex) return out end return mapexpr end function custom_walk!(p::AbstractEvalController, ex) @nospecialize if target_reached(p) return RemoveThisExpr() else ex isa Expr || return ex if isdef(ex) ex = longdef(ex) end # We pass through all non Expr, and process the Exprs return custom_walk!(p, ex, Val{ex.head}()) end end # By defaults, all expression which are not explicitly customized simply return the input expression function custom_walk!(p::AbstractEvalController, ex::Expr, ::Val) @nospecialize return ex end # This will add calls below the `using` to track imported names function custom_walk!(p::AbstractEvalController, ex::Expr, ::Val{:using}) @nospecialize new_ex = if inside_extension(p) # We are inside an extension code, we do not need to track usings handle_extensions_imports(p, ex) else # Here we want to track the using expressions # We add the expression to the set for the current module expr_set = get!(Set{Expr}, p.using_expressions, p.current_module) push!(expr_set, ex) # We just leave the expression unchanged ex end return new_ex end function custom_walk!(p::AbstractEvalController, ex::Expr, ::Val{:import}) @nospecialize return handle_extensions_imports(p, ex) end # For function and macro calls, we want to be able to specialize on the name of the function being called function custom_walk!(p::AbstractEvalController, ex::Expr, v::Union{Val{:call}, Val{:macrocall}}) @nospecialize called_name = first(ex.args) |> Symbol return custom_walk!(p, ex, v, Val{called_name}()) end function custom_walk!(::AbstractEvalController, ex::Expr, ::Union{Val{:call}, Val{:macrocall}}, ::Val) @nospecialize return ex end # This handles include calls, by adding p.custom_walk as the mapexpr function custom_walk!(p::AbstractEvalController, ex::Expr, ::Val{:call}, ::Val{:include}) @nospecialize (; current_line) = p new_ex = :($process_include_expr!($p)) append!(new_ex.args, ex.args[2:end]) push!(new_ex.args, String(current_line.file)) return new_ex end # This handles include calls, by adding p.custom_walk as the mapexpr function custom_walk!(p::AbstractEvalController, ex::Expr, ::Val{:macrocall}, ::Union{ Val{Symbol("@frompackage")}, Val{Symbol("@fromparent")}, }) @nospecialize # This will only process and returns the import block of the macro. We process it to exclude invalid statements outside pluto and eventualy track usings new_ex = process_outside_pluto(p, ex.args[end]) return new_ex end # This function will eventually modify using/import expressions inside extensions modules. Outside of extension modules, it will simply return the provided expression function handle_extensions_imports(p::FromPackageController, ex::Expr) @nospecialize @assert Meta.isexpr(ex, (:using, :import)) "You can only call this function with using or import expressions as second argument" inside_extension(p) || return ex return process_import_statement(p, ex; inside_extension = true) end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
411
const IS_DEV = first(fullname(@__MODULE__)) === :Main const TEMP_MODULE_NAME = Symbol(:_FrompPackage_TempModule_, IS_DEV ? "DEV_" : "") const STDLIBS_DATA = Dict{String,Base.UUID}() for (uuid, (name, _)) in Pkg.Types.stdlibs() STDLIBS_DATA[name] = uuid end const PREV_CONTROLLER_NAME = Symbol(:_Previous_Controller_, IS_DEV ? "DEV_" : "") const CURRENT_FROMPACKAGE_CONTROLLER = Ref{FromPackageController}()
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
16967
# This function imitates Base.find_ext_path to get the path of the extension specified by name, from the project in p function find_ext_path(p::ProjectData, extname::String) project_path = dirname(p.file) extfiledir = joinpath(project_path, "ext", extname, extname * ".jl") isfile(extfiledir) && return extfiledir return joinpath(project_path, "ext", extname * ".jl") end function inside_extension(p::FromPackageController{name}) where {name} @nospecialize m = p.current_module nm = nameof(m) exts = keys(p.project.extensions) while nm βˆ‰ (:Main, name) nm = nameof(m) String(nm) in exts && return true m = parentmodule(m) end return false end #= We don't use manual rerun so we just comment this till after we can use it ## simulate manual rerun """ simulate_manual_rerun(cell_id::Base.UUID; PlutoRunner) simulate_manual_rerun(cell_id::String; PlutoRunner) simulate_manual_rerun(cell_id::Array; PlutoRunner) This function takes as input a cell_id or an array of cell_ids (either as `UUID` or as `String`) and simulate a manual rerun for each of the provided cell_ids. This is useful when one wants to programmatically rerun a cell with a macro and recompile the macro like it's done upon manual rerun, but doesn't require to click on the run button on the cell. This is using internal Pluto API so it might break if the Pluto internals change until PlutoDevMacros itself is updated. It works by deleting the cached expression of the cell before triggering a re-run using `PlutoRunner.run_channel` """ function simulate_manual_rerun(cell_id::Base.UUID; PlutoRunner) delete!(PlutoRunner.cell_expanded_exprs, cell_id) delete!(PlutoRunner.computers, cell_id) push!(PlutoRunner.run_channel, cell_id) return nothing end # String version simulate_manual_rerun(cell_id::String; kwargs...) = simulate_manual_rerun(Base.UUID(cell_id);kwargs...) # Array version function simulate_manual_rerun(cell_ids::Array; kwargs...) for cell_id in cell_ids simulate_manual_rerun(cell_id;kwargs...) end end =# ## HTML Popup function _popup_style() #! format: off """ fromparent-container { height: 20px; position: fixed; top: 40px; right: 10px; margin-top: 5px; padding-right: 5px; z-index: 200; background: var(--overlay-button-bg); padding: 5px 8px; border: 3px solid var(--overlay-button-border); border-radius: 12px; height: 35px; font-family: "Segoe UI Emoji", "Roboto Mono", monospace; font-size: 0.75rem; visibility: visible; } fromparent-container.PlutoDevMacros { right: auto; left: 10px; } fromparent-container.PlutoDevMacros:before { content: "Reload PlutoDevMacros" } fromparent-container.errored { border-color: var(--error-cell-color); } fromparent-container:hover { font-weight: 800; cursor: pointer; } body.disable_ui fromparent-container { display: none; } """ #! format: on end function html_reload_button(p::FromPackageController; kwargs...) @nospecialize (; name) = p.project simple_html_cat( beautify_package_path(p), html_reload_button(p.cell_id; name, kwargs...), ) end function html_reload_button(cell_id; name="@frompackage", err=false) id = string(cell_id) text_content = "Reload $name" style_content = _popup_style() #! format: off # We add the text content based on the package name style_content *= """ fromparent-container:before { content: '$text_content'; } """ html_content = """ <script id='html_reload_button'> const container = html`<fromparent-container class='$name'>` // We set the errored state container.classList.toggle('errored', $err) const style = container.appendChild(html`<style>`) style.innerHTML = `$(style_content)` const cell = document.getElementById('$id') const actions = cell._internal_pluto_actions container.onclick = (e) => { if (e.ctrlKey) { history.pushState({}, '') cell.scrollIntoView({ behavior: 'auto', block: 'center', }) } else { actions.set_and_run_multiple(['$id']) } } return container </script> """ #! format: on # We make an HTML object combining this content and the hide_this_log functionality return hide_this_log(html_content) end # Function to clean the filepath from the Pluto cell delimiter if present cleanpath(path::String) = first(split(path, "#==#")) |> abspath # Check if two paths are equal, ignoring case on the drive letter on windows. function issamepath(path1::String, path2::String) path1 = abspath(path1) path2 = abspath(path2) if Sys.iswindows() uppercase(path1[1]) == uppercase(path2[1]) || return false path1[2:end] == path2[2:end] && return true else path1 == path2 && return true end end is_raw_str(ex) = Meta.isexpr(ex, :macrocall) && first(ex.args) === Symbol("@raw_str") # This function extracts the target path by evaluating the ex of the target in the caller module. It will error if `ex` is not a string or a raw string literal if called outside of Pluto function extract_target_path(ex, caller_module::Module; calling_file, notebook_local::Bool=is_notebook_local(calling_file)) valid_outside = ex isa AbstractString || is_raw_str(ex) # If we are not inside a notebook and the path is not provided as string or raw string, we throw an error as the behavior is not supported @assert notebook_local || valid_outside "When calling `@frompackage` outside of a notebook, the path must be provided as `String` or `@raw_str` (i.e. an expression of type `raw\"...\"`)." path = Core.eval(caller_module, ex) # Make the path absolute path = abspath(dirname(calling_file), path) # Eventuallly remove the cell_id from the target path = cleanpath(path) @assert ispath(path) "The extracted path does not seem to be a valid path.\n-`extracted_path`: $path" return path end function beautify_package_path(p::FromPackageController) @nospecialize modpath..., name = fullname(get_temp_module(p)) modpath = map(enumerate(modpath)) do (i, s) Base.isgensym(s) || return String(s) return "var\"$s\"" end regex = """/$(join(modpath, "\\."))(\\.$(name))?/g""" Docs.HTML( #! format: off """ <script id='frompackage-text-replace'> // We have a mutationobserver for each cell: const notebook = document.querySelector('pluto-notebook') const mut_observers = { current: [], } currentScript.mut_observers = mut_observers function replaceTextInNode(node, pattern, replacement, originals = []) { if (node.nodeType === Node.TEXT_NODE) { const content = node.textContent if (!pattern.test(content)) {return} originals.push({node, content}) node.textContent = content.replace(pattern, replacement); } else { node.childNodes.forEach(child => replaceTextInNode(child, pattern, replacement, originals)); } } function execute_cell_observer(observer) { if (invalidated.current) { observer.disconnect() return } const { cell, regex, replacement, originals } = observer const output = cell.querySelector('pluto-output') const content = output.lastChild replaceTextInNode(content, regex, replacement, originals); } function revert_cell_original_text(observer) { observer.originals?.forEach(item => { item.node.textContent = item.content }) } currentScript.revert_original_text = () => { mut_observers.current.forEach(revert_cell_original_text) } const invalidated = { current: false } const createCellObservers = () => { mut_observers.current.forEach((o) => o.disconnect()) mut_observers.current = Array.from(notebook.querySelectorAll("pluto-cell")).map(el => { const o = new MutationObserver((mutations, observer) => {execute_cell_observer(observer)}) o.cell = el o.regex = $regex o.replacement = '$name' o.originals = [] o.observe(el, { attributeFilter: ["class"] }) execute_cell_observer(o) return o }) } createCellObservers() // And one for the notebook's child list, which updates our cell observers: const notebookObserver = new MutationObserver((mutations, observer) => { if (invalidation.current) { observer.disconnect() return } createCellObservers() }) notebookObserver.observe(notebook, { childList: true }) const cell = currentScript.closest('pluto-cell') invalidation.then(() => { invalidated.current = true const revert = cell?.querySelector("script[id='frompackage-text-replace']") == null notebookObserver.disconnect() mut_observers.current.forEach((o) => { revert && revert_cell_original_text(o) o.disconnect() }) }) </script> """ #! format: on ) end function populate_manifest_deps!(p::FromPackageController) @nospecialize (;manifest_deps) = p d = TOML.parsefile(get_manifest_file(p)) for (name, data) in d["deps"] # We use `only` here because I believe the entry will always contain a single dict wrapped in an array. If we encounter a case where this is not true the only will throw instead of silently taking just the first uuid = only(data)["uuid"] |> Base.UUID manifest_deps[uuid] = name end return manifest_deps end # This will extract the path of the manifest file. By default it will error if the manifest can not be found in the env directory, but it can be forced to instantiate/resolve using options function get_manifest_file(p::FromPackageController) @nospecialize (; project, options) = p mode = options.manifest proj_file = project.file envdir = dirname(abspath(proj_file)) manifest_file = if mode in (:instantiate, :resolve) context_kwargs = options.verbose ? (;) : (; io = devnull) c = Context(;env = EnvCache(proj_file), context_kwargs...) resolve = mode === :resolve if resolve Pkg.resolve(c) else Pkg.instantiate(c; update_registry = false, allow_build = false, allow_autoprecomp = false) end joinpath(envdir, "Manifest.toml") else manifest_file = "" for name in ("Manifest.toml", "JuliaManifest.toml") path = joinpath(envdir, name) if isfile(path) manifest_file = path break end end #! format: off @assert !isempty(manifest_file) "A manifest could not be found at the project's location. You have to provide an instantiated environment or set the `manifest` option to `:resolve` or `:instantiate`. EnvDir: $envdir" #! format: on manifest_file end return manifest_file end function update_loadpath(p::FromPackageController) @nospecialize (; verbose) = p.options proj_file = p.project.file if isassigned(CURRENT_FROMPACKAGE_CONTROLLER) prev_proj = CURRENT_FROMPACKAGE_CONTROLLER[].project.file prev_idx = findfirst(==(prev_proj), LOAD_PATH) if !isnothing(prev_idx) && prev_proj !== proj_file verbose && @info "Deleting $prev_proj from LOAD_PATH" deleteat!(LOAD_PATH, prev_idx) end end if proj_file βˆ‰ LOAD_PATH verbose && @info "Adding $proj_file to end of LOAD_PATH" push!(LOAD_PATH, proj_file) end end # This function traverse a path to access a nested module from a `starting_module`. It is used to extract the corresponding module from `import/using` statements. function extract_nested_module(starting_module::Module, nested_path; first_dot_skipped=false) m = starting_module for name in nested_path m = if name === :. first_dot_skipped ? parentmodule(m) : m else @assert isdefined(m, name) "The module `$name` could not be found inside parent module `$(nameof(m))`" getproperty(m, name)::Module end first_dot_skipped = true end return m end # This will create a unique name for a module by translating the PkgId into a symbol unique_module_name(m::Module) = Symbol(Base.PkgId(m)) unique_module_name(uuid::Base.UUID, name::AbstractString) = Symbol(Base.PkgId(uuid, name)) function get_temp_module() if isdefined(Main, TEMP_MODULE_NAME) getproperty(Main, TEMP_MODULE_NAME)::Module else Core.eval(Main, :(module $TEMP_MODULE_NAME module _LoadedModules_ end module _DirectDeps_ end end))::Module end end get_temp_module(s::Symbol) = get_temp_module([s]) function get_temp_module(names::Vector{Symbol}) temp = get_temp_module() out = extract_nested_module(temp, names)::Module return out end function get_temp_module(::FromPackageController{name}) where {name} @nospecialize get_temp_module(name)::Module end get_loaded_modules_mod() = get_temp_module(:_LoadedModules_)::Module get_direct_deps_mod() = get_temp_module(:_DirectDeps_)::Module function populate_loaded_modules(; verbose=false) loaded_modules = get_loaded_modules_mod() @lock Base.require_lock begin for (id, m) in Base.loaded_modules name = Symbol(id) isdefined(loaded_modules, name) && continue Core.eval(loaded_modules, :(const $name = $m)) end end callbacks = Base.package_callbacks if mirror_package_callback βˆ‰ callbacks for i in reverse(eachindex(callbacks)) # This part is only useful when developing this package itself f = callbacks[i] nameof(f) === :mirror_package_callback || continue owner = parentmodule(f) nameof(owner) === nameof(@__MODULE__) || continue isdefined(owner, :IS_DEV) && owner.IS_DEV || continue # We delete this as it's a previous version of the mirror_package_callback function verbose && @warn "Deleting previous version of package_callback function" deleteat!(callbacks, i) end # Add the package callback if not already present push!(callbacks, mirror_package_callback) end end # This function will extract a module from the _LoadedModules_ module which will be populated when each package is loaded in julia function get_dep_from_loaded_modules(key::Symbol) loaded_modules = get_loaded_modules_mod() isdefined(loaded_modules, key) || error("The module $key can not be found in the loaded modules.") m = getproperty(loaded_modules, key)::Module return m end # This is internally calls the previous function, allowing to control which packages can be loaded (by default only direct dependencies and stdlibs are allowed) function get_dep_from_loaded_modules(p::FromPackageController{name}, base_name::Symbol; allow_manifest=false, allow_weakdeps=inside_extension(p), allow_stdlibs=true)::Module where {name} @nospecialize base_name === name && return get_temp_module(p) package_name = string(base_name) # Construct the custom error message error_msg = let msg = """The package with name $package_name could not be found as a dependency$(allow_weakdeps ? " (or weak dependency)" : "") of the target project""" both = allow_manifest && allow_stdlibs allow_manifest && (msg *= """$(both ? "," : " or") as indirect dependency from the manifest""") allow_stdlibs && (msg *= """ or as standard library""") msg *= "." end if allow_stdlibs uuid = get(STDLIBS_DATA, package_name, nothing) uuid !== nothing && return get_dep_from_loaded_modules(unique_module_name(uuid, package_name)) end proj = p.project uuid = get(proj.deps, package_name) do # Throw error unless either of manifest/weakdeps is allowed allow_weakdeps | allow_manifest || error(error_msg) out = get(proj.weakdeps, package_name, nothing) !isnothing(out) && return out allow_manifest || error(error_msg) for (uuid, dep_name) in p.manifest_deps package_name === dep_name && return uuid end error(error_msg) end key = unique_module_name(uuid, package_name) return get_dep_from_loaded_modules(key) end # Basically Base.names but ignores names that are not defined in the module and allows to restrict to only exported names (since 1.11 added also public names as out of names). It also defaults `all` and `imported` to true (to be more precise, to the opposite of `only_exported`) function _names(m::Module; only_exported=false, all=!only_exported, imported=!only_exported, kwargs...) mod_names = names(m; all, imported, kwargs...) filter!(mod_names) do nm isdefined(m, nm) || return false only_exported && return Base.isexported(m, nm) return true end end # Check whether the FromPackageController has reached the target file while loading the module target_reached(p::FromPackageController) = (@nospecialize; p.target_location !== nothing)
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
11455
mutable struct ImportAs original::Vector{Symbol} as::Union{Symbol,Nothing} end ImportAs(nm::Symbol) = ImportAs([nm], nothing) function ImportAs(original::Vector) @assert all(nm -> isa(nm, Symbol), original) "Only vectors containing just symbols are valid inputs to the ImportAs constructor." ImportAs(Symbol.(original), nothing) end function ImportAs(ex::Expr) if ex.head === :. ImportAs(ex.args) elseif ex.head === :as as = last(ex.args) original = first(ex.args).args ImportAs(original, as) else error("The provided expression is not valid for constructing ImportAs.\nOnly `:.` and `:as` are supported as expression head.") end end function reconstruct_import_statement(ia::ImportAs) ex = Expr(:., ia.original...) if ia.as !== nothing ex = Expr(:as, ex, ia.as) end return ex end abstract type ImportData end mutable struct ModuleWithNames <: ImportData head::Symbol modname::ImportAs imported::Vector{ImportAs} end function ModuleWithNames(ex::Expr) args = ex.args is_valid = Meta.isexpr(ex, (:using, :import)) && length(args) == 1 && Meta.isexpr(first(args), :(:)) @assert is_valid "Only import/using expression with an explicit list of imported names are valid inputs to the ModuleWithNames constructor." # We extract the :(:) expression args = first(args).args # The first arg is the module modname = ImportAs(first(args)) # The remaining args are the imported names imported = map(ImportAs, args[2:end]) ModuleWithNames(ex.head, modname, imported) end function reconstruct_import_statement(mwn::ModuleWithNames; head=mwn.head) inner_expr = Expr(:(:), reconstruct_import_statement(mwn.modname), map(reconstruct_import_statement, mwn.imported)...) Expr(head, inner_expr) end mutable struct JustModules <: ImportData head::Symbol modnames::Vector{ImportAs} end function JustModules(ex::Expr) args = ex.args is_valid = Meta.isexpr(ex, (:using, :import)) && all(x -> Meta.isexpr(x, (:., :as)), args) @assert is_valid "Only import/using expression with multiple imported/used modules are valid inputs to the JustModules constructor." JustModules(ex.head, map(ImportAs, args)) end function reconstruct_import_statement(jm::JustModules) Expr(jm.head, map(reconstruct_import_statement, jm.modnames)...) end # This is used to reconstruct a mwn with empty import list function JustModules(mwn::ModuleWithNames) @assert isempty(mwn.imported) "You can only construct a JustModules object with a ModuleWithNames object with an empty import list." JustModules(mwn.head, [mwn.modname]) end function extract_import_data(ex::Expr) @assert Meta.isexpr(ex, (:using, :import)) "You can only use import or using expression as input to the `extract_import_data` function." id = if Meta.isexpr(first(ex.args), :(:)) ModuleWithNames(ex) else JustModules(ex) end return id end is_catchall(ia::ImportAs) = length(ia.original) == 1 && first(ia.original) === :* is_catchall(v::Vector{ImportAs}) = length(v) === 1 && is_catchall(first(v)) is_catchall(mwn::ModuleWithNames) = any(is_catchall, (mwn.imported, mwn.modname)) iterate_imports(mwn::ModuleWithNames) = [mwn] function iterate_imports(jm::JustModules) f(modname::ImportAs) = ModuleWithNames(jm.head, modname, Symbol[]) map(f, jm.modnames) end iterate_imports(ex::Expr) = extract_import_data(ex) |> iterate_imports # This function will add the explicitly imported names to the set of imported names function add_imported_names!(p::FromPackageController, mwn::ModuleWithNames) @nospecialize foreach(mwn.imported) do ia nm = something(ia.as, last(ia.original)) push!(p.imported_names, nm) end end # This function will update the modname_path to make always start from Main. The inner flag specifies whether the provided import expression was found inside the package/extension code, or inside the code given as input to the macro function process_modpath!(mwn::ModuleWithNames, p::FromPackageController{name}; inner::Bool=false) where {name} @nospecialize inner && process_inner_imports!(mwn, p) modname = mwn.modname path = modname.original root_name = popfirst!(path) if root_name in (:ParentModule, :<) @assert !isnothing(p.target_module) "You can't import from the Parent Module when the calling file is not a file `included` in the target package." m = p.target_module prepend!(path, fullname(m)) elseif root_name in (:PackageModule, :^, name) m = get_temp_module(p) prepend!(path, fullname(m)) elseif root_name === :> # Deps import @assert !is_catchall(mwn) "You can't use the catch-all expression when importing from dependencies" m = get_dep_from_loaded_modules(p, first(path); allow_manifest=true) # Replace the deps name with the uuid_name symbol from loaded modules path[1] = unique_module_name(m) # Add the loaded module path prepend!(path, fullname(get_loaded_modules_mod())) elseif root_name === :* # Here we simply substitute the path of the current module, and :* to the imported names imported = mwn.imported @assert isempty(imported) "You can't use the catchall import statement `import *` with explicitly imported names" m = @something p.target_module get_temp_module(p) prepend!(path, fullname(m)) push!(mwn.imported, ImportAs(:*)) elseif root_name === :. @assert inner || !isnothing(p.target_module) "You can't use relative imports when the calling file is not a file `included` in the target package." starting_module = @something p.target_module get_temp_module(p) m = extract_nested_module(starting_module, path; first_dot_skipped=true) modname.original = fullname(m) |> collect else error("The provided import statement is not a valid input for the @frompackage macro.\nIf you want to import from a dependency of the target package, prepend `>.` in front of the package name, e.g. `using >.BenchmarkTools`.") end return end # This function will modify inner imports (i.e. import statements that have been collected while evaluating the package code, rather than ones seen as input to the @frompackage macro) so that they point to the correct module (mostly prepending :> to dependencies) function process_inner_imports!(mwn::ModuleWithNames, ::FromPackageController{name}) where {name} @nospecialize modname_path = mwn.modname.original root_name = modname_path |> first if root_name βˆ‰ (:., name) # If not a relative path and not targeting directly the package module, assume it's a dependency pushfirst!(modname_path, :>) end return end # This function will include all the names of the module as explicit imports in the import statement. It will modify the provided mwn in place and unless usings are excluded, it will also add all the using statements being parsed while evaluating the target module function catchall_import_expression!(mwn::ModuleWithNames, p::FromPackageController, m::Module; exclude_usings::Bool) @nospecialize mwn.imported = filterednames(p, m) .|> ImportAs ex = reconstruct_import_statement(mwn; head=:import) # If we exclude using, we simply return the expression exclude_usings && return ex # Otherwise, we add the using statements we collected for this module block = quote $ex end # We extract the using expression that were encountered while loading the specified module using_expressions = get(Set{Expr}, p.using_expressions, m) old_current = p.current_module try p.current_module = m for ex in using_expressions new_ex = process_import_statement(p, ex; exclude_usings, inner=true) push!(block.args, new_ex) end finally p.current_module = old_current end return block end # This will modify the import statements provided as input to `@frompackage` by updating the modname_path and eventually extracting exported names from the module and explicitly import them. It will also transform each statement into using explicit imported names (even for simple imports) are import/using without explicit names are currently somehow broken in Pluto if not handled by the PkgManager function complete_imported_names!(mwn::ModuleWithNames, p::FromPackageController; exclude_usings::Bool=false, inside_extension::Bool=false, inner::Bool=inside_extension)::Expr catchall = is_catchall(mwn) inner && catchall && error("You can't use the catchall import statement `import *` inside package code") if !isempty(mwn.imported) && !catchall # If we already have an explicit list of imports, we do not modify and simply return the corresponding expression # Here we do not modify the list of explicitily imported names, as it's better to get an error if you explicitly import something that was already defined in the notebook return reconstruct_import_statement(mwn; head=:import) end m = extract_nested_module(Main, mwn.modname.original) if catchall # We extract all the names, potentially include usings encountered return catchall_import_expression!(mwn, p, m; exclude_usings) else if mwn.head === :import # We explicitly import the module itself modname = mwn.modname import_as = ImportAs(nameof(m)) as = modname.as if as !== nothing # We remove the `as` from the module name expression modname.as = nothing # We add it to the imported name import_as.as = as end push!(mwn.imported, import_as) else # We export the names exported by the module mwn.imported = _names(m; only_exported=true) .|> ImportAs end end if !inside_extension # We have to filter the imported names to exclude ones that are already defined in the caller filter_func = filterednames_filter_func(p) filter!(mwn.imported) do import_as as = import_as.as imported_name = something(as, last(import_as.original)) return filter_func(imported_name) end end # The list of imported names should be empty only when inner=false ex = isempty(mwn.imported) ? quote QuoteNode(:_Removed_Import_Statement) end : reconstruct_import_statement(mwn; head=:import) return ex end # This function will generate an importa statement by expanding the modname_path to the correct path based on the provided `starting_module`. It will also expand imported names if a catchall expression is found function process_import_statement(p::FromPackageController, ex::Expr; exclude_usings::Bool=false, inside_extension::Bool=false, inner::Bool=inside_extension) @nospecialize # Extract the import statement data block = quote end for isd in iterate_imports(ex) process_modpath!(isd, p; inner) ex = complete_imported_names!(isd, p; exclude_usings, inside_extension, inner) # We add the imported names to the controller if not evaluating extension code inside_extension || add_imported_names!(p, isd) push!(block.args, ex) end return block end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
5111
function parse_options!(p::FromPackageController, ex::Expr, extra_args) @nospecialize (; options) = p #! format: off error_msg(arg) = "The provided extra arguments at the end of the macro call are not in a supported format. $(arg) Each argument should be in the form `option_name = value`, with the following supported option names and types: - `rootmodule::Bool` - `manifest::Symbol` - `verbose::Bool` Check the documentations for more details on the options." #! format: on for arg in extra_args Meta.isexpr(arg, :(=)) || error(error_msg(arg)) name, val = arg.args typeof(name) in (Symbol, QuoteNode) || error(error_msg(arg)) hasfield(FromPackageOptions, name) || error(error_msg(arg)) val isa QuoteNode && (val = val.value) val isa fieldtype(FromPackageOptions, name) || error(error_msg(arg)) setproperty!(options, name, val) end return nothing end function should_exclude_using_names!(ex::Expr) Meta.isexpr(ex, :macrocall) || return false macro_name = ex.args[1] exclude_name = Symbol("@exclude_using") @assert macro_name === exclude_name "The provided input expression is not supported.\nExpressions should be only import statements, at most prepended by the `@exclude_using` decorator." # If we reach here, we have the include usings. We just extract the underlying expression actual_ex = ex.args[end] ex.head = actual_ex.head ex.args = actual_ex.args return true end # This function will parse the input expression and eventually function process_input_expr(p::FromPackageController, ex) # Eventually remove `@exclude_using` exclude_usings = should_exclude_using_names!(ex) return process_import_statement(p, ex; exclude_usings, inner=false) end function excluded_names(p::FromPackageController) @nospecialize excluded = (:eval, :include, variable_name(p), Symbol("@bind"), :PLUTO_PROJECT_TOML_CONTENTS, :PLUTO_MANIFEST_TOML_CONTENTS, :__init__, PREV_CONTROLLER_NAME) return excluded end function filterednames_filter_func(p::FromPackageController) @nospecialize previous = if isdefined(p.caller_module, PREV_CONTROLLER_NAME) prev_p = getproperty(p.caller_module, PREV_CONTROLLER_NAME)::FromPackageController prev_p.imported_names else Set{Symbol}() end caller_module = p.caller_module f(s)::Bool = let excluded = excluded_names(p), previous = previous, caller_module = caller_module Base.isgensym(s) && return false s in excluded && return false isdefined(caller_module, s) && return s in previous return true end return f end ## Similar to `_names` but allows to exclude names by applying an additional filtering function to the output of `_names`. The default filtering function always returns true function filterednames(m::Module, filter_func = _ -> true; kwargs...) mod_names = _names(m; kwargs...) filter!(filter_func, mod_names) end function filterednames(p::FromPackageController, m::Module; kwargs...) @nospecialize filter_func = filterednames_filter_func(p) return filterednames(m, filter_func; kwargs...) end # This is just for doing some check on the inputs and returning the list of expressions function extract_input_args(ex) # Single import Meta.isexpr(ex, (:import, :using)) && return [ex] # Block of imports Meta.isexpr(ex, :block) && return ex.args # single statement preceded by @exclude_using Meta.isexpr(ex, :macrocall) && ex.args[1] === Symbol("@exclude_using") && return [ex] error("You have to call this macro with an import statement or a begin-end block of import statements") end function process_outside_pluto(p::FromPackageController, ex::Expr) @nospecialize # Remove `@exclude_using` if present should_exclude_using_names!(ex) args = extract_input_args(ex) block = Expr(:block) for arg in args arg isa Expr || continue for mwn in iterate_imports(arg) # We extract the head to keep it modname_path = mwn.modname.original root_name = first(modname_path) # We only support relative and deps imports if root_name === :. # Relative import, we just make sure it's not a catch all is_catchall(mwn) && continue elseif root_name === :> @assert !is_catchall(mwn) "You can't use the catch-all expression when importing from dependencies" # Deps import, we have to make sure we are only importing direct dependencies # We remove the first symbol as its :> popfirst!(modname_path) depname = first(modname_path) String(depname) in keys(p.project.deps) || continue else continue end import_data = isempty(mwn.imported) ? JustModules(mwn) : mwn ex = reconstruct_import_statement(import_data) push!(block.args, ex) end end return block end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
8397
function maybe_call_init(m::Module) # Check if it exists isdefined(m, :__init__) || return nothing # Check if it's owned by this module which(m, :__init__) === m || return nothing f = getproperty(m, :__init__) # Verify that is a function f isa Function || return nothing Core.eval(m, :(__init__())) return nothing end ## ExprSplitter stuff ## # This function separate the LNN and expression that are contained in the :block expressions returned by iteration with ExprSplitter. It is based on the assumption that each `ex` obtained while iterating with `ExprSplitter` are :block expressions with exactly two arguments, the first being a LNN and the second being the relevant expression function destructure_expr(ex::Expr) @assert Meta.isexpr(ex, :block) && length(ex.args) === 2 "The expression does not seem to be coming out of iterating an `ExprSplitter` object" lnn, ex = ex.args end # This function will use ExprSplitter from JuliaInterpreter to cycle through expression and execute them one by one function split_and_execute!(p::FromPackageController, ast::Expr, f=p.custom_walk) @nospecialize top_mod = prev_mod = p.current_module for (mod, ex) in ExprSplitter(top_mod, ast) # Update the current module p.current_module = mod process_exprsplitter_item!(p, ex, f) if prev_mod !== top_mod && mod !== prev_mod maybe_call_init(prev_mod) # We try calling init in the last module after switching end prev_mod = mod end end function process_exprsplitter_item!(p::AbstractEvalController, ex, process_func::Function=p.custom_walk) # We update the current line under evaluation lnn, ex = destructure_expr(ex) p.current_line = lnn # @info "Original" ex new_ex = process_func(ex) # @info "Change" new_ex if !isa(new_ex, RemoveThisExpr) && !target_reached(p) Core.eval(p.current_module, new_ex) end return end ## Misc ## # Returns the name (as Symbol) of the variable where the controller will be stored within the generated module variable_name(p::FromPackageController) = (@nospecialize; :_frompackage_controller_) # This is a callback to add any new loaded package to the Main._FromPackage_TempModule_._LoadedModules_ module function mirror_package_callback(modkey::Base.PkgId) target = get_loaded_modules_mod() name = Symbol(modkey) m = Base.root_module(modkey) Core.eval(target, :(const $name = $m)) if isassigned(CURRENT_FROMPACKAGE_CONTROLLER) try_load_extensions!(CURRENT_FROMPACKAGE_CONTROLLER[]) end return end # This will try to see if the extensions of the target package can be loaded function try_load_extensions!(p::FromPackageController) @nospecialize loaded_modules = get_loaded_modules_mod() (; extensions, deps, weakdeps) = p.project package_name = p.project.name (; options) = p for (name, triggers) in extensions name in p.loaded_extensions && continue nactive = 0 for trigger_name in triggers trigger_uuid = weakdeps[trigger_name] unique_name = unique_module_name(trigger_uuid, trigger_name) is_loaded = isdefined(loaded_modules, unique_name) nactive += is_loaded end if nactive === length(triggers) options.verbose && @info "Loading code of extension $name for package $package_name" entry_path = find_ext_path(p.project, name) # Set the module to the package module parent, which is a temp module in the Pluto workspace p.current_module = get_temp_module(p) |> parentmodule try # Load the extension module inside the package module process_include_expr!(p, entry_path) push!(p.loaded_extensions, name) finally p.current_module = get_temp_module(p) end end end end ### Load Module ### function load_direct_deps(p::FromPackageController) @nospecialize deps_mod = get_direct_deps_mod() for (name, uuid) in p.project.deps name_uuid = unique_module_name(uuid, name) isdefined(deps_mod, name_uuid) && continue Core.eval(deps_mod, :(import $(Symbol(name)) as $name_uuid)) end end function load_module!(p::FromPackageController{name}; reset=true) where {name} @nospecialize # Add to LOAD_PATH if not present update_loadpath(p) # Reinitialize the current module to the base one p.current_module = get_temp_module() if reset # This reset is currently always true, it will be relevant mostly when trying to incorporate Revise # We create the module holding the target package inside the calling pluto workspace. This is done to have Pluto automatically remove any binding the the previous module upon re-run of the cell containing the macro. Not doing so will cause some very weird inconsistencies as some functions will still refer to the previous version of the module which should not exist anymore from within the notebook temp_mod = Core.eval(p.caller_module, :(module $(gensym(:TempModule)) end)) # We create our actal module of interest inside this temp module m = Core.eval(temp_mod, :(module $name end)) # We mirror the generated module inside the temp_module module, so we can alwyas access it without having to know the current workspace Core.eval(get_temp_module(), :($name = $m)) p.options.rootmodule && register_target_as_root(p) # We put the controller inside the module Core.eval(m, :($(variable_name(p)) = $p)) end # We put the controller in the Ref CURRENT_FROMPACKAGE_CONTROLLER[] = p load_direct_deps(p) # We load the direct dependencies Core.eval(p.current_module, process_include_expr!(p, p.entry_point)) # Maybe call init maybe_call_init(get_temp_module(p)) # We populate the loaded modules (; verbose) = p.options populate_loaded_modules(;verbose) # Try loading extensions try_load_extensions!(p) return p end function get_filepath(path::AbstractString, caller_file::Union{Nothing, AbstractString}) @nospecialize base_dir = if isnothing(caller_file) pwd() else dirname(caller_file) end return abspath(base_dir, path) end # This will process include statements by extracting the ast and evaluating the extracted code using ExprSplitter and applying the custom_walk! function to each expression. function process_include_expr!(p::FromPackageController, path::AbstractString, caller_path = nothing) @nospecialize process_include_expr!(p, identity, path, caller_path) end function process_include_expr!(p::FromPackageController, mapexpr::Function, path::AbstractString, caller_path = nothing) @nospecialize filepath = get_filepath(path, caller_path) # @info "Custom Including $(basename(filepath))" if issamepath(p.target_path, filepath) p.target_location = p.current_line p.target_module = p.current_module return nothing end _f = p.custom_walk f = if mapexpr === identity _f else # We compose _f ∘ mapexpr end ast = extract_file_ast(filepath) split_and_execute!(p, ast, f) return nothing end # This function will register the module of the target package as a root module. # This relies on Base internals (and even the C API) so it's disable by default but will allow make the loaded module behave more like if we simply did `using TargetPackage` without the macro function register_target_as_root(p::FromPackageController) @nospecialize (;name, uuid) = p.project m = get_temp_module(p) id = Base.PkgId(uuid, name) (; verbose) = p.options @lock Base.require_lock begin # Set the uuid of this module with the C API. This is required to get the correct UUID just from the module within `register_root_module` ccall(:jl_set_module_uuid, Cvoid, (Any, NTuple{2, UInt64}), m, uuid) # Register this module as root logger = verbose ? Logging.current_logger() : Logging.NullLogger() Logging.with_logger(logger) do Base.register_root_module(m) end # Set the path of the module to the actual package Base.set_pkgorigin_version_path(id, p.entry_point) end end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
4938
import Base: stacktrace, catch_backtrace function wrap_parse_error(e) # Just return the error if we are not in 1.10 or is not a ParseError VERSION >= v"1.10" && e isa Base.Meta.ParseError && hasproperty(e, :detail) || return e # Extract the filename and line of the parseerror (; source, diagnostics) = e.detail byte_index = first(diagnostics) |> Base.JuliaSyntax.first_byte line = Base.JuliaSyntax.source_line(source, byte_index) file = source.filename # We wrap this in a LoadError as if we `included` the file containnig the error return LoadError(file, line, e) end ## @frompackage function frompackage(ex, target_file, caller_module; macroname, cell_id, extra_args) p = FromPackageController(target_file, caller_module; cell_id) p.cell_id !== nothing || return process_outside_pluto(p, ex) parse_options!(p, ex, extra_args) populate_manifest_deps!(p) load_module!(p) args = extract_input_args(ex) for (i, arg) in enumerate(args) arg isa Expr || continue args[i] = process_input_expr(p, arg) end text = "Reload $macroname" out = quote # We put the cell id variable $PREV_CONTROLLER_NAME = $p try $(args...) # We add the reload button as last expression so it's sent to the cell output $html_reload_button($p) catch e # We also send the reload button as an @info log, so that we can use the cell output to format the error nicely @info $html_reload_button($p; err = true) rethrow() end end |> flatten return out end function _combined(ex, target, calling_file, caller_module; macroname, extra_args) # Enforce absolute path to handle different OSs calling_file = abspath(calling_file) _, cell_id = _cell_data(calling_file) notebook_local = !isempty(cell_id) # Get the target file target_file = extract_target_path(target, caller_module; calling_file, notebook_local) out = try frompackage(ex, target_file, caller_module; macroname, cell_id, extra_args) catch e # If we are outside of pluto we simply rethrow notebook_local || rethrow() out = Expr(:block) # We send a log to maintain the reload button @info html_reload_button(cell_id; name = macroname, err=true) # Wrap ParseError in LoadError (see https://github.com/disberd/PlutoDevMacros.jl/issues/30) we = wrap_parse_error(e) bt = stacktrace(catch_backtrace()) # Outputting the CaptureException as last statement allows pretty printing of errors inside Pluto push!(out.args, :(CapturedException($we, $bt))) out end return out end """ @frompackage target import_block This macro takes a local Package (derived from the `target` path, which can be an `AbstractString` or a `@raw_str`), loads it as a submodule of the current Pluto workspace and then process the various import/using statements inside `import_block` to extract varables/functions from the local Package into the notebook workspace. Its main use is allowing to load a local package under development within a running Pluto notebook in order to facilitate prototyping and testing. The following julia code inside a Pluto notebook cell: ```julia @frompackage local_package_path begin import ^: * using >.LocalDependency end ``` takes the main module definition code for the package located at `local_package_path`, creates the corresponding module in the notebook workspace and imports all of the names defined within (That is what the `import ^:*` statement does). Additionally, it loads the package called `LocalDependency` (must be a dependency of the local package) as if the `using LocalDependency` code was used within the notebook, but without adding `LocalDependency` to the notebook environment. See the package [documentation](https://disberd.github.io/PlutoDevMacros.jl/dev/frompackage/introduction/#Introduction) for more details. See also: [`@fromparent`](@ref) """ macro frompackage(target::Union{AbstractString,Expr,Symbol}, ex, extra_args...) calling_file = String(__source__.file) out = _combined(ex, target, calling_file, __module__; macroname="@frompackage", extra_args) esc(out) end """ This macro is equivalent to [`@frompackage`](@ref) but assumes the calling file as the `target` argument. So the code ``` @fromparent import_block ``` is equivalent to ``` @frompackage @__FILE__ import_block ``` Refer to the [`@frompackage`](@ref) docstring and the package [documentation](https://disberd.github.io/PlutoDevMacros.jl/dev/frompackage/introduction/#Introduction) for understanding its use. See also: [`@addmethod`](@ref) """ macro fromparent(ex, extra_args...) calling_file = String(__source__.file) out = _combined(ex, calling_file, calling_file, __module__; macroname="@fromparent", extra_args) esc(out) end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
4448
# This structure is just a placeholder that is put in place of expressions that are to be removed when parsing a file struct RemoveThisExpr end @kwdef mutable struct FromPackageOptions "Specifies whether the target package shall be registered as root module while loading" rootmodule::Bool = false "Symbol to select whether the target environment should be instantiated or resolved before loading the package" manifest::Symbol = :none "Flag to enable verbose logging of FromPackage functions" verbose::Bool = false end struct ProjectData file::String deps::Dict{String, Base.UUID} weakdeps::Dict{String, Base.UUID} extensions::Dict{String, Vector{String}} name::Union{Nothing, String} uuid::Union{Nothing, Base.UUID} version::Union{Nothing, VersionNumber} function ProjectData(file::AbstractString) raw = TOML.parsefile(file) deps = Dict{String, Base.UUID}() for (name, uuid) in get(raw, "deps", ()) deps[name] = Base.UUID(uuid) end weakdeps = Dict{String, Base.UUID}() for (name, uuid) in get(raw, "weakdeps", ()) weakdeps[name] = Base.UUID(uuid) end extensions = Dict{String, Vector{String}}() for (name, deps) in get(raw, "extensions", ()) deps = deps isa String ? [deps] : deps extensions[name] = deps end name = get(raw, "name", nothing) uuid = get(raw, "uuid", nothing) isnothing(uuid) || (uuid = Base.UUID(uuid)) version = get(raw, "version", nothing) isnothing(version) || (version = VersionNumber(version)) new(file, deps, weakdeps, extensions, name, uuid, version) end end abstract type AbstractEvalController end # We do not store the ECG directly inside as @kwdef mutable struct FromPackageController{package_name} <: AbstractEvalController "The entry point of the package" entry_point::String "The path that was provided to the macro call" target_path::String "The data of the project at of the target" project::ProjectData "The module where the macro was called" caller_module::Module "The current module where code evaluation is happening" current_module::Union{Module, Nothing} = nothing "The current line being evaluated" current_line::Union{Nothing, LineNumberNode} = nothing "The dict of manifest deps" manifest_deps::Dict{Base.UUID, String} = Dict{Base.UUID, String}() "The tracked names imported into the current module by `using` statements" using_expressions::Dict{Module, Set{Expr}} = Dict{Module, Set{Expr}}() "Specifies wheter the target was reached while including the module" target_location::Union{Nothing,LineNumberNode} = nothing "Module of where the target is included if the target is found. Nothing otherwise" target_module::Union{Nothing, Module} = nothing "Custom walk function" custom_walk::Function = identity "Loaded Extensions" loaded_extensions::Set{String} = Set{String}() "Names imported by the macro" imported_names::Set{Symbol} = Set{Symbol}() "ID of the cell where the macro was called, nothing if not called from Pluto" cell_id::Union{Nothing, Base.UUID} = nothing "Options to customize loading" options::FromPackageOptions = FromPackageOptions() end # Default constructor function FromPackageController(target_path::AbstractString, caller_module::Module; cell_id = nothing) # We remove pluto cell id in the name if present target_path = cleanpath(target_path) @assert isabspath(target_path) "You can only construct the FromPackageController with an absolute path" # Find the project project_file = Base.current_project(target_path) project_file isa Nothing && error("No project was found starting from $target_path") project = ProjectData(project_file) @assert project.name !== nothing "@frompackage can only be called with a Package as target.\nThe pointed project does not have `name` and `uuid` fields" entry_point = joinpath(dirname(project_file), "src", project.name * ".jl") name = project.name # We parse the cell_id if string cell_id = cell_id isa AbstractString ? (isempty(cell_id) ? nothing : Base.UUID(cell_id)) : cell_id p = FromPackageController{Symbol(name)}(;entry_point, target_path, project, caller_module, cell_id) p.custom_walk = custom_walk!(p) return p end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1380
import Pluto: update_save_run!, update_run!, WorkspaceManager, ClientSession, ServerSession, Notebook, Cell, project_relative_path, SessionActions, load_notebook, Configuration using PlutoDevMacros using PlutoDevMacros: hide_this_log using Test function noerror(cell; verbose=true) if cell.errored && verbose @show cell.output.body end !cell.errored end @testset "Outside Pluto" begin @current_pluto_cell_id() === "" @current_pluto_notebook_file() === "" @only_in_nb(3) === nothing @only_out_nb(3) === 3 asd(x::Int) = 3 @addmethod asd(x::Float64) = 4.0 @addmethod asd(x::String) = "LOL" * string(asd(1)) @test asd(3.0) === 4.0 @test asd("ASD") === "LOL3" @test PlutoDevMacros.is_notebook_local() === false lnn = LineNumberNode(1, @__FILE__) @test PlutoDevMacros.is_notebook_local(lnn) === false end options = Configuration.from_flat_kwargs(; disable_writing_notebook_files=true, workspace_use_distributed_stdlib = true) srcdir = normpath(@__DIR__, "./notebooks") eval_in_nb(sn, expr) = WorkspaceManager.eval_fetch_in_workspace(sn, expr) @testset "basics test notebook" begin ss = ServerSession(; options) path = joinpath(srcdir, "basics.jl") nb = SessionActions.open(ss, path; run_async=false) for cell in nb.cells @test noerror(cell) end SessionActions.shutdown(ss, nb) end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
468
using TestItemRunner @testitem "Aqua" begin using Aqua using PlutoDevMacros Aqua.test_all(PlutoDevMacros) end @testitem "Basics" begin include("basics.jl") end # @safetestset "@frompackage: basics" begin include("frompackage/basics.jl") end # @safetestset "@frompackage: settings" begin include("frompackage/settings.jl") end include("frompackage/with_pluto_session.jl") include("frompackage/pluto_package_extensions.jl") @run_package_tests verbose=true
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1268
### A Pluto.jl notebook ### # v0.19.42 using Markdown using InteractiveUtils # ╔═║ 9ff61650-18ef-11ef-165b-13081b75c35f begin test_project = Base.current_project(normpath(@__DIR__, "..")) notebook_project = Base.active_project() plutodevmacros_project= Base.current_project(normpath(@__DIR__, "../..")) Base.eval(Main, quote # instantiate the parent env, mostly for CI import Pkg Pkg.activate($test_project) Pkg.instantiate() Pkg.activate($notebook_project) end) pushfirst!(LOAD_PATH, test_project) # This contains Revise pushfirst!(LOAD_PATH, plutodevmacros_project) # This loads the PlutoDevMacros environment, so we can do import with the latest version try Base.eval(Main, :(import Revise)) Base.eval(Main, :(import PlutoDevMacros)) finally popfirst!(LOAD_PATH) # Remove plutodevmacros env popfirst!(LOAD_PATH) # Remove parent_env end using Main.Revise using Main.PlutoDevMacros end # ╔═║ e9f7421b-9ed0-4f4d-b458-689b301dad5c @fromparent begin using * using >.TestPackage end # ╔═║ 4b493e7f-78d5-4005-b7c8-630dca053e6b TestPackage isa Module || error("TestPackage not loaded correctly") # ╔═║ Cell order: # ╠═9ff61650-18ef-11ef-165b-13081b75c35f # ╠═e9f7421b-9ed0-4f4d-b458-689b301dad5c # ╠═4b493e7f-78d5-4005-b7c8-630dca053e6b
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
90
module TestDevDependency greet() = print("Hello World!") end # module TestDevDependency
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1467
### A Pluto.jl notebook ### # v0.19.43 using Markdown using InteractiveUtils # ╔═║ c2b18f94-b49d-4b4e-a485-85072cb797bf begin import Pkg Pkg.activate(joinpath(@__DIR__, "notebook_env")) using Revise end # ╔═║ abccfc80-afaf-4c54-b300-c0c893de3848 begin using PlutoDevMacros using PlutoPlotly using Example end # ╔═║ 90ca1f01-cbad-496a-b3e2-7dc7231ed101 @fromparent using PackageModule # ╔═║ 675230da-e628-4059-b44d-6137a4dd4987 standard_extension_output = to_extend(plot(rand(4)).Plot) # ╔═║ 8e7563ce-d2ba-4356-93e4-70ebe0f2be87 weird_extension_output = to_extend(Example) # ╔═║ 8d561235-2003-4446-bd64-b7f235d653a4 standard_extension_output === "Standard Extension works!" || error("PlotlyBase extension did not load") # ╔═║ 6f258d3c-7c09-4009-ad8d-001dbd451ad2 weird_extension_output === "Weird Extension name works!" || error("Example extension did not load") # ╔═║ da703251-1f4a-4fa1-ba08-720bceb2ada6 p = plot_this() # ╔═║ 1e143a84-1a79-448b-a7ff-189ef167870d to_extend((hello, p.Plot)) === "Dual Deps Extension works!" || error("dual deps extension failed") # ╔═║ Cell order: # ╠═c2b18f94-b49d-4b4e-a485-85072cb797bf # ╠═abccfc80-afaf-4c54-b300-c0c893de3848 # ╠═90ca1f01-cbad-496a-b3e2-7dc7231ed101 # ╠═675230da-e628-4059-b44d-6137a4dd4987 # ╠═8e7563ce-d2ba-4356-93e4-70ebe0f2be87 # ╠═8d561235-2003-4446-bd64-b7f235d653a4 # ╠═6f258d3c-7c09-4009-ad8d-001dbd451ad2 # ╠═1e143a84-1a79-448b-a7ff-189ef167870d # ╠═da703251-1f4a-4fa1-ba08-720bceb2ada6
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
209
module DualDepsExt import Example import PlotlyBase import TestDirectExtension TestDirectExtension.to_extend(::Tuple{typeof(Example.hello), PlotlyBase.Plot}) = "Dual Deps Extension works!" end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
264
module PlotlyBaseExt using PlotlyBase using TestDirectExtension using TestDirectExtension.PlotlyExtensionsHelper TestDirectExtension.to_extend(p::Plot) = "Standard Extension works!" TestDirectExtension.plot_this() = plotly_plot(rand(10,4)) end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
78
module Magic using TestDirectExtension include("includemagic.jl") end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
72
TestDirectExtension.to_extend(m::Module) = "Weird Extension name works!"
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
199
module TestDirectExtension using PlotlyExtensionsHelper using HypertextLiteral export to_extend, plot_this to_extend(x) = "Generic Method" function plot_this end end # module TestDirectExtension
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
12234
### A Pluto.jl notebook ### # v0.19.43 using Markdown using InteractiveUtils # ╔═║ abcc4604-aa6c-4830-8909-5811aa6eab8d # Here we import PlutoDevMacros itself with @frompackage so we can reload it PDM.@frompackage "../.." begin import PackageModule.FromPackage: * end verbose = true # Verbose here makes deletion of package callback logs below (only after first run) # ╔═║ 12d02710-36fa-11ef-1430-512f552ee8e1 begin # We do a hack to import PlutoDevMacros plutodevmacros_proj = Base.current_project("../..") |> abspath push!(LOAD_PATH, plutodevmacros_proj) try Core.eval(Main, :(import PlutoDevMacros as PDM)) finally pop!(LOAD_PATH) end PDM = Main.PDM end # ╔═║ f120af18-d655-4221-b53c-028f0c396e2f # This should trigger the extension in the direct dependency PlotlyExtensionHelper using PlotlyBase # ╔═║ 308cbcf0-2a0b-4e97-b5f1-30f8d06020c6 # Here we instead import the TestPackage module @fromparent import * verbose = true rootmodule = true manifest = :instantiate # ╔═║ edac1ff6-d264-4268-8063-0b4f4e0d8dca md""" ## Rootmodule """ # ╔═║ 5762c453-fc45-49e2-b71a-f15036c81d30 pkgdir(TestInception) === (@__DIR__) || error("The registration as root module did not seem to work, pkgdir returns the wrong path") # ╔═║ bdac8541-fca9-4650-a9bb-485519fa02b8 md""" ## Indirect Extension """ # ╔═║ 6ae6e908-d78e-4e23-9565-a0a44c9d509e hasmethod(PlotlyExtensionsHelper._plot_func, Tuple{Val{:PlotlyBase}}) || error("The indirect extension was not loaded correctly") # ╔═║ 340e3c74-6504-45d9-b23f-d60b71ffe527 md""" ## Direct Extension (Single) """ # ╔═║ d189a27d-5612-41a7-937c-756644c669b3 import SimplePlutoInclude # This triggers a direct extension # ╔═║ d11a039c-32fc-451f-af42-e4abcdf8e8b4 isdefined(parentmodule(TestInception), :SingleExtension) || error("The single dependency extension did not seem to load correctly") # ╔═║ bbc3bdc3-249f-4b56-8ba2-c2694932372f md""" ## Direct Extension (Dual) """ # ╔═║ 3e2621f4-bd00-4e6a-b44b-dd62091228c4 import Example # This triggers the other direct extension depending on both SimplePlutoInclude and Example # ╔═║ 0be0fe0b-a40c-4575-934d-26b289f06e98 isdefined(parentmodule(TestInception), :DualExtension) || error("The single dependency extension did not seem to load correctly") # ╔═║ b81acc6d-df12-48af-9f12-5f79b6ab59bc dual_extension_loaded[] || error("The single dependency extension did not seem to load correctly") # ╔═║ 16528b1e-e59b-426d-9ba5-37c2f83ab775 md""" ## Test Reload """ # ╔═║ 4244baf8-bd30-4d81-9236-f4291b364c44 random_variable # ╔═║ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] Example = "7876af07-990d-54b4-ab0e-23690620f79a" PlotlyBase = "a03496cd-edff-5a9b-9e67-9cda94a718b5" SimplePlutoInclude = "6f00a2c5-ea4a-46bf-9183-91b7b57a087f" [compat] Example = "~0.5.3" PlotlyBase = "~0.8.19" SimplePlutoInclude = "~0.1.0" """ # ╔═║ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.10.4" manifest_format = "2.0" project_hash = "e006c989728577e863f2417116df37ca484b4a62" [[deps.ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" version = "1.1.1" [[deps.Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[deps.Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[deps.ColorSchemes]] deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"] git-tree-sha1 = "4b270d6465eb21ae89b732182c20dc165f8bf9f2" uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4" version = "3.25.0" [[deps.ColorTypes]] deps = ["FixedPointNumbers", "Random"] git-tree-sha1 = "b10d0b65641d57b8b4d5e234446582de5047050d" uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f" version = "0.11.5" [[deps.ColorVectorSpace]] deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "Requires", "Statistics", "TensorCore"] git-tree-sha1 = "a1f44953f2382ebb937d60dafbe2deea4bd23249" uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4" version = "0.10.0" [deps.ColorVectorSpace.extensions] SpecialFunctionsExt = "SpecialFunctions" [deps.ColorVectorSpace.weakdeps] SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b" [[deps.Colors]] deps = ["ColorTypes", "FixedPointNumbers", "Reexport"] git-tree-sha1 = "362a287c3aa50601b0bc359053d5c2468f0e7ce0" uuid = "5ae59095-9a9b-59fe-a467-6f913c188581" version = "0.12.11" [[deps.CompilerSupportLibraries_jll]] deps = ["Artifacts", "Libdl"] uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" version = "1.1.1+0" [[deps.Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[deps.DelimitedFiles]] deps = ["Mmap"] git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae" uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" version = "1.9.1" [[deps.DocStringExtensions]] deps = ["LibGit2"] git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d" uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" version = "0.9.3" [[deps.Downloads]] deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" version = "1.6.0" [[deps.Example]] git-tree-sha1 = "46e44e869b4d90b96bd8ed1fdcf32244fddfb6cc" uuid = "7876af07-990d-54b4-ab0e-23690620f79a" version = "0.5.3" [[deps.FileWatching]] uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" [[deps.FixedPointNumbers]] deps = ["Statistics"] git-tree-sha1 = "05882d6995ae5c12bb5f36dd2ed3f61c98cbb172" uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" version = "0.8.5" [[deps.InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[deps.JSON]] deps = ["Dates", "Mmap", "Parsers", "Unicode"] git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a" uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" version = "0.21.4" [[deps.LaTeXStrings]] git-tree-sha1 = "50901ebc375ed41dbf8058da26f9de442febbbec" uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" version = "1.3.1" [[deps.LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" version = "0.6.4" [[deps.LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" version = "8.4.0+0" [[deps.LibGit2]] deps = ["Base64", "LibGit2_jll", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[deps.LibGit2_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll"] uuid = "e37daf67-58a4-590a-8e99-b0245dd2ffc5" version = "1.6.4+0" [[deps.LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" version = "1.11.0+1" [[deps.Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[deps.LinearAlgebra]] deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"] uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" [[deps.Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[deps.Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[deps.MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" version = "2.28.2+1" [[deps.Mmap]] uuid = "a63ad114-7e13-5084-954f-fe012c677804" [[deps.MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" version = "2023.1.10" [[deps.NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" version = "1.2.0" [[deps.OpenBLAS_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" version = "0.3.23+4" [[deps.OrderedCollections]] git-tree-sha1 = "dfdf5519f235516220579f949664f1bf44e741c5" uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" version = "1.6.3" [[deps.Parameters]] deps = ["OrderedCollections", "UnPack"] git-tree-sha1 = "34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe" uuid = "d96e819e-fc66-5662-9728-84c9c7592b0a" version = "0.12.3" [[deps.Parsers]] deps = ["Dates", "PrecompileTools", "UUIDs"] git-tree-sha1 = "8489905bcdbcfac64d1daa51ca07c0d8f0283821" uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" version = "2.8.1" [[deps.Pkg]] deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" version = "1.10.0" [[deps.PlotlyBase]] deps = ["ColorSchemes", "Dates", "DelimitedFiles", "DocStringExtensions", "JSON", "LaTeXStrings", "Logging", "Parameters", "Pkg", "REPL", "Requires", "Statistics", "UUIDs"] git-tree-sha1 = "56baf69781fc5e61607c3e46227ab17f7040ffa2" uuid = "a03496cd-edff-5a9b-9e67-9cda94a718b5" version = "0.8.19" [[deps.PrecompileTools]] deps = ["Preferences"] git-tree-sha1 = "5aa36f7049a63a1528fe8f7c3f2113413ffd4e1f" uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a" version = "1.2.1" [[deps.Preferences]] deps = ["TOML"] git-tree-sha1 = "9306f6085165d270f7e3db02af26a400d580f5c6" uuid = "21216c6a-2e73-6563-6e65-726566657250" version = "1.4.3" [[deps.Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[deps.REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[deps.Random]] deps = ["SHA"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[deps.Reexport]] git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b" uuid = "189a3867-3050-52da-a836-e630ba90ab69" version = "1.2.2" [[deps.Requires]] deps = ["UUIDs"] git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7" uuid = "ae029012-a4dd-5104-9daa-d747884805df" version = "1.3.0" [[deps.SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" version = "0.7.0" [[deps.Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[deps.SimplePlutoInclude]] git-tree-sha1 = "db4e715674a7ad0fcc00bf1dc55f40a3bfc6ab15" uuid = "6f00a2c5-ea4a-46bf-9183-91b7b57a087f" version = "0.1.0" [[deps.Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[deps.SparseArrays]] deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"] uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" version = "1.10.0" [[deps.Statistics]] deps = ["LinearAlgebra", "SparseArrays"] uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" version = "1.10.0" [[deps.SuiteSparse_jll]] deps = ["Artifacts", "Libdl", "libblastrampoline_jll"] uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c" version = "7.2.1+1" [[deps.TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" version = "1.0.3" [[deps.Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" version = "1.10.0" [[deps.TensorCore]] deps = ["LinearAlgebra"] git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6" uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50" version = "0.1.1" [[deps.UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[deps.UnPack]] git-tree-sha1 = "387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b" uuid = "3a884ed6-31ef-47d7-9d2a-63182c4928ed" version = "1.0.2" [[deps.Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[deps.Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" version = "1.2.13+1" [[deps.libblastrampoline_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" version = "5.8.0+1" [[deps.nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" version = "1.52.0+1" [[deps.p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" version = "17.4.0+2" """ # ╔═║ Cell order: # ╠═12d02710-36fa-11ef-1430-512f552ee8e1 # ╠═abcc4604-aa6c-4830-8909-5811aa6eab8d # ╠═308cbcf0-2a0b-4e97-b5f1-30f8d06020c6 # β•Ÿβ”€edac1ff6-d264-4268-8063-0b4f4e0d8dca # ╠═5762c453-fc45-49e2-b71a-f15036c81d30 # β•Ÿβ”€bdac8541-fca9-4650-a9bb-485519fa02b8 # ╠═f120af18-d655-4221-b53c-028f0c396e2f # ╠═6ae6e908-d78e-4e23-9565-a0a44c9d509e # ╠═340e3c74-6504-45d9-b23f-d60b71ffe527 # ╠═d189a27d-5612-41a7-937c-756644c669b3 # ╠═d11a039c-32fc-451f-af42-e4abcdf8e8b4 # ╠═bbc3bdc3-249f-4b56-8ba2-c2694932372f # ╠═3e2621f4-bd00-4e6a-b44b-dd62091228c4 # ╠═0be0fe0b-a40c-4575-934d-26b289f06e98 # ╠═b81acc6d-df12-48af-9f12-5f79b6ab59bc # β•Ÿβ”€16528b1e-e59b-426d-9ba5-37c2f83ab775 # ╠═4244baf8-bd30-4d81-9236-f4291b364c44 # β•Ÿβ”€00000000-0000-0000-0000-000000000001 # β•Ÿβ”€00000000-0000-0000-0000-000000000002
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
189
module DualExtension using Example using SimplePlutoInclude using TestInception @info "Loading DualExtension" Example SimplePlutoInclude TestInception.dual_extension_loaded[] = true end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
125
module SingleExtension using SimplePlutoInclude using TestInception @info "Loading SingleExtension" SimplePlutoInclude end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
147
module TestInception using PlotlyExtensionsHelper random_variable = rand() dual_extension_loaded = Ref{Bool}(false) end # module TestInception
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
6514
### A Pluto.jl notebook ### # v0.19.43 using Markdown using InteractiveUtils # ╔═║ f6bb9eb6-1f66-424a-9043-607aeee0cd76 begin test_project = Base.current_project(normpath(@__DIR__, "..")) notebook_project = Base.active_project() plutodevmacros_project= Base.current_project(normpath(@__DIR__, "../..")) Base.eval(Main, quote # instantiate the parent env, mostly for CI import Pkg Pkg.activate($test_project) Pkg.instantiate() Pkg.activate($notebook_project) end) pushfirst!(LOAD_PATH, test_project) # This contains Revise pushfirst!(LOAD_PATH, plutodevmacros_project) # This loads the PlutoDevMacros environment, so we can do import with the latest version try Base.eval(Main, :(import Revise)) Base.eval(Main, :(import PlutoDevMacros)) finally popfirst!(LOAD_PATH) # Remove plutodevmacros env popfirst!(LOAD_PATH) # Remove parent_env end using Main.Revise using Main.PlutoDevMacros end # ╔═║ abccfc80-afaf-4c54-b300-c0c893de3848 begin using PlotlyKaleido end # ╔═║ f5fef1d2-eaab-4f43-91f2-a58d2d881733 @fromparent begin using >.PlutoPlotly end # ╔═║ 790cb87b-472c-4aa3-a656-fc61e19b4995 method_present = !isempty(methods(savefig, (IO, PlutoPlot))) # ╔═║ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] PlotlyKaleido = "f2990250-8cf9-495f-b13a-cce12b45703c" [compat] PlotlyKaleido = "~2.1.0" """ # ╔═║ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.10.4" manifest_format = "2.0" project_hash = "a306e345b2ba616e53c5188b7eca690040bebb51" [[deps.ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" version = "1.1.1" [[deps.Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[deps.Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[deps.Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[deps.Downloads]] deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" version = "1.6.0" [[deps.FileWatching]] uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" [[deps.InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[deps.JLLWrappers]] deps = ["Artifacts", "Preferences"] git-tree-sha1 = "7e5d6779a1e09a36db2a7b6cff50942a0a7d0fca" uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210" version = "1.5.0" [[deps.JSON]] deps = ["Dates", "Mmap", "Parsers", "Unicode"] git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a" uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" version = "0.21.4" [[deps.Kaleido_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] git-tree-sha1 = "43032da5832754f58d14a91ffbe86d5f176acda9" uuid = "f7e6163d-2fa5-5f23-b69c-1db539e41963" version = "0.2.1+0" [[deps.LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" version = "0.6.4" [[deps.LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" version = "8.4.0+0" [[deps.LibGit2]] deps = ["Base64", "LibGit2_jll", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[deps.LibGit2_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll"] uuid = "e37daf67-58a4-590a-8e99-b0245dd2ffc5" version = "1.6.4+0" [[deps.LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" version = "1.11.0+1" [[deps.Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[deps.Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[deps.Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[deps.MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" version = "2.28.2+1" [[deps.Mmap]] uuid = "a63ad114-7e13-5084-954f-fe012c677804" [[deps.MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" version = "2023.1.10" [[deps.NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" version = "1.2.0" [[deps.Parsers]] deps = ["Dates", "PrecompileTools", "UUIDs"] git-tree-sha1 = "716e24b21538abc91f6205fd1d8363f39b442851" uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" version = "2.7.2" [[deps.Pkg]] deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" version = "1.10.0" [[deps.PlotlyKaleido]] deps = ["Base64", "JSON", "Kaleido_jll"] git-tree-sha1 = "f96e4582db7a9533487b94f6258b8a01c69f18b0" uuid = "f2990250-8cf9-495f-b13a-cce12b45703c" version = "2.1.0" [[deps.PrecompileTools]] deps = ["Preferences"] git-tree-sha1 = "9673d39decc5feece56ef3940e5dafba15ba0f81" uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a" version = "1.1.2" [[deps.Preferences]] deps = ["TOML"] git-tree-sha1 = "7eb1686b4f04b82f96ed7a4ea5890a4f0c7a09f1" uuid = "21216c6a-2e73-6563-6e65-726566657250" version = "1.4.0" [[deps.Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[deps.REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[deps.Random]] deps = ["SHA"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[deps.SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" version = "0.7.0" [[deps.Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[deps.Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[deps.TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" version = "1.0.3" [[deps.Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" version = "1.10.0" [[deps.UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[deps.Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[deps.Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" version = "1.2.13+1" [[deps.nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" version = "1.52.0+1" [[deps.p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" version = "17.4.0+2" """ # ╔═║ Cell order: # ╠═f6bb9eb6-1f66-424a-9043-607aeee0cd76 # ╠═abccfc80-afaf-4c54-b300-c0c893de3848 # ╠═f5fef1d2-eaab-4f43-91f2-a58d2d881733 # ╠═790cb87b-472c-4aa3-a656-fc61e19b4995 # β•Ÿβ”€00000000-0000-0000-0000-000000000001 # β•Ÿβ”€00000000-0000-0000-0000-000000000002
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
98
module TestIndirectExtension greet() = print("Hello World!") end # module TestIndirectExtension
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
4183
### A Pluto.jl notebook ### # v0.19.43 using Markdown using InteractiveUtils # ╔═║ 931a8c2c-ed76-11ed-3721-396dae146ad4 # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate(Base.current_project(@__FILE__)) # Revise is only used for internal testing during development to update the # changes to PlutoDevMacros using Revise end ╠═║ =# # ╔═║ bd0d177f-ab66-493d-89a6-a9faca81cd11 using PlutoDevMacros # ╔═║ ca13553c-d246-437a-9962-2a2045c7dd12 @fromparent begin import TestPackage end # ╔═║ 9cab38df-9ba5-4f6a-b568-b8699d44e0d4 md""" ## Basic Tests """ # ╔═║ 16a4e5e1-bde4-45a6-8777-ee4c7aa3d8f2 isdefined(TestPackage, :Issue2) || error("TestPackage should have the Issue2 module") # ╔═║ 71c1f0f3-79d9-4358-8032-9f7dee73836b isdefined(TestPackage.Issue2, :CoolStruct) || error("CoolStruct2 inside module Issue2 should be defined") # ╔═║ c231c321-b89f-4f1a-8a60-5eb03c098fa1 isdefined(TestPackage, :SpecificImport) || error("The module SpecificImport was not found, it should be there but empty") # ╔═║ 06408ada-f0b7-4057-9177-a79baf2fa9cf isdefined(TestPackage, :TEST_INIT) && TestPackage.TEST_INIT[] == 5 || error("The execution of the __init__ function did not seem to happen") # ╔═║ e37034a1-398c-45ad-803c-4b78e3388464 isdefined(TestPackage.SUBINIT, :TEST_SUBINIT) && TestPackage.SUBINIT.TEST_SUBINIT[] == 15 || error("The execution of the __init__ function in the submodule did not seem to happen") # ╔═║ 4a72716e-13a5-4914-a02f-8df4d590091f md""" ## ImportAs Tests This tests that import statements with `x as y` work """ # ╔═║ 8642825b-d05c-407b-84ad-958a83a92953 !isdefined(TestPackage.ImportAsStatements, :CT) || error("The CT module should not be defined inside the ImportAsStatements submodule") # ╔═║ 081f71cb-8512-4b66-9f64-80a7c3fa8a71 let m = TestPackage.ImportAsStatements isdefined(m, :tp) & isdefined(m, :TML) || error("`tp` and `TML` should be defined inside the ImportAsStatements module") end # ╔═║ 5c9a13c3-78b1-45a6-b9d9-67983e4fb927 md""" ## map expr tests This tests that using custom `mapexpr` function within include statements in the package works """ # ╔═║ c3691cc1-9cfb-460e-b94a-15c9357b0892 TestPackage.MapExpr.should_be_100 == 100 || error("The custom application of mapexpr in `include` did not work") # ╔═║ 83b8c9bb-c831-48cd-8d5d-0c9b8691d35c TestPackage.MapExpr.should_not_be_15 !== 15 || error("The custom application of mapexpr in `include` did not work.\nVariable `should_not_be_15` is 15") # ╔═║ a298f325-85ef-4b48-a15c-67080515dd8d !isdefined(TestPackage.MapExpr, :var_to_delete) || error("The custom application of mapexpr in `include` did not work") # ╔═║ 79a035c0-9138-4b47-87ab-1ce5e4b9a4d4 md""" ## Prettify Output This tests that the types and function defined in the target package do not show the full module names which includes various temp modules !!! note These tests can not be assessed outside of the browser as the _beautifying_ function is in javascript. """ # ╔═║ 53dcca38-0014-4b0c-9a5c-f8cf6779a16f TestPackage.PrettyPrint # ╔═║ 12e174cd-b431-4df9-80bc-e7e8974eee71 methods(TestPackage.PrettyPrint.some_function) # ╔═║ 783ae9cf-05a4-40c9-814d-c359bde6c668 TestPackage.testmethod |> methods # ╔═║ 0fd4ad04-b7cd-4055-aec4-e5c2612ebef2 let M = TestPackage.PrettyPrint M.some_function(M.SomeType()) end # ╔═║ Cell order: # ╠═931a8c2c-ed76-11ed-3721-396dae146ad4 # ╠═bd0d177f-ab66-493d-89a6-a9faca81cd11 # ╠═ca13553c-d246-437a-9962-2a2045c7dd12 # β•Ÿβ”€9cab38df-9ba5-4f6a-b568-b8699d44e0d4 # ╠═16a4e5e1-bde4-45a6-8777-ee4c7aa3d8f2 # ╠═71c1f0f3-79d9-4358-8032-9f7dee73836b # ╠═c231c321-b89f-4f1a-8a60-5eb03c098fa1 # ╠═06408ada-f0b7-4057-9177-a79baf2fa9cf # ╠═e37034a1-398c-45ad-803c-4b78e3388464 # β•Ÿβ”€4a72716e-13a5-4914-a02f-8df4d590091f # ╠═8642825b-d05c-407b-84ad-958a83a92953 # ╠═081f71cb-8512-4b66-9f64-80a7c3fa8a71 # β•Ÿβ”€5c9a13c3-78b1-45a6-b9d9-67983e4fb927 # ╠═c3691cc1-9cfb-460e-b94a-15c9357b0892 # ╠═83b8c9bb-c831-48cd-8d5d-0c9b8691d35c # ╠═a298f325-85ef-4b48-a15c-67080515dd8d # β•Ÿβ”€79a035c0-9138-4b47-87ab-1ce5e4b9a4d4 # ╠═53dcca38-0014-4b0c-9a5c-f8cf6779a16f # ╠═12e174cd-b431-4df9-80bc-e7e8974eee71 # ╠═783ae9cf-05a4-40c9-814d-c359bde6c668 # ╠═0fd4ad04-b7cd-4055-aec4-e5c2612ebef2
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1936
### A Pluto.jl notebook ### # v0.19.42 using Markdown using InteractiveUtils # ╔═║ 071ec1a4-eda6-11ed-3a1b-c1347c9fafa5 begin plutodevmacros_project= Base.current_project(normpath(@__DIR__, "../..")) # pushfirst!(LOAD_PATH, parent_project) # This contains Revise pushfirst!(LOAD_PATH, plutodevmacros_project) # This loads the PlutoDevMacros environment, so we can do import with the latest version try # Base.eval(Main, :(import Revise)) Base.eval(Main, :(import PlutoDevMacros)) finally popfirst!(LOAD_PATH) # Remove plutodevmacros env # popfirst!(LOAD_PATH) # Remove parent_env end # using Main.Revise using Main.PlutoDevMacros end # ╔═║ e12b4f7a-0d4a-4fa2-a850-faa6cb626795 @fromparent begin import PackageModule: toplevel_variable import ^.Issue2: GreatStructure import >.TOML using >.BenchmarkTools end # ╔═║ d341f653-e1d0-4fbf-b83f-fccaa383cfa8 isdefined(@__MODULE__, :toplevel_variable) || error("toplevel_variable should be defined") # ╔═║ 0cee8704-b824-4274-880d-9d00645fbdd2 isdefined(@__MODULE__, :TOML) || error("TOML package was not imported apparently") # ╔═║ a187f7aa-3d21-43d5-a877-83a49db3d965 isdefined(@__MODULE__, Symbol("@benchmark")) || error("@benchmark macro not defined in module, the `using BenchmarkTools` import statement was not respected") # ╔═║ f2aebf0c-b135-4735-89d2-716d9983d42c GreatStructure isa DataType || error("GreatStructure should be defined (and a Type)") # ╔═║ 3decbd80-c1bc-4d00-b89e-7f3ddaa07683 isdefined(@__MODULE__, Symbol("@benchmark")) || error("@benchmark should be available as BenchmarkTools should have been loaded as dependency by @fromparent") # ╔═║ Cell order: # ╠═071ec1a4-eda6-11ed-3a1b-c1347c9fafa5 # ╠═e12b4f7a-0d4a-4fa2-a850-faa6cb626795 # ╠═d341f653-e1d0-4fbf-b83f-fccaa383cfa8 # ╠═0cee8704-b824-4274-880d-9d00645fbdd2 # ╠═a187f7aa-3d21-43d5-a877-83a49db3d965 # ╠═f2aebf0c-b135-4735-89d2-716d9983d42c # ╠═3decbd80-c1bc-4d00-b89e-7f3ddaa07683
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
2229
module TestPackage import PlutoDevMacros export toplevel_variable const TEST_INIT = Ref{Int}(0) toplevel_variable = 15 hidden_toplevel_variable = 10 module SUBINIT const TEST_SUBINIT = Ref{Int}(0) function __init__() TEST_SUBINIT[] = 15 end end using .TestPackage.SUBINIT: TEST_SUBINIT include("notebook1.jl") module Inner include("inner_notebook1.jl") include("inner_notebook2.jl") end module Issue2 include("test_macro1.jl") # Defines NotThatCoolStruct at line 28 include("test_macro2.jl") # Defines GreatStructure end module SpecificImport include("specific_imports1.jl") # Defines inner_variable1 include("specific_imports2.jl") end module ImportAsStatements include("import_as.jl") end module PrettyPrint function some_function end struct SomeType end end module MapExpr import PlutoDevMacros.FromPackage: RemoveThisExpr import PlutoDevMacros.FromPackage.MacroTools: postwalk # This apply mapexpr to all the args of an expression and remove all of the arguments that are of type RemoveThisExpr after mapping. # If not args are left, simply returns RemoveThisExpr, otherwise reconstruct the resulting expression function map_and_clean_expr(ex::Expr, mapexpr = identity) @nospecialize new_args = map(mapexpr, ex.args) filter!(x -> !isa(x, RemoveThisExpr), new_args) # If we still have args, or if the head is a block, we return the modified haed. We have this special case for a block for tests mostly !isempty(new_args) | (ex.head === :block) && return Expr(ex.head, new_args...) # If we get here we just return RemoveThisExpr return RemoveThisExpr() end function mapexpr(ex) ex isa Expr || return ex Meta.isexpr(ex, :(=)) || return map_and_clean_expr(ex) args = deepcopy(ex.args) varname = first(args) varname === :var_to_delete && return RemoveThisExpr() if varname === :should_be_100 args[2] = 100 return Expr(:(=), args...) end return ex end include(ex -> postwalk(mapexpr, ex), "test_mapexpr.jl") end function __init__() TEST_INIT[] = 5 end end # module TestPackage
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1264
### A Pluto.jl notebook ### # v0.19.43 using Markdown using InteractiveUtils # ╔═║ f08451b0-5666-4132-9c7e-a7d37c7d0c5a # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate(Base.current_project(@__FILE__)) # Revise is only used for internal testing during development to update the # changes to PlutoDevMacros using Revise end ╠═║ =# # ╔═║ 1a327f54-0bb4-4206-9070-e02d24c7861c using PlutoDevMacros # ╔═║ d483e6a9-262a-4346-91d2-68bf342c5ef9 @fromparent begin # CodeTracking is an indirect dependency import >.CodeTracking as CT, >.TOML as TML using >.TOML: tryparse as tp end # ╔═║ e2707562-9e31-4d4d-bc61-8af24911de9a tp === TML.tryparse || error("Import as from TOML did not work as expected") # ╔═║ 74384ece-10c5-4b1a-bfcb-3c83eceb0447 # ╠═║ skip_as_script = true #=╠═║ # This cell is commented outside of the notebook as CT will not be imported oustide of the notebook since it's an indirect dependency nameof(CT) === :CodeTracking || error("import of CodeTracking with different name did not work") ╠═║ =# # ╔═║ Cell order: # ╠═f08451b0-5666-4132-9c7e-a7d37c7d0c5a # ╠═1a327f54-0bb4-4206-9070-e02d24c7861c # ╠═d483e6a9-262a-4346-91d2-68bf342c5ef9 # ╠═e2707562-9e31-4d4d-bc61-8af24911de9a # ╠═74384ece-10c5-4b1a-bfcb-3c83eceb0447
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1463
### A Pluto.jl notebook ### # v0.19.42 using Markdown using InteractiveUtils # ╔═║ f90b0ae3-0e16-4b83-8546-23d4450812b2 # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate(Base.current_project(@__FILE__)) # Revise is only used for internal testing during development to update the # changes to PlutoDevMacros using Revise end ╠═║ =# # ╔═║ 8aa0221b-8f13-4ee8-8cc6-a19fdce2468b using PlutoDevMacros # ╔═║ e1c8bbbd-da6f-4550-9f2c-30337d4962ad @fromparent begin import ..TestPackage: testmethod using >.BenchmarkTools # This is a direct dependency of the package end # ╔═║ c83b0017-bb5e-48bd-96e6-5192b6151233 BenchmarkTools isa Module || error("It should be defined") # ╔═║ d5c73062-b20a-459f-8165-550e0f07375a isdefined(@__MODULE__, Symbol("@benchmark")) || error("It should be defined") # ╔═║ c30c2104-9fb1-4afd-a119-6da9d50ae2b6 testmethod(3) # ╔═║ 596410f6-81b7-48ae-a761-e5cca4a996ba # To add methods to function import with @fromparent, you need to use the @addmethod macro. @addmethod function testmethod(x::Int) "INT" end # ╔═║ a1430424-c9b8-4517-9105-c4daa72fdeea testmethod(3) # ╔═║ Cell order: # ╠═f90b0ae3-0e16-4b83-8546-23d4450812b2 # ╠═8aa0221b-8f13-4ee8-8cc6-a19fdce2468b # ╠═e1c8bbbd-da6f-4550-9f2c-30337d4962ad # ╠═c83b0017-bb5e-48bd-96e6-5192b6151233 # ╠═d5c73062-b20a-459f-8165-550e0f07375a # ╠═c30c2104-9fb1-4afd-a119-6da9d50ae2b6 # ╠═596410f6-81b7-48ae-a761-e5cca4a996ba # ╠═a1430424-c9b8-4517-9105-c4daa72fdeea
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1219
### A Pluto.jl notebook ### # v0.19.43 using Markdown using InteractiveUtils # ╔═║ 5fe1bfc9-9622-4266-8efa-d4032b42d847 # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate(Base.current_project(@__FILE__)) # Revise is only used for internal testing during development to update the # changes to PlutoDevMacros using Revise end ╠═║ =# # ╔═║ 2a3b9920-8fa7-4e20-aee9-71a93d589b70 using PlutoDevMacros # ╔═║ d9d182c7-abc8-4097-97da-459e351e01ba @fromparent begin import * using >.BenchmarkTools end # ╔═║ eaf576ed-ea38-4bb8-b2c8-4ba6ea6b2ac9 @addmethod testmethod(x::Float64) = "FLOAT" # ╔═║ 3cb7f11d-8829-409c-b3c8-9359a5da0763 testmethod("a") == "ANY" || error("Something went wrong") # ╔═║ b91a7413-534f-442b-bc55-a61244938820 testmethod(3) == "INT" || error("Something went wrong") # ╔═║ 88b26633-0760-428e-868a-1b799076189c testmethod(3.0) == "FLOAT" || error("Something went wrong") # ╔═║ Cell order: # ╠═5fe1bfc9-9622-4266-8efa-d4032b42d847 # ╠═2a3b9920-8fa7-4e20-aee9-71a93d589b70 # ╠═d9d182c7-abc8-4097-97da-459e351e01ba # ╠═eaf576ed-ea38-4bb8-b2c8-4ba6ea6b2ac9 # ╠═3cb7f11d-8829-409c-b3c8-9359a5da0763 # ╠═b91a7413-534f-442b-bc55-a61244938820 # ╠═88b26633-0760-428e-868a-1b799076189c
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1124
### A Pluto.jl notebook ### # v0.19.42 using Markdown using InteractiveUtils # ╔═║ 8de53a58-e6ab-11ed-1db7-ef087d78eaef # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate(Base.current_project(@__FILE__)) # Revise is only used for internal testing during development to update the # changes to PlutoDevMacros using Revise end ╠═║ =# # ╔═║ 22f0a6a4-907b-4389-b6b7-1f175289c69b using PlutoDevMacros # ╔═║ cf9f785b-f8f5-4d1b-9a48-ca5983843ba4 @fromparent begin import * # This import both exported and unexported names from the parent module up to the location where this file was included. end # ╔═║ 9a8ae7e2-d3c4-4cf2-876e-bcde84741540 # We have also visibility on `hidden_toplevel_variable` as was import in this notebook via the catchall * toplevel_variable + hidden_toplevel_variable # ╔═║ c9997396-bd93-41f1-8c3c-d13c7c6c5c3e # # We define a method testmethod(x) = "ANY" # ╔═║ Cell order: # ╠═8de53a58-e6ab-11ed-1db7-ef087d78eaef # ╠═22f0a6a4-907b-4389-b6b7-1f175289c69b # ╠═cf9f785b-f8f5-4d1b-9a48-ca5983843ba4 # ╠═9a8ae7e2-d3c4-4cf2-876e-bcde84741540 # ╠═c9997396-bd93-41f1-8c3c-d13c7c6c5c3e
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1292
### A Pluto.jl notebook ### # v0.19.42 using Markdown using InteractiveUtils # ╔═║ 414ea677-fc22-42d1-b28c-36d0666f466e # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate(Base.current_project(@__FILE__)) # Revise is only used for internal testing during development to update the # changes to PlutoDevMacros using Revise end ╠═║ =# # ╔═║ d8bb9b0c-b777-4b92-aab4-688358059f6d using PlutoDevMacros # ╔═║ da3cb2df-c686-45ed-abad-d4556c253ffa # When using PackageModule as name of the package to use or import from, `PackageModule` is substituted with the acutal module of the package targeted by @frompackage/@fromparent and loaded within the notebook. @fromparent import PackageModule: hidden_toplevel_variable # ╔═║ b03c28ca-9ad3-4ca0-a025-d0ca7799a6b2 # ╠═║ skip_as_script = true #=╠═║ hidden_toplevel_variable ╠═║ =# # ╔═║ ea26eaf9-bc34-4d53-b3af-641fec5039dd # Outside of Pluto, these variables are defined inside the module containing this notebook, which is called SpecificImport begin inner_variable1 = 100 inner_variable2 = 200 end # ╔═║ Cell order: # ╠═414ea677-fc22-42d1-b28c-36d0666f466e # ╠═d8bb9b0c-b777-4b92-aab4-688358059f6d # ╠═da3cb2df-c686-45ed-abad-d4556c253ffa # ╠═b03c28ca-9ad3-4ca0-a025-d0ca7799a6b2 # ╠═ea26eaf9-bc34-4d53-b3af-641fec5039dd
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
2293
### A Pluto.jl notebook ### # v0.19.42 using Markdown using InteractiveUtils # ╔═║ 414ea677-fc22-42d1-b28c-36d0666f466e # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate(Base.current_project(@__FILE__)) # Revise is only used for internal testing during development to update the # changes to PlutoDevMacros using Revise end ╠═║ =# # ╔═║ d8bb9b0c-b777-4b92-aab4-688358059f6d using PlutoDevMacros # ╔═║ da3cb2df-c686-45ed-abad-d4556c253ffa # When using PackageModule as name of the package to use or import from, `PackageModule` is substituted with the acutal module of the package targeted by @frompackage/@fromparent and loaded within the notebook. # Similarly, ParentModule as name is substituted to the name of module that in the loaded package is including the target/current file. If the current file is not included within the package a statement referring to ParentModule is invalid and will throw an error. # PackageModule and ParentModule can point to the same module in case the file is not part of a submodule of the package module. @fromparent begin using PackageModule # This just loads the exported names from TestPackage, which is only toplevel_variable import ^: Issue2 import ParentModule: inner_variable1 # This only imports `inner_variable` from the module containing the current file, which is the SpecificImport module end # ╔═║ 2f91c9eb-48c7-45ad-a475-3ac003d83c3b # ╠═║ skip_as_script = true #=╠═║ Issue2 ╠═║ =# # ╔═║ b03c28ca-9ad3-4ca0-a025-d0ca7799a6b2 # This cell will not error outside of Pluto (when executing the code of this notebook that is included in TestPackage) because inner_variable2 is visible outside of Pluto inner_variable2 # ╔═║ ea26eaf9-bc34-4d53-b3af-641fec5039dd # ╠═║ skip_as_script = true #=╠═║ # This is skipped_as_script because toplevel_variable is not visible outside of Pluto, as import statements that are not using relative module paths are discarded by @frompackage/@fromparent outside of Pluto toplevel_variable + inner_variable1 ╠═║ =# # ╔═║ Cell order: # ╠═414ea677-fc22-42d1-b28c-36d0666f466e # ╠═d8bb9b0c-b777-4b92-aab4-688358059f6d # ╠═da3cb2df-c686-45ed-abad-d4556c253ffa # ╠═2f91c9eb-48c7-45ad-a475-3ac003d83c3b # ╠═b03c28ca-9ad3-4ca0-a025-d0ca7799a6b2 # ╠═ea26eaf9-bc34-4d53-b3af-641fec5039dd
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1735
### A Pluto.jl notebook ### # v0.19.42 using Markdown using InteractiveUtils # ╔═║ e1caf748-e9c4-11ed-037b-8564786d02a4 # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate(Base.current_project(@__FILE__)) # Revise is only used for internal testing during development to update the # changes to PlutoDevMacros using Revise end ╠═║ =# # ╔═║ e9bf965f-6d89-4df4-9515-6664eec341d7 abstract type CrazyType end # ╔═║ baf6004f-4abc-4fd0-ae9e-a05144e955c4 struct CoolStruct <: CrazyType v :: Vector{<:CrazyType} end # ╔═║ d88d8173-a3d5-4d00-9372-ffce7ceecac9 struct NotThatCoolStruct <: CrazyType x :: Int64 end # ╔═║ 1dc784ea-e469-4c91-a202-bcf51e9961b5 foo(c::CrazyType) = error("This wasn't implemented for $c") # ╔═║ 335e2f3d-359f-4f61-ae92-97c75292acd3 foo(n::NotThatCoolStruct) = "Yes! this was implemented: $(n.x)" # ╔═║ 1aca5c06-e5cc-4d89-8586-7d98b01ddbec foo(n::CoolStruct) = foo.(n.v) # ╔═║ 1e78971b-fc54-4b58-8a49-603b29864843 # ╠═║ skip_as_script = true #=╠═║ ns = [NotThatCoolStruct(i) for i ∈ (1:3)] ╠═║ =# # ╔═║ 51bd6a66-48fe-400d-8f03-ff051895c859 #=╠═║ cool = CoolStruct(ns) ╠═║ =# # ╔═║ 0daf4126-8626-4403-b16a-e55890e21faa #=╠═║ foo(ns[1]) ╠═║ =# # ╔═║ 3786adad-39a4-4766-839b-dd508afc7e47 #=╠═║ foo(cool) ╠═║ =# # ╔═║ Cell order: # ╠═e1caf748-e9c4-11ed-037b-8564786d02a4 # ╠═e9bf965f-6d89-4df4-9515-6664eec341d7 # ╠═baf6004f-4abc-4fd0-ae9e-a05144e955c4 # ╠═d88d8173-a3d5-4d00-9372-ffce7ceecac9 # ╠═1dc784ea-e469-4c91-a202-bcf51e9961b5 # ╠═335e2f3d-359f-4f61-ae92-97c75292acd3 # ╠═1aca5c06-e5cc-4d89-8586-7d98b01ddbec # ╠═1e78971b-fc54-4b58-8a49-603b29864843 # ╠═51bd6a66-48fe-400d-8f03-ff051895c859 # ╠═0daf4126-8626-4403-b16a-e55890e21faa # ╠═3786adad-39a4-4766-839b-dd508afc7e47
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1345
### A Pluto.jl notebook ### # v0.19.42 using Markdown using InteractiveUtils # ╔═║ 85628a8b-b883-4374-918d-e080f4ab7d2e # ╠═║ skip_as_script = true #=╠═║ begin import Pkg Pkg.activate(Base.current_project(@__FILE__)) # Revise is only used for internal testing during development to update the # changes to PlutoDevMacros using Revise end ╠═║ =# # ╔═║ 9fd3e305-b493-46a5-8d4d-2d3712d9b23a using PlutoDevMacros # ╔═║ 52ad0f6c-a01a-4c9d-a176-64d9872aa3c1 @fromparent import * # ╔═║ 7f231b93-521d-4378-8094-763245eb5e43 struct GreatStructure <: CrazyType s :: String end # ╔═║ ebd09585-3edf-4167-9724-47a16ce4b596 @addmethod foo(g::GreatStructure) = "What a great structure! $(g.s)" # ╔═║ 2b245479-cce8-4e57-9261-42e2c926312b gs = [GreatStructure("$c") for c ∈ ('a':'c')] # ╔═║ 0735dc02-2b60-4fa6-bb8d-98729ad01d27 c = CoolStruct(gs) # ╔═║ 62546e81-98fe-49c0-8022-8b28389b24ba foo(c) # This doesn't breaks anymore! See https://github.com/disberd/PlutoDevMacros.jl/issues/2 for details # ╔═║ Cell order: # ╠═85628a8b-b883-4374-918d-e080f4ab7d2e # ╠═9fd3e305-b493-46a5-8d4d-2d3712d9b23a # ╠═52ad0f6c-a01a-4c9d-a176-64d9872aa3c1 # ╠═7f231b93-521d-4378-8094-763245eb5e43 # ╠═ebd09585-3edf-4167-9724-47a16ce4b596 # ╠═2b245479-cce8-4e57-9261-42e2c926312b # ╠═0735dc02-2b60-4fa6-bb8d-98729ad01d27 # ╠═62546e81-98fe-49c0-8022-8b28389b24ba
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
104
should_be_100 = 0 var_to_delete = 10 should_not_be_15 = let a = 1 global var_to_delete = 15 end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1098
### A Pluto.jl notebook ### # v0.19.43 using Markdown using InteractiveUtils # ╔═║ d4f2f0ca-c463-4318-8fe8-ad41ae9ca998 begin test_project = Base.current_project(normpath(@__DIR__, "..")) notebook_project = Base.active_project() plutodevmacros_project= Base.current_project(normpath(@__DIR__, "../..")) Base.eval(Main, quote # instantiate the parent env, mostly for CI import Pkg Pkg.activate($test_project) Pkg.instantiate() Pkg.activate($notebook_project) end) pushfirst!(LOAD_PATH, test_project) # This contains Revise pushfirst!(LOAD_PATH, plutodevmacros_project) # This loads the PlutoDevMacros environment, so we can do import with the latest version try Base.eval(Main, :(import Revise)) Base.eval(Main, :(import PlutoDevMacros)) finally popfirst!(LOAD_PATH) # Remove plutodevmacros env popfirst!(LOAD_PATH) # Remove parent_env end using Main.Revise using Main.PlutoDevMacros end # ╔═║ 03c088e9-257c-4e76-a13e-d14366b6f96c @fromparent begin import ^: * end # ╔═║ Cell order: # ╠═d4f2f0ca-c463-4318-8fe8-ad41ae9ca998 # ╠═03c088e9-257c-4e76-a13e-d14366b6f96c
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
104
module TestParseError include("error.jl") greet() = print("Hello World!") end # module TestParseError
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
34
let a = 1 b = 2 c = 3
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1383
### A Pluto.jl notebook ### # v0.19.42 using Markdown using InteractiveUtils # ╔═║ bb3dd7a0-19fc-11ef-093c-a938acaf0cf5 # ╠═║ skip_as_script = true #=╠═║ begin test_project = Base.current_project(normpath(@__DIR__, "..")) notebook_project = Base.active_project() plutodevmacros_project= Base.current_project(normpath(@__DIR__, "../..")) Base.eval(Main, quote # instantiate the parent env, mostly for CI import Pkg Pkg.activate($test_project) Pkg.instantiate() Pkg.activate($notebook_project) end) pushfirst!(LOAD_PATH, test_project) # This contains Revise pushfirst!(LOAD_PATH, plutodevmacros_project) # This loads the PlutoDevMacros environment, so we can do import with the latest version try Base.eval(Main, :(import Revise)) Base.eval(Main, :(import PlutoDevMacros)) finally popfirst!(LOAD_PATH) # Remove plutodevmacros env popfirst!(LOAD_PATH) # Remove parent_env end using Main.Revise using Main.PlutoDevMacros end ╠═║ =# # ╔═║ 23a1bdef-5c31-4c90-a7f5-1f5a806d3d2e #=╠═║ @fromparent @exclude_using import * ╠═║ =# # ╔═║ e4f436ed-27e9-4d19-98bd-c2b3021cf8bd # ╠═║ skip_as_script = true #=╠═║ !isdefined(@__MODULE__, :base64encode) || error("base64encode from Base64 should not be defined") ╠═║ =# # ╔═║ Cell order: # ╠═bb3dd7a0-19fc-11ef-093c-a938acaf0cf5 # ╠═23a1bdef-5c31-4c90-a7f5-1f5a806d3d2e # ╠═e4f436ed-27e9-4d19-98bd-c2b3021cf8bd
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1514
### A Pluto.jl notebook ### # v0.19.42 using Markdown using InteractiveUtils # ╔═║ 4f8def86-f90b-4f74-ac47-93fe6e437cee # ╠═║ skip_as_script = true #=╠═║ begin test_project = Base.current_project(normpath(@__DIR__, "..")) notebook_project = Base.active_project() plutodevmacros_project= Base.current_project(normpath(@__DIR__, "../..")) Base.eval(Main, quote # instantiate the parent env, mostly for CI import Pkg Pkg.activate($test_project) Pkg.instantiate() Pkg.activate($notebook_project) end) pushfirst!(LOAD_PATH, test_project) # This contains Revise pushfirst!(LOAD_PATH, plutodevmacros_project) # This loads the PlutoDevMacros environment, so we can do import with the latest version try Base.eval(Main, :(import Revise)) Base.eval(Main, :(import PlutoDevMacros)) finally popfirst!(LOAD_PATH) # Remove plutodevmacros env popfirst!(LOAD_PATH) # Remove parent_env end using Main.Revise using Main.PlutoDevMacros end ╠═║ =# # ╔═║ ac3d261a-86c9-453f-9d86-23a8f30ca583 #=╠═║ @fromparent import * ╠═║ =# # ╔═║ dd3f662f-e2ce-422d-a91a-487a4da359cc # ╠═║ skip_as_script = true #=╠═║ isdefined(@__MODULE__, :base64encode) || error("base64encode from Base64 should be defined") ╠═║ =# # ╔═║ 4492d516-2b23-45b7-bf76-7458e7352fea #=╠═║ rand_variable # This should change at every re-run ╠═║ =# # ╔═║ Cell order: # ╠═4f8def86-f90b-4f74-ac47-93fe6e437cee # ╠═ac3d261a-86c9-453f-9d86-23a8f30ca583 # ╠═dd3f662f-e2ce-422d-a91a-487a4da359cc # ╠═4492d516-2b23-45b7-bf76-7458e7352fea
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
394
module TestUsingNames using Base64 export top_level_func top_level_func() = 1 rand_variable = rand() module Test1 using Example include("test1.jl") end module Test2 using ..Test1, Base64 include("test2.jl") end module Test3 using ..TestUsingNames include("test3.jl") end include("../test_notebook1.jl") include("../test_notebook2.jl") end # module TestUsingNames
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
26
export test1 test1() = 10
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
14714
@testitem "Project/Manifest" begin include(joinpath(@__DIR__, "basics_helpers.jl")) # We test parsing the project of the TestUsingNames folder target_dir = abspath(@__DIR__, "../TestUsingNames/") # We delete the manifest if it exists delete_manifest(target_dir) # We test that by default it throws since there is no manifest controller = FromPackageController(target_dir, @__MODULE__; cell_id = Base.UUID(0)) @test controller.options.manifest βˆ‰ (:instantiate, :resolve) pd = controller.project @test pd.uuid === Base.UUID("ad5af708-d1e5-4d28-9e91-6798178ddbab") @test pd.name === "TestUsingNames" @test pd.version === v"0.1.0" @test "Example" in keys(pd.deps) @test "Revise" in keys(pd.deps) # We test parsing of the Manifest @test_throws "A manifest could not be found" populate_manifest_deps!(controller) controller.options.verbose = true controller.options.manifest = :resolve populate_manifest_deps!(controller) @test isfile(joinpath(target_dir, "Manifest.toml")) delete_manifest(target_dir) @test !isfile(joinpath(target_dir, "Manifest.toml")) controller.options.manifest = :instantiate populate_manifest_deps!(controller) @test isfile(joinpath(target_dir, "Manifest.toml")) md = controller.manifest_deps @test "Example" in values(md) @test "InteractiveUtils" in values(md) # Indirect Dependencies @test "TOML" in values(md) @test "CodeTracking" in values(md) # We test that pointing to a folder without a project throws @test_throws "No project was found" FromPackageController(homedir(), @__MODULE__) end @testitem "extract_target_path" begin include(joinpath(@__DIR__, "basics_helpers.jl")) calling_file = @__FILE__ m = @__MODULE__ # Test that an invalid file throws @test_throws "does not seem to be a valid path" extract_target_path("asd", m; calling_file) # We test that it create abspath based on the dir of the calling file @test extract_target_path(basename(@__FILE__), m; calling_file) === @__FILE__ # We test that this also works with an expression, if inside pluto basepath = basename(@__FILE__) @test extract_target_path(:basepath, m; calling_file, notebook_local=true) === @__FILE__ # We test that also an expression works @test extract_target_path(:(basename($(@__FILE__))), m; calling_file, notebook_local=true) === @__FILE__ # Test that this instead throws an error outside of pluto as at macro expansion we don't know symbols @test_throws "the path must be provided as" extract_target_path(:basepath, m; calling_file, notebook_local=false) === @__FILE__ end @testitem "Outside Pluto" begin include(joinpath(@__DIR__, "basics_helpers.jl")) controller = FromPackageController(outpackage_target, @__MODULE__) valid(ex) = any(x -> Meta.isexpr(x, (:using, :import)), process_outside_pluto(controller, ex).args) invalid(ex) = !valid(ex) @test valid(:(import .ASD: lol)) @test invalid(:(import .ASD: *)) @test invalid(:(import TestPackage: lol)) # We only allow relative imports or imports from direct deps (always starting with >.) @test invalid(:(import *)) # Outside of pluto the catchall is removed @test valid(:(import >.BenchmarkTools)) # This is a direct dependency @test valid(:(import >.InteractiveUtils)) # This is a direct dependency and a stdlib @test invalid(:(import >.JSON)) # This is an indirect dependency, from HypertextLiteral @test invalid(:(import >.Statistics)) # This is an stdlib, but on in the proj @test invalid(:(import >.DataFrames)) # This is not a dependency f_compare(ex_out, ex_in) = compare_exprs(ex_out, process_outside_pluto(controller, ex_in)) # We test some some specific imports ex_out = quote import BenchmarkTools as BT end ex_in = :(import >.BenchmarkTools as BT) @test f_compare(ex_out, ex_in) ex_out = quote using BenchmarkTools using Markdown end ex_in = :(using >.BenchmarkTools, >.Markdown) @test f_compare(ex_out, ex_in) # MacroTools is an indirect dep so it's discarded ex_out = quote using BenchmarkTools end ex_in = :(using >.BenchmarkTools, >.MacroTools) @test f_compare(ex_out, ex_in) ex_out = quote import BenchmarkTools as BT import .ASD as LOL end ex_in = :(import >.BenchmarkTools as BT, .ASD as LOL) @test f_compare(ex_out, ex_in) ex_out = quote using BenchmarkTools import .ASD: boh as lol end ex_in = quote using >.BenchmarkTools import .ASD: boh as lol end @test f_compare(ex_out, ex_in) ex_out = quote end ex_in = quote import * using >.CodeTracking # Interactive dependency end @test f_compare(ex_out, ex_in) end @testitem "Include using names" begin include(joinpath(@__DIR__, "basics_helpers.jl")) target_dir = abspath(@__DIR__, "../TestUsingNames/") instantiate_from_path(target_dir) caller_module = Core.eval(@__MODULE__, :(module $(gensym(:TestUsingNames)) end)) function f(target; caller_module=caller_module) cell_id = Base.UUID(0) target_file = joinpath(target_dir, target * "#==#$cell_id") controller = FromPackageController(target_file, caller_module; cell_id) # Load the module load_module!(controller) return controller end # Test1 - test1.jl target = "src/test1.jl" controller = f(target) valid(ex) = any(x -> Meta.isexpr(x, (:using, :import)), process_outside_pluto(controller, ex).args) invalid(ex) = !valid(ex) # Test that this only works with catchall @test_throws "The provided input expression is not supported." process_input_expr(controller, :(@include_using import Downloads)) # Test that even with the @exclude_using macro in front the expression is filtered out outside Pluo @test invalid(:(@exclude_using import *)) # Test that the names are extracted correctly ex = process_input_expr(controller, :(import *)) @test has_symbol(:domath, ex) ex = process_input_expr(controller, :(@exclude_using import *)) @test !has_symbol(:domath, ex) # Test2 - test2.jl target = "src/test2.jl" controller = f(target) # Test that the names are extracted correctly ex = process_input_expr(controller, :(import *)) |> MacroTools.prettify @test has_symbol(:test1, ex) # test1 is exported by Module Test1 @test has_symbol(:base64encode, ex) # test1 is exported by Module Base64 ex = process_input_expr(controller, :(@exclude_using import *)) @test !has_symbol(:test1, ex) @test !has_symbol(:base64encode, ex) # Test3 - test3.jl target = "src/test3.jl" controller = f(target) # Test that the names are extracted correctly, :top_level_func is exported by TestUsingNames ex = process_input_expr(controller, :(import *)) |> MacroTools.prettify @test has_symbol(:top_level_func, ex) ex = process_input_expr(controller, :(@exclude_using import *)) @test !has_symbol(:top_level_func, ex) # Test from a file outside the package target = "" controller = f(target) # # Test that the names are extracted correctly, :base64encode is exported by Base64 ex = process_input_expr(controller, :(import *)) |> MacroTools.prettify @test has_symbol(:base64encode, ex) ex = process_input_expr(controller, :(@exclude_using import *)) @test !has_symbol(:base64encode, ex) # We test the new skipping capabilities of `filterednames` # We save the module associated to the controller controller = f("") target_mod = get_temp_module(controller) m = Module(gensym()) # We create a function in the new module Core.eval(m, :(top_level_func = $(target_mod.top_level_func))) # We test that :top_level_func will not be imported because it's already in the caller module @test :top_level_func βˆ‰ filterednames(f(""; caller_module=m), target_mod) # If we put a controller with the :top_level_func name inside the `imported_names` field as previous controller in the caller module, it will instead be imported as it was in the list of previously imported names push!(controller.imported_names, :top_level_func) Core.eval(m, :($PREV_CONTROLLER_NAME = $controller)) @test :top_level_func ∈ filterednames(f(""; caller_module=m), target_mod) end @testitem "target in package" begin include(joinpath(@__DIR__, "basics_helpers.jl")) cell_id = Base.UUID(0) caller_module = Core.eval(@__MODULE__, :(module $(gensym(:InPackage)) end)) controller = FromPackageController(inpackage_target, caller_module; cell_id) populate_manifest_deps!(controller) load_module!(controller) f(ex; alias=false) = MacroTools.prettify(process_input_expr(controller, ex); alias) # FromDeps imports ex = :(using >.BenchmarkTools) expected_parent_path = fullname(get_loaded_modules_mod()) mwn = ModuleWithNames(f(ex)) # We remove the last name which is the unique name modname_path = copy(mwn.modname.original) unique_name = pop!(modname_path) @test compare_modname(modname_path, expected_parent_path) @test unique_name === unique_module_name(Base.UUID("6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"), "BenchmarkTools") ex = :(using >.BenchmarkTools: *) @test_throws "catch-all" f(ex) ex = :(using DataFrames) @test_throws "The provided import statement is not a valid input" f(ex) # Test indirect import ex = f(:(using >.JSON)) # We now test that Tricks is loaded in DepsImports @test has_symbol(:json, ex) # We test that trying to load a package that is not a dependency throws an error saying so @test_throws "The package with name DataFrames could not" f(:(using >.DataFrames)) # FromPackage imports ex = :(import TestPackage) mwn = f(ex) |> ModuleWithNames # This works because TestPackage is the name of the loaded package @test compare_modname(mwn, fullname(get_temp_module(controller))) ex = :(import PackageModule.SUBINIT) mwn = f(ex) |> ModuleWithNames @test compare_modname(mwn, [fullname(get_temp_module(controller))..., :SUBINIT]) out_ex = f(:(using PackageModule.SUBINIT)) @test has_symbol(:SUBINIT, out_ex) # # Relative imports ex = f(:(import ..SUBINIT)) mwn = ex |> ModuleWithNames @test compare_modname(mwn, [fullname(get_temp_module(controller))..., :SUBINIT]) ex = :(import ..NonExistant) @test_throws "The module `NonExistant` could not be found" f(ex) # It can't find the module # FromParent import ex = :(@exclude_using import *) parent_path = fullname(get_temp_module(controller)) expected = :(import $(parent_path...).Inner: Inner, testmethod) @test expected == f(ex) ex = :(@exclude_using import ParentModule: *) @test expected == f(ex) ex = :(import ParentModule: testmethod) expected = :(import $(parent_path...).Inner: testmethod) @test expected == f(ex) ex = :(using ParentModule) expected = :(import $(parent_path...).Inner: Inner) @test expected == f(ex) end @testitem "target not in package" begin include(joinpath(@__DIR__, "basics_helpers.jl")) cell_id = Base.UUID(0) caller_module = Core.eval(@__MODULE__, :(module $(gensym(:NotInPackage)) end)) controller = FromPackageController(outpackage_target, caller_module; cell_id) load_module!(controller) f(ex; alias=false) = MacroTools.prettify(process_input_expr(controller, ex); alias) parent_path = fullname(get_temp_module(controller)) ex = :(import PackageModule.Issue2) expected = :(import $(parent_path...).Issue2: Issue2) @test expected == f(ex) ex = f(:(@exclude_using import *)) mwn = ModuleWithNames(ex) # Test that the module path is correct @test compare_modname(mwn, parent_path) # We test that non-exported names of TestPackage are in the explicitly imported names @test has_symbol(:hidden_toplevel_variable, ex) # We test that the names coming from `using` statements within the target package are not re-exported @test !has_symbol(:TEST_SUBINIT, ex) # We now include usings ex = f(:(import *)) # We also test that also symbols visible in the target package due to `using` statements are re-exported @test has_symbol(:TEST_SUBINIT, ex) @test has_symbol(Symbol("@code_lowered"), ex) @test has_symbol(Symbol("@md_str"), ex) # We test that you can't call the parent module or relative imports when not included ex = :(import ParentModule: *) @test_throws "You can't import from the Parent Module" f(ex) ex = :(import ..LOL) @test_throws "You can't use relative imports" f(ex) end @testitem "Errors" begin include(joinpath(@__DIR__, "basics_helpers.jl")) cell_id = Base.UUID(0) caller_module = Core.eval(@__MODULE__, :(module $(gensym(:NotInPackage)) end)) controller = FromPackageController(outpackage_target, caller_module; cell_id) load_module!(controller) # Test that an error is thrown if the dependency could not be found in deps or weakdeps @test_throws "could not be found as a dependency (or weak dependency)" get_dep_from_loaded_modules(controller, :DataFrames; allow_weakdeps = true) @test_throws "is not valid for constructing ImportAs" ImportAs(:(1+1)) @test_throws "or a begin-end block of import statements" extract_input_args(:(1+1)) end @testitem "Options Parsing" begin include(joinpath(@__DIR__, "basics_helpers.jl")) # Parse options macro dummy(args...) caller_module = __module__ calling_file = @__FILE__ target = outpackage_target target_file = extract_target_path(target, caller_module; calling_file, notebook_local=false) p = FromPackageController(target_file, caller_module; cell_id = Base.UUID(0)) ex = :(import *) parse_options!(p, ex, args) :($p) end # Test correct handling default = FromPackageOptions() p = @dummy verbose = true rootmodule = true manifest = :instantiate @test p.options.verbose === true !== default.verbose @test p.options.rootmodule === true !== default.rootmodule @test p.options.manifest === :instantiate !== default.manifest # Manifest with name directly p = @dummy manifest = resolve @test p.options.manifest === :resolve !== default.manifest # @test_throws "are not in a supported format" eval(:(@dummy verboses = true)) @test_throws "are not in a supported format" eval(:(@dummy verbose = 3)) @test_throws "are not in a supported format" eval(:(@dummy manifest = true)) end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
2122
import PlutoDevMacros.FromPackage: FromPackage, @fromparent, load_module!, FromPackageController, populate_manifest_deps!, ProjectData, @frompackage, extract_target_path, is_notebook_local, process_outside_pluto, process_input_expr, iterate_imports, ImportAs, get_temp_module, PREV_CONTROLLER_NAME, filterednames, ModuleWithNames, JustModules, get_loaded_modules_mod, unique_module_name, extract_nested_module, get_dep_from_loaded_modules, extract_input_args, custom_walk!, parse_options!, FromPackageOptions import MacroTools using Test function compare_exprs(ex1, ex2) ex1 = MacroTools.prettify(ex1) ex2 = MacroTools.prettify(ex2) equal = ex1 == ex2 equal || @error "The expression are not equivalent" ex1 ex2 end # Function to extract the name of the imported symbol imported_symbol(ia::ImportAs) = something(ia.as, last(ia.original)) # Function to check if an expression contain an explict imported symbol with the provided name function has_symbol(symbol, ex::Expr) block = MacroTools.prettify(ex) |> MacroTools.block any(block.args) do arg any(iterate_imports(arg)) do mwn any(mwn.imported) do ia imported_symbol(ia) === symbol end end end end function compare_modname(m1, m2) Tuple(m1) == Tuple(m2) end function compare_modname(mwn::ModuleWithNames, m2; skip_last = 0) m1 = mwn.modname.original[1:end-skip_last] compare_modname(m1, m2) end include(joinpath(@__DIR__, "helpers.jl")) TestPackage_path = normpath(@__DIR__, "../TestPackage") dev_package_in_proj(TestPackage_path) # instantiate_from_path(TestPackage_path) # Also instantiate the test env instantiate_from_path(TestPackage_path |> dirname) # We point at the helpers file inside the TestPackage module, we stuff up to the first include outpackage_target = TestPackage_path inpackage_target = joinpath(outpackage_target, "src/inner_notebook2.jl") outpluto_caller = joinpath(TestPackage_path, "src") # We simulate a caller from a notebook by appending a fake cell-id cell_id = Base.UUID(0) inpluto_caller = join([outpluto_caller, "#==#", string(cell_id)])
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1391
import Pkg import Pkg.Types: Context, EnvCache, PackageSpec, GitRepo function eval_with_load_path(ex, path) push!(LOAD_PATH, path) try eval(ex) finally pop!(LOAD_PATH) end end function current_package_path() package_path = @__DIR__ package_path_names = splitpath(package_path) test_idxs = findall(==("test"), package_path_names) for idx in test_idxs package_path = joinpath(package_path_names[1:idx]) "runtests.jl" in readdir(package_path) && break end package_path = dirname(package_path) end # Package path must be the directory where the Package project is located function dev_package_in_proj(proj_path::AbstractString, package_path = current_package_path()) c = Context(;env = EnvCache(Base.current_project(proj_path))) ps = PackageSpec(; repo = GitRepo(;source = package_path) ) Pkg.develop(c, [ps]) end function instantiate_from_path(path::AbstractString; resolve = true) c = Context(;env = EnvCache(Base.current_project(path))) resolve && Pkg.resolve(c) Pkg.instantiate(c; update_registry = false, allow_build = false, allow_autoprecomp = false) end function delete_manifest(path::AbstractString) envdir = dirname(Base.current_project(path)) manifest_file = joinpath(envdir, "Manifest.toml") isfile(manifest_file) && rm(manifest_file) return nothing end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
1182
@testitem "Indirect Extension" begin include(joinpath(@__DIR__, "with_pluto_helpers.jl")) ss = ServerSession(; options) path = joinpath(indirect_path, "test_extension.jl") nb = SessionActions.open(ss, path; run_async=false) @test eval_in_nb((ss, nb), :method_present) === true for cell in nb.cells @test noerror(cell) end SessionActions.shutdown(ss, nb) end @testitem "Direct Extensions" begin # Include the setup include(joinpath(@__DIR__, "with_pluto_helpers.jl")) env_path = joinpath(direct_path, "notebook_env") dev_package_in_proj(env_path) instantiate_from_path(env_path) instantiate_from_path(direct_path) # Do the rest ss = ServerSession(; options) path = joinpath(direct_path, "test_extension.jl") nb = SessionActions.open(ss, path; run_async=false) @test eval_in_nb((ss, nb), :standard_extension_output) === "Standard Extension works!" @test eval_in_nb((ss, nb), :weird_extension_output) === "Weird Extension name works!" @test eval_in_nb((ss, nb), :(p isa PlutoPlot)) === true for cell in nb.cells @test noerror(cell) end SessionActions.shutdown(ss, nb) end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
3518
import PlutoDevMacros.FromPackage: FromPackage, add_loadpath, process_settings!, get_active, get_project_file import PlutoDevMacros.FromPackage.Settings: Settings, get_setting, SETTINGS_DEFAULTS, SETTINGS_SYNONYMS, setting_name, add_setting, remove_setting using Test TestPackage_path = normpath(@__DIR__, "../TestPackage") # We point at the helpers file inside the TestPackage module, we stuff up to the first include target = TestPackage_path # We test that the prefix is there in the temp env @test startswith(FromPackage.default_ecg() |> get_active |> get_project_file |> dirname |> basename, "frompackage_") @testset "Get Setting" begin @test_throws "is not associated to any valid setting" get_setting(:asdfasdf) key = :SHOULD_PREPEND_LOAD_PATH current = SETTINGS_DEFAULTS[key] @test get_setting(key) === current SETTINGS_DEFAULTS[key] = !current @test get_setting(key) === !current SETTINGS_DEFAULTS[key] = current @test get_setting(key) === current # Test with dict d = Dict("Custom Settings" => Dict(key => !current)) @test get_setting(d, key) === !current end @testset "Parsing" begin # Check that we don't have a as name @test_logs (:warn, r"Nothing was removed") remove_setting(:a) # We add a and b as valid setting names add_setting(:a, 0) add_setting(:b, 0) @test get_setting(:a) === 0 @test get_setting(:b) === 0 ex = :(@settings a = 1) # Nothing done without block, as that is anyhow not supported @test ex === process_settings!(ex, Dict()) # Test that settings are removed if in a block ex = quote $ex end d = Dict() new_ex = process_settings!(deepcopy(ex), d) |> Base.remove_linenums! @test isempty(new_ex.args) @test haskey(d, "Custom Settings") @test d["Custom Settings"][:a] == 1 # We check illegal expressions ex = quote @settings a = 1 b = rand() end @test_throws "Only primitive" process_settings!(deepcopy(ex), Dict()) ex = quote @settings a = 1 b c end @test_throws "Only `var = value`" process_settings!(deepcopy(ex), Dict()) # Test the begin end synthax ex = quote @settings begin a = 1 b = 2 end end d = Dict() new_ex = process_settings!(deepcopy(ex), d) |> Base.remove_linenums! @test isempty(new_ex.args) @test haskey(d, "Custom Settings") @test d["Custom Settings"][:a] == 1 @test d["Custom Settings"][:b] == 2 remove_setting(:a) @test_throws "is not associated to any valid setting" setting_name(:a) remove_setting(:b) @test_throws "is not associated to any valid setting" setting_name(:b) end @testset "SHOULD_PREPEND_LOAD_PATH" begin @test setting_name(:prepend) === :SHOULD_PREPEND_LOAD_PATH proj_file = FromPackage.default_ecg() |> get_active |> get_project_file # Remove the custom envs from the load path filter!(LOAD_PATH) do proj !startswith(proj |> dirname |> basename, "frompackage_") end @info LOAD_PATH l = length(LOAD_PATH) @test proj_file βˆ‰ LOAD_PATH add_loadpath(proj_file; should_prepend = false) @test length(LOAD_PATH) == l+1 add_loadpath(proj_file; should_prepend = false) @test length(LOAD_PATH) == l+1 @test LOAD_PATH[end] == proj_file LOAD_PATH[end] == proj_file && pop!(LOAD_PATH) # Prepend add_loadpath(proj_file; should_prepend = true) @test LOAD_PATH[1] == proj_file LOAD_PATH[1] == proj_file && popfirst!(LOAD_PATH) end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
806
import Pluto: update_save_run!, update_run!, WorkspaceManager, ClientSession, ServerSession, Notebook, Cell, project_relative_path, SessionActions, load_notebook, Configuration include(joinpath(@__DIR__, "helpers.jl")) function noerror(cell; verbose=true) if cell.errored && verbose @show cell.output.body end !cell.errored end indirect_path = normpath(@__DIR__, "../TestIndirectExtension/") direct_path = normpath(@__DIR__, "../TestDirectExtension/") testpackage_path = joinpath(@__DIR__, "../TestPackage/") instantiate_from_path(indirect_path) instantiate_from_path(testpackage_path) options = Configuration.from_flat_kwargs(; disable_writing_notebook_files=true, workspace_use_distributed_stdlib = true) eval_in_nb(sn, expr) = WorkspaceManager.eval_fetch_in_workspace(sn, expr)
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
8703
@testitem "notebook1.jl" begin # Include the setup include(joinpath(@__DIR__, "with_pluto_helpers.jl")) srcdir = joinpath(@__DIR__, "../TestPackage/src/") # We add PlutoDevMacros as dev dependency to TestPackage dev_package_in_proj(srcdir) instantiate_from_path(srcdir) eval_with_load_path(:(import TestPackage), testpackage_path) # Do the tests ss = ServerSession(; options) path = joinpath(srcdir, "notebook1.jl") nb = SessionActions.open(ss, path; run_async=false) @test eval_in_nb((ss, nb), :toplevel_variable) == TestPackage.toplevel_variable @test eval_in_nb((ss, nb), :hidden_toplevel_variable) == TestPackage.hidden_toplevel_variable # We test that __init__ was not ran, as this file will only contain the module before the __init__ function is defined @test eval_in_nb((ss, nb), :(TEST_INIT[])) == 0 for cell in nb.cells @test noerror(cell) end SessionActions.shutdown(ss, nb) end @testitem "inner_notebook2.jl" begin # Include the setup include(joinpath(@__DIR__, "with_pluto_helpers.jl")) srcdir = joinpath(@__DIR__, "../TestPackage/src/") # We add PlutoDevMacros as dev dependency to TestPackage dev_package_in_proj(srcdir) instantiate_from_path(srcdir) # Do the tests ss = ServerSession(; options) path = joinpath(srcdir, "inner_notebook2.jl") nb = SessionActions.open(ss, path; run_async=false) for cell in nb.cells @test noerror(cell) end eval_in_nb((ss, nb), :(BenchmarkTools isa Module)) SessionActions.shutdown(ss, nb) end @testitem "test_macro2.jl" begin # Include the setup include(joinpath(@__DIR__, "with_pluto_helpers.jl")) srcdir = joinpath(@__DIR__, "../TestPackage/src/") # We add PlutoDevMacros as dev dependency to TestPackage dev_package_in_proj(srcdir) instantiate_from_path(srcdir) # Do the tests ss = ServerSession(; options) path = joinpath(srcdir, "test_macro2.jl") nb = SessionActions.open(ss, path; run_async=false) for cell in nb.cells @test noerror(cell) end SessionActions.shutdown(ss, nb) end @testitem "TestPackage/import_as.jl" begin # Include the setup include(joinpath(@__DIR__, "with_pluto_helpers.jl")) srcdir = joinpath(@__DIR__, "../TestPackage/src/") # We add PlutoDevMacros as dev dependency to TestPackage dev_package_in_proj(srcdir) instantiate_from_path(srcdir) # Do the tests ss = ServerSession(; options) path = joinpath(srcdir, "import_as.jl") nb = SessionActions.open(ss, path; run_async=false) for cell in nb.cells @test noerror(cell) end SessionActions.shutdown(ss, nb) end @testitem "TestPackage/out_notebook.jl" begin # Include the setup include(joinpath(@__DIR__, "with_pluto_helpers.jl")) srcdir = joinpath(@__DIR__, "../TestPackage/src/") # We add PlutoDevMacros as dev dependency to TestPackage dev_package_in_proj(srcdir) instantiate_from_path(srcdir) # Do the tests ss = ServerSession(; options) path = abspath(srcdir, "../out_notebook.jl") nb = SessionActions.open(ss, path; run_async=false) for cell in nb.cells[1:end-1] # The last cell contains an error on purpose @test noerror(cell) end SessionActions.shutdown(ss, nb) end @testitem "test_pkgmanager.jl" begin # Include the setup include(joinpath(@__DIR__, "with_pluto_helpers.jl")) srcdir = joinpath(@__DIR__, "../TestPackage/src/") # We add PlutoDevMacros as dev dependency to TestPackage dev_package_in_proj(srcdir) instantiate_from_path(srcdir) # Do the tests ss = ServerSession(; options) path = abspath(srcdir, "../test_pkgmanager.jl") nb = SessionActions.open(ss, path; run_async=false) for cell in nb.cells @test noerror(cell) end SessionActions.shutdown(ss, nb) end @testitem "test_parse_error.jl" begin # Include the setup include(joinpath(@__DIR__, "with_pluto_helpers.jl")) # We test the ParseError (issue 30) srcdir = joinpath(@__DIR__, "../TestParseError/src/") instantiate_from_path(srcdir) # Do the tests ss = ServerSession(; options) path = abspath(srcdir, "../parseerror_notebook.jl") nb = SessionActions.open(ss, path; run_async=false) cell = nb.cells[2] @test cell.errored msg = cell.output.body[:msg] if VERSION < v"1.10" @test startswith(msg, "syntax: incomplete:") else @test startswith(msg, "LoadError: ParseError:") end SessionActions.shutdown(ss, nb) end @testitem "test_dev_dependency.jl" begin # Include the setup include(joinpath(@__DIR__, "with_pluto_helpers.jl")) # We test dev dependencies with relative path (issue 30) srcdir = joinpath(@__DIR__, "../TestDevDependency/src/") # We add TestPackage as dev dependency dev_package_in_proj(srcdir, testpackage_path) # Do the tests ss = ServerSession(; options) path = abspath(srcdir, "../test_notebook.jl") nb = SessionActions.open(ss, path; run_async=false) for cell in nb.cells @test noerror(cell) end SessionActions.shutdown(ss, nb) end @testitem "Using Names" begin # Include the setup include(joinpath(@__DIR__, "with_pluto_helpers.jl")) # We test @exclude_using (issue 11) srcdir = joinpath(@__DIR__, "../TestUsingNames/src/") instantiate_from_path(srcdir) # Do the tests ss = ServerSession(; options) for filename in ["test_notebook1.jl", "test_notebook2.jl"] path = abspath(srcdir, "..", filename) nb = SessionActions.open(ss, path; run_async=false) # We test that no errors are present for cell in nb.cells @test noerror(cell) end # We extract the rand_variable value first_value = eval_in_nb((ss, nb), :rand_variable) # We rerun the second cell, containing the `@fromparent` call update_run!(ss, nb, nb.cells[2]) # We check again that no errors arose for cell in nb.cells @test noerror(cell) end # We check that the rand_variable value changed second_value = eval_in_nb((ss, nb), :rand_variable) @test first_value != second_value SessionActions.shutdown(ss, nb) end end @testitem "TestInception" begin # Include the setup include(joinpath(@__DIR__, "with_pluto_helpers.jl")) # We test @exclude_using (issue 11) target_dir = joinpath(@__DIR__, "../TestInception") # We delete the manifest if it exists as we are testing the instantiation happens correctly delete_manifest(target_dir) # Do the tests ss = ServerSession(; options) path = abspath(target_dir, "inception_notebook.jl") nb = SessionActions.open(ss, path; run_async=false) # We test that no errors are present for cell in nb.cells @test noerror(cell) end function has_log_msg(cell, needle) any(cell.logs) do dict msg = dict["msg"] |> first contains(msg, needle) end end # We check that the manifest has been created from the cell, and the messages has been logged in the 3rd cell (which is the one calling @fromparent) @test has_log_msg(nb.cells[3], r"Updating .*Manifest.toml") # We check that the cell importing SimplePlutoInclude has logs for loading the SingleExtension @test has_log_msg(nb.cells[10], "Loading code of extension SingleExtension") # We check that the cell importing Example has logs for loading the DualExtension @test has_log_msg(nb.cells[13], "Loading code of extension DualExtension") # We extract the rand_variable value first_value = eval_in_nb((ss, nb), :random_variable) # We rerun the second cell, containing the `PDM.@frompackage` call, which reload PlutoDevMacros itself update_run!(ss, nb, nb.cells[2]) # We check again that no errors arose for cell in nb.cells @test noerror(cell) end # We check that warning of replacing rootmodule and deleting mirror_package_callback from previous workspace are present in cell 3 @test has_log_msg(nb.cells[3], "Replacing module") @test has_log_msg(nb.cells[3], "Deleting previous version of package_callback function") # We also have the messages for reloading the extension in this cell now @test has_log_msg(nb.cells[3], "Loading code of extension SingleExtension") @test has_log_msg(nb.cells[3], "Loading code of extension DualExtension") # We check that the rand_variable value changed second_value = eval_in_nb((ss, nb), :random_variable) @test first_value != second_value # We now try to SessionActions.shutdown(ss, nb) end
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
19477
### A Pluto.jl notebook ### # v0.19.29 #> custom_attrs = ["hide-enabled"] using Markdown using InteractiveUtils # ╔═║ d0e6a2b2-1e5d-11ee-177a-5f0a92dd83f5 begin test_project= Base.current_project(@__DIR__) plutodevmacros_project= Base.current_project(normpath(@__DIR__, "../..")) pushfirst!(LOAD_PATH, test_project) # This contains Revise pushfirst!(LOAD_PATH, plutodevmacros_project) # This loads the PlutoDevMacros environment, so we can do import with the latest version try Base.eval(Main, :(import Revise)) Base.eval(Main, :(import PlutoDevMacros)) finally popfirst!(LOAD_PATH) # Remove plutodevmacros env popfirst!(LOAD_PATH) # Remove parent_env end using Main.Revise using Main.PlutoDevMacros using Main.PlutoDevMacros.PlutoCombineHTL.WithTypes using Main.PlutoDevMacros.HypertextLiteral end # ╔═║ 8325847e-fd7e-42ef-84c7-a30c6467183e using PlutoUI # ╔═║ 65bff575-5dcb-4d81-b357-2b2f8bfd43d7 using PlutoVSCodeDebugger # ╔═║ c924a590-a189-4ca2-abef-2b7dca80fe11 md""" # Packages """ # ╔═║ ede9b8dd-104f-4d5c-a134-f1fc67a1b9c7 import .PlutoCombineHTL: print_html # ╔═║ 13d2cf9a-2fce-47f9-a851-6dd80d130b63 TableOfContents() # ╔═║ 7a8c6eb4-cc33-41c3-9e1a-d8e07954fef9 # This is just to test that the html_reload_button generates the button correctly PlutoDevMacros.FromPackage.html_reload_button("asd") # ╔═║ 01368463-0f95-4ced-abb1-6c8800ca2524 md""" All outputs of type `ScriptContent`, `Script` or `Node` where `Script <: Node` are shown in Pluto by default as formatted code (using Markdown). To actually generate and show in the pluto-output their corresponding HTML code you have to either interpolate them inside `@htl` or call the `make_html` function on them. """ # ╔═║ c862e547-3b62-4218-b06e-0e84d05d6587 @connect_vscode begin end # ╔═║ d115c2b6-f92d-4609-94a9-59391c160645 md""" # Scripts """ # ╔═║ 201323b9-8caf-4acb-904e-b76d16e5ffb1 md""" ## ScriptContent """ # ╔═║ f1bde184-7487-4745-8c47-0df407da6813 md""" The ScriptContent type wraps javascript content of a script, and can be used to compose a script with multiple `ScriptContent` elements """ # ╔═║ adf46403-ec6b-4278-ae65-5747f319dc96 simple_sc = """ let out = html`<div>ASD</div>` console.log('first script') return out """ |> ScriptContent # ╔═║ 0a1e9af6-6b32-49c6-9cf6-8cf7f594f109 md""" ### @htl constructor """ # ╔═║ f2fde939-638a-4b69-94ee-d32aff03879e md""" Objects of `ScriptContent` type can also be generated using outputs of the `@htl` macro as input. In this case, the constructor performs some additional check and only accepts objects of type `HypertextLiteral.Result` that are containing at least one `<script>` tag element. The content used for generating the `ScriptContent` is the text contained within the first `<script>` tag found. """ # ╔═║ 05941b74-00f1-4937-9a1d-d01e6e1a776f # They can also be created starting form a String ScriptContent("asd") === ScriptContent(@htl("<script>asd</script>")) || error("Something went wrong") # ╔═║ fbe39d75-01e8-4f3a-8e65-f260a039365e md""" When using the `@htl` macro to construct a `ScriptContent` element, some warning are printed if the content of the `@htl` macro either does not contain a <script> tag or contains more than the <script> tag """ # ╔═║ 4c41b737-c392-455e-b6d8-98931f88d467 # This generates an empty content with no warning ScriptContent(@htl("")) # ╔═║ 6879d22c-f01c-424f-bc37-eb42062e49db # This generates a warning because some extra content was present but is discarded ScriptContent(@htl("asd <script id='lol'> asd </script>")) # ╔═║ 55044c8e-3f70-4a55-ad9f-7514d44a7211 # This generates a warning because no script tag was found despite its input being non-empty ScriptContent(@htl("asd")) # ╔═║ a9bc9479-722d-4564-9cb9-560f7b0f4ffb # This generates a warning because two script tags are found ScriptContent(@htl("<script>asd</script>lol<script>boh</script>")) # ╔═║ da343b23-1ee0-44f9-9341-2c337f0de333 # This cell will throw an error because you have to always provide the closing </script> tag in the constructor when using @htl try ScriptContent(@htl("<script>asd")) false catch e contains(e.msg, "No closing </script>") || rethrow() end # ╔═║ 57929023-813c-42ab-acdd-8a8f9033c11a md""" ### Display/Interpolation """ # ╔═║ 8d9dd998-c3d0-435c-a709-ee42c586c230 md""" `ScriptContent` objects can only be _materialized_ as scripts by performing a direct interpolation within the <script> tag of the `@htl` macro. Using `make_html` will not work. Alternatively one can also wrap the ScriptContent inside a `Script` element before calling `make_html` as will be shown later """ # ╔═║ c2aa06c6-3d34-4793-afa6-2e5a7c8b920a # Here we interpolate this inside `@htl` to create the script @htl("<script>$simple_sc</script>") # ╔═║ 720f431c-00d6-418a-a33c-d440070a7363 # make_html will simply re-show the formatted HTML code make_html(simple_sc) # ╔═║ 3362ad99-d10c-4312-84ae-e3876ad1787f md""" A Vector of `ScriptContent` can also be directly interpolated inside the <script> tags within the `@htl` macro. """ # ╔═║ 318a9af6-a7e9-449d-8299-db4b6ab11fea @htl(""" <script> $([ ScriptContent("let dv = html`<div>LOL</div>`") # This creates the div ScriptContent("currentScript.insertAdjacentElement('beforebegin',dv)") # This puts the previous div before the currentScript ScriptContent("return html`<div>ASD`") # This returns a new div, which is put after the previous one. Return statements should not be contained inside ScriptContents directly but provided with the returned_element keyword when constructing a Script. ]) </script> """) # ╔═║ cc621eb7-b977-4ee8-9fbf-600a6f2bcfd2 md""" ## SingleScript """ # ╔═║ 02f7b708-1f21-4533-bc3c-de4573d0a14b md""" There are two subyptes of `InOrOutScript <: Script`. They are: - `PlutoScript` - `NormalScript` These are elements representing scripts that are exclusive to either be shown in Pluto or outside of Pluto. The PlutoScript internally contains two `ScriptContent` fields, one for the normal script body, and one for the invalidation part of the script that takes place when a cell is removed/re-run.\ Check the JavaScript sample Pluto notebook for more details on the `invalidation` stage of Pluto cells. `SinglScript` objects can be constructed either with `ScriptContent` objects directly or with inputs that are supported by the `ScriptContent` constructor (i.e. `String` and `HypertextLiteral.Result` containing a <script> tag) """ # ╔═║ 1e2d7cc9-45d8-4aca-806b-76f1e50986b0 md""" ### PlutoScript """ # ╔═║ 73932307-b68c-453a-a7e6-8ba5d8bd8334 # When showing a Script object, the <script> tag is included PlutoScript(simple_sc) |> formatted_code # ╔═║ d866e092-f24b-4553-971f-c1f74f3a1c1a # Can also be constructed with Strings ps = PlutoScript(" console.log('asd')", " console.log('lol')"; id = "my_id") |> formatted_code # ╔═║ 3dfb8184-2fce-4296-9c47-f0a034e99f73 PlutoScript("return html`<div>MAGIC`") # ╔═║ 7f70ce43-567b-47aa-856e-bb41ee00fcc4 md""" ### NormalScript """ # ╔═║ 07db9619-2cfe-4796-a083-f571f6c30721 md""" NormalScript will not show the formatted code as normal output in Pluto, but will transform into an empty script when actually shown with `make_html` inside Pluto. In order to maximize code reuse between the Pluto and Normal scripts, some JS packages are loaded and made available in NormalScript objects' generated HTML by default. These are the packages that are also automatically loaded inside Pluto and are available when executing cell code and include: - the [Observable Standard Library](https://github.com/observablehq/stdlib) - the [Lodash](https://lodash.com/) package. Similarly to what happens in Pluto, the `currentScript` variable is also associated to the script being executed. While `currentScript` is always bound, the package loading/inclusion is controlled by a `Bool` field of the `NormalScript` structure and it can be overridden by calling the script constructor with the `add_pluto_compat = false` keyword argument. """ # ╔═║ ebd5e071-e151-43d6-806e-ca6582c0046b ns = NormalScript("return html`<div>MAGIC`") # ╔═║ 22589abd-63f4-46de-9fed-b673a72a449f # The MAGIC word is not appearing like for the PlutoScript because we are showing inside Pluto make_html(ns) # ╔═║ 0b129e2a-842f-44cd-9d5e-61f7090ab63d md""" ### JS Listeners """ # ╔═║ bdac5c70-2114-4f2b-9a0b-14ff172a1559 md""" `Script` objects can also be constructed with a convenience function to attach JS listeners to objects that are automatically removed upon cell invalidation. To use this functionality, it is sufficient to add a call to the `addScriptEventListeners` inside the script content. See below the actually generated HTML when this keyword is added to the contents of a Script: """ # ╔═║ d508ea5d-cc5d-44d1-a1b0-8ae6c18bf954 begin ps_js = PlutoScript(""" let dv = html`<div>ASDLOL` let active = false addScriptEventListeners(dv, { 'click': (e) => { console.log(e) active = !active if (active) { dv.style = "border: solid 2px red;" } else { dv.style = "" } } }) """; returned_element = "dv") # To avoid having a return statement within the script that will stop the rest of the content. Returned elements name should be given as a separated keyword argument. formatted_code(ps_js) end # ╔═║ a87c1d5f-1160-477b-9de9-432f1b742e3f # One can also just show the content without the scripts parts added by PlutoDevMacros ps_js |> formatted_code(;only_contents = true) # ╔═║ a4004826-ee3d-451f-a944-dff8d0787481 md""" And here is the generated script which will create a div which changes its border color upon click """ # ╔═║ 5ec6e1a4-ece4-4cdf-81f5-fe0d1c9c39b9 ps_js # ╔═║ f8e10efd-f29d-431b-bbc7-ae4c0608e4d6 md""" ## DualScript """ # ╔═║ 0e16969e-197f-4fca-a0f1-cbe4c4c4822e v = PrintToScript # ╔═║ 00000000-0000-0000-0000-000000000001 PLUTO_PROJECT_TOML_CONTENTS = """ [deps] PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8" PlutoVSCodeDebugger = "560812a8-17ff-4261-aab5-f8f600b273e2" [compat] PlutoUI = "~0.7.52" PlutoVSCodeDebugger = "~0.2.0" """ # ╔═║ 00000000-0000-0000-0000-000000000002 PLUTO_MANIFEST_TOML_CONTENTS = """ # This file is machine-generated - editing it directly is not advised julia_version = "1.10.0-beta2" manifest_format = "2.0" project_hash = "2a231071dd4c3eaebeebc799c8f5832c9f4ce78a" [[deps.AbstractPlutoDingetjes]] deps = ["Pkg"] git-tree-sha1 = "91bd53c39b9cbfb5ef4b015e8b582d344532bd0a" uuid = "6e696c72-6542-2067-7265-42206c756150" version = "1.2.0" [[deps.ArgTools]] uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" version = "1.1.1" [[deps.Artifacts]] uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" [[deps.Base64]] uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" [[deps.ColorTypes]] deps = ["FixedPointNumbers", "Random"] git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4" uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f" version = "0.11.4" [[deps.CompilerSupportLibraries_jll]] deps = ["Artifacts", "Libdl"] uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" version = "1.0.5+1" [[deps.Dates]] deps = ["Printf"] uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" [[deps.Downloads]] deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" version = "1.6.0" [[deps.FileWatching]] uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" [[deps.FixedPointNumbers]] deps = ["Statistics"] git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc" uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" version = "0.8.4" [[deps.Hyperscript]] deps = ["Test"] git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9" uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91" version = "0.0.4" [[deps.HypertextLiteral]] deps = ["Tricks"] git-tree-sha1 = "c47c5fa4c5308f27ccaac35504858d8914e102f9" uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2" version = "0.9.4" [[deps.IOCapture]] deps = ["Logging", "Random"] git-tree-sha1 = "d75853a0bdbfb1ac815478bacd89cd27b550ace6" uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89" version = "0.2.3" [[deps.InteractiveUtils]] deps = ["Markdown"] uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" [[deps.JSON]] deps = ["Dates", "Mmap", "Parsers", "Unicode"] git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a" uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" version = "0.21.4" [[deps.LibCURL]] deps = ["LibCURL_jll", "MozillaCACerts_jll"] uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" version = "0.6.4" [[deps.LibCURL_jll]] deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" version = "8.0.1+1" [[deps.LibGit2]] deps = ["Base64", "NetworkOptions", "Printf", "SHA"] uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" [[deps.LibSSH2_jll]] deps = ["Artifacts", "Libdl", "MbedTLS_jll"] uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" version = "1.11.0+1" [[deps.Libdl]] uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" [[deps.LinearAlgebra]] deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"] uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" [[deps.Logging]] uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" [[deps.MIMEs]] git-tree-sha1 = "65f28ad4b594aebe22157d6fac869786a255b7eb" uuid = "6c6e2e6c-3030-632d-7369-2d6c69616d65" version = "0.1.4" [[deps.Markdown]] deps = ["Base64"] uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" [[deps.MbedTLS_jll]] deps = ["Artifacts", "Libdl"] uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" version = "2.28.2+1" [[deps.Mmap]] uuid = "a63ad114-7e13-5084-954f-fe012c677804" [[deps.MozillaCACerts_jll]] uuid = "14a3606d-f60d-562e-9121-12d972cd8159" version = "2023.1.10" [[deps.NetworkOptions]] uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" version = "1.2.0" [[deps.OpenBLAS_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" version = "0.3.23+2" [[deps.Parsers]] deps = ["Dates", "PrecompileTools", "UUIDs"] git-tree-sha1 = "716e24b21538abc91f6205fd1d8363f39b442851" uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" version = "2.7.2" [[deps.Pkg]] deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" version = "1.10.0" [[deps.PlutoUI]] deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "FixedPointNumbers", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "MIMEs", "Markdown", "Random", "Reexport", "URIs", "UUIDs"] git-tree-sha1 = "e47cd150dbe0443c3a3651bc5b9cbd5576ab75b7" uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8" version = "0.7.52" [[deps.PlutoVSCodeDebugger]] deps = ["AbstractPlutoDingetjes", "InteractiveUtils", "Markdown", "REPL"] git-tree-sha1 = "888128e4c890f15b1a0eb847bfd54cf987a6bc77" uuid = "560812a8-17ff-4261-aab5-f8f600b273e2" version = "0.2.0" [[deps.PrecompileTools]] deps = ["Preferences"] git-tree-sha1 = "03b4c25b43cb84cee5c90aa9b5ea0a78fd848d2f" uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a" version = "1.2.0" [[deps.Preferences]] deps = ["TOML"] git-tree-sha1 = "7eb1686b4f04b82f96ed7a4ea5890a4f0c7a09f1" uuid = "21216c6a-2e73-6563-6e65-726566657250" version = "1.4.0" [[deps.Printf]] deps = ["Unicode"] uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" [[deps.REPL]] deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" [[deps.Random]] deps = ["SHA"] uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [[deps.Reexport]] git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b" uuid = "189a3867-3050-52da-a836-e630ba90ab69" version = "1.2.2" [[deps.SHA]] uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" version = "0.7.0" [[deps.Serialization]] uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" [[deps.Sockets]] uuid = "6462fe0b-24de-5631-8697-dd941f90decc" [[deps.SparseArrays]] deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"] uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" version = "1.10.0" [[deps.Statistics]] deps = ["LinearAlgebra", "SparseArrays"] uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" version = "1.9.0" [[deps.SuiteSparse_jll]] deps = ["Artifacts", "Libdl", "Pkg", "libblastrampoline_jll"] uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c" version = "7.2.0+1" [[deps.TOML]] deps = ["Dates"] uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" version = "1.0.3" [[deps.Tar]] deps = ["ArgTools", "SHA"] uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" version = "1.10.0" [[deps.Test]] deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [[deps.Tricks]] git-tree-sha1 = "aadb748be58b492045b4f56166b5188aa63ce549" uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775" version = "0.1.7" [[deps.URIs]] git-tree-sha1 = "b7a5e99f24892b6824a954199a45e9ffcc1c70f0" uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4" version = "1.5.0" [[deps.UUIDs]] deps = ["Random", "SHA"] uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" [[deps.Unicode]] uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" [[deps.Zlib_jll]] deps = ["Libdl"] uuid = "83775a58-1f1d-513f-b197-d71354ab007a" version = "1.2.13+1" [[deps.libblastrampoline_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" version = "5.8.0+1" [[deps.nghttp2_jll]] deps = ["Artifacts", "Libdl"] uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" version = "1.52.0+1" [[deps.p7zip_jll]] deps = ["Artifacts", "Libdl"] uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" version = "17.4.0+2" """ # ╔═║ Cell order: # β•Ÿβ”€c924a590-a189-4ca2-abef-2b7dca80fe11 # ╠═d0e6a2b2-1e5d-11ee-177a-5f0a92dd83f5 # ╠═ede9b8dd-104f-4d5c-a134-f1fc67a1b9c7 # ╠═8325847e-fd7e-42ef-84c7-a30c6467183e # ╠═13d2cf9a-2fce-47f9-a851-6dd80d130b63 # ╠═7a8c6eb4-cc33-41c3-9e1a-d8e07954fef9 # β•Ÿβ”€01368463-0f95-4ced-abb1-6c8800ca2524 # ╠═65bff575-5dcb-4d81-b357-2b2f8bfd43d7 # ╠═c862e547-3b62-4218-b06e-0e84d05d6587 # β•Ÿβ”€d115c2b6-f92d-4609-94a9-59391c160645 # β•Ÿβ”€201323b9-8caf-4acb-904e-b76d16e5ffb1 # β•Ÿβ”€f1bde184-7487-4745-8c47-0df407da6813 # ╠═adf46403-ec6b-4278-ae65-5747f319dc96 # β•Ÿβ”€0a1e9af6-6b32-49c6-9cf6-8cf7f594f109 # β•Ÿβ”€f2fde939-638a-4b69-94ee-d32aff03879e # ╠═05941b74-00f1-4937-9a1d-d01e6e1a776f # β•Ÿβ”€fbe39d75-01e8-4f3a-8e65-f260a039365e # ╠═4c41b737-c392-455e-b6d8-98931f88d467 # ╠═6879d22c-f01c-424f-bc37-eb42062e49db # ╠═55044c8e-3f70-4a55-ad9f-7514d44a7211 # ╠═a9bc9479-722d-4564-9cb9-560f7b0f4ffb # ╠═da343b23-1ee0-44f9-9341-2c337f0de333 # β•Ÿβ”€57929023-813c-42ab-acdd-8a8f9033c11a # β•Ÿβ”€8d9dd998-c3d0-435c-a709-ee42c586c230 # ╠═c2aa06c6-3d34-4793-afa6-2e5a7c8b920a # ╠═720f431c-00d6-418a-a33c-d440070a7363 # β•Ÿβ”€3362ad99-d10c-4312-84ae-e3876ad1787f # ╠═318a9af6-a7e9-449d-8299-db4b6ab11fea # β•Ÿβ”€cc621eb7-b977-4ee8-9fbf-600a6f2bcfd2 # β•Ÿβ”€02f7b708-1f21-4533-bc3c-de4573d0a14b # β•Ÿβ”€1e2d7cc9-45d8-4aca-806b-76f1e50986b0 # ╠═73932307-b68c-453a-a7e6-8ba5d8bd8334 # ╠═d866e092-f24b-4553-971f-c1f74f3a1c1a # ╠═3dfb8184-2fce-4296-9c47-f0a034e99f73 # β•Ÿβ”€7f70ce43-567b-47aa-856e-bb41ee00fcc4 # β•Ÿβ”€07db9619-2cfe-4796-a083-f571f6c30721 # ╠═ebd5e071-e151-43d6-806e-ca6582c0046b # ╠═22589abd-63f4-46de-9fed-b673a72a449f # β•Ÿβ”€0b129e2a-842f-44cd-9d5e-61f7090ab63d # β•Ÿβ”€bdac5c70-2114-4f2b-9a0b-14ff172a1559 # ╠═d508ea5d-cc5d-44d1-a1b0-8ae6c18bf954 # ╠═a87c1d5f-1160-477b-9de9-432f1b742e3f # β•Ÿβ”€a4004826-ee3d-451f-a944-dff8d0787481 # ╠═5ec6e1a4-ece4-4cdf-81f5-fe0d1c9c39b9 # β•Ÿβ”€f8e10efd-f29d-431b-bbc7-ae4c0608e4d6 # ╠═0e16969e-197f-4fca-a0f1-cbe4c4c4822e # β•Ÿβ”€00000000-0000-0000-0000-000000000001 # β•Ÿβ”€00000000-0000-0000-0000-000000000002
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
code
2278
### A Pluto.jl notebook ### # v0.19.27 using Markdown using InteractiveUtils # ╔═║ f32cb55a-cf6d-40cd-8d5a-81445a685b53 begin plutodevmacros_project= Base.current_project(normpath(@__DIR__, "../..")) pushfirst!(LOAD_PATH, plutodevmacros_project) # This loads the PlutoDevMacros environment, so we can do import with the latest version try Base.eval(Main, :(import PlutoDevMacros)) finally popfirst!(LOAD_PATH) # Remove plutodevmacros env end using Main.PlutoDevMacros end # ╔═║ e3296a1c-9d38-4363-b275-42738d1ebae7 asd(x::Int) = 3 # ╔═║ 5808997c-0da3-4d1d-8b9a-b0e8965ce4a8 @addmethod asd(x::Float64) = 4.0 # ╔═║ 65603c9c-5b1b-4cd0-9db2-7216520d1c36 @addmethod asd(x::String) = "LOL" * string(asd(1)) # ╔═║ 53f8ca75-67f1-47c5-9c1e-a3747b376c3a asd(3.0) === 4.0 || error("Something went wrong") # ╔═║ b4351ff1-65eb-45d8-9262-6811fc0884f1 asd("ASD") === "LOL3" || error("Something went wrong") # ╔═║ 18c8788a-0213-43f3-8359-329a0501fc6c @current_pluto_cell_id() |> string |> typeof # ╔═║ 63c5d858-7d51-48d6-b221-50343482044b @current_pluto_cell_id() === "63c5d858-7d51-48d6-b221-50343482044b" || error("Something went wrong") # ╔═║ 00ed0ca3-3b5e-45a8-bf46-55e898c4b923 @current_pluto_notebook_file() === string(first(split(@__FILE__(), "#==#"))) || error("Something went wrong") # ╔═║ bda0d273-68f2-4954-bad1-b6c7aef9c1bd @only_in_nb(asd) === asd # ╔═║ 9985d53f-bc97-41b3-ab08-435b75db58d1 let pd = plutodump(@macroexpand(@only_in_nb(a))) pd isa Text && pd.content === "Symbol a\n" || error("Something went wrong") end # ╔═║ 2647436d-5170-41f8-86de-9bce9acf2f70 @only_out_nb(3) === nothing # ╔═║ 5ec03ab5-a3e3-4855-af59-6e589f5b104f PlutoDevMacros.is_notebook_local() || error("Something went wrong") # ╔═║ Cell order: # ╠═f32cb55a-cf6d-40cd-8d5a-81445a685b53 # ╠═e3296a1c-9d38-4363-b275-42738d1ebae7 # ╠═5808997c-0da3-4d1d-8b9a-b0e8965ce4a8 # ╠═65603c9c-5b1b-4cd0-9db2-7216520d1c36 # ╠═53f8ca75-67f1-47c5-9c1e-a3747b376c3a # ╠═b4351ff1-65eb-45d8-9262-6811fc0884f1 # ╠═18c8788a-0213-43f3-8359-329a0501fc6c # ╠═63c5d858-7d51-48d6-b221-50343482044b # ╠═00ed0ca3-3b5e-45a8-bf46-55e898c4b923 # ╠═bda0d273-68f2-4954-bad1-b6c7aef9c1bd # ╠═9985d53f-bc97-41b3-ab08-435b75db58d1 # ╠═2647436d-5170-41f8-86de-9bce9acf2f70 # ╠═5ec03ab5-a3e3-4855-af59-6e589f5b104f
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
docs
2288
# PlutoDevMacros [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://disberd.github.io/PlutoDevMacros.jl/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://disberd.github.io/PlutoDevMacros.jl/dev) [![Build Status](https://github.com/disberd/PlutoDevMacros.jl/actions/workflows/CI.yml/badge.svg?branch=master)](https://github.com/disberd/PlutoDevMacros.jl/actions/workflows/CI.yml?query=branch%3Amaster) [![Coverage](https://codecov.io/gh/disberd/PlutoDevMacros.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/disberd/PlutoDevMacros.jl) [![Aqua QA](https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg)](https://github.com/JuliaTesting/Aqua.jl) > [!WARNING] > This package is currently undergoing a significant refactoring, the documentation is still outdated and will be updated (together with the README) once the code is stabilized This is a package containing macros/functions to help develop Packages using [Pluto](https://github.com/fonsp/Pluto.jl) notebooks testing/prototyping aids. The major feature contribution of this package is the `@fromparent` macro, which allows to load a local package in Pluto and have its code re-parsed and updated upon manual re-run of the cell containing the macro call. This is simlar to a `Revise`-based workflow but provides a few notable advantages: - Package code can be re-evaluated correctly without requiring a julia restart even when re-defining structs or constants - Local code reload, triggered manually via a floating button in the Pluto notebook, automatically triggers execution of all dependent cells, simplifying the process of testing changes of code on specific runtime paths - Possibilty of adding packages to the notebook environment which are not dependencies of the local package, very useful for testing plotting or benchmarking of the local package code without having to put the related packages in either the global or package-local environment - Support for the package extensions functionality added in julia 1.9, which together with the point on notebook environment above simplify the testing and development of extensions on the local package under development. See the [documentation](https://disberd.github.io/PlutoDevMacros.jl/) for more details.
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
docs
392
# PlutoDevMacros Documentation for [PlutoDevMacros](https://github.com/disberd/PlutoDevMacros.jl). ## @frompackage/@fromparent ```@contents Pages = [ "frompackage/introduction.md", "frompackage/basic_use.md", "frompackage/import_statements.md", "frompackage/skipping_parts.md", "frompackage/use_with_plutopkg.md", "frompackage/package_extensions.md", ] Depth = 1 ```
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
docs
563
# Other Functions This package also exports some additional convenience macros for simplifying package development aided by Pluto notebooks. Additionally, the *non-exported* function [`PlutoDevMacros.hide_this_log`](@ref) can be used for sending javascript code through logs to Pluto and hide the corresponding log from view (without stopping the javascript code to execute) ## Utilities Macros ```@docs @addmethod @only_in_nb @only_out_nb @current_pluto_cell_id @current_pluto_notebook_file ``` ## Utilities Functions ```@docs PlutoDevMacros.hide_this_log ```
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
docs
4548
# Basic Use ```julia @fromparent import_block @frompackage target import_block ``` The `@frompackage` macro takes a local Package (derived from the `target` path), loads it as a submodule of the current Pluto workspace and then process the various import/using statements inside `import_block` to extract varables/functions from the local Package into the notebook workspace. !!! note `@fromparent` is simply a convenience synthax that uses the calling notebook file as `target`. More details on how the target path is processed are given below.\ \ Due to the equivalence in functionality between `@frompackage` and `@fromparent`, the rest of the documentation will only refer to `@frompackage` for convenience. When changes to the code of the local Package are made, the cell containing the call to `@frompackage` can be re-executed to reload the most recent version of the module. Thanks to Pluto's reactivity, this will automatically trigger re-execution of all cells that use functionality defined in the local package loaded by the macro. When testing functionalities of the local package using statements in the notebook cells, this reactivity simplifies the workflow as one does not need to manually re-run tests. At the same time, re-loading the full package module at each statement (similar to what Revise does) would most likely generate a significant overhead. For this reason the *reload* of local code is only triggered manually within `@frompackage` and happens only when manually re-running the cell containing the macro call. This process is simplified by the reload button explained [below](#Reload-Button). ## `target` path The first argument to `@frompackage` (`target`) has to be an AbstractString (or a `@raw_str`) containing the path (either absolute or relative to the file calling the macro) that points to a local Package (the path can be to any file or subfolder within the Package folder). The main module of the package identified by the `target` path will be used as the module to process and load within the calling notebook ## `import_block` The second argument to the macro is supposed to be either a single `using`/`import` statement, or multiple statements wrapped inside a `begin...end` block. These statements are used to select which parts of the loaded Package module have to be evaluated and which of its variables have te be imported within the notebook scope. Most of these import statements are only relevant when called within Pluto, so `@frompackage` simply avoid loading the target Package and deletes these import statements **in most cases** when called oustide of Pluto. There is a specific type of import statement (relative import) that is relevant and applicable also outside of Pluto, so this kind of statement is maintained in the macro output even outside of Pluto. The macro respects the differentiation between `using` and `import` as in normal Julia, so statements containing `using Module` without any variable name specifier will import all the exported names of `Module`. ## Reload Button When called within Pluto, the `@frompackage` macro also creates a convenient button that can be used to re-execute the cell calling the macro to reload the Package code due to a change in the source files. This button can also be used to quickly navigate to the position of the cell containing the macro by using **Ctrl+Click**.\ The reload button will change appearance (getting a red border) when the macrocall incur in a runtime error either due to incorrect import statement (like if a relative import is used without a proper target) or due to an error encountered when loading the package code. Here is a short video showing the reload button. The window on the left has opened the [specific_imports1.jl](https://github.com/disberd/PlutoDevMacros.jl/blob/8e481f552fdce1562cc9e45970cb11e8b54faa71/test/TestPackage/src/specific_imports1.jl) notebook, while the one on the right has the [specific_imports2.jl](https://github.com/disberd/PlutoDevMacros.jl/blob/8e481f552fdce1562cc9e45970cb11e8b54faa71/test/TestPackage/src/specific_imports2.jl) one. Both are included in the TestPackage using for tests and defined in [test/TestPackage/src/TestPackage.jl](https://github.com/disberd/PlutoDevMacros.jl/blob/f7b2bbf3a89ca677ab1765a2d4fcb3a1600d66f6/test/TestPackage/src/TestPackage.jl) ```@raw html <video controls=true> <source src="https://user-images.githubusercontent.com/12846528/236453634-c95aa7b2-61eb-492f-85f5-6539bbb714d5.mp4" type="video/mp4"> </video> ```
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
docs
974
# Customize Macro Settings The macro also allows to override default settings similar to how one skip lines in the package, using a custom `@settings` block as: ```julia @fromparent begin @settings setting1 = val1 setting2 = val2 import * end ``` or alternatively: ```julia @fromparent begin @settings begin setting1 = val1 setting2 = val2 end import * end ``` Only assignments are supported inside the `@settings` block and only primitive values can be used as `val`, i.e. anything that is parsed as an `Expr` as macro argument is not a valid `val`. These are the supported settings: ## `SHOULD_PREPEND_LOAD_PATH` `Bool` value that **defaults to `false`**. This specifies whether the active environment added to the `LOAD_PATH` by the macro should go to the end or to the front of the `LOAD_PATH`. In some cases it can be useful to have the custom environment at the beginning of the LOAD_PATH for the purpose of locating packages.
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
docs
8449
# Supported import statements The macro supports 4 different types of import statements: - Relative Imports - Imports from the Package module - Import from the Parent module (or submodule) - Import from the Package dependencies (direct or indirect). which are explained in more details in their respective section All of them also allow the following (*catch-all*) notation `import Module: *`, which imports within the notebook all the variables that are created or imported within `Module`. This is useful when one wants to quickly import all the names defined in `Module` for testing without requiring to either: - export all names in the definition of `Module` - explicitly import each name using the `import Module: name1, name2, ...` synthax **Each import statement can only contain one module**, so statements like *`import Module1, Module2` are not supported. In case multiple imports are *needed, use multiple statements within a `begin...end` block. ## Relative Imports Relative imports are the ones where the module name starts with a dot (.). These are mostly relevant when the loaded module contains multiple submodules.\ **Relative import statements are also produced when the macro is called from Pluto**. !!! note Relative imports are mostly useful when creating packages with notebooks as building blocks (i.e. notebooks that are *included* within the local package module)\ \ While _catch-all_ notation is supported also with relative imports (e.g. `import ..SiblingModule: *`), the extraction of all the names from the desired relative module requires loading and inspecting the full Package module and is thus only functional inside of Pluto.\ **A relative-import with catch-all notation is deleted when @frompackage is called outside of Pluto**. ## Imports from Package module These are all the import statements that have the name `PackageModule` or `^` as the first identifier, e.g.: - `using PackageModule.SubModule` - `import PackageModule: varname` - `import PackageModule.SubModule.SubSubModule: *` These statements are processed by the macro and transformed so that `PackageModule` actually points to the module that was loaded by the macro. The alternative notation `^` can also be used to represent the `PackageModule`, so one can write the two expressions below interchangeably ```julia @fromparent import PackageModule: var_name @fromparent import ^: var_name ``` This is to avoid triggering the Pkg statusmark within Pluto which always appears when a valid name of a package is typed (`^` is not valid so it doesn't create the status mark). See image below: ![image](https://user-images.githubusercontent.com/12846528/236888015-454183e6-44c1-4cd0-b9f8-9faf67aa0da6.png) ## Imports from Parent module (or submodule) These statements are similar to the previous (imports from Package module) ones, with two main difference: - They only work if the `target` file is actually a file that is included in the loaded Package, giving an error otherwise - `ParentModule` does not point to the loaded Package, but the module that contains the line that calls `include(target)`. If `target` is loaded from the Package main module, and not from one of its submodules, then `ParentModule` will point to the same module as `PackageModule`. ### Catch-All A special kind parent module import is: ```julia import * ``` which is equivalent to: - `import ParentModule: *` if the `target` file provided to `@frompackage`/`@fromparent` **is** a file *included* in the target Package. - This tries to reproduce within the namespace of the calling notebook, the namespace that would be visible by the notebook file when it is loaded as part of the Package module outside of Pluto. - `import PackageModule: *` if the `target` file provided to `@frompackage`/`@fromparent` **is not** a file *included* in the target Package. ## Imports from Package dependencies It is possible to to import direct (or indirect) dependencies of the target Package from within the `@frompackage` macro. Direct dependencies are the ones directy listed within the `[deps]` section of the `Project.toml`. Indirect dependencies are instead all the packages within the Package's `Manifest.toml` which are not direct dependencies. To import a package dependency from the `@frompackage` macro, one must prepend the package name with `>.`, so for example if one wants to load the `BenchmarkTools` package from the macro, assuming that it is indeed a dependency of the target package, one can do: ```julia @frompackage target begin using >.BenchmarkTools end ``` This modification is necessary when trying to use `@frompackage` in combination with the Pluto PkgManager, as explained in [Issue 10](https://github.com/disberd/PlutoDevMacros.jl/pull/10). These kind of statements (import/using from Dependencies) are also supported both inside and outside Pluto. **Outside of Pluto, only direct dependencies are supported** (as that is how julia works) which means that the example code above will effectively translate to `using BenchmarkTools` both inside and outside of Pluto if BenchmarkTools is a direct dependency. !!! note These kind of statements can not be used in combination with the `catch-all` imported name (*).\ \ Imports from package dependencies are useful when trying to combine `@frompackage` with the integrated Pluto PkgManager. In this case, is preferable to keep in the Pluto notebook environment just the packages that are not also part of the target/loaded Package environment, and load the eventual packages that are also in the environment of the loaded Package directly from within the `@frompackage` `import_block`.\ \ Doing so minimizes the risk of having issues caused by versions collision between dependencies that are shared both by the notebook environment and the loaded Package environment. Combining the use of `@frompackage` with the Pluto PkgManager is a very experimental feature that comes with significant caveats. Please read the [related section](#use-of-fromparentfrompackage-with-pluto-pkgmanager) at the end of this README ## Re-export `using` names with Catch-All Prior to version v0.7.3 of PlutoDevMacros, the catch-all import would not allow to automatically import names in the scope of the parent/package module that were added via `using` statements. See [Issue 11](https://github.com/disberd/PlutoDevMacros.jl/issues/11) for more details on the reasons. This meant that to effectively have access to all of the names in the parent/package scope, the statement `@fromparent import *` would not be sufficient. If for example you had `using Base64` at the top of your module, to effectively have access to also the names of the `Base64` stdlib, you would have to call the macro as follows: ```julia @fromparent begin import * using >.Base64 end ``` Since v0.8.0 of PlutoDevMacros, the automatic inclusion of names exposed via `using` statements is the default behavior when doing `catch-all` imports. !!! note Since this behavior now brings by default many more names into scope, a new functionality in 0.8 is a check that names in the target packages do not clash with existing names in the Pluto module that is calling `@frompackage`. Once a clash is identified (i.e. two different objects with the same name are defined in both the Pluto module and the target package), the specific clashed name will not be brought into scope by `@frompackage` and a warning will be issued. \ \ You can see this warning for example in the test notebook at [test/TestUsingNames/test_notebook2.jl](https://github.com/disberd/PlutoDevMacros.jl/tree/master/test/TestUsingNames/test_notebook2.jl), where the name `:clash_name` is explicitly given to different values both in the target and calling modules, and results in the following warning: ![Warning Example Image](https://github.com/disberd/PlutoDevMacros.jl/assets/12846528/c32e53bd-3607-483c-9330-dad66a9b6a4a) If one wants to revert back to the previous version where only names effectively defined within the target module (or explicitly imported with `import OtherPackage: x`) would be brought into the Pluto module's scope, it is sufficient to prepend the `@exclude_using` macro to the _catch-all_ import statement like so: ```julia @fromparent @exclude_using import * ``` This statement can be used alone or coupled with other valid import statements within a `begin ... end` block.
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
docs
2073
# Introduction The main functionality provided by PlutoDevMacros is the possibility of loading local packages within a Pluto notebook without requiring to activate a local environment (and thus deactivate the Pluto package manager). This functionality is implemented inside the `FromPackage` submodule of `PlutoDevMacros` and accessed throught the [`@fromparent`](@ref) or [`@frompackage`](@ref) macros. !!! note Both [`@fromparent`](@ref) and [`@frompackage`](@ref) are exported by `PlutoDevMacros` itself without requiring to explicitly use `FromPackage`. While the [`@fromparent`](@ref) macro was initially developed in order to facilitate creating Julia packages using Pluto notebooks as building blocks, in its current implementation it helps a lot with prototyping and testing during local package development, even when creating normal packages not relying on Pluto notebooks as building blocks. This macro allows in fact to load the module of a local package within a running Pluto notebook and permits to easily reload the local code upon request similar to a `Revise`-based workflow but with a few notable advantages: - Package code can be re-evaluated correctly without requiring a julia restart even when re-defining structs or constants - Local code reload, triggered manually via a floating button in the Pluto notebook, automatically triggers execution of all dependent cells, simplifying the process of testing changes of code on specific runtime paths - Possibilty of adding packages to the notebook environment which are not dependencies of the local package, very useful for testing plotting or benchmarking of the local package code without having to put the related packages in either the global or package-local environment - Support for the package extensions functionality added in julia 1.9, which together with the point on notebook environment above simplify the testing and development of extensions on the local package under development. More details on the synthax and functionality of these macros is given in the following sections.
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
docs
3178
# Package Extensions The `@frompackage` macro supports [package extensions](https://pkgdocs.julialang.org/v1.9/creating-packages/#Conditional-loading-of-code-in-packages-(Extensions)) defined within the packages loaded by the macro within the [`import_block`](../basic_use.html#import_block) We specify two possible types of extensions within the context of `@frompackage`: - **Direct Extensions**: These are extensions that are defined directly within the local `target` package loaded by the macro - **Indirect Extensions**: These are extensions that are not defined by the `target` package directly, but by one of its dependencies. ## Direct Extensions An example of a scenario with Direct Extensions is the one of the `TestDirectExtension` package found in the [test/TestDirectExtension](https://github.com/disberd/PlutoDevMacros.jl/tree/master/test/TestDirectExtension) folder and whose Project.toml is replicated below: ```toml name = "TestDirectExtension" uuid = "f446dfe5-66ce-4684-9abf-53561df9f9a0" authors = ["Alberto Mengali <[email protected]>"] version = "0.1.0" [deps] Revise = "295af30f-e4ad-537b-8983-00126c2a3abe" [weakdeps] PlutoPlotly = "8e989ff0-3d88-8e9f-f020-2b208a939ff0" Example = "7876af07-990d-54b4-ab0e-23690620f79a" [extensions] PlutoPlotlyExt = "PlutoPlotly" Magic = "Example" ``` We can see that this package defines two extensions `PlutoPlotlyExt` and `Magic` that depend on the `PlutoPlotly` and `Example` packages respectively. When the `TestDirectExtension` module is loaded within a Pluto notebook using the `@frompackage` or `@fromparent` macro, the module is not associated to a package UUID so julia does not know that the `Magic` extension has to be loaded whenever the `Example` package is loaded into the notebook. To still support loading the extension code in this situation, the macro will *eval* the `Magic` module definition within the `TestDirectExtension` module if the `Example` package is defined within the notebook environment. This allows prototyping and testing package extensions during their development exploiting the `@frompackage` macro. Check the relevant example notebook located at [test/TestDirectExtension/test_extension.jl](https://github.com/disberd/PlutoDevMacros.jl/blob/master/test/TestDirectExtension/test_extension.jl) for more clarity. ## Indirect Extensions Indirect extensions are mostly handled correctly by julia directly, but some issues may arise when a package added to the notebook environment triggers the load of an extension of a package loaded as a [direct dependency](../import_statements.html#Imports-from-Direct-dependencies) within the [`import_block`](../basic_use.html#import_block). If the notebook package triggering the extension is loaded **after** the direct dependency has already been loaded by the `@frompackage` macro, an extension compilation error is generated because the direct dependency is not in the `LOAD_PATH` (See the [Use with PlutoPkg](../use_with_plutopk.md) section) The way to solve this issue is to simply reload the local code by using the re-executing the cell containing the macro call. This will trigger a call to `Base.retry_load_extensions`.
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
docs
2784
# Skipping Package Parts The macro also allows to specify parts of the source code of the target Package that have to be skipped when loading it within Pluto. This is achieved by adding a statement inside the `import_block` like the following: ```julia @skiplines lines ``` The `@skiplines` macro is not defined within the package, it's just processed during the parsing of the `@frompackage` macro. `lines` is expected to either be a single String, or a group of Strings within a `begin ... end` block. Each string represent a part of a file that has to be skipped, with the following formats being supported: 1. `filpeath:::firstline-lastline`: This specifies that all the lines between `firstline` and `lastline` (extrema included) in the file present at `filepath` must be skipped when loading the Package module 2. `filepath:::line`: Like 1. but a single line is skipped 3. `filepath`: Like 1. but the full file located at `filepath` is ignored when loading the module 4. `line`: Ignores line number `line` in the Package entry point (i.e. the file at `src/PackageName.jl` in the folder of PackageName) 5. `firstline-lastline`: Like 4., but ignores a range of lines. In all of the examples above `filepath` can be provided as either an absolute path, or as a relative path **starting from the `src` subfolder of the Package folder** The functionality of skipping lines is only used when `@frompackage` is called inside Pluto. When calling the macro from outside of Pluto, the eventual statement with `@skiplines` is discarded. ## Example For an example consider the source file of the `TestPackage` module defined at [test/TestPackage/src/TestPackage.jl](https://github.com/disberd/PlutoDevMacros.jl/blob/f7b2bbf3a89ca677ab1765a2d4fcb3a1600d66f6/test/TestPackage/src/TestPackage.jl), whose contents are shown below: ![image](https://user-images.githubusercontent.com/12846528/236829189-dc30414a-d936-4a63-831b-963664249558.png) The notebook called `out_notebook.jl` located in the main folder of `TestPackage` gives an example of how to use the new functionality. The following call to `@fromparent` is used to import the `TestPackage` in the notebook's workspace while removing some of the code that is present in the original source of `TestPackage`: ```julia @fromparent begin import TestPackage @skiplines begin "11" # Skip line 11 in the main file TestPackage.jl. "test_macro2.jl" # This skips the whole file test_macro2.jl "22-23" # This skips from line 21 to 22 in the main file, including extrema. "test_macro1.jl:::28-10000" # This skips parts of test_macro1.jl end end ``` The output of the notebook is also pasted here for reference: ![image](https://user-images.githubusercontent.com/12846528/236832303-eb2fdc0f-08fd-47e7-9c1d-35f1f1b637fd.png)
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.9.0
72f65885168722413c7b9a9debc504c7e7df7709
docs
2725
# Use with PlutoPkg The macro evaluates the code of the local `target` package within the Pluto notebook workspace. For this to work, the notebook needs to have access to all the packages that are loaded within the `target` package. Normally, this is achieved by either: - Adding the dependencies directly to the notebook environment - Activating the environment of the local package within the notebook The first option risk polluting the notebook environment with a lot of packages that are not directly used within the notebook, while the second option deactivate the integrate PlutoPkg which handles package dependencies. To address these issues, the macro currently adds the `target` package environment to the [`LOAD_PATH`](https://docs.julialang.org/en/v1/manual/code-loading/#code-loading) during package code evaluation in the notebook workspace. This approach gives the flexibility of loading arbitrary local package code without requiring to modify the notebook environment itself. !!! note For this to work, the environment of the local `target` package needs to be instantiated. The macro will actually errors if this is not the case. The macro tries to catch all possible exceptions that are thrown either during macro compilation or during the resulting expression evaluation (using a try catch) to correctly clean `LOAD_PATH` after the macro is executed. This approach may cause issues in case the notebook and the package environment share some dependencies at different version. In this case, the one that was loaded first is the actual version used within the notebook (and within the Package module when loaded in the notebook). The macro adds the local package environment at the second position in the LOAD_PATH (so after the notebook environment). This should minimize the potential issues as the notebook environment is parsed first to find the packages. This does not prevent the case when a package (for example DataFrames) that is only used by the loaded package, is also added to the notebook after the target Package has been loaded. In this case, the version of DataFrames used by the notebook will be the version loaded by Package, and not the one installed in the notebook environment. Upon restarting the notebook, the situation will flip. Since now DataFrames is in the notebook environment, the notebook version will be loaded both in the notebook and in the Package module, potentially causing issues with the PackageCode if it was depending on a different version of DataFrames. **Due to the issues just mentioned, use the macro knowing that it might break if you want to use the Pluto PkgManager without manually adding all depending packages to the notebook environment**.
PlutoDevMacros
https://github.com/disberd/PlutoDevMacros.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
4221
########################################################################## # brbase.jl Meinolf Geck and Sungsoon Kim # # Copyright (C) 1996 Equipe des groupes finis, Universite Paris VII # # # Example: If W=coxgroup(:type,rank) is a Coxeter group then the command # `BaseBruhat(W)' adds a component `incidence' to `W' which contains for # each element in `W.elts' the associated boolean vector defined above. # If one is only interested in the set of bi-grassmannians and the set of # base elements (especially for large groups), one should use the # commands: # gap> W := CoxeterGroup( \"F\", 4 ); # for example # gap> bg := bi_grassmannians( W ); # gap> base := FindBaseBruhat( W, bg ); # # written MG, SK, Oct 1996 ############################################################################ """ `bi_grassmannians(W)` returns the set of bi-grassmannians in the Coxeter group `W`, that is those elements whose right and left descent sets are both of length 1. The result is a matrix `bi` such that `bi[i,j]` contains those elements with leftdescents [i] and rightdescents [j]. """ function bi_grassmannians(W) toM(map(1:ngens(W)) do k bi=[empty(gens(W)) for i in 1:ngens(W)] ea=[one(W)] while true en=empty(gens(W)) for a in ea for r in 1:ngens(W) if !isleftdescent(W,inv(a),r) x=a*W(r) if !(x in en) && !any(j->j!=k && isleftdescent(W,x,j),1:ngens(W)) push!(en,x) end end end end for i in en l=leftdescents(W,inv(i)) if length(l)==1 push!(bi[only(l)],i) end end ea=en if isempty(en) break end end # InfoChevie("#I ",length.(bi),"\n") bi end) end """ `BaseBruhat(W)` The base of a poset relation is defined to be the set of all elements w ∈ W which cannot be obtained as the supremum of a subset not containing w. Denote the base by B. Then every element w in W can be coded by the boolean vector (e_b)_{b in B} recording the relation b<=w. The Bruhat order on W is given by the subset relation on such vectors. A `Dict` named `W.bruhatincidence` records such vectors. The key for `w∈ W` is the image of `inclusiongens(W)` by `w` and the value is the vector `e_b`. The bases for all finite Coxeter groups are determined in the article 'Bases for the Bruhat--Chevalley order on all finite Coxeter groups'. """ function BaseBruhat(W) get!(W,:bruhatincidence)do bg=bi_grassmannians(W) mins=[] InfoChevie("#I ") for r in axes(bg,1) for s in axes(bg,2) InfoChevie("\t",length(bg[r,s])) l1=bg[r,s] if !isempty(l1) inz=fill(0,length(l1),length(l1)) for i in eachindex(l1) for j in 1:i if bruhatless(W,l1[j],l1[i]) inz[i,j]=1 end end end for z in eachindex(l1) leqz=filter(j->inz[z,j]==1,1:z) leqz=setdiff(1:length(l1),leqz) for i in leqz z1=filter(<=(i),leqz) if sum(inz[i,z1])==1 && !(bg[r,s][i] in mins) push!(mins,bg[r,s][i]); end end end if all(==(1),inz[:,1]) push!(mins,bg[r,s][1]) end end end InfoChevie("\n#I ") end InfoChevie("No of base elements = ",length(mins),"\n") p=sortPerm(map(i->length(W,i),mins)) base=invpermute(mins,inv(p)) InfoChevie("#I Calculating incidence matrix...") incidence=Dict{Vector{Int},BitVector}() for w in elements(W) incidence[inclusiongens(W).^w]=BitVector(bruhatless.(Ref(W),base,w)) end InfoChevie("\n") incidence end end function CoxGroups.bruhatless(W,x,y) if x==one(W) return true end d=length(W,y)-length(W,x) if haskey(W,:bruhatincidence) println("hello") if d<0 return false end iy=W.bruhatincidence[inclusiongens(W).^y] ix=W.bruhatincidence[inclusiongens(W).^x] return iy==iy.|ix end while d>0 i=firstleftdescent(W,y) s=W(i) if isleftdescent(W,x,i) if x==s return true end x=s*x else d-=1 end y=s*y end return x==y end
Chevie
https://github.com/jmichel7/Chevie.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
6528
# TL.jl from TL.g (C) Francois Digne and Jean Michel 2014 # # functions for working with elements of a # Temperley-Lieb algebra of a Coxeter group # # we implement unequal parameter TL algebras for non-simply laced coxeter groups @GapObj struct TL{C,TW} W::TW parameter::Vector{C} x::Union{C,Nothing} end function TL(W,p;x=nothing) if p isa Tuple para=fill(p[1],ngens(W)) s=simple_reps(W,1:ngens(W)) C=sort(unique(s)) for i in 1:ngens(W) para[i]=p[findfirst(==(s[i]),C)] end else para=fill(p,ngens(W)) end TL(W,para,x,Dict{Symbol,Any}()) end Groups.Group(H::TL)=H.W HeckeAlgebras.coefftype(H::TL{C}) where C=C abstract type TLElt{P,C} end # P=typeof(keys) [Perms] C typeof(coeffs) TL(h::TLElt)=h.TL # algebra of element struct TLTElt{P,C,TH}<:TLElt{P,C} d::ModuleElt{P,C} TL::TH end basename(h::TLTElt)="tl" function IsFullyCommutative(W,w) N=refls(W,inversions(W,reverse(word(W,w)))) c(p)=isone(comm(p[1],p[2])) ? one(W) : p[1]^p[2] isempty(intersect(N,c.(cartesian(N,N)))) end tlbasis(H::TL)=(x...)->x==() ? one(H) : tlbasis(H,x...) tlbasis(H::TL,w::Vararg{Integer})=tlbasis(H,H.W(w...)) tlbasis(H::TL,w::Vector{<:Integer})=tlbasis(H,H.W(w...)) tlbasis(H::TL,h::TLTElt)=h tlbasis(H::TL,h::TLElt)=tlbasis(h) tlbasis(H::TL,w)=TLTElt(ModuleElt(w=>one(coefftype(H));check=false),H) Base.one(H::TL)=tlbasis(H,one(H.W)) Base.:^(a::TLElt, n::Integer)=n>=0 ? Base.power_by_squaring(a,n) : Base.power_by_squaring(inv(a),-n) function Base.:*(x::TLTElt{P,C},y::TLTElt{P,C})where {P,C} H=TL(x) W=Group(H) res=zero(ModuleElt{P,C}) for (i,(px,cx)) in enumerate(pairs(x.d)) temp=y.d*cx xi=inv(px) while xi!=one(W) s=firstleftdescent(W,xi) es=W(s) xi=es*xi temp1=Pair{P,C}[] for (j,(e,c)) in enumerate(pairs(temp)) if isleftdescent(W,e,s) q=H.parameter[s] push!(temp1,e=>(q+1)*c) else phie=inversions(W,word(W,e)) p=findfirst(x->roots(W,x)-roots(W,s) in roots(W,phie),phie) # on a une relation s2=k*s2*s1*s2 si dans N(s2s1s2) il y a # 2 racines dont la somme est une racine. Cette relation intervient # dans es*e ssi dans N(es*e) ... ou encore ssi dans N(e) il y a une # racine dont la difference avec W.roots[s] est une racine. if isnothing(p) push!(temp1,es*e=>c) else r=findfirst(==(roots(W,phie[p])-roots(W,s)),roots(W)) w=refls(W,r)*e q=H.parameter[s] if IsFullyCommutative(W,w) if cartan(W,s,r)==-2 Q=H.parameter[simple_reps(W,r)] coeff=(q+Q)*c elseif cartan(W,s,r)==-1 coeff=q*c elseif cartan(W,s,r)==-3 Q=H.parameter[simple_reps(W,r)] coeff=(q+Q+GetRoot(q*Q))*c else coeff=H.x*c end push!(temp1,w=>coeff) else w1=with_inversions(W,phie[1:findfirst(==(r),phie)-1]) w2=inv(w1)*refls(W,r)*e tlw1=TLTElt(H,ModuleElt(w1=>one(coefftype(H)))) tlw2=TLTElt(H,ModuleElt(w2=>one(coefftype(H)))) println("recursive case: ",s,"*",BraidMonoid(W)(e), " tl(w1)=",tlw1," tl(w2)=",tlw2) w=tlw1*tlw2 if cartan(W,s,r)==-2 Q=H.parameter[simple_reps(W,r)]; w*=(q+Q)*c elseif cartan(W,s,r)==-1 w*=q*c elseif cartan(W,s,r)==-3 Q=H.parameter[simple_reps(W,r)]; w*=(q+Q+root(q*Q))*c else w*=H.x*c end append!(temp1,pairs(w)) end end end end temp=ModuleElt(temp1) end res+=temp end TLTElt(res,H) end #F AlphaInvolution(h) ## The involution on TL Elements defined by T_w->T_{w^{-1}} ## (and same in other bases) Garside.Ξ±(h::TLTElt)=TLTElt(ModuleElt(inv(p)=>c for (p,c) in h.d),TL(h)) function Base.show(io::IO, h::TLElt) function showbasis(io::IO,e) w=word(TL(h).W,e) res=basename(h) if hasdecor(io) res*=isempty(w) ? "." : "_"*joindigits(w,"{}";always=true) else res*="("*join(w,",")*")" end fromTeX(io,res) end show(IOContext(io,:showbasis=>showbasis),h.d) end ## The function below is made member of CoxeterTLAlgebraOps just to hide it ## it computes T(w^-1)^-1 #CoxeterTLAlgebraOps.getTinv:=function(H,w)local p,i,q,W; # Error("not implemented"); # W:=Group(H); # if not IsBound(H.elts) then H.elts:=[W.identity]; fi; # if not IsBound(H.Tinv) then H.Tinv:=[Basis(H,"t")()];fi; # p:=Position(H.elts,w); # if p=false then Add(H.elts,w);p:=Length(H.elts);fi; # if not IsBound(H.Tinv[p]) then # i:=FirstLeftDescending(W,w); # q:=H.parameter[i]; # H.Tinv[p]:=Basis(H,"t")([W.identity,W.reflections[i]], # [(q[1]+q[2])/(q[1]*q[2]),-1/(q[1]*q[2])])* # H.operations.getTinv(H,W.reflections[i]*w); # fi; # return H.Tinv[p]; #end; # #Matrixtltot:=function(H)local W,l,t,tl,M; # if not IsBound(H.tltot) then # W:=H.group; # l:=Filtered(Elements(W),x->IsFullyCommutative(W,x)); # SortParallel(List(l,x->CoxeterLength(W,x)),l); # t:=Basis(H,"t"); tl:=Basis(H,"tl"); # H.elts:=l; # M:=List(List(l,x->tl(t(x))),x->List(l,y->Coefficient(x,y))); # H.tltot:=M^-1; # fi; # return H.tltot; #end; # ############################################################################## ### ### An exemple of CreateTLBasis: create the 'T' basis for ### CoxeterTLAlgebraOps (i.e. all TL algebras for Coxeter groups...) ### #CreateTLBasis("t",rec( # tl:=function(x) local W,tl; # tl:=Basis(x.TL,"tl"); # W:=x.TL.group; # return Sum([1..Length(x.coeff)],function(i) # if x.elm[i]=() then return x.coeff[i]*tl(); # else return x.coeff[i]*Product(CoxeterWord(W,x.elm[i]),j->tl(j)-tl()); # fi; # end); # end, # t:=function(x) local tl,H,M;H:=x.TL;tl:=Basis(H,"tl");M:=Matrixtltot(H); # return Sum([1..Length(x.coeff)],i->x.coeff[i]*TLEltOps.Normalize( # TLEltOps.MakeRec(H,"t",ShallowCopy(H.elts), # ShallowCopy(M[Position(H.elts,x.elm[i])])))); # end, # inverse:=function(h) # if Length(h.elm)<>1 then Error("inverse implemented only for single t_w");fi; # return h.coeff[1]^-1*TL(h).operations.getTinv(TL(h),h.elm[1]^-1); # end),CoxeterTLAlgebraOps); # #CreateTLBasis("tl",rec(tl:=x->x) # method to convert to tl #,CoxeterTLAlgebraOps);
Chevie
https://github.com/jmichel7/Chevie.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
768
using Documenter, Chevie makedocs(sitename="Chevie.jl documentation", modules=[Chevie], format = Documenter.HTML( # Use clean URLs, unless built as a "local" build prettyurls = !("local" in ARGS), #canonical = "https://juliadocs.github.io/Documenter.jl/stable/", collapselevel=1 ), pages=[ "index.md", "Infrastructure"=>[ "format.md", "symbols.md", "nf.md"], "Reflection groups"=>[ "permroot.md", "coxgroups.md", "weyl.md", "chars.md"], "Hecke algebras"=>[ "hecke.md", "kl.md", "algebras.md"], "garside.md", "Reductive groups"=>[ "semisimple.md", "cosets.md", "sscoset.md", "uch.md", "ct.md"], "Eigenspaces"=>[ "eigen.md", "dseries.md"], "Unipotent elements"=>[ "ucl.md", "urad.md"], "gendec.md", "dict.md" ] )
Chevie
https://github.com/jmichel7/Chevie.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
16543
ChevieDict::Dict{String,String}=Dict( "AbelianGenerators"=>"abelian_gens", "AbelianInvariants"=>"abelian_invariants", "Add"=>"push!", "Affine"=>"affine", #AffineRootAction "AlgebraicCentre"=>"algebraic_center", "AlmostCharacter"=>"almost_character or almostchar", "Append"=>"append!", "ApplyFunc(f,l)"=>"f(l...)", "Arrangements"=>"arrangements", "AsReflection"=>"reflection", "AsFraction"=>"fraction", "AsRootOfUnity"=>"Root1", "AssociatedPartition"=>"conjugate_partition", "AsymptoticAlgebra"=>"AsymptoticAlgebra", "AsWord"=>"word", "BadPrimes"=>"badprimes", "BaseIntMat"=>"baseInt", "Basis"=>"basis", "BetaSet"=>"Ξ²set", "BigCellDecomposition"=>"bigcell_decomposition", "Binomial"=>"binomial", "BipartiteDecomposition"=>"bipartite_decomposition", "BlocksMat"=>"blocks", "Braid"=>"BraidMonoid", "BraidMonoid"=>"BraidMonoid", "BraidRelations"=>"braid_relations", "BrieskornNormalForm"=>"Brieskorn_normal_form", "Bruhat"=>"bruhatless", "BruhatPoset"=>"Poset", "BruhatSmaller"=>"bruhatless", "Catalan"=>"catalan", "CartanMat(\"A\",5)"=>"cartan(:A,5)", "CartanMatrix"=>"cartan", "Cartesian"=>"cartesian", "CartesianAt"=>"lin2cart", "CartanMatFromCoxeterMatrix"=>"cartan", "CentralIdempotents"=>"centralidempotents", "Centralizer"=>"centralizer", "CentralizerGenerators"=>"centralizer_gens", "CharFFE"=>"char", #CharName "CharNames"=>"charnames", "CharParams(W)"=>"charinfo(W).charparams", "CharRepresentationWords"=>"traces_words_mats", "CharTable"=>"CharTable", "CheckHeckeDefiningRelations"=>"isrepresentation", "ChevieClassInfo"=>"classinfo", "ChevieCharInfo"=>"charinfo", "ClassName"=>"see ClassNames", "ClassTypes"=>"ClassTypes", "Coefficient(p,i)"=>"p[i]", "Collected"=>"tally", "CollectBy(l,f)"=>"collectby(f,l)", "Comm"=>"comm or commutator", "Combinations"=>"combinations", "ComplementIntMat"=>"complementInt", "ComplexConjugate"=>"conj", "ComplexReflectionGroup"=>"complex_reflection_group or crg", "Compositions"=>"compositions", "Concatenation(s::Vector)"=>"vcat(s...)", "ConcatenationString(s...)"=>"prod([s...])", "ConjugacyClasses"=>"conjugacy_classes", "ConjugacySet(b[,F][,type])"=>"conjcat(b[,F],ss=type).obj", "ConjugatePartition"=>"conjugate_partition", "CoxeterCoset"=>"spets", "CoxeterSubCoset"=>"subspets", "CoxeterElements(W[,l])"=>"elements(W[,l])", "CoxeterGroup(\"A\",5)"=>"coxeter_group(:A,5) or coxgroup", "CoxeterGroupByCoxeterMatrix(C)"=>"coxeter_group(cartan(C)) or coxgroup", "CoxeterGroupByCartanMatrix(C)"=>"coxeter_group(C) or coxgroup", "CoxeterGroupHyperoctaedralGroup(n)"=>"coxeter_hyperoctaedral_group(n) or coxhyp", "CoxeterGroupSymmetricGroup(n)"=>"coxeter_symmetric_group(n) or coxsym", "CoxeterLength(W,w)"=>"length(W,w)", "CoxeterMatrix"=>"coxmat or coxeter_matrix", "CoxeterMatrixFromCartanMat"=>"coxmat or coxeter_matrix", "CoxeterNumber"=>"coxnum or coxeter_number", "CoxeterWord(W,w)"=>"word(W,w)", "CoxeterWords(W[,l])"=>"word.(Ref(W),elements(W[,l]))", "CuspidalPairs"=>"cuspidal_data", "CuspidalUnipotentCharacters(W[,d])"=>"cuspidal(UnipotentCharacters(W)[,d])", "CyclotomicPolynomial(R,i)"=>"cyclotomic_polynomial(i)", "Cycle"=>"orbit", "Cycles"=>"orbits", "CyclotomicModP(c,p)"=>"FFE{p}(c)", "CycPol"=>"CycPol", "CycPolFakeDegreeSymbol"=>"fegsymbol", "CycPolGenericDegreeSymbol"=>"gendeg_symbol", "CycPolUnipotentDegrees(W)"=>"CycPoldegrees(UnipotentCharacters(W))", "DecomposedMat"=>"diagblocks", "DefectSymbol"=>"defectsymbol", "Degree(p)"=>"degree(p)", "DegreeFFE"=>"degree", "M::GarsideMonoid.delta"=>"M.Ξ΄", "DeligneLusztigCharacter"=>"deligne_lusztig_character or dlchar", "DeligneLusztigLefschetz"=>"deligne_lusztig_leftschetz or dlleftschetz", "DescribeInvolution"=>"describe_involution", "DetPerm(W)"=>"perm(detPerm(W))", "DiaconisGraham"=>"diaconis_graham", "DiagonalMat"=>"Diagonal or cat", "DiagonalOfMat"=>"diag", #DifferenceMultiSet "Digits"=>"digits", "Dimension"=>"dim or dimension", #Discriminant "DistinguishedParabolicSubgroups"=>"distinguished_parabolics", "Dominates"=>"dominates", "DrinfeldDouble"=>"drinfeld_double", "Drop"=>"deleteat!", #Dual "DualBraid"=>"DualBraidMonoid", "DualBraidMonoid"=>"DualBraidMonoid", "EigenspaceProjector"=>"eigenspace_projector", "EigenvaluesMat"=>"eigmat", "Elements"=>"elements", "ElementWithInversions(W,l)"=>"with_inversions(W,l)", "EltBraid"=>"image", "EltWord(W,w)"=>"W(w...)", "ER"=>"root", "ExteriorPower"=>"exterior_power", "FactorizedSchurElement"=>"FactorizedSchurElement", "FactorizedSchurElements"=>"FactorizedSchurElements", "FakeDegree"=>"fakedegree", "FakeDegrees"=>"fakedegrees", "FamiliesClassical"=>"FamiliesClassical", "Family"=>"Family", "FamilyImprimitive"=>"family_imprimitive", "Filtered(l,f)"=>"filter(f,l)", "FiniteCoxeterTypeFromCartanMat(m)"=>"type_cartan(m)", "FirstLeftDescending(W,w)"=>"firstleftdescent(W,w)", "ForAll(l::list,f::function)"=>"all(f,l)", "ForAny(l::list,f::function)"=>"any(f,l)", "ForEachCoxeterWord(W,f)"=>"for w in W f(word(W,w)) end", "ForEachElement(W,f)"=>"for w in W f(w) end", "FormatTable"=>"showtable", "Frobenius"=>"Frobenius", "FullSymbol"=>"fullsymbol", "FundamentalGroup"=>"fundamental_group", "FusionAlgebra"=>"fusion_algebra", "FusionConjugacyClasses"=>"fusion_conjugacy_classes", "GaloisCyc"=>"galois", "GarsideAlpha"=>"Ξ±", "GarsideWords"=>"elements", "GcdPartitions"=>"gcd_partitions", "GcdRepresentation(x,y)"=>"gcdx(x,y)[2:3]", "W.generators"=>"gens(W) or generators(W)", "Length(W.generators)"=>"ngens(W) or number_of_generators(W)", "List(l::list,f::function)"=>"map(f,l)", "GenericOrder"=>"generic_order", "GenericSign"=>"generic_sign", "GetRoot"=>"root", #GoodCoxeterWord "GraphAutomorphisms"=>"graph_automorphisms", "Hasse"=>"hasse", "Hecke"=>"hecke", "HeckeCharValues"=>"char_values", #HeckeCharValuesGood "HeckeCentralMonomials"=>"central_monomials", "HeckeClassPolynomials"=>"class_polynomials", "HeckeReflectionRepresentation"=>"reflection_representation or reflrep", #HeckeSubAlgebra "HermiteNormalFormIntegerMat"=>"hermite", "HermiteNormalFormIntegerMatTransforms(m)"=>"hermite_transforms(m)", "HighestPowerFakeDegrees(W)"=>"charinfo(W).B", "HighestPowerFakeDegreeSymbol"=>"degree_fegsymbol", "HighestPowerGenericDegrees(W)"=>"charinfo(W).A", "HighestPowerGenericDegreeSymbol"=>"degree_gendeg_symbol", "HighestShortRoot"=>"highest_short_root", "KazhdanLusztigPolynomial"=>"KLPol", "HyperplaneOrbits"=>"hyperplane_orbits", "ICCTable"=>"ICCTable", "Idempotents"=>"idempotents", "Incidence"=>"incidence", "IndependentLines"=>"independent_lines", "IndependentRoots"=>"independent_roots", "InducedLinearForm"=>"induced_linear_form", "InductionTable"=>"induction_table", "Inherit"=>"look at merge for hashes", "Intersection"=>"intersect", "IntermediateGroup"=>"intermediate_group", "IntFFE"=>"Int", "IntListToString"=>"joindigits", "InvariantForm"=>"invariant_form", "Invariants"=>"invariants", "Inversions"=>"inversions", "IsAbelian"=>"isabelian", "IsAssociative"=>"isassociative", "IsCyclic"=>"iscyclic", "IsCycPol(p)"=>"p isa CycPol", "IsFamily(f)"=>"f isa Family", "IsFFE(x)"=>"x isa FFE", "IsIsolated"=>"isisolated", "IsJoinLattice"=>"isjoin_lattice", "IsMeetLattice"=>"ismeet_lattice", "IsLeftDescending(W,w,i)"=>"isleftdescent(W,w,i)", "IsSubset(a,b)"=>"issubset(b,a)", "IsParabolic"=>"isparabolic", #IsNormalizing #IsQuasiIsolated "IsomorphismType"=>"isomorphism_type", "IsUnipotentElement(x)"=>"x isa UnipotentElement", "jInductionTable"=>"j_induction_table", "JInductionTable"=>"J_induction_table", "Join"=>"join", "KroneckerProduct"=>"kron", "LargestMovedPoint"=>"last_moved", "last"=>"ans", "LcmPartitions"=>"lcm_partitions", "LeadingCoefficient(p)"=>"p[end]", "LeftCell"=>"LeftCell", "LeftCells"=>"left_cells", "LeftDescentSet(W,w)"=>"leftdescents(W,w)", "LeftDivisorsSimple"=>"left_divisors", "LeftGcd"=>"leftgcd", "LeftLcm"=>"leftlcm", "M.LeftLcmSimples(x...)"=>"leftlcm(M,...)", "LinearExtension"=>"linear_extension", "List(l,f)"=>"map(f,l)", "ListBlist(a,b)"=>"a[b]", "ListPerm(p)"=>"perm(p)", "List(ConjugacyClasses(G),Representative)"=>"classreps(G) or class_representatives(G)", "LogFFE"=>"log", "LongestCoxeterElement(W)"=>"longest(W)", "LongestCoxeterWord(W)"=>"word(W,longest(W))", "LoewyLength"=>"loewylength", "LowestPowerFakeDegrees(W)"=>"charinfo(W).b", "LowestPowerFakeDegreeSymbol"=>"valuation_fegsymbol", "LowestPowerGenericDegrees(W)"=>"charinfo(W).a", "LowestPowerGenericDegreeSymbol"=>"valuation_gendeg_symbol", "Lusztigaw"=>"Lusztigaw", "LusztigAw"=>"LusztigAw", "LusztigInduction"=>"lusztig_induce", "LusztigInductionTable"=>"lusztig_induction_table", "LusztigRestriction"=>"lusztig_restrict", "MappingPermListList"=>"mappingPerm", "W.matgens"=>"reflection_representation(W) or reflrep", "W.matgens[i]"=>"reflection_representation(W,i) or reflrep", "MatStab"=>"stab_onmats", "MatXPerm(W,p)"=>"reflection_representation(W,p) or reflrep", "MatYPerm"=>"YMatrix", "Maximum"=>"max or maximum", "Minimum"=>"min or minimum", "Mod1"=>"modZ", "MovedPoints"=>"support", "Mvp(\"x\")"=>"Mvp(:x)", "W.N"=>"nref(W) or number_of_reflections(W)", "W.Nhyp"=>"nhyp(W) or number_of_hyperplanes(W)", "NrArrangements"=>"narrangements", "NrCombinations"=>"ncombinations", "NrConjugacyClasses"=>"nconjugacy_classes", "NrDrinfeldDouble"=>"ndrinfeld_double", "NrPartitions"=>"npartitions", "NrPartitionsSet"=>"npartitions", "NrPartitionTuples"=>"npartition_tuples", "NrRestrictedPartitions"=>"npartitions", "NullMat(m[,n])"=>"zeros(Int,m,m) resp. zeros(Int,m,n)", "NullspaceIntMat"=>"lnullspaceInt", "W.Nhyp"=>"number_of_hyperplanes(W) or nyp(W)", "Number(l,f)"=>"count(f,l)", "OnFamily(f,p::Perm)"=>"f^p", "OnFamily(f,p::Int)"=>"galois(f,p)", "OnMatrices"=>"onmats", "OnSets"=>"onsets", "OnTuples"=>"ontuples", "OnPolynomials(m,p)"=>"p^m", "W.orbitRepresentative"=>"simple_reps(W)", "W.orbitRepresentativeElements[i]"=>"simple_conjugating(W,i)", "OrderedPartitions"=>"compositions", "OrderFFE"=>"order", "OrderMod(n,m)"=>"order(Mod{m}(n))", "W.OrdersGeneratingReflections"=>"ordergens(W) or orders_of_generators(W)", "ParabolicClosure"=>"parabolic_closure", "ParabolicRepresentatives"=>"parabolic_reps", #ParabolicSubgroups "PartBeta"=>"partΞ²", "Partition"=>"partition", "Partitions"=>"partitions", "PartitionsSet"=>"partitions", "PartitionTuples"=>"partition_tuples", "PartitionTupleToString"=>"string_partition_tuple", "PermCosetsSubgroup(H,W)"=>"D=vcat(reduced(H,W)...);map(s->Perm(reduced.(Ref(H),D.*s),D),gens(W))", "PermListList(l1,l2)"=>"Perm(l1,l2)", "PermList(v)"=>"Perm(v)", "PermMatMat(m,n)"=>"Perm(m,n;dims=(1,2))", "PermMatX"=>"PermX", "PermMatY"=>"PermY", "PermutationMat(p,dim)"=>"Matrix(p,dim)", "PermutationOnClasses"=>"on_classes", "PermutationOnCharacters"=>"on_chars", "PermutationOnUnipotents"=>"on_unipotents", "Permuted(v,p)"=>"invpermute(v,p)", "PermutedByCols(m,p)"=>"invpermute(m,p;dims=2)", #PoincarePolynomial "Poset"=>"Poset", "Position(l,x)"=>"findfirst(==(x),l)", "PositionClass"=>"position_class", "PositionCartesian(a,b)"=>"cart2lin(a,b)=LinearIndices(reverse(Tuple(a)))[reverse(b)...]", "PositionDet"=>"charinfo(W).positionDet", "PositionId"=>"charinfo(W).positionId", "PositionRegularClass"=>"position_regular_class", "Positions(l,x)"=>"findall(==(x),l)", "PositionProperty(l,f)"=>"findfirst(f,l)", "PositionsProperty(l,f)"=>"findall(f,l)", "PowerRoot(x,y)"=>"(Root1(;r=x)^y).r", "Presentation"=>"Presentation", "PrintDiagram(W)"=>"diagram(W)", "Product"=>"prod", "ProportionalityCoefficient(v,w)"=>"ratio(v,w)", "QuasiIsolatedRepresentatives"=>"quasi_isolated_reps", "QuoInt"=>"div", "Radical"=>"radical", "RadicalPower"=>"radicalpower", "Rank"=>"rank", "RankSymbol"=>"ranksymbol", "RecFields"=>"propertynames", "ReducedCoxeterWord(W,w)"=>"word(W,W(w...))", "ReducedExpressions(W,w)"=>"words(W,w)", "ReducedInRightCoset(W,w)"=>"reduced(W,w)", "ReducedRightCosetRepresentatives(W,H)"=>"reduced(H,W)", "Reflection"=>"refls(W,i) or reflectionMatrix(root,coroot)", "ReflectionCharacter"=>"reflection_character or reflchar", "ReflectionCharValue"=>"tr(reflrep(W,w))", #ReflectionCoset "ReflectionDegrees(W)"=>"degrees(W)", "ReflectionCoDegrees(W)"=>"codegrees(W)", "ReflectionEigenvalues"=>"refleigen", "ReflectionGroup"=>"reflection_group", "ReflectionLength(W,w)"=>"reflength(W,w)", #ReflectionWord "ReflectionName(W)"=>"repr(W;context=:limit=>true)", "Reflections"=>"Perm.(reflections(W)[1:nhyp(W)])", #ReflectionSubCoset "ReflectionSubgroup"=>"reflection_subgroup", "ReflectionType"=>"refltype", "RegularEigenvalues"=>"regular_eigenvalues", "RelativeDegrees"=>"relative_degrees", "RelativeGroup"=>"relative_group", "Replace"=>"replace", "Representations"=>"representations", "RepresentativeConjugation(b,b'[,F][,type])"=>"conjugating_elt(b,b'[,F],ss=type)", "RepresentativeDiagonalConjugation"=>"diagconj_elt", "RepresentativeOperation"=>"transporting_elt or transporting_element", "RepresentativeRowColPermutation"=>"Perm_rowcol", "Restricted"=>"restricted", "RestrictedPartitions"=>"partitions", "RestrictedPerm(p,d)"=>"restricted(p,d)", "Reversed"=>"reverse", "ReversedWord"=>"reverse", "RightDescentSet(W,w)"=>"rightdescents(W,w)", "RightGcd"=>"rightgcd", "RightLcm"=>"rightlcm", "M.RightLcmSimples(x...)"=>"rightlcm(M,...)", "RootDatum"=>"rootdatum", "W.rootLengths"=>"rootlengths(W)", "W.roots"=>"W.rootdec", "RootsCartan(m)"=>"roots(m)", "W.rootInclusion"=>"inclusion(W)", "W.rootRestriction"=>"restriction(W)", "Rotation(v,i)"=>"circshift(v,-i)", "Rotations(v)"=>"circshift.(Ref(v),length(v):-1:1)", "ScalarProduct"=>"Chars.scalarproduct", "ScalMvp"=>"scalar", #SchurElement "SchurElements"=>"schur_elements", "SchurFunctor"=>"schur_functor", "SemisimpleCentralizerRepresentatives"=>"semisimple_centralizer_representatives or sscentralizer_reps", "SemisimpleElement"=>"ss", "SemisimpleRank"=>"semisimplerank", "SemisimpleSubgroup"=>"torsion_subgroup", "ShiftBeta"=>"shiftΞ²", "ShrinkGarsideGeneratingSet"=>"shrink", "SignedMatStab"=>"sstab_onmats", "SignedPerm"=>"SPerm", "SignedPermListList"=>"SPerm", "SignedPermMatMat(M,N)"=>"SPerm(M,N;dims=(1,2))", "W.simpleCoroots"=>"simplecoroots(W)", "W.simpleRoots"=>"simpleroots(W)", "Size(W)"=>"length(W)", "SmallestMovedPoint"=>"first_moved", "SmithNormalFormIntegerMat"=>"smith", "SmithNormalFormIntegerMatTransforms(m)"=>"smith_transforms(m)", "SolutionMat"=>"solutionmat", "SolutionIntMat"=>"solutionmatInt", "Sort"=>"sort!", "SortBy(l,f)"=>"sort!(l,by=f)", "SortingPerm(a)"=>"inv(sortPerm(a))", "SortParallel(a,b)"=>"b=b[sortperm(a)];sort!(a)", "SpecialPieces"=>"special_pieces", "Spets"=>"spets", "Split"=>"split", "SplitLevis"=>"split_levis", "Sprint"=>"string", "Stabilizer"=>"stabilizer", "StandardParabolic"=>"standard_parabolic", "StandardParabolicClass"=>"standard_parabolic_class", "StructureRationalPointsConnectedCentre"=>"structure_rational_points_connected_centre", "SubSpets"=>"subspets", "SubTorus"=>"SubTorus", "Sum"=>"sum", "SumIntersectionMat(m,n)"=>"(rowspace(vcat(m,n)),intersect_rowspace(m,n))", "Symbols"=>"BDSymbols", "SymbolsDefect(e,r,def,ct)"=>"symbols(e,r,ct,def)", "SymmetricDifference"=>"symdiff", "SymmetricPower"=>"symmetric_power", "Tableaux"=>"tableaux", "Tensored(c,d)"=>"vec([i.*j for i in c,j ind])", "M.ToOrdinary(i)"=>"B(M,i)", "Torus"=>"torus", "TorusOrder"=>"torus_order", "TraceMat"=>"tr", "TransitiveClosure"=>"transitive_closure", "Transporter"=>"transporter", "TransposedMat"=>"transpose or permutedims", "Transversals"=>"related to transversal and orbits", "TriangulizeMat"=>"echelon!", "Twistings"=>"twistings", "TwoTree(m)"=>"twotree(m)", "UnipotentAbelianPart"=>"abelianpart", "UnipotentCharacter"=>"unipotent_character or unichar", "UnipotentCharacters"=>"UnipotentCharacters", "UnipotentClasses"=>"UnipotentClasses", "UnipotentDecompose"=>"decompose", "UnipotentDegrees(W,q)"=>"degrees(UnipotentCharacters(W),q)", "UnipotentGroup"=>"UnipotentGroup", "UnorderedTuples"=>"multisets", "Valuation(p)"=>"valuation(p)", "Value(p,x)"=>"p(x)", "ValuePol"=>"evalpoly", "WeightInfo"=>"weightinfo", "WGraph"=>"Wgraph", "WGraphToRepresentation"=>"WGraphToRepresentation", "Zip(a1,..,an,f)"=>"map(f,a1,...,an)" ) function gap(s) if !(s isa Regex) s=Regex(s,"i") end kk=filter(x->occursin(s,x),keys(ChevieDict)) if isempty(kk) println("no match") return end pad=maximum(length(k) for k in kk)+2 print(join(sort([rpad(k,pad)*"=> "*ChevieDict[k]*"\n" for k in kk]),"")) end function fixdoc() pad=maximum(length(k) for k in keys(ChevieDict))+2 u=[rpad(k,pad)*v*"\n" for (k,v) in ChevieDict] sort!(u,by=lowercase) open("dict.md","w")do f write(f,""" # Dictionary from GAP3/Chevie The dictionary from GAP3/Chevie is as follows: ``` """) write(f,join(u)) write(f,"```") end length(u) end
Chevie
https://github.com/jmichel7/Chevie.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
3553
module Gap4 #println("loading Gap4 extension to Chevie") using GAP, Chevie, Reexport #@reexport using GAP function GAP.Obj(g::Group) get!(g,:GAP)do isempty(gens(g)) ? GAP.Globals.Group(GAP.Obj(one(g))) : GAP.Globals.Group(GAP.Obj.(gens(g))...) end end # Create a GAP permutation given a vector of 16-bit integers. # No input verification is done! Callers must ensure that the # entries of `vec` form a permutation of the numbers in the range # 0:length(vec)-1 function GAP.Obj(p::Perm{Int16}) # or UInt16 vec=p.d.-1 deg = length(vec) @assert deg <= 2^16 perm = ccall((:NEW_PERM2, GAP.libgap), GapObj, (Cuint,), deg) addr = ccall((:ADDR_PERM2, GAP.libgap), Ptr{UInt16}, (Any,), perm) copyto!(unsafe_wrap(Array, addr, deg), vec) return perm end function GAP.Obj(p::Perm{Int32}) # or UInt32 vec=p.d.-1 deg = length(vec) @assert deg <= 2^32 perm = ccall((:NEW_PERM4, GAP.libgap), GapObj, (Cuint,), deg) addr = ccall((:ADDR_PERM4, GAP.libgap), Ptr{UInt32}, (Any,), perm) copyto!(unsafe_wrap(Array, addr, deg), vec) return perm end # convert a GAP permutation into a Perm{Perms.Idef} function Perms.Perm(perm::GapObj) if GAP.TNUM_OBJ(perm) == GAP.T_PERM2 deg = ccall((:DEG_PERM2, GAP.libgap), Cuint, (Any,), perm) addr = ccall((:ADDR_PERM2, GAP.libgap), Ptr{UInt16}, (Any,), perm) vec = Vector{UInt16}(undef, deg) copyto!(vec, unsafe_wrap(Array, addr, deg)) Perms.Perm_(Perms.Idef.(vec.+1)) elseif GAP.TNUM_OBJ(perm) == GAP.T_PERM4 deg = ccall((:DEG_PERM4, GAP.libgap), Cuint, (Any,), perm) addr = ccall((:ADDR_PERM4, GAP.libgap), Ptr{UInt16}, (Any,), perm) vec = Vector{UInt32}(undef, deg) copyto!(vec, unsafe_wrap(Array, addr, deg)) Perms.Perm_(Perms.Idef.(vec.+1)) else error("<perm> is not a GAP permutation") end end #@test perm=GAP.evalstr("(1,2,3)(4,5)");perm==Gap.obj(Perm(perm)) mapgap(f,gv)=map(f,GAP.gap_to_julia(gv;recursive=false)) fromgap(g)=improve_type(GAP.gap_to_julia(g)) function CyclotomicNumbers.Cyc(p::GapObj) l=improve_type(Vector{Any}(GAP.Globals.ExtRepOfObj(p))) sum(i->E(length(l),i-1)*l[i],eachindex(l)) end function gapclassreps(g::PermGroup) gg=GAP.Obj(g) mapgap(Perm∘GAP.Globals.Representative,GAP.Globals.ConjugacyClasses(gg)) end function Groups.classreps(g::PermGroup) get!(g,:classreps)do if length(g)>19000 gapclassreps(g) else map(c->c.representative,conjugacy_classes(g)) end end end function Chars.CharTable(ct::GapObj) u=GAP.Globals.Irr(ct) girr=mapgap(x->mapgap(Cyc,x),u) irr=permutedims(hcat(girr...)) n=fromgap(GAP.Globals.ClassNames(ct)) cn=fromgap(GAP.Globals.CharacterNames(ct)) sz=fromgap(GAP.Globals.SizesCentralisers(ct)) s=fromgap(GAP.Globals.Size(ct)) id=fromgap(GAP.Globals.Identifier(ct)) Chars.CharTable(irr,cn,n,sz,s,Dict{Symbol,Any}(:name=>id)) end function Chars.CharTable(g::PermGroup) gg=GAP.Obj(g) # in case :classreps not computed using gapclassreps gc=gapclassreps(g) l=map(x->position_class(g,x),gc) ct=CharTable(GAP.Globals.CharacterTable(gg)) ct.irr[:,l]=ct.irr ct.classnames[l]=ct.classnames ct end function centralizer(g::PermGroup,p::Perm) gg=GAP.Obj(g) pp=GAP.Obj(p) c=GAP.Globals.Centralizer(gg,pp) Group(Perm.(GAP.Globals.GeneratorsOfGroup(c))) end function intersect(g1::PermGroup,g2::PermGroup) gg1=GAP.Obj(g1) gg2=GAP.Obj(g2) gg=GAP.Globals.Intersection(gg1,gg2) Group(Perm.(GAP.Globals.GeneratorsOfGroup(gg))) end end
Chevie
https://github.com/jmichel7/Chevie.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
35941
""" This is a port of the GAP3 package Algebras by CΓ©dric BonnafΓ©. """ module Algebras using ..Chevie export FiniteDimAlgebra, coefftype, AlgebraElt, basis, idempotents, involution, isassociative, SubAlgebra, TwoSidedIdeal, loewylength, radicalpower, centralidempotents, PolynomialQuotientAlgebra, Quaternions, SolomonAlgebra, ZeroHecke # finite dimensional algebra over ring whose elements have type C abstract type FiniteDimAlgebra{C} end coefftype(A::FiniteDimAlgebra{C}) where C=C InfoAlgebra=print """ `ppart(g,p)` Given an element `g` of a group and an integer `p` we can uniquely write `g=g₁gβ‚‚` where the order of `gβ‚‚` is prime to `p` and the order of `g₁` is a product of primes which divide `p`. this function returns `g₁`. """ function ppart(g,k) n=order(g) np=prod(p^m for (p,m) in factor(n) if k%p==0;init=1) g^(gcdx(np,div(n,np))[3]*div(n,np)) end """ `pprimesections(G::Group,p::Integer)` This function returns a partition of the indices of the conjugacy classes of `G`. Indices `i,j` are in the same part if the elements `x/ppart(x,p)` for `x` in `classreps(G)[i],classreps(G)[j]` are in the same class. ```julia-repl julia> G=symmetric_group(5) Group((1,2),(2,3),(3,4),(4,5)) julia> Algebras.pprimesections(G,2) 3-element Vector{Vector{Int64}}: [1, 2, 4, 5] [3, 6] [7] julia> Algebras.pprimesections(G,3) 5-element Vector{Vector{Int64}}: [1, 3] [2, 6] [4] [5] [7] ``` """ function pprimesections(G::Group,k::Integer) pp=map(x->x/ppart(x,k),classreps(G)) collectby(i->position_class(G,pp[i]),eachindex(pp)) end # properties of Algebras: have .multable, dim # Algebra element of algebra A over ring elements of type T # d coefficients on basis indexed by number # basis[1] should be identity element struct AlgebraElt{TA<:FiniteDimAlgebra,T} A::TA d::ModuleElt{Int,T} end Base.broadcastable(h::AlgebraElt)=Ref(h) AlgebraElt(A::FiniteDimAlgebra,v::AbstractVector)= AlgebraElt(A,ModuleElt(Pair.(1:dim(A),v))) Weyl.dim(A::FiniteDimAlgebra)=error("not implemented in general") idempotents(A::FiniteDimAlgebra)=error("not implemented in general") struct AlgebraHom source::FiniteDimAlgebra target::FiniteDimAlgebra images::Vector end (H::AlgebraHom)(h::AlgebraElt)=sum(H.images[k]*c for (k,c) in h.d) # fallback method Groups.gens(A::FiniteDimAlgebra)=basis(A) "`isabelian(A::FiniteDimAlgebra)` whether `A` is commutative" function Groups.isabelian(A::FiniteDimAlgebra) get!(A,:isabelian)do all(x*y==y*x for x in gens(A), y in gens(A)) end::Bool end function isassociative(A::FiniteDimAlgebra) get!(A, :isassociative)do l=basis(A) all((x*y)*z==x*(y*z) for x in l, y in l, z in l) end::Bool end function basis(A::FiniteDimAlgebra{T};force=false)where T get!(A,:basis)do if !force && dim(A)>10000 error(A," is of dimension ",dim(A),"\nif you really want to do that ", "call basis(A;force=true)") end map(i->basis(A,i),1:dim(A)) end end basis(A::FiniteDimAlgebra{T},i::Integer) where T = AlgebraElt(A,ModuleElt(Int(i)=>T(1))) Base.one(A::FiniteDimAlgebra)=basis(A,1) function Base.show(io::IO, h::AlgebraElt) if !get(io,:limit,false) && !get(io,:TeX,false) print(io,"AlgebraElt(",h.A,",",h.d,")") return end if haskey(h.A,:showbasis) showbasis=h.A.showbasis else showbasis=function(io::IO,e) fromTeX(io,"B"*"_{"*string(e)*"}") end end show(IOContext(io,:showbasis=>showbasis),h.d) end Base.:+(a::AlgebraElt,b::AlgebraElt)=AlgebraElt(a.A,a.d+b.d) Base.:+(a::AlgebraElt,b::Number)=a+one(a.A)*b Base.:-(a::AlgebraElt)=AlgebraElt(a.A,-a.d) Base.:-(a::AlgebraElt, b::AlgebraElt)=a+(-b) Base.:*(a::AlgebraElt, b::Vector)=a.*b #for tbl Base.:*(a::AlgebraElt, b)=AlgebraElt(a.A,a.d*b) Base.:*(b,a::AlgebraElt)=AlgebraElt(a.A,a.d*b) Base.://(a::AlgebraElt, b)=AlgebraElt(a.A,a.d//b) Base.zero(a::AlgebraElt)=AlgebraElt(a.A,zero(a.d)) Base.:^(a::AlgebraElt, n::Integer)=n>=0 ? Base.power_by_squaring(a,n) : Base.power_by_squaring(inv(a),-n) Base.isless(a::AlgebraElt,b::AlgebraElt)=isless(a.d,b.d) Base.:(==)(a::AlgebraElt,b::AlgebraElt)=a.d==b.d Base.hash(a::AlgebraElt,k::UInt)=hash(a.d,k) Base.one(a::AlgebraElt)=one(a.A) function LaurentPolynomials.coefficients(a::AlgebraElt{A,T})where {A,T} v=fill(T(0),dim(a.A)) for (i,c) in a.d v[i]=c end v end Base.Matrix(a::AlgebraElt)=toM(map(coefficients,a.*basis(a.A))) using LinearAlgebra function Base.inv(a::AlgebraElt) m=Matrix(a) d=LinearAlgebra.det_bareiss(m) if iszero(d) error(a," is not invertible") end mi=inv(m//1) if eltype(m)<:Integer && (isone(d) || d==-1) mi=Integer.(mi) end AlgebraElt(a.A,mi[1,:]) end GenLinearAlgebra.charpoly(a::AlgebraElt)=Pol(charpoly(Matrix(a))) function minpoly(a::AlgebraElt) p=charpoly(a) exactdiv(p,gcd(p,derivative(p)//1)) end basismult(A::FiniteDimAlgebra,i::Integer,j::Integer)=A.multable[i,j] function Base.:*(a::AlgebraElt{A,T1}, b::AlgebraElt{A,T2})where {A<:FiniteDimAlgebra,T1,T2} res=Pair{Int,promote_type(T1,T2)}[] for (i,c) in a.d, (i1,c1) in b.d append!(res,[k=>c*c1*c2 for (k,c2) in basismult(a.A,i,i1)]) end AlgebraElt(a.A,ModuleElt(res)) end function GenLinearAlgebra.rowspace(v::AbstractVector{<:ModuleElt}) v=filter(!iszero,v) if isempty(v) return v end kk=unique_sorted!(sort(vcat(map(x->collect(keys(x)),v)...))) V=fill(zero(first(values(v[1]))),length(v),length(kk)) for i in eachindex(v), (k,c) in v[i] V[i,searchsortedfirst(kk,k)]=c end map(r->ModuleElt(Pair.(kk,r)),eachrow(rowspace(V))) end function GenLinearAlgebra.rowspace(v::AbstractVector{<:AlgebraElt}) if isempty(v) return v end A=v[1].A map(x->AlgebraElt(A,x),rowspace(map(x->x.d,v))) end function saturate_left(gens,v) l=0 newl=1 while newl>l l=newl v=rowspace(vcat(v,map(g->g.*v,gens)...)) newl=length(v) end v end function saturate_right(gens,v) l=0 newl=1 while newl>l l=newl v=rowspace(vcat(v,map(g->v.*g,gens)...)) newl=length(v) end v end #----------------------------- LeftIdeal -------------------------------- @GapObj struct LeftIdeal{T<:FiniteDimAlgebra} parent::T basis end function left_ideal(A,v::AbstractVector) LeftIdeal(A,saturate_left(gens(A),rowspace(v)),Dict{Symbol,Any}()) end function Base.show(io::IO,I::LeftIdeal) print(io,"LeftIdeal(",I.parent,",[") join(io,I.basis,",") print(io,"])") end basis(I::LeftIdeal)=I.basis Weyl.dim(I::LeftIdeal)=length(basis(I)) #----------------------------- TwoSidedIdeal ---------------------------- @GapObj struct TwoSidedIdeal{T<:FiniteDimAlgebra} parent::T basis end function twosided_ideal(A,v::AbstractVector) v=rowspace(v) v=saturate_left(gens(A),v) if !isabelian(A) v=saturate_right(gens(A),v) end TwoSidedIdeal(A,v,Dict{Symbol,Any}()) end function Base.show(io::IO,I::TwoSidedIdeal) print(io,"TwoSidedIdeal(",I.parent,",[") join(io,I.basis,",") print(io,"])") end Groups.gens(I::TwoSidedIdeal)=basis(I) basis(I::TwoSidedIdeal)=I.basis Weyl.dim(I::TwoSidedIdeal)=length(basis(I)) #------------------------------------------------------------------------ # radicalpower(A,n) computes radical(A)^n. This is again a two-sided ideal function radicalpower(A::FiniteDimAlgebra,n) if n==0 return A elseif n==1 return radical(A) elseif haskey(A,:radicalpowers) && length(A.radicalpowers)>=n return A.radicalpowers[n] end res=vcat(map(b->b.*basis(radicalpower(A,n-1)),basis(radical(A)))...) ideal=TwoSidedIdeal(A,rowspace(res),Dict{Symbol,Any}()) # if dim(ideal)==0 # ideal.operations.LeftTrace=x->0*A.field.one; # ideal.operations.RightTrace=x->0*A.field.one; # else # ideal.operations.LeftTrace=x->TraceMat(List(base.vectors,v-> # Coefficients(base,Matrix(x*AlgebraElt(A,v))))); # ideal.operations.RightTrace=x->TraceMat(List(base.vectors,v-> # Coefficients(base,Matrix(A.AlgebraElt(A,v)*x)))); # end push!(A.radicalpowers,ideal) ideal end # loewylength(A) is the smallest d such that radicalpower(A,d)=0 function loewylength(A::FiniteDimAlgebra) get!(A,:loewylength)do d=1 if length(gens(radical(A)))==1 gen=gens(radical(A))[1] res=gen while !iszero(res) d+=1; res*=gen end else while dim(radicalpower(A,d))>0 d+=1 end end d end end function LeftIndecomposableProjectives(A::FiniteDimAlgebra) get!(A,:leftprojectives)do map(i->left_ideal(A,[i]),idempotents(A)) end end function centralidempotents(A::FiniteDimAlgebra) get!(A,:centralidempotents) do idem=idempotents(A) mat=[length(rowspace(i*basis(j))) for i in idem, j in LeftIndecomposableProjectives(A)] A.blocks=diagblocks(mat) perm=vcat(A.blocks...) A.cartan=mat[perm,perm] map(i->sum(idem[i]),A.blocks) end end function PermRoot.cartan(A::FiniteDimAlgebra) if !haskey(A,:cartan) centralidempotents(A) # computes A.blocks and A.cartan end if applicable(CharTable,A) && hasproperty(CharTable(A),:rows) rows=CharTable(A).rows else rows=string.(1:length(idempotents(A))) end rows=joindigits.(rows[vcat(A.blocks...)]) m=map(e->iszero(e) ? "." : repr(e),A.cartan) Format.Table(m,row_labels=rows) end #------------------------- SubAlgebra ------------------------- @GapObj struct SubAlgebra{T}<:FiniteDimAlgebra{T} parent::FiniteDimAlgebra{T} inclusion::Vector space::Matrix{T} end Weyl.dim(A::SubAlgebra)=length(A.inclusion) function SubAlgebra(A::FiniteDimAlgebra,l) inclusion=saturate_left(vcat([one(A)],l),vcat([one(A)],l)) space=improve_type(toM(coefficients.(inclusion))) res=SubAlgebra(A,inclusion,space,Dict{Symbol,Any}()) res.gens=restriction.(Ref(res),l) res end Groups.gens(A::SubAlgebra)=A.gens function Base.show(io::IO,A::SubAlgebra) print(io,"SubAlgebra(",A.parent,",",inclusion.(Ref(A),gens(A)),")") end # SUB.injection:=AlgebraHomomorphismByLinearity(SUB,A,SUB.basisinclusion); function PermRoot.inclusion(A::SubAlgebra,h::AlgebraElt) sum(c*A.inclusion[i] for (i,c) in h.d) end # SUB.belongs:=v->A.EltToVector(v) in subspace; # restriction of basis element b to A function PermRoot.restriction(A::SubAlgebra,b) res=solutionmat(A.space,coefficients(b)) if !isnothing(res) AlgebraElt(A,improve_type(res)) end end function basismult(A::SubAlgebra,i::Integer,j::Integer) restriction(A,A.inclusion[i]*A.inclusion[j]).d.d end #----------------------- Quaternions ----------------------------------- @GapObj struct Quaternions{T}<:FiniteDimAlgebra{T} multable::Matrix{Vector{Pair{Int,T}}} end function Quaternions(a::T=-1,b::T=-1)where T multable=[[1=>1] [2=>1] [3=>1] [4=>1]; [2=>1] [1=>a] [4=>1] [3=>-1]; [3=>1] [4=>-1] [1=>b] [2=>-b]; [4=>1] [3=>-a] [2=>b] [1=>-a*b]] multable=map(x->[x],multable) A=Quaternions(multable,Dict{Symbol,Any}()) A.a=a;A.b=b A.isabelian=false A.showbasis=(io::IO,i)->["","i","j","k"][i] A end Weyl.dim(A::Quaternions)=4 Base.show(io::IO,A::Quaternions{T}) where T=print(io,"Quaternions(",A.a,",",A.b,")") Groups.gens(A::Quaternions)=basis.(Ref(A),[2,3]) involution(h::AlgebraElt{<:Quaternions})= AlgebraElt(h.A,coefficients(h).*[1,-1,-1,-1]) LinearAlgebra.norm(h::AlgebraElt{<:Quaternions})=h*involution(h) #----------------------- 0-Hecke ----------------------------------- #@GapObj struct ZeroHecke{TE,TW<:CoxeterGroup{TE}}<:FiniteDimAlgebra{Int} @GapObj struct ZeroHecke{TE,TW<:CoxeterGroup{TE},T}<:FiniteDimAlgebra{T} W::TW e::Vector{TE} u::T end Base.show(io::IO,A::ZeroHecke)= print(io,hasdecor(io) ? "0-Hecke" : "ZeroHecke","(",A.W,")") Weyl.dim(A::ZeroHecke)=length(A.W) function basismult(A::ZeroHecke,i::Integer,j::Integer) res=A.e[j] for k in reverse(word(A.W,A.e[i])) if !isleftdescent(A.W,res,k) res=A.W(k)*res end end [findfirst(==(res),A.e)=>1] end function Tbasis(A::ZeroHecke) return function(v::Int...) prod(i->gens(A)[i],v;init=one(A)) end end Groups.gens(A::ZeroHecke)=basis.(Ref(A),2:ngens(A.W)+1) # 0-Hecke algebra of W with parameters 0,1 function ZeroHecke(W::CoxeterGroup,T=Int) e=elements(W);# we use they are stored by increasing CoxeterLength A=ZeroHecke(W,e,one(T),Dict{Symbol,Any}()) A.isabelian=false A.showbasis=(io::IO,i)->fromTeX(io,string("T_{",joindigits(word(A.W,A.e[i])),"}")) A end function PermRoot.radical(A::ZeroHecke) get!(A,:radical)do c=groupby(x->unique!(sort!(word(A.W,A.e[x]))),eachindex(A.e)) l=filter(x->length(x)>1,collect(values(c))) twosided_ideal(A,vcat(map(i->map(j->basis(A,i[1])-basis(A,j),i[2:end]),l)...)) end end # subsets:=Combinations([1..W.semisimpleRank])); # A.tbasis:=function(arg) local mot; # if Length(arg)>1 then mot:=arg; # elif IsList(arg[1]) then mot:=arg[1]; # elif IsInt(arg[1]) then mot:=Digits(arg[1]); # else mot:=CoxeterWord(W,arg[1]); # fi; # if mot=[] then return A.basis[Position(A.mots,[])]; # else return Product(mot,i->A.basis[Position(A.mots,[i])]); # fi; # end; # A.radical:=TwoSidedIdeal(A,Concatenation(A.radical)); # A.radicalpowers:=[A.radical]; # A.embedding:=function(g) return A.basis[Position(e,g)];end; #------------------------ T[q]/p(q)---------------------------------------- ## The function A.class sends a polynomial to its image in A ## An element of A is printed as "Class(polynomial)" @GapObj struct PolynomialQuotientAlgebra{T}<:FiniteDimAlgebra{T} p::Pol{T} fp::Vector{Pair{Pol{T},Int}} var::Symbol multable::Matrix{Vector{Pair{Int,T}}} end Weyl.dim(A::PolynomialQuotientAlgebra)=degree(A.p) Groups.gens(A::PolynomialQuotientAlgebra)=basis(A,2) Base.show(io::IO,A::PolynomialQuotientAlgebra)= print(io,eltype(A.p.c),"[",A.var,"]/",A.p) function PolynomialQuotientAlgebra(p::Pol{T})where T # A.string:=r->SPrint("Class(",Sum(r.coefficients, i-> i[1]*q^(i[2]-1)),")"); d=degree(p) function class(r::Pol) r*=one(p) r=isone(p[end]) ? pseudodiv(r,p)[2] : rem(r//1,p) filter(x->x[2]!=0,map(Pair,1:degree(r)+1,r[0:end])) end basismult(i,j)=class(Pol([1],i+j-2)) A=PolynomialQuotientAlgebra(p,sort(collect(factor(p)),by=x->degree(x[1])), LaurentPolynomials.varname, [basismult(i,j) for i in 1:d, j in 1:d],Dict{Symbol,Any}()) A.showbasis=(io::IO,i)->fromTeX(io,i==1 ? "β‹…1" : string(A.var)*(i==2 ? "" : string("^{",i-1,"}"))) A.isAbelian=true A.class=class A end function idempotents(A::PolynomialQuotientAlgebra) map(A.fp)do (pp,mul) a=pp^mul b=exactdiv(A.p,a) bezout=gcdx(a*1//1,b*1//1) res=bezout[2]*a+bezout[3]*b res=res[0] res=(bezout[3]*b)//res AlgebraElt(A,ModuleElt(A.class(res))) end end PermRoot.cartan(A::PolynomialQuotientAlgebra)=Diagonal(last.(A.fp)) function Chars.CharTable(A::PolynomialQuotientAlgebra) factors=first.(A.fp) irr=fill(0,dim(A),length(factors)) for k in eachindex(factors) coefs=factors[k][0:end] deg=degree(factors[k]) mat=fill(zero(coefs[1]),deg,deg) for i in 1:deg-1 mat[i+1,i]=1 end for i in 1:deg mat[i,deg]=-coefs[i] end for j in 1:dim(A) irr[j,k]=tr(mat^(j-1)) end end Format.Table(irr,col_labels=factors,row_labels=basis(A)) end function PermRoot.radical(A::PolynomialQuotientAlgebra) res=prod(first.(filter(i->i[2]>1,A.fp)),init=Pol([1],0)) A.radical=TwoSidedIdeal(A,[AlgebraElt(A,ModuleElt(A.class(res)))]) A.radicalpowers=[A.radical] A.radical end ###################################################################### ## GrothendieckRing(G,Q) renvoie l'anneau de Grothendieck A=Q Irr(G) ##(si Q est omis, on prend pour Q le corps des rationnels) ## ## A.basisname = "Ο‡" (par defaut) ## ## La fonction Degre envoie un element de l'anneau de ## Grothendieck sur son degre (virtuel a priori bien sur) @GapObj struct GrothendieckRing{T}<:FiniteDimAlgebra{T} G::Group ct::CharTable multable::Matrix{Vector{Pair{Int,T}}} positionid::Int end Weyl.dim(A::GrothendieckRing)=size(A.ct.irr,1) function CharTable(A::GrothendieckRing{T})where T if char(T)==0 rows=1:dim(A) irr=permutedims(A.ct.irr) else cl=classreps(A.G) rows=filter(i->gcd(order(cl[i]),char(T))==1,eachindex(cl)) irr=T.(permutedims(A.ct.irr)[rows,:]) end CharTable(irr,A.ct.classnames[rows],A.ct.charnames,A.ct.centralizers[rows], A.ct.order,Dict{Symbol,Any}(:name=>string(A))) end Base.show(io::IO,A::GrothendieckRing{T}) where T= print(io,"GrothendieckRing(",A.G,",",T,")") function PermRoot.radical(A::GrothendieckRing{T})where T if char(T)==0 || length(A.G)%char(T)!=0 b=empty(basis(A)) else p=char(T); while p<dim(A) p*=char(T) end mat=toM(coefficients.(basis(A).^p)) mat=rowspace(lnullspace(mat)) b=map(x->AlgebraElt(A,x),eachrow(mat)) end radical=TwoSidedIdeal(A,b) A.radicalpowers=[radical] radical end function LaurentPolynomials.degree(h::AlgebraElt) sum(c*Int(h.A.ct.irr[k,1]) for (k,c) in h.d) end function PermRoot.cartan(A::GrothendieckRing{T})where T if char(T)==0 Diagonal(fill(1,dim(A))) else Diagonal(length.(pprimesections(A.G,char(T)))) end end Base.one(A::GrothendieckRing)=basis(A,A.positionid) function GrothendieckRing(G::Group,T=Int) ct=CharTable(G) d=size(ct.irr,1) basismult(i,j)=filter(x->!iszero(x[2]),map(Pair,1:size(ct.irr,1), T.(decompose(ct,ct.irr[i,:].*ct.irr[j,:])))) multable=[basismult(i,j) for i in 1:d, j in 1:d] positionid=findfirst(i->all(isone,ct.irr[i,:]),1:d) A=GrothendieckRing{T}(G,ct,multable,positionid,Dict{Symbol,Any}()) A.isabelian=true A.showbasis=(io::IO,i)->"["*fromTeX(io,ct.charnames[i])*"]" A end; function idempotents(A::GrothendieckRing{T}) where T e=map(i->sum((conj.(A.ct.irr[:,i]).//A.ct.centralizers[i]).*basis(A)),1:dim(A)) if char(T)==0 return e end e=map(i->sum(e[i]),pprimesections(A.G,char(T))) map(x->AlgebraElt(A,ModuleElt(k=>T(c) for (k,c) in x.d)),e) end #GrothendieckRingOps.PrincipalIdempotent:=function(A)local G,e,c,res; # G:=A.group; # e:=Idempotents(GrothendieckRing(G)); # c:=PositionClass(G,G.identity); # res:=Sum(e{First(pprimesections(G,A.field.char),i->c in i)}); # return AlgebraElement(A,List(res.coefficients,i-> # [A.field.one*Numerator(i[1])/Denominator(i[1]),i[2]])); #end; #GrothendieckRingOps.PrincipalLoewyLength:=function(A)local e; # e:=GrothendieckRingOps.PrincipalIdempotent(A); # LoewyLength(A); # e:=List(A.radicalpowers,i->LeftIdeal(A,i.basis*e)); # A.principalloewyseries:=Filtered(e,i->i.dimension>0); # return Length(A.principalloewyseries)+1; #end; #RestrictionHomomorphism:=function(A,B)local k; # k:=induction_table(B.group,A.group).scalar; # return AlgebraHomomorphismByLinearity(A,B,k*B.basis); #end; function AdamsOperation(A::GrothendieckRing,n) r=map(x->position_class(A.G,x^n),classreps(A.G)) v=map(x->decompose(A.ct,x[r]),eachrow(A.ct.irr)) AlgebraHom(A,A,map(x->AlgebraElt(A,x),v)) end #----------------- Group Algebras ----------------------------------------- @GapObj struct GroupAlgebra{T,E,TG<:Group{E}}<:FiniteDimAlgebra{T} group::TG elts::Vector{E} one::Pair{Int,T} end #GroupAlgebraOps.CharacterDegrees:=function(A) # if A.field.char=0 then # A.characterDegrees:=CharacterDegrees(A.group); # else Error("Cannot compute CharacterDegrees in positive characteristic"); # fi; # return A.characterdegrees; #end; # #GroupAlgebraOps.CharTable:=function(A)local conj; # if A.field.char>0 then # Error("Cannot compute CharTable in positive characteristic"); # fi; # A.charTable:=CharTable(A.group); # conj:=List(Elements(A.group),i->PositionClass(A.group,i)); # A.charTable.basistraces:=List(A.charTable.irreducibles,chi->chi{conj}); # A.charTable.Print:=function(table)Display(table);end; # return A.charTable; #end; function PermRoot.radical(A::GroupAlgebra{T})where T if char(T)!=0 error("not implemented in positive characteristic") end TwoSidedIdeal(A,empty(basis(A)),Dict{Symbol,Any}()) end Base.show(io::IO,A::GroupAlgebra{T}) where T =print(io,"Algebra(",A.group,",",T,")") embedding(A::GroupAlgebra{T,E},g::E) where{T,E}=findfirst(==(g),A.elts) """ `GroupAlgebra(G,T=Int)` group algebra of `G` with coefficients `T` """ function GroupAlgebra(G,T=Int) A=GroupAlgebra(G,elements(G),1=>T(1),Dict{Symbol,Any}()) A.gens=map(g->basis(A,embedding(A,g)),gens(G)) if A.elts[1]!=one(G) error(one(G)," should be first in ",elements(G)) end A.showbasis=function(io::IO,e) fromTeX(io,"e"*"_{"*joindigits(word(A.group,A.elts[e]))*"}") end # if Q.char=0 then # A.radical:=TwoSidedIdeal(A,[]); # A.radicalpowers:=[A.radical]; # fi; A end Weyl.dim(A::GroupAlgebra)=length(A.elts) Groups.gens(A::GroupAlgebra)=A.gens basismult(A::GroupAlgebra{T},i::Integer,j::Integer) where T= [embedding(A,A.elts[i]*A.elts[j])=>T(1)] function centralidempotents(A::GroupAlgebra{T}) where T p=map(i->position_class(A.group,i),A.elts) res=map(eachrow(CharTable(A.group).irr))do chi ModuleElt(map(Pair,1:dim(A),chi[1].*conj.(chi[p]).//dim(A))) end if char(T)==0 return map(x->AlgebraElt(A,x),res) end pid=map(b->sum(res[b]),blocks(A.group,char(T))) map(i->AlgebraElt(A,ModuleElt(convert(ModuleElt{Int,T},i).d)),pid) end # augmentation morphism augmentation(r)=sum(values(r.d)) ################################################################################ ## La fonction SolomonAlgebra(W,Q) construit l'algebre de Solomon ## d'un groupe de Coxeter fini W sur le corps Q (s'il est omis, ## la fonction prend pour Q le corps des rationnels). Le resultat ## est une algebre A munie en plus des champs suivants (ici, r est ## le rang semi-simple de W) : ## A.group = W ## A.xbase = fonction qui envoie la partie I de [1..r] sur x_I ## A.ybase = fonction qui envoie la partie I de [1..r] sur y_I ## A.radical = radical de A : ## A.radical.base = base de A.radical (x_I-x_J)_{I et J conjugues} ## A.radical.dimension = dimension de A.radical ## A.radicalpowers = [A.radical] ## A.injection = injection dans l'algebre de groupe (disponible ## si |W| <= 2000 : jusqu'a D5 donc...) ## ## De plus ## A.base = base x_I ## A.parameters = parties de [1..r] (comme nombres : ex. 123 pour [1,2,3]) ## A.basisname = "X" (par defaut) ## ## La fonction SolomonAlgebra munit W du record W.solomon contenant ## les champs suivants : ## W.solomon.mackey = constantes de structure (coeff de x_I * x_J sur x_K) ## W.solomon.conjugacy = classes de conjugaison de parties de [1..r] ## reperees par leur position dans A.parameters ## W.solomon.domain = A ## W.solomon.subsets = parties de [1..r] #SolomonAlgebraOps.CharacterDegrees:=function(A) # if A.field.char=0 then # if A.type="Solomon algebra" then # A.characterDegrees:=List(A.group.solomon.conjugacy, i-> 1); # elif A.type="Generalized Solomon algebra" then # A.characterDegrees:=List(A.group.generalizedsolomon.conjugacy, i-> 1); # else # Error("<A> must be a Solomon algebra"); # fi; # else Error("Cannot compute character degrees of Solomon algebra in positive characteristic"); # fi; # return A.characterDegrees; #end; @GapObj struct SolomonAlgebra{T}<:FiniteDimAlgebra{T} W::FiniteCoxeterGroup multable::Matrix{Vector{Pair{Int,T}}} end function Base.show(io::IO,A::SolomonAlgebra{T})where T print(io,"SolomonAlgebra(",A.W,",",T,")") end @GapObj struct SolomonCharTable{TA} A::TA irr::Matrix{Int} rows::Vector{Vector{Int}} end function Base.show(io::IO,ct::SolomonCharTable) print(io,"CharTable(",ct.A,")") if !hasdecor(io) return end println(io) showtable(io,ct.irr,row_labels=joindigits.(ct.rows),dotzero=true) end function Chars.CharTable(A::SolomonAlgebra) W=A.W conj=first.(W.solomon_conjugacy) orb=map(i->reflection_subgroup(W,W.solomon_subsets[i]),conj) cox=map(g->prod(gens(g);init=one(g)),orb) irr=[W.solomon_mackey[j,i][i] for i in conj, j in conj] SolomonCharTable(A,irr,map(w->word(W,w),cox),Dict{Symbol,Any}()) # res.columns[Length(res.columns)]:=["0"]; # res.basistraces:=List([1..Length(res.irreducibles)],function(ii)local r; # r:=Concatenation(List([1..Length(W.solomon.conjugacy)], # i->List(W.solomon.conjugacy[i], j-> [j,res.irreducibles[ii][i]]))); # Sort(r); return List(r,i->i[2]);end); # if A.field.char=0 then return res;fi; # irr:=CyclotomicModP(res.irreducibles,A.field.char); # inc:=CollectBy([1..Length(irr)],irr);Sort(inc); # res.rows:=List(inc, i-> res.rows[i[1]]); # res.irreducibles:=List(inc, i-> irr[i[1]]); # res.basistraces:=CyclotomicModP(res.basistraces,A.field.char); # res.parameters:=List(inc, i-> A.parameters[W.solomon.conjugacy[i[1]][1]]); # res.invertiblematrix:=List(inc,i-> List(inc,j->irr[i[1]][j[1]])); # res.incidence:=inc; # return res; end function injection(A::SolomonAlgebra{T})where T W=A.W B=GroupAlgebra(W,T) # if A.type="Solomon algebra" then X=map(W.solomon_subsets)do i sum(j->basis(B,embedding(B,inv(j))),vcat(reduced(reflection_subgroup(W,i),W)...)) end # else # X:=List(W.generalizedsolomon.subgroups, i-> # Sum(ReducedRightCosetRepresentatives(W, i),i-> B.embedding(i^-1))); # fi; AlgebraHom(A,B,X) end Weyl.dim(A::SolomonAlgebra)=2^ngens(A.W) const LIM=10000 """ 'SolomonAlgebra(W,K)' Let `(W,S)` be a finite Coxeter group. If `w` is an element of `W`, let `R(w)={s ∈ S | l(ws) > l(w)}`. If `I` is a subset of `S`, we set `Y_I={w ∈ W | R(w)=I}`, `X_I={w ∈ W | R(w) βŠƒ I}`. Note that `X_I` is the set of minimal length left coset representatives of `W/W_I`. Now, let `y_I=βˆ‘_{w ∈ Y_I} w`, `x_I=βˆ‘_{w ∈ X_I} w`. They are elements of the group algebra `β„€ W` of `W` over `Z`. Now, let ``Ξ£(W) = βŠ•_{I βŠ‚ S} β„€ y_I = βŠ•_{I βŠ‚ S} β„€ x_I``. This is a sub-`β„€`-module of `β„€W`. In fact, Solomon proved that it is a sub-algebra of `β„€W`. Now, let `K(W)` be the Grothendieck ring of `W` and let `ΞΈ:Ξ£(W)β†’ K(W)` be the map defined by `ΞΈ(x_I) = Ind_{W_I}^W 1`. Solomon proved that this is an homomorphism of algebras. We call it the *Solomon homomorphism*. returns the Solomon descent algebra of the finite Coxeter group `(W,S)` over `K`. If `S=[s₁,…,sα΅£]`, the element `x_I` corresponding to the subset `I=[s₁,sβ‚‚,sβ‚„]` of `S` is printed as |X(124)|. Note that 'A:=SolomonAlgebra(W,K)' is endowed with the following fields: 'A.W': the group `W` 'A.basis': the basis `(x_I)_{I βŠ‚ S}`. 'A.xbasis': the function sending the subset `I` (written as a number: for instance `124` for `[s_1,s_2,s_4]`) to `x_I`. 'A.ybasis': the function sending the subset `I` to `y_I`. 'A.injection': the injection of `A` in the group algebra of `W`, obtained by calling 'SolomonAlgebraOps.injection(A)'. Note that 'SolomonAlgebra(W,K)' endows `W` with the field `W.solomon` which is a record containing the following fields: 'W.solomon_subsets': the set of subsets of `S` 'W.solomon_conjugacy': conjugacy classes of parabolic subgroups of `W` (a conjugacy class is represented by the list of the positions, in 'W.solomon.subsets', of the subsets `I` of `S` such that `W_I` lies in this conjugacy class). 'W.solomon_mackey': essentially the structure constants of the Solomon algebra over the rationals. ```julia-repl julia> W=coxgroup(:B,4) Bβ‚„ julia> A=SolomonAlgebra(W) SolomonAlgebra(Bβ‚„,Int64) julia> X=A.xbasis; X(1,2,3)*X(2,4) 2Xβ‚‚+2Xβ‚„ julia> W.solomon_subsets 16-element Vector{Vector{Int64}}: [1, 2, 3, 4] [1, 2, 3] [1, 2, 4] [1, 3, 4] [2, 3, 4] [1, 2] [1, 3] [1, 4] [2, 3] [2, 4] [3, 4] [1] [2] [3] [4] [] julia> W.solomon_conjugacy 12-element Vector{Vector{Int64}}: [1] [2] [3] [4] [5] [6] [7, 8] [9, 11] [10] [12] [13, 14, 15] [16] julia> Algebras.injection(A)(X(1,2,3)) e_+eβ‚„+e₃₄+e₂₃₄+e₁₂₃₄+e₂₁₂₃₄+e₃₂₁₂₃₄+e₄₃₂₁₂₃₄ ``` """ function SolomonAlgebra(W::FiniteCoxeterGroup,T=Int) r=ngens(W) d=2^r n=length(W) # if r <=7 then A.generators:=List([2..r+1],i->A.basis[i]);fi; I=sort(combinations(1:r),by=x->-length(x)) if !haskey(W,:solomon_mackey) if n>LIM InfoAlgebra("# structure constants...") end;c=n Idict=Dict(p=>i for (i,p) in enumerate(I)) subsets=map(x->map(j->Idict[j],combinations(x)),I) mackey=[Pair{Int,Int}[] for i in 1:d,j in 1:d] for w in W leftascents=Idict[setdiff(1:r,leftdescents(W,w))] rightascents=Idict[setdiff(1:r,leftdescents(W,inv(w)))] l=map(i->action(W,i,w),1:r) for i in subsets[leftascents] II=sort!(l[I[i]]) for j in subsets[rightascents] push!(mackey[i,j],Idict[Combinat.intersect_sorted(II,I[j])]=>1) end end if c%LIM==0 InfoAlgebra(c,".") end; c-=1 end if n>LIM InfoAlgebra("\n") end W.solomon_mackey=ModuleElt.(mackey) W.solomon_subsets=I end if !haskey(W,:solomon_conjugacy) if n>LIM InfoAlgebra("# orbits of parabolic subgroups...") end orb=1:d conj=Vector{Int}[] while !isempty(orb) i=orb[1] j=filter(k->!iszero(W.solomon_mackey[i,k][k]) && length(I[i])==length(I[k]),orb) push!(conj,j) orb=setdiff(orb,j) end W.solomon_conjugacy=conj if n>LIM InfoAlgebra("\n") end end basismult(i,j)=[k=>T(c) for (k,c) in W.solomon_mackey[i,j].d] multable=[basismult(i,j) for i in 1:d, j in 1:d] A=SolomonAlgebra(W,multable,Dict{Symbol,Any}()) A.xbasis=function(a...) a=sort(collect(a)) basis(A,findfirst(==(a),W.solomon_subsets)) end if iszero(char(T)) A.xprimebasis=function(a...) a=sort(collect(a)) sum(i->(-1//2)^(length(a)-length(i))*A.xbasis(i...),combinations(a)) end end A.ybasis=function(a...) a=sort(collect(a)) res=zero(one(A)) for i in filter(i->issubset(a,I[i]),eachindex(I)) res+=(-1)^(length(I[i])-length(a))*basis(A,i) end res end A.showbasis=function(io::IO,i) fromTeX(io,string("X_{",joindigits(A.W.solomon_subsets[i]),"}")) end if char(T)==0 A.characterDegrees=fill(1,length(W.solomon_conjugacy)) end A end function PermRoot.radical(A::SolomonAlgebra{T})where T get!(A,:radical) do if iszero(char(T)) if length(A.W)>LIM InfoAlgebra("# Computing radical...") end k=vcat(map(i->map(j->basis(A,i[1])-basis(A,j),i[2:end]), A.W.solomon_conjugacy)...) radical=TwoSidedIdeal(A,k,Dict{Symbol,Any}()) # if dim(radical)==0 # A.radical.operations.LeftTrace=x->0*A.field.one # A.radical.operations.RightTrace=x->0*A.field.one # else # subspace=Subspace(A.vectorspace,Matrix(k)) # base=CanonicalBasis(subspace) # A.radical.operations.LeftTrace=x->TraceMat(List(base.vectors,v-> # Coefficients(base,Matrix(x*AlgebraElt(A,v))))); # A.radical.operations.RightTrace=x->TraceMat(List(base.vectors,v-> # Coefficients(base,Matrix(AlgebraElt(A,v)*x)))); # end A.radicalpowers=[radical] if length(A.W)>LIM InfoAlgebra("done!\n") end radical end end end function permutation_character(W,S) t=induction_table(S,W).scalar i=findfirst(x->all(==(1),x),eachrow(CharTable(S).irr)) permutedims(CharTable(W).irr)*t[:,i] end #SolomonHomomorphism:=function(x) local A,i,W,T,irr,mat,WI,p; # A:=x.domain; W:=A.group; T:=CharTable(W); irr:=T.irreducibles; # mat:=List(irr, i-> 0); # for i in x.coefficients do # if A.type="Solomon algebra" then # WI:=ReflectionSubgroup(W,W.solomon.subsets[i[2]]); # elif A.type="Generalized Solomon algebra" then # WI:=W.generalizedsolomon.subgroups[i[2]]; # fi; ## p:=PermutationCharacter(W,WI); # p:=PermutationCharacterByInductiontable(W,WI); # faster for large groups # mat:=mat+i[1]*MatScalarProducts(T,irr,[p])[1]; # od; # return GrothendieckRing(W,A.field).VectorToElt(mat); #end; #SolomonAlgebraOps.xprimePrint:=function(r) local res,i,A,f,xprime; # A:=r.domain; # A.xprimebasisname:="X'"; # res:=Matrix(r); # xprime:=Matrix(List(A.group.solomon.subsets,A.xprimebasis)); # res:=AlgebraElt(A,res*xprime^-1); # res:=res.coefficients; # if IsBound(A.xprimeprint) then A.xprimeprint(r); # else # f:=function(coef) # if coef[1]=A.field.one then # Print(A.xprimebasisname,"(",A.parameters[coef[2]],")"); # elif coef[1]=-A.field.one then # Print(" - ",A.xprimebasisname,"(",A.parameters[coef[2]],")"); # else Print(coef[1],"*",A.xprimebasisname,"(",A.parameters[coef[2]],")"); # fi; # end; # if Length(res)=0 then Print("0*",A.xprimebasisname,"(", # A.parameters[A.one.coefficients[1][2]],")"); # else # f(res[1]); # for i in [2..Length(res)] do # if res[i][1] < 0 or (res[i][1]=-A.field.one and A.field.char <> 2) # then Print(" - ");f([-res[i][1],res[i][2]]); # else Print(" + ");f(res[i]); # fi; # od; # fi; # fi; #end; # #ProjectionMatrix:=function(quotient) local res; # quotient.zero:=quotient.operations.Zero(quotient); # quotient.generators:=quotient.operations.Generators(quotient); # Basis(quotient); # res:=List(Basis(quotient.factorNum).vectors, # i-> quotient.semiEchelonBasis.operations.Coefficients(Basis(quotient), # VectorSpaceProjection(quotient,i))); # return res; #end; # #SolomonAlgebraOps.Radical:=function(A)local B,space,quotient,mat; # if A.field.char=0 then return A.radical;fi; # B:=GrothendieckRing(A.group,GF(A.field.char)); # space:=B.vectorspace; # quotient:=space/Subspace(space,Matrix(Radical(B).basis)); # mat:=List(A.basis,i->Matrix(SolomonHomomorphism(i))); # mat:=mat*ProjectionMatrix(quotient); # A.radical:=TwoSidedIdeal(A,AlgebraElt(A,NullspaceMat(mat))); # A.radicalpowers:=[A.radical]; # return A.radical; #end; function idempotents(A::SolomonAlgebra{T})where T get!(A,:idempotents)do W=A.W if char(T)==0 M=CharTable(A).irr # if A.type="Solomon algebra" then I=W.solomon_subsets[first.(W.solomon_conjugacy)] # elseif A.type="Generalized Solomon algebra" then # I:=List(W.generalizedsolomon.conjugacy, i-> # W.generalizedsolomon.signedcompositions[i[1]]); # end else # #if A.type="Solomon algebra" then M=CharTable(A).invertiblematrix I=CharTable(A).parameters # #fi; end r=length(I) e=permutedims(inv(M*1//1))*map(i->A.xbasis(i...),I) f=map(i->sum(e[i:r]),1:r) n=loewylength(A) v=Pol(T[1],1) pol=sum(j->binomial(2*n,j)*v^(2*n-j)*(1-v)^j,0:n) InfoAlgebra("# Computations to do: ",r) # f[1]=one(A) for i in 2:r f[i]=pol(f[i-1]*f[i]*f[i-1]) InfoAlgebra(".",r-i) end InfoAlgebra("\n") e[r]=f[r] for i in 1:r-1 e[i]=f[i]-f[i+1] end e end end #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #Section{Generalized Solomon algebras} # #In this subsection, we refer to the paper cite{BH05}. # #If `n` is a non-zero natural number, we denote by `W_n` the Weyl group of #type `B_n` and by `W_{-n}` the Weyl group of type `A_{n-1}` (isomorphic to #the symmetric group of degree `n`). If `C=[i_1,...,i_r]` is a *signed #composition* of `n`, we denote by `W_C` the subgroup of `W_n` equal to `W_C # = W_{i_1} x ... x W_{i_r}`. This is a subgroup generated by reflections (it #is not in general a parabolic subgroup of `W_n`). Let `X_C = {x ∈ W_C #| l(xw) β‰₯ l(x) βˆ€ w ∈ W_C}`. Note that `X_C` is the set of #minimal length left coset representatives of `W_n/W_C`. Now, let #`x_C=βˆ‘_{w ∈ X_C} w`. We now define `Ξ£'(W_n) = βŠ•_C β„€ #`, where `C` runs over the signed compositions of `n`. By cite{BH05}, #this is a subalgebra of `ZW_n`. Now, let `Y_C` be the set of elements of #`X_C` which are not in any other `X_D` and let `y_C=βˆ‘_{w ∈ Y_C} w`. #Then `Ξ£'(W_n) = βŠ•_C β„€ y_C`. Moreover, the linear map #`ΞΈ' : Ξ£^'(W_n) β†’ K(W_n)` defined by #`ΞΈ'(x_C) = Ind_{W_C}^{W_n} 1` is a *surjective homomorphism* of #algebras (see cite{BH05}). We still call it the *Solomon homomorphism*. #SolomonAlgebraOps.Print:=function(A) # Print("GeneralizedSolomonAlgebra(",A.group,",",A.field,")"); #end; end
Chevie
https://github.com/jmichel7/Chevie.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
64206
""" Characters and conjugacy classes of complex reflection groups. The `CharTable` of a finite complex reflection group `W` is computed using the decomposition of `W` in irreducible groups (see `refltype`). For each irreducible group the character table is either computed using recursive formulas for the infinite series, or read into the system from a library file for the exceptional types. Thus, character tables can be obtained quickly even for very large groups (e.g., Eβ‚ˆ). Similar remarks apply for conjugacy classes. The conjugacy classes and irreducible characters of irreducible finite complex reflection groups have canonical labelings by certain combinatorial objects; these labelings are used in the tables we give. For the classes, these are partitions or partition tuples for the infinite series, or, for exceptional Coxeter groups, Carter's admissible diagrams [Carter1972](biblio.htm#Car72); for other primitive complex reflection groups we just use words in the generators to specify the classes. For the characters, these are again partitions or partition tuples for the infinite series, and for the others they are pairs of two integers `(d,e)` where `d` is the degree of the character and `e` is the smallest symmetric power of the reflection representation containing the given character as a constituent (the `b`-invariant of the character). This information is given by the functions `classinfo` and `charinfo`. When you display the character table, the canonical labelings for classes and characters are displayed. A typical example is `coxgroup(:A,n)`, the symmetric group `π”–β‚™β‚Šβ‚` where classes and characters are parameterized by partitions of `n+1` (this is also the case for `coxsym(n+1)`). ```julia-repl julia> W=coxgroup(:A,3) A₃ julia> CharTable(W) CharTable(A₃) β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚1111 211 22 31 4β”‚ β”œβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚1111β”‚ 1 -1 1 1 -1β”‚ β”‚211 β”‚ 3 -1 -1 . 1β”‚ β”‚22 β”‚ 2 . 2 -1 .β”‚ β”‚31 β”‚ 3 1 -1 . -1β”‚ β”‚4 β”‚ 1 1 1 1 1β”‚ β””β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ julia> W=coxgroup(:G,2) Gβ‚‚ julia> ct=CharTable(W) CharTable(Gβ‚‚) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚Aβ‚€ Ã₁ A₁ Gβ‚‚ Aβ‚‚ A₁+Ã₁│ β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚Ο†β‚β€šβ‚€ β”‚ 1 1 1 1 1 1β”‚ β”‚Ο†β‚β€šβ‚† β”‚ 1 -1 -1 1 1 1β”‚ β”‚Ο†β€²β‚β€šβ‚ƒβ”‚ 1 1 -1 -1 1 -1β”‚ β”‚Ο†β€³β‚β€šβ‚ƒβ”‚ 1 -1 1 -1 1 -1β”‚ β”‚Ο†β‚‚β€šβ‚ β”‚ 2 . . 1 -1 -2β”‚ β”‚Ο†β‚‚β€šβ‚‚ β”‚ 2 . . -1 -1 2β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ julia> ct.charnames 6-element Vector{String}: "\\phi_{1,0}" "\\phi_{1,6}" "\\phi_{1,3}'" "\\phi_{1,3}''" "\\phi_{2,1}" "\\phi_{2,2}" julia> ct.classnames 6-element Vector{String}: "A_0" "\\tilde A_1" "A_1" "G_2" "A_2" "A_1+\\tilde A_1" ``` Reflection groups have fake degrees (see [`fakedegrees`](@ref)), whose valuation and degree give two integers `b,B` for each irreducible character of `W`. For spetsial groups (which include finite Coxeter groups), the valuation and degree of the generic degrees of the Hecke algebra give two more integers `a,A` (for Coxeter groups see [Carter1985, Ch.11](biblio.htm#Car85) for more details). These integers are also used in the operations of truncated induction, see [`j_induction_table`](@ref) and [`J_induction_table`](@ref). Iwahori-Hecke algebras and cyclotomic Hecke algebras also have character tables, see the corresponding chapters. We now describe for each type our conventions for labeling the classes and characters. Type `Aβ‚™` (`nβ‰₯0`). In this case we have `W β‰… π”–β‚™β‚Šβ‚`. The classes and characters are labelled by partitions of `n+1`. The partition labelling a class is the cycle type of the elements in that class; the representative in '.classtext' is the concatenation of the words corresponding to each part, where the word for a part `i` is the product of `i-1` consecutive generators (starting one higher than the last generator used for the previous parts). The partition labelling a character describes the type of the Young subgroup such that the trivial character induced from this subgroup contains that character with multiplicity `1` and such that every other character occurring in this induced character has a higher `a`-value. Thus, the sign character is labelled by the partition `(1ⁿ⁺¹)` and the trivial character by the partition `(n+1)`. The character of the reflection representation of `W` is labelled by `(n,1)`. Type `Bβ‚™` (`nβ‰₯2`). In this case `W=W(Bβ‚™)` is isomorphic to the wreath product of the cyclic group of order `2` with the symmetric group `𝔖ₙ`. Hence the classes and characters are parameterized by pairs of partitions such that the total sum of their parts equals `n`. The pair corresponding to a class describes the signed cycle type for the elements in that class, as in [Carter1972](biblio.htm#Car72). We use the convention that if `(Ξ»,ΞΌ)` is such a pair then `Ξ»` corresponds to the positive and `ΞΌ` to the negative cycles. Thus, `(1ⁿ,-)` and `(-,1ⁿ)` label respectively the trivial class and the class of the longest element. The pair corresponding to an irreducible character is determined via Clifford theory, as follows. We have a semidirect product decomposition `W(Bβ‚™)=N β‹Š 𝔖ₙ` where `N` is the standard `n`-dimensional `𝔽₂ⁿ`-vector space. For `a,b β‰₯ 0` such that `n=a+b` let ``Ξ·_{a,b}`` be the irreducible character of `N` which takes value `1` on the first `a` standard basis vectors and value `-1` on the last `b` standard basis vectors of `N`. Then the inertia subgroup of ``Ξ·_{a,b}`` has the form ``T_{a,b}=N.(𝔖_a Γ— 𝔖_b)`` and we can extend ``Ξ·_{a,b}`` trivially to an irreducible character ``Ξ·Μƒ_{a,b}`` of ``T_{a,b}``. Let `Ξ±` and `Ξ²` be partitions of `a` and `b`, respectively. We take the tensor product of the corresponding irreducible characters of `𝔖_a` and `𝔖_b` and regard this as an irreducible character of ``T_{a,b}``. Multiplying this character with ``Ξ·Μƒ_{a,b}`` and inducing to `W(Bβ‚™)` yields an irreducible character ``Ο‡= Ο‡_{(Ξ±,Ξ²)}`` of `W(Bβ‚™)`. This defines the correspondence between irreducible characters and pairs of partitions as above. For example, the pair `((n),-)` labels the trivial character and `(-,(1ⁿ))` labels the sign character. The character of the natural reflection representation is labeled by `((n-1),(1))`. Type `Dβ‚™` (`nβ‰₯4`). In this case `W=W(Dβ‚™)` can be embedded as a subgroup of index `2` into the Coxeter group `W(Bβ‚™)`. The intersection of a class of `W(Bβ‚™)` with `W(Dβ‚™)` is either empty or a single class in `W(Dβ‚™)` or splits up into two classes in `W(Dβ‚™)`. This also leads to a parameterization of the classes of `W(Dβ‚™)` by pairs of partitions `(Ξ»,ΞΌ)` as before but where the number of parts of `ΞΌ` is even and where there are two classes of this type if `ΞΌ` is empty and all parts of `Ξ»` are even. In the latter case we denote the two classes in `W(Dβ‚™)` by `(Ξ»,+)` and `(Ξ»,-)`, where we use the convention that the class labeled by `(Ξ»,+)` contains a representative which can be written as a word in `{s₁,s₃,…,sβ‚™}` and `(Ξ»,-)` contains a representative which can be written as a word in `{sβ‚‚,s₃, …,sβ‚™}`. By Clifford theory the restriction of an irreducible character of `W(Bβ‚™)` to `W(Dβ‚™)` is either irreducible or splits up into two irreducible components. Let `(Ξ±,Ξ²)` be a pair of partitions with total sum of parts equal to `n`. If `Ξ±!=Ξ²` then the restrictions of the irreducible characters of `W(Bβ‚™)` labeled by `(Ξ±,Ξ²)` and `(Ξ²,Ξ±)` are irreducible and equal. If `Ξ±=Ξ²` then the restriction of the character labeled by `(Ξ±,Ξ±)` splits into two irreducible components which we denote by `(Ξ±,+)` and `(Ξ±,-)`. Note that this can only happen if `n` is even. In order to fix the notation we use a result of [Stembridge1989](biblio.htm#Ste89) which describes the value of the difference of these two characters on a class of the form `(Ξ»,+)` in terms of the character values of the symmetric group `𝔖_{n/2}`. Recall that it is implicit in the notation `(Ξ»,+)` that all parts of `Ξ»` are even. Let `Ξ»'` be the partition of `n/2` obtained by dividing each part by `2`. Then the value of `Ο‡_{(Ξ±,-)}-Ο‡_{(Ξ±,+)}` on an element in the class `(Ξ»,+)` is given by `2^{k(Ξ»)}` times the value of the irreducible character of `𝔖_{n/2}` labeled by `Ξ±` on the class of cycle type `Ξ»'`. (Here, `k(Ξ»)` denotes the number of non-zero parts of `Ξ»`.) The labels for the trivial, the sign and the natural reflection character are the same as for `W(Bβ‚™)`, since these characters are restrictions of the corresponding characters of `W(Bβ‚™)`. The groups `G(d,1,n)`. They are isomorphic to the wreath product of the cyclic group of order `d` with the symmetric group `𝔖ₙ`. Hence the classes and characters are parameterized by `d`-tuples of partitions such that the total sum of their parts equals `n`. The words chosen as representatives of the classes are, when `d>2`, computed in a slightly different way than for `Bβ‚™`, in order to agree with the words on which Ram and Halverson compute the characters of the Hecke algebra. First the parts of the `d` partitions are merged in one big partition and sorted in increasing order. Then, to a part `i` coming from the `j`-th partition is associated the word `(l+1…1… l+1)ʲ⁻¹l+2…l+i` where `l` is the highest generator used to express the previous part. The `d`-tuple corresponding to an irreducible character is determined via Clifford theory in a similar way than for the `Bβ‚™` case. The identity character has the first partition with one part equal `n` and the other ones empty. The character of the reflection representations has the first two partitions with one part equal respectively to `n-1` and to `1`, and the other partitions empty. The groups `G(de,e,n)`. They are normal subgroups of index `e` in `G(de,1,n)`. The quotient is cyclic, generated by the image `g` of the first generator of `G(de,1,n)`. The classes are parameterized as the classes of `G(de,e,n)` with an extra information for a component of a class which splits. According to [Hugues1985](biblio.htm#Hu85), a class `C` of `G(de,1,n)` parameterized by a `de`-partition ``(Sβ‚€,…,S_{de-1})`` is in `G(de,e,n)` if `e` divides ``βˆ‘α΅’ i βˆ‘_{p∈ Sα΅’}p``. It splits in `d` classes for the largest `d` dividing `e` and all parts of all `Sα΅’` and such that `Sα΅’` is empty if `d` does not divide `i`. If `w` is in `C` then 'gⁱ w g⁻ⁱ' for 'i in 0:d-1' are representatives of the classes of `G(de,e,n)` which meet `C`. They are described by appending the integer `i` to the label for `C`. The characters are described by Clifford theory. We make `g` act on labels for characters of `G(de,1,n)` . The action of `g` permutes circularly by `d` the partitions in the `de`-tuple. A character has same restriction to `G(de,e,n)` as its transform by `g`. The number of irreducible components of its restriction is equal to the order `k` of its stabilizer under powers of `g`. We encode a character of `G(de,e,n)` by first, choosing the smallest for lexicographical order label of a character whose restriction contains it; then this label is periodic with a motive repeated `k` times; we represent the character by one of these motives, to which we append `E(k)ⁱ` for 'i in 0:k-1' to describe which component of the restriction we choose. Types `Gβ‚‚` and `Fβ‚„`. The matrices of character values and the orderings and labelings of the irreducible characters are exactly the same as in [Carter1985, p.412/413](biblio.htm#Car85): in type `Gβ‚‚` the character `φ₁,₃'` takes the value -1 on the reflection associated to the long simple root; in type `Fβ‚„`, the characters `φ₁,₁₂'`, `Ο†β‚‚,β‚„'`, `Ο†β‚„,₇'`, `Ο†β‚ˆ,₉'` and `φ₉,₆'` occur in the induced of the identity from the `Aβ‚‚` corresponding to the short simple roots; the pairs (`Ο†β‚‚,₁₆'`, `Ο†β‚‚,β‚„β€³`) and (`Ο†β‚ˆ,₃'`, `Ο†β‚ˆ,₉″`) are related by tensoring by sign; and finally `φ₆,₆″` is the exterior square of the reflection representation. Note, however, that we put the long root at the left of the Dynkin diagrams to be in accordance with the conventions in [Lusztig1985, (4.8) and (4.10)](biblio.htm#Lus85). The classes are labeled by Carter's admissible diagrams [Carter1972](biblio.htm#Car72). A character is labeled by a pair `(d,b)` where `d` denotes the degree and `b` the corresponding `b`-invariant. If there are several characters with the same pair `(d,b)` we attach a prime to them, as in [Carter1985](biblio.htm#Car85). Types `E₆,E₇,Eβ‚ˆ`. The character tables are obtained by specialization of those of the Hecke algebra. The classes are labeled by Carter's admissible diagrams [Carter1972](biblio.htm#Car72). A character is labeled by the pair `(d,b)` where `d` denotes the degree and `b` is the corresponding `b`-invariant. For these types, this gives a unique labeling of the characters. Non-crystallographic types `Iβ‚‚(m)`, `H₃`, `Hβ‚„`. In these cases we do not have canonical labelings for the classes. We label them by reduced expressions. Each character for type `H₃` is uniquely determined by the pair `(d,b)` where `d` is the degree and `b` the corresponding `b`-invariant. For type `Hβ‚„` there are just two characters (those of degree `30`) for which the corresponding pairs are the same. These two characters are nevertheless distinguished by their fake degrees: the character `φ₃₀,₁₀'` has fake degree `q¹⁰+qΒΉΒ²+` higher terms, while `φ₃₀,₁₀″` has fake degree `q¹⁰+q¹⁴+` higher terms. The characters in the table for type `Hβ‚„` are ordered in the same way as in [Alvis and Lusztig1982](biblio.htm#AL82). Finally, the characters of degree `2` for type `Iβ‚‚(m)` are ordered as follows. The matrix representations affording the characters of degree `2` are given by: `` ρ_j : s₁sβ‚‚ ↦ \\begin{pmatrix}\\zeta_m^j&0\\\\0&\\zeta_m^{-j}\\end{pmatrix}, s₁↦\\begin{pmatrix}0&1\\\\1&0\\end{pmatrix},`` where `1 ≀ j ≀ ⌊(m-1)/2βŒ‹`. The reflection representation is `ρ₁`. The characters in the table are ordered by listing first the characters of degree 1 and then `ρ₁,ρ₂,…`. Primitive complex reflection groups `Gβ‚„` to `G₃₄`. The groups `G₂₃=H₃`, `Gβ‚‚β‚ˆ=Fβ‚„`, `G₃₀=Hβ‚„` are exceptional Coxeter groups and have been explained above. Similarly for the other groups labels for characters consist primarily of the pair `(d,b)` where `d` denotes the degree and `b` is the corresponding `b`-invariant. This is sufficient for `Gβ‚„`, `G₁₂`, `Gβ‚‚β‚‚` and `Gβ‚‚β‚„`. For other groups there are pairs or triples of characters which have the same `(d,b)` value. We disambiguate these according to the conventions of [Malle2000](biblio.htm#Mal00) for `G₂₇, G₂₉, G₃₁, G₃₃` and `G₃₄`: - For `G₂₇`: The fake degree of `φ₃,β‚…'` (resp. `φ₃,β‚‚β‚€'`, `Ο†β‚ˆ,₉″`) has smaller degree that of `φ₃,β‚…β€³` (resp. `φ₃,β‚‚β‚€β€³`, `Ο†β‚ˆ,₉'`). The characters `Ο†β‚…,₁₅'` and `Ο†β‚…,₆'` occur with multiplicity 1 in the induced from the trivial character of the parabolic subgroup of type `Aβ‚‚` generated by the first and third generator (it is asserted mistakenly in [Malle2000](biblio.htm#Mal00) that `Ο†β‚…,₆″` does not occur in this induced; it occurs with multiplicity 2). - For `G₂₉`: The character `φ₆,₁₀‴` is the exterior square of `Ο†β‚„,₁`; its complex conjugate is `φ₆,₁₀⁗`. The character `φ₁₅,β‚„β€³` occurs in `Ο†β‚„,β‚βŠ—Ο†β‚„,₃`; the character `φ₁₅,₁₂″` is tensored by the sign character from `φ₁₅,β‚„β€³`. Finally `φ₆,₁₀'` occurs in the induced from the trivial character of the standard parabolic subgroup of type `A₃` generated by the first, second and fourth generators. - For `G₃₁`: The characters `φ₁₅,β‚ˆ'`, `φ₁₅,β‚‚β‚€'` and `Ο†β‚„β‚…,β‚ˆβ€³` occur in `Ο†β‚„,β‚βŠ—Ο†β‚‚β‚€,₇`; the character `Ο†β‚‚β‚€,₁₃'` is complex conjugate of `Ο†β‚‚β‚€,₇`; the character `Ο†β‚„β‚…,₁₂'` is tensored by sign of `Ο†β‚„β‚…,β‚ˆ'`. The two terms of maximal degree of the fakedegree of `φ₃₀,₁₀'` are `q⁡⁰+q⁴⁢` while for `φ₃₀,₁₀″` they are `q⁡⁰+2q⁴⁢`. - For `G₃₃`: The two terms of maximal degree of the fakedegree of `φ₁₀,β‚ˆ'` are `q²⁸+q²⁢` while for `φ₁₀,β‚ˆβ€³` they are `q²⁸+q²⁴`. The terms of maximal degree of the fakedegree of `Ο†β‚„β‚€,β‚…'` are `qΒ³ΒΉ+q²⁹` while for `Ο†β‚„β‚€,β‚…β€³` they are `qΒ³ΒΉ+2q²⁹`. The character `φ₁₀,₁₇'` is tensored by sign of `φ₁₀,β‚ˆ'` and `Ο†β‚„β‚€,₁₄'` is tensored by sign of `Ο†β‚„β‚€,β‚…'`. - For `G₃₄`: The character `Ο†β‚‚β‚€,₃₃'` occurs in `φ₆,β‚βŠ—Ο†β‚β‚…,₁₄`. The character `φ₇₀,₉'` is rational. The character `φ₇₀,₉″` occurs in `φ₆,β‚βŠ—Ο†β‚β‚…,₁₄`. The character `φ₇₀,β‚„β‚…'` is rational.The character `φ₇₀,β‚„β‚…β€³` is tensored by the determinant character of `φ₇₀,₉″`. The character `φ₅₆₀,β‚β‚ˆ'` is rational. The character `φ₅₆₀,β‚β‚ˆβ€΄` occurs in `φ₆,β‚βŠ—Ο†β‚ƒβ‚ƒβ‚†,₁₇`. The character `Ο†β‚‚β‚ˆβ‚€,₁₂'` occurs in `φ₆,β‚βŠ—Ο†β‚ƒβ‚ƒβ‚†,₁₇`. The character `Ο†β‚‚β‚ˆβ‚€,₃₀″` occurs in `φ₆,β‚βŠ—Ο†β‚ƒβ‚ƒβ‚†,₁₇`. The character `Ο†β‚…β‚„β‚€,₂₁'` occurs in `φ₆,β‚βŠ—Ο†β‚β‚€β‚…,β‚‚β‚€`. The character `φ₁₀₅,β‚ˆ'` is complex conjugate of `φ₁₀₅,β‚„`, and `Ο†β‚ˆβ‚„β‚€,₁₃'` is complex conjugate of `Ο†β‚ˆβ‚„β‚€,₁₁`. The character `Ο†β‚ˆβ‚„β‚€,₂₃'` is complex conjugate of `Ο†β‚ˆβ‚„β‚€,₁₉`. Finally `φ₁₂₀,₂₁'` occurs in induced from the trivial character of the standard parabolic subgroup of type `Aβ‚…` generated by the generators of `G₃₄` with the third one omitted. For the groups `Gβ‚…` and `G₇` we adopt the following conventions. For `Gβ‚…` they are compatible with those of [MalleRouquier2003](biblio.htm#MR03) and [BroueMalleMichel2014](biblio.htm#BMM14). - For `Gβ‚…`: We let `W=complex_reflection_group(5)`, so the generators are `W(1)` and `W(2)`. The character `φ₁,β‚„'` (resp. `φ₁,₁₂'`, `Ο†β‚‚,₃'`) takes the value `1` (resp. `΢₃`, `-΢₃`) on `W(1)`. The character `φ₁,β‚ˆβ€³` is complex conjugate to `φ₁,₁₆`, and the character `φ₁,β‚ˆ'` is complex conjugate to `φ₁,β‚„'` . The character `Ο†β‚‚,β‚…β€³` is complex conjugate to `Ο†β‚‚,₁`; `Ο†β‚‚,β‚…'` takes the value `-1` on `W(1)`. The character `Ο†β‚‚,₇'` is complex conjugate to `Ο†β‚‚,β‚…'`. - For `G₇`: We let `W=complex_reflection_group(7)`, so the generators are `W(1)`, `W(2)` and `W(3)`. The characters `φ₁,β‚„'` and `φ₁,₁₀'` take the value `1` on `W(2)`. The character `φ₁,β‚ˆβ€³` is complex conjugate to `φ₁,₁₆` and `φ₁,β‚ˆ'` is complex conjugate to `φ₁,β‚„'`. The characters `φ₁,₁₂'` and `φ₁,β‚β‚ˆ'` take the value `΢₃` on `W(2)`. The character `φ₁,₁₄″` is complex conjugate to `φ₁,β‚‚β‚‚` and `φ₁,₁₄'` is complex conjugate to `φ₁,₁₀'`. The character `Ο†β‚‚,₃'` takes the value `-΢₃` on `W(2)` and `Ο†β‚‚,₁₃'` takes the value `-1` on `W(2)`. The characters `Ο†β‚‚,₁₁″`, `Ο†β‚‚,β‚…β€³`, `Ο†β‚‚,₇‴` and `Ο†β‚‚,₁` are Galois conjugate, as well as the characters `Ο†β‚‚,₇'`, `Ο†β‚‚,₁₃'`, `Ο†β‚‚,₁₁'` and `Ο†β‚‚,β‚…'`. The character `Ο†β‚‚,₉'` is complex conjugate to `Ο†β‚‚,₁₅` and `Ο†β‚‚,₉‴` is complex conjugate to `Ο†β‚‚,₃'`. Finally, for the remaining groups `G₆, Gβ‚ˆ` to `G₁₁, G₁₃` to `G₂₁`, `Gβ‚‚β‚…`, `G₂₆`, `G₃₂` and `G₃₃` there are only pairs of characters with same value `(d,b)`. We give labels uniformly to these characters by applying in order the following rules : - If the two characters have different fake degrees, label `Ο†_{d,b}'` the one whose fake degree is minimal for the lexicographic order of polynomials (starting with the highest term). - For the not yet labeled pairs, if only one of the two characters has the property that in its Galois orbit at least one character is distinguished by its `(d,b)`-invariant, label it `Ο†_{d,b}'`. - For the not yet labeled pairs, if the minimum of the `(d,b)`-value (for the lexicographic order `(d,b)`) in the Galois orbits of the two character is different, label `Ο†_{d,b}'` the character with the minimal minimum. - We define now a new invariant for characters: consider all the pairs of irreducible characters `Ο‡` and `ψ` uniquely determined by their `(d,b)`-invariant such that `Ο†` occurs with non-zero multiplicity `m` in `Ο‡βŠ—Οˆ`. We define `t(Ο†)` to be the minimal (for lexicographic order) possible list `(d(Ο‡),b(Ο‡),d(ψ),b(ψ),m)`. For the not yet labeled pairs, if the t-invariants are different, label `Ο†_{d,b}'` the character with the minimal `t`-invariant. After applying the last rule all the pairs will be labelled for the considered groups. The labelling obtained is compatible for `Gβ‚‚β‚…`, `G₂₆`, `G₃₂` and `G₃₃` with that of [Malle2000](biblio.htm#Mal00) and for `Gβ‚ˆ` with that described in [MalleRouquier2003](biblio.htm#MR03). We should emphasize that for all groups with a few exceptions, the parameters for characters do not depend on any non-canonical choice. The exceptions are `G(de,e,n)` with `e>1`, and `Gβ‚…`, `G₇`, `G₂₇`, `Gβ‚‚β‚ˆ`, `G₂₉` and `G₃₄`, groups which admit outer automorphisms preserving the set of reflections, so choices of a particular value on a particular generator must be made for characters which are not invariant by these automorphisms. Labels for the classes. For the exceptional complex reflection groups, the labels for the classes represent the decomposition of a representative of the class as a product of generators, with the additional conventions that 'z' represents the generator of the center and for well-generated groups 'c' represents a Coxeter element (a product of the generators which is a regular element for the highest reflection degree). """ module Chars using ..Chevie export charinfo, classinfo, fakedegree, fakedegrees, CharTable, representation, WGraphToRepresentation, DualWGraph, WGraph2Representation, charnames, representations, InductionTable, induction_table, classes, j_induction_table, J_induction_table, decompose, on_chars, detPerm, conjPerm, classnames, decomposition_matrix, eigen, schur_functor, charnumbers """ `schur_functor(mat,l)` `mat` should be a square matrix and `l` a partition. The result is the Schur functor of the matrix `mat` corresponding to partition `l`; for example, if `l==[n]` it returns the n-th symmetric power and if `l==[1,1,1]` it returns the 3rd exterior power. The current algorithm (from Littlewood) is rather inefficient so it is quite slow for partitions of n where `n>6`. ```julia-repl julia> m=cartan(:A,3) 3Γ—3 Matrix{Int64}: 2 -1 0 -1 2 -1 0 -1 2 julia> schur_functor(m,[2,2]) 6Γ—6 Matrix{Rational{Int64}}: 9 -6 4 3//2 -2 1 -12 16 -16 -4 8 -4 4 -8 16 2 -8 4 12 -16 16 10 -16 12 -4 8 -16 -4 16 -12 1 -2 4 3//2 -6 9 ``` """ function schur_functor(A,la) n=sum(la) S=coxsym(n) r=representation(S,findfirst(==(la),partitions(n))) rep=function(x)x=word(S,x) isempty(x) ? r[1]^0 : prod(r[x]) end f=j->prod(factorial,last.(tally(j))) basis=multisets(axes(A,1),n) M=sum(x->kron(rep(x),toM(map(function(i)i=invpermute(i,x) return map(j->prod(k->A[i[k],j[k]],1:n),basis)//f(i) end,basis))),elements(S)) # Print(Length(M),"=>"); M=M[filter(i->!all(iszero,M[i,:]),axes(M,1)),:] M=M[:,filter(i->!all(iszero,M[:,i]),axes(M,2))] m=sort.(collectby(i->M[:,i],axes(M,2))) m=sort(m) M=M[:,first.(m)] improve_type(toM(map(x->sum(M[x,:],dims=1)[1,:],m))) end """ `fakedegree(W, Ο†, q=Pol())` returns the fake degree (see [`fakedegrees`](@ref) for a definition) of the character of parameter Ο† (see `charinfo(W).charparams`) of the reflection group `W`, evaluated at `q` . ```julia-repl julia> fakedegree(coxgroup(:A,2),[[2,1]],Pol(:q)) Pol{Cyc{Int64}}: qΒ²+q ``` """ function fakedegree(W,p,q=Pol()) typ=refltype(W) if isempty(typ) return one(q) end # prod(map((t,p)->fakedegree(t,p,q),typ,p)) prod(fakedegree.(typ,p,q)) end function fakedegree(t::TypeIrred,p,q=Pol()) if haskey(t,:scalar) q=prod(s->q*conj(s),t.scalar) elseif haskey(t,:orbit) q=q^length(t.orbit) end getchev(t,:FakeDegree,p,q) end """ `fakedegrees(W, q=Pol())` returns a list holding the fake degrees of the reflection group `W` on the vector space `V`, evaluated at `q`. These are the graded multiplicities of the irreducible characters of `W` in the quotient `SV/I` where `SV` is the symmetric algebra of `V` and `I` is the ideal generated by the homogeneous invariants of positive degree in `SV`. The ordering of the result corresponds to the ordering of the characters in `charinfo(W)`. ```julia-repl julia> fakedegrees(coxgroup(:A,2),Pol(:q)) 3-element Vector{Pol{Int64}}: qΒ³ qΒ²+q 1 ``` """ function fakedegrees(W,q=Pol();recompute=false) if !recompute res=get!(W,:fakedegrees)do improve_type(map(p->fakedegree(W,p,Pol()),charinfo(W).charparams)) end if !any(isnothing,res) && !all(iszero,res) if q==Pol() return res else return map(x->x(q),res) end end end # recompute from general principles InfoChevie("# recomputing fakedegrees for ",W,"\n") qq=Pol() P=generic_order(W,qq) P=shift(P,-valuation(P)) ct=CharTable(W) P=ct.irr*map(enumerate(ct.centralizers))do (i,c) exactdiv(P, improve_type(prod(l->(qq*conj(l)-1),refleigen(W,i);init=one(qq))))//c end if q!=qq P=map(x->x(q),P) end P=improve_type(P) if W isa Spets P.*=(-1)^rank(W)*generic_sign(W) end P end @GapObj struct CharInfo end charnumbers(d::Dict)=d[:charNumbers] function charinfo(t::TypeIrred) c=CharInfo(copy(getchev(t,:CharInfo))) c.positionId=c.extRefl[1] c.positionDet=c.extRefl[end] if !haskey(c,:charnames) error("charnames(",t,") missing") end if !haskey(c,:b) c.b=getchev(t,:LowestPowerFakeDegrees) end if !haskey(c,:B) c.B=getchev(t,:HighestPowerFakeDegrees) end if !haskey(c,:a) c.a=getchev(t,:LowestPowerGenericDegrees) end if !haskey(c,:A) c.A=getchev(t,:HighestPowerGenericDegrees) end if isnothing(c.a) uc=getchev(t,:UnipotentCharacters) if !isnothing(uc) && uc!=false # printstyled(rio(),"using UniChars\n";color=:red) if haskey(uc,:almostHarishChandra) c.a=uc[:a][charnumbers(uc[:almostHarishChandra][1])] c.A=uc[:A][charnumbers(uc[:almostHarishChandra][1])] else c.a=uc[:a][charnumbers(uc[:harishChandra][1])] c.A=uc[:A][charnumbers(uc[:harishChandra][1])] end elseif !haskey(t,:orbit) para=ordergens(t) if !isnothing(para) para=map(x->vcat([Mvp(:x)],map(j->E(x,j),1:x-1)),para) s=map(p->getchev(t,:SchurElement,p,para,Any[]),c.charparams) c.a=-valuation.(s) c.a.+=valuation(s[c.positionId]) c.A=-degree.(s) c.A.+=degree(s[c.positionId]) end end end for f in [:a,:A,:b,:B] if haskey(c,f) if isnothing(c[f]) || c[f]==false delete!(c.prop,f) else c.prop[f]=improve_type(c[f]) end end end if haskey(t,:orbit) if !haskey(c,:charRestrictions) c.charRestrictions=eachindex(c.charparams) c.nrGroupClasses=length(c.charparams) # assume orbit twist trivial end for f in [:a,:A,:b,:B] if haskey(c,f) c.prop[f]*=length(t.orbit) end end end c end cartfields(p,f)=if length(p)==1 map(x->[x],getindex(p[1],f)) else cartesian(getindex.(p,f)...) end """ `charinfo(W)` returns information about the irreducible characters of the finite reflection group or Spets `W`. The result is an object with various entries describing properties of the irreducible characters of `W`. This object prints at the Repl or in Pluto or Jupyter as a table synthesizing most information. A field not in the table is `.charparams`: it contains parameters for the irreducible characters. A parameter is a list with one item for each irreducible component of `W` (as given by `refltype`). For an irreducible `W` see the helpstring for `Chars` for what are the parameters. ```julia-repl julia> charinfo(coxgroup(:G,2)).charparams 6-element Vector{Vector{Vector{Int64}}}: [[1, 0]] [[1, 6]] [[1, 3, 1]] [[1, 3, 2]] [[2, 1]] [[2, 2]] ``` ```julia-repl julia> charinfo(coxgroup(:G,2)) β”Œβ”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚n0β”‚ name ext b B a A spaltenstein lusztig symbolβ”‚ β”œβ”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚1 β”‚ Ο†β‚β€šβ‚€ Id 0 0 0 0 1 1 (0,0,0,0,0,2)β”‚ β”‚2 β”‚ Ο†β‚β€šβ‚† det 6 6 6 6 Ξ΅ Ξ΅ (01,01,01,01,01,12)β”‚ β”‚3 β”‚Ο†β€²β‚β€šβ‚ƒ 3 3 1 5 Ξ΅β‚— Ξ΅β€² (0,0,1+)β”‚ β”‚4 β”‚Ο†β€³β‚β€šβ‚ƒ 3 3 1 5 Ξ΅_c Ξ΅β€³ (0,0,1-)β”‚ β”‚5 β”‚ Ο†β‚‚β€šβ‚ Λ¹ 1 5 1 5 ΞΈβ€² ΞΈβ€² (0,0,0,0,1,1)β”‚ β”‚6 β”‚ Ο†β‚‚β€šβ‚‚ 2 4 1 5 ΞΈβ€³ ΞΈβ€³ (0,0,0,1,0,1)β”‚ β””β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` In the table printed at the Repl, the columns reflect various fields of `charinfo`. The column `name` reflects the field `.charnames`, a name computed from `.charparams`. This is the same as `charnames(io,W)` where here `io` being the Repl has the property `:limit` true. The column `ext` shows the exterior powers of the reflection representation. It corresponds to the field `.extrefl` which is present only if `W` is irreducible. Otherwise, only two items are shown in the column: `Id` corresponds to the field `.positionId` and shows the trivial character. `det` corresponds to the field `.positionDet` and shows the determinant character (for Coxeter groups the sign character). When `W` is irreducible, the characters marked `Λⁱ` are the `i`-th exterior power of the reflection representation. They are irreducible by a theorem of Steinberg. The column `b` shows the field `.b` listing for each character the valuation of the fake degree, and the column `B` shows the field `.B`, the degree of the fake degree. The columns `a` and `A` only appear for Spetsial groups. They correspond then to the fields `.a` and `.A`, and contain respectively the valuation and the degree of the generic degree of the character (in the one-parameter Hecke algebra `hecke(W,Pol())` for `W`). For irreducible groups, the table shows sometimes additional columns, corresponding to a field of the same name. for `Fβ‚„`, the column `kondo` gives the labeling of the characters given by Kondo, also used in [Lusztig1985, (4.10)](biblio.htm#Lus85). for `E₆, E₇, Eβ‚ˆ` the column `frame` gives the labeling of the characters given by Frame, also used in [Lusztig1985, (4.11), (4.12), and (4.13)](biblio.htm#Lus85). for `Gβ‚‚` the column `spaltenstein` gives the labeling of the characters given by Spaltenstein. for `G(de,e,2)` even `e` and `d>1`, the column `malle` gives the parameters for the characters used in [Malle1996](biblio.htm#Mal96). If `W` is irreducible spetsial and imprimitive, the column 'symbol` (corresponding to the field `.charSymbols`) shows the symbol attached to the corresponding unipotent caracter. If `W isa Spets`, the column `restr.` (corresponding to the field `.charRestrictions`) gives the number of the corresponding character of `Group(W)`. Finally, the field `.hgal` contains the permutation of the characters resulting from a Galois action on the characters of `H=hecke(W,Pol()^e)` where `e` is the order of the center of `W`. `H` splits by taking `v` an `e`-th root of `Pol()`, and `.hgal` records the permutation effected by the Galois action `v->E(e)*v` (`charinfo` does not have the key `:hgal` if this permutation is trivial). `.hgal*conj`, where `conj` is the complex conjugaison, is the Opdam involution. ```julia-repl julia> charinfo(complex_reflection_group(24)) β”Œβ”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚n0β”‚ name ext b B a Aβ”‚ β”œβ”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚1 β”‚ Ο†β‚β€šβ‚€ Id 0 0 0 0β”‚ β”‚2 β”‚Ο†β‚β€šβ‚‚β‚ det 21 21 21 21β”‚ β”‚3 β”‚ Ο†β‚ƒβ€šβ‚ˆ 8 18 8 20β”‚ β”‚4 β”‚ Ο†β‚ƒβ€šβ‚ Λ¹ 1 11 1 13β”‚ β”‚5 β”‚Ο†β‚ƒβ€šβ‚β‚€ Λ² 10 20 8 20β”‚ β”‚6 β”‚ Ο†β‚ƒβ€šβ‚ƒ 3 13 1 13β”‚ β”‚7 β”‚ Ο†β‚†β€šβ‚‚ 2 12 1 13β”‚ β”‚8 β”‚ Ο†β‚†β€šβ‚‰ 9 19 8 20β”‚ β”‚9 β”‚ Ο†β‚‡β€šβ‚† 6 18 6 18β”‚ β”‚10β”‚ Ο†β‚‡β€šβ‚ƒ 3 15 3 15β”‚ β”‚11β”‚ Ο†β‚ˆβ€šβ‚„ 4 16 4 17β”‚ β”‚12β”‚ Ο†β‚ˆβ€šβ‚… 5 17 4 17β”‚ β””β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ hgal=(11,12) ``` """ function charinfo(W) get!(W,:charinfo)do p=charinfo.(refltype(W)) if isempty(p) res=CharInfo(Dict(:a=>[0],:A=>[0],:b=>[0],:B=>[0],:positionId=>1, :positionDet=>1,:charnames=>["Id"],:extRefl=>[1],:charparams=>[[]])) if W isa Spets res.charRestrictions=[1] res.nrGroupClasses=1 end return res end if length(p)==1 res=p[1] else res=CharInfo(Dict{Symbol, Any}()) end res.charparams=cartfields(p,:charparams) if W isa Spets gt=map(x->sort(x.indices),refltype(Group(W))) t=refltype(W) n=fill(0,length(gt)) for i in eachindex(t), f in t[i].orbit n[findfirst(==(sort(f.indices)),gt)]=p[i].nrGroupClasses end res.charRestrictions= map(cartesian(getindex.(p,:charRestrictions)...))do y m=fill(0,length(gt)) for i in eachindex(t), f in t[i].orbit m[findfirst(==(sort(f.indices)),gt)]=y[i] end cart2lin(n,m) end res.nrGroupClasses=prod(i->p[i].nrGroupClasses^length(t[i].orbit), eachindex(t)) end if length(p)>1 res.charnames=join.(cartfields(p,:charnames),",") end for f in [:positionId, :positionDet] if all(d->haskey(d,f),p) res.prop[f]=cart2lin(map(x->length(x.charparams),p),getindex.(p,f)) end end for f in [:b, :B, :a, :A] if all(d->haskey(d,f),p) res.prop[f]=improve_type(sum.(cartfields(p,f))) end end if !haskey(res,:b) || !haskey(res,:B) P=fakedegrees(W;recompute=true) res.b=valuation.(P) res.B=degree.(P) end if any(x->haskey(x,:hgal),p) res.hgal=map(x->haskey(x,:hgal) ? x.hgal : Perm(), p) gt=cartesian(map(x->1:length(x.charparams), p)...) res.hgal=Perm(gt, map(t->map((x,i)->x^i,t,res.hgal),gt)) end res end::CharInfo end charinfo(W::Weyl.FC)=charinfo(W.G) function Base.show(io::IO, ::MIME"text/html", ci::CharInfo) show(IOContext(io,:TeX=>true), "text/plain",ci) end function Base.show(io::IO,t::CharInfo) print(io,"CharInfo(",t.prop,")") end function Base.show(io::IO, ::MIME"text/plain", ci::CharInfo) if !hasdecor(io) print(io,"CharInfo(",ci.prop,")") return end n=length(ci.charnames) t=fromTeX.(Ref(io),ci.charnames);cl=String["name"] ext=fill("",n) if haskey(ci,:extRefl) ext[ci.extRefl[[1,end]]]=["Id","det"] for (i,j) in pairs(ci.extRefl[2:end-1]) ext[j]=fromTeX(io,"\\Lambda^$i") end else ext[ci.positionId]="Id";ext[ci.positionDet]="det" end t=hcat(t,ext); push!(cl,"ext") for key in [:b,:B,:a,:A,:kondo,:spaltenstein,:frame,:malle,:lusztig, :carter] if haskey(ci,key) && ci[key]!=false t=hcat(t,fromTeX.(Ref(io),string.(ci[key]))) push!(cl,string(key)) end end if haskey(ci,:charRestrictions) t=hcat(t,string.(ci.charRestrictions)) push!(cl,"restr.") end if haskey(ci,:charSymbols) t=hcat(t,stringsymbol.(Ref(io),ci.charSymbols));push!(cl,"symbol") end showtable(io,string.(t);row_labels=string.(1:n),col_labels=cl,rows_label="n0") if haskey(ci,:hgal) println(io,"hgal=",ci.hgal) end end """ `detPerm(W)` return the permutation of the characters of the reflection group `W` which is effected when tensoring by the determinant character (for Coxeter groups this is the sign character). ```julia-repl julia> W=coxgroup(:D,4) Dβ‚„ julia> detPerm(W) (1,8)(2,9)(3,11)(4,13)(7,12) ``` """ function detPerm(W) get!(W,:detPerm)do t=CharTable(W).irr Perm(t,t.*transpose(t[charinfo(W).positionDet,:]);dims=1) end::Perm{Perms.Idef} end """ `conjPerm(W)` return the permutation of the characters of the group `W` which is effected when taking the complex conjugate of the character table. ```julia-repl julia> W=complex_reflection_group(4) Gβ‚„ julia> conjPerm(W) (2,3)(5,6) ``` """ function conjPerm(W) get!(W,:conjPerm)do t=CharTable(W).irr Perm(t,conj.(t);dims=1) end::Perm{Perms.Idef} end @GapObj struct ClassInfo end function classinfo(t::TypeIrred) cl=deepcopy(convert(Dict{Symbol,Any},getchev(t,:ClassInfo))) if haskey(t,:orbit) l=length(t.orbit) t=t.orbit[1] if l>1 && haskey(cl,:classes) cl[:classes].*=prod(degrees(t))^(l-1) end end inds=t.indices cl[:classtext]=map(x->inds[x],cl[:classtext]) if haskey(cl,:classes) cl[:classes]=Int.(cl[:classes]) end if haskey(cl,:centralizers) cl[:centralizers]=Int.(cl[:centralizers]) end cl[:classnames]=String.(cl[:classnames]) if !haskey(cl,:classparams) cl[:classparams]=cl[:classtext] end ClassInfo(cl) end Groups.nconjugacy_classes(t::TypeIrred)=getchev(t,:NrConjugacyClasses) """ `classinfo(W)` returns information about the conjugacy classes of the finite reflection group or Spets `W`. The result is an object with various entries describing properties of the conjugacy classes of `W`. This object prints at the Repl or in Pluto or Jupyter as a table synthesizing most information. A field not in the table is `.classparams`, containing parameters for the conjugacy classes. Each parameter is a vector which has one item for each irreducible component of `W`. For what are the parameters for an irreducible `W`, see the helpstring of `Chars`. ```julia-repl julia> classinfo(coxgroup(:A,2)) β”Œβ”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚n0β”‚name length order wordβ”‚ β”œβ”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚1 β”‚ 111 1 1 .β”‚ β”‚2 β”‚ 21 3 2 1β”‚ β”‚3 β”‚ 3 2 3 12β”‚ β””β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` The table contains the columns: - `name`, corresponding to the field `.classnames`: strings describing the conjugacy classes, made out of the information in `:classparams`. - `length`, corresponding to the field `.classes`, is the number of elements in the conjugacy class. - `order`, corresponding to the field `.orders`, is the order of elements in the conjugacy class. - `word`, corresponding to the field `.classtext`, describes a word in the generators for the representatives of each conjugacy class. Each word is a list of integers where the generator `W(i)` is represented by the integer `i`. For finite Coxeter groups, it is the same as `word.(Ref(W),classreps(W))`, and each such representative is of minimal length in its conjugacy class and is a "very good" element in the sense of [GeckMichel1997](biblio.htm#GM97). """ function classinfo(W) get!(W,:classinfo)do tmp=map(classinfo,refltype(W)) if isempty(tmp) return ClassInfo(Dict(:classtext=>[Int[]],:classnames=>[""], :classparams=>[Int[]],:orders=>[1],:classes=>[1])) end if any(isnothing, tmp) return nothing end if length(tmp)==1 res=copy(tmp[1].prop) else res=Dict{Symbol, Any}() end res[:classtext]=map(x->reduce(vcat,x),cartfields(tmp,:classtext)) res[:classnames]=map(x->join(x,","),cartfields(tmp,:classnames)) if all(haskey.(tmp,:classparams)) res[:classparams]=cartfields(tmp,:classparams) end if all(haskey.(tmp,:orders)) res[:orders]=map(lcm, cartfields(tmp,:orders)) end if all(haskey.(tmp,:classes)) res[:classes]=map(prod, cartfields(tmp,:classes)) end ClassInfo(res) end::ClassInfo end @forward Weyl.FC.G classinfo, charinfo function Base.show(io::IO, ::MIME"text/html", ci::ClassInfo) show(IOContext(io,:TeX=>true), "text/plain",ci) end function Base.show(io::IO,t::ClassInfo) print(io,"ClassInfo(",t.prop,")") end function limitto(s,sz) if length(s)<sz || sz<=1 return s end s[1:prevind(s,sz-1)]*"…" end function showperiodic(io::IO,v::Vector{Int}) if isempty(v) return "." end i=prev=1 res="" while i<=length(v) for p in 2:div(length(v)-i+1,2) # @show i,p if (@view v[i:i+p-1])!=(@view v[i+p:i+2p-1]) continue end c=2 while i+(c+1)*p-1<=length(v) && (@view v[i:i+p-1])==(@view v[i+c*p:i+(c+1)*p-1]) c+=1 end if c==2 && p==2 continue end res*=string(joindigits(@view v[prev:i-1]),"(",joindigits(@view v[i:i+p-1]),")",stringexp(io,c)) i+=c*p-1;prev=i+1 # @show i,c,p,res,prev break end i+=1 end res*=joindigits(@view v[prev:end]) end function Base.show(io::IO, ::MIME"text/plain", ci::ClassInfo) if !hasdecor(io) print(io,"ClassInfo(",ci.prop,")") return end n=length(ci.classnames) sz=length(string(n))+1 t=Any[fromTeX.(Ref(io),ci.classnames)];cl=String["name"] sz+=max(maximum(length.(t[end])),4)+1 for (key,tkey) in [(:classes,:length),(:orders,:order)] if haskey(ci,key) && ci[key]!=false push!(t,string.(ci[key])) push!(cl,string(tkey)) sz+=max(maximum(length.(t[end])),length(cl[end]))+1 end end if haskey(ci,:refleigen) m=toM(ci.refleigen) for i in axes(m,2) push!(t,xrepr.(io,m[:,i])) push!(cl,i==size(m,2) ? "eig" : "") sz+=max(maximum(length.(t[end])),length(cl[end]))+1 end end push!(t,limitto.(showperiodic.(io,ci.classtext),displaysize(io)[2]-sz-2)) push!(cl,"word") showtable(io,permutedims(string.(toM(t)));row_labels=string.(1:n),col_labels=cl,rows_label="n0") end const Hastype=Union{PermRootGroup,Spets,CoxSym,CoxHyp} function Groups.conjugacy_classes(W::TW)where TW<:Hastype get!(W,:classes) do c=classinfo(W) map(1:length(c.classtext))do i C=ConjugacyClass(W,W(c.classtext[i]...), Dict{Symbol,Any}(:length=>c.classes[i], :word=>c.classtext[i], :name=>c.classnames[i], :param=>c.classparams[i])) if haskey(c,:orders) C.order=c.orders[i] end if haskey(c,:malle) C.malle=c.malle[i] end if haskey(c,:centralizers) C.centralizers=c.centralizers[i] end if haskey(c,:indexclasses) C.index=c.indexclasses[i] end C end end end function Base.show(io::IO,C::ConjugacyClass{T,TW})where{T,TW<:Hastype} if get(io,:limit,false) || get(io,:TeX,false) print(io,"conjugacy_class(",C.G,",",fromTeX(io,C.name),")") else print(io,"conjugacy_class(",C.G,",",C.representative,")") end end function Groups.position_class(W::Hastype,w;verbose=false) l=PermGroups.positions_class(W,w) if length(l)==1 return only(l) elseif verbose println("ambiguity: ",l) end # p=eigmat(reflrep(W,w)) # l=filter(x->eigen(conjugacy_classes(W)[x])==p,l) # if length(l)==1 return only(l) end p=findfirst(c->w in c,conjugacy_classes(W)[l]) if isnothing(p) @show w error() end l[p] end function Perms.reflength(C::ConjugacyClass{T,TW})where{T,TW<:Hastype} getp(eigen,C,:reflength) end Base.length(C::ConjugacyClass{T,TW}) where{T,TW<:Hastype}=C.length Groups.word(C::ConjugacyClass{T,TW}) where{T,TW<:Hastype}=C.word function eigen(C::ConjugacyClass{T,TW})where{T,TW<:Hastype} get!(C,:eigen)do t=refltype(C.G) if !any(x->haskey(x,:orbit) && (length(x.orbit)>1 || order(x.twist)>1 || (haskey(x,:scalar) && !all(isone,x.scalar))),t) l=refleigen(C.G) for (i,C1) in enumerate(conjugacy_classes(C.G)) C1.eigen=l[i] C1.reflength=count(!isone,C1.eigen) end else C.eigen=eigmat(reflrep(C.G,C.representative)) # eigmat is sorted C.reflength=count(!isone,C.eigen) end C.eigen end::Vector{Root1} end #--------------- CharTables ----------------------------------------- @GapObj struct CharTable{T} irr::Matrix{T} charnames::Vector{String} classnames::Vector{String} centralizers::Vector{Int} order::Int end @doc """ CharTable is a structure to hold character tables of groups and Hecke algebras """ CharTable function Base.show(io::IO, ::MIME"text/html", ct::CharTable) show(IOContext(io,:TeX=>true), "text/plain",ct) end function Base.show(io::IO,t::CharTable) if hasdecor(io) || !haskey(t,:repr) printTeX(io,"CharTable(\$",haskey(t,:name) ? t.name : "?","\$)") else print(io,t.repr) end end function Base.show(io::IO, ::MIME"text/plain", ct::CharTable) println(io,ct) showtable(io,ct.irr,row_labels=ct.charnames,col_labels=ct.classnames,dotzero=true) end function CharTable(t::TypeIrred;opt...) ct=getchev(t,:CharTable) irr=improve_type(toM(ct[:irreducibles])) CharTable(irr,charnames(t;opt...,TeX=true),classnames(t;opt...,TeX=true), improve_type(ct[:centralizers]),ct[:size], Dict{Symbol,Any}(:name=>xrepr(t;TeX=true))) end function Base.prod(ctt::Vector{<:CharTable}) if isempty(ctt) return CharTable(hcat(1),["Id"],["."],[1],1,Dict{Symbol,Any}(:name=>".")) elseif length(ctt)==1 return ctt[1] end charnames=join.(cartesian(getfield.(ctt,:charnames)...),",") classnames=join.(cartesian(getfield.(ctt,:classnames)...),",") centralizers=prod.(cartesian(getfield.(ctt,:centralizers)...)) order=prod(getfield.(ctt,:order)) if length(ctt)==1 irr=ctt[1].irr else irr=kron(getfield.(ctt,:irr)...) end CharTable(irr,charnames,classnames,centralizers,order,Dict{Symbol,Any}(:name=>"x")) end """ `CharTable(WF::Spets)` This function returns the character table of the reflection coset `WF`. We call *characters* of the coset `WF=W.Ο•` of the group `W` the restriction to `W.Ο•` of a set containing one extension of each `Ο•`-invariant character of W to the semidirect product of W with the cyclic group generated by `Ο•` (for Coxeter cosets we choose, following Lusztig, in each case one extension, called the preferred extension.) ```julia-repl julia> W=spets(coxgroup(:D,4),Perm(1,2,4)) Β³Dβ‚„ julia> CharTable(W) CharTable(Β³Dβ‚„) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚C₃ AΜƒβ‚‚ C₃+A₁ AΜƒβ‚‚+A₁ Fβ‚„ AΜƒβ‚‚+Aβ‚‚ Fβ‚„(a₁)β”‚ β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚.4 β”‚ 1 1 1 1 1 1 1β”‚ β”‚.1111β”‚-1 1 1 -1 1 1 1β”‚ β”‚.22 β”‚ . 2 2 . -1 -1 -1β”‚ β”‚11.2 β”‚ . . . . -1 3 3β”‚ β”‚1.3 β”‚ 1 1 -1 -1 . -2 2β”‚ β”‚1.111β”‚-1 1 -1 1 . -2 2β”‚ β”‚1.21 β”‚ . 2 -2 . . 2 -2β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` """ function CharTable(W::Union{Hastype,FiniteCoxeterGroup};opt...) get!(W,:chartable)do t=refltype(W) ct=isempty(t) ? prod(CharTable[]) : prod(CharTable.(t;opt...)) ct.name=xrepr(W;TeX=true) ct.repr=string("CharTable(",W,")") ct end::CharTable end function CharTable(W::Group) get!(W,:chartable)do error("to have CharTable(s) for arbitrary PermGroup(s) do 'using GAP'") end end function classes(ct::CharTable) get!(ct,:classes)do div.(ct.order,ct.centralizers) end::Vector{Int} end function scalarproduct(ct::CharTable,c1::AbstractVector,c2::AbstractVector;exact=true) v=c2'*(c1.*classes(ct)) exact ? exactdiv.(v,ct.order) : improve_type(v//ct.order) end """ `decompose(ct::CharTable,c::Vector;exact=true)` decompose class function `c` (given by its values on conjugacy classes) on irreducible characters as given by `CharTable` `ct`. By default `c` is expected to be a virtual character so the result will be an integer vector. If `c` is not a virtual character give the keyword `exact=false` to get a correct result. """ function decompose(ct::CharTable,c::AbstractVector;exact=true) v=conj(ct.irr)*Diagonal(classes(ct))*c exact ? exactdiv.(v,ct.order) : improve_type(v//ct.order) end """ `on_chars(G,aut)` `aut` is an automorphism of the group `G` (for a permutation group, this could be given as a permutation normalizing `G`). The result is the permutation of the indices of the irreducible characters induced by `aut`. ```julia-repl julia> WF=rootdatum("3D4") Β³Dβ‚„ julia> on_chars(Group(WF),WF.phi) (1,2,7)(8,9,12) ``` """ function on_chars(W,aut) ct=CharTable(W).irr inv(Perm(ct,invpermute(ct,on_classes(W, aut),dims=2),dims=1)) end """ `representation(W,i)` returns, for the `i`-th irreducible representation of the complex reflection group or Spets `W`, a list of matrices images of the generating reflections of `W` in a model of the representation (for Spets, the result is a `NamedTuple` with fields `gens`, a representation of `Group(W)`, and `F`, the matrix for `W.phi` in the representation). This function is based on the classification, and is not yet fully implemented for `G₃₄`; 78 representations are missing out of 169, that is, representations of dimension β‰₯140, except half of those of dimensions 315, 420 and 840. ```julia-repl julia> representation(complex_reflection_group(24),3) 3-element Vector{Matrix{Cyc{Int64}}}: [1 0 0; -1 -1 0; -1 0 -1] [-1 0 -1; 0 -1 (1-√-7)/2; 0 0 1] [-1 -1 0; 0 1 0; 0 (1+√-7)/2 -1] ``` """ function representation(W::Union{Hastype,FiniteCoxeterGroup},i::Integer) dims=getchev(W,:NrConjugacyClasses) if isempty(dims) return Matrix{Int}[] end tt=refltype(W) mm=map((t,j)->getchev(t,:Representation,j),tt,lin2cart(dims,i)) if any(isnothing,mm) error("no representation for ",W) end if W isa Spets FF=map(x->x[:F],mm) if !(FF[1] isa AbstractMatrix) FF=map(toM,FF) end F=length(FF)==1 ? FF[1] : kron(FF...) mm=map(x->x[:gens],mm) end if !(mm[1][1] isa AbstractMatrix) mm=map(x->toM.(x),mm) end if !all(m->m isa Vector{<:SparseMatrixCSC},mm) mm=improve_type.(mm*1) end n=length(tt) if n==1 reps=mm[1] else reps=vcat(map(1:n) do i map(mm[i]) do m kron(map(j->j==i ? m : mm[j][1]^0,1:n)...) end end...) end if !(W isa Spets) return reps end (gens=reps,F=F) end """ `representations(W)` returns the list of representations of the complex reflection group or Spets `W` (see `representation`). ```julia-repl julia> representations(coxgroup(:B,2)) 5-element Vector{Vector{Matrix{Int64}}}: [[1;;], [-1;;]] [[1 0; -1 -1], [1 2; 0 -1]] [[-1;;], [-1;;]] [[1;;], [1;;]] [[-1;;], [1;;]] ``` """ representations(W::Union{Hastype,FiniteCoxeterGroup})=representation.(Ref(W),1:nconjugacy_classes(W)) using SparseArrays """ `WGraphToRepresentation(coxrank::Integer,graph,v)` We store some representations of one-parameter Iwahori-Hecke algebras as `W`-graphs. For a Coxeter system `(W,S)`, a `W`-graph is defined by a set of vertices `C` with a function `I` which attaches to `x∈ C` a subset `I(x)βŠ‚ S`, and *edge labels* which to `(x,y)∈ C^2` attach `ΞΌ(x,y)∈ K` where `K` is the field of definition of `W`; this defines a representation of the Hecke algebra with parameters `v` and `-v⁻¹` on a space with basis ``{e_y}_{y∈ C}`` by: ``Tβ‚›(e_y)=-e_y`` if `s∈ I(y)` and otherwise ``Tβ‚›(e_y)=v^2 e_y+βˆ‘_{x∣s∈ I(x)} vΞΌ(x,y)eβ‚“``. The `W`-graphs are stored in a compact format to save space. They are represented as a pair. - The first element is a list describing `C`. Its elements are either a vector `I(x)` of indices in `eachindex(S)`, or an integer `n` specifying to repeat the previous element `n` more times. - The second element is a list which specifies `ΞΌ`. We first describe the `ΞΌ`-list for symmetric `W`-graphs (when `ΞΌ(x,y)=ΞΌ(y,x)`). There is one element of the `ΞΌ`-list for each non-zero value `m` taken by `ΞΌ`, which consists of a pair whose first element is `m` and whose second element is a list of lists; if `l` is one of these lists each pair `[l[1],l[i]]` represents an edge (`x=l[1]`,`y=l[i]`) such that `ΞΌ(x,y)=ΞΌ(y,x)=m`. For non-symmetric `W`-graphs, the first element of each pair in the `ΞΌ`-list is a pair `[m1,m2]` and each edge `[x,y]` obtained from the lists in the second element has to be interpreted as `ΞΌ(x,y)=m1` and `ΞΌ(y,x)=m2`. ```julia-repl julia> W=coxgroup(:H,3) H₃ julia> g=Wgraph(W,3) 2-element Vector{Vector{Vector{Any}}}: [[2], [1, 2], [1, 3], [1, 3], [2, 3]] [[-1, [[1, 3], [2, 4], [3, 5], [4, 5]]]] julia> WGraphToRepresentation(3,g,Pol(:x)) 3-element Vector{Matrix{Pol{Int64}}}: [xΒ² 0 … 0 0; 0 -1 … 0 0; … ; 0 0 … -1 -x; 0 0 … 0 xΒ²] [-1 0 … 0 0; 0 -1 … -x 0; … ; 0 0 … xΒ² 0; 0 0 … -x -1] [xΒ² 0 … 0 0; 0 xΒ² … 0 0; … ; 0 -x … -1 0; 0 0 … 0 -1] ``` """ function WGraphToRepresentation(rk::Integer,gr::Vector,v) # Jean Michel june/december 2003 from code/data of Geck, Marin, Alvis, # Naruse, Howlett,Yin) I=Vector{Int}[] for S in gr[1] if S isa Integer append!(I,fill(I[end],S)) else push!(I,S) end end dim=length(I) T=Int function prom(a) if a isa Vector for u in a prom(u) end else T=promote_type(T,typeof(a)) end end prom(gr[2]) v=improve_type(v) T=promote_type(T,typeof(v)) S=map(i->spzeros(T,dim,dim),1:rk) for j in 1:dim for i in 1:rk if i in I[j] S[i][j,j]=-one(v) else S[i][j,j]=v^2 end end end for i in gr[2] if i[1] isa Vector mu=i[1] else mu=[i[1],i[1]] end for l in i[2] x=l[1] for y in l[2:end] for j in I[y] if !(j in I[x]) S[j][y,x]=mu[2]*v end end for j in I[x] if !(j in I[y]) S[j][x,y]=mu[1]*v end end end end end density=sum(nnz.(S))/(rk*dim^2) density>0.2 ? Array.(S) : S end ############################################################################ # How to interpret W-graphs for complex reflection groups with one orbit of # reflections, for hecke(W,[vars]). function WGraph2Representation(a,vars) # println("a=$a vars=$vars") nodes=a[1] pos=function(n,j) if n[1] isa Vector p=findfirst(x->j in x,n) if isnothing(p) p=length(vars) end elseif j in n p=1 else p=2 end p end flat(l)=l[1] isa Vector ? flat(reduce(vcat,l)) : l rk=maximum(Int.(flat(nodes))) # number of generators dim=length(nodes) R=map(j->map(k->vars[pos(nodes[k],j)]+0,1:dim),1:rk) R=Array.(Diagonal.(R)) R=map(x->x.+0*E(1)//1,R) # println("R=$(typeof(R))$R") for r in a[2] # println("r=$r") for k in [3,4] if r[k] isa Vector for j in 2:2:length(r[k]) R[Int(r[k][j-1])][r[k-2],r[5-k]]=r[k][j] end else r2=Int.(r[1:2]) j=filter(i->pos(nodes[r2[k-2]],i)<pos(nodes[r2[5-k]],i),1:rk) for i in j R[i][r2[k-2],r2[5-k]]=r[k] end end end end # println("R=$(typeof(R))$R") toL.(R) end # the next function returns the dual W-graph of gr (for an Hecke algebra of # rank rk). A dual W-graph corresponds to a Curtis Dual representation. function DualWGraph(rk,gr) [map(x->x isa Integer ? x : setdiff(1:rk,x),gr[1]), map(((x,y),)->x isa Vector ? [-reverse(x),y] : [-x,y],gr[2])] end function charnames(io::IO,c::CharInfo) cn=c.charnames for k in [:spaltenstein, :frame, :malle, :kondo, :gp, :lusztig, :carter] if get(io,k,false) && haskey(c,k) cn=string.(c[k]) end end fromTeX.(Ref(io),cn) end charnames(io::IO,W::Weyl.FC)=charnames(io,W.G) """ `charnames(ComplexReflectionGroup or Spets;options...)` `charnames(io::IO,ComplexReflectionGroup or Spets)` returns the list of character names for the reflection group or Spets `W`. The options may imply alternative names in certain cases, or a different formatting of names in general. They can be specified by `IO` attributes if giving an `IO` as argument. ```julia-repl julia> W=coxgroup(:G,2) Gβ‚‚ julia> charnames(W;limit=true) 6-element Vector{String}: "Ο†β‚β€šβ‚€" "Ο†β‚β€šβ‚†" "Ο†β€²β‚β€šβ‚ƒ" "Ο†β€³β‚β€šβ‚ƒ" "Ο†β‚‚β€šβ‚" "Ο†β‚‚β€šβ‚‚" julia> charnames(W;TeX=true) 6-element Vector{String}: "\\phi_{1,0}" "\\phi_{1,6}" "\\phi_{1,3}'" "\\phi_{1,3}''" "\\phi_{2,1}" "\\phi_{2,2}" julia> charnames(W;spaltenstein=true,limit=true) 6-element Vector{String}: "1" "Ξ΅" "Ξ΅β‚—" "Ξ΅_c" "ΞΈβ€²" "ΞΈβ€³" julia> charnames(W;spaltenstein=true,TeX=true) 6-element Vector{String}: "1" "\\varepsilon" "\\varepsilon_l" "\\varepsilon_c" "\\theta'" "\\theta''" ``` The last two commands show the character names used by Spaltenstein and Lusztig when describing the Springer correspondence. """ function charnames(io::IO,W::Union{Group,Coset}) if applicable(refltype,W) charnames(io,charinfo(W)) else fromTeX.(Ref(io),CharTable(W).charnames) end end charnames(W;opt...)=charnames(IOContext(stdout,opt...),W) charnames(t::TypeIrred;opt...)=charnames(IOContext(stdout,opt...),t) function charnames(io::IO,t::TypeIrred) ci=getchev(t,:CharInfo) cn=ci[:charnames] for k in [:spaltenstein, :frame, :malle, :kondo, :gp, :lusztig, :carter] if get(io,k,false) && haskey(ci,k) cn=string.(ci[k]) end end fromTeX.(Ref(io),cn) end function charnames(io::IO,tt::Vector{TypeIrred}) if isempty(tt) return ["Id"] end cn=map(t->charnames(io,t),tt) if length(cn)==1 cn[1] else map(x->join(x,fromTeX(io,"\\otimes ")),cartesian(cn...)) end end """ `classnames(W;options...)` `classnames(io::IO,W)` returns the list of class names for the reflection group `W`. The optional options are IOContext attributes which can give alternative names in certain cases, or a different formatting of names in general. They can be specified by giving an IO as argument. """ function classnames(io::IO,W) if applicable(refltype,W) c=classinfo(W) cn=c.classnames for k in [:malle] if get(io,k,false) && haskey(c,k) cn=string.(c[k]) end end else cn=CharTable(W).classnames end fromTeX.(Ref(io),cn) end classnames(W;opt...)=classnames(IOContext(stdout,opt...),W) function classnames(t::TypeIrred;opt...) c=classinfo(t) cn=c.classnames for k in [:malle] if get(opt,k,false) && haskey(c,k) cn=string.(c[k]) end end cn end @GapObj struct InductionTable{T} scalar::Matrix{T} gcharnames::Vector{String} ucharnames::Vector{String} identifier::String end """ `induction_table(u,g)` returns an object describing the decomposition of the irreducible characters of the subgroup `u` induced to the group `g`. At the repl or IJulia or Pluto, a table is displayed where the rows correspond to the characters of the parent group, and the columns to those of the subgroup. The returned object has a field `scalar` which is a `Matrix{Int}` containing the induction table, and the other fields contain labeling information taken from the character tables of `u` and `g` when it exists. ```julia-rep1 julia> g=Group([Perm(1,2),Perm(2,3),Perm(3,4)]) Group([(1,2),(2,3),(3,4)]) julia> u=Group( [ Perm(1,2), Perm(3,4) ]) Group([(1,2),(3,4)]) julia> induction_table(u,g) # needs "using GAP" Induction table from Group((1,2),(3,4)) to Group((1,2),(2,3),(3,4)) β”Œβ”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚X.1 X.2 X.3 X.4β”‚ β”œβ”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚X.1β”‚ . 1 . .β”‚ β”‚X.2β”‚ . 1 1 1β”‚ β”‚X.3β”‚ 1 1 . .β”‚ β”‚X.4β”‚ 1 . 1 1β”‚ β”‚X.5β”‚ 1 . . .β”‚ β””β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` ```julia-repl julia> g=coxgroup(:G,2) Gβ‚‚ julia> u=reflection_subgroup(g,[1,6]) Gβ‚‚β‚β‚β‚…β‚Ž=Aβ‚‚ julia> t=induction_table(u,g) Induction table from Gβ‚‚β‚β‚β‚…β‚Ž=Aβ‚‚ to Gβ‚‚ β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚111 21 3β”‚ β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚Ο†β‚β€šβ‚€ β”‚ . . 1β”‚ β”‚Ο†β‚β€šβ‚† β”‚ 1 . .β”‚ β”‚Ο†β€²β‚β€šβ‚ƒβ”‚ 1 . .β”‚ β”‚Ο†β€³β‚β€šβ‚ƒβ”‚ . . 1β”‚ β”‚Ο†β‚‚β€šβ‚ β”‚ . 1 .β”‚ β”‚Ο†β‚‚β€šβ‚‚ β”‚ . 1 .β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` `IO` attributes can be transmitted to the table format method ```julia-rep1 julia> xdisplay(t;rows=[5],cols=[3,2]) Induction table from Gβ‚‚β‚β‚β‚…β‚Ž=Aβ‚‚ to Gβ‚‚ β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β” β”‚ β”‚3 21β”‚ β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€ β”‚Ο†β‚‚β€šβ‚ β”‚. 1β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”˜ ``` It is also possible to TeX induction tables with `xdisplay(t;TeX=true)`. `induction_table` also works for spets (reflection cosets). """ function induction_table(u,g) tu=CharTable(u) tg=CharTable(g) f=fusion_conjugacy_classes(u,g) function myexactdiv(a,b) q,r=divrem(a,b) if !iszero(r) error("$b does not exactly divide $a") end q end function myexactdiv(a::Cyc,b) q=Cyc(conductor(a),exactdiv(a.d,b)) if q*b!=a error("$b does not exactly divide $a") end q end cl=myexactdiv.(length(u),tu.centralizers) sc=myexactdiv.(tu.irr*Diagonal(cl)*tg.irr[:,f]',length(u)) InductionTable(permutedims(sc),tg.charnames,tu.charnames, "Induction table from \$"*TeXs(u)*"\$ to \$"*TeXs(g)*"\$", Dict{Symbol,Any}(:repr=>string("induction_table(",u,",",g,")"))) end function Base.show(io::IO, ::MIME"text/html", t::InductionTable) show(IOContext(io,:TeX=>true),"text/plain",t) end function Base.show(io::IO,t::InductionTable) if !hasdecor(io) && haskey(t,:repr) print(io,t.repr) else printTeX(io,t.identifier) end end function Base.show(io::IO,::MIME"text/plain",t::InductionTable) println(io,t) showtable(io,t.scalar;row_labels=t.gcharnames,col_labels=t.ucharnames,dotzero=true) end """ `j_induction_table(H, W)` computes the decomposition into irreducible characters of the reflection group `W` of the `j`-induced of the irreducible characters of the reflection subgroup `H`. The `j`-induced of `Ο†` is the sum of the irreducible components of the induced of `Ο†` which have same `b`-function (see `charinfo`) as `Ο†`. What is returned is an `InductionTable` struct. ```julia-repl julia> W=coxgroup(:D,4) Dβ‚„ julia> H=reflection_subgroup(W,[1,3]) Dβ‚„β‚β‚β‚ƒβ‚Ž=A₂Φ₁² julia> j_induction_table(H,W) j-induction table from Dβ‚„β‚β‚β‚ƒβ‚Ž=A₂Φ₁² to Dβ‚„ β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚111 21 3β”‚ β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚11+ β”‚ . . .β”‚ β”‚11- β”‚ . . .β”‚ β”‚1.111β”‚ . . .β”‚ β”‚.1111β”‚ . . .β”‚ β”‚11.2 β”‚ . . .β”‚ β”‚1.21 β”‚ 1 . .β”‚ β”‚.211 β”‚ . . .β”‚ β”‚2+ β”‚ . . .β”‚ β”‚2- β”‚ . . .β”‚ β”‚.22 β”‚ . . .β”‚ β”‚1.3 β”‚ . 1 .β”‚ β”‚.31 β”‚ . . .β”‚ β”‚.4 β”‚ . . 1β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` """ function j_induction_table(u,g) tbl=induction_table(u,g) bu=charinfo(u).b bg=charinfo(g).b t=copy(tbl.scalar) for (i,bi) in pairs(bu), (j,bj) in pairs(bg) if bi!=bj t[j,i]=0 end end InductionTable(t,tbl.gcharnames,tbl.ucharnames, "j-induction table from \$"*TeXs(u)*"\$ to \$"*TeXs(g)*"\$", Dict{Symbol,Any}(:repr=>string("j_induction_table(",u,",",g,")"))) end """ `J_induction_table(H, W)` computes the decomposition into irreducible characters of the reflection group `W` of the `J`-induced of the irreducible characters of the reflection subgroup `H`. The `J`-induced of `Ο†` is the sum of the irreducible components of the induced of `Ο†` which have same `a`-function (see `charinfo`) as `Ο†`. What is returned is an `InductionTable` struct. ```julia-repl julia> W=coxgroup(:D,4) Dβ‚„ julia> H=reflection_subgroup(W,[1,3]) Dβ‚„β‚β‚β‚ƒβ‚Ž=A₂Φ₁² julia> J_induction_table(H,W) J-induction table from Dβ‚„β‚β‚β‚ƒβ‚Ž=A₂Φ₁² to Dβ‚„ β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚111 21 3β”‚ β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚11+ β”‚ . . .β”‚ β”‚11- β”‚ . . .β”‚ β”‚1.111β”‚ . . .β”‚ β”‚.1111β”‚ . . .β”‚ β”‚11.2 β”‚ 1 . .β”‚ β”‚1.21 β”‚ 1 . .β”‚ β”‚.211 β”‚ . . .β”‚ β”‚2+ β”‚ . . .β”‚ β”‚2- β”‚ . . .β”‚ β”‚.22 β”‚ . . .β”‚ β”‚1.3 β”‚ . 1 .β”‚ β”‚.31 β”‚ . . .β”‚ β”‚.4 β”‚ . . 1β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` """ function J_induction_table(u,g) tbl=induction_table(u,g) bu=charinfo(u).a bg=charinfo(g).a t=copy(tbl.scalar) for (i,bi) in pairs(bu), (j,bj) in pairs(bg) if bi!=bj t[j,i]=0 end end InductionTable(t,tbl.gcharnames,tbl.ucharnames, "J-induction table from \$"*TeXs(u)*"\$ to \$"*TeXs(g)*"\$", Dict{Symbol,Any}(:repr=>string("J_induction_table(",u,",",g,")"))) end """ `discriminant(W)` returns the discriminant of the complex reflection group `W`, as a polynomial in the fundamental invariants. The discriminant is the invariant obtained by taking the product of the linear forms describing the reflecting hyperplanes of `W`, each raised to the order of the corresponding reflection. The discriminant is returned as a function `f` such that the discriminant in the variables `a₁,…,aβ‚™` is obtained by calling `f(a₁,…,aβ‚™)`. For the moment, this function is implemented only for the exceptional complex reflection groups `Gβ‚„` to `G₃₃`. ```julia-repl julia> W=complex_reflection_group(4);@Mvp x,y julia> discriminant(W)(x,y) Mvp{Int64}: xΒ³-yΒ² ``` """ function LaurentPolynomials.discriminant(W::Group) t=refltype(W) if isempty(t) return ()->Mvp(1) elseif length(t)==1 return getchev(t[1],:Discriminant) else error("not implemented for non-irreducible ",W) end end function decomposition_matrix(t::TypeIrred,p) m=getchev(t,:DecompositionMatrix,p) if m==false error("decomposition_matrix(",t,",",p,") not implemented") end n=getchev(t,:NrConjugacyClasses) append!(m,map(i->[[i],[[1]]],setdiff(1:n,union(first.(m))))) res=cat(map(x->toM(x[2]),m)...;dims=(1,2)) res[sortperm(vcat(first.(m)...)),:] end """ `decomposition_matrix(W,p)` This provides an interface to some decomposition matrices for Weyl groups available in the Chevie library: those for `E₆, E₇, Eβ‚ˆ` for `p=2,3,5,7`. """ function decomposition_matrix(W,p) m=map(t->decomposition_matrix(t,p),refltype(W)) map(x->prod.(cartesian(x)),cartesian(toL.(m)...)) end end
Chevie
https://github.com/jmichel7/Chevie.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
7745
""" This is my attempt to port the Chevie package from GAP3 to Julia. I started this project at the end of 2018 and it is still in flux so some function names or interfaces may still change. Pull requests and issues are welcome. I have implemented the GAP functionality (infrastructure) needed to make Chevie work. I have already registered most of this infrastructure as separate packages; the following packages are loaded and re-exported so that their functionality is automatically available when you use `Chevie`. In other words, `Chevie` is a meta-package for the following packages: * (univariate) [LaurentPolynomials](https://github.com/jmichel7/LaurentPolynomials.jl) (and rational fractions) * (multivariate) [PuiseuxPolynomials](https://github.com/jmichel7/PuiseuxPolynomials.jl) (and rational fractions when there are no fractional exponents) * [CyclotomicNumbers](https://github.com/jmichel7/CyclotomicNumbers.jl)(elements of cyclotomic fields) * [ModuleElts](https://github.com/jmichel7/ModuleElts.jl) (elements of a free module over some ring) * [Combinat](https://github.com/jmichel7/Combinat.jl) (combinatorics and some basic number theory) * [PermGroups](https://github.com/jmichel7/PermGroups.jl) (permutations, groups, permutations groups. It contains the modules `Perms` and `Groups` which could be separate packages) * [SignedPerms](https://github.com/jmichel7/SignedPerms.jl) (signed permutations) * [MatInt](https://github.com/jmichel7/MatInt.jl) (Integer matrices and lattices) * [CycPols](https://github.com/jmichel7/CycPols.jl) (cyclotomic polynomials) * [GenLinearAlgebra](https://github.com/jmichel7/GenLinearAlgebra.jl) (linear algebra on any field/ring) * [FinitePosets](https://github.com/jmichel7/FinitePosets.jl) (finite posets) * [FiniteFields](https://github.com/jmichel7/FiniteFields.jl) (finite fields) * [GroupPresentations](https://github.com/jmichel7/GroupPresentations.jl) (presentations of groups, and groups defined by generators and relations) * [UsingMerge](https://github.com/jmichel7/UsingMerge.jl) (Automatically compose several packages) Have a look at the documentation of the above packages to see how to use their features. I have implemented some other infrastructure which currently resides in `Chevie` but may eventually become separate packages: * factorizing polynomials over finite fields (module `FFfac`) * factorizing polynomials over the rationals (module `Fact`) * Number fields which are subfields of the Cyclotomics (module [`Nf`](@ref)) For permutation groups I have often replaced GAP's sophisticated algorithms with naive but easy-to-write methods suitable only for small groups (sufficient for the rest of the package but perhaps not for your needs). Otherwise the infrastructure code is often competitive with GAP, despite using much less code (often 100 lines of Julia replace 1000 lines of C); and I am sure it could be optimised better than I did. Comments on code and design are welcome. For functions that are too inefficient or difficult to implement (such as character tables of arbitrary groups), `Chevie` uses the `GAP` package as an extension. This means that if you have the `GAP` package installed, `Chevie` will automatically call `GAP` to implement these functions. Functions in the `Chevie.jl` package are often 10 times faster than the equivalent functions in GAP3/Chevie (after the maddeningly long compilation time on the first run --- Julia's TTFP). The `Chevie` package currently contains about 95% of the GAP3 Chevie functionality. If you are a user of GAP3/Chevie, the `gap` function can help you to find the equivalent functionality in `Chevie.jl` to a Gap3 function: it takes a string and gives you Julia translations of functions in Gap3 that match that string. ```julia-rep1 julia> gap("words") CharRepresentationWords => traces_words_mats CoxeterWords(W[,l]) => word.(Ref(W),elements(W[,l])) GarsideWords => elements ``` You can then access online help for the functions you have found. The port to Julia is not complete in the sense that 80% of the code is the data library from Chevie, which was automatically ported by a transpiler so its code is "strange". When the need to maintain the `GAP3` and `Julia` versions simultaneously subsides, I will do a proper translation of the data library, which should give an additional speed boost. ### Installing This is a registered package that can be installed/upgraded in the standard way. For Julia newbies, we will remind you what this is. To install, do this at the REPL command line: * enter package mode with ] * do the command ``` (@v1.10) pkg> add Chevie ``` - exit package mode with backspace and then do ``` julia> using Chevie ``` and you are set up. For first help, type "?Chevie". To update later to the latest version, do ``` (@v1.10) pkg> update ``` `Chevie.jl` requires julia 1.10 or later. """ module Chevie #--------------------- external packages ---------------------------------- using Reexport using UsingMerge @reexport using PuiseuxPolynomials # reexports LaurentPolynomials @reexport using LaurentPolynomials: stringexp @reexport using ModuleElts @reexport using Combinat @reexport using MatInt @reexport using Primes: factor, eachfactor, divisors @reexport using OrderedCollections: OrderedDict # careful: use very little of LinearAlgebra @reexport using LinearAlgebra: diag, tr, I, Diagonal, exactdiv, det_bareiss, dot @reexport using PermGroups @reexport using SignedPerms @usingmerge verbose=true reexport CyclotomicNumbers @reexport using CyclotomicNumbers: bracket_if_needed, format_coefficient, stringind @usingmerge verbose=true reexport FiniteFields @reexport using CycPols @reexport using CycPols: stringprime @reexport using GenLinearAlgebra @reexport using FinitePosets @reexport using GroupPresentations #--------------------- internal modules ----------------------------------- include("../docs/src/cheviedict.jl");export gap include("Format.jl");@reexport using .Format include("Util.jl");@reexport using .Util include("FFfac.jl");@reexport using .FFfac include("Nf.jl");@reexport using .Nf include("Tools.jl");@reexport using .Tools include("Fact.jl");@reexport using .Fact include("PermRoot.jl");@reexport using .PermRoot include("Diagrams.jl");@reexport using .Diagrams include("CoxGroups.jl");@reexport using .CoxGroups include("Weyl.jl");@reexport using .Weyl include("Cosets.jl");@reexport using .Cosets include("ComplexR.jl");@reexport using .ComplexR include("Chars.jl");@reexport using .Chars include("Tools2.jl");@reexport using .Tools2 include("Algebras.jl");@reexport using .Algebras include("InitChevie.jl");@reexport using .InitChevie include("Symbols.jl");@reexport using .Symbols include("Lusztig.jl");@reexport using .Lusztig include("Eigenspaces.jl");@reexport using .Eigenspaces include("Garside.jl");@reexport using .Garside include("HeckeAlgebras.jl");@reexport using .HeckeAlgebras include("KL.jl");@reexport using .KL include("Semisimple.jl");@reexport using .Semisimple include("Urad.jl");@reexport using .Urad include("Ucl.jl");@reexport using .Ucl include("Gt.jl");@reexport using .Gt include("Murphy.jl");@reexport using .Murphy include("Families.jl");@reexport using .Families include("Uch.jl");@reexport using .Uch include("dSeries.jl");@reexport using .dSeries include("Sscoset.jl");@reexport using .Sscoset include("gendec.jl"); # for now no module include("GAPENV.jl");@reexport using .GAPENV function contr(s) include(replace(@__DIR__,"/src"=>"/contr/"*s*".jl")) end export contr roundtrip(x)=x==eval(Meta.parse(repr(x))) # for debugging purposes end
Chevie
https://github.com/jmichel7/Chevie.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
14373
module ComplexR using ..Chevie export complex_reflection_group, crg, diagram, degrees, codegrees, Reflection, reflections, isdistinguished, hyperplane, hyperplane_orbits, hyperplane_orbit, simple_rep, reflection_group, torusfactors @forward Weyl.FC.G hyperplane_orbits, codegrees, degrees # roots for the adjoint group PermRoot.simpleroots(t::TypeIrred)= t.series==:ST ? toM(getchev(t,:GeneratingRoots)) : one(cartan(t)) # coroots for the adjoint group function PermRoot.simplecoroots(t::TypeIrred) if t.series==:ST cr=getchev(t,:GeneratingCoRoots) if isnothing(cr) r=getchev(t,:GeneratingRoots) cr=coroot.(r,E.(ordergens(t))) end toM(map(x->convert.(Cyc{Rational{Int}},x),cr)) else cartan(t) end end """ `complex_reflection_group(STnumber)` or `crg(STnumber)` `complex_reflection_group(p,q,r)` or `crg(p,q,r)` The first form of `complex_reflection_group` returns the complex reflection group which has Shephard-Todd number `STnumber`, see [Shephard-Todd1954](biblio.htm#ST54). The second form returns the imprimitive complex reflection group `G(p,q,r)`. ```julia-repl julia> G=complex_reflection_group(4) Gβ‚„ julia> degrees(G) 2-element Vector{Int64}: 4 6 julia> length(G) 24 julia> W*coxgroup(:A,2) # how to make a non-irreducible group Gβ‚„Γ—Aβ‚‚ julia> complex_reflection_group(1,1,3) # another way to enter Aβ‚‚ gl₃ julia> crg(4) # there is also a short alias Gβ‚„ ``` """ function complex_reflection_group(i::Integer) if i==23 coxgroup(:H,3) elseif i==28 coxgroup(:F,4) elseif i==30 coxgroup(:H,4) elseif i==35 coxgroup(:E,6) elseif i==36 coxgroup(:E,7) elseif i==37 coxgroup(:E,8) else t=TypeIrred(Dict(:series=>:ST,:ST=>Int(i))) PRG(simpleroots(t),simplecoroots(t)) end end function complex_reflection_group(p,q,r) if !iszero(p%q) || p<=0 || r<=0 || (r==1 && q!=1) error("complex_reflection_group(p,q,r) must satisfy: q|p, r>0, and r=1 => q=1") end if p==1 return r==1 ? coxgroup() : rootdatum(:gl,r) elseif p==2 return rootdatum(:so,q==2 ? 2r : 2r+1) elseif p==q && r==2 return coxgroup(:I,2,p) end t=TypeIrred(Dict(:series=>:ST,:p=>p,:q=>q,:rank=>r)) PRG(simpleroots(t),simplecoroots(t)) end const crg=complex_reflection_group # converts a type back to a group function reflection_group(t::TypeIrred) if haskey(t,:orbit) W=reflection_group(t.orbit) if length(t.orbit)>1 spets(W,reflrep(W,Perm(vcat(circshift(map(x->x.indices, refltype(W)),-1)...))*t.twist)) else spets(W,t.twist) end elseif t.series==:ST PRG(simpleroots(t),simplecoroots(t)) else C=cartan(t) all(isreal,C) ? rootdatum(C) : PRG(one(C),C) end end function reflection_group(l::Vector{TypeIrred}) if isempty(l) return coxgroup() end prod(reflection_group.(l)) end """ `degrees(W::ComplexReflectionGroup)` returns a list holding the degrees of `W` as a reflection group on the vector space `V` on which it acts. These are the degrees `d₁,…,dβ‚™` where `n` is the dimension of `V` of the basic invariants of `W` in `SV`. They reflect various properties of `W`; in particular, their product is the cardinality of `W`. ```julia-repl julia> W=complex_reflection_group(30) Hβ‚„ julia> degrees(W) 4-element Vector{Int64}: 2 12 20 30 julia> length(W) 14400 ``` """ function degrees(W::ComplexReflectionGroup) get!(W,:degrees)do vcat(fill(1,rank(W)-semisimplerank(W)),degrees.(refltype(W))...) end::Vector{Int} end function torusfactors(WF::Spets) get!(WF,:torusfactors)do eigmat(central_action(Group(WF),WF.F)) end::Vector{Root1} end """ `degrees(WF::Spets)` Let `W` be the group of the reflection coset `WF`, and let `V` be the vector space of dimension `rank(W)` on which `W` acts as a reflection group. Let `f₁,…,fβ‚™` be the basic invariants of `W` on the symmetric algebra `SV` of `V`; they can be chosen so they are eigenvectors of the matrix `WF.F`. The corresponding eigenvalues are called the *factors* of `F` acting on `V`; they characterize the coset --- they are equal to 1 only for the trivial coset. The *generalized degrees* of `WF` are the pairs formed of the reflection degrees and the corresponding factor. ```julia-repl julia> W=coxgroup(:E,6) E₆ julia> WF=spets(W) E₆ julia> phi=W(6,5,4,2,3,1,4,3,5,4,2,6,5,4,3,1); julia> HF=subspets(WF,2:5,phi) Eβ‚†β‚β‚‚β‚ƒβ‚„β‚…β‚Ž=Β³D₄Φ₃ julia> diagram(HF) Ο• acts as (1,2,4) on the component below O 2 οΏ¨ Oβ€”Oβ€”O Dβ‚„ 1 3 4 julia> degrees(HF) 6-element Vector{Tuple{Int64, Cyc{Int64}}}: (1, ΢₃) (1, ΢₃²) (2, 1) (4, ΢₃) (6, 1) (4, ΢₃²) ``` """ function degrees(W::Spets) get!(W,:degrees)do if isempty(refltype(W)) b=Tuple{Int,Cyc{Int}}[] else b=vcat(degrees.(refltype(W))...) end vcat(map(x->(1,Cyc(x)),torusfactors(W)),b) end::Vector{Tuple{Int,Cyc{Int}}} end function degrees(t::TypeIrred) if !haskey(t,:orbit) return getchev(t,:ReflectionDegrees) end d=getchev(t.orbit[1],:ReflectionDegrees) # Let t.scalar=[s₁,…,sα΅£], where r=length(t.orbit) and ΞΆ=prod(t.scalar). let # p be the PhiFactor of t.twist associated to the reflection degree dα΅’ of # t.orbit[1]. If G0 is the Spets described by t.orbit[1], and # G1:=Ennola(ΞΆ,G0) then G is isomorphic to the descent of scalars of G1. # According to spets 1.5, a Phifactor of Ennola(ΞΆ,G0) is ΞΆ^dα΅’ times that of # G0; and by spets 1.5 or [Digne-Michel, parabolic A.1] those of an # a-descent of scalars are ΢ₐʲ΢ᡒ^{1/a} (all the a-th roots of ΞΆα΅’). if order(t.twist)>1 f=getchev(t,:PhiFactors) if isnothing(f) return nothing end else f=fill(1,length(d)) end if haskey(t,:scalar) p=improve_type(prod(t.scalar)) f=[f[i]*p^d[i] for i in eachindex(d)] end f=collect(zip(d,Cyc.(f))) a=length(t.orbit) if a==1 return f end vcat(map(f)do (d,e) map(x->(d,x),root(e,a).*E.(a,0:a-1)) end...) end function codegrees(t::TypeIrred) if !haskey(t,:orbit) d=getchev(t,:ReflectionCoDegrees) if !isnothing(d) return d else d=getchev(t,:ReflectionDegrees) return reverse(maximum(d).-d) end end d=getchev(t,:ReflectionCoDegrees) if isnothing(d) d=getchev(t.orbit[1],:ReflectionDegrees) a=argmax(d) d=reverse(d[a].-d) if order(t.twist)==1 f=fill(1,length(d)) else f=getchev(t,:PhiFactors) if isnothing(f) return f end f=Cyc.(improve_type(reverse(map(x->f[a]//x,f)))) end d=collect(zip(d,Cyc.(f))) elseif order(t.twist)==1 d=collect(zip(d,fill(Cyc(1),length(d)))) end if haskey(t,:scalar) f=Cyc.(improve_type(prod(t.scalar))) d=[(deg,eps*f^deg) for (deg,eps) in d] end a=length(t.orbit) if a==1 return d end vcat(map(d)do (d,e) map(x->(d,x),root(e,a).*E.(a,0:a-1)) end...) end """ `codegrees(W::ComplexReflectionGroup)` returns the vector of codegrees of `W` as a reflection group on the space `V` of `reflrep(W)`. These are one less than the degrees of the basic derivations of ` W` on `SVβŠ— V^vee`. ```julia-repl julia> W=complex_reflection_group(4) Gβ‚„ julia> codegrees(W) 2-element Vector{Int64}: 0 2 ``` """ function codegrees(W::ComplexReflectionGroup) vcat(fill(-1,rank(W)-semisimplerank(W)),collect.(codegrees.(refltype(W)))...) end function codegrees(W::Spets) get!(W,:codegrees)do a=inv.(torusfactors(W)) if isempty(refltype(W)) b=Tuple{Int,Cyc{Int}}[] # separate/recombine for promotions to work else b=vcat(codegrees.(refltype(W))...) end collect(zip(vcat(fill(-1,length(a)),first.(b)),vcat(a,last.(b)))) end::Vector{Tuple{Int,Cyc{Int}}} end """ `hyperplane_orbits(W::ComplexReflectionGroup)` returns a list of named tuples, one for each hyperplane orbit of the reflection group `W`. If `o` is the named tuple for such an orbit, and `s` is the first element of `gens(W)` whose hyperplane is in the orbit, it contains the following fields `.s`: index of `s` in `gens(W)` `.order`: order of s `.cl_s`: for i in `1:order-1`, `position_class(W,W(s)^i)` `.N_s`: size of hyperplane orbit `.det_s`: for i in `1:order-1`, position in `CharTable(W)` of `detₛⁱ`, where `detβ‚›` is the linear character taking the value `det(reflrep(W,s))` on `s` and `1` on non-conjugate reflections. ```julia-repl julia> W=coxgroup(:B,2) Bβ‚‚ julia> hyperplane_orbits(W) 2-element Vector{@NamedTuple{s::Int64, cl_s::Vector{Int64}, order::Int64, N_s::Int64, det_s::Vector{Int64}}}: (s = 1, cl_s = [2], order = 2, N_s = 2, det_s = [5]) (s = 2, cl_s = [4], order = 2, N_s = 2, det_s = [1]) ``` """ function hyperplane_orbits(W::ComplexReflectionGroup) T=@NamedTuple{s::Int,cl_s::Vector{Int},order::Int,N_s::Int,det_s::Vector{Int}} get!(W,:hyperplane_orbits)do sr=simple_reps(W) if isempty(sr) return T[] end rr=refls(W) cr=classreps(W) orb=unique(sort(sr)) class=map(orb)do s map(1:ordergens(W)[s]-1)do o # return position_class(W,refls(W,s)^o) for i in eachindex(sr) if sr[i]==s p=findfirst(==(rr[i]^o),cr) if p!==nothing return p end end end error("not found") end end if !allunique(class) # when there are too many roots in rootsystem l=unique(indexin(class,class));class=class[l];orb=orb[l] end chars=CharTable(W).irr pairs=zip(orb,class) res=map(pairs) do (s,c) ord=ordergens(W)[s] dets=map(1:ord-1) do j findfirst(i->chars[i,1]==1 && chars[i,c[1]]==E(ord,j) && all(p->chars[i,p[2][1]]==1 || p[1]==s,pairs),axes(chars,1)) end (s=s,cl_s=c,order=ord,N_s=div(length(W),CharTable(W).centralizers[c[1]]),det_s=dets) end end::Vector{T} end #------------------------- Reflection(s) -------------------------------- @GapObj struct Reflection{TW<:ComplexReflectionGroup} W::TW rootno::Int eigen::Root1 word::Vector{Int} end @doc """ `Reflection` is a `struct` representing a reflection in a reflection group. ```julia-repl julia> W=crg(8); julia> r=reflections(W)[7] # shows (r.W,r.rootno,r.eigen) Reflection(Gβ‚ˆ,1,-1) julia> r.rootno # r is a reflection for the first root 1 julia> r.eigen # the non-trival eigenvalue, as a Root1 Root1: -1 julia> r.W # the group of which r is a reflection Gβ‚ˆ julia> r==Reflection(W,1,-1) # specify r with .rootno and .eigen true julia> Reflection(W,1) # specify with .rootno gets the distinguished reflection Reflection(Gβ‚ˆ,1,ΞΆβ‚„) julia> root(r) 2-element Vector{Cyc{Rational{Int64}}}: 0 ΞΆβ‚„ julia> coroot(r) 2-element Vector{Cyc{Int64}}: 0 -2ΞΆβ‚„ julia> Matrix(r) 2Γ—2 Matrix{Cyc{Rational{Int64}}}: 1 0 0 -1 julia> hyperplane(r) # the fixed hyperplane, as a rowspace 1Γ—2 Matrix{Cyc{Rational{Int64}}}: 1 0 julia> hyperplane(r)*Matrix(r)==hyperplane(r) true julia> isdistinguished(r) # r is not distinguished false julia> exponent(r) # which power of a distinguished reflection it is 2 julia> Perm(r) (1,8)(2,9)(3,16)(4,15)(5,17)(6,18)(7,19)(10,22)(11,21)(12,23) julia> hyperplane_orbit(r) # r is in the first hyperplane orbit 1 julia> position_class(r) # the index of the conjugacy class of r in W 15 julia> simple_rep(r) # smallest root index affording a conjugate reflection 1 julia> word(r) # a word in the generators of r.W for r 2-element Vector{Int64}: 1 1 ``` """ Reflection function Base.show(io::IO,r::Reflection) print(io,"Reflection(",r.W,",",r.rootno,",",r.eigen,")") end LaurentPolynomials.root(r::Reflection)=roots(r.W,r.rootno) function PermRoot.coroot(r::Reflection) get!(r,:coroot)do rr=root(r)//1 cr=coroots(r.W,r.rootno) improve_type(cr*(1-r.eigen)/(transpose(cr)*rr)) end end function Base.Matrix(r::Reflection) get!(r,:matrix)do reflectionMatrix(root(r),coroot(r)) end end Perms.order(r::Reflection)=order(r.eigen) simple_rep(r::Reflection)=simple_reps(r.W)[r.rootno] Base.exponent(r::Reflection)=Int(r.eigen.r*ordergens(r.W)[simple_rep(r)]) isdistinguished(r::Reflection)=exponent(r)==1 Perms.Perm(r::Reflection)=refls(r.W,r.rootno)^exponent(r) function hyperplane_orbit(r::Reflection) findfirst(x->x.s==simple_rep(r),hyperplane_orbits(r.W)) end function hyperplane(r::Reflection) get!(r,:hyperplane)do Matrix(rowspace(lnullspace(hcat(coroot(r))))) end end function Groups.position_class(r::Reflection) get!(r,:position_class)do hyperplane_orbits(r.W)[hyperplane_orbit(r)].cl_s[exponent(r)] end::Int end # invert word w in gens(w) to a positive word in gens(w) function invert_word(W,w) if isempty(w) return w end lastg=0 mul=0 seq=Pair{Int,Int}[] for i in length(w):-1:1 if w[i]==lastg mul+=1 else if lastg!=0 push!(seq,lastg=>mul) end lastg=w[i]; mul=1 end end if lastg!=0 push!(seq,lastg=>mul) end o=ordergens(W) [i for (i,mul) in seq for y in 1+mul:o[i]] end function Reflection(W::ComplexReflectionGroup,i::Integer,eig) if !(eig isa Root1) eig=Root1(eig) end p=findfirst(r->refls(W,r.rootno)==refls(W,i) && r.eigen==eig,reflections(W)) reflections(W)[p] end function Reflection(W::ComplexReflectionGroup,i::Integer) Reflection(W,i,E(order(refls(W,i)))) end """ `reflections(W)` a `Vector{Reflection}` of all reflections of the reflection group `W` (including the non-distinguished ones; see [`Reflection`](@ref)). `reflections(W)[1:nhyp(W)]` are the distinguished reflections. ```julia-repl julia> W=crg(4) Gβ‚„ julia> reflections(W) 8-element Vector{Reflection{PRG{Cyc{Rational{Int64}}, Int16}}}: Reflection(Gβ‚„,1,΢₃) Reflection(Gβ‚„,2,΢₃) Reflection(Gβ‚„,4,΢₃) Reflection(Gβ‚„,5,΢₃) Reflection(Gβ‚„,1,΢₃²) Reflection(Gβ‚„,2,΢₃²) Reflection(Gβ‚„,4,΢₃²) Reflection(Gβ‚„,5,΢₃²) ``` """ function reflections(W::ComplexReflectionGroup) get!(W,:reflections)do sreps=sort(unique(simple_reps(W))) pnts=refls(W,sreps) if W isa PermRootGroup dd=map(x->Groups.words_transversal(gens(W),x),pnts) end res=map(i->Reflection{typeof(W)}[],1:maximum(ordergens(W))-1) for i in unique_refls(W) e=ordergens(W)[simple_reps(W)[i]] if W isa CoxeterGroup w=word(W,refls(W,i)) else rep=simple_reps(W)[i] w=dd[findfirst(==(rep),sreps)][refls(W,i)] w=vcat(invert_word(W,w),[rep],w) end for j in 1:e-1 push!(res[j],Reflection(W,i,E(e,j),repeat(w,j),Dict{Symbol,Any}())) end end vcat(res...) end::Vector{Reflection{typeof(W)}} end Groups.word(r::Reflection)=r.word end
Chevie
https://github.com/jmichel7/Chevie.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
48316
""" Let `R` be a root system in the real vector space `V`. We say that `Fβ‚€βˆˆ GL(V)` is an *automorphism of `R`* if it permutes `R` and is of finite order (finite order is automatic if `R` generates `V`). It follows by [chap. VI, Β§1.1, lemme 1 Bourbaki1968](biblio.htm#Bou68) that the dual `Fβ‚€*∈ GL(V*)` permutes the coroots `R*βŠ‚ V*`; thus `Fβ‚€` normalizes the reflection group `W` associated to `R`, that is `w↦ Fβ‚€wF₀⁻¹` is an automorphism of `W`. Thus we get a reflection coset `WFβ‚€`, which we call a *Coxeter coset*. The motivation for introducing Coxeter cosets comes from automorphisms of algebraic reductive groups, giving rise to non-split reductive groups over finite fields. Let `𝐆` be a connected reductive algebraic group `𝐆` over an algebraic closure `𝔽̄_q` of a finite field `𝔽_q`, defined over `𝔽_q`; this corresponds to a Frobenius endomorphism `F` so that the finite group of rational points `𝐆(𝔽_q)` identifies to the subgroup `𝐆^F` of fixed points under `F`. Let `𝐓` be a maximal torus of `𝐆`, and `Ξ¦` (resp. `Ξ¦*`) be the roots (resp. coroots) of `𝐆` with respect to `𝐓` in the character group `X(𝐓)` (resp. the group of one-parameter subgroups `Y(𝐓)`). Then `𝐆` is determined up to isomorphism by `(X(𝐓),Ξ¦,Y(𝐓),Ξ¦*)`; this corresponds to give a root system in the vector space `V=β„š βŠ— X(𝐓)` and a rational reflection group `W=N_𝐆(𝐓)/𝐓` acting on it. If `𝐓` is `F`-stable the Frobenius endomorphism `F` acts also naturally on `X(T)` and defines thus an endomorphism of `V`, which is of the form `q Fβ‚€`, where `Fβ‚€βˆˆ GL(V)` is of finite order and normalizes `W`. We get thus a Coxeter coset `WFβ‚€βŠ‚GL(V)`. The data `(X(𝐓), Ξ¦, Y(𝐓), Ξ¦*, Fβ‚€)`, and the integer `q` completely determine up to isomorphism the associated *reductive finite group* `𝐆^F`. Thus these data is a way of representing in the essential information which determines a finite reductive group. Indeed, all properties of Chevalley groups can be computed from that datum: symbols representing characters, conjugacy classes, and finally the whole character table of `𝐆^F`. It turns out that many interesting objects attached to this datum depend only on `(V,W, Fβ‚€)`: the order of the maximal tori, the *fake degrees*, the order of `𝐆^F`, symbols representing unipotent characters, Deligne-Lusztig induction in terms of *almost characters*, the Fourier matrix relating characters and almost characters, etc… (see, e.g., [Broue-Malle-Michel1993](biblio.htm#BMM93)). It is thus possible to extend their construction to non-crystallographic groups (or even to more general complex reflection groups, see [`spets`](@ref)); this is why we did not include a root system in the definition of a reflection coset. However, unipotent conjugacy classes for instance depend on the root system. We assume now that `𝐓` is contained in an `F`-stable Borel subgroup of `𝐆`. This defines an order on the roots, and there is a unique element `Ο•βˆˆ W Fβ‚€`, the *reduced element* of the coset, which preserves the set of positive roots. It thus defines a *diagram automorphism*, that is an automorphism of the Coxeter system `(W,S)`. This element is stored in the component `.phi` of the coset record. It may be defined without mentioning the roots, as follows: `(W,Fβ‚€(S))` is another Coxeter system, thus conjugate to `S` by a unique element of `W`, thus there is a unique element `Ο•βˆˆ WFβ‚€` which stabilizes `S` (a proof follows from [Theoreme 1, chap. V, Β§3 Bourbaki1968](biblio.htm#Bou68)). We consider thus cosets of the form `WΟ•` where `Ο•` stabilizes `S`. The coset `W Ο•` is completely defined by the permutation `.phi` when `𝐆` is semi-simple --- equivalently when `Ξ¦` generates `V`; in this case we just need to specify `phi` to define the coset. There is a slight generalisation of the above setup, covering in particular the case of the Ree and Suzuki groups. We consider `𝐆^F` where `F` not a Frobenius endomorphism, but an isogeny such that some power `F^n` is a Frobenius endomorphism. Then `F` still defines an endomorphism of `V` which normalizes `W`; we define a real number `q` such that `F^n` is attached to an `𝔽_{qⁿ}`-structure. Then we still have `F=q Fβ‚€` where `Fβ‚€` is of finite order but `q` is no more an integer. Thus `Fβ‚€βˆˆ GL(VβŠ— ℝ)` but `Fβ‚€βˆ‰ GL(V)`. For instance, for the Ree and Suzuki groups, `Fβ‚€` is an automorphism of order `2` of `W`, which is of type `Gβ‚‚`, `Bβ‚‚` or `Fβ‚„`, and `q=√2` for `Bβ‚‚` and `Fβ‚„` and `q=√3` for `Gβ‚‚` This can be constructed starting from root systems for `Gβ‚‚`, `Bβ‚‚` or `Fβ‚„` where all the roots have the same length. This kind of root system is *not* crystallographic. Such non-crystallographic root systems exist for all finite Coxeter groups such as the dihedral groups, `H₃` and `Hβ‚„`. We will call here *Weyl cosets* the cosets corresponding to rational forms of algebraic groups, which include thus some non-rational roots systems for `Bβ‚‚`, `Gβ‚‚` and `Fβ‚„`. ## Spets We now extend the above notions to general complex reflection groups. Let `WβŠ‚ GL(V)` be a complex reflection group on the vector space `V`. Let `Ο•` be an element of `GL(V)` which normalizes `W`. Then the coset `WΟ•` is called a reflection coset. A reference for these cosets is [Broue-Malle-Michel 1999](biblio.htm#BMM99). When `W` is a so-called *Spetsial* group, they are the basic object for the construction of a *Spetses*, which is an object attached to a complex reflection group from which one can derive combinatorially some attributes shared with finite reductive groups, like unipotent degrees, etc…. We say that a reflection coset is irreducible if `W` is irreducible. A general coset is a direct product of *descents of scalars*, which is the case where `Ο•` is transitive on the irreducible components of `W`. The irreducible cosets have been classified in [Broue-Malle-Michel 1999](biblio.htm#BMM99): up to multiplication of `Ο•` by a scalar, there is usually only one or two possible cosets for a given irreducible group. We deal only with *finite order* cosets, that is, we assume there is a (minimal) integer `Ξ΄` such that `(WΟ•)^Ξ΄=W`. Then the group generated by `W` and `Ο•` is finite, of order `Ξ΄|W|`. A subset `C` of a `WΟ•` is called a *conjugacy class* if one of the following equivalent conditions is fulfilled: * `C` is the orbit of an element in `WΟ•` under the conjugation action of `W`. * `C` is a conjugacy class of `⟨W,Ο•βŸ©` contained in `WΟ•`. * The set `{w∈ W|wΟ•βˆˆ C}` is a `Ο•`-conjugacy class of `W` (two elements `v,w∈ W` are called `Ο•`-conjugate, if and only if there exists `x∈ W` with `v=xwΟ•(x⁻¹)`). An irreducible character of `⟨W,Ο•βŸ©` has some non-zero values on `WΟ•` if and only if its restriction to `W` is irreducible. Further, two characters `χ₁` and `Ο‡β‚‚` which have same irreducible restriction to `W` differ by a character of the cyclic group `βŸ¨Ο•βŸ©` (which identifies to the quotient `⟨W,Ο•βŸ©/W`). A set containing one extension to `⟨W,Ο•βŸ©` of each `Ο•`-invariant character of `W` is called a *set of irreducible characters of `WΟ•`*. Two such characters are orthogonal for the scalar product on the class functions on `WΟ•` given by ``βŸ¨Ο‡,ψ⟩:=|W|ΒΉβˆ‘_{w∈ W}Ο‡(wΟ•)\\overline{ψ(wΟ•)}.`` For rational groups (Weyl groups), Lusztig has defined a choice of a set of irreducible characters for `WΟ•` (called the *preferred extensions*), but for more general reflection cosets we have made some rather arbitrary choices, which however have the property that their values lie in the smallest possible field. The *character table* of `WΟ•` is the table of values of a set of irreducible characters on the conjugacy classes. A *subcoset* `LwΟ•` of `WΟ•` is given by a reflection subgroup `L` of `W` and an element `w` of `W` such that `wΟ•` normalizes `L`. We then have a natural notion of *restriction* of class functions on `WΟ•` to class functions on `LwΟ•` as well as of *induction* in the other direction. These maps are adjoint with respect to the scalar product defined above (see [Broue-Malle-Michel 1999](biblio.htm#BMM99)). In this package the most general construction of a reflection coset is by starting from a reflection datum, and giving in addition the matrix `F` of the map `Ο•:Vβ†’ V` (see the command `spets`). However, at present, general cosets are only implemented for groups represented as permutation groups on a set of roots, and it is required that the automorphism given preserves this set up to a scalar (it is allowed that these scalars depend on the pair of an irreducible component and its image). It is also allowed to specify `Ο•` by the permutation it induces on the roots; in this case it is assumed that `Ο•` acts trivially on the orthogonal of the roots, but the roots could be those of a parent group, generating a larger space. Thus in any case we have a permutation representation of `⟨W,Ο•βŸ©` and we consider the coset to be a set of permutations. Reflection cosets are implemented in by a `struct` which points to a reflection group record and has additional fields holding `F` and the corresponding permutation `phi`. In the general case, on each component of `W` which is a descent of scalars, `F` will permute the components and differ by a scalar on each component from an automorphism which preserves the roots. In this case, we have a permutation `phi` and a `scalar` which is stored for that component. The most common situation where cosets with non-trivial `phi` arise is as sub-cosets of reflection groups. Here is an "exotic" example, see the next chapter for more classical examples involving Coxeter groups. ```julia-repl julia> W=complex_reflection_group(14) G₁₄ julia> R=reflection_subgroup(W,[2,4]) Gβ‚β‚„β‚β‚‚β‚„β‚Ž=Gβ‚… julia> RF=spets(R,W(1)) # should be Β²Gβ‚…(√6) Gβ‚β‚„β‚β‚‚β‚„β‚Ž=Β²Gβ‚… ``` ```julia-rep1 julia> diagram(RF) Ο• acts as (1,2) on the component below β‘’ ══⑒ Gβ‚… 1 2 ``` ```julia-repl julia> degrees(RF) 2-element Vector{Tuple{Int64, Cyc{Int64}}}: (6, 1) (12, -1) ``` The last line shows for each reflection degree the corresponding *factor* of the coset, which is the scalar by which `Ο•` acts on the corresponding fundamental reflection invariant. The factors characterize the coset. A spets by default is printed in an abbreviated form which describes its type, as above (`Gβ‚…` twisted by 2, with a Cartan matrix which differs from the standard one by a factor of `√6`). The function `repr` gives a form which could be input back in Julia. With the same data as above we have: ```julia-rep1 julia> print(RF) spets(reflection_subgroup(complex_reflection_group(14),[2, 4]),perm"(1,3)(2,4)(5,9)(6,10)(7,11)(8,12)(13,21)(14,22)(15,23)(16,24)(17,25)(18,26)(19,27)(20,28)(29,41)(30,42)(31,43)(32,44)(33,45)(34,46)(35,47)(36,48)(37,49)(38,50)(39,51)(40,52)(53,71)(54,72)(55,73)(56,74)(57,75)(58,76)(59,77)(60,78)(62,79)(64,80)(65,81)(66,82)(67,69)(68,70)(83,100)(84,101)(85,102)(87,103)(89,99)(90,97)(91,98)(92,96)(93,104)(94,95)(105,113)(106,114)(109,111)(110,112)(115,118)(116,117)(119,120)") ``` Conjugacy classes and irreducible characters of Coxeter cosets are defined as for general reflection cosets. For irreducible characters of Weyl cosets, we choose (following Lusztig) for each `Ο•`-stable character of `W` a particular extension to a character of `Wβ‹Š βŸ¨Ο•βŸ©`, which we will call the *preferred extension*. The *character table* of the coset `WΟ•` is the table of the restrictions to `WΟ•` of the preferred extensions. The question of finding the conjugacy classes and character table of a Coxeter coset can be reduced to the case of irreducible root systems `R`. * The automorphism `Ο•` permutes the irreducible components of `W`, and `WΟ•` is a direct product of cosets where `Ο•` permutes cyclically the irreducible components of `W`. The preferred extension is defined to be the direct product of the preferred extension in each of these situations. * Assume now that `WΟ•` is a descent of scalars, that is the decomposition in irreducible components `W=W₁× β‹― Γ— Wβ‚–` is cyclically permuted by `Ο•`. Then there are natural bijections from the `Ο•`-conjugacy classes of `W` to the `ϕᡏ`-conjugacy classes of `W₁` as well as from the `Ο•`-stable characters of `W` to the `ϕᡏ`-stable characters of `W₁`, which reduce the definition of preferred extensions on `WΟ•` to the definition for `W₁ϕᡏ`. * Assume now that `W` is the Coxeter group of an irreducible root system. `Ο•` permutes the simple roots, hence induces a graph automorphism on the corresponding Dynkin diagram. If `Ο•=1` then conjugacy classes and characters coincide with those of the Coxeter group `W`. The nontrivial cases for crystallographic roots systems are (the order of `Ο•` is written as left exponent to the type): `Β²Aβ‚™`, `Β²Dβ‚™`, `Β³Dβ‚„`, `Β²E₆`. For non-crystallographic root systems where all the roots have the same length the additional cases `Β²Bβ‚‚`, `Β²Gβ‚‚`, `Β²Fβ‚„` and `Β²Iβ‚‚(k)` arise. * In case `Β³Dβ‚„` the group `Wβ‹Š βŸ¨Ο•βŸ©` can be embedded into the Coxeter group of type `Fβ‚„`, which induces a labeling for the conjugacy classes of the coset. The preferred extension is chosen as the (single) extension with rational values. * In case `Β²Dβ‚™` the group `Wβ‹Š βŸ¨Ο•βŸ©` is isomorphic to a Coxeter group of type `Bβ‚™`. This induces a canonical labeling for the conjugacy classes of the coset and allows to define the preferred extension in a combinatorial way using the labels (pairs of partitions) for the characters of the Coxeter group of type `Bβ‚™`. * In the remaining crystallographic cases `Ο•` identifies to `-wβ‚€` where `wβ‚€` is the longest element of `W`. So, there is a canonical labeling of the conjugacy classes and characters of the coset by those of `W`. The preferred extensions are defined by describing the signs of the character values on `-wβ‚€`. The most general construction of a Coxeter coset is by starting from a Coxeter datum specified by the matrices of `simpleRoots` and `simplecoroots`, and giving in addition the matrix `F0Mat` of the map `Fβ‚€:Vβ†’ V` (see the commands `CoxeterCoset` and `CoxeterSubCoset`). As for Coxeter groups, the elements of `WΟ•` are uniquely determined by the permutation they induce on the set of roots `R`. We consider these permutations as `elements` of the Coxeter coset. Coxeter cosets are implemented by a struct which points to a Coxeter datum record and has additional fields holding `F0Mat` and the corresponding element `phi`. Functions on the coset (for example, `classinfo`) are about properties of the group coset `W Ο•` ; however, most definitions for elements of untwisted Coxeter groups apply without change to elements in `W Ο•`: e.g., if we define the length of an element `wΟ•βˆˆ WΟ•` as the number of positive roots it sends to negative ones, it is the same as the length of `w`, i.e., `Ο•` is of length `0`, since `Ο•` has been chosen to preserve the set of positive roots. Similarly, the Coxeter `word` describing `wΟ•` is the same as the one for `w`, etc… We associate to a Coxeter coset `WΟ•` a *twisted Dynkin diagram*, consisting of the Dynkin diagram of `W` and the graph automorphism induced by `Ο•` on this diagram (this specifies the group `Wβ‹Š ⟨F⟩`, mentioned above, up to isomorphism). See the functions `ReflectionType`, `ReflectionName` and `diagram` for Coxeter cosets. Below is an example showing first how to *not* define, then how to define, the Weyl coset for a Suzuki group: ```julia-repl julia> W=coxgroup(:B,2) Bβ‚‚ julia> spets(W,Perm(1,2)) ERROR: matrix F must preserve the roots Stacktrace: [1] error(::String) at ./error.jl:33 [2] spets(::Chevie.Weyl.FCG{Int16,Int64,PRG{Int64,Int16}}, ::Matrix{Int64}) at /home/jmichel/julia/Chevie/src/Cosets.jl:241 (repeats 2 times) [3] top-level scope at REPL[19]:1 julia> W=coxgroup(:Bsym,2) Bsymβ‚‚ julia> WF=spets(W,Perm(1,2)) Β²Bsymβ‚‚ julia> CharTable(WF) CharTable(Β²Bsymβ‚‚) β”Œβ”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ 1 121β”‚ β”œβ”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚2. β”‚1 1 1β”‚ β”‚.11β”‚1 -1 -1β”‚ β”‚1.1β”‚. -√2 √2β”‚ β””β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` A *subcoset* `HwΟ•` of `WΟ•` is given by a reflection subgroup `H` of `W` and an element `w` of `W` such that `wΟ•` induces an automorphism of the root system of `H`. For algebraic groups, this corresponds to a rational form of a reductive subgroup of maximal rank. For example, if `WΟ•` corresponds to the algebraic group `𝐆` and `H` is the trivial subgroup, the coset `HwΟ•` corresponds to a maximal torus `𝐓_w` of type `w`. ```julia-repl julia> W=coxgroup(:Bsym,2) Bsymβ‚‚ julia> WF=spets(W,Perm(1,2)) Β²Bsymβ‚‚ julia> subspets(WF,Int[],W(1)) Β²Bsymβ‚‚β‚β‚Ž=Ξ¦β€΄β‚ˆ ``` A subgroup `H` which is a parabolic subgroup corresponds to a rational form of a Levi subgroup of `𝐆`. The command `twistings` gives all rational forms of such a Levi. ```julia-repl julia> W=coxgroup(:B,2) Bβ‚‚ julia> twistings(W,[1]) 2-element Vector{Spets{FiniteCoxeterSubGroup{Perm{Int16},Int64}}}: Bβ‚‚β‚β‚β‚Ž=Ã₁Φ₁ Bβ‚‚β‚β‚β‚Ž=Ã₁Φ₂ julia> twistings(W,[2]) 2-element Vector{Spets{FiniteCoxeterSubGroup{Perm{Int16},Int64}}}: Bβ‚‚β‚β‚‚β‚Ž=A₁Φ₁ Bβ‚‚β‚β‚‚β‚Ž=A₁Φ₂ ``` Notice how we distinguish between subgroups generated by short roots and by long roots. A general `H` corresponds to a reductive subgroup of maximal rank. Here we consider the subgroup generated by the long roots in `Bβ‚‚`, which corresponds to a subgroup of type `SLβ‚‚Γ— SLβ‚‚` in `SPβ‚„`, and show its possible rational forms. ```julia-repl julia> W=coxgroup(:B,2) Bβ‚‚ julia> twistings(W,[2,4]) 2-element Vector{Spets{FiniteCoxeterSubGroup{Perm{Int16},Int64}}}: Bβ‚‚β‚β‚‚β‚„β‚Ž=A₁×A₁ Bβ‚‚β‚β‚‚β‚„β‚Ž=(A₁A₁) ``` """ module Cosets using ..Chevie export twistings, spets, Frobenius, Spets, subspets, relative_coset, generic_sign, PhiOnDiscriminant, graph_automorphisms, CoxeterCoset, twisted_power abstract type Spets{T,TW}<:NormalCoset{T,TW} end abstract type CoxeterCoset{T,TW}<:Spets{T,TW} end extprod(W1::Spets,W2::Spets)=spets(W1.W*W2.W,cat(W1.F,W2.F,dims=(1,2))) extprod(W1::Spets,W2::FiniteCoxeterGroup)=extprod(W1,spets(W2)) extprod(W1::FiniteCoxeterGroup,W2::Spets)=extprod(spets(W1),W2) extprod(W1::FiniteCoxeterGroup,W2::FiniteCoxeterGroup)=W1*W2 function graph_automorphisms(W::FiniteCoxeterGroup,J::AbstractVector{<:Integer}) if isempty(J) return W end H=reflection_subgroup(W,J) if !isparabolic(W,H) return stabilizer(W,sort(inclusiongens(H)),onsets) end if issubset(inclusiongens(H),1:ngens(W)) p=one(W) else p=standard_parabolic(W,H); H=H^p end J=inclusiongens(H) C=collect(endomorphisms(CoxGroups.parabolic_category(W,J),1)) Group(C.^inv(p)) end twisting_elements(W::FiniteCoxeterGroup,J::AbstractVector{<:Integer})= classreps(graph_automorphisms(W,J)) function twisting_elements(WF::CoxeterCoset,J::AbstractVector{<:Integer}) if isempty(J) return classreps(WF)./WF.phi end if isone(WF.phi) return twisting_elements(Group(WF),J) end W=Group(WF) iJ=inclusion(W,J) h=transporting_elt(W,onsets(iJ,WF.phi),sort(iJ),onsets) if isnothing(h) println("\n# no subspets for ",J) return eltype(W)[] end W_L=stabilizer(W,sort(iJ),onsets) e=classreps(Group(vcat(gens(W_L),[WF.phi*h]))) res=filter(x->WF.phi*h*inv(x) in W_L,e).*inv(WF.phi) res end Groups.Group(WF::Spets)=WF.W @forward Spets.W PermRoot.inclusion, PermRoot.restriction, PermRoot.semisimplerank, PermRoot.rank Weyl.dimension(WF::CoxeterCoset)=dimension(WF.W) CoxGroups.word(WF::CoxeterCoset,w)=word(WF.W,w/WF.phi) """ `twistings(W,I)` `W` should be a complex reflection group. The function returns the list, up to `W`-conjugacy, of subspets of `W` whose group is `reflection_subgroup(W,I)` --- In the case of Weyl groups, it corresponds to representatives of the possible twisted forms of the reductive subgroup of maximal rank `L` defined by `reflection_subgroup(W,I)`. `W` could also be a coset `WΟ•`; then the subgroup `L` must be conjugate to `Ο•(L)` for a rational form to exist. If `Ο•` normalizes `L`, then the rational forms are classified by the the `Ο•`-classes of `N_W(L)/L`. ```julia-repl julia> W=coxgroup(:E,6) E₆ julia> WF=spets(W,Perm(1,6)*Perm(3,5)) Β²E₆ julia> twistings(W,2:5) 3-element Vector{Spets{FiniteCoxeterSubGroup{Perm{Int16},Int64}}}: Eβ‚†β‚β‚‚β‚ƒβ‚„β‚…β‚Ž=D₄Φ₁² Eβ‚†β‚β‚‚β‚ƒβ‚„β‚…β‚Ž=Β³D₄Φ₃ Eβ‚†β‚β‚‚β‚ƒβ‚„β‚…β‚Ž=Β²D₄Φ₁Φ₂ julia> twistings(WF,2:5) 3-element Vector{Spets{FiniteCoxeterSubGroup{Perm{Int16},Int64}}}: Β²Eβ‚†β‚β‚‚β‚…β‚„β‚ƒβ‚Ž=Β²Dβ‚„β‚β‚β‚„β‚ƒβ‚‚β‚ŽΞ¦β‚Ξ¦β‚‚ Β²Eβ‚†β‚β‚‚β‚…β‚„β‚ƒβ‚Ž=Β³Dβ‚„β‚β‚β‚„β‚ƒβ‚‚β‚ŽΞ¦β‚† Β²Eβ‚†β‚β‚‚β‚ƒβ‚„β‚…β‚Ž=Dβ‚„Ξ¦β‚‚Β² ``` """ function twistings(W,J::AbstractVector{<:Integer}) subspets.(Ref(W),Ref(J),twisting_elements(W,J)) end twistings(W,R::FiniteCoxeterGroup)=twistings(W,inclusiongens(R,W)) """ `graph_automorphisms(t::Vector{TypeIrred})` Given the `refltype` of a finite Coxeter group, returns the group of all Graph automorphisms of `t` as a group of permutations of `indices(t)`. ```julia-repl julia> W=coxgroup(:D,4) Dβ‚„ julia> graph_automorphisms(refltype(W*W)) Group((1,5)(2,6)(3,7)(4,8),(1,2),(1,4)) ``` """ function graph_automorphisms(t::Vector{TypeIrred}) gen=empty([Perm()]) for (n,t) in groupby(repr,t) for i in 1:length(t)-1 push!(gen,prod(Perm.(t[i].indices,t[i+1].indices))) end J=t[1].indices rk=length(J) if t[1].series==:A if rk>1 push!(gen,prod(i->Perm(J[i],J[rk+1-i]),1:div(rk,2))) end elseif t[1].series==:B && t[1].cartanType==root(2) push!(gen,Perm(J[1],J[2])) elseif t[1].series==:D push!(gen,Perm(J[1],J[2])) if rk==4 push!(gen,Perm(J[1],J[4])) end elseif t[1].series==:E && rk==6 push!(gen,Perm(J[1],J[6])*Perm(J[3],J[5])) elseif t[1].series==:F && t[1].cartanType==root(2) push!(gen,Perm(J[1],J[4])*Perm(J[2],J[3])) elseif t[1].series==:G && t[1].cartanType==root(3) push!(gen,Perm(J[1],J[2])) end end Group(gen) end graph_automorphisms(W::FiniteCoxeterGroup)= Group(map(g->PermX(W,reflrep(W,g)),gens(graph_automorphisms(refltype(W))))) """ `twistings(W)` `W` should be a Coxeter group which is not a proper reflection subgroup of another reflection group (so that `inclusion(W)==eachindex(roots(W))`). The function returns all `spets` representing twisted forms of algebraic groups of type `W`. ```julia-repl julia> twistings(coxgroup(:A,3)*coxgroup(:A,3)) 8-element Vector{Spets{FiniteCoxeterGroup{Perm{Int16},Int64}}}: A₃×A₃ A₃ײA₃ Β²A₃×A₃ Β²A₃ײA₃ (A₃A₃) Β²(A₃A₃) Β²(A₃A₃)β‚β‚β‚‚β‚ƒβ‚†β‚…β‚„β‚Ž (A₃A₃)β‚β‚β‚‚β‚ƒβ‚†β‚…β‚„β‚Ž julia> twistings(coxgroup(:D,4)) 6-element Vector{Spets{FiniteCoxeterGroup{Perm{Int16},Int64}}}: Dβ‚„ Β²Dβ‚„β‚β‚‚β‚„β‚ƒβ‚β‚Ž Β²Dβ‚„ Β³Dβ‚„ Β²Dβ‚„β‚β‚β‚„β‚ƒβ‚‚β‚Ž Β³Dβ‚„β‚β‚β‚„β‚ƒβ‚‚β‚Ž julia> W=rootdatum(:so,8) soβ‚ˆ julia> twistings(W) 2-element Vector{Spets{FiniteCoxeterGroup{Perm{Int16},Int64}}}: Dβ‚„ Β²Dβ‚„ ``` """ function twistings(W::FiniteCoxeterGroup) if W!=parent(W) error(W," must not be a proper subgroup of another reflection group") end l=elements(graph_automorphisms(refltype(W))) l=filter(y->all(isinteger,YMatrix(W.G,y)),l) spets.(Ref(W),l) end #function Groups.position_class(G::Coset,g) # if isone(G.phi) return position_class(G.W,g) end # findfirst(c->g in c,conjugacy_classes(G)) #end twisted_power(x,n,F::Function)=iszero(n) ? one(x) : x*F(twisted_power(x,n-1,F)) #-------------- finite coxeter cosets --------------------------------- @GapObj struct FCC{T,TW<:FiniteCoxeterGroup{T}}<:CoxeterCoset{T,TW} phi::T F::Matrix W::TW end function Base.show(io::IO,t::Type{FCC{T,TW}})where {T,TW} #function Base.show(io::IO,::MIME"text/plain",t::Type{FCC{T,TW}})where {T,TW} if get(io,:limit,true) print(io,"Spets{",TW,"}") else print(io,t) end end Groups.NormalCoset(W::FiniteCoxeterGroup,w::Perm=one(W))=spets(W,w) spets(phi,F::Matrix,W::FiniteCoxeterGroup,P::Dict{Symbol,Any})=FCC(phi,F,W,P) Base.parent(W::Spets)=get!(()->W,W,:parent) """ `spets(W::ComplexReflectionGroup, F::Matrix=I(rank(W)))` This function returns a or a `CoxeterCoset` or a `Spets`. `F` must be an invertible matrix, representing an automorphism of the vector space `V` of dimension of dimension `rank(W)` which for a finite Coxeter group induces an automorphism of the root system of `parent(W)`, or for a more general complex reflection group just stabilizes `W`. The returned struct has in particular the following fields: `.W`: the group `W` `.F`: the matrix acting on `V` which represents the unique element `phi` in `WF` which preserves the positive roots (for finite Coxeter groups) or some "canonical" representative of the coset for more general complex reflection groups. `.phi`: a `Perm`, the permutation of the roots of `W` induced by `.F` (for general complex reflection groups this may be a permutation up to scalars) (also for Coxeter groups the element of smallest length in the NormalCoset `W .phi`). In the first example we create a Coxeter coset corresponding to the general unitary group `GU_3(q)` over the finite field `FF(q)`. ```julia-repl julia> W=rootdatum(:gl,3) gl₃ julia> gu3=spets(W,-reflrep(W,W())) Β²Aβ‚‚Ξ¦β‚‚ julia> F4=coxgroup(:F,4);D4=reflection_subgroup(F4,[1,2,16,48]) Fβ‚„β‚β‚‰β€šβ‚‚β€šβ‚β€šβ‚β‚†β‚Ž=Dβ‚„β‚β‚ƒβ‚‚β‚β‚„β‚Ž julia> spets(D4,[1 0 0 0;0 1 2 0;0 0 0 1;0 0 -1 -1]) Fβ‚„β‚β‚‰β€šβ‚β‚†β€šβ‚β€šβ‚‚β‚Ž=Β³Dβ‚„β‚β‚ƒβ‚„β‚β‚‚β‚Ž ``` `spets(W::ComplexReflectionGroup,p::Perm)` In this version `F` is defined by the permutation of the simple roots it does. ```julia-repl julia> W=coxgroup(:A,3) A₃ julia> spets(W,Perm(1,3)) Β²A₃ ``` """ function spets(W::FiniteCoxeterGroup{Perm{T}},F::Matrix) where{T} perm=PermX(W.G,F) if isnothing(perm) error("matrix F must preserve the roots") end phi=reduced(W,perm) FCC(phi,F*reflrep(W,perm\phi),W,Dict{Symbol,Any}()) end function spets(W::FiniteCoxeterGroup{Perm{T}}) where{T} get!(W,:trivialspets)do FCC(Perm{T}(),reflrep(W,one(W)),W,Dict{Symbol,Any}()) end end spets(W::FiniteCoxeterGroup,w::Perm)=spets(W,reflrep(W,w)) PermRoot.radical(WF::CoxeterCoset)=torus(central_action(Group(WF),WF.F)) """ `torus(m::AbstractMatrix)` `m` should be a matrix of finite order. The function returns the coset `T` of the trivial group such that `T.F==m`. When `m` is integral his corresponds to an algebraic torus `𝐓 ` of rank `size(m,1)`, with an isogeny which acts by `m` on `X(𝐓)`. ```julia-repl julia> torus([0 -1;1 -1]) Φ₃ ``` """ Weyl.torus(m::AbstractMatrix)=spets(torus(size(m,1)),m) """ `torus(W,i)` where `W` is a `Spets` or a `ComplexReflectionGroup`. This returns the torus twisted by a representative of the `i`-th conjugacy class of `W`. This is the same as `twistings(W,Int[])[i]`. ```julia-repl julia> W=coxgroup(:A,3) A₃ julia> twistings(W,Int[]) 5-element Vector{Spets{FiniteCoxeterSubGroup{Perm{Int16},Int64}}}: Aβ‚ƒβ‚β‚Ž=Φ₁³ Aβ‚ƒβ‚β‚Ž=Φ₁²Φ₂ Aβ‚ƒβ‚β‚Ž=Φ₁Φ₂² Aβ‚ƒβ‚β‚Ž=Φ₁Φ₃ Aβ‚ƒβ‚β‚Ž=Ξ¦β‚‚Ξ¦β‚„ julia> torus(W,2) Aβ‚ƒβ‚β‚Ž=Φ₁²Φ₂ julia> WF=spets(W,Perm(1,3)) Β²A₃ julia> twistings(WF,Int[]) 5-element Vector{Spets{FiniteCoxeterSubGroup{Perm{Int16},Int64}}}: Β²Aβ‚ƒβ‚β‚Ž=Ξ¦β‚‚Β³ Β²Aβ‚ƒβ‚β‚Ž=Φ₁Φ₂² Β²Aβ‚ƒβ‚β‚Ž=Φ₁²Φ₂ Β²Aβ‚ƒβ‚β‚Ž=Φ₂Φ₆ Β²Aβ‚ƒβ‚β‚Ž=Φ₁Φ₄ julia> torus(WF,2) Β²Aβ‚ƒβ‚β‚Ž=Φ₁Φ₂² ``` """ Weyl.torus(W::Spets,i::Integer)=subspets(W,Int[],W.phi\classreps(W)[i]) Weyl.torus(W::ComplexReflectionGroup,i::Integer)=subspets(W,Int[],classreps(W)[i]) function Groups.elements(C::ConjugacyClass{T,TW})where {T,TW<:Spets} get!(C,:elements)do orbit(Group(C.G),C.representative) end end function PermRoot.generic_order(WF::Spets,q) if rank(Group(WF))==0 return one(q) end generic_sign(WF)*q^sum(x->x[1]+1,codegrees(WF))* prod(((d,e),)->1-q^d*conj(e),degrees(WF)) end function PhiOnDiscriminant(WF) tt=refltype(WF) isempty(tt) ? 1 : prod(t->haskey(t,:scalar) ? prod(t.scalar)^sum(degrees(t.orbit[1]).+codegrees(t.orbit[1])) : 1, tt) end generic_sign(WF)=(-1)^rank(Group(WF))* prod(last.(degrees(WF)))*conj(PhiOnDiscriminant(WF)) function PermRoot.refltype(WF::CoxeterCoset)::Vector{TypeIrred} get!(WF,:refltype)do W=Group(WF) t=refltype(W) c=map(x->indices(x),t) phires=Perm(action.(Ref(W),eachindex(roots(W)),WF.phi)) map(orbits(Perm(sort.(c),map(i->sort(i.^phires),c)),eachindex(c)))do c o=deepcopy(t[c]) J=indices(o[1]) twist=Perm(J,J.^(phires^length(c))) if o[1].series==:D && length(J)==4 if order(twist)==2 rf=reduce(vcat,cycles(twist)) o[1].indices=J[vcat(rf,[3],setdiff([1,2,4],rf))] elseif twist==Perm(1,4,2) o[1].indices=J[[1,4,3,2]] twist=Perm(1,2,4) end end for i in 2:length(c) o[i].indices=indices(o[i-1]).^phires end TypeIrred(Dict(:orbit=>o,:twist=>twist)) end end end function PermRoot.parabolic_reps(WF::CoxeterCoset,s) W=Group(WF) res=Vector{Int}[] for I in parabolic_reps(W,s) if sort(action.(Ref(W),I,WF.phi))==sort(I) push!(res,I) else c=filter(x->sort(action.(Ref(W),x,WF.phi))==sort(x), standard_parabolic_class(W,I)) if !isempty(c) push!(res,c[1]) end end end res end PermRoot.parabolic_reps(WF::Spets,s)=if !isone(WF.phi) error() else parabolic_reps(Group(WF),s) end function Base.show(io::IO, WF::Spets) if haskey(WF,:callname) if hasdecor(io) printTeX(io,WF.TeXcallname) else print(io,WF.callname) end return end W=Group(WF) if !hasdecor(io) print(io,"spets(",W,",",WF.phi,")") return end if get(io,:parent,true) if haskey(WF,:parent) n=inclusion(WF,indices(refltype(WF))) if n!=eachindex(gens(Group(WF.parent))) printTeX(io,"{",WF.parent,"}_{"*joindigits(n;always=true)*"}=") end elseif isdefined(W,:parent) n=inclusion(W,indices(refltype(WF))) if n!=eachindex(gens(W.parent)) printTeX(io,"{",W.parent,"}_{"*joindigits(n;always=true)*"}=") end end end show(io,refltype(WF)) t=CycPol(1,0,ModuleElt(map(x->x.r,torusfactors(WF)).=>1)) if !isone(t) show(io,t) elseif isempty(refltype(WF)) print(io,".") end end PermRoot.reflrep(WF::Spets,w)=WF.F*reflrep(Group(WF),WF.phi\w) function PermGroups.classreps(W::Spets) get!(W,:classreps)do map(x->x.representative,conjugacy_classes(W)) end end """ Frobenius(WF)(x,i=1) If `WF` is a Coxeter coset associated to the Coxeter group `W`, `Frobenius(WF)` returns a function `F` such that `x↦ F(x,i=1)` does the automorphism induced by `WF.phi^i` on the object `x`. ```julia-repl julia> W=coxgroup(:D,4) Dβ‚„ julia> WF=spets(W,Perm(1,2,4)) Β³Dβ‚„ julia> u=unichar(W,2) [Dβ‚„]:<11-> julia> F=Frobenius(WF);F(u) [Dβ‚„]:<.211> julia> F(u,-1) [Dβ‚„]:<11+> julia> F(1) 4 ``` """ function Frobenius(WF::CoxeterCoset) (w,i=1)->Frobenius(w,WF.phi^i) end Frobenius(w::Perm,phi)=w^(inv(phi)) Frobenius(w::Integer,phi)=w^(inv(phi)) function twisting_elements(WF::Spets,J::AbstractVector{<:Integer}) if isempty(J) return classreps(WF)./WF.phi end if !isone(WF.phi) error( "not implemented for twisted parent Spets" ) end twisting_elements(Group(WF),J) # W=Group(WF) # L=reflection_subgroup(W,J) # N=normalizer(W,L) # W_L=N/L # if length(W_L)>=10 # H=Group(map(x->central_action(L,reflrep(L,x.phi)),gens(W_L))) # if length(H)==length(W_L) # h=Hom(H,W_L,gens(W_L)) # e=classreps(H) # return map(x->h(x).phi,e) # end # end # sort(map(x->x.phi,classreps(W_L))) end function twisting_elements(W::PermRootGroup,J::AbstractVector{<:Integer}) if isempty(J) return classreps(W) end L=reflection_subgroup(W,J) N=normalizer(W,L) # W_L=C/N W_L=Group(gens(N))/Group(gens(L)) map(x->x.phi,classreps(W_L)) end function relative_coset(WF::CoxeterCoset,J) # Print("CoxeterCosetOps.RelativeCoset ",WF,J," called \n"); res=relative_group(Group(WF),J) spets(res,Perm(res.toparent,res.toparent.^WF.phi)) end #-------------- subcoset --------------------------------- """ `subspets(WF,I,w=one(Group(WF)))` Returns the reflection subcoset of the coset `WF` with group `reflection_subgroup(Group(WF),I)` and torsion `w*WF.phi`. `w` must be an element of `Group(WF)` such that `w*WF.phi` normalizes the subroot system generated by `I`. ```julia-repl julia> WF=spets(coxgroup(:F,4)) Fβ‚„ julia> w=transporting_elt(Group(WF),[1,2,9,16],[1,9,16,2],ontuples); julia> LF=subspets(WF,[1,2,9,16],w) Fβ‚„β‚β‚‰β€šβ‚β‚†β€šβ‚β€šβ‚‚β‚Ž=Β³Dβ‚„β‚β‚ƒβ‚„β‚β‚‚β‚Ž julia> diagram(LF) Ο• acts as (2,3,4) on the component below O 4 οΏ¨ Oβ€”Oβ€”O Dβ‚„ 3 1 2 ``` """ function subspets(WF::Spets,I::AbstractVector{<:Integer},w=one(Group(WF));NC=false) # xprintln("WF=",WF," I=",I," w=",w) W=Group(WF) if !(w in W) error(w," should be in ",W) end phi=w*WF.phi R=reflection_subgroup(W,I) if (W isa CoxeterGroup) && (sort(action.(Ref(R),1:2nref(R),phi))!=1:2nref(R)) error("w*WF.phi does not normalize subsystem") end phi=reduced(R,phi) if !(phi isa Perm) phi=phi.phi end if isone(phi) RF=spets(R) else RF=spets(phi,reflrep(WF,phi),R,Dict{Symbol,Any}()) end if R!==W RF.parent=WF end if !NC refltype(RF) end RF end PermRoot.reflection_subgroup(WF::Spets,I::AbstractVector{<:Integer})=subspets(WF,I) subspets(W::ComplexReflectionGroup,I::AbstractVector{<:Integer},w=one(W))=subspets(spets(W),I,w) #-------------- spets --------------------------------- @GapObj mutable struct PRC{T,TW<:PermRootGroup}<:Spets{T,TW} phi::T F::Matrix W::TW end function Base.show(io::IO,t::Type{PRC{T,TW}})where {T,TW} print(io,"Spets{",TW,"}") end function spets(W::PermRootGroup) get!(W,:trivialspets)do PRC(one(W),reflrep(W,one(W)),W,Dict{Symbol,Any}()) end end function spets(W::PermRootGroup,w::Perm;NC=false) if isone(w) return spets(W) end w=reduced(W,w) if !(w isa Perm) w=w.phi end F=reflrep(W,w) # println("w=$w\nF=$F") res=PRC(w,F,W,Dict{Symbol,Any}()) if !NC refltype(res) end # changes phi and F res end function spets(W::PermRootGroup,F::Matrix;NC=false) w=PermX(W,F) if !isnothing(w) return spets(W,w;NC) end # if W isa PRSG error("that's all for subgroups") end # check if there exists a permutation perm and for each W-orbit of roots O # a scalar l_O such that W.roots{O}*WF.F0Mat=l_O*W.roots{OnTuples(O,perm)} t=collectby(j->simple_reps(W)[j],eachindex(gens(W))) s=map(t)do inds scal=map(inds)do y r=transpose(F)*roots(W,y) scals=ratio.(Ref(r),roots(W)) l=filter(i->!isnothing(scals[i]),eachindex(roots(W))) (ind=l,scal=scals[l]) end if length(unique(map(x->unique(sort(x.scal)),scal)))>1 error("theory") end l=intersect(map(x->x.scal,scal)...) if isempty(l) return false end l=Root1.(l) if nothing in l error("only reflection cosets of finite order implemented") return false end # choose simplest scal l=minimum(map(x->[order(x),exponent(x)],l)) l=E(l[1],l[2]) [l,map(x->x.ind[findfirst(==(l),x.scal)],scal)] end if false in s ChevieErr("Spets(",W,",F=",FormatGAP(F), " must normalize set of roots of parent up to scalars.\n") return false end scalars=map(x->x[1],s)[simple_reps(W)[eachindex(gens(W))]] perm=fill(0,length(roots(W))) for i in eachindex(t) perm[t[i]]=s[i][2] end while true i=filter(j->!iszero(perm[j]),eachindex(perm)) if length(i)==length(perm) break end for j in eachindex(gens(W)) perm[i.^refls(W,j)].=perm[i].^refls(W,perm[j]) end end if length(unique(perm))<length(perm) return false end w=Perm(eltype(one(W)).(perm)) if isnothing(w) error("matrix F must preserve the roots") end res=PRC(w,F,W,Dict{Symbol,Any}(:scalars=>scalars)) end """ spets(s::String) builds a few of the exceptional spets ```julia-repl julia> spets("3G422") Β³Gβ‚„β€šβ‚‚β€šβ‚‚ julia> spets("2G5") Β²Gβ‚… julia> spets("3G333") Gβ‚ƒβ€šβ‚ƒβ€šβ‚ƒβ‚β‚β€šβ‚‚β€šβ‚ƒβ€šβ‚„β‚„β‚Ž=Β³Gβ‚ƒβ€šβ‚ƒβ€šβ‚ƒβ‚β‚β€šβ‚‚β€šβ‚ƒβ€šβ‚„β‚„β‚Ž julia> spets("3pG333") Gβ‚ƒβ€šβ‚ƒβ€šβ‚ƒβ‚β‚β€šβ‚‚β€šβ‚ƒβ€šβ‚„β‚„β‚Ž=Β³Gβ‚ƒβ€šβ‚ƒβ€šβ‚ƒβ‚β‚β€šβ‚‚β€šβ‚ƒβ€šβ‚„β‚„β‚Ž julia> spets("4G333") Gβ‚ƒβ€šβ‚ƒβ€šβ‚ƒβ‚β‚‚β€šβ‚β‚‚β€šβ‚β‚β€šβ‚β‚†β€šβ‚…β‚ƒβ€šβ‚β‚€β€šβ‚„β‚ƒβ€šβ‚ƒβ‚†β‚Ž=⁴Gβ‚ƒβ€šβ‚ƒβ€šβ‚ƒβ‚β‚β€šβ‚‚β€šβ‚ƒβ€šβ‚ƒβ‚‚β€šβ‚β‚†β€šβ‚ƒβ‚†β€šβ‚ƒβ‚€β€šβ‚β‚€β‚Ž ``` """ function spets(s::String;NC=false) if s=="3G422" W=PRG([2 (root(3)-1)E(3);2 (-1+root(3))E(3,2);2 root(3)-1].//1, [(3+root(3))//2 root(3)E(3,2);(3+root(3))//2 root(3)E(3);(3+root(3))//2 root(3)].//3) return spets(W,reflrep(W,Perm(1,2,3));NC) elseif s=="2G5" # reflection_subgroup(G14,[10,52]) W=PRG([[(-E(3)-2E(3,2))*(-3+root(6))//3,E(3)], [(-E(3)-2E(3,2))*(3-root(6))//3, E(3)]], [[E(3)//2,(-E(3)-2E(3,2))*(-3-root(6))//6], [-E(3)//2,(-E(3)-2E(3,2))*(-3-root(6))//6]]) return spets(W,[-1 0;0 1];NC) elseif s=="3G333" W=crg(3,3,3);return spets(reflection_subgroup(W,1:3),reflrep(W,Perm(1,2,44));NC) elseif s=="3pG333" W=crg(3,3,3);return spets(reflection_subgroup(W,1:3),reflrep(W,Perm(1,44,2));NC) elseif s=="4G333" W=crg(3,3,3) return spets(reflection_subgroup(W,1:3), perm"(1,44,32,37)(2,12,16,53)(3,50,30,15) ( 4,49,39,19)( 5, 9, 6,48)( 7,41,54,25)( 8,33,18,51)(10,43,36,11) (13,47,28,42)(14,52,22,17)(21,46,38,31)(24,27,26,40)";NC) elseif s=="3G422" W=PRG([[2,(-1+root(3))*E(3)],[2,(-1+root(3))*E(3,2)],[2,(-1+root(3))]], [[(3+root(3))//2,root(3)*E(3,2)],[(3+root(3))//2,root(3)*E(3)],[(3+root(3))//2,root(3)]]//3) return spets(W,[1 0;0 E(3)];NC) else error("argument should be 2G5, 3G422, 3G333, 3pG333 or 4G333") end end function relative_coset(WF::Spets,J=Int[],a...) # xprintln("relative_coset(",WF,",",J,")"); W=Group(WF) R=relative_group(W,J,a...) L=reflection_subgroup(W,J) res=spets(R,central_action(L,reflrep(L,WF.phi))) if isempty(J) Group(res).fromparent=R.fromparent # else Group(res).fromparent:=function(x)Error("fromparent failed");return false;end; end res end Groups.NormalCoset(W::PermRootGroup,w::Perm=one(W))=spets(W,w) spets(phi,F::Matrix,W::PermRootGroup,P::Dict{Symbol,Any})=PRC(phi,F,W,P) Groups.Group(W::PRC)=W.W isG333(t::TypeIrred)=haskey(t,:p) && (t.p,t.q,t.rank)==(3,3,3) function PermRoot.refltype(WF::PRC) get!(WF,:refltype)do W=Group(WF) t=deepcopy(refltype(W)) if isone(WF.phi) return map(x->TypeIrred(Dict(:orbit=>[x],:twist=>Perm())),t) end subgens=map(x->refls(W,x.indices),t) c=Perm(map(x->sort(x.^WF.phi),subgens),map(sort,subgens)) if isnothing(c) && any(isG333,t) for a in t if isG333(a) a.subgroup=reflection_subgroup(W,a.indices;NC=true) c=chevieget(:timp,:ReducedInRightCoset)(a.subgroup,WF.phi) WF.phi=c.phi c=restriction(W,c.gen) a.indices=c a.subgroup=reflection_subgroup(W,c;NC=true) WF.W=reflection_subgroup(W,indices(t);NC=true) W=WF.W if order(WF.phi) in [3,6] G333=[1,2,3,44] elseif order(WF.phi)==4 G333=[1,2,3,32,16,36,30,10] else G333=1:3 end a.subgens=refls(a.subgroup,G333) a.indices=inclusion(a.subgroup,W,G333) WF.W.refltype=t end end # subgens=map(x->gens(reflection_subgroup(W,x.indices)),t) subgens=map(x->refls(W,x.indices),t) c=Perm(map(x->sort(x.^WF.phi),subgens),map(sort,subgens)) end c=orbits(inv(c),eachindex(t)) prr=roots(parent(W)) function scals(rr,img) map(ratio,prr[inclusion(W,rr).^WF.phi],prr[inclusion(W,img)]) end typ=map(c) do orb to=TypeIrred(Dict{Symbol,Any}(:orbit=>map(copy,t[orb]))) scalar=Cyc{Rational{Int}}[] for i in eachindex(orb) next=i==length(orb) ? 1 : i+1 u=Perm(subgens[orb[next]],subgens[orb[i]].^WF.phi) tn=t[orb[next]] ti=t[orb[i]] if i!=length(orb) tn.indices=invpermute(tn.indices,u) scal=scals(ti.indices,tn.indices) else to.twist=u scal=scals(ti.indices,invpermute(tn.indices,inv(u))) end if any(isnothing,scal) || !allequal(scal) if ti.series==:B && ti.rank==2 scal=[root(prod(scal))] else println("W=$W\nphi=",WF.phi) error("scal=$scal :no element of coset acts as scalar on orbits") return nothing end end scal=Root1(scal[1]) if !isone(scal) sub=reflection_subgroup(W,ti.indices;NC=true) zg=center(sub) z=length(zg) # println("zg=$zg") if z>1 # simplify scalars using center ee=sort(elements(zg)) zg=ee[findfirst(x->order(x)==z,ee)] i=inclusion(sub)[1] v=Root1(ratio(prr[i.^zg],prr[i])) zg^=invmod(exponent(v),order(v)) # distinguished v=scal.*E.(z,0:z-1) m=argmin(order.(v)) Perms.mul!(WF.phi,(zg^(m-1))^WF.phi) WF.F=reflrep(Group(WF),WF.phi) scal=v[m] end # simplify again by -1 in types 2A(>1), 2D(odd), 2E6 if mod(order(scal),4)==2 && (ti.series in [:A,:D] || (ti.series==:E && ti.rank==6)) sb=coxgroup(ti.series,ti.rank) w0=sub(word(sb,longest(sb))...) Perms.mul!(WF.phi,w0) u=Perm(subgens[orb[next]],subgens[orb[i]].^WF.phi) #print("l=$l i=$i scal before:$scal") if i!=length(orb) tn.indices^=u subgens[orb[next]]=refls(W,tn.indices) scal=scals(ti.indices,tn.indices) else to.twist=u scal=scals(ti.indices,invpermute(tn.indices,inv(u))) end #println(" scal after:$scal") if !allequal(scal) error(" scal after:$scal") else scal=Root1(scal[1]) end end end push!(scalar,Cyc(scal)) end to.scalar=scalar to end # some adjustment such that in type ^2D_4 the first two simple # roots are permuted by res.twist, and in type ^3D_4 the permutation # of the simple roots is 1 -> 2 -> 4 -> 1: # in type 4G333 restore the indices to be in 1,2,3 typ=map(typ)do a i=a.orbit[1].indices b=a.orbit[1] if b.series==:D && b.rank==4 if order(a.twist)==2 # ^2D_4 rf=filter(x->refls(W,i[x])!=refls(W,i[x])^WF.phi,1:4) rf=vcat(rf,[3],setdiff([1,2,4],rf)) for j in a.orbit j.indices=j.indices[rf] end elseif order(a.twist)==3 # ^3D_4 if refls(W,i[1])^WF.phi!=refls(W,i[2]) for j in a.orbit j.indices=j.indices[[1,4,3,2]] end end end elseif isG333(b) # needless? if order(a.twist)==4 for j in a.orbit j.indices[2]=inclusion(j.subgroup,W,2) end end end a end end end #--------------------- Root data --------------------------------- Weyl.rootdatum(t::String,r::Int...)=rootdatum(Symbol(t),r...) """ `rootdatum(type::String or Symbol[,dimension or bond::Integer])` root datum from type. The known types are `2B2, 2E6, 2E6sc, 2F4, 2G2, 2I2, 3D4, 3D4sc, 3gpin8, CE6, CE7, E6, E6sc, E7, E7sc, E8, F4, G2, cso, csp, gl, gpin, gpin-, halfspin, pgl, pso, pso-, psp, psu, ree, sl, slmod, so, so-, sp, spin, spin-, su, suzuki, tgl, triality, u` """ function Weyl.rootdatum(t::Symbol,r::Int...) if haskey(rootdata,t) res=rootdata[t](r...) res.callname="rootdatum("*repr(t) if !isempty(r) res.callname*=","*join(r,",") end res.callname*=")" n=string(t) sc=endswith(n,"sc") if sc n=n[1:end-2] end pre=match(r"^[0-9]+",n) if !isnothing(pre) res.TeXcallname="{}^{"*pre.match*"}" else res.TeXcallname="" end mid=match(r"[a-zA-Z-]+",n) if !isnothing(mid) res.TeXcallname*=mid.match end las=match(r"[0-9]+$",n) if !isnothing(las) res.TeXcallname*="_{"*las.match*"}" end if !isempty(r) if mid.match=="I" res.TeXcallname*="("*join(r,",")*")" else res.TeXcallname*="_{"*join(r,",")*"}" end end if sc res.TeXcallname*="sc" end return res end error("Unknown root datum $t. Known types are:\n", sprint(cut,join(sort(collect(keys(rootdata))),", "))) end id(r)=Matrix{Int}(I,r,r) const rootdata=Dict{Symbol,Function}() rootdata[:gl]=function(r) if r==1 return torus(1) end R=id(r) R=R[1:end-1,:]-R[2:end,:] rootdatum(R,R) end rootdata[:sl]=r->rootdatum(cartan(:A,r-1),id(r-1)) rootdata[:slmod]=function(dim,q) if dim%q!=0 error(q," should divide ",dim) end intermediate_group(rootdata[:sl](dim),[q]) end rootdata[:tgl]=function(n, k) if gcd(n,k)!=1 error(k," should be prime to ",n) end X=hcat(cartan(:A,n-1),fill(0,n-1)) # We intertwine the last weight with the torus lat=vcat(X,transpose(vcat(fill(0,n-2), [k,1]))) # Get a basis for the sublattice lat=hermite(lat) # Find the roots in a basis of the sublattice Y=id(n)[1:n-1,:] rootdatum(toM(map(x->solutionmatInt(lat,x),toL(X))),Y*transpose(lat)) end rootdata[:pgl]=r->coxgroup(:A,r-1) rootdata[:sp]=function(r) r=div(r,2) R=id(r) for i in 2:r R[i,i-1]=-1 end R1=copy(R) R1[1,:].*=2 rootdatum(R1,R) end rootdata[:csp]=function(r) r=div(r,2) R=id(r+1) R=R[1:r,:]-R[2:end,:] cR=copy(R) R[1,1:2]=[0,-1] cR[1,1:2]=[1,-2] rootdatum(cR,R) end rootdata[:psp]=r->coxgroup(:C,div(r,2)) rootdata[:cso]=function(dim) n=div(dim,2) R=fill(0,n,n+1) cR=fill(0,n,n+1) R[1,1:3]=[1,-1,-1] cR[1,2:3]=[-1,-1] for i in 2:n R[i,i:i+1]=[1,-1] cR[i,i:i+1]=[1,-1] end rootdatum(R,cR) end rootdata[:so]=function(r) r1=div(r,2) R=id(r1) for i in 2:r1 R[i,i-1]=-1 end if isodd(r) R1=copy(R) R1[1,1]=2 rootdatum(R,R1) else R[1,2]=1 rootdatum(R,R) end end rootdata[:pso]=function(r) r1=div(r,2) isodd(r) ? coxgroup(:B,r1) : coxgroup(:D,r1) end rootdata[:spin]=function(r) r1=div(r,2) isodd(r) ? rootdatum(cartan(:C,r1),id(r1)) : rootdatum(cartan(:D,r1),id(r1)) end rootdata[:halfspin]=function(r) if !iszero(r%4) error("halfspin groups only exist in dimension 4r") end r=div(r,2) R=id(r) R[r,:]=vcat([-div(r,2),1-div(r,2)],2-r:1:-2,[2]) rootdatum(R,Int.(cartan(:D,r)*transpose(inv(Rational.(R))))) end rootdata[:gpin]=function(r) d=div(r,2) R=id(d+1) R=R[1:d,:]-R[2:end,:] cR=copy(R) if isodd(r) R[1,1]=0 cR[1,2]=-2 else R[1,3]=-1 cR[1,1:3]=[0,-1,-1] R=hcat(fill(0,d),R) cR=hcat(fill(0,d),cR) cR[1,1]=1 end rootdatum(R,cR) end rootdata[:E6]=()->coxgroup(:E,6) rootdata[:E7]=()->coxgroup(:E,7) rootdata[:CE6]=()->rootdatum([2 0 -1 0 0 0 1;0 2 0 -1 0 0 0;-1 0 2 -1 0 0 -1; 0 -1 -1 2 -1 0 0;0 0 0 -1 2 -1 1;0 0 0 0 -1 2 -1],id(7)[1:6,:]) rootdata[Symbol("2CE6")]=()->spets(rootdatum(:CE6),[0 0 0 0 0 1 0;0 1 0 0 0 0 0; 0 0 0 0 1 0 0;0 0 0 1 0 0 0;0 0 1 0 0 0 0;1 0 0 0 0 0 0;0 0 0 0 0 0 -1]) rootdata[:CE7]=()->rootdatum([0 2 -1 0 0 0 0 0;1 0 0 -1 0 0 0 0; 0 -1 2 -1 0 0 0 0;-1 0 -1 2 -1 0 0 0;1 0 0 -1 2 -1 0 0; -1 0 0 0 -1 2 -1 0;1 0 0 0 0 -1 2 0], [0 1 0 0 0 0 0 0;2 0 0 0 -1 0 -1 -1;0 0 1 0 0 0 0 0;0 0 0 1 0 0 0 0; 0 0 0 0 1 0 0 0;0 0 0 0 0 1 0 0;0 0 0 0 0 0 1 0]) rootdata[:E8]=()->coxgroup(:E,8) rootdata[:E6sc]=()->rootdatum(cartan(:E,6),id(6)) rootdata[:E7sc]=()->rootdatum(cartan(:E,7),id(7)) rootdata[:F4]=()->coxgroup(:F,4) rootdata[:G2]=()->coxgroup(:G,2) rootdata[:u]=r->spets(rootdatum(:gl,r),reverse(-id(r),dims=1)) rootdata[:su]=r->r==2 ? spets(rootdatum(:sl,r)) : spets(rootdatum(:sl,r),prod(i->Perm(i,r-i),1:div(r-1,2))) rootdata[:psu]=function(r)g=rootdatum(:pgl,r) r==2 ? g : spets(g,prod(i->Perm(i,r-i),1:div(r-1,2))) end rootdata[Symbol("3gpin8")]=()->spets(rootdatum(:gpin,8),[1 1 1 0 0 0; -2 0 -1 -1 -1 -1;-1 0 -1 0 0 -1;-1 0 -1 0 -1 0; -1 0 -1 -1 0 0;-1 -1 0 0 0 0]) rootdata[Symbol("gpin-")]=function(r) d=div(r,2) F=id(d+2) F[1,1:3]=[1,-1,1] F[1:d+2,2]=fill(-1,d+2) F[2:3,2:3]=-id(2) spets(rootdatum(:gpin,r),F) end rootdata[Symbol("so-")]=r->spets(rootdatum(:so,r),Perm(1,2)) rootdata[Symbol("pso-")]=r->spets(rootdatum(:pso,r),Perm(1,2)) rootdata[Symbol("spin-")]=r->spets(rootdatum(:spin,r),Perm(1,2)) rootdata[Symbol("2I2")]=e->spets(coxgroup(:Isym,2,e),Perm(1,2)) rootdata[:suzuki]=()->spets(coxgroup(:Bsym,2),Perm(1,2)) rootdata[Symbol("2B2")]=()->rootdatum(:suzuki) rootdata[:ree]=()->spets(coxgroup(:Gsym,2),Perm(1,2)) rootdata[Symbol("2G2")]=()->rootdatum(:ree) rootdata[:triality]=()->spets(coxgroup(:D,4),Perm(1,2,4)) rootdata[Symbol("3D4")]=()->rootdatum(:triality) rootdata[Symbol("3D4sc")]=()->spets(rootdatum(:spin,8),Perm(1,2,4)) rootdata[Symbol("2E6")]=()->spets(coxgroup(:E,6),Perm(1,6)*Perm(3,5)) rootdata[Symbol("2E6sc")]=()->spets(rootdatum(:E6sc),Perm(1,6)*Perm(3,5)) rootdata[Symbol("2F4")]=()->spets(coxgroup(:Fsym,4),Perm(1,4)*Perm(2,3)) end
Chevie
https://github.com/jmichel7/Chevie.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
31161
""" A suitable reference for the general theory of Coxeter groups is, for example, Bourbaki "Lie Groups and Lie Algebras" chapter 4. A *Coxeter group* is a group which has the presentation ``W=⟨S|(st)^{m(s,t)}=1\\text{ for }s,t∈ S⟩`` for some symmetric integer matrix `m(s,t)` called the *Coxeter matrix*, where `m(s,t)>1` for `sβ‰ t` and `m(s,s)=1`; `m(s,t)=∞` is allowed meaning there is no relation between `s` and `t`. It is true (but a non-trivial theorem) that in a Coxeter group the order of `st` is exactly `m(s,t)`, thus a Coxeter group is the same as a *Coxeter system*, that is a pair `(W,S)` of a group `W` and a set `SβŠ‚W` of involutions, such that the group is presented by generators `S` and relations describing the order of the product of two elements of `S`. A Coxeter group has a natural representation, its *reflection representation*, on a real vector space `V` of dimension `length(S)` (which is the *Coxeter rank* of W), where each element of `S` acts as a reflection; the faithfulness of this representation (a theorem of Tits) is the main argument to prove that the order of `st` is exactly `m(s,t)`. This representation is defined as follows on a space `V` with basis `{eβ‚›}` for `s∈ S`. The *cartan matrix* associated to the Coxeter matrix `m(s,t)` is the matrix `C` with entries `C(s,t)=-2cos(Ο€/m(s,t))`; we set `C(s,t)=-2` if `m(s,t)=∞`. Then the action of `s∈ S` on `V` is given by `s(eβ‚œ)=eβ‚œ-C(s,t)eβ‚›`. Thus, Coxeter groups are real reflection groups. The converse need not be true if the set of reflecting hyperplanes has bad topological properties, but it turns out that finite Coxeter groups are the same as finite real reflection groups. The possible Coxeter matrices for finite Coxeter groups have been completely classified, see [`Weyl`](@ref); the corresponding finite groups play a deep role in several areas of mathematics. Coxeter groups have a nice solution to the word problem. The *length* `l(w)` of an element `w∈ W` is the minimum number of elements of `S` of which it is a product (since the elements of `S` are involutions, we do not need inverses). An expression of `w` of minimum length is called a *reduced word* for `w`. The main property of reduced words is the *exchange lemma* which states that if `s₁…sβ‚–` is a reduced word for `w` (thus `k=l(w)`) and `s∈ S` is such that `l(sw)≀l(w)` then one of the `sα΅’` in the word for `w` can be deleted to obtain a reduced word for `sw`. Thus given `s∈ S` and `w∈ W`, either `l(sw)=l(w)+1` or `l(sw)=l(w)-1` and in the latter case we say that `s` belongs to the *left descent set* of `w`. Computing a reduced word for an element, and other word problems, are easy if we know how to multiply elements and know left descent sets. In each of the Coxeter groups that we implement, the left descent set is easy to compute (see for example [`coxeter_symmetric_group`](@ref) below), so this suggests how to deal with Coxeter groups generically: The type `CoxeterGroup` is an abstract type; an actual struct which implements it must define a function `isleftdescent(W,w,i)` which tells whether the `i`-th element of `S` is in the left descent set of `w`. the other functions needed in an instance of a Coxeter group are - `gens(W)` which returns the set `S` (the list of *Coxeter generators*) - `nref(W)` which returns the number of reflections of `W`, if `W` is finite or `nothing` if `W` is infinite. It should be noted that a Coxeter group can be *any* kind of group implementing the above functions. Because of the easy solution of the word problem in Coxeter groups, a convenient way to represent their elements is as words in the Coxeter generators, that is lists of integers in `1:length(S)`. The functions 'word' and 'W(...)' do the conversion between Coxeter words and elements of the group. # Examples ```julia-repl julia> W=coxsym(4) 𝔖 β‚„ julia> p=W(1,3,2,1,3) (1,4) julia> word(W,p) 5-element Vector{Int64}: 1 2 3 2 1 ``` We notice that the word we started with and the one that we ended up with, are not the same, even though they represent the same element of `W`. The reason is that there are several reduced words for an element of `W`. The function 'word' calculates a lexicographically smallest word for `w`. Below are some other possible computations using the same Coxeter group: ```julia-repl julia> word(W,longest(W)) # the (unique) longest element in W 6-element Vector{Int64}: 1 2 1 3 2 1 julia> w0=longest(W) (1,4)(2,3) julia> length(W,w0) 6 julia> map(w->word(W,w),refls(W,1:nref(W))) 6-element Vector{Vector{Int64}}: [1] [2] [3] [1, 2, 1] [2, 3, 2] [1, 2, 3, 2, 1] julia> [length(elements(W,i)) for i in 0:nref(W)] 7-element Vector{Int64}: 1 3 5 6 5 3 1 ``` The last list tells us that there is 1 element of length 0, there are 6 of length 3, … For most basic functions the convention is that the input is an element of the group, rather than a Coxeter word. The reason for this is that for a Coxeter group which is a permutation group, using the low level functions for permutations is usually much faster than manipulating lists representing reduced expressions. The only Coxeter group constructors implemented in this module are `coxsym` and `coxgroup`; the last constructor takes a Cartan matrix and builds the corresponding Coxeter group as a matrix group. The module [`Weyl`](@ref) defines other methods for `coxgroup` building a finite Coxeter group as a permutation group, given its type. """ module CoxGroups export bruhatless, CoxeterGroup, firstleftdescent, leftdescents, isleftdescent, isrightdescent, longest, braid_relations, coxeter_matrix, coxmat, coxeter_symmetric_group, coxsym, CoxSym, coxeter_hyperoctaedral_group, coxhyp, CoxHyp, coxeter_group, coxgroup, standard_parabolic_class, inversions, degrees, FiniteCoxeterGroup using ..Chevie #-------------------------- Coxeter groups abstract type CoxeterGroup{T}<:Group{T} end """ `firstleftdescent(W,w)` returns the index in `gens(W)` of the first element of the left descent set of `w` --- that is, the first `i` such that if `s=W(i)` then `l(sw)<l(w). It returns `nothing` for `one(W)`. ```julia-repl julia> W=coxsym(3) 𝔖 ₃ julia> firstleftdescent(W,Perm(2,3)) 2 ``` """ function firstleftdescent(W::CoxeterGroup{T},w::T)where T findfirst(i->isleftdescent(W,w,i),eachindex(gens(W)::Vector{T})) end """ `leftdescents(W,w)` The left descents of the element `w` of the Coxeter group `W`, that is the set of `i` such that `length(W,W(i)*w)<length(W,w)`. ```julia-repl julia> W=coxsym(3) 𝔖 ₃ julia> leftdescents(W,Perm(1,3)) 2-element Vector{Int64}: 1 2 ``` """ function leftdescents(W::CoxeterGroup,w) filter(i->isleftdescent(W,w,i),eachindex(gens(W))) end isrightdescent(W::CoxeterGroup,w,i)=isleftdescent(W,inv(w),i) """ `word(W::CoxeterGroup,w)` returns a reduced word in the standard generators of the Coxeter group `W` for the element `w` (represented as the vector of the corresponding generator indices). ```julia-repl julia> W=coxgroup(:A,3) A₃ julia> w=perm"(1,11)(3,10)(4,9)(5,7)(6,12)" (1,11)(3,10)(4,9)(5,7)(6,12) julia> w in W true julia> word(W,w) 5-element Vector{Int64}: 1 2 3 2 1 ``` The result of Β `word` is the lexicographically smallest reduced word for `w` (for the ordering of the Coxeter generators given by `gens(W)`). """ function Groups.word(W::CoxeterGroup{T},w)where T ww=Int[] while true i=firstleftdescent(W,w) if i===nothing return ww end push!(ww,i) w=(gens(W)::Vector{T})[i]*w end end """ `length(W::CoxeterGroup ,w)` returns the length of a reduced expression in the Coxeter generators of the element `w` of `W`. ```julia-repl julia> W=coxsym(4) 𝔖 β‚„ julia> p=W(1,2,3,1,2,3) (1,3)(2,4) julia> length(W,p) 4 julia> word(W,p) 4-element Vector{Int64}: 2 1 3 2 ``` """ Base.length(W::CoxeterGroup,w)=length(word(W,w)) PermRoot.semisimplerank(W::CoxeterGroup)=ngens(W) """ `reduced(W,w)` The unique element of minimal length in the coset W.w. This makes sense when `isleftdescent(W,u)` makes sense for `u∈ W.w` which happens when `w` is a Coxeter automorphism of `W` or when `w` lives in a Coxeter overgroup of `W`. ```julia-repl julia> W=coxgroup(:G,2) Gβ‚‚ julia> H=reflection_subgroup(W,[2,6]) Gβ‚‚β‚β‚‚β‚†β‚Ž=Ã₁×A₁ julia> word.(Ref(W),unique(reduced.(Ref(H),elements(W)))) 3-element Vector{Vector{Int64}}: [] [1] [1, 2] ``` """ function PermGroups.reduced(W::CoxeterGroup,w) while true i=firstleftdescent(W,w) if i===nothing return w end w=W(i)*w end end """ `reduced(H::CoxeterGroup,W::CoxeterGroup,i=nref(W))` The elements `w∈ W` which are `H`-reduced, and of length `≀i` (by default all of them), grouped by length. ```julia-repl julia> W=coxgroup(:G,2) Gβ‚‚ julia> H=reflection_subgroup(W,[2,6]) Gβ‚‚β‚β‚‚β‚†β‚Ž=Ã₁×A₁ julia> [word(W,w) for S in reduced(H,W) for w in S] 3-element Vector{Vector{Int64}}: [] [1] [1, 2] ``` """ function PermGroups.reduced(H::CoxeterGroup,W::CoxeterGroup,i::Integer=nref(W)) res=[[one(W)]] while length(res)<=i new=reducedfrom(H,W,res[end]) if isempty(new) break else push!(res,new) end end vcat(res) end #reduced(H,W,S) # The elements in `W` which are `H`-reduced of length `i` given the set `S` # of those of length `i-1` function reducedfrom(H::CoxeterGroup,W::CoxeterGroup,S) res=empty(S) for w in S for i in eachindex(gens(W)) if !isrightdescent(W,w,i) w1=w*W(i) if w1==reduced(H,w1) push!(res,w1) end end end end unique(res) end maxpara(W::CoxeterGroup)=2:ngens(W) """ `elements(W::CoxeterGroup[,l])` When `l` is not given this works only if `W` is finite; it returns the elements of `W` sorted by increasing Coxeter length. If the second argument is an integer `l`, the elements of `W` of Coxeter length `l` are returned. ```julia_repl julia> W=coxgroup(:G,2) Gβ‚‚ julia> e=elements(W,6) 1-element Vector{Perm{Int16}}: (1,7)(2,8)(3,9)(4,10)(5,11)(6,12) julia> e[1]==longest(W) true ``` """ function Groups.elements(W::CoxeterGroup{T}, l::Int)::Vector{T} where T elts=get!(()->OrderedDict(0=>[one(W)]),W,:elements)::OrderedDict{Int,Vector{T}} get!(elts,l)do if ngens(W)==1 return l>1 ? T[] : gens(W) end if isfinite(W) H=get!(()->reflection_subgroup(W,maxpara(W)),W,:maxpara)::CoxeterGroup{T} rc=get!(()->[[one(W)]],W,:rc)::Vector{Vector{T}} while length(rc)<=l new=reducedfrom(H,W,rc[end]) if isempty(new) break else push!(rc,new) end end # @show l,W,H,rc v=T[] for i in max(0,l+1-length(rc)):l, x in rc[1+l-i] append!(v,elements(H,i).*Ref(x)) end # if applicable(nref,W) # this does not reduce much time # N=nref(W) # if N-l>l && !haskey(elts,N-l) elts[N-l]=elts[l].*longest(W) end # end v else if l==1 return gens(W) end v=elements(W,l-1) res=Set(empty(v)) for e in v, i in 1:ngens(W) if !isleftdescent(W,e,i) push!(res,W(i)*e) end end collect(res) end end end function Groups.elements(W::CoxeterGroup,I::AbstractVector{<:Integer}) reduce(vcat,map(i->elements(W,i),I)) end function Groups.elements(W::CoxeterGroup) if isfinite(W) return elements(W,0:nref(W)) else error(W," is infinite") end end PermRoot.nref(W::CoxeterGroup)=length(W,longest(W)) const wordtype=Vector{Int8} function Groups.words(W::CoxeterGroup{T}, l::Integer)where T if !isfinite(W) return word.(Ref(W),elements(W,l)) end ww=get!(W,:words)do OrderedDict(0=>[wordtype([])]) end::OrderedDict{Int,Vector{wordtype}} if haskey(ww,l) return ww[l] end if ngens(W)==1 if l!=1 return Vector{Int}[] else return [[1]] end end H=get!(()->reflection_subgroup(W,maxpara(W))::CoxeterGroup{T},W,:maxpara) rc=get!(()->[[wordtype([])]]::Vector{Vector{wordtype}},W,:rcwords) while length(rc)<=l new=reducedfrom(H,W,(x->W(x...)).(rc[end])) if isempty(new) break else push!(rc,wordtype.(word.(Ref(W),new))) end end ww[l]=wordtype([]) d=inclusiongens(H) for i in max(0,l+1-length(rc)):l e=words(H,i) for x in rc[1+l-i], w in e push!(ww[l],vcat(d[w],x)) end # somewhat slower variant # for x in rc[1+l-i] append!(ww[l],vcat.(e,Ref(x))) end end ww[l] end """ `words(W::CoxeterGroup[,l::Integer])` With one argument this works only if `W` is finite; it returns the reduced Coxeter words of elements of `W` by increasing length. If the second argument is an integer `l`, only the elements of length `l` are returned; this works for infinite Coxeter groups. ```julia_repl julia> W=coxgroup(:G,2) Gβ‚‚ julia> e=elements(W,6) 1-element Vector{Perm{Int16}}: (1,7)(2,8)(3,9)(4,10)(5,11)(6,12) julia> e[1]==longest(W) true ``` """ function Groups.words(W::CoxeterGroup) reduce(vcat,map(i->words(W,i),0:nref(W))) end """ `bruhatless(W, x, y)` whether `x≀y` in the Bruhat order, for `x,y∈ W`. We have `x≀y` if a reduced expression for `x` can be extracted from one for `w`. See [(5.9) and (5.10) Humphreys1990](biblio.htm#Hum90) for properties of the Bruhat order. ```julia-repl julia> W=coxgroup(:H,3) H₃ julia> w=W(1,2,1,3); julia> b=filter(x->bruhatless(W,x,w),elements(W)); julia> word.(Ref(W),b) 12-element Vector{Vector{Int64}}: [] [1] [2] [3] [1, 2] [2, 1] [1, 3] [2, 3] [1, 2, 1] [1, 2, 3] [2, 1, 3] [1, 2, 1, 3] ``` """ function bruhatless(W::CoxeterGroup,x,y) if x==one(W) return true end d=length(W,y)-length(W,x) while d>0 i=firstleftdescent(W,y) s=W(i) if isleftdescent(W,x,i) if x==s return true end x=s*x else d-=1 end y=s*y end return x==y end """ `bruhatless(W, y)` returns a vector whose `i`-th element is the vector of elements of `W` smaller for the Bruhat order than `w` and of Coxeter length `i-1`. Thus the first element of the returned list contains only `one(W)` and the `length(W,w)`-th element contains only `w`. ```julia-repl julia> W=coxsym(3) 𝔖 ₃ julia> bruhatless(W,Perm(1,3)) 4-element Vector{Vector{Perm{Int16}}}: [()] [(1,2), (2,3)] [(1,2,3), (1,3,2)] [(1,3)] ``` see also [`Poset`](@ref) for Coxeter groups. """ function bruhatless(W::CoxeterGroup,w) if w==one(W) return [[w]] end i=firstleftdescent(W,w) s=W(i) res=bruhatless(W,s*w) for j in 1:length(res)-1 res[j+1]=union(res[j+1],Ref(s).*filter(x->!isleftdescent(W,x,i),res[j])) end push!(res,Ref(s).*filter(x->!isleftdescent(W,x,i),res[end])) end """ `Poset(W::CoxeterGroup,w=longest(W))` returns as a poset the Bruhat interval `[1,w]`of `W`. If `w` is not given, the whole Bruhat Poset of `W` is returned (`W` must then be finite). ```julia-repl julia> W=coxsym(3) 𝔖 ₃ julia> Poset(W) .<1,2<21,12<121 ``` The above poset is constructed efficiently by constructing the Hasse diagram, but it could be constructed naively as follows: ```julia-repl julia> p=Poset((x,y)->bruhatless(W,x,y),elements(W)) ()<(1,2),(2,3)<(1,3,2),(1,2,3)<(1,3) ``` The output is not so nice, showing permutations instead of words. This can be fixed by defining: ```julia-repl julia> p.show_element=(io,x,n)->join(io,word(W,x.elements[n])); julia> p <1,2<12,21<121 julia> W=coxsym(4) 𝔖 β‚„ julia> Poset(W,W(1,3)) .<3,1<13 ``` """ function FinitePosets.Poset(W::CoxeterGroup,w=longest(W)) if w==one(W) p=Poset(CPoset([Int[]]),[w],Dict(:action=>map(x->[0],gens(W)), :W=>W)) else s=firstleftdescent(W,w) p=Poset(W,W(s)*w) l=length(p) # action: the Cayley graph: for generator i, action[i][w]=sw # where w and sw are represented by their index in :elements new=filter(k->iszero(p.action[s][k]),1:l) append!(p.elements,Ref(W(s)).*p.elements[new]) append!(hasse(p),map(x->Int[],new)) p.action[s][new]=l.+(1:length(new)) for i in eachindex(gens(W)) append!(p.action[i],i==s ? new : fill(0,length(new))) end for i in 1:length(new) push!(hasse(p)[new[i]],l+i) end for i in 1:l j=p.action[s][i] if j>i for h in p.action[s][hasse(p)[i]] if h>l push!(hasse(p)[j],h) k=findfirst(==(p.elements[h]/p.elements[j]),gens(W)) if k!==nothing p.action[k][j]=h;p.action[k][h]=j end end end end end end p.show_element=(io,x,n)->(e=x.elements[n];print(io,isone(e) ? "." : joindigits(word(W,e)))) p end """ `words(W::CoxeterGroup,w)` returns the list of all reduced expressions of the element `w` of the Coxeter group `W`. ```julia-repl julia> W=coxgroup(:A,3) A₃ julia> words(W,longest(W)) 16-element Vector{Vector{Int64}}: [1, 2, 1, 3, 2, 1] [1, 2, 3, 1, 2, 1] [1, 2, 3, 2, 1, 2] [1, 3, 2, 1, 3, 2] [1, 3, 2, 3, 1, 2] [2, 1, 2, 3, 2, 1] [2, 1, 3, 2, 1, 3] [2, 1, 3, 2, 3, 1] [2, 3, 1, 2, 1, 3] [2, 3, 1, 2, 3, 1] [2, 3, 2, 1, 2, 3] [3, 1, 2, 1, 3, 2] [3, 1, 2, 3, 1, 2] [3, 2, 1, 2, 3, 2] [3, 2, 1, 3, 2, 3] [3, 2, 3, 1, 2, 3] ``` """ function Groups.words(W::CoxeterGroup{T},w::T)where T if isone(w) return [Int[]] end reduce(vcat,map(x->pushfirst!.(words(W,W(x)*w),x),leftdescents(W,w))) end """ `inversions(W,w)` Returns the inversions of the element `w` of the finite Coxeter group `W`, that is, the list of the indices of reflections `r` of `W` such that `l(rw)<l(w)` where `l` is the Coxeter length. ```julia-repl julia> W=coxgroup(:A,3) A₃ julia> inversions(W,W(1,2,1)) 3-element Vector{Int64}: 1 2 4 ``` """ inversions(W::CoxeterGroup,w)=filter(x->isleftdescent(W,w,x),1:nref(W)) # assumes isleftdescent works for all reflections function parabolic_category(W,I::AbstractVector{<:Integer}) Category(sort(I);action=(J,e)->sort!(action.(Ref(W),J,e)))do J map(setdiff(1:ngens(W),J)) do i longest(W,J)*longest(W,push!(copy(J),i)) end end end """ `standard_parabolic_class(W,I)` `I` should be a subset of `eachindex(gens(W))`. The function returns the list of such subsets `W`-conjugate to `I`. ```julia-repl julia> CoxGroups.standard_parabolic_class(coxgroup(:E,8),[7,8]) 7-element Vector{Vector{Int64}}: [7, 8] [6, 7] [5, 6] [4, 5] [2, 4] [3, 4] [1, 3] ``` """ standard_parabolic_class(W,I::Vector{Int})=parabolic_category(W,I).obj # representatives of parabolic classes function PermRoot.parabolic_reps(W::CoxeterGroup,s) l=combinations(1:ngens(W),s) res=Vector{Int}[] while !isempty(l) o=standard_parabolic_class(W,first(l)) push!(res,first(o)) l=setdiff(l,o) end res end """ `coxeter_matrix(m::AbstractMatrix)` or `coxmat` returns the Coxeter matrix of the Coxeter group defined by the cartan matrix `m` ```julia-repl julia> C=cartan(:H,3) 3Γ—3 Matrix{Cyc{Int64}}: 2 ΞΆβ‚…Β²+ΞΆβ‚…Β³ 0 ΞΆβ‚…Β²+ΞΆβ‚…Β³ 2 -1 0 -1 2 julia> coxmat(C) 3Γ—3 Matrix{Int64}: 1 5 2 5 1 3 2 3 1 ``` """ function coxeter_matrix(m::AbstractMatrix) function find(c) if c in 0:4 return [2,3,4,6,0][Int(c)+1] end x=conductor(c) if c==2+E(x)+E(x,-1) return x elseif c==2+E(2x)+E(2x,-1) return 2x else error("not a Cartan matrix of a Coxeter group") end end res=Int.([i==j for i in axes(m,1), j in axes(m,2)]) for i in 2:size(m,1), j in 1:i-1 res[i,j]=res[j,i]=find(m[i,j]*m[j,i]) end res end """ `coxeter_matrix(W)` or `coxmat` returns the Coxeter matrix of the Coxeter group `W`, that is the matrix `m` whose entry `m[i,j]` contains the order of `W(i)*W(j)` where `W(i)` is the `i`-th Coxeter generator of `W`. An infinite order is represented by the entry `0`. ```julia-repl julia> W=coxsym(4) 𝔖 β‚„ julia> coxmat(W) 3Γ—3 Matrix{Int64}: 1 3 2 3 1 3 2 3 1 ``` """ coxeter_matrix(W::CoxeterGroup)=coxeter_matrix(cartan(W)) const coxmat=coxeter_matrix """ `braid_relations(W)` this function returns the relations which present the braid group of the reflection group `W`. These are homogeneous (both sides of the same length) relations between generators in bijection with the generating reflections of `W`. A presentation of `W` is obtained by adding relations specifying the order of the generators. ```julia-repl julia> W=complex_reflection_group(29) G₂₉ julia> braid_relations(W) 7-element Vector{Tuple{Vector{Int64}, Vector{Int64}}}: ([1, 2, 1], [2, 1, 2]) ([2, 4, 2], [4, 2, 4]) ([3, 4, 3], [4, 3, 4]) ([2, 3, 2, 3], [3, 2, 3, 2]) ([1, 3], [3, 1]) ([1, 4], [4, 1]) ([4, 3, 2, 4, 3, 2], [3, 2, 4, 3, 2, 4]) ``` each relation is represented as a pair of lists, specifying that the product of the generators according to the indices on the left side is equal to the product according to the indices on the right side. See also `diagram`. """ function braid_relations(t::TypeIrred) r=if t.series==:ST Tuple.(getchev(t,:BraidRelations)) else m=coxmat(cartan(t)) p(i,j)=map(k->iszero(k%2) ? j : i,1:m[i,j]) vcat(map(i->map(j->(p(i,j),p(j,i)),1:i-1),axes(m,1))...) end haskey(t,:indices) ? map(x->map(y->t.indices[y],x),r) : r end braid_relations(W::Group)=vcat(braid_relations.(refltype(W))...) # construct Coxeter generators and rootinclusion of reflection subgroup # defined by J by Dyer's method. function dyer(W,J) refs=refls(W,J) refs=vcat(orbits(Group(refs),refs)...) inc=Int.(indexin(refs,refls(W))) gens=filter(t->count(s->isrightdescent(W,refls(W,t),s),inc)==1,inc) gens=sort(gens) (gens=gens,rootinclusion=vcat(gens,sort(setdiff(inc,gens)))) end """ `longest(W)` If `W` is finite, returns the unique element of maximal length of the Coxeter group `W`. May loop infinitely otherwise. ```julia-repl julia> longest(coxsym(4)) (1,4)(2,3) ``` `longest(W,I)` returns the longest element of the parabolic subgroup of `W` generated by the generating reflections of indices in `I`. ```julia-repl julia> longest(coxsym(4)) (1,4)(2,3) ``` """ function longest(W::CoxeterGroup,I::AbstractVector{<:Integer}=eachindex(gens(W))) if length(I)==ngens(W) && !isfinite(W) error(W," must be finite") end w=one(W) i=1 while i<=length(I) if isleftdescent(W,w,I[i]) i+=1 else w=W(I[i])*w i=1 end end w end abstract type FiniteCoxeterGroup{T} <: CoxeterGroup{T} end # FiniteCoxeterGroup should be derived from PermGroup and CoxeterGroup. # Since such inheritance is impossible in Julia, we have to choose. We # derive it from CoxeterGroup and represent the other inheritance by # composition. Thus, implementations of FiniteCoxeterGroups have a field # .G, a PermGroup, to which we forward the following methods. @forward FiniteCoxeterGroup.G Base.iterate, Base.one, Groups.gens, Groups.conjugacy_classes, PermGroups.classreps Groups.transporting_elt(W::FiniteCoxeterGroup,x,y,F::Function)= transporting_elt(W.G,x,y,F) Base.hash(W::FiniteCoxeterGroup,i::UInt64)=hash(W.G,i) PermGroups.orbit(W::FiniteCoxeterGroup,p,F::Function)=orbit(W.G,p,F) PermGroups.orbits(W::FiniteCoxeterGroup,v,F::Function=^)=orbits(W.G,v,F) PermGroups.orbits(W::FiniteCoxeterGroup)=orbits(W.G) PermGroups.stabilizer(W::FiniteCoxeterGroup,p,F::Function)=stabilizer(W.G,p,F) PermGroups.stabilizer(W::FiniteCoxeterGroup,p,::typeof(ontuples))=stabilizer(W.G,p,ontuples) Base.isfinite(W::FiniteCoxeterGroup)=true #--------------------- CoxSym --------------------------------- @GapObj struct CoxSym{T} <: FiniteCoxeterGroup{Perm{T}} G::PermGroup{T} inversions::Vector{Tuple{Int,Int}} refls::Vector{Perm{T}} d::UnitRange{Int} end """ `coxeter_symmetric_group(n::Integer)` or `coxeter_symmetric_group(m:n)` or `coxsym` The symmetric group on the letters `1:n` (or if a `m≀n` is given, on the letters `m:n`) as a Coxeter group. The Coxeter generators are the `Perm(i,i+1)` for `i` in `m:n-1`. ```julia-repl julia> W=coxsym(3) 𝔖 ₃ julia> gens(W) 2-element Vector{Perm{Int16}}: (1,2) (2,3) julia> e=elements(W) 6-element Vector{Perm{Int16}}: () (1,2) (2,3) (1,3,2) (1,2,3) (1,3) julia> length.(Ref(W),e) # length in the genrators of the elements 6-element Vector{Int64}: 0 1 1 2 2 3 ``` """ coxeter_symmetric_group(n::Int)=coxeter_symmetric_group(1:n) const coxsym=coxeter_symmetric_group function coxsym(d::UnitRange,n=d.stop) gens=map(i->Perm(i,i+1;degree=n),d.start:d.stop-1) inversions=[(i,i+k) for k in 1:length(d)-1 for i in d.start:d.stop-k] refs=[Perm(r...;degree=n) for r in inversions] append!(refs,refs) CoxSym(Group(gens,one(prod(gens))),inversions,refs,d,Dict{Symbol,Any}()) end function Base.show(io::IO, W::CoxSym) if W.d.start==1 n=string(W.d.stop) else n=string(W.d) end if hasdecor(io) printTeX(io,"\\mathfrak S_{$n}") else print(io,"coxsym($n)") end end PermRoot.action(W::CoxSym,i,p)=i^p PermRoot.refltype(W::CoxSym)=get!(W,:refltype)do [TypeIrred(Dict(:series=>:A,:indices=>collect(1:length(W.d)-1)))] end PermRoot.inclusiongens(W::CoxSym)=W.d Groups.classreps(W::CoxSym)=map(x->W(x...),classinfo(W).classtext) Perms.reflength(W::CoxSym,a)=reflength(a) PermRoot.nref(W::CoxSym)=length(W.inversions) function PermRoot.simple_reps(W::CoxSym) get!(W,:simple_reps)do W.unique_refls=collect(1:nref(W)) fill(1,length(W.refls)) end::Vector{Int} end PermRoot.refls(W::CoxSym)=W.refls PermRoot.rank(W::CoxSym)=ngens(W)+1 PermRoot.reflrep(W::CoxSym,w::Perm)=Matrix(w,rank(W)) PermRoot.reflrep(W::CoxSym,i::Integer)=Matrix(W(i),rank(W)) PermRoot.reflrep(W::CoxSym)=reflrep.(Ref(W),1:ngens(W)) """ `isleftdescent(W::CoxeterGroup,w,i::Integer)` returns `true` iff the `i`-th generating reflection of the Coxeter group `W` is in the left descent set of the element `w` of `W`, that is iff `length(W,W(i)*w)<length(W,w)`. ```julia-repl julia> W=coxsym(3) 𝔖 ₃ julia> isleftdescent(W,Perm(1,2),1) true ``` """ function isleftdescent(W::CoxSym,w,i::Integer) j,k=W.inversions[i] j^w>k^w end """ `isrightdescent(W::CoxeterGroup,w,i::Integer)` returns `true` iff the `i`-th generating reflection of the Coxeter group `W` is in the right descent set of the element `w` of `W`, that is iff `length(W,w*W(i))<length(W,w)`. ```julia-repl julia> W=coxsym(3) 𝔖 ₃ julia> isrightdescent(W,Perm(1,2),1) true ``` """ function isrightdescent(W::CoxSym,w,i::Integer) j,k=W.inversions[i] preimage(j,w)>preimage(k,w) end """ `cartan(W::CoxeterGroup)` The Cartan matrix of `W`. """ PermRoot.cartan(W::CoxSym)=cartan(:A,ngens(W)) # for reflection_subgroups note the difference with Chevie: # leftdescents, rightdescents, word use indices in W and not in parent(W) """ `reflection_subgroup(W::CoxSym,I)` The only reflection subgroups defined for `coxsym(n)` are for `I=1:m` for `m≀n` """ function PermRoot.reflection_subgroup(W::CoxSym,I::AbstractVector{Int}) if sort(I)!=minimum(I):maximum(I) error(I," should be a:b for some a,b") end if W.d.start+maximum(I)>W.d.stop error("range too large") end coxsym(W.d.start.+(minimum(I)-1:maximum(I)),W.d.stop) end #------------ Example II: HyperOctaedral groups as Coxeter groups @GapObj struct CoxHyp{T} <: FiniteCoxeterGroup{SPerm{T}} G::SPermGroup{T} roots::Vector{Tuple{T,T}} n::Int end Groups.gens(W::CoxHyp)=gens(W.G) """ `coxeter_hyperoctaedral_group(n)` or `coxhyp(n)` The Hyperoctaedral group (the group of all signed permutations of Β±1,…,Β±n) as a Coxeter group of type `Bβ‚™`, with generators `(1,-1)` and `(i,i+1)(-i,-i-1)`. ```julia-repl julia> elements(coxhyp(2)) 8-element Vector{SPerm{Int8}}: () (1,2) (1,-1) (1,2,-1,-2) (1,-2,-1,2) (2,-2) (1,-2) (1,-1)(2,-2) ``` """ function coxeter_hyperoctaedral_group(n::Int) roots=Tuple{Int8,Int8}[(1,-1)] append!(roots,map(i->(i-1,i),2:n)) append!(roots,map(i->(i,-i),2:n)) for i in 2:n-1 append!(roots,map(j->(j,j+i),1:n-i)) end for i in 1:n-1 append!(roots,map(j->(j,-j-i),1:n-i)) end append!(roots,roots) CoxHyp{Int8}(hyperoctaedral_group(n),roots,n,Dict{Symbol,Any}()) end const coxhyp=coxeter_hyperoctaedral_group Base.show(io::IO, W::CoxHyp)=print(io,"coxhyp($(W.n))") PermRoot.action(W::CoxHyp,i,p)=abs(i^p) PermRoot.refltype(W::CoxHyp)=[TypeIrred(Dict(:series=>:B, :indices=>collect(1:W.n)))] CoxGroups.nref(W::CoxHyp)=length(W.roots) # use that "roots" correspond to roots of so_{2n+1}. # If eα΅’ are the basis vectors (i,-i) <-> eα΅’, (i,j) <-> eβ±Ό-eα΅’, (i,-j) <-> eα΅’+eβ±Ό function CoxGroups.isleftdescent(W::CoxHyp,w,i) a,b=W.roots[i] aw=a^w if a==-b return aw<0 end bw=b^w if b>0 aw=-aw else bw=-bw end if aw>0 && bw>0 return false end if aw<0 && bw<0 return true end max(aw,bw)<-min(aw,bw) end PermRoot.rank(W::CoxHyp)=W.n CoxGroups.maxpara(W::CoxHyp)=1:W.n-1 PermRoot.inclusiongens(W::CoxHyp)=1:W.n function PermRoot.refls(W::CoxHyp{T})where T get!(W,:refls)do refs=map(t->SPerm{T}(t...),W.roots) W.simple_reps=map(x->x[1]==-x[2] ? 1 : 2,W.roots) W.unique_refls=collect(1:nref(W)) refs end::Vector{SPerm{T}} end PermRoot.simple_reps(W::CoxHyp)=getp(refls,W,:simple_reps) PermRoot.unique_refls(W::CoxHyp)=getp(refls,W,:unique_refls) function Perms.reflength(W::CoxHyp,w) sym=nsym=0 for x in cycles(w) if sort(x)==sort(-x) sym+=length(x) else nsym+=length(x)-1 end end div(sym,2)+nsym end PermRoot.reflrep(W::CoxHyp,w::SPerm)=Matrix(w,W.n) PermRoot.reflrep(W::CoxHyp,i::Integer)= reflrep(W,i<=ngens(W) ? gens(W)[i] : refls(W)[i]) PermRoot.reflrep(W::CoxHyp)=reflrep.(Ref(W),1:ngens(W)) """ `reflection_subgroup(W::CoxHyp,I)` is defined only for `I=1:m` for `m≀ngens(W)`. """ function PermRoot.reflection_subgroup(W::CoxHyp,I::AbstractVector{Int}) if I!=1:length(I) error(I," should be 1:n for some n") end CoxHyp(Group(gens(W)[I]),filter(t->abs(t[2]!=W.n),W.roots), length(I),Dict{Symbol,Any}()) end PermRoot.cartan(W::CoxHyp)=cartan(:B,W.n) #------------------------ MatCox ------------------------------ @GapObj struct MatCox{T}<:CoxeterGroup{Matrix{T}} gens::Vector{Matrix{T}} end Base.one(W::MatCox)=one(W(1)) PermRoot.cartan(W::MatCox)=W.cartan isleftdescent(W::MatCox,w,i::Int)=real(sum(w[i,:]))<0 """ `coxeter_group(m)` or `coxgroup(m)` `m` should be a square matrix of real cyclotomic numbers. It returns the Coxeter group whose Cartan matrix is `m`. This is a matrix group `W` constructed as follows. Let `V` be a real vector space of dimension `size(m,1)`, let `eα΅’` be the canonical basis of `V`. Then `W` is the matrix group generated by the reflections `sα΅’(eβ±Ό)=eβ±Ό-mα΅’β±Ό eα΅’`. ```julia-repl julia> W=coxgroup([2 -2;-2 2]) coxeter_group([2 -2; -2 2]) ``` Above is a way to construct the affine Weyl group `Ã₁`. """ function coxeter_group(C::Matrix{T})where T I=one(C) MatCox(reflectionMatrix.(eachrow(I),eachrow(C)),Dict{Symbol,Any}(:cartan=>C)) end function Base.isfinite(W::MatCox) get!(W,:isfinite)do !any(isnothing,Weyl.type_cartan(cartan(W))) end::Bool end const coxgroup=coxeter_group maxpara(W::MatCox)=1:ngens(W)-1 function PermRoot.reflection_subgroup(W::MatCox,I::AbstractVector{Int}) if length(I)>0 n=maximum(I) if I!=1:n error(I," should be 1:n for some n") end else n=0 end MatCox(gens(W)[I],Dict{Symbol,Any}()) end function Base.show(io::IO,W::MatCox) print(io,"coxeter_group(",cartan(W),")") end end
Chevie
https://github.com/jmichel7/Chevie.jl.git
[ "MIT" ]
0.1.7
55a61b006686ca8e2f0031d3c2ab5de0ead553b0
code
24058
module Diagrams export Diagram, diagram using ..Chevie struct Diagram t::TypeIrred end function Base.show(io::IO, ::MIME"text/html", v::Vector{Diagram}) show(IOContext(io,:TeX=>true), "text/plain",v) end Base.show(io::IO,::MIME"text/plain",v::Vector{Diagram})=show(io,v) Base.show(io::IO,v::Vector{Diagram})=join(io,v,"\n") function Base.show(io::IO,d::Diagram) if !(get(io,:limit,false)|| get(io,:TeX,false)) print(io,"Diagram(",d.t,")") return end t=d.t if haskey(t,:orbit) act=length(t.orbit)>1 if act println(io,"Ο• permutes the next ",length(t.orbit)," components") end if !isone(t.twist) println(io,"Ο•",act ? "^$(length(t.orbit))" : "", " acts as ",t.twist^mappingPerm(t.orbit[1].indices,1:rank(t.orbit[1])), " on the component below") end show(io,Diagram.(t.orbit)) return end series=t.series::Symbol if series!=:ST show(io,d,Val(series)) elseif haskey(t,:ST) show(io,d,Val(Symbol("G",t.ST))) else impdiagram(io,d,t.p,t.q,rank(t),t.indices) end end """ `diagram(W)` prints a diagram describing a presentation of the finite reflection group or spets `W` ```julia-repl julia> diagram(coxgroup(:E,8)) O 2 οΏ¨ Oβ€”Oβ€”Oβ€”Oβ€”Oβ€”Oβ€”O Eβ‚ˆ 1 3 4 5 6 7 8 julia> diagram(crg(33)) 3 β‘‘ G₃₃ /^\\ β‘‘ β€”β€”β‘‘ β€”β€”β‘‘ β€”β€”β‘‘ 1 2 4 5 423423=342342 ``` """ diagram(W)=Diagram.(refltype(W)) hbar="\u2014" rdarrow(n)="\u21D0"^(n-1)*" " ldarrow(n)="\u21D2"^(n-1)*" " tarrow(n)="\u21DB"^(n-1)*" " dbar="\u2550" tbar(n)="\u2261"^(n-1)*" " vbar="\UFFE8" # "\u2503" function cd(i) if i<=10 ('\u2460'+i-1)*" " else "($i)" end end node="O" script(i)=string("{\\scriptstyle ",i,"}") rlap(s)="\\rlap{"*s*"}" kern(n)=string("\\kern",n,"pt") nnode(i)=string(kern(-2),"\\mathop\\bigcirc\\limits_{",i,"}",kern(-2)) # circle o with i beneath ncnode(o,i)=string(kern(-2),rlap("\\hbox{\$"*kern(4.5)*script(o)*"\$}"), "\\mathop\\bigcirc\\limits_{",i,"}",kern(-2),"\n") # circle o with i on right rcnode(o,i)=kern(-0.4)*"\\bigcirc"*kern(-7)*script(o)*kern(4.6)*script(i)*"\n" # circle o with i on left lcnode(o,i)=script(i)*kern(0.6)*"\\bigcirc"*kern(-9.3)*script(o)*kern(3.6)*"\n" rule(d,w,h)=string("\\rule[",d,"pt]{",w,"pt}{",h,"pt}\n") barr(n)=rule(2,n,1) dbarr(n)=rlap(rule(3,n,1))*rule(1,n,1) const tbarr=rlap(rule(4,10,1))*rlap(barr(10))*rule(0,10,1) raise(n,s)=string("\\raise",n,"pt\\hbox{\$",s,"\$}") vertbar(x,y)=kern(1.5)*rlap("\\hbox{\$"*nnode(x)*"\$}")*"\n"* rlap(kern(2.6)*rule(6.6,1,10.8))*"\n"* rlap(raise(19.4,kern(-2)*"\\bigcirc"*script(y)))*"\n"*kern(8) larger(s)="\\mathlarger{"*s*"}" larger(s,i)=i==0 ? larger(s) : larger(larger(s,i-1)) function getlind(d) t=d.t indices=t.indices if isnothing(indices) ind=fill("?",rank(t)) else ind=repr.(indices) end length.(ind),ind end function showrel(io,d::Diagram,i...) R=braid_relations(d.t)[collect(i)] r(a,b)=joindigits(R[a][b]) if length(i)==2 && R[1][1]==R[2][1] print(io," ",r(1,1),"=",r(1,2),"=",r(2,2)) else for a in eachindex(i) print(io," ",r(a,1),"=",r(a,2)) end end end function Base.show(io::IO,d::Diagram,::Val{:A}) l,ind=getlind(d) if get(io,:TeX,false) println(io,"\$\$",nnode(ind[1])) for i in 2:length(l) println(io,barr(10),nnode(ind[i])) end println(io,"\$\$") else join(io,node.*hbar.^l[1:end-1]);print(io,node);println(io," ",d.t) join(io,ind," ") end end function Base.show(io::IO,d::Diagram,::Val{:B}) l,ind=getlind(d) # c=haskey(d.t,:cartanType) ? d.t.cartanType : 1 c=d.t.cartanType if get(io,:TeX,false) println(io,"\$\$",nnode(ind[1])) if c==2 print(io,rlap(raise(5,"\\leftarrow")),dbarr(10)) elseif c==1 print(io,rlap(raise(5,"\\rightarrow")),dbarr(10)) elseif c==root(2) print(io,dbarr(10)) else print(io,rlap(raise(5,script(xrepr(io,c)))),dbarr(10)) end println(io,nnode(ind[2])) for i in 3:length(l) println(io,barr(10),nnode(ind[i])) end println(io,"\$\$") else print(io,node) if c==2 l1=max(l[1],2);print(io,rdarrow(l1)) elseif c==1 l1=max(l[1],2);print(io,ldarrow(l1)) elseif c==root(2) l1=max(l[1],2);print(io,dbar^l1) else print(io,"=",c,"="); l1=length(xrepr(rio(),c))+2 end join(io,node.*hbar.^l[2:end-1]);println(io,node," ",d.t) print(io,rpad(ind[1],l1+1));join(io,ind[2:end]," ") end end function Base.show(io::IO,d::Diagram,::Val{:D}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",nnode(ind[1]),barr(10)) print(io,vertbar(ind[3],ind[2])) for i in 4:length(l) print(io,barr(10),nnode(ind[i])) end print(io,"\$\$") else println(io," "^(l[1]+1),node," $(ind[2])") println(io," "^(l[1]+1),vbar) print(io,node,map(l->hbar^l*node,l[[1;3:end-1]])...) println(io," ",d.t) join(io,ind[[1;3:end]]," ") end end function Base.show(io::IO,d::Diagram,::Val{:E}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",nnode(ind[1]),barr(10)) print(io,nnode(ind[3]),barr(10)) print(io,vertbar(ind[4],ind[2])) for i in 5:length(l) print(io,barr(10),nnode(ind[i])) end print(io,"\$\$") else println(io," "^(2+l[1]+l[3]),node," $(ind[2])") println(io," "^(2+l[1]+l[3]),vbar) print(io,node,map(l->hbar^l*node,l[[1;3:end-1]])...) println(io," ",d.t) join(io,ind[[1;3:end]]," ") end end function Base.show(io::IO,d::Diagram,::Val{:F}) l,ind=getlind(d) # c=haskey(d.t,:cartanType) ? d.t.cartanType : 1 c=d.t.cartanType if get(io,:TeX,false) print(io,"\$\$",nnode(ind[1])) print(io,barr(10),nnode(ind[2])) if c==1 print(io,rlap(raise(5,"\\rightarrow")),dbarr(10)) elseif c==root(2) print(io,dbarr(10)) else print(io,rlap(raise(5,script(xrepr(io,c)))),dbarr(10)) end print(io,nnode(ind[3])) print(io,barr(10),nnode(ind[4])) print(io,"\$\$") else print(io,node,hbar^l[1],node) if c==1 l1=max(l[2],2);print(io,ldarrow(l1)) else l1=max(l[2],1);print(io,dbar^l1) end println(io,node,hbar^l[3],node," ",d.t) print(io,ind[1]," ",rpad(ind[2],l1+1),ind[3]," ",ind[4]) end end function Base.show(io::IO,d::Diagram,::Val{:G}) l,ind=getlind(d) # c=haskey(d.t,:cartanType) ? d.t.cartanType : 1 c=d.t.cartanType if get(io,:TeX,false) println(io,"\$\$",nnode(ind[1])) if c==1 print(io,rlap(raise(5,"\\rightarrow")),tbarr) elseif c==root(3) print(io,dbarr(10)) else error("not implemented") end print(io,nnode(ind[2]),"\$\$") else if c==1 print(io,node,tarrow(max(l[1],2))) else print(io,node,tbar(max(l[1],2))) end println(io,node," ",d.t) print(io,ind[1]," "^max(3-l[1],1),ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:H}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",nnode(ind[1])) print(io,rlap(kern(3)*raise(6,script(5))),barr(10)) print(io,nnode(ind[2])) for i in 3:length(l) print(io,barr(10),nnode(ind[i])) end print(io,"\$\$") else println(io," "^l[1],"β‚…") println(io,map(i->node*hbar^l[i],1:length(l)-1)...,node," ",d.t) join(io,ind," ") end end function Base.show(io::IO,d::Diagram,::Val{:I}) l,ind=getlind(d) if get(io,:TeX,false) println(io,"\$\$",nnode(ind[1])) println(io,rlap(kern(3)*raise(6,script(d.t.bond)))) println(io,barr(10),nnode(ind[2])) println(io,"\$\$") else println(io," "^l[1],d.t.bond) println(io,node,hbar^l[1],node) join(io,ind," ") end end function Base.show(io::IO,d::Diagram,::Val{:G4}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(3,ind[1])) print(io,barr(10),ncnode(3,ind[2]),"\$\$") else println(io,cd(3),hbar^2,cd(3),d.t);print(io,ind[1]," "^3,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G5}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(3,ind[1])) print(io,dbarr(10),ncnode(3,ind[2]),"\$\$") else println(io,cd(3),dbar^2,cd(3),d.t);print(io,ind[1]," "^3,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G6}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(2,ind[1])) print(io,tbarr,ncnode(3,ind[2]),"\$\$") else println(io,cd(2),tbar(2),cd(3),d.t);print(io,ind[1]," "^3,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G7}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",lcnode(2,ind[1])) print(io,kern(-2.5),raise(-3,larger("\\bigcirc",5)),"\n",kern(-5), rlap(raise(11,rcnode(3,ind[2]))), raise(-10,rcnode(3,ind[3])),"\$\$") else println(io," "^2,cd(3),ind[2]," ",d.t); println(io," ","/3\\") println(io,cd(2),hbar^2,cd(3)) print(io,ind[1]," "^3,ind[3]) end showrel(io,d,1,2) end function Base.show(io::IO,d::Diagram,::Val{:G8}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(4,ind[1])) print(io,barr(10),ncnode(4,ind[2]),"\$\$") else println(io,cd(4),hbar^2,cd(4),d.t);print(io,ind[1]," "^3,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G9}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(2,ind[1])) print(io,tbarr,ncnode(4,ind[2]),"\$\$") else println(io,cd(2),tbar(2),cd(4),d.t);print(io,ind[1]," "^3,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G10}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(3,ind[1])) print(io,dbarr(10),ncnode(4,ind[2]),"\$\$") else println(io,cd(3),dbar^2,cd(4),d.t);print(io,ind[1]," "^3,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G11}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",lcnode(2,ind[1])) print(io,kern(-2.5),raise(-3,larger("\\bigcirc",5)),kern(-5),"\n", rlap(raise(11,rcnode(3,ind[2]))), raise(-10,rcnode(4,ind[3])),"\$\$") else println(io," "^2,cd(3),ind[2]," ",d.t);println(io," /3\\"); println(io,cd(2),hbar^2,cd(4)) print(io,ind[1]," "^3,ind[3]) end showrel(io,d,1,2) end function Base.show(io::IO,d::Diagram,::Val{:G12}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",lcnode(2,ind[1])) print(io,kern(-2.5),raise(-3,larger("\\bigcirc",5)*raise(3,kern(-15)*"4")), kern(4),"\n", rlap(raise(11,rcnode(2,ind[2]))), raise(-10,rcnode(2,ind[3])),"\$\$") else println(io," ",cd(2),ind[2]," ",d.t); println(io," /4\\");println(io,cd(2),hbar^2,cd(2)) print(io,ind[1]," "^3,ind[3]) end showrel(io,d,1,2) end function Base.show(io::IO,d::Diagram,::Val{:G13}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",lcnode(2,ind[1]),kern(-2.5), rlap(raise(-3,larger("\\bigcirc",5))), rlap(kern(18.5)*raise(0.5,script(4))), rlap(kern(13)*raise(0.5,script(5))), kern(5),raise(-0.5,larger("\\bigcirc",2)), kern(0.3), rlap(raise(11,rcnode(2,2))), raise(-10,rcnode(2,3)), "\$\$") else println(io," ",cd(2),ind[1]," ",d.t) println(io," / \\") print(io,cd(2),hbar^2,cd(2)) end showrel(io,d,1,2) end function Base.show(io::IO,d::Diagram,::Val{:G14}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(2,ind[1])) print(io,rlap(kern(3)*raise(6,script(8)))) print(io,barr(10),ncnode(3,ind[2]),"\$\$") else println(io," β‚ˆ");println(io,cd(2),hbar,cd(3),d.t) print(io,ind[1]," "^2,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G15}) l,ind=getlind(d) if get(io,:TeX,false) println(io,"\$\$",lcnode(2,ind[1]),kern(-1), rlap(kern(-2.5)*raise(-10,script(5)))) println(io,kern(-2.4),raise(0,"\\bigg ("),kern(-1),"\n", rlap(raise(10,rcnode(2,ind[2]))), raise(-10,rcnode(3,ind[3]))) print(io,"\$\$") else println(io," ",cd(2),ind[1]," ",d.t); println(io," /5");println(io,cd(2),ind[3]); println(io," \\");print(io," ",cd(3),ind[2]) end showrel(io,d,1,2) end function Base.show(io::IO,d::Diagram,::Val{:G16}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(5,ind[1])) print(io,barr(10),ncnode(5,ind[2]),"\$\$") else println(io,cd(5),hbar^2,cd(5),d.t);print(io,ind[1]," "^3,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G17}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(2,ind[1])) print(io,tbarr,ncnode(5,ind[2]),"\$\$") else println(io,cd(2),tbar(2),cd(5),d.t);print(io,ind[1]," "^3,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G18}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(3,ind[1])) print(io,dbarr(10),ncnode(5,ind[2]),"\$\$") else println(io,cd(3),dbar^2,cd(5),d.t);print(io,ind[1]," "^3,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G19}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",lcnode(2,ind[1])) print(io,kern(-2.5),raise(-3,larger("\\bigcirc",5)),kern(-5),"\n", rlap(raise(11,rcnode(3,ind[2]))), raise(-10,rcnode(5,ind[3])),"\$\$") else println(io," "^2,cd(3),ind[2]," ",d.t);println(io," /3\\"); println(io,cd(2),hbar^2,cd(5)) print(io,ind[1]," "^3,ind[3]) end showrel(io,d,1,2) end function Base.show(io::IO,d::Diagram,::Val{:G20}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(3,ind[1])) print(io,rlap(kern(3)*raise(6,script(5)))) print(io,barr(10),ncnode(3,ind[2]),"\$\$") else println(io," β‚…");println(io,cd(3),hbar,cd(3),d.t) print(io,ind[1]," "^2,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G21}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(2,ind[1])) print(io,rlap(kern(3)*raise(6,script(10)))) print(io,barr(10),ncnode(3,ind[2]),"\$\$") else println(io," ₁₀"); println(io,cd(2),hbar^2,cd(3),d.t);print(io,ind[1]," "^3,ind[2]) end end function Base.show(io::IO,d::Diagram,::Val{:G22}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",lcnode(2,ind[1])) print(io,kern(-2.5),raise(-3,larger("\\bigcirc",5)* raise(3,kern(-15)*"5")),kern(4),"\n", rlap(raise(11,rcnode(2,ind[2]))), raise(-10,rcnode(2,ind[3])),"\$\$") else println(io," ",cd(2),ind[2]," ",d.t);println(io," /5\\") println(io,cd(2),hbar^2,cd(2)) print(io,ind[1]," "^3,ind[3]) end showrel(io,d,1,2) end function Base.show(io::IO,d::Diagram,::Val{:G24}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(2,ind[2]),dbarr(14),ncnode(2,ind[3])) print(io,kern(-26.2),raise(8.5,"\\diagup"),kern(-3.1)) print(io,rlap(raise(16.7,rcnode(2,ind[1])))) print(io,kern(6),raise(8.3,"\\diagdown")) print(io,"\$\$") else println(io," ",cd(2),ind[1]," ",d.t) println(io," / \\") println(io,cd(2),dbar^2,cd(2)) print(io,ind[2]," "^3,ind[3]) end showrel(io,d,4) end function Base.show(io::IO,d::Diagram,::Val{:G25}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(3,ind[1])) for i in 2:3 print(io,barr(10),ncnode(3,ind[i])) end print(io,"\$\$") else println(io,cd(3),hbar^2,cd(3),hbar^2,cd(3),d.t) print(io,prod(map((i,j)->i*" "^(4-j),ind,l))) end end function Base.show(io::IO,d::Diagram,::Val{:G26}) l,ind=getlind(d) if get(io,:TeX,false) println(io,"\$\$",ncnode(2,ind[1])) println(io,dbarr(10),ncnode(3,ind[2])) println(io,barr(10),ncnode(3,ind[3]),"\$\$") else println(io,cd(2),dbar^2,cd(3),hbar^2,cd(3),d.t) print(io,prod(map((i,j)->i*" "^(4-j),ind,l))) end end function Base.show(io::IO,d::Diagram,::Val{:G27}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(2,ind[2]),dbarr(14),ncnode(2,ind[3])) print(io,kern(-26.2),raise(8.5,"\\diagup"),kern(-3.1)) print(io,rlap(raise(16.7,rcnode(2,ind[1])))) print(io,kern(6),raise(8.3,"\\diagdown")) print(io,"\$\$") else println(io," ",cd(2),ind[1]," ",d.t) println(io, " / \\") println(io,cd(2),dbar^2,cd(2)) print(io,ind[2]," "^3,ind[3]) end showrel(io,d,4) end function Base.show(io::IO,d::Diagram,::Val{:G29}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(2,ind[1]),barr(10),ncnode(2,ind[2])) print(io,rlap(rlap(raise(5,"\\leftarrow"))*dbarr(14))) print(io,rlap(kern(5)*rule(10,1,5)*kern(-2)*rule(10,1,5))) print(io,rlap(kern(2)*raise(17,rcnode(2,ind[4])))) print(io,rlap(kern(-4)*raise(9,"\\diagup"))) print(io,rlap(kern(9)*raise(9,"\\diagdown"))) print(io,kern(14),ncnode(2,ind[3])) print(io,"\$\$") else println(io," "^6,cd(2),ind[4]," "^2,d.t) println(io," /\u2016\\") println(io,cd(2),hbar^2,cd(2),dbar^2,cd(2)) print(io,ind[1]," "^(4-l[1]),ind[2]," "^(4-l[2]),ind[3]) end showrel(io,d,7) end function Base.show(io::IO,d::Diagram,::Val{:G31}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(2,ind[4]),kern(-2),raise(8,"\\diagup"), kern(-2),raise(16,ncnode(2,ind[1])), kern(-12.5),barr(19.5),ncnode(2,ind[2]), kern(-16.5),raise(12.3,larger("\\bigcirc",5)), kern(-9),barr(19.5),ncnode(2,ind[5]), kern(-22),raise(16,ncnode(2,ind[3])), kern(-1),raise(8,"\\diagdown"),"\$\$") else print(io,prod(map((i,j)->i*" "^(4-j),ind[[4,2,5]],l[[4,2,5]]))) println(io,cd(2),hbar^2, cd(2),hbar^2, cd(2)," "^2,d.t) println(io," \\ /3\\ /") println(io," "^2,cd(2),hbar^2,cd(2)) print(io," "^2,ind[1]," "^(4-l[1]),ind[3]) end print(io," i.e. ",fromTeX(io,"\$A_5\$ on ")) print(io,joindigits(d.t.indices[[1,4,2,5,3]])," plus") showrel(io,d,5,6) end function Base.show(io::IO,d::Diagram,::Val{:G32}) l,ind=getlind(d) if get(io,:TeX,false) print(io,"\$\$",ncnode(3,ind[1])) for i in 2:4 print(io,barr(10),ncnode(3,ind[i])) end print(io,"\$\$") else println(io,(cd(3)*hbar^2)^3,cd(3),d.t) print(io,prod(map((i,j)->i*" "^(4-j),ind,l))) end end trianglerel(a,b,c)=string(ncnode(2,a),barr(14),kern(-12), rlap(raise(7.5,"\\underleftarrow"*script(6))), rlap(kern(-6)*raise(9,"\\diagup")), rlap(kern(1)*raise(16.5,rcnode(2,c))), rlap(kern(8.6)*raise(9,"\\diagdown")), kern(11.5),"\n",rlap("\\hbox{\$"*ncnode(2,b)*"\$}"), kern(9)) function Base.show(io::IO,d::Diagram,::Val{:G33}) l,ind=getlind(d) if get(io,:TeX,false) println(io,"\$\$",ncnode(2,ind[1]),barr(10), trianglerel(ind[2],ind[3],ind[4])) println(io,barr(10),ncnode(2,ind[5]),"\$\$") else println(io," "^4, ind[3]," ",cd(2)," "^6,d.t) println(io," "^5,"/^\\") println(io,(cd(2)*hbar^2)^3,cd(2)) print(io,prod(map((i,j)->i*" "^(4-j),ind[[1,2,4,5]],l[[1,2,4,5]]))) end showrel(io,d,11) end function Base.show(io::IO,d::Diagram,::Val{:G34}) l,ind=getlind(d) if get(io,:TeX,false) println(io,"\$\$",ncnode(2,1),barr(10),trianglerel(ind[2],ind[3],ind[4])) println(io,barr(10),ncnode(2,5),barr(10),ncnode(2,6),"\$\$") else println(io," "^4, ind[3]," ",cd(2)," "^10,d.t) println(io," "^5,"/^\\") println(io,(cd(2)*hbar^2)^4,cd(2)) print(io,prod(map((i,j)->i*" "^(4-j),ind[[1,2,4,5,6]],l[[1,2,4,5,6]]))) end showrel(io,d,16) end function impdiagram(io::IO,D::Diagram,p,q,r,ind) d=div(p,q) j=chevieget(:imp, :BraidRelations)(p, q, r) if q==1 if get(io,:TeX,false) print(io,"\$\$",ncnode(p,ind[1]),dbarr(10),ncnode(2,ind[2])) for i in 3:r print(io,barr(10),ncnode(2,i)) end print(io,"\$\$") else join(io,ind," "^3);println(io," ",D.t) print(io,cd(p)) if length(ind)>1 print(io,dbar^2) end join(io,fill(cd(2),r-1),hbar^2) end elseif p==q if get(io,:TeX,false) print(io,"\$\$",p,kern(2),rule(-5,0.7,14.5),kern(-12), rlap(raise(12,lcnode(2,ind[1]))), raise(-12,lcnode(2,ind[2])),kern(-1.3), rlap(raise(7,"\\diagdown")), raise(-7,"\\diagup"), kern(-9.6),dbarr(8),ncnode(2,ind[3])) for i in 4:r print(io,barr(10),ncnode(2,i)) end print(io,"\$\$") else indent=p==3 ? "" : " "^length(string(p)) println(io,indent,ind[1]," ",D.t) println(io,indent,vbar,"\\") if p!=3 print(io,p) end println(io,vbar,dbar,join(ind[3:r],hbar^2)) println(io,indent,vbar,"/") print(io,indent, ind[2]) end showrel(io,D,2) elseif q==2 if get(io,:TeX,false) print(io,"\$\$",lcnode(d,ind[1]),kern(-2.7), raise(-4,larger("\\bigcirc",5)), kern(-7), rlap(raise(12,rcnode(2,ind[2]))), raise(-12,rcnode(2,ind[3]))) if r>3 print(io,kern(-6.2),rlap(raise(7,"\\diagdown")), raise(-7,"\\diagup"),kern(-1.6),ncnode(2,ind[4])) end for i in 5:r print(io,barr(10),ncnode(2,ind[i])) end print(io,"\$\$") else indent=" "^(textwidth(cd(d))-textwidth(cd(2))) println(io,indent," "^3,ind[2]," ",cd(2)," ",D.t) print(io,indent," /",vbar) if r>=3 print(io,"\\") end println(io,join(ind[4:r+1]," "^3)) println(io,ind[1]," ",cd(d),"3",vbar," ",join(fill(cd(2),r-2),hbar^2)) print(io,indent," \\",vbar) if r>=3 print(io,"/") end println(io) print(io,indent," "^3,ind[3]," ",cd(2)) end showrel(io,D,1,2) else if get(io,:TeX,false) print(io,"\$\$",lcnode(d,ind[1]),kern(-1), rlap(kern(-2.5)*raise(-10,script(q+1))), kern(-2.4), # raise(-4,larger("(",7)), raise(0,"\\bigg ("), kern(-1), rlap(raise(10,rcnode(2,ind[2]))), raise(-10,rcnode(2,ind[3]))) if r>2 print(io,kern(-6.2),rlap(raise(7,"\\diagdown")),raise(-7,"\\diagup"), kern(-11.6),dbarr(10),ncnode(2,ind[4])) end for i in 5:length(ind) print(io,barr(10),ncnode(2,ind[i])) end print(io,"\$\$") else indent=" "^(textwidth(cd(d))-textwidth(cd(2))) println(io,indent," "^2,ind[2]," ",cd(2)," ",D.t) print(io,indent," /",q+1) if r>=3 print(io,"\\ ") end println(io,join(ind[4:r+1]," "^3)) print(io,ind[1]," ",cd(d)," ") if r>=3 print(io,dbar^2) end println(io,join(fill(cd(2),r-2),hbar^2)) print(io,indent," \\ ") if r>=3 print(io,"/") end println(io) print(io,indent," "^2,ind[3]," ",cd(2)) end showrel(io,D,(1:min(3,r))...) end end function Base.show(io::IO,d::Diagram,::Val{Symbol("AΜƒ")}) v=d.t.indices r=length(v)-1 if r==1 println(io,d.t.series,"₁ ",v[1]," ∞ ",v[2]) else n=string(d.t.series,stringind(io,r)," ") s=string(join(v[1:r],hbar^3)) o=length(s)-4 println(io," "^length(n)," ",hbar^div(o,2),v[r+1],hbar^div(o,2)) println(io," "^length(n),"/"," "^o,"\\") println(io,n,s) end end function Base.show(io::IO,d::Diagram,::Val{Symbol("BΜƒ")}) v=d.t.indices r=length(v)-1 c=d.t.cartanType if c==1 || r==2 println(io,"CΜƒ",stringind(io,r)," ",v[1]," > ",join(v[2:end]," - ")," < ",v[r+1]) else s=string("BΜƒ",stringind(io,r)," ",v[1]," < ",join(v[2:end-2]," - ")) println(io," "^(length(s)-2),v[r+1]) println(io," "^(length(s)-2),"|") println(io,s," - ",v[r]) end end function Base.show(io::IO,d::Diagram,::Val{Symbol("DΜƒ")}) v=d.t.indices r=length(v)-1 lr=length(string(r)) println(io,d.t.series,stringind(io,r)," ",v[1]," "^(4*(r-3)-1),v[r+1]) println(io," "^(lr+3),"\\"," "^(1+4*(r-4)),"/") print(io," "^(lr+4),v[3]) for i in 4:r-1 print(io,hbar^3,v[i]) end println(io) println(io," "^(lr+3),"/"," "^(1+4*(r-4)),"\\") println(io," "^(lr+2),v[2]," "^(4*(r-3)-1),v[r]) end function Base.show(io::IO,d::Diagram,::Val{Symbol("EΜƒ")}) v=d.t.indices if length(v)==7 print(io," ",v[7],"\n |\n"," ",v[2],"\n |\n", join(v[[1,3,4,5,6]],hbar^3)," ",d.t) elseif length(v)==8 println(io," ",v[2],"\n |") print(io,join(v[[8,1,3,4,5,6,7]],hbar^3)," ",d.t) elseif length(v)==9 println(" ",v[2],"\n |") print(io,join(v[[1,3,4,5,6,7,8,9]],hbar^3)," ",d.t) end end function Base.show(io::IO,d::Diagram,::Val{Symbol("FΜƒ")}) v=d.t.indices print(io,v[5],hbar^3,v[1],hbar^3,v[2],ldarrow(2),v[3],hbar^3,v[4]," "^3,d.t) end function Base.show(io::IO,d::Diagram,::Val{Symbol("GΜƒ")}) v=d.t.indices print(io,v[3],hbar^2,v[1],tarrow(2),v[2]," ",d.t) end end
Chevie
https://github.com/jmichel7/Chevie.jl.git