repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/Error-418-SWE/Documenti
https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/template_modern.typ
typst
#import "/common.typ": * #let project( title: "", subTitle: "", authors: (), reviewers: (), showLog: false, showIndex: true, showImagesIndex: true, showTablesIndex: true, isExternalUse: false, body ) = { // Document and elements styling set text( font: "Inter", lang: "it", ) set par( leading: 0.85em, ) set page( numbering: "1", number-align: center, paper: "a4", margin: (x: 2cm, y: 2.5cm), ) set heading( numbering: "1.1", ) set list( marker: ([•], [--]), ) set enum( numbering: "1a)", ) set table( fill: (_, row) => if row == 0 { luma(220) }, stroke: 0.5pt + luma(140), ) show link: set text(fill: blue) show heading.where( level: 1 ): it => { it v(1em, weak: true) } show heading.where( level: 2 ): it => { v(0.5em, weak: false) it v(1em, weak: true) } show heading.where( level: 3 ): it => { it v(1em, weak: true) } show outline.entry.where( level: 1 ): it => { strong(it) } show "WIP": it => [ #text(it, fill: red) ] show "TODO": it => [ #box( stroke: red, inset: 0.15em, text("Riferimento assente", fill: red, weight: "bold") ) ] // Define constants let groupName = "Error_418" let groupMembers = ("<NAME>","<NAME>", "<NAME>" ,"<NAME>", "<NAME>", "<NAME>", "<NAME>") let recipients = ("Gruppo " + groupName, "<NAME>", "<NAME>") let changelogData = csv("log.csv") let logo = "logo.png" let product_logo = "logo_wms3.svg" // Import parameters let title = title let subTitle = subTitle let showLog = showLog let showIndex = showIndex let showImagesIndex = showImagesIndex let showTablesIndex = showTablesIndex let authors = authors let reviewers = reviewers let isExternalUse = isExternalUse let documentVersion = "WIP" // Check members validity for author in authors { if (author not in groupMembers) { panic("Controlla lo spelling dei redattori.") } } for reviewer in reviewers { if (reviewer not in groupMembers) { panic("Controlla lo spelling dei verificatori, o rimuovili per caricare automaticamente il verificatore designato.") } } // Handle plurals let str_authors = "Redattore" if (authors.len() >= 2) { str_authors = "Redattori" } let str_reviewers = "Verificatore" if (reviewers.len() >= 2) { str_reviewers = "Verificatori" } // Define version if (changelogData.flatten().len() > 0) { documentVersion = changelogData.flatten().at(0) } // Set the document's basic properties set document( author: "Error_418", title: title, date: auto ) // Page header set page( header: locate(loc => { text( 0.75em, if counter(page).at(loc).first() > 1 [ #upper(title) v#documentVersion #h(1fr) #groupName #line(length: 100%, stroke: 0.25pt) ] ) }) ) // Extract Json data based on date let calculateKey(jObject, jObjectKeys) = { let dateToFind = "" let today = datetime.today() let year = str(today.year()-2000) let month = str(today.month()) let day = str(today.day()) if month.len() == 1 { month = "0" + month } if day.len() == 1 { day = "0" + day } dateToFind = year + "-" + month + "-" + day let i = 0 while i < jObject.keys().len()-1 { if jObjectKeys.at(i) <= dateToFind and dateToFind < jObjectKeys.at(i + 1) { return jObject.keys().at(i) } i = i + 1 } //check se è l'ultimo elemento let lastKey = jObject.keys().at(jObject.keys().len() - 1) if dateToFind >= lastKey { return lastKey } } let pat(lightness) = pattern( size: (20pt, 20pt), relative: "parent", place( dx: 5pt, dy: 5pt, rotate(45deg, square( size: 5pt, fill: luma(lightness), )), ), ) // Cover page set page(margin: (x: 1.5cm, y: 0cm)) v(6em) place( horizon + right, [ #v(20em) #rect(fill: pat(200), width: 10em, height: 15em, outset: 0.3em) ] ) image(product_logo, width: 30%) v(-1em) text(2.5em, weight: "medium", title) v(-1em) text(1.5em,subTitle) v(2em) // Information table v(1fr) set text(size: 10pt) text(1em, weight: "bold", "Informazioni") line(length: 40%, stroke: 0.25pt) // Load roles from JSON file let jObject = json("/roles.json") let jObjectKeys = jObject.keys() let key = calculateKey(jObject, jObjectKeys) let ruoli = jObject.at(key) let summaryHeading = align.with(left) let summaryContent = align.with(left) // Show roles grid( columns: (auto, auto), gutter: 15pt, // Versione summaryHeading[*Versione*], summaryContent[ #documentVersion ], // Destinazione d'uso summaryHeading[*Uso*], summaryContent[ #if isExternalUse { text("Esterno") } else { text("Interno") } ], // Stato di approvazione summaryHeading[*Stato*], summaryContent[Approvato], // Responsabile del gruppo summaryHeading[*Responsabile*], summaryContent[ #let responsabile = "n/a" #for role in ruoli.ruoli { if role.contains("Responsabile") { responsabile = role.flatten().at(0) } } #responsabile ], // Redattori documento summaryHeading[*#str_authors*], summaryContent[ #authors.join("\n") ], // Verificatori documento summaryHeading[*#str_reviewers*], summaryContent[ #let verificatore = "n/a" #if (reviewers.len() > 0) { verificatore = reviewers.join("\n") } else { for role in ruoli.ruoli { if role.contains("Verificatore") { verificatore = role.flatten().at(0) } } } #verificatore ], // Destinatari documento summaryHeading[*Destinatari*], summaryContent[ #recipients.join("\n") ], ) v(6em) line(length: 100%, stroke: 0.25pt) grid( columns: (1fr, auto), gutter: 1em, align: horizon, stack( dir: ltr, spacing: 1em, image(logo, width: 4em), groupName ), stack( dir: ltr, spacing: 2em, align(horizon, link("https://github.com/Error-418-SWE/")[GitHub/Error-418-SWE]), align(horizon, link("mailto:<EMAIL>")) ) ) v(1cm) pagebreak() set page( margin: (x: 2cm, y: 2.5cm), ) set text(size: 11pt) // Changelog if (showLog) { page(numbering: "I")[ #counter(page).update(1) #align(center, text(weight: "bold", "Registro delle modifiche")) #show par: set par(leading: 0.65em) #table( align: left, columns: (1fr, 1.5fr, 0.8fr, 5fr, 2.1fr, 2.1fr), [*Ver.*],[*Data*],[*PR*],[*Titolo*],[*Redattore*],[*Verificatore*], ..changelogData.flatten(), ) ] pagebreak() } // Index of contents if showIndex { page(numbering: none)[ #outline( title: "Indice dei contenuti", depth: 3, indent: true ) ] pagebreak() } // Index of images if showImagesIndex { page(numbering: none)[ #outline( title: "Indice delle immagini", target: figure.where(kind: image) ) ] pagebreak() } // Index of tables if showTablesIndex { page(numbering: none)[ #outline( title: "Indice delle tabelle", target: figure.where(kind: table) ) ] pagebreak() } // Prepare regex for glossary terms matching let glossary = json("glossario_manuale_utente.json"); let glossaryRegex = () let regexSeparator = "(\b|$)|(\b|$)" for term in glossary.keys() { glossaryRegex.push(term) glossaryRegex.push(lower(term)) if glossary.at(term).acronyms.len() > 0 { glossaryRegex.push(glossary.at(term).acronyms.join(regexSeparator)) glossaryRegex.push(lower(glossary.at(term).acronyms.join(regexSeparator))) } if glossary.at(term).synonyms.len() > 0 { glossaryRegex.push(glossary.at(term).synonyms.join(regexSeparator)) glossaryRegex.push(lower(glossary.at(term).synonyms.join(regexSeparator))) } } glossaryRegex = glossaryRegex.dedup().sorted().rev().join(regexSeparator) // Highlight glossary terms show regex( glossaryRegex ): it => { it h(0.03em) text( fill: luma(100), sub(emph("G")) ) h(0.02em) } // Body set par(justify: true) counter(page).update(1) body show regex( "\bG\b" ): it => { "" } set heading( level: 1, numbering: none, outlined: false ) let previousTerm = glossary.keys().at(0) heading( level: 1, previousTerm.at(0) ) line(length: 100%) for term in glossary.keys() { if (term.at(0) != previousTerm.at(0)) { heading( level: 1, term.at(0) ) line(length: 100%) } heading( level: 2, if glossary.at(term).acronyms.len() > 0 { term + " (" + glossary.at(term).acronyms.join(", ") + ")" } else { term } ) text( glossary.at(term).description ) previousTerm = term } }
https://github.com/Jollywatt/typst-fletcher
https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/node-defocus/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 1em) #import "/src/exports.typ" as fletcher: diagram, node, edge #let around = ( (-1,+1), ( 0,+1), (+1,+1), (-1, 0), (+1, 0), (-1,-1), ( 0,-1), (+1,-1), ) #grid( columns: 2, ..(-10, -1, -.25, 0, +.25, +1, +10).map(defocus => { ((7em, 3em), (3em, 7em)).map(((w, h)) => { align(center + horizon, diagram( node-defocus: defocus, node-inset: 0pt, { node((0,0), rect(width: w, height: h, inset: 0pt, align(center + horizon)[#defocus])) for p in around { edge(p, (0,0)) } })) }) }).join() )
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/demo.typ
typst
#import "themes/polylux/polylux.typ" #import "themes/fudan.typ": * #show: fudan-theme.with( footer: [Author, institution], short-title: [Short title], ) #title-slide( title: [这是一个PPT模板的标题], subtitle: [哈尔滨工程大学], authors: ([Author A], [Author B], [Author C]), date: [January 1, 1970] ) #slide(title: [First slide title])[ #lorem(20) ] #new-section-slide("The new section") #slide(title: [Slide with multiple columns])[ #lorem(20) ][ #lorem(10) ][ #lorem(30) ] #focus-slide[ _Focus!_ This is very important. ] #focus-slide[ 哈哈哈哈哈哈1111 $lim_(x->oo) 1/x = 1$ 1111111222222222 $vec(1, 2) dot.op vec(3, 4) = 11$ ] #focus-slide[ 单词:Former 意思:前者的,以前的 国际音标:/ˈfɔːrmər/ 词性:形容词 词源解说:该词源于中古英语的"formere",意为"以前的"。它由"fore"(前)和"mer"(更早的)两个词根组成。 词根:fore-,mer- 派生词:formation(形成),formal(正式的),formality(正式),formulate(阐述),formidable(可怕的) 常用短语: 1. former president(前总统) 2. former employee(前雇员) 3. in the former case(在前一种情况下) 4. former glory(昔日的辉煌) 5. former life(前世) 关联例句: 1. The former CEO of the company retired last year. (该公司的前首席执行官去年退休了。) 2. She used to be a teacher, but now she works as a writer. (她曾经是一名教师,但现在从事写作工作。) ]
https://github.com/fuchs-fabian/typst-template-aio-studi-and-thesis
https://raw.githubusercontent.com/fuchs-fabian/typst-template-aio-studi-and-thesis/main/src/dictionary.typ
typst
MIT License
#import "@preview/linguify:0.4.1": set-database as initialize-dictionary, linguify #let use-dictionary() = initialize-dictionary(toml("lang.toml")) // Cover sheet #let txt-cooperation = linguify("co-operation") #let txt-faculty = linguify("faculty") #let txt-programme = linguify("programme") #let txt-semester = linguify("semester") #let txt-course = linguify("course") #let txt-examiner = linguify("examiner") #let txt-submission-date = linguify("submission-date") // Declaration on the Final Thesis #let txt-declaration-on-the-final-thesis = linguify("declaration-on-the-final-thesis") #let txt-declaration-on-the-final-thesis-first-part = linguify("declaration-on-the-final-thesis-first-part") // Signing #let txt-location = linguify("location") #let txt-date = linguify("date") #let txt-author-signature = linguify("author-signature") // Headings #let txt-abstract = linguify("abstract") #let txt-list-of-figures = linguify("list-of-figures") #let txt-list-of-abbreviations = linguify("list-of-abbreviations") #let txt-list-of-formulas = linguify("list-of-formulas") #let txt-supplement-formula = linguify("supplement-formula") #let txt-list-of-tables = linguify("list-of-tables") #let txt-literature-and-bibliography = linguify("literature-and-bibliography") #let txt-list-of-attachements = linguify("list-of-attachements") // Other #let txt-attachement = linguify("attachement") // Assets #let txt-author = linguify("author") #let txt-authors = linguify("authors") // Project Management Assets #let txt-persona-name = linguify("persona-name") #let txt-persona-age = linguify("persona-age") #let txt-persona-family = linguify("persona-family") #let txt-persona-job = linguify("persona-job") #let txt-persona-do-and-say = linguify("persona-do-and-say") #let txt-persona-wishes = linguify("persona-wishes") #let txt-persona-see-and-hear = linguify("persona-see-and-hear") #let txt-persona-challenges = linguify("persona-challenges") #let txt-persona-typical-day = linguify("persona-typical-day") #let txt-persona-goals = linguify("persona-goals") #let txt-retro = linguify("retro") #let txt-retro-improvements = linguify("retro-improvements") #let txt-retro-impediments = linguify("retro-impediments") #let txt-retro-measures = linguify("retro-measures") #let txt-user-story-title = linguify("user-story-title") #let txt-user-story-acceptance-criteria = linguify("user-story-acceptance-criteria")
https://github.com/ngyngcphu/tick3d-docs
https://raw.githubusercontent.com/ngyngcphu/tick3d-docs/main/components/header.typ
typst
Apache License 2.0
#let m = yaml("/metadata.yml") #set text(font: m.at("fonts").at("monospace"), size: 10pt) #set par(leading: 0.75em) #show: block.with( stroke: (bottom: 1pt), inset: (bottom: 0.5em), ) #show: upper #locate(loc => [ // skip first page header #if loc.page() == 1 { return } #box(image("/components/logo.png", height: 2.5em)) #h(0.5cm) #box[ Trường Đại học Bách Khoa - ĐHQG-HCM \ Khoa Khoa học và Kỹ thuật Máy tính ] #h(1fr) ])
https://github.com/fuchs-fabian/typst-template-aio-studi-and-thesis
https://raw.githubusercontent.com/fuchs-fabian/typst-template-aio-studi-and-thesis/main/template/abbreviations.typ
typst
MIT License
#let abbreviations() = ( ( key: "repo-vorlage", short: "aio-studi-and-thesis", plural: "", long: "Repository der aktuellen Typst-Vorlage", longplural: "", desc: [ #link("https://github.com/fuchs-fabian/typst-template-aio-studi-and-thesis") ], group: "", ), ( key: "", short: "", plural: "", long: "", longplural: "", desc: [ ], group: "", ), )
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/dynamic/pause.typ
typst
#import "../../../polylux.typ": * #set page(paper: "presentation-16-9") #set text(size: 50pt) #polylux-slide[ Show this first. #show: pause(2) Show this later. #show: pause(3) Show this even later. #show: pause(4) That took aaaages! ]
https://github.com/jomaway/typst-gentle-clues
https://raw.githubusercontent.com/jomaway/typst-gentle-clues/main/docs.typ
typst
MIT License
#import "lib/lib.typ": * #import "@preview/tidy:0.3.0" // #import "@local/svg-emoji:0.1.0": * // extract version from typst.toml package file. #let pkg-data = toml("typst.toml").package #let version = pkg-data.at("version") #let import_statement = raw(block: true, lang: "typ", "#import \"@preview/gentle-clues:" + version +"\": *") // extract provided language translations #let lang-data = toml("lib/lang.toml") #let provided-translations = { let languages = lang-data.lang.keys() for lang in languages [ #if lang == languages.first() [] else if lang == languages.last() [and] else [,] "#lang" ] } // global page settings #set page(margin: 2cm); #set text(font: "Rubik", weight: 300, lang: "en") // #show: setup-emoji // tidy docs #let docs-clues = tidy.parse-module( read("lib/clues.typ"), name: "Gentle Clues API", scope: (clues: clues), preamble: "import clues: *;", label-prefix: "gc" ) #let ex(a,b) = grid(columns: 2, gutter: 1em)[ #a #align(end)[_Turns into this_ #sym.arrow] ][ #b ] = Gentle clues for typst Add some beautiful, predefined admonitions or define your own. == Getting started #clue(title: "Minimal starting example")[ #ex[ #import_statement ```typ #tip[Check out this cool package] ``` ][ #tip[Check out this cool package] ] ] #clue(title: "Usage")[ + Import the package like this: #import_statement + *Optional:* Change the default settings for all clues if desired. See @gentle-clues-example. + #ex[ Use a predefined clue without any options ```typ #info[You will find a list with all predefined clues at the last page.] ``` ][ #set align(bottom) #info[You will find a list with all predefined clues at the last page.] ] + #ex[ Or overwrite the default parameters. e.g. set a custom title ```typ #example(title: "Custom title")[ Content ...] ``` ][ #set align(bottom) #example(title: "Custom title")[ Content ...] ] See *all available parameters* at @clue-api. + *I18n:* - The current language which is set by `#set text(lang: "de")` changes the default header title. - Currently supported are #provided-translations. This package uses linguify for language settings. Feel free to contribute more languages. ] == Features #box( height: 4.5cm, stroke: gray.lighten(40%), radius: 2pt, inset: 2mm, columns(2)[ #notify(title: "Breaking news", breakable: true)[ Clues can now break onto the next page with option: `breakable: true` #lorem(30) ] This is a two columns layout. ]) // Color options #clue( title: "Color management", accent-color: gradient.linear(red, blue, dir: ttb), header-color: gradient.linear(red, yellow, blue), border-color: blue.darken(40%), body-color: pattern(text(fill:fuchsia.lighten(40%),"\n .")) )[ Clues can be styled in your liking. The simplest way is to change the `accent-color` which will be the thick border stroke on the left side. Header and border color will then automatically derived from this color. But you can set the `header-color`,`border-color` and `body-color` independently with a `color`, `gradient` or `pattern`. *Example:* ```typ #clue( title: "Color management", accent-color: gradient.linear(red, blue, dir:ttb), header-color: gradient.linear(red, yellow, blue), border-color: blue.darken(40%), body-color: pattern(text(fill:fuchsia.lighten(40%),"\n .")) )[...] ``` ] #clue(title: "Define your own clue")[ ```typst // Define a clue called ghost #let ghost(title: "Buuuuuuh", icon: emoji.ghost , ..args) = clue( accent-color: purple, // Define a base color title: title, // Define the default title icon: icon, // Define the default icon ..args // Pass along all other arguments ) // Use it #ghost[Huuuuuuh.] ``` The result looks like this. #let ghost( title: "Buuuuuuh.", accent-color: purple, icon: emoji.ghost , ..args ) = clue(title: title, icon: icon, ..args) #ghost[Huuuuuuh.] #set text(9pt) #tip[Use the `svg-emoji` package until emoji support is fully supported in typst ] ] == List of all predefined clues <predefined> #columns(2)[ `#clue` #clue[ Default clue ] `idea` #idea[Lets make something beautifull.] `#abstract` #abstract[Make it short. This is all you need.] `#question` #question[How do amonishments work?] `#info` #info[It's as easy as ```typst #info[Whatever you want to say] ``` ] `#example`, #example[Testing ...] `#experiment` #experiment[Testing ...] `#task` #task[ #box(width: 0.8em, height: 0.8em, stroke: 0.5pt + black, radius: 2pt) Check out this wonderful typst package! ] `#error` #error[Something did not work here.] `#warning` #warning[Still a work in progress.] `#success` #success[All tests passed. It's worth a try.] `#tip` #tip[Try it yourself] `#conclusion` #conclusion[This package makes it easy to add some beatufillness to your documents] `#memo` #memo[Leave a #emoji.star on github.] `#quotation` #quotation(attribution: "The maintainer")[Keep it simple. Admonish your life.] `#goal` #goal[Beatuify your document!] `#notify` #notify[ In version 0.9 some new predefined clues where added.] `#code` #code[```typ #let x = "secret" ```] `#danger` #danger[ Nothing here ... ] === Headless Variant just add `title: none` to any example #info(title:none)[Just a short information.] ] // columns end #tidy.show-module(docs-clues, style: tidy.styles.default)
https://github.com/kadykov/typstCV
https://raw.githubusercontent.com/kadykov/typstCV/main/kadykov-cv.typ
typst
#import "style.typ": * #let name = "<NAME>" #let post-name = "Research Engineer" #let website = "www.kadykov.com" #let github = "kadykov" #let gitlab = "kadykov" #let linkedin = "aleksandr-kadykov" // Optional email input #let email = { if "EMAIL" in sys.inputs.keys() {sys.inputs.EMAIL} else {"<EMAIL>"} } // Call the function from `style.typ` and pass variables to set up the document style #show: setup-style.with( name: name, email: email, website: website, github: github, gitlab: gitlab, linkedin: linkedin, ) // Main content starts here #block(width: 100%)[ #box(width: calc.min(bodywidth, 70%))[ = #post-name Proven ability to design and execute experiments, develop data processing methods, and automate workflows in scientific environments. Strong background in THz and IR applied photonics, solid-state physics, cryogenic measurements, data analysis, signal processing, and instrumentation integration. ] #place(top + right)[ #box( clip: true, stroke: 1.5pt + primary-color, radius: ( bottom-left: 0%, bottom-right: 50%, top-left: 50%, top-right: 0%, ), )[ #image( "photo.jpg", width: 25%, ) ] ] ] #hidden-section()[ Core competencies ] #block( width: calc.min(bodywidth, 70%), )[ #secline() - Experimental design & execution - Instrumentation integration & automation - Data analysis & signal processing - #link("https://github.com/search?q=language%3APython+author%3Akadykov&type=pullrequests" )[Python] programming - THz & IR photonics - Solid-state physics ] #hidden-section()[ Professional experience ] #experience( company-title: [ #link("https://www.multitel.eu/expertise/applied-photonics/terahertz-spectroscopy-and-imaging/" )[Multitel ASBL] ], company-subtitle: [ Non-profit innovation center specializing in #link("https://www.multitel.eu/expertise/applied-photonics/" )[applied photonics], #link("https://www.multitel.eu/expertise/artificial-intelligence/" )[AI], etc. ], dates: [Jul.~2021 \ Aug.~2024], company-location: [ #link("https://www.openstreetmap.org/#map=19/50.45756/3.92540" )[Mons \ Belgium] ], )[ === Research Engineer in THz Spectroscopy and Imaging - Developed advanced methods for THz-TDS data processing, improving results extraction for the #link("https://www.multitel.eu/projects/tera4all/" )[TERA4ALL] project. - Offloaded Transfer Matrix Method (TMM) calculations to a GPU, significantly enhancing refraction index profile extraction. - Automated laboratory workflows by implementing Python tools for measurement orchestration, data management, analysis, and result presentation. - Led the #link("https://www.multitel.eu/projects/saphire/")[SAPHIRE] project, developing THz-based _in-situ_ solutions for pill coating thickness and humidity control. - Ensured robust software development practices by incorporating unit testing, CI/CD pipelines, and comprehensive documentation. ] #experience( company-title: [ #link("https://www.lne.fr/en/research-and-development" )[Laboratoire National de Métrologie et d'Essais (LNE)] ], company-subtitle: [ French National Laboratory of Metrology and Testing ], dates: [Sep.~2018\ Sep.~2020], company-location: [ #link("https://www.openstreetmap.org/#map=17/48.76090/1.98370" )[ Trappes \ France ] ] )[ === Research Engineer in Quantum Hall Effect Metrology - Led low-noise cryogenic quantum Hall measurements on graphene, exploring its potential as a resistance standard. - Designed a flexible Python software package using PyMeasure, optimizing scientific equipment orchestration. - Participated in the nanofabrication of hBN-encapsulated graphene samples, advancing quantum Hall research. ] #experience( company-title: [ #link("http://www.ipmras.ru/en/institute/scientific-departments/department-110/" )[Institute for Physics of Microstructures (IPM RAS)] ], company-subtitle: [ State-owned research institute specializing in solid state physics. ], company-location: [ #link("https://www.openstreetmap.org/#map=17/56.29878/43.97990" )[<NAME> \ Russia] ], dates: [May~2017 \ Sep.~2018], )[ === Research Engineer in Photonics of Narrow-Gap Semiconductors - Conducted THz and FTIR cryogenic measurements of photoluminescence and photoconductivity. - Achieved laser emission in HgCdTe heterostructures at #link("https://doi.org/10.1063/1.4996966")[a record wavelength]. ] #hidden-section()[ Education ] #experience( company-title: [ #link("https://coulomb.umontpellier.fr/?lang=en" )[Laboratoire Char<NAME> (L2C)] & #link("http://www.ipmras.ru/en/institute/scientific-departments/department-110/" )[IPM RAS] ], company-subtitle: [ #link("https://edi2s.umontpellier.fr/" )[I2S Doctorlal School] at the #link("https://www.umontpellier.fr/en/" )[University of Montpellier] ], company-location: [ #link("https://www.openstreetmap.org/#map=18/43.63339/3.86312" )[Montpellier, France] \ #link("https://www.openstreetmap.org/#map=17/56.29878/43.97990" )[Nizh<NAME>gorod, Russia] ], dates: [Sep.~2014 \ Dec.~2017], )[ === Ph.D.~in Physics Thesis: #link("https://www.theses.fr/en/2017MONTS086")[ Physical properties of HgCdTe-based heterostructures: towards terahertz emission and detection ] - Implemented a double-modulation technique, enabling the extraction of critical magnetic fields in a topological insulator. - First to observe #link("https://dx.doi.org/10.1103/PhysRevLett.120.086401")[a temperature-driven phase transition] in a topological insulator using magnetotransport. ] #secline() == Technical skills - *Programming & data analysis*: #link("https://www.python.org/")[Python], #link("https://jupyter.org/")[Jupyter], #link("https://numpy.org/")[NumPy], #link("https://pandas.pydata.org/")[Pandas], #link("https://xarray.dev/")[Xarray], SciPy, #link("https://docs.pytest.org/")[PyTest], #link("https://pytorch.org/")[PyTorch], #link("https://scikit-learn.org/")[scikit-learn], #link("https://www.mathworks.com/products/matlab.html")[MATLAB] - *Data visualization*: #link("https://matplotlib.org/")[Matplotlib], #link("https://hvplot.holoviz.org/")[hvPlot], #link("https://plotly.com/python/")[Plotly], #link("https://bokeh.org/")[Bokeh], #link("https://panel.holoviz.org/")[Panel], #link("https://www.originlab.com/")[OriginPro] - *Measurement & automation*: #link("https://pymeasure.readthedocs.io")[PyMeasure], #link("https://blueskyproject.io/")[Bluesky], #link("https://yaq.fyi/")[yaq], #link("https://www.ni.com/en/shop/labview.html")[LabVIEW] - *Data management & integration*: #link("https://intake.readthedocs.io")[Intake], #link("https://en.wikipedia.org/wiki/SQL")[SQL] - *Document preparation*: #link("https://quarto.org/")[Quarto], #link("https://github.com/search?q=owner%3Akadykov+language%3ATypst&type=repositories" )[Typst], #link("https://pandoc.org/")[Pandoc], #link("https://www.latex-project.org/")[LaTeX] - *Other tools*: #link("https://code.visualstudio.com/")[VSCode], #link("https://git-scm.com/")[Git], #link("https://www.linux.com/what-is-linux/")[Linux], #link("https://www.docker.com/")[Docker], #link("https://about.gitlab.com/topics/ci-cd/")[CI/CD], #link("https://www.zotero.org/")[Zotero], #link("https://github.com/kadykov/")[GitHub], #link("https://gitlab.com/kadykov/")[GitLab], #link("https://en.wikipedia.org/wiki/Test-driven_development")[TDD] #secline() == Languages - *French* (#link("https://www.duolingo.com/profile/aleksandrkadykov" )[upper-intermediate] ) - *Russian* (native) // #secline() // = Selected publications // + <NAME>., <NAME>., <NAME>.S. et al., // #link("https://dx.doi.org/10.1063/1.4955018")[_Terahertz imaging of Landau levels in HgTe-based topological insulators_], // *Applied Physics Letters*, 108(26), _262102_, 2016 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1038/ncomms12576")[_Temperature-driven massless Kane fermions in HgCdTe crystals_], // *Nature Communications*, 7, _12576_, 2016 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1103/PhysRevLett.120.086401")[_Temperature-Induced Topological Phase Transition in HgTe Quantum Wells_], // *Physical Review Letters*, 120(8), _086401_, 2018 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1063/1.4932943")[_Terahertz detection of magnetic field-driven topological phase transition in HgTe-based transistors_], // *Applied Physics Letters*, 107(15), _152101_, 2015 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1103/PhysRevB.97.245419")[_Temperature-dependent terahertz spectroscopy of inverted-band three-layer InAs / GaSb / InAs quantum well_], // *Physical Review B*, 97(24), _245419_, 2018 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1063/1.4977781")[_HgCdTe-based heterostructures for terahertz photonics_], // *APL Materials*, 5(3), _035503_, 2017 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1038/s41535-019-0154-3")[_Magneto-transport in inverted HgTe quantum wells_], // *npj Quantum Materials*, 4(1), _1--8_, 2019 // + <NAME>., <NAME>., <NAME> al., // #link("https://dx.doi.org/10.1103/PhysRevB.96.035405")[_Temperature-driven single-valley Dirac fermions in HgTe quantum wells_], // *Physical Review B*, 96(3), _035405_, 2017 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1063/1.4996966")[_Stimulated emission from HgCdTe quantum well heterostructures at wavelengths up to 19.5~μm_], // *Applied Physics Letters*, 111(19), _192101_, 2017 // + <NAME>., <NAME>., <NAME> al., // #link("https://dx.doi.org/10.1063/1.4943087")[_Long wavelength stimulated emission up to 9.5~μm from HgCdTe quantum well heterostructures_], // *Applied Physics Letters*, 108(9), _092104_, 2016 // + <NAME>., <NAME>., <NAME> al., // #link("https://dx.doi.org/10.1063/1.4926927")[_Long wavelength superluminescence from narrow gap HgCdTe epilayer at 100~K_], // *Applied Physics Letters*, 107(4), _042105_, 2015 // + <NAME>., <NAME>., <NAME>., // #link("https://dx.doi.org/10.1063/1.4890416")[_Time resolved photoluminescence spectroscopy of narrow gap Hg1-xCdxTe/CdyHg1-yTe quantum well heterostructures_], // *Applied Physics Letters*, 105(2), _022102_, 2014 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1088/1361-6641/aa76a0")[_Terahertz photoconductivity of double acceptors in narrow gap HgCdTe epitaxial films grown by molecular beam epitaxy on GaAs(013) and Si(013) substrates_], // *Semiconductor Science and Technology*, 32(9), _095007_, // 2017 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1364/OE.26.012755")[_Stimulated emission in the 2.8--3.5~μm wavelength range from Peltier cooled HgTe/CdHgTe quantum well heterostructures_], // *Optics Express*, 26(10), _12755_, 2018 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1002/pssc.201510264")[_Observation of topological phase transition by terahertz photoconductivity in HgTe-based transistors_], // *physica status solidi (c)*, 13(7), _534--537_, 2016 // + <NAME>., <NAME>., <NAME> al., // #link("https://dx.doi.org/10.1088/1742-6596/647/1/012009")[_Terahertz excitations in HgTe-based field effect transistors_], // *Journal of Physics: Conference Series*, 647(1), // _012009_, 2015 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1134/S1063782616110063")[_Magnetospectroscopy of double HgTe/CdHgTe quantum wells_], // *Semiconductors*, 50(11), _1532--1538_, 2016 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1134/S1063776113130013")[_Nonresonant radiative exciton transfer by near field between quantum wells_], // *Journal of Experimental and Theoretical Physics*, 117(5), // _944--949_, 2013 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1088/1742-6596/647/1/012008")[_Investigation of possibility of VLWIR lasing in HgCdTe based heterostructures_], // *Journal of Physics: Conference Series*, 647(1), // _012008_, 2015 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1134/S1063782615120106")[_Impurity-induced photoconductivity of narrow-gap Cadmium--Mercury--Telluride structures_], // *Semiconductors*, 49(12), _1605--1610_, 2015 // + <NAME>., Fadeev, M.A., <NAME> al., // #link("https://dx.doi.org/10.1134/S1063782616120174")[_Long-wavelength stimulated emission and carrier lifetimes in HgCdTe-based waveguide structures with quantum wells_], // *Semiconductors*, 50(12), _1651--1656_, 2016 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1134/S1063782617120090")[_On the band spectrum in p-type HgTe/CdHgTe heterostructures and its transformation under temperature variation_], // *Semiconductors*, 51(12), _1531--1536_, 2017 // + <NAME>., <NAME>., <NAME>.~et al., // #link("https://dx.doi.org/10.1134/S106378261712017X")[_Investigation of HgCdTe waveguide structures with quantum wells for long-wavelength stimulated emission_], // *Semiconductors*, 51(12), _1557--1561_, 2017 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1134/S1063782617010109")[_Cyclotron resonance of Dirac fermions in InAs/GaSb/InAs quantum wells_], // *Semiconductors*, 51(1), _38--42_, 2017 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1134/S1063782616120113")[_Mercury vacancies as divalent acceptors in Hg1-xCdxTe/CdyHg1-yTe structures with quantum wells_], // *Semiconductors*, 50(12), _1662--1668_, 2016 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1134/S1063782618040255")[_Magnetooptical Studies and Stimulated Emission in Narrow Gap HgTe/CdHgTe Structures in the Very Long Wavelength Infrared Range_], // *Semiconductors*, 52(4), 2018 // + <NAME>., <NAME>., <NAME> al., // #link("http://mmi.univ-savoie.fr/agence/8thzdays/siteANG/")[_Terahertz excitations in HgTe-based field effect transistors_], // _113--114_, 2015 // + <NAME>., <NAME>., <NAME> al., // #link("https://dx.doi.org/10.1109/MIKON.2016.7492017")[_THz lasers based on narrow-gap semiconductors_], // _1--4_, 2016 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1109/IRMMW-THz.2016.7758790")[_THz magnetospectroscopy of double HgTe quantum well_], // _1--2_, 2016 // + <NAME>., <NAME>., <NAME>. et al., // #link("https://dx.doi.org/10.1109/IRMMW-THz.2016.7758927")[_Long-wavelength stimulated emission in HgCdTe quantum well waveguide heterostructures_], // 2016-Novem, _1--2_, 2016 // + But, D.B., <NAME>., <NAME>., // #link("https://dx.doi.org/10.1109/IRMMW-THz.2016.7758889")[_Terahertz cyclotron emission from HgCdTe bulk films_], // 2016-Novem, _1--2_, 2016 // + <NAME>., <NAME>., <NAME> al., // _Graphene-like band structure (Hg, Cd) Te Quantum Wells for // Quantum Hall Effect Metrology Applications_, _229_, 2017
https://github.com/felsenhower/kbs-typst
https://raw.githubusercontent.com/felsenhower/kbs-typst/master/examples/14.typ
typst
MIT License
#heading([Einführung]) Mein erster Text mit Typst! #lorem(20)
https://github.com/jamesrswift/splendid-mdpi
https://raw.githubusercontent.com/jamesrswift/splendid-mdpi/main/src/impl.typ
typst
The Unlicense
#let make-venue(venue, publisher) = { box(venue) h(1fr) box(publisher) v(2pt) line(length: 100%) v(5pt) } #let template( title: [], authors: (), date: [], doi: "", keywords: (), abstract: [], venue: image("ijms.png", height: 1.2cm), venue-abbrv: [_Int. J. Mol. Sci._], venue-link: "https://www.mdpi.com/journal/anawesomejournal", publisher: image("mdpi.svg", height: 1.2cm), paper-type: [Article], details: auto, body, ) = { set page( paper: "a4", margin: (top: 1.9cm, bottom: 1.1in, x: 1.6cm), footer: { set text(8pt) v(1fr) line(length: 100%, stroke: 0.5pt) v(5pt) [#venue-abbrv *#date.year*, #date.day, #date.month. ] link("https://doi.org/" + doi) h(1fr) link(venue-link) v(0.75cm) } ) set text(10pt, font: "TeX Gyre Pagella") set list(indent: 8pt) show heading: set block(below: 8pt) make-venue(venue, publisher) emph(paper-type) v(-4pt) strong({ block(text(18pt, title)) v(4pt) authors.enumerate().map(((i, author)) => author.name + [ ] + super[#{i+1}]).join(", ") }) let details = [ #set text(7pt) #set par(leading: 7pt) #show par: set block(spacing: 18pt) *Citation:* #{authors.map(author => author.name).join("; ")}. #title. #venue-abbrv *#date.year,* #date.day, #date.month. #link("https://doi.org/" + doi) #details ] show: (body) => grid( columns: (120pt, 1fr), column-gutter: 10pt, align(bottom, details), align(bottom, body), ) set par(justify: true) text(9pt)[ #for (i, author) in authors.enumerate() [ #super[#{i+1}] #{author.institution}; #link("mailto:" + author.mail) \ ] #v(8pt) *Abstract:* #abstract *Keywords:* #{keywords.join("; ")}. ] v(5pt) line(length: 100%, stroke: 0.5pt) v(0pt) show figure: align.with(center) show figure: set text(8pt) show figure.caption: pad.with(x: 10%) body }
https://github.com/myst-templates/lapreprint-typst
https://raw.githubusercontent.com/myst-templates/lapreprint-typst/main/frontmatter.typ
typst
MIT License
#let orcidLogo( // The ORCID identifier with no URL, e.g. `0000-0000-0000-0000` orcid: none, ) = { /* Logos */ let orcidSvg = ```<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 24 24"><path fill="#AECD54" d="M21.8,12c0,5.4-4.4,9.8-9.8,9.8S2.2,17.4,2.2,12S6.6,2.2,12,2.2S21.8,6.6,21.8,12z M8.2,5.8c-0.4,0-0.8,0.3-0.8,0.8s0.3,0.8,0.8,0.8S9,7,9,6.6S8.7,5.8,8.2,5.8z M10.5,15.4h1.2v-6c0,0-0.5,0,1.8,0s3.3,1.4,3.3,3s-1.5,3-3.3,3s-1.9,0-1.9,0H10.5v1.1H9V8.3H7.7v8.2h2.9c0,0-0.3,0,3,0s4.5-2.2,4.5-4.1s-1.2-4.1-4.3-4.1s-3.2,0-3.2,0L10.5,15.4z"/></svg>```.text if (orcid == none) { // Do not box(height: 1.1em, baseline: 13.5%, [#image.decode(orcidSvg)]) return } link("https://orcid.org/" + orcid)[#box(height: 1.1em, baseline: 13.5%)[#image.decode(orcidSvg)]] } #let validateString(raw, name, alias: none) = { if (name in raw) { assert(type(raw.at(name)) == "string", message: name + " must be a string") return raw.at(name) } if (type(alias) != "array") { return } for a in alias { if (a in raw) { assert(type(raw.at(a)) == "string", message: a + " must be a string") return raw.at(a) } } } #let validateBoolean(raw, name, alias: none) = { if (name in raw) { assert(type(raw.at(name)) == "boolean", message: name + " must be a boolean") return raw.at(name) } if (type(alias) != "array") { return } for a in alias { if (a in raw) { assert(type(raw.at(a)) == "boolean", message: a + " must be a boolean") return raw.at(a) } } } #let validateAffiliation(raw) = { let out = (:) if (type(raw) == "string") { out.name = raw; return out; } let id = validateString(raw, "id") if (id != none) { out.id = id } let name = validateString(raw, "name") if (name != none) { out.name = name } let institution = validateString(raw, "institution") if (institution != none) { out.institution = institution } let department = validateString(raw, "department") if (department != none) { out.department = department } let doi = validateString(raw, "doi") if (doi != none) { out.doi = doi } let ror = validateString(raw, "ror") if (ror != none) { out.ror = ror } let address = validateString(raw, "address") if (address != none) { out.address = address } let city = validateString(raw, "city") if (city != none) { out.city = city } let region = validateString(raw, "region", alias: ("state", "province")) if (region != none) { out.region = region } let postal-code = validateString(raw, "postal-code", alias: ("postal_code", "postalCode", "zip_code", "zip-code", "zipcode", "zipCode")) if (postal-code != none) { out.postal-code = postal-code } let country = validateString(raw, "country") if (country != none) { out.country = country } let phone = validateString(raw, "phone") if (phone != none) { out.phone = phone } let fax = validateString(raw, "fax") if (fax != none) { out.fax = fax } let email = validateString(raw, "email") if (email != none) { out.email = email } let url = validateString(raw, "url") if (url != none) { out.url = url } let collaboration = validateBoolean(raw, "collaboration") if (collaboration != none) { out.collaboration = collaboration } return out; } #let pickAffiliationsObject(raw) = { if ("affiliation" in raw and "affiliations" in raw) { panic("You can only use `affiliation` or `affiliations`, not both") } if ("affiliation" in raw) { raw.affiliations = raw.affiliation } if ("affiliations" not in raw) { return; } if (type(raw.affiliations) == "string" or type(raw.affiliations) == "dictionary") { // convert to a list return (validateAffiliation(raw.affiliations),) } else if (type(raw.affiliations) == "array") { // validate each entry return raw.affiliations.map(validateAffiliation) } else { panic("The `affiliation` or `affiliations` must be a array, dictionary or string, got:", type(raw.affiliations)) } } #let validateAuthor(raw) = { let out = (:) if (type(raw) == "string") { out.name = raw; return out; } let name = validateString(raw, "name") if (name != none) { out.name = name } let orcid = validateString(raw, "orcid") if (orcid != none) { out.orcid = orcid } let email = validateString(raw, "email") if (email != none) { out.email = email } let url = validateString(raw, "url") if (url != none) { out.url = url } let affiliations = pickAffiliationsObject(raw); if (affiliations != none) { out.affiliations = affiliations } else { out.affiliations = () } return out; } #let consolidateAffiliations(authors, affiliations) = { let cnt = 0 for affiliation in affiliations { if ("id" not in affiliation) { affiliation.insert("id", "aff-" + str(cnt + 1)) } affiliations.at(cnt) = affiliation cnt += 1 } let authorCnt = 0 for author in authors { let affCnt = 0 for affiliation in author.affiliations { let pos = affiliations.position(item => { ("id" in item and item.id == affiliation.name) or ("name" in item and item.name == affiliation.name) }) if (pos != none) { affiliation.remove("name") affiliation.id = affiliations.at(pos).id affiliations.at(pos) = affiliations.at(pos) + affiliation } else { affiliation.id = if ("id" in affiliation) { affiliation.id } else { affiliation.name } affiliations.push(affiliation) } author.affiliations.at(affCnt) = (id: affiliation.id) affCnt += 1 } authors.at(authorCnt) = author authorCnt += 1 } // Now that they are normalized, loop again and update the numbers let fullAffCnt = 0 let authorCnt = 0 for author in authors { let affCnt = 0 for affiliation in author.affiliations { let pos = affiliations.position(item => { item.id == affiliation.id }) let aff = affiliations.at(pos) if ("index" not in aff) { fullAffCnt += 1 aff.index = fullAffCnt affiliations.at(pos) = affiliations.at(pos) + (index: fullAffCnt) } author.affiliations.at(affCnt) = (id: affiliation.id, index: aff.index) affCnt += 1 } authors.at(authorCnt) = author authorCnt += 1 } return (authors: authors, affiliations: affiliations) } #let loadFrontmatter(raw) = { let out = (:) let title = validateString(raw, "title") if (title != none) { out.title = title } let subtitle = validateString(raw, "subtitle") if (subtitle != none) { out.subtitle = subtitle } let short-title = validateString(raw, "short-title", alias: ("short_title", "shortTitle", "runningHead",)) if (short-title != none) { out.short-title = short-title } // author information if ("author" in raw and "authors" in raw) { panic("You can only use `author` or `authors`, not both") } if ("author" in raw) { raw.authors = raw.author } if ("authors" in raw) { if (type(raw.authors) == "string" or type(raw.authors) == "dictionary") { // convert to a list out.authors = (validateAuthor(raw.authors),) } else if (type(raw.authors) == "array") { // validate each entry out.authors = raw.authors.map(validateAuthor) } else { panic("The `author` or `authors` must be a array, dictionary or string, got:", type(raw.authors)) } } let affiliations = pickAffiliationsObject(raw); if (affiliations != none) { out.affiliations = affiliations } else { out.affiliations = () } let open-access = validateBoolean(raw, "open-access", alias: ("open_access", "openAccess",)) if (open-access != none) { out.open-access = open-access } let doi = validateString(raw, "doi") if (doi != none) { assert(not doi.starts-with("http"), message: "DOIs should not include the link, use only the part after `https://doi.org/[]`") out.doi = doi } let date = none; let citation = validateString(raw, "citation") if (citation != none) { out.citation = citation; } else { // Create a citation, e.g. Cockett et al., 2023 let year = if (date != none) { ", " + date.display("[year]") } else { ", " + datetime.today().display("[year]") } if (out.authors.len() == 1) { out.citation = out.authors.at(0).name.split(" ").last() + year } else if (out.authors.len() == 2) { out.citation = out.authors.at(0).name.split(" ").last() + " & " + out.authors.at(1).name.split(" ").last() + year } else if (out.authors.len() > 2) { out.citation = out.authors.at(0).name.split(" ").last() + " " + emph("et al.") + year } } let consolidated = consolidateAffiliations(out.authors, out.affiliations) out.authors = consolidated.authors out.affiliations = consolidated.affiliations return out }
https://github.com/Daillusorisch/HYSeminarAssignment
https://raw.githubusercontent.com/Daillusorisch/HYSeminarAssignment/main/template/components/outline.typ
typst
#import "../utils/style.typ": * #let outline-page( depth: 3, title: "目  录" ) = { align(center)[ #text( font: 字体.黑体, size: 字号.小二 )[#title] ] set par( first-line-indent: 0em, leading: 1.25em ) set text( font: 字体.宋体, size: 字号.四号, ) locate(loc => { let elements = query(heading.where(outlined: true), loc) for el in elements { if el.level > depth {continue} let before_toc = query(heading.where(outlined: true).before(loc), loc).find((one) => {one.body == el.body}) != none let page_num = if before_toc { numbering("I", counter(page).at(el.location()).first()) } else { counter(page).at(el.location()).first() } link(el.location())[#{ // acknowledgement has no numbering let chapt_num = if el.numbering != none { numbering(el.numbering, ..counter(heading).at(el.location())) } else {none} if el.level == 1 { set text(weight: "bold") if chapt_num == none {} else { text( font: 字体.宋体, size: 字号.小四, (el.level - 1) * " " + chapt_num ) " " } el.body } else { text( font: 字体.宋体, size: 字号.小四, (el.level - 1) * " " + chapt_num ) " " el.body } }] // fill with ...... box(width: 1fr, h(0.5em) + box(width: 1fr, repeat[.]) + h(0.5em)) [#page_num] linebreak() } }) }
https://github.com/ysthakur/PHYS121-Notes
https://raw.githubusercontent.com/ysthakur/PHYS121-Notes/main/Notes/Ch03.typ
typst
MIT License
= Chapter 3 == Vectors - $A_x = A cos(theta)$ and $A_y = A sin(theta)$ $theta = tan^(-1)(A_y / A_x)$ == Projectile Motion / Projectile: An object that moves in 2 dimensions under the influence of gravity and nothing else / Launch angle: Angle of the initial velocity above the horizontal (x-axis) / Range: The range of àprojectile is the horizontal distance travelled - Horizontal direction has uniform motion - Vertical direction has free-fall motion - For smaller objects, air resistance is critical - Maximum range comes at an angle less than 45#sym.degree == Circular Motion / Centripetal acceleration: Acceleration pointing towards the center of a circle $(Delta v)/v = d/r$, where $d$ is displacement Centripetal acceleration is $a = (v^2)/r$, towards the center of the circle == Relative Velocity ???
https://github.com/kotfind/hse-se-2-notes
https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/algo/lectures/2024-10-01.typ
typst
#import "/utils/math.typ": * == Время работы quicksort-а Случайно выбираем опорный элемент $x$ Мысленно отсортируем массив: $ a_1, a_2, ..., a_n --> b_1, b_2, ..., b_n $ Опорный элемент $x$ сравнивается со всем и исключается из работы. Значит, два элемента никогда не сравниваются больше одного раза. Пусть $delta_(i j) = "int"(b_i " сравнивали с " b_j)$. Для времени работы считаем количество сравнений: $ E(T(n)) = E(sum_(i = 0)^(n-1) sum_(j = i + 1)^n delta_(i j)) = sum sum E(delta_(i j)) = sum sum P(b_i " сравнивали с " b_j) $ Два элемента $b_i$ и $b_j$ НЕ будут сравниваться, если между ними когда-то выбирался опорный. Они будут сравниваться только, если среди элементов $b_i, ..., b_j$ первым был выбран $i$-ый или $j$-ый. $ E(T(n)) = sum_(i = 0)^(n-1) sum_(j = i + 1)^n 2/(j - i + 1) = sum_(i = 0)^(n - 1) sum_(k = 1)^(n - i) 2/(k + 1) = sum_(i = 0)^(n - 1) 2 underbrace((1/2 + 1/3 + ... + (n - i + 1)), O(log n)) = O(n log n) $ == Skip List Вероятностная структура данных на основе list-а и операциями, как у дерева поиска Элементы лежат по возрастанию. Есть фиктивные элементы $-oo$ и $oo$ в начале и конце. $ -oo -> -4 -> 0 -> 1 -> 3 -> 7 -> 12 -> 15 -> +oo $ Хотим ходить шагами по большими шагами, а не только шагами по 1. Делаем новый список ("уровень"), в который включаем элементы данного с $P = 1/2$. Бесконечности всегда переходят на новый уровень. В каждом элементе указатель направо и вниз. Отдельно храним указатель на $-oo$ верхнего уровня. #figure( caption: [Структура списка], table( columns: 18, stroke: none, align: center, [], $arrow.b$, $$, $$, $$, $$, $$, $$, $$, $$, $$, $$, $$, $$, $$, $$, $$, $$, [Уровень 2:], $-oo$, $->$, $-4$, $ $, $ $, $ $, $ $, $ $, $ $, $ $, $7$, $->$, $ $, $ $, $ $, $ $, $+oo$, [Уровень 1:], $-oo$, $->$, $-4$, $ $, $ $, $ $, $ $, $ $, $3$, $->$, $7$, $->$, $ $, $ $, $15$, $->$, $+oo$, [Уровень 0:], $-oo$, $->$, $-4$, $->$, $0$, $->$, $1$, $->$, $3$, $->$, $7$, $->$, $12$, $->$, $15$, $->$, $+oo$, ) ) Операции: - Поиск: спускаемся по дереву - Удаление: удаляем из всех слоев - Добавление: случайно выбираем в каких слоях элемент будет, а в каких --- нет (количество слоев может увеличиться), потом добавляем. Способы реализации: - multiple nodes: несколько уровней с node-ами - fat nodes: у node-ы Преимущество перед деревом: - Легко пишется - Легко распараллеливается (можно вставлять несколько элементов одновременно) - Легко печатается $ P("есть i-ый уровень") = 1 - (1 - 1/(2^i)) underbrace(<=, "неравенство бернули") 1 - (1 - n/(2^i)) = n / (2^i) $ $ i = 4 log_2 n: P(i) <= n/(2^(4 log n)) = n/(n^4) = 1/(n^3) $ === Модификации Skip List-а - $p != 1/2$. - количество слоев: $log_(1/p) n$ - $O(1/p log_(1/p) n)$ - Лучший вариант $p = 1/e$, но на практике, вероятно, бесполезно. - Можно сделать только два слоя: получим корневую декомпозицию == Метод имитации отжига Пытаемся минимизировать некоторую величину (например, какой-нибудь путь в графе, расставить на доску ферзей, которые друг друга не бьют) -- функционал качества. Будем пытаться улучшить значение функционала: $Q_0 -> Q_1 -> ...$ #blk(title: [Плохой способ])[ Будем рандомно генерировать новое состояние и переходить на него только, если оно лучше. Не работает, так как можно попасть в локальный минимум, а не глобальный. ] Вводим понятие температуры $T_i$, функции, которая как-то убывает с каждой итерацией. Делаем случайное, небольшое изменение. Если функционал стал меньше, то переходим, иначе переходим с вероятностью: $ P = e^(-(Q_(i + 1) - Q_i) / T_i) $ Идея в том, что изначально (когда $T_i$ большое) у нас плохое состояние и не страшно его "потерять", перепрыгнув в другое. Потом (когда $T_i$ маленькое), состояние более хорошее и перепрыгивать мы хотим меньше.
https://github.com/mem-courses/calculus
https://raw.githubusercontent.com/mem-courses/calculus/main/homework-2/homework11.typ
typst
#import "../template.typ": * #show: project.with( course: "Calculus II", course_fullname: "Calculus (A) II", course_code: "821T0160", title: "Homework #11: 重积分", authors: ( ( name: "<NAME>", email: "<EMAIL>", id: "#198", ), ), semester: "Spring-Summer 2024", date: "May 7th, 2024", ) #let iintd = iintb($D$) #let iints = iintb($S$) #let iintsg = iintb($sigma$) #let iiintv = iiintb($V$) #let iiintog = iiintb($Omega$) = 习题9-3 == P171 2(2) #prob[ 利用适当方法计算三重积分: $ iiintv (x^2 + y^2 + z^2) dif V $ 其中 $V$:$a^2 <= x^2 + y^2 + z^2 <= b^2,space z >= 0$。 ] 令 $ cases( x = r sin theta cos psi, y = r sin theta sin psi, z = r cos theta, ) $ 则 $ iiintv (x^2 + y^2 + z^2) dif V &= int_0^(2 pi) dif theta int_0^(pi / 2) dif psi int_a^b r^2 dot r^2 sin psi dif r\ &= int_0^(2 pi) dif theta int_0^(pi / 2) sin psi dif psi int_a^b r^4 dif r\ &= (2 pi) / 5 (b^2 - a^2) $ == P172 2(4) #prob[ 利用适当方法计算三重积分: $ iiintb(Omega) (x+z) dif V $ 其中 $Omega$ 是由曲面 $z=sqrt(x^2 + y^2)$ 与 $z=sqrt(1-x^2-y^2)$ 所围成的区域。 ] 由对称性得 $ iiintb(Omega) x dif V = 0 $ 用球面坐标公式代换,可解得 $0<=psi<=display(pi/4)$,故 $ iiintb(Omega) (x+z) dif V = iiintb(Omega) z dif V = int_0^(2 pi) dif theta int_0^(pi / 4) dif psi int_0^1 r cos psi dot r^2 sin psi dif r = pi / 8 $ == P172 3 #prob[ 求函数 $f(x,y,z) = x^2 + y^2 + z^2$ 在区域 $x^2 + y^2 + z^2 <= x+y+z$ 内的平均值。 ] 令 $ Omega &= {(x,y,z) : x^2+y^2+z^2 <= x+y+z}\ &= {(x,y,z) : (x-1 / 2)^2 + (y-1 / 2)^2 + (z-1 / 2)^2 <= 3 / 4} $ 故 $ iiintog dif Omega = 4 / 3 pi (sqrt(3/4))^3 = sqrt(3) / 2 pi $ 令 $ cases( display(x = 1/2 + r sin theta cos psi), display(y = 1/2 + r sin theta sin psi), display(z = 1/2 + r cos theta), ) $ 得 $ iiintog f(x,y,z) dif Omega &= iiintog (r^2 + x+y+z- 3 / 4) dif Omega\ &= iiintog (r^2 + 3 / 4 + r sin theta cos psi + r sin theta sin psi + r cos theta) dif Omega\ &= int_(0)^(2 pi) dif theta int_0^(pi) dif psi int_0^(sqrt(3) / 2) (r^2 + 3 / 4) r^2 sin psi dif r\ &= 4pi (1 / 5 (sqrt(3) / 2)^5 + 1 / 4 (sqrt(3) / 2)^3) = (3sqrt(3)) / 5 pi $ 故 $ overline(f) = display(iiintog f(x,y,z) dif Omega) / display(iiintog dif Omega) = display((3sqrt(3))/5 pi) / display(sqrt(3)/2 pi) = 6 / 5 $ == P172 7 #prob[ 计算积分 $iiintb(Omega) (x+y+z)^2 dif V$,其中 $Omega:space x^2 + y^2 + z^2 <= R$。 ] 由对称性可知 $ iiintog x y dif Omega = iiintog x z dif Omega = iiintog y z dif Omega = 0 $ 故 $ I = iiintog (x+y+z)^2 dif Omega = iiintog (x^2 + y^2 + z^2) dif Omega $ 用球面坐标公式代换得 $ I = int_0^(2 pi) dif theta int_0^(pi) dif psi int_0^R r^4 sin psi dif r = 4 / 5 pi R^5 $ = 习题9-4 == P178 1(1) #prob[ 计算第一类曲线积分 $ intb(C) y^2 dif s $ 其中 $C$ 为摆线 $x=a (t - sin t),space y = a (1 - cos t) space (0<=t<=2 pi)$ 的一拱。 ] $ & x'(t) = a (1-cos t); quad quad y'(t) = a sin t \ ==> & dif s = sqrt(a^2 (1-cos t)^2 + a^2 sin^2 t) dif t = 2 a sin t / 2 dif t $ 故 $ intb(C) y^2 dif S &= 2 a^3 int_0^(2pi) sin t / 2 (1-cos t)^2 dif t = 32 a^3 int_0^(pi / 2) sin^5 t dif t = 32 a^3 dot 4 / 5 dot 2 / 3 dot 1 = 256 / 15 a^3 $ == P178 1(3) #prob[ 计算第一类曲线积分 $ intb(C) abs(y) dif s $ 其中 $C$ 为双纽线 $(x^2 + y^2)^2 = a^2 (x^2 - y^2)$ 的弧。 ] 作极坐标代换 $ x = r cos theta; quad quad y = r sin theta $ 得: $ (r^2 cos^2 theta + r^2 sin^2 theta)^2 &= a^2 (r^2 cos^2 theta - r^2 sin^2 theta) \ ==> r^4 &= a^2 r^2 (cos^2 theta - sin^2 theta)\ ==> r &= pm a sqrt(cos^2 theta - sin^2 theta) $ 故: $ (dif r) / (dif theta) = mp (2 a cos theta sin theta) / sqrt(cos^2 theta - sin^2 theta) $ 代入弧微分公式得: $ dif s &= sqrt(r^2 + r'^2 )dif theta = sqrt(a^2 (cos^2 theta - sin^2 theta) + 4 a^2 (cos^2 theta sin^2 theta)/(cos^2 theta - sin^2 theta)) dif theta\ &= a sqrt((cos^2 theta + sin^2 theta)^2/(cos^2 theta - sin^2 theta)) dif theta = a / sqrt(cos 2 theta) dif theta $ 故 $ intb(C) abs(y) dif s &= 4 int_0^(pi / 4) abs(r sin theta) (a dif theta) / (cos 2 theta) = 4 int_0^(pi / 4) a sqrt(cos 2 theta) sin theta dot a / sqrt(cos 2 theta) dif theta\ &= 4 a^2 int_0^(pi / 4) sin theta dif theta = 2a^2 (2-sqrt(2)) $ #align(center, image("images/2024-05-29-19-39-08.png", width: 60%)) == P178 1(5) #prob[ 计算第一类曲线积分 $ intb(C) (x^2 + y^2 + 1) dif s $ 其中 $C$ 为曲线 $display(cases( x^2 + y^2 + z^2 = 5, z = x^2 + y^2 + 1 ))$ ] 化简得 $ & x^2 + y^2 = 5 - z^2 = z-1\ ==>quad &z^2 + z - 6 = (z-2)(z+3) = 0\ ==>quad &z = 2 quad (z>1) $ 故曲线即 $x^2 + y^2 = 1$。 $ intb(C) (x^2+y^2+1) dif s = intb(C) 2 dif s = 2 dot 2 pi = 4pi $ = 习题9-5 == P189 5 #prob[ 设球在动点 $P(x,y,z)$ 的密度与该点至球心的距离成正比,求质量为 $M$ 的非均质球体 $x^2 + y^2 + z^2 <= R^2$ 对其直径的转动惯量。 ] 设密度函数 $rho(r) = k r$,则 $ M &= iiintv dif m = k iiintv r dif V = int_0^(2 pi) dif phi int_0^pi dif theta int_0^R r^3 sin theta dif r = k dot R^4 / 4 dot 2pi dot 2 = k pi R^4 $ 另根据转动惯量公式得 $ J &= iiintv r^2 dif m = k iiintv r^3 dif V = int_0^(2 pi) dif phi int_0^pi dif theta int_0^R r^5 sin theta dif r = k dot R^6 / 6 dot 2 pi dot 2 = 2 / 3 k pi R^6 $ 代入得 $ J = 2 / 3 M R^2 $ // #correction[ // 答案应该是 $display(4/9 M R^2)$(还没看出来哪错了)。 // ] == P189 6 #prob[ 求由曲面 $z=sqrt(x^2 + y^2),space z=1,space z=2$ 所围成的均质立体对质量为 $m$ 的质点 $A(0,0,0)$ 的引力,其中体密度为 $mu$。 ] 作柱面坐标代换 $ x = r cos theta; quad y = r sin theta; quad z = z quad (0<=theta<=2pi,space 0<=r<=z) $ 则万有引力为 $ F &= iiintv (G m) / (x^2 + y^2 + z^2) dif M = int_1^2 dif z int_0^(2 pi) dif theta int_0^(z) (G m) / (r^2 + z^2) r dif r \ &= 2 pi int_1^2 pi / (4 z) dif z = (pi^2) / 2 ln(2) $ // #correction[ // 好像算的也不对啊 // ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/grotesk-cv/0.1.3/template/content/references.typ
typst
Apache License 2.0
#import "@preview/grotesk-cv:0.1.3": reference-entry #import "@preview/fontawesome:0.4.0": * #let meta = toml("../info.toml") #let language = meta.layout.language == #fa-users() #h(5pt) #if language == "en" [References] else if language == "es" [Referencias] #v(5pt) #if language == "en" [ #reference-entry( name: [<NAME>, Resistance Leader], company: [Cyberdyne Systems], telephone: [+1 (555) 654-3210], email: [<EMAIL>], ) #reference-entry( name: [<NAME>, CEO], company: [Tyrell Corporation], telephone: [+1 (555) 987-6543], email: [<EMAIL>], ) ] else if language == "es" [ #reference-entry( name: [<NAME>, Líder de la Resistencia], company: [Cyberdyne Systems], telephone: [+1 (555) 654-3210], email: [<EMAIL>], ) #reference-entry( name: [<NAME>, CEO], company: [Tyrell Corporation], telephone: [+1 (555) 987-6543], email: [<EMAIL>], ) ]
https://github.com/fredguth/desid-report
https://raw.githubusercontent.com/fredguth/desid-report/main/README.md
markdown
# DESID-Report Format ## Installing ```bash quarto use template fredguth/desid-report ``` This will install the format extension and create an example qmd file that you can use as a starting place for your document. You can also add to existing project: ```bash quarto add fredguth/desid-report ``` and then add to the document metadata ``` format: DESID-Report-typst: default ```
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fh-joanneum-iit-thesis/1.2.3/template/chapters/4-concept.typ
typst
Apache License 2.0
#import "global.typ": * = Concept #lorem(30) #todo( [ Describe an overall concept of a solution, which could possibly solve a given problem. Design a novel solution and visualise the architecture and relevant (data) flows. Compare and relate your approach to possible alternatives and argue why and in which way(s) the suggested solution(s) will be better. ], ) #todo( [ #v(3cm) *Hints for formatting in Typst*: + You can use built-in styles: + with underscore (\_) to _emphasise_ text + forward dash (\`) for `monospaced` text + asterisk (\*) for *strong* (bold) text You can create and use your own (custom) formatting macros: + check out the custom style (see in file `lib.typ`): + `#textit` for #textit([italic]) text + `#textbf` for #textbf([bold face]) text ], )
https://github.com/loicreynier/sandbox
https://raw.githubusercontent.com/loicreynier/sandbox/main/.github/README.md
markdown
The Unlicense
<!-- markdownlint-disable MD033 --> <h1 align="center">:parasol_on_ground:</h1> <!-- markdownlint-enable MD033 --> Sandbox environment for conducting small tests that I maintain a record of. ## Sand castles <!-- markdownlint-disable MD013 --> - [`advection-stab`](../advection-stab): Python script to study Euler methods' stability for the advection equation. - [`acc-demo`](../acc-demo): [OpenACC](https://www.openacc.org) Fortran sample. - [`amgx-demo`](../amgx-demo): [AMGX](https://developer.nvidia.com/amgx) sample using a Fortran interface. - [`coconut-factorial`](../coconut-factorial): Elegant and pointless factorial implementation in [Coconut](http://coconut-lang.org). - [`cuda-demo`](../cuda-demo): Small CUDA samples. - [`detect-windarkmode`](../detect-windarkmode): Dirty function to detect Windows dark mode. - [`f03cli`](../f03cli): Fortran 2003 CLI argument parser example. - [`gmres-scipy`](../gmres-scipy): Wrapper for the GMRES provided by SciPy. - [`gmres.py`](../gmres.py): Dirty unoptimized Python implementation of the GMRES algorithm. - [`isosurf-skimage`](../isosurf-skimage): Isosurface calculation with scikit-image example. - [`jmtpfs-pyudev`](../jmtpfs-pyudev): MTP device monitoring and mounting dirty script using `jmtpfs` and pyudev. - [`multigrid-laplace2d.py`](../multigrid-laplace2d.py): Dirty unoptimized Python implementation of the multigrid method for solving the 2D Laplace equation. - [`nix-derivs`](../nix-derivs): Stuff build with Nix™. - [`numbat-demo`](../numbat-demo): Small scripts to test [Numbat](https://numbat.dev) features. - [`porn.py`](../porn.py): Cool and horrific miscellaneous Python stuff. - [`presenterm-demo`](../presenterm-demo): Presentation written using [presenterm](https://github.com/mfontanini/presenterm) to test its features. - [`pwsh-magic`](../pwsh-magic): Random PowerShell scripts. - [`pyfftw-demo`](../pyfftw-demo): PyFFTW example scripts. - [`python-perf`](../python-perf): Python performance test scripts. - [`regula-falsi.c`](../regula-falsi.c): Unoptimized C implementation of the Regula Falsi method. - [`rnm-go`](../rnm-go): Useless CLI util to rename files written in Go. - [`spotify-export`](../spotify-export): Python script to export Spotify playlists to CSV files. - [`spotify-opus2mp3`](../spotify-opus2mp3): Python script to convert OPUS files to MP3 for Spotify local use. - [`typst-demo`](../typst-demo): Sandbox article written using [Typst](https://typst.app) to test its features.
https://github.com/maucejo/book_template
https://raw.githubusercontent.com/maucejo/book_template/main/template/appendix/app_main.typ
typst
MIT License
#include "app1.typ" #include "app2.typ"
https://github.com/Pablo-Gonzalez-Calderon/showybox-package
https://raw.githubusercontent.com/Pablo-Gonzalez-Calderon/showybox-package/main/manual/template.typ
typst
MIT License
#import "../showy.typ": * #let version = "2.0.2" #let front-page(body) = { set document(author: "Showybox Contributors", title: "Showybox Manual") set page(numbering: "1", number-align: center) set text(size: 12pt, font: "HK Grotesk", lang: "en") set heading(numbering: "1.1.") show heading.where(level: 3) : it => { text(font: "Cascadia Code", size: 10.5pt, it.body.text) } show heading: set block(spacing: 1em) show raw.where(block: false): box.with( fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) show link : it => { text(blue, it) } set list(indent: .5cm) v(1fr) showybox( frame: ( inset: 2em, footer-inset: (x: 1em, y: 0.65em) ), title-style: ( align: center ), body-style: ( align: center ), footer-style: ( align: center, weight: "regular" ), title: text(2.5em, weight: 700, "Showybox's Manual"), text(size: 1.5em, "Updated for version " + version), footer: [Colorful and customizable boxes for Typst #emoji.rocket] ) v(2fr) pagebreak() outline(depth: 2, indent: true) pagebreak() set par(justify: true) body } #let line-raw(value) = raw( lang: "typc", block: false, value ) #let types-color-dict = ( "string": rgb("#d1ffe2"), "dictionary": rgb("#eff0f3"), "alignment": rgb("#eff0f3"), "2d-alignment": rgb("#eff0f3"), "array": rgb("#eff0f3"), "none": rgb("#ffcbc4"), "content": rgb("#a6ebe6"), "boolean": rgb("#ffedc1"), "length": rgb("#e7d9ff"), "integer": rgb("#e7d9ff"), "relative-length": rgb("#e7d9ff"), "body": rgb("#a6ebe6"), ) #let type-block(type) = if type != "color"{ return box( fill: types-color-dict.at(type, default: white), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, text( font: "Cascadia Code", size: 10.5pt, type ) ) } else { return box( height: 13pt, baseline: 3pt, )[ #image("../assets/gradient.svg") #place( center + horizon, text( font: "Cascadia Code", size: 10.5pt, type ) ) ] } #let observation(..body) = showybox( frame: ( title-color: blue.darken(40%), border-color: blue.darken(40%), body-color: blue.lighten(95%), radius: 0pt ), title: [*Observation*], ..body ) #let sbox-parameters() = showybox( frame: ( radius: 3pt, inset: 1em, body-color: luma(250), border-color: luma(200), thickness: 0.6pt ), shadow: ( offset: 1.5pt, color: luma(200) ), breakable: true, text( font: "Cascadia Code", size: 10.5pt )[ #text(rgb("#4b69c6"), "showybox")\( #h(12pt) title: #type-block("string") #type-block("content") #h(12pt) footer: #type-block("string") #type-block("content") #h(12pt) frame: #type-block("dictionary") #h(12pt) title-style: #type-block("dictionary") #h(12pt) body-style: #type-block("dictionary") #h(12pt) footer-style: #type-block("dictionary") #h(12pt) sep: #type-block("dictionary") #h(12pt) shadow: #type-block("dictionary") #type-block("none") #h(12pt) width: #type-block("relative-length") #h(12pt) align: #type-block("alignment") #type-block("2d-alignment") #h(12pt) breakable: #type-block("boolean") #h(12pt) spacing: #type-block("relative-length") #h(12pt) spacing: #type-block("relative-length") #h(12pt) above: #type-block("relative-length") #h(12pt) below: #type-block("relative-length") #h(12pt) ..#type-block("body") ) -> #type-block("body") ] ) #let frame-parameters() = showybox( frame: ( radius: 3pt, inset: 1em, body-color: luma(250), border-color: luma(200), thickness: 0.6pt ), shadow: ( offset: 1.5pt, color: luma(200) ), breakable: true, text( font: "Cascadia Code", size: 10.5pt )[ ... frame: \( #h(12pt) title-color: #type-block("color") #h(12pt) body-color: #type-block("color") #h(12pt) footer-color: #type-block("color") #h(12pt) border-color: #type-block("color") #h(12pt) radius: #type-block("relative-length") #type-block("dictionary") #h(12pt) thickness: #type-block("length") #type-block("dictionary") #h(12pt) dash: #type-block("string") #h(12pt) inset: #type-block("relative-length") #type-block("dictionary") #h(12pt) title-inset: #type-block("relative-length") #type-block("dictionary") #h(12pt) body-inset: #type-block("relative-length") #type-block("dictionary") #h(12pt) footer-inset: #type-block("relative-length") #type-block("dictionary") ), ... ] ) #let title-style-parameters() = showybox( frame: ( radius: 3pt, inset: 1em, body-color: luma(250), border-color: luma(200), thickness: 0.6pt ), shadow: ( offset: 1.5pt, color: luma(200) ), breakable: true, text( font: "Cascadia Code", size: 10.5pt )[ ... title-style: \( #h(12pt) color: #type-block("color") #h(12pt) weight: #type-block("integer") #type-block("string") #h(12pt) align: #type-block("alignment") #type-block("2d-alignment") #h(12pt) sep-thickness: #type-block("length") #h(12pt) boxed-style: #type-block("dictionary") #type-block("none") ), ... ] ) #let boxed-style-parameters() = showybox( frame: ( radius: 3pt, inset: 1em, body-color: luma(250), border-color: luma(200), thickness: 0.6pt ), shadow: ( offset: 1.5pt, color: luma(200) ), breakable: true, text( font: "Cascadia Code", size: 10.5pt )[ ... title-style: \( #h(12pt) ..., #h(12pt) boxed-style \( #h(24pt) anchor: #type-block("dictionary") #h(24pt) offset: #type-block("dictionary") #h(24pt) radius: #type-block("relative-length") #type-block("dictionary") #h(12pt) ), #h(12pt) ... ), ... ] ) #let body-style-parameters() = showybox( frame: ( radius: 3pt, inset: 1em, body-color: luma(250), border-color: luma(200), thickness: 0.6pt ), shadow: ( offset: 1.5pt, color: luma(200) ), breakable: true, text( font: "Cascadia Code", size: 10.5pt )[ ... body-style: \( #h(12pt) color: #type-block("color") #h(12pt) align: #type-block("alignment") #type-block("2d-alignment") ), ... ] ) #let footer-style-parameters() = showybox( frame: ( radius: 3pt, inset: 1em, body-color: luma(250), border-color: luma(200), thickness: 0.6pt ), shadow: ( offset: 1.5pt, color: luma(200) ), breakable: true, text( font: "Cascadia Code", size: 10.5pt )[ ... footer-style: \( #h(12pt) color: #type-block("color") #h(12pt) weight: #type-block("integer") #type-block("string") #h(12pt) align: #type-block("alignment") #type-block("2d-alignment") #h(12pt) sep-thickness: #type-block("length") ), ... ] ) #let sep-parameters() = showybox( frame: ( radius: 3pt, inset: 1em, body-color: luma(250), border-color: luma(200), thickness: 0.6pt ), shadow: ( offset: 1.5pt, color: luma(200) ), breakable: true, text( font: "Cascadia Code", size: 10.5pt )[ ... sep: \( #h(12pt) thickness: #type-block("length") #h(12pt) dash: #type-block("string") #h(12pt) gutter: #type-block("relative-length") ), ... ] ) #let shadow-parameters() = showybox( frame: ( radius: 3pt, inset: 1em, body-color: luma(250), border-color: luma(200), thickness: 0.6pt ), shadow: ( offset: 1.5pt, color: luma(200) ), breakable: true, text( font: "Cascadia Code", size: 10.5pt )[ ... shadow: \( #h(12pt) color: #type-block("color") #h(12pt) offset: #type-block("relative-length") #type-block("dictionary") ), ... ] )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1F780.typ
typst
Apache License 2.0
#let data = ( ("BLACK LEFT-POINTING ISOSCELES RIGHT TRIANGLE", "So", 0), ("BLACK UP-POINTING ISOSCELES RIGHT TRIANGLE", "So", 0), ("BLACK RIGHT-POINTING ISOSCELES RIGHT TRIANGLE", "So", 0), ("BLACK DOWN-POINTING ISOSCELES RIGHT TRIANGLE", "So", 0), ("BLACK SLIGHTLY SMALL CIRCLE", "So", 0), ("MEDIUM BOLD WHITE CIRCLE", "So", 0), ("BOLD WHITE CIRCLE", "So", 0), ("HEAVY WHITE CIRCLE", "So", 0), ("VERY HEAVY WHITE CIRCLE", "So", 0), ("EXTREMELY HEAVY WHITE CIRCLE", "So", 0), ("WHITE CIRCLE CONTAINING BLACK SMALL CIRCLE", "So", 0), ("ROUND TARGET", "So", 0), ("BLACK TINY SQUARE", "So", 0), ("BLACK SLIGHTLY SMALL SQUARE", "So", 0), ("LIGHT WHITE SQUARE", "So", 0), ("MEDIUM WHITE SQUARE", "So", 0), ("BOLD WHITE SQUARE", "So", 0), ("HEAVY WHITE SQUARE", "So", 0), ("VERY HEAVY WHITE SQUARE", "So", 0), ("EXTREMELY HEAVY WHITE SQUARE", "So", 0), ("WHITE SQUARE CONTAINING BLACK VERY SMALL SQUARE", "So", 0), ("WHITE SQUARE CONTAINING BLACK MEDIUM SQUARE", "So", 0), ("SQUARE TARGET", "So", 0), ("BLACK TINY DIAMOND", "So", 0), ("BLACK VERY SMALL DIAMOND", "So", 0), ("BLACK MEDIUM SMALL DIAMOND", "So", 0), ("WHITE DIAMOND CONTAINING BLACK VERY SMALL DIAMOND", "So", 0), ("WHITE DIAMOND CONTAINING BLACK MEDIUM DIAMOND", "So", 0), ("DIAMOND TARGET", "So", 0), ("BLACK TINY LOZENGE", "So", 0), ("BLACK VERY SMALL LOZENGE", "So", 0), ("BLACK MEDIUM SMALL LOZENGE", "So", 0), ("WHITE LOZENGE CONTAINING BLACK SMALL LOZENGE", "So", 0), ("THIN GREEK CROSS", "So", 0), ("LIGHT GREEK CROSS", "So", 0), ("MEDIUM GREEK CROSS", "So", 0), ("BOLD GREEK CROSS", "So", 0), ("VERY BOLD GREEK CROSS", "So", 0), ("VERY HEAVY GREEK CROSS", "So", 0), ("EXTREMELY HEAVY GREEK CROSS", "So", 0), ("THIN SALTIRE", "So", 0), ("LIGHT SALTIRE", "So", 0), ("MEDIUM SALTIRE", "So", 0), ("BOLD SALTIRE", "So", 0), ("HEAVY SALTIRE", "So", 0), ("VERY HEAVY SALTIRE", "So", 0), ("EXTREMELY HEAVY SALTIRE", "So", 0), ("LIGHT FIVE SPOKED ASTERISK", "So", 0), ("MEDIUM FIVE SPOKED ASTERISK", "So", 0), ("BOLD FIVE SPOKED ASTERISK", "So", 0), ("HEAVY FIVE SPOKED ASTERISK", "So", 0), ("VERY HEAVY FIVE SPOKED ASTERISK", "So", 0), ("EXTREMELY HEAVY FIVE SPOKED ASTERISK", "So", 0), ("LIGHT SIX SPOKED ASTERISK", "So", 0), ("MEDIUM SIX SPOKED ASTERISK", "So", 0), ("BOLD SIX SPOKED ASTERISK", "So", 0), ("HEAVY SIX SPOKED ASTERISK", "So", 0), ("VERY HEAVY SIX SPOKED ASTERISK", "So", 0), ("EXTREMELY HEAVY SIX SPOKED ASTERISK", "So", 0), ("LIGHT EIGHT SPOKED ASTERISK", "So", 0), ("MEDIUM EIGHT SPOKED ASTERISK", "So", 0), ("BOLD EIGHT SPOKED ASTERISK", "So", 0), ("HEAVY EIGHT SPOKED ASTERISK", "So", 0), ("VERY HEAVY EIGHT SPOKED ASTERISK", "So", 0), ("LIGHT THREE POINTED BLACK STAR", "So", 0), ("MEDIUM THREE POINTED BLACK STAR", "So", 0), ("THREE POINTED BLACK STAR", "So", 0), ("MEDIUM THREE POINTED PINWHEEL STAR", "So", 0), ("LIGHT FOUR POINTED BLACK STAR", "So", 0), ("MEDIUM FOUR POINTED BLACK STAR", "So", 0), ("FOUR POINTED BLACK STAR", "So", 0), ("MEDIUM FOUR POINTED PINWHEEL STAR", "So", 0), ("REVERSE LIGHT FOUR POINTED PINWHEEL STAR", "So", 0), ("LIGHT FIVE POINTED BLACK STAR", "So", 0), ("HEAVY FIVE POINTED BLACK STAR", "So", 0), ("MEDIUM SIX POINTED BLACK STAR", "So", 0), ("HEAVY SIX POINTED BLACK STAR", "So", 0), ("SIX POINTED PINWHEEL STAR", "So", 0), ("MEDIUM EIGHT POINTED BLACK STAR", "So", 0), ("HEAVY EIGHT POINTED BLACK STAR", "So", 0), ("VERY HEAVY EIGHT POINTED BLACK STAR", "So", 0), ("HEAVY EIGHT POINTED PINWHEEL STAR", "So", 0), ("LIGHT TWELVE POINTED BLACK STAR", "So", 0), ("HEAVY TWELVE POINTED BLACK STAR", "So", 0), ("HEAVY TWELVE POINTED PINWHEEL STAR", "So", 0), ("CIRCLED TRIANGLE", "So", 0), ("NEGATIVE CIRCLED TRIANGLE", "So", 0), ("CIRCLED SQUARE", "So", 0), ("NEGATIVE CIRCLED SQUARE", "So", 0), ("NINE POINTED WHITE STAR", "So", 0), (), (), (), (), (), (), ("LARGE ORANGE CIRCLE", "So", 0), ("LARGE YELLOW CIRCLE", "So", 0), ("LARGE GREEN CIRCLE", "So", 0), ("LARGE PURPLE CIRCLE", "So", 0), ("LARGE BROWN CIRCLE", "So", 0), ("LARGE RED SQUARE", "So", 0), ("LARGE BLUE SQUARE", "So", 0), ("LARGE ORANGE SQUARE", "So", 0), ("LARGE YELLOW SQUARE", "So", 0), ("LARGE GREEN SQUARE", "So", 0), ("LARGE PURPLE SQUARE", "So", 0), ("LARGE BROWN SQUARE", "So", 0), (), (), (), (), ("HEAVY EQUALS SIGN", "So", 0), )
https://github.com/francescoo22/kt-uniqueness-system
https://raw.githubusercontent.com/francescoo22/kt-uniqueness-system/main/src/annotation-system/while-loops-experiments.typ
typst
#import "rules/base.typ": * #import "rules/relations.typ": * #import "rules/unification.typ": * #import "rules/statements.typ": * #import "../vars.typ": * #pagebreak() == While Loops The process of typing a while statement from a context $Delta$ involves unifying $Delta$ with the resulting context after executing the body of the while loop. This unification is repeated with the context obtained until a fixed point is reached. === First approach Given a statement $s$, we can define a funtion $u_s : Delta -> Delta$ as follows: #display-rules( U-Fun, "" ) Then we can define the following sequence: $ Delta, u_s (Delta), u_s (u_s (Delta)), ..., u_s^n (Delta), ... $ After defining an ordering ($subset.eq.sq$) between contexts it will be possible to show that this sequence is an ascending chain i.e. $ Delta subset.eq.sq u_s (Delta) subset.eq.sq u_s (u_s (Delta)) subset.eq.sq ... subset.eq.sq u_s^n (Delta) subset.eq.sq ... $ Moreover it will be possible to show that chain at some point will reach a fixed-point: $ forall Delta . forall s . exists n . space u_s^n (Delta) = u_s^(n + 1) (Delta) = u_s^* (Delta) $ And so now it is possible to define the typing rule for while loops as follows: #display-rules( While, "" ) === Alternative approach Simpler approach with no guarantees on the termination of the typing algorithm #display-rules( While-Base, While-Rec, )
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Philosophie_Creation.typ
typst
#import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "Philosophie Creation", authors: ( "<NAME>", ), date: "13 Juin, 2024", ) #set heading(numbering: "1.1.") = Thèses en présence <thèses-en-présence> == Thèse 1 <thèse-1> La création artistique est le résultat d’un apprentissage. == Thèse 2 <thèse-2> La création artistique est le résultat du génie, de l’inspiration. = Arguments des thèses dans les textes <arguments-des-thèses-dans-les-textes> == Thèse 1~ <thèse-1-1> La création artistique est le résultat d’un apprentissage. Elle consiste à répéter longtemps des gestes sur la matière spécifique de l’art (pierre, instrument, mots, peinture). Elle compose à partir d’une culture, d‘un héritage, de techniques et œuvres déjà là. Il faut donc les apprendre. On peut concevoir ce que l’on va faire avant que ce soit fait == Thèse 2 <thèse-2-1> La création artistique est le résultat de l’inspiration, voire du génie. On ne peut apprendre à inventer. On ne peut apprendre à être inspiré à partir d’autres artistes, on ne peut apprendre à inventer grâce à l’entraînement. On ne peut savoir quand la création apparaîtra, on ne peut maîtriser l’inspiration. Elle est imprévisible. Elle rompt avec ce qui existait avant, elle est invention. Ce qui est créé ne peut être pensé/conçu avant d’être créé. = Problématique <problématique> La création est-elle le résultat de l’imitation de la reproduction dû à l’effort conscient de l’artiste ou est-elle le résultat d’une inspiration, d’un surgissement que même l’artiste ne maîtrise pas~? = Synthèse des idées~: <synthèse-des-idées> + Toute création suppose un apprentissage, un savoir-faire, et un projet, une intention créatrice + Mais la création consiste en nouveauté et ce qui va être créé ne peut être conçu avant d’être fait. La création s’opère sous le coup de l’inspiration, d’une force aveugle + Sans doute cette inspiration a besoin d’être éduquée pour trouver sa forme, son style + Mais cette éducation ne doit pas se contenter d’imitation de modèle mais doit laisser la place à la liberté
https://github.com/Chwiggy/thesis_bachelor
https://raw.githubusercontent.com/Chwiggy/thesis_bachelor/main/src/abstract_en.typ
typst
This thesis tries to establish two indicators for public transit analysis. These indicators are based in a thorough reading of the literature as well as an explorative data analysis phase based on openly available data. These indicators were tested on a case study, for which Heidelberg, Germany was selected due to the familiarity and local knowledge of the author. These indicators are based on a conceptualisation of reach based on grid cells and an approximation of an inverse closeness centrality. A difference in favourable and unfavourable departure times was used to establish an indicator for the need to plan. For the purpose of analysis a `h3` hexagonal grid was laid over the study area, and bi-modal travel times were calculated between each cell pairing with `r5py`. Population data was used to filter cells. A literature gap was identified in the daily variation of travel time analysis, so for each of the two indicators they were computed for every hour of the day, covering a full 24 hours. The travel time indicator displays expected features of a travel time dataset, but lacks more informed choices of itinerary scenarious for a deeper analysis. The temporal variation however suggests that not all areas of a city are necessarily served equally well during the day, and specific features of transit infrastructure can even disadvantage otherwise central cells in off peak travel. The planning indicator, unfortunately, turned out to be hard to operationalise correctly, based on limited routing options. Both indicators need further work in fine tuning and potentially the set of indicators needs to grow to sufficiently describe a public transit system in all its complexity.
https://github.com/Otto-AA/definitely-not-tuw-thesis
https://raw.githubusercontent.com/Otto-AA/definitely-not-tuw-thesis/main/template/thesis.typ
typst
MIT No Attribution
#import "@preview/definitely-not-tuw-thesis:0.1.0": * #show: general-styles #show: thesis.with( lang: "en", title: (en: "An ode for Lord Ipsum", de: "Eine Ode an Lord Ipsum"), subtitle: (:), thesis-type: (en: "Diploma Thesis", de: "Diplomarbeit"), academic-title: (de: "Diplom-Ingenieur", en: "Diplom-Ingenieur"), curriculum: (en: "Software Engineering & Internet Computing", de: "Software Engineering & Internet Computing "), author: (name: "<NAME>", student-number: 11223344), advisor: (name: "<NAME>", pre-title: "Univ.Prof.Dr."), assistants: ((name: "Ipsinator", pre-title: "Sir"),), reviewers: (), keywords: ("Lorem Ipsum"), font: "DejaVu Sans", date: datetime.today(), ) #show: flex-caption-styles #show: toc-styles #show: front-matter-styles // If you have non-image/table figures, you need to pass a "supplement", that is shown when referencing it (@my-alg). You can globally set this, e.g. for algorithms: #show figure.where(kind: "algorithm"): set figure(supplement: "Algorithm") #include "content/front-matter.typ" #outline() #show: main-matter-styles #show: page-header-styles #include "content/main.typ" #show: back-matter-styles #set page(header: none) #outline(title: "List of Figures", target: figure.where(kind: image)) #outline(title: "List of Tables", target: figure.where(kind: table)) #outline(title: "List of Algorithms", target: figure.where(kind: "algorithm")) #bibliography("refs.bib") #show: appendix-styles #include "content/appendix.typ"
https://github.com/giZoes/justsit-thesis-typst-template
https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/pages/acknowledgement.typ
typst
MIT License
// 致谢页 #let acknowledgement( // documentclass 传入参数 anonymous: false, twoside: false, // 其他参数 title: "致谢", outlined: true, body, ) = { if (not anonymous) { pagebreak(weak: true, to: if twoside { "odd" }) [ #heading(level: 1, numbering: none, outlined: outlined, title,) <no-auto-pagebreak> #body ] } }
https://github.com/alikindsys/aula
https://raw.githubusercontent.com/alikindsys/aula/master/Matematica/math.typ
typst
#import "../Core/prelude.typst": * #let glossario-matematica = ( Função:( description:[ Uma função é uma relação de um conjunto $A$ com um conjunto $B$. Denotamos uma função por $f: A -> B, y(x) = f(x)$. ], link: [https://pt.wikipedia.org/wiki/Fun%C3%A7%C3%A3o_(matem%C3%A1tica)] ) ) #let matematica(doc) = [ #show: aula(materia: [Matemática], glossary: glossario-matematica, doc); ]
https://github.com/CFiggers/typst-companion
https://raw.githubusercontent.com/CFiggers/typst-companion/main/README.md
markdown
Other
# Typst Companion A VS Code extension that adds Markdown-like editing niceties **on top of and in addition to** to <NAME>'s [Typst LSP](https://github.com/nvarner/typst-lsp). ## Features - Intuitive handling of Ordered and Unordered lists in `.typ` files. - `Enter` while in a list context (either ordered or unordered) continues the existing list at the current level of indentation (with correct numbering, if ordered). - `Tab` and `Shift+Tab` while in a list context (either ordered or unordered) indents and out-dents bullets intuitively (and re-numbers ordered lists if appropriate). - Reordering lines inside an ordered list automatically updates the list numbers accordingly. - Keyboard Shortcuts for: - Toggle Bold, Italics, and Underline (`ctrl/cmd + b|i|u`) - Increase and decrease header level (`ctrl/cmd + shift + ]|[`) - Insert a page break (`ctrl/cmd + enter`, when not in a list context) ## Requirements I *strongly* encourage installing <NAME>ner's [Typst LSP](https://github.com/nvarner/typst-lsp) in addition to this extension for syntax highlighting, error reporting, code completion, and all of Typst LSP's other features. This extension just adds some small additional features that I missed when using Typst LSP. ## Release Notes ### 0.0.5 - Will no longer warn if [tinymist](https://github.com/Myriad-Dreamin/tinymist) LSP is installed rather than [Typst LSP](https://github.com/nvarner/typst-lsp). For previous versions, see the [CHANGELOG on GitHub](https://github.com/CFiggers/typst-companion/blob/main/CHANGELOG.md). ## Prior Art The core logic of this extension is adapted, with attribution and gratitude, from [Markdown All-in-One](https://github.com/yzhang-gh/vscode-markdown/), under the following license: MIT License, Copyright (c) 2017 张宇
https://github.com/timetraveler314/Note
https://raw.githubusercontent.com/timetraveler314/Note/main/Discrete/categories.typ
typst
#import "@local/MetaNote:0.0.1" : * #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge #let Ccat = math.cal($C$) #let CSet = math.serif("Set") #let Vect = math.serif("Vect") #let opp = "op" #let ev = math.op("ev") #let Ob = math.op("Ob") #let Yon = "よ" #let Fct = math.op("Fct") #let Hom = math.op("Hom") #let Nat = math = Categories == Yoneda Lemma From the enlightening view of the Yoneda perspective, we deduce that objects in a category are uniquely determined by their morphisms, up to isomorphism. To work with their morphismic representations, we will work in the so-called _presheaf category_ $Ccat^and := Fct(Ccat^opp, CSet)$. #definition("Presheaf Category")[ The presheaf category $C^and$ is the category of contravariant functors from $C$ to $CSet$, i.e. functors $F: C^opp -> CSet$. The morphisms in $C^and$ are natural transformations between these functors. Similarly, we can define the _copresheaf category_: $ C^and &:= Fct(Ccat^opp, CSet) \ C^or &:= Fct(Ccat^opp, CSet^opp) = Fct(Ccat, CSet)^opp $ ] Now we can formally define the Yoneda embedding, which maps an object $X$ in $C$ to the contravariant functor that sends an vantage object $Z$ to the set of morphisms $Hom(Z, X)$. #definition("Yoneda Embedding")[ The Yoneda embedding $Yon: Ccat -> Ccat^and$ is defined by $ Yon &: Ccat -> Ccat^and \ & S |-> Hom_Ccat (-, S). $ ] Naturally, we have the evaluation functor $ev: Ccat^and times Ccat -> CSet$ that evaluates a presheaf $F$ at an object $X$, leading to the set $F(X)$. #definition("Evaluation Functor")[ The evaluation functor $ev^and: Ccat^and times Ccat -> CSet$ is defined by $ ev^and &: Ccat^and times Ccat -> CSet \ & (F, X) |-> F(X). $ ] Now we can state the Yoneda lemma, which asserts that the Yoneda embedding is fully faithful as a consequence. #theorem("Yoneda")[ For any object $S in Ob(Ccat)$ and any presheaf $F in Ob(Ccat^and)$, we have a natural bijection from natural transformations $eta$ to elements in $F(S)$, given by $ Phi &: Hom_(Ccat^and) (Yon(S), F) -> F(S) \ & [eta, Hom_Ccat (-,S) ->^eta F(-)] |-> eta_S (id_S), $ which gives rise to a natural functor isomorphism $Hom_(Ccat^and) (Yon(-), -) tilde.equiv ev^and$. As a result, the Yoneda embedding $Yon$ is fully faithful. ] #proof[ For any morphism $f : T->S$ in $Ccat$, let $u_s := eta_S (id_S) in F(S)$. The following diagram suffices to prove the Yoneda lemma: #align(center)[ #diagram( node((0, 0), $Hom_C (S,S)$), node((0, 1), $Hom_C (T,S)$), node((1, 0), $F(S)$), node((1, 1), $F(T)$), edge((0, 0), (0, 1), "->", $"pullback" f^*$), edge((0, 0), (1, 0), "->", $eta_S$), edge((0, 1), (1, 1), "->", $eta_T$), edge((1, 0), (1, 1), "->", $F(f)$), node((-0.5, 0), $in$), node((-1, 0), $id_S$), node((-0.5, 1), $in$), node((-1, 1), $f$), edge((-1, 0), (-1, 1), "|->"), node((1.5, 0), $in.rev$), node((2, 0), $u_S$), node((1.5, 1), $in.rev$), node((2, 1), $eta_T (f)$), edge((2, 0), (2, 1), "|->"), )] Explanation: To show $Phi$ is a bijection, it suffices to construct an inverse $Psi$. Assume that $Psi(eta_S (id_S)) = beta$, then if $beta = eta$ holds, we have (as is shown in the diagram) $ Psi(eta_S (id_S))_T (f compose id_S) = F(f)(eta_S (id_S)). $ Hence we wish to define $Psi$ as $ forall x in F(S), Psi(x)_T (f compose id_S) = F(f)(x). $ Now in turn we should verify $Psi(x) = beta$ is indeed natural, i.e. whether the diagram commutes replacing $eta$ to $beta$. For any $g in Hom_Ccat (Q,P)$: #align(center)[ #diagram( node((0, 0), $Hom_C (P,S)$), node((0, 1), $Hom_C (Q,S)$), node((1, 0), $F(P)$), node((1, 1), $F(Q)$), edge((0, 0), (0, 1), "->", $"pullback" g^*$), edge((0, 0), (1, 0), "->", $beta_P$), edge((0, 1), (1, 1), "->", $beta_Q$), edge((1, 0), (1, 1), "->", $F(g)$), )] For any $h in Hom_Ccat (P,S)$, $ beta_P (h) = Psi(x)_P (h compose id_S) = F(h)(x), F(g)(F(h)(x)) = F(g compose h) (x) \ beta_Q (g compose h) = F(g compose h) (x). $ The diagram commutes. Then it remains to show $Psi compose Phi = Phi compose Psi = id$. (i) $ Psi(Phi(eta)) = Psi(eta_S (id_S)) = f |-> F(f)(eta_S (id_S)) = f |-> eta_T (f compose id_S) $ which is just $eta$! (ii) $ Phi(Psi(x)) = Psi(x)_S (id_S) = F(id_S) (x) = x. $ Finally, Substituting $F = Yon(T)$ gives bijection $Hom_(Ccat^and) (Yon(S),Yon(T)) <-> Hom_Ccat (S,T) = F(S)$. This shows that $Yon$ is fully faithful by definition. ] Now that objects are basically the same thing as all the morphisms related to it, we will often omit the Yoneda embedding $Yon$ and see $Ccat$ as a full subcategory of $Ccat^and$. We might want to extend the concept to other presheaf in $Ccat^and$, i.e. whether it stands for a object in $Ccat$. So here comes the definition of _representable functor_, which will later be proved to show the property by its universal property. #definition("Representable Functor")[ We call $A: C^opp -> CSet$ a _representable functor_, if there exists $X in Ob(Ccat)$ and isomorphism $ phi: Yon(X) ->^tilde A, $ and $(X, phi)$ its _representation element_. ] In terms of the comma category, the representation element can be embedded into $(Yon slash A)$, corresponding to the functor $Ccat ->^Yon Ccat^and <-^(j_A) bold(1)$. Now we can state and prove the universal property and show why the representation element really lives up to its name, as we did to free vector spaces. #theorem("Universal Property of Representation Element")[ If $A$ is a representable functor, then its representation element is unique up to isomorphism. ] #proof[ For any $Y in Ob(Ccat), psi : Yon(Y)->A$, the following diagram #align(center)[ #diagram( node((0, 0), $Yon(Y)$), node((1, 0), $Yon(X)$), node((1, 1), $A$), edge((0, 0), (1, 1), "->", $psi$), edge((0, 0), (1, 0), "->", $Yon(f)$), edge((1, 0), (1, 1), "<->", $phi$,), )] commutes for some unique $f in Hom(Y,X)$, because $Yon(f) = phi^(-1) compose psi$ and the fully faithfulness of $Yon$. By definiton of $(Yon slash A)$, $(X,phi)$ is its final object, and uniqueness is hence determined. ] #example[ Review the free vector space functor $V : CSet -> Vect$, whose universal property gives the isomorphism $ Hom_CSet (X, U(-)) ->^tilde Hom_Vect (V(X),-) $ Hence $V(X)$ and the above mapping represents the functor $Hom_CSet (X,U(-))$. ]
https://github.com/DaAlbrecht/lecture-notes
https://raw.githubusercontent.com/DaAlbrecht/lecture-notes/main/computer_networks/network_layer.typ
typst
MIT License
#import "../template.typ": * = Network Layer The network layer is the third layer of the OSI model, responsible for routing packets across different networks. It provides logical addressing, routing, and packet forwarding. The network layer is implemented in routers and end systems. == Circuit Switching Circuit switching is a method of establishing a dedicated communication path between two devices in a network. The path is reserved for the duration of the communication session. Circuit switching is used in traditional telephone networks. == Packet Switching Packet switching is a method of transmitting data in a network. Data is divided into packets, which are sent independently to the destination. Packets may take different paths to reach the destination. Packet switching is used in computer networks. === Datagram Packet Switching In datagram packet switching, each packet is treated independently and may take a different path to reach the destination. It is connectionless and does not establish a dedicated path for communication. Datagram packet switching is used in IP networks. === Virtual Circuit Packet Switching In virtual circuit packet switching, a path is established before data transfer begins. Packets follow the same path and are identified by a virtual circuit identifier. Virtual circuit packet switching is used in ATM networks. == Routing Routing is the process of selecting the best path for data to travel from the source to the destination. Routers use routing tables to determine the next hop for packets. Routing algorithms are used to calculate the best path based on metrics such as distance, cost, or speed. == Multiplexing Multiplexing is the process of combining multiple data streams into a single stream for transmission. It allows multiple devices to share a single communication channel. == Demultiplexing Demultiplexing is the process of separating a single data stream into multiple streams at the receiving end. It allows devices to receive data intended for them. == Fragmentation Fragmentation is the process of breaking a packet into smaller units to fit the maximum transmission unit (MTU) of the network. It is used when the packet size exceeds the MTU of the network. == Defragmentation Defragmentation is the process of reassembling fragmented packets at the receiving end. It is used to reconstruct the original packet from the smaller units.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/let-27.typ
typst
Other
// Error: 5 expected identifier #let // Error: 6 expected identifier #{let} // Error: 5 expected identifier // Error: 5 expected semicolon or line break #let "v" // Error: 7 expected semicolon or line break #let v 1 // Error: 9 expected expression #let v = // Error: 5 expected identifier // Error: 5 expected semicolon or line break #let "v" = 1 // Terminated because expression ends. // Error: 12 expected semicolon or line break #let v4 = 4 Four // Terminated by semicolon even though we are in a paren group. // Error: 18 expected expression // Error: 18 expected closing paren #let v5 = (1, 2 + ; Five // Error: 9-13 expected identifier, found boolean #let (..true) = false
https://github.com/jeffa5/typst-cambridge
https://raw.githubusercontent.com/jeffa5/typst-cambridge/main/thesis/manual.typ
typst
MIT License
#import "cambridge.typ": * #show: doc => thesis( author: "<NAME>", short-author: "<NAME>", college: "Trinity", college-shield: "CollegeShields/Trinity.svg", title: [Cambridge PhD thesis template with some extra long words], subtitle: "Date 01/01/1970", short-title: "Cambridge thesis", date: [27#super("th") June 2023], summary: lorem(100), acknowledgements: lorem(50), compact: false, doc, ) #include "manual-1.typ" #include "manual-2.typ" #include "manual-3.typ"
https://github.com/SkytAsul/trombinoscope
https://raw.githubusercontent.com/SkytAsul/trombinoscope/main/data/trombi.typ
typst
MIT License
// This function allows to display a text with a variable size so it fits the available space the best. // It works by trying to display it multiple times, and decreasing the font size each time until it fits. // It is probably not the best way and can crash the compiler if there are too many iterations. #let fit-text(content-text, size) = { layout(avail-size => { let real-size = measure(block(width: avail-size.width, text(size: size, content-text))) if real-size.height <= avail-size.height{ text(size: size, content-text) } else { fit-text(content-text, size - 0.4pt) } }) } #let display-student(group-data-path, line) = { // As the CSVs do not always have the same amount of columns, we cannot directly destructure // the line to a tuple (name, surname, birthdate...). let name = upper(line.at(0)) let surname = line.at(1) let birthdate = line.at(2) let quote = line.at(3) let picture = group-data-path + line.at(5) + ".JPG" align(center, grid( rows: (auto, 10pt, 9pt, 1fr), gutter: 4pt, image(picture, width: 95pt), { set text(weight: "bold") block(width: 95%, fit-text(name.trim(" ") + " " + surname.trim(" "), 11pt)) }, text(size: 9pt, birthdate), fit-text(quote, 10pt) )) } #let display-group(promo, depart, group-row) = { let group-name = group-row.at("Group") let full-group-name = depart // Sometimes there is only 1 Group in a Department so the group-name is empty and we should not display it. if group-name != "" { full-group-name += " - " + group-name } let header = [ #h(1fr) *#promo\A - #full-group-name* #h(0.3cm) ] set page(header: header) heading(level: 2, full-group-name) let group-data-path = group-row.at("DataPath") let group-data = csv(group-data-path + group-row.at("CsvName") + ".csv") // We must not load the csv as dictionary because all sheets do not have the same columns headers... _ = group-data.remove(0) if group-data.at(0).len() <= 5{ panic("Group " + depart + " " + promo + " " + group-name + " has wrong amount of columns") } let students = group-data.filter(line => line.at(5) != "DSC0" and line.at(5) != "DSC00" and line.at(5) != "") // there must be a better way to do that students = students.sorted(key: line => upper(line.at(0))) for students-chunk in students.chunks(9, exact: false){ let students-boxes = students-chunk.map(line => display-student(group-data-path, line)) grid(columns: (1fr, 1fr, 1fr), rows: (1fr, 1fr, 1fr), gutter: 0.1cm, ..students-boxes) } } #let add-images(promo-function) = [ // We do not want to *display* the headings: we only want them so they can be shown in the // PDF index (and eventually in the #outline function if needed). #show heading: it => {} #let groups-data = csv("GroupsData.csv", row-type: dictionary) #let promos = groups-data.map(x => x.at("Promo")).dedup() #for promo in promos { //heading(level: 1, "Année " + str(promo)) // first page headers are not shown if we keep that, see problem-demo.typ promo-function(promo) let departs = groups-data.filter(x => x.at("Promo") == promo).map(x => x.at("Depart")).dedup() for depart in departs{ for group-row in groups-data.filter(x => x.at("Promo") == promo and x.at("Depart") == depart){ display-group(promo, depart, group-row) } } } ] // Example : /* #set page("a5", margin: (top: 1cm, left: 0.5cm, right: 0.5cm, bottom: 0.5cm)) #add-images(promo => align(center+horizon, box(stroke: 2pt, inset: 15pt, text(size: 60pt, weight: "extrabold", str(promo) + "A")))) */
https://github.com/csimide/SEU-Typst-Template
https://raw.githubusercontent.com/csimide/SEU-Typst-Template/master/seu-thesis/utils/set-degree.typ
typst
MIT License
#import "numbering-tools.typ": chinese-numbering #import "packages.typ": show-cn-fakebold, i-figured #import "show-heading.typ": show-heading #import "bilingual-bibliography.typ": show-bibliography #import "show-equation-degree.typ": show-math-equation-degree #import "fonts.typ": 字体, 字号 #let set-degree(always-new-page: true, bilingual-bib: true, doc) = { set page(paper: "a4", margin: (top: 2cm, bottom: 2cm, left: 2cm, right: 2cm)) set text(font: 字体.宋体, size: 字号.小四, weight: "regular", lang: "zh") set par(first-line-indent: 2em, leading: 9.6pt, justify: true) show par: set block(spacing: 9.6pt) show: show-cn-fakebold show: show-bibliography.with(bilingual: bilingual-bib) show heading: show-heading.with( always-new-page: always-new-page, heading-top-margin: (1cm, 0.1cm, 0.05cm), heading-bottom-margin: (1cm, 0cm, 0cm), heading-text: ( (font: 字体.黑体, size: 字号.三号, weight: "regular"), (font: 字体.宋体, size: 字号.四号, weight: "bold"), (font: 字体.黑体, size: 字号.小四, weight: "regular"), ), ) show heading.where(level: 1): set heading(supplement: none) show figure.where(kind: table): set figure.caption(position: top) show figure: set text(size: 字号.五号, font: 字体.宋体, weight: "regular") show figure: i-figured.show-figure.with(numbering: "1-1") show figure.where(kind: table): i-figured.show-figure.with(numbering: "1.1") show math.equation.where(block: true): i-figured.show-equation set math.equation(number-align: bottom) // 研究生院要求:公式首行的起始位置空四格。 show math.equation.where(block: true): show-math-equation-degree set heading(numbering: chinese-numbering) doc }
https://github.com/jomaway/typst-teacher-templates
https://raw.githubusercontent.com/jomaway/typst-teacher-templates/main/examples/exam/sa.typ
typst
MIT License
#import "@local/ttt-exam:0.1.0": * #import components: lines, frame #import layout: side-by-side #set text(size: 12pt, font: ("Rubix","Source Sans Pro"), weight: 300, lang: "en") #let logo = box(height: 2cm, image("logo.jpg", fit: "contain")) #let details = toml("details.toml") #show: exam.with(..details.exam, title: logo_title(logo, details.exam.title)); = Part 1: Free text answers #question(points: 12)[Short task to do some fancy math calculations. #solution(alt:caro(4))[$ pi + x = 7 $] ] #assignment[ Test assignment with three sub-questions. #question(points: 3)[This question will give 3 points. #placeholder(lines(2)) #solution[ - First - Second - Third ] ] #side-by-side(gutter: 2cm)[ #question(points: 1)[ Short question only valid 1 point. #solution(alt: lines(1))[quick] ] ][ #question(points: 1)[ Short question only valid 1 point. #solution[badass] #lines(1) ] ] #with-solution(true)[ #frame(question[ Question with solution is only an example and not valid any points. #pad(x: 1em,solution[This is right?]) ]) ] ] // #include "a1.typ" = Part 2: Some single and multiple Choice fun. #include "mc.typ" = Part 3: Evaluation #free-text-question(points: 5, area: lines(5))[ Describe how did you manage? #solution[Done.] ] = Punkteverteilung #point-table #h(1fr) #point-sum-box
https://github.com/Wh4rp/Presentacion-Typst
https://raw.githubusercontent.com/Wh4rp/Presentacion-Typst/master/comparacion/fibonacci.typ
typst
#import "tablex.typ": * #set page(paper: "a5", margin: 1cm) #set heading(numbering: "1 ") #align(center)[ #text(size: 18pt, weight: 600)[Secuencia de Fibonacci] ] = Definición Recursiva La secuencia de Fibonacci se define de forma recursiva como: $ F_n = cases( 0 &"si" n = 0, 1 &"si" n = 1, F_(n-1) + F_(n-2) &"si" n > 1 ) $ = Ecuación Cerrada La secuencia de Fibonacci también se puede expresar mediante la siguiente ecuación cerrada: $ F_n = 1 / sqrt(5) [ ((1 + sqrt(5)) / (2))^n - ((1 - sqrt(5))/(2))^n ] $ = Tabla de Valores A continuación se muestra una tabla que presenta los primeros 10 números de la secuencia de Fibonacci: #let black_stroke = hlinex(start: 0, end: 2, stroke: 0.5pt) #figure( tablex( columns: 2, auto-lines: false, black_stroke, [$n$], [$F_n$], black_stroke, [0], [0], [1], [1], [2], [1], [3], [2], [4], [3], [5], [5], [6], [8], [7], [13], [8], [21], [9], [34], black_stroke, ), caption: [Los primeros 10 números de la secuencia de Fibonacci.], )
https://github.com/Student-Smart-Printing-Service-HCMUT/ssps-docs
https://raw.githubusercontent.com/Student-Smart-Printing-Service-HCMUT/ssps-docs/main/components/references.typ
typst
Apache License 2.0
#align(center)[*TÀI LIỆU THAM KHẢO*] #linebreak() #h(1cm)1. Projects Inventory. (1/6/2022). _Functional and Non-functional Requirements of Printing Press Management System System._ Truy cập từ https://projectsinventory.com/functional-and-non-functional-requirements-of-printing-press-management-system-system/ #linebreak() #h(1cm)2. ResearchGate. _The system and its context_. Truy cập từ https://www.researchgate.net/figure/The-system-and-its-context-The-context-is-split-into-problem-domain-and-application_fig1_228417190
https://github.com/kazewong/lecture-notes
https://raw.githubusercontent.com/kazewong/lecture-notes/main/Engineering/SoftwareEngineeringForDataScience/lab/versionControl.typ
typst
#set page( paper: "us-letter", header: align(center, text(17pt)[ *Version Control with git* ]), numbering: "1", ) #import "./style.typ": style_template #show: doc => style_template(doc,) = Foreword If you have not heard of the idea of version control, or use git regularly, you are about to learn one of the most important tools in software development, second to only a text editor. It is so important that I put it right after the introduction session, even before the programming language session. We are going to learn about git, mostly from a contributor perspective. Down the road in this course you will also learn about git from a maintainer perspective. There are many great guides on the internet about how to use git (#link("https://rogerdudler.github.io/git-guide/")[This] being my favorite guide), and it is not very useful for me to go through every existing git commands. In this session, we are going to learn some of the basic commands which you will use most frequently. In case you want to dig deeper into the git rabbit hole, ```bash git help [topic]``` actually provide a great selection of tutorials for you to follow. By the end of this session, you will know how to use all of the following commands #set align(center) #table( columns: (auto, auto), inset: 5pt, align: horizon, table.header( [*Command*], [*Function*], ), [init], [Initialize a new git repository], [add], [Add files to the staging area], [rm], [Remove files from the staging area], [commit], [Commit changes to the repository], [push], [Push changes to a remote repository], [pull], [Pull changes from a remote repository], [fetch], [Fetch changes from a remote repository], [log], [Show the commit history], [checkout], [Checkout another branch], [status], [Show the status of the repository], [branch], [List, create, or delete branches], [remote], [Manage remote repositories], [diff], [Show changes between commits], [rebase], [Reapply commits on top of another base tip], [merge], [Join two or more development histories together], [blame], [Show what revision and author last modified each line of a file], [reset], [Reset current HEAD to the specified state], [revert], [Revert some existing commits], [tag], [Actions related to a specific tag in the code base], ) #pagebreak() #set align(left) = Git system #figure( image("./assets/git-snapshots.png"), caption: [Git versioning system, taken from #link("https://git-scm.com/book/en/v2/Getting-Started-What-is-Git%3F")[git]], ) Before we dive right into learning git, it is useful to learn a bit about the concept behind the git system. The main idea behind git is to keep track of the changes you make to your code such that if there are any problems, you can always go back to a previous version of the code. This also enable collaboration between multiple people seamlessly. The way git does this is by taking snapshots of the code at different points in time. This is different from other version control systems, which keep track of the changes you make to the code. As seen from the user, this provides the advantage of being able to quickly checkout any version of the code. To learn more about some of git's main features, visit the #link("https://git-scm.com/about/branching-and-merging")[About] page on the git website. = Exercises == Starting a repository === Step 1 - Configuring the committer info Before we start a repository, let's first configure some info about the committer. You can do this by running the following commands: ```bash git config --global user.name "<NAME>" git config --global user.email "Your Email" ``` Then you should be able to see the configuration by running ```bash git config --list```. === Step 2 - Initializing a repository To start a git repository on your local machine, first create a new directory for your semester project, then navigate to it. For example, on my local machine, it is going to be a series of command like this: ```bash mkdir ./semester_project cd ./semester_project ``` Once in the directory, you can do ```bash ls -a``` to see all the files in the directory, which should be completely empty at this point. Then we will run the command ```bash git init``` to initialize a new git repository. Now if you do ```bash ls -a``` again, you will see a new directory called ```.git```. This is where git stores all the information about your repository. == Working on code === Step 0 - Check git status Since your directory do not have any files in it, you can run ```bash git status``` to see the status of the repository. You will see that git has detected that the directory is clean. === Step 1 - Creating a file Now let's try to move the ReadME.md file you created last week into this directory, and commit the changes with git. Once you move the file into the directory, you can run ```bash git status``` to see the status of the repository. You will see that git has detected a new file in the directory. === Step 2 - Adding the file To add the file to the staging area, you can run ```bash git add ReadME.md```. You can then run ```bash git status``` again to see the status of the repository. You will see that git has detected a new file in the staging area. === Step 3 - Committing the file To make the changes permanent, you can run ```bash git commit -m "Add ReadME.md"```. You can then run ```bash git status``` again to see the status of the repository. You will see that git has detected that the directory is clean. What happened here is you have created a new commit in the repository, which will create a new snapshot of the repository. You can see the history of the repository by running ```bash git log```. === Step 4 - The reason why Git is great for your health Now we can see the biggest reason why you should always use git: to prevent accidental deletion of files. You have worked so hard on the ReadME.md file, and you accidentally deleted it with ```bash rm ReadME.md```. Normally you would go through the five stages of grief, but with git, your file can be recovered. Let's check the status of the repository with ```bash git status```. You will see that git has detected that the file has been deleted. To get your file back, you can simply run ```bash git restore ReadME.md```. Now you should see the file back in the directory, and the status of the repository is clean. If you really hate your ```bash ReadME.md``` for some reason and you want to nuke it out of existence === Rules of thumb for committing You should develop the habit of committing your changes frequently. A good rule of thumb is to commit your changes whenever you have made a significant change to the code, or whenever you are about to leave your computer. It doesn't matter whether your code is perfect or not (At least considering you are only working locally), you can always go back to the previous commit if you mess up. #pagebreak() == Branching off The next important features of git is branching. For a small personal project it might not be very useful, but for any real world applications that you are planning to release, maintain a code base, and keep adding new features, branching is an awesome feature that you should use. The idea of branching is you can maintain multiple "branches" of the code, which could be different from each other. Say you are maintaining a codebase that is catered to an audience, and their scientific workflow depends on your code, you may not want to put untested changes in the public such that it breaks downstream workflows. Instead of commiting everything to the main branch (assuming that's where the published version of the code based on), we can create different development branches of the code, make our changes and test them there, and only merge the changes to the main branch when we are sure that the changes are good. A schematic of the branching system is shown below. #figure( image("./assets/git-branch.png"), caption: [Git branching system, taken from #link("https://ottagit.gitbooks.io/git-push-freshman-open-curriculum/content/git-branching.html")[gitbook]], ) In my daily work, there are a lot of boxes my collaborators and I need to check before we merge changes to the main branch, such as testing and code review. These are good practices we will go through in the later part of this course. === Step 1 - Creating a branch In order to create a new branch, you can run ```bash git branch [branch_name]```. You can then run ```bash git branch``` to see all the branches in the repository. You can then run ```bash git checkout [branch_name]``` or ```bash git switch [branch_name]``` to switch to the new branch. I also use a one-liner ```bash git checkout -b [branch_name]``` to create a new branch and switch to it at the same time. Once you create the branch, you can view the branch you are on by running ```bash git branch```. If you are running out of idea for naming the branch, let's use development for now. === Step 2 - Making changes on the branch Now you can make changes to the code on the development branch. Let's add some more text to the ReadME.md file. Once you are done, you can run ```bash git status``` to see the status of the repository. You will see that git has detected that the file has been modified. Commit it like you did before. === Step 3 - Merging the branch The changes you have made in this branch has not propagated back to the main branch you were working on. Assuming most of your collaborators or your community is not working on this sepecfic new branch you were working on, it would be good to push the changes back to the main branch. The way to do this is through merging the branch. First, you have to switch to your "target" branch, which is the branch you want to merge the changes to. In this case, it is the main branch. Then you can run ```bash git merge development``` to merge the changes from the development branch to the main branch. Once you have merge the changes, you should be able to see the commit history of the main branch by running ```bash git log```. Once you are satisfied with the changes, you can delete the development branch by running ```bash git branch -d development```. === Rules of thumb for branching 1. *You should not be afraid of branching out.* There is basically no overhead or price you have to pay for branching, so there is no reason not to branch off when you want to work on something significant. Branching is a powerful feature to keep different development tasks separated. Sometimes you want to fix a bug, sometimes you want to inroduce a new feature. The rules of thumb here is whenever you have *independent* tasks, you should branch off. 2. *You can branch off from another branch too.* When there is a significant change you want to make to the codebase, say you want to refactor the core of the code, you can first branch off the main branch such that only tested and reviewed changes are merged to the main branch. And then, you can branch off from the development branch into smaller feature branches to work on the smaller features. Once you are done with the smaller features, instead of merging back to the main branch directly, you can merge the changes into the development branch for further testing and review. == Online collaboration Now you have tried to work with `git` locally, it is time to go online. `git` can prevent you from accidental `rm -rf`, but if the only copy of the code is on your computer, it will not be able to save your data if the computer itself is compromised. The most popular online platform for `git` is `GitHub` If you do not have an account on `GitHub` yet, go to this link to create one: #link("https://github.com/join")[https://github.com/join]. Once you have an account, you are ready to push your code online. \* In preparing this lecture note, somehow one of my local filesystem actually get corrupted and I couldn't perform any update on my files. Thanks to `GitHub`, I just nuked the directory and cloned the repository back to my local machine. Nothing is lost. === Step 1 - Creating a repository on GitHub Go to the `GitHub` website and log in. You should see a `+` sign on the top right corner of the page. Click on it and select `New repository`. You will be asked to fill in some information about the repository, such as the name of the repository, whether it is public or private, and whether you want to add a README file. Let's keep the repository public from the get-go, and skip adding the README and other files. === Step 2 - Pushing the code to GitHub Once you have created the repository, you will see a page with a URL on the top, choose the https URL instead of the ssh URL and copy it (If you choose private repositories, this will not work and you will have to use the ssh URL). Run the following command in your terminal to add the remote repository to your local repository: ```bash git remote add origin [URL]```. You can then run ```bash git remote -v``` to see the remote repository you have added, which should have the URL you just copied. You can then run ```bash git push -u origin main``` to push the code to the remote repository. If everything goes well, you should be able to see the code on the GitHub page. === Step 3 - Pulling the code from GitHub Now `GitHub` is not only a one-way cloud drive for you to store your code, but an online platform such that a community can work on the same code together. This means you will have to pull the changes from `GitHub` to your local machine from time to time. Let's modified the ReadME.md file on the `GitHub` page using its online editor, then commit the changes to the main branch. It doeesn't have to be a significant change, just add a line of text to the file. Once you have committed the changes, you can run ```bash git pull``` to pull the changes from the remote repository to your local machine. You should see the changes you made on the `GitHub` page reflected in the ReadME.md file on your local machine. Another option as opposed to pulling is to run ```bash git fetch``` to fetch the changes from the remote repository, and then run ```bash git merge origin/main``` to merge the changes to your local repository. === Rules of thumb for collaboration 1. *You should always pull before you push.* This is to make sure that you are not overwriting someone else's changes. If you push your changes without pulling the changes from the remote repository, you might overwrite someone else's changes, which is not a good practice. 2. *You should always pull before you start working.* This is to make sure that you are working on the latest version of the code. If you start working on an old version of the code, you might have to resolve a lot of conflicts when you try to push your changes to the remote repository. 3. *Read the CONTRIBUTING.md file.* This is a file that is usually included in the repository to tell you how to contribute to the repository. It usually tells you how to format your commit messages, how to create a pull request, and how to get your changes reviewed. == Dealing with conflicts Conflicts can arise when the same files are worked on by multiple people at the same time. This is a common problem and can be annoying from time to time, espeically when it happens close to a deadline. If you adhere to the best practices we mentioned above, there should be minimal conflicts. But in case it does happen, here is how you can resolve it. === Step 1 - Creating a conflict Let's create a conflict by modifying the ReadME.md file on the `GitHub` page using its online editor, and commit the changes to the main branch. Then modify the ReadME.md file on your local machine (Make sure you are changing the same content in a different way, e.g. modified the same line but with different input), and commit the changes to the main branch. Once you have committed the changes, you can run ```bash git pull``` to pull the changes from the remote repository to your local machine. You should see a message saying that there is a conflict in the ReadME.md file. === Step 2 - Resolving the conflict To resolve the conflict, you can open the ReadME.md file in your text editor. You will see something like this: ```markdown <<<<<<< HEAD This is the content you have on your local machine ======= This is the content you have on the remote repository >>>>>>> [commit hash] ``` You can then decide which content you want to keep, or you can keep both contents. Just go ahead and edit your file and make sure those lines includes <<< and >>> are gone. Once you have resolved the conflict, you can run ```bash git add ReadME.md``` to add the file to the staging area, and then run ```bash git commit -m "Resolve conflict"``` to commit the changes. You can then run ```bash git push``` to push the changes to the remote repository. === Rules of thumb for conflicts 1. *Check with the person who made the conflicting changes.* If you are not sure which content to keep, you can always ask the person who made the conflicting changes. They might have a good reason for making the changes, and they might be able to help you resolve the conflict. You can use ```bash git blame ReadME.md``` to see who made the conflicting changes. 2. *Don't panic.* Conflicts are a normal part of working with git, and they are not the end of the world. You can always resolve them by following the steps above. === Nuke buttons for conflicts - `git reset` and `git revert` Sometimes you may regret making a particular changes (or regret you accepted someone's changes) and you want to roll them back, ```bash git revert``` and ```bash git reset``` comes in handy. If someone did something to your repo that you decide you want to roll back the changes, you should use ```bash git revert```. This will create a new commit that undoes the changes made in the previous commit, meaning if you check ```bash git log```, you should be able to see both the unwanted the commits and the commits that you use to undo those changes. On the other hand, if you have some commits you want to get rid of entirely, say some local commits which you have not send it to the public repo, you can use ```bash git reset --hard [commit hash]```. This will reset the HEAD to the commit you specified, and all the commits after that will be gone. In general, you should use ```bash git revert``` over a hard reset. Having the commit history available is better for decision making down the road == Working with public repositories Now that you have learned how to work with `git` locally and online, it is time to work with public repositories. The main difference between what we have been doing and working with public repositories is you often do not have the permission to push directly to the repository unless you are given permission to. In this case, you will have to "fork" the repository, i.e. create a copy of the repository on your own account, make your changes, and then create a "pull request" to the original repository to ask the maintainer to merge your changes. As a final exercise, you will fork a repository related to this class, add a link to your project, then create a pull request to ask me to merge your changes. === Step 1 - Forking a repository Go to https://github.com/KazeClasses/AwesomeKazeClassProject, and click on the "Fork" button on the top right corner of the page. This will create a copy of the repository on your own account. === Step 2 - Making changes Go to the repository on your account, and click on the "README.md" file. You can then click on the pencil icon on the top right corner of the page to edit the file. Add a link to your project in the file according to the contributing guide, then scroll down to the bottom of the page and click on the "Commit changes" button. === Step 3 - Creating a pull request Once you have made the changes, you can click on the "Pull requests" tab on the top of the page, then click on the "New pull request" button. You will be asked to fill in some information about the pull request, such as the title and the description. Once you have filled in the information, you can click on the "Create pull request" button. This will create a pull request to the original repository, and the maintainer of the repository will be able to review your changes and merge them if they are good. Once the pull request is merged, you will see the changes on the original repository. If you go through this process successful, congratulations! Now your project will be listed in the list of project for this course, and you have learned the basic of `git` and `GitHub`!
https://github.com/HitZhouzhou/SecondYear_FirstSemester
https://raw.githubusercontent.com/HitZhouzhou/SecondYear_FirstSemester/main/algorithm/4homework/hw4-algo.typ
typst
// set PDF document metadata #set document(title: "算法设计与分析", author: "周健毅") #import "template.typ": * #show: project.with( logopath: "./asset/hitsz_logo.jpg", subject: "算法设计与分析", labname: "第四章作业", kwargs: ( "学院": "计算机科学与技术学院", "姓名": "周健毅", "学号": "220110713", "专业": "计算机科学与技术", "日期": "2023 年 10 月 14 日", "成绩": "", ), // set firstlineindent, default 0em // firstlineindent: 2em ) = 第一题 #set enum(numbering: "(1).") (1) 请写出该问题的递推方程(定义dp[i][j]为第i种物品到第n种物品装进限重为j的背包可获得的最大价值)(10分) $"dp"[i][j]=max{"dp"[i+1][j],d[i+1][j-k*w[i]]+k*v[i]}$\ 如果使用该递推方程来求最大价值的话,我们需要进行三重循环,时间复杂度为$O(n^3)$。 我们可以对其进行优化: 将上式中的$j$替换为$j-w[i]$可以得到:$ "dp"[i][j-w[i]]=max(f[i+1][j-w[i]],f[i+1][j-2*w[i]]+v[i],...,) $ 对比: $ "dp"[i][j]=max{"dp"[i+1][j],d[i+1][j-k*w[i]]+k*v[i],... } $ 可得新的递推关系式为:$ "dp"[i][j]=max{"dp"[i+1][j-w[i]]+v[i],"dp"[i-1][j]} $ 使用此递推式来解决完全背包问题,时间复杂度为$O(n^2)$\ (2)假设背包容量为5,有4种物品,其重量分别为w=[1,2,3,4],其价值分别为v=[2,4,4,5],请写出对应的dp矩阵 #table( columns:(auto,auto,auto,auto,auto,auto,auto), inset:10pt, align:horizon, [i\\j],[0],[1],[2],[3],[4],[5], [0],[0],[0],[0],[0],[0],[0], [1],[0],[2],[4],[6],[8],[10], [2],[0],[0],[4],[4],[8],[8], [3],[0],[0],[0],[4],[5],[5], [4],[0],[0],[0],[0],[5],[5], ) (3) 请写出该问题的伪代码(10分)\ ```cpp #include<iostream> using namespace std; const int N =1010; int w[N],v[N],dp[N][N]; int n,m; int main() { cin>>n>>m; for(int i=1;i<=n;i++) { cin>>w[i]>>v[i]; } for(int i=n;i>=1;i--) { for(int j=0;j<=m;j++) { dp[i][j]=dp[i+1][j]; if(j>=w[i]) dp[i][j]=max(dp[i][j],dp[i][j-w[i]]+v[i]); } } for(int i=1;i<=n;i++) { for(int j=0;j<=m;j++) cout<<dp[i][j]<<' '; cout<<endl; } cout<<dp[1][m]<<endl; return 0; } ``` (4) 如果上述伪代码是用二维数组实现的,请问是否有空间更优化的的实现版本?提示:可否将2维dp数组降至1维dp数组。 (附加题10 分)\ 可以优化成一维$"dp"$数组:\ 因为每次更新$"dp"[i][j]$时,我们只用到了$"dp"[i+1][j-k*w[i]](k=0,1...)$,即更新第i维的$"dp"$数组时,只用到了第$i+1$维的$"dp"$数组,因此可以省略掉第一维的数组,新的递推表达式为: $ "dp"[j]=max("dp"[j],"dp"[j-w[i]]+v[i]) $ 证明该变形的正确性:\ 更新后的代码为: ```cpp for(int i=n;i>=1;i--) { for(int j=w[i];j<=m;j++) { dp[j]=max(dp[j],dp[j-w[i]]+v[i]); //原代码:dp[i][j]=max(dp[i][j],dp[i][j-w[i]]+v[i]); } } ``` 可以看到每次更新$"dp"[j]$时,用到的是$"dp"[j-w[i]]$,因为第二重循环是从小到大遍历的,因此$"dp"[j-w[i]]$在更新$"dp"[j]$之前就已经被更新过了,所以此时的$"dp"[j-w[i]]$代表的是原代码中的$"dp"[i][j-w[i]]$,因此变形前后的代码是等价的,故可以优化为一维数组。 = 第二题 #set enum(numbering: "I.") 2. 若7个关键字的概率如下所示,求其最优二叉搜索树的结构和代价,要求必须写出递推方程。(30分) #figure( image("BST.jpg",height :20%), caption: [ 最优二叉搜索树 ] ) 递推方程: $ E(i,j)=cases(q_(i-1)=q_j "if" j=i-1 ,min_(i<=r<=j){E(i,r-1)+E(r+1,j)+W(i,j) "if" j>=i} )$ $ E(1,7)=E(1,4)+E(6,7)+W(1,7)\ =[E(1,1)+E(3,4)+W(1,4)]+[E(6,6)+E(8,8)+W(6,8)]\ = 3.12 $ = 第三题 #set enum(numbering: "I.") 3. 灭鼠人计划消灭菜田中田鼠,每个鼠洞内都藏有一定数量的田鼠。这个菜田所有的鼠洞不互通且都围成一圈 ,这意味着第一个鼠洞和最后一个鼠洞是紧挨着的。同时,由于灭鼠动静过大,左右相邻的鼠洞中的田鼠会听见灭鼠动静而全部迅速逃窜,逃窜的田鼠不会去往其他鼠洞,而是逃离这片菜田。 给定一个代表每个鼠洞藏匿老鼠数量的非负整数数组,计算能够消灭田鼠的最大数量。(40分) 思路: 将围成圈的鼠洞分成两次计算,第一次只计算$[0,n-2]$的鼠洞的最大灭鼠量,第二次计算$[1,n-1]$鼠洞的最大灭鼠量,两次计算结果的最大值就是答案。 状态转移方程: $ "dp"[i][0]=max{"dp"[i-1][0],"dp"[i-1][1]} $ $ "dp"[i][1]="dp"[i-1][0]+"nums"[i] $ 其中:$"dp"[i][1]$表示考虑前i个鼠洞,且选择第i个鼠洞能打到的最大鼠数,$"dp"[i][0]$表示考虑前i个鼠洞,且不选择第i个鼠洞能打到的最大鼠数。 优化空间复杂度: $ "dp"[i]=max{"dp"[i-2]+"nums"[i],"dp"[i-1]} $ 其中,$"dp"[i-1]$表示不选第i个鼠洞,$"dp"[i-2]+"nums"[i]$表示选择第i个鼠洞。 实现: ```cpp #include<iostream> #include<vector> #include<cstring> using namespace std; const int N = 1010; int dp[N]; int KillMostMice(vector<int> a,int l,int r) { memset(dp,0,sizeof dp); dp[0]=a[0]; dp[1]=max(a[0],a[1]); for(int i=2;i<a.size();i++) { dp[i]=max(dp[i-1],dp[i-2]+a[i]); } return dp[r]; } int main() { vector<int>a; int n; cin>>n; for(int i=0;i<n;i++) { int x; cin>>x; a.push_back(x); } int ans1=KillMostMice(a,0,n-2); int ans2=KillMostMice(a,1,n-1); cout<<max(ans1,ans2)<<endl; return 0; } ```
https://github.com/IliHanSoLow/W-Seminar_typst_template
https://raw.githubusercontent.com/IliHanSoLow/W-Seminar_typst_template/main/W-Semi-Test.typ
typst
Do What The F*ck You Want To Public License
#import "W-Semi-Template.typ": * #show: project.with( author: "Mustermann, Max", title: "Mikroplastik in der Meeresumwelt", school: "Matrix Mischer Schule", location: "Mümmelhausen", subject: "Merresschutz", teacher: "<NAME>", years: "2024/26", deadline: "07. November 2025" ) = #lorem(2) #lorem(20) #lorem(50)@harry #lorem(50)@electronic #lorem(50)@kinetics #lorem(50)@wwdc-network #lorem(50)@plaque . == #lorem(2) #lorem(20)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/gradient-hue-rotation_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test in Oklab space for reference. #set page( width: 100pt, height: 30pt, fill: gradient.linear(red, purple, space: oklab) )
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/knowledge/semigroups.typ
typst
#import "../cfg.typ": cfg #show: cfg = Semigroups $*$ is an operation on a set $M :=$ + $* in M^(M times M)$. + $M$ is closed under $*$. $(M, *)$ is a semigroup $:= *$ is an associative operation on $M$.
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/docs/tutorial/welcome.md
markdown
Apache License 2.0
--- description: Typst's tutorial. --- # Tutorial Welcome to Typst's tutorial! In this tutorial, you will learn how to write and format documents in Typst. We will start with everyday tasks and gradually introduce more advanced features. This tutorial does not assume prior knowledge of Typst, other Markup languages, or programming. We do assume that you know how to edit a text file. The best way to start is to sign up to the Typst app for free and follow along with the steps below. The app gives you instant preview, syntax highlighting and helpful autocompletions. Alternatively, you can follow along in your local text editor with the [open-source CLI](https://github.com/typst/typst). ## When to use Typst { #when-typst } Before we get started, let's check what Typst is and when to use it. Typst is a markup language for typesetting documents. It is designed to be easy to learn, fast, and versatile. Typst takes text files with markup in them and outputs PDFs. Typst is a good choice for writing any long form text such as essays, articles, scientific papers, books, reports, and homework assignments. Moreover, Typst is a great fit for any documents containing mathematical notation, such as papers in the math, physics, and engineering fields. Finally, due to its strong styling and automation features, it is an excellent choice for any set of documents that share a common style, such as a book series. ## What you will learn { #learnings } This tutorial has four chapters. Each chapter builds on the previous one. Here is what you will learn in each of them: 1. [Writing in Typst:]($tutorial/writing-in-typst) Learn how to write text and insert images, equations, and other elements. 2. [Formatting:]($tutorial/formatting) Learn how to adjust the formatting of your document, including font size, heading styles, and more. 3. [Advanced Styling:]($tutorial/advanced-styling) Create a complex page layout for a scientific paper with typographic features such as an author list and run-in headings. 4. [Making a Template:]($tutorial/making-a-template) Build a reusable template from the paper you created in the previous chapter. We hope you'll enjoy Typst!
https://github.com/rose-pine/typst
https://raw.githubusercontent.com/rose-pine/typst/main/src/themes/rose-pine-moon.typ
typst
MIT License
#let rose-pine-moon = ( base : rgb("#232136"), surface : rgb("#2a273f"), overlay : rgb("#393552"), muted : rgb("#6e6a86"), subtle : rgb("#908caa"), text : rgb("#e0def4"), love : rgb("#eb6f92"), gold : rgb("#f6c177"), rose : rgb("#ea9a97"), pine : rgb("#3e8fb0"), foam : rgb("#9ccfd8"), iris : rgb("#c4a7e7"), highlight : ( low : rgb("#2a283e"), med : rgb("#44415a"), high : rgb("#56526e"), ), codeThemePath: "themes/rose-pine-moon.tmTheme", ) #let variant = rose-pine-moon
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/knowledge/r.typ
typst
#import "../cfg.typ": * #show: cfg = $RR$ Real numbers $:= RR :=$ + $(RR, +, *)$ is a field. + $(RR, <)$ is a linearly ordered set. + $forall x <= y: x + z <= y + z$. + $0 <= x, y -> 0 <= x y$. + Continuity axiom: $forall X, Y subset.eq RR: (forall x, y: x <= y) -> exists c forall x, y: x <= c <= y$. A real number is algebraic (#overline[transcendental]) $:= exists arrow(a) in QQ^(n + 1):$ it is a solution to $a_0 x^n + ... + a_(n - 1) x + a_n = 0$. *Archimedes' principle:* $forall h > 0 thick exists! k in ZZ: k <= x/h < k + 1$. $forall a < b thick exists q in QQ: a < q < b$. An interval $:= (a, b)$. A segment $:= [a, b]$. A neighbourhood of a point $:=$ an interval containing the point. $delta$-neighbourhood of a point $x := (x - delta, x + delta)$. *The triangle inequality:* $abs(x + y) <= abs(x) + abs(y)$. *The Borel-Lebesgue principle:* $X$ is a set of intervals $-> [a, b] = union X -> exists$ a finite set $Y subset.eq X: [a, b] = union Y$. $x$ is a limit point of $A subset.eq RR := abs((x - delta, x + delta) sect A) >= aleph_0$. $RR_+ := {x in RR mid(|) 0 < x}$ $exp_a x := a^x$ where $a > 0 and a != 1$ $exp_a$ is a bijection: $RR -> RR_+$
https://github.com/haxibami/haxipst
https://raw.githubusercontent.com/haxibami/haxipst/main/src/lib/macro.typ
typst
#let no-indent( it, ) = { set par(first-line-indent: 0pt) it } #let latex = text( font: "Linux Libertine", [L#h(-0.3em)#text(size: 0.8em, baseline: -0.2em)[A]#h(-0.125em)T#h(-0.175em)#text(baseline: 0.2em)[E]#h(-0.125em)X], )
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap2/1_voltage_current_resistance_relation.typ
typst
Other
#import "../../core/core.typ" === How voltage, current and resistance relate An electric circuit is formed when a conductive path is created to allow free electrons to continuously move. This continuous movement of free electrons through the conductors of a circuit is called a current, and it is often referred to in terms of "flow," just like the flow of a liquid through a hollow pipe. The force motivating electrons to "flow" in a circuit is called voltage. Voltage is a specific measure of potential energy that is always relative between two points. When we speak of a certain amount of voltage being present in a circuit, we are referring to the measurement of how much potential energy exists to move electrons from one particular point in that circuit to another particular point. Without reference to two particular points, the term "voltage" has no meaning. Free electrons tend to move through conductors with some degree of friction, or opposition to motion. This opposition to motion is more properly called resistance. The amount of current in a circuit depends on the amount of voltage available to motivate the electrons, and also the amount of resistance in the circuit to oppose electron flow. Just like voltage, resistance is a quantity relative between two points. For this reason, the quantities of voltage and resistance are often stated as being "between" or "across" two points in a circuit. To be able to make meaningful statements about these quantities in circuits, we need to be able to describe their quantities in the same way that we might quantify mass, temperature, volume, length, or any other kind of physical quantity. For mass we might use the units of "kilogram" or "gram." For temperature we might use degrees Fahrenheit or degrees Celsius. Here are the standard units of measurement for electrical current, voltage, and resistance: #table( columns: (auto, auto, auto, auto), table.header([*Quantity*], [*Symbol*], [*Unit of Measurement*], [*Unit of Abbreviation*]), [Current], [I], [Ampere (Amp)], [A], [Voltage], [E or V], [Volt], [V], [Resistance], [R], [Ohm], $Omega$, ) The "symbol" given for each quantity is the standard alphabetical letter used to represent that quantity in an algebraic equation. Standardized letters like these are common in the disciplines of physics and engineering, and are internationally recognized. The "unit abbreviation" for each quantity represents the alphabetical symbol used as a shorthand notation for its particular unit of measurement. And, yes, that strange-looking "horseshoe" symbol is the capital Greek letter $Omega$, just a character in a foreign alphabet (apologies to any Greek readers here). Each unit of measurement is named after a famous experimenter in electricity: The _amp_ after the Frenchman Andre M. Ampere, the _volt_ after the Italian Alessandro Volta, and the _ohm_ after the German Georg Simon Ohm. The mathematical symbol for each quantity is meaningful as well. The "R" for resistance and the "V" for voltage are both self-explanatory, whereas "I" for current seems a bit weird. The "I" is thought to have been meant to represent "Intensity" (of electron flow), and the other symbol for voltage, "E," stands for "Electromotive force." From what research I've been able to do, there seems to be some dispute over the meaning of "I." The symbols "E" and "V" are interchangeable for the most part, although some texts reserve "E" to represent voltage across a source (such as a battery or generator) and "V" to represent voltage across anything else. All of these symbols are expressed using capital letters, except in cases where a quantity (especially voltage or current) is described in terms of a brief period of time (called an "instantaneous" value). For example, the voltage of a battery, which is stable over a long period of time, will be symbolized with a capital letter "E," while the voltage peak of a lightning strike at the very instant it hits a power line would most likely be symbolized with a lower-case letter "e" (or lower-case "v") to designate that value as being at a single moment in time. This same lower-case convention holds true for current as well, the lower-case letter "i" representing current at some instant in time. Most direct-current (DC) measurements, however, being stable over time, will be symbolized with capital letters. One foundational unit of electrical measurement, often taught in the beginnings of electronics courses but used infrequently afterwards, is the unit of the _coulomb_, which is a measure of electric charge proportional to the number of electrons in an imbalanced state. One coulomb of charge is equal to 6,250,000,000,000,000,000 electrons. The symbol for electric charge quantity is the capital letter "Q," with the unit of coulombs abbreviated by the capital letter "C." It so happens that the unit for electron flow, the amp, is equal to 1 coulomb of electrons passing by a given point in a circuit in 1 second of time. Cast in these terms, current is the rate of _electric charge motion_ through a conductor. As stated before, voltage is the measure of potential energy per unit charge available to motivate electrons from one point to another. Before we can precisely define what a "volt" is, we must understand how to measure this quantity we call "potential energy." The general metric unit for energy of any kind is the joule, equal to the amount of work performed by a force of 1 newton exerted through a motion of 1 meter (in the same direction). In British units, this is slightly less than 3/4 pound of force exerted over a distance of 1 foot. Put in common terms, it takes about 1 joule of energy to lift a 3/4 pound weight 1 foot off the ground, or to drag something a distance of 1 foot using a parallel pulling force of 3/4 pound. Defined in these scientific terms, 1 volt is equal to 1 joule of electric potential energy per (divided by) 1 coulomb of charge. Thus, a 9 volt battery releases 9 joules of energy for every coulomb of electrons moved through a circuit. These units and symbols for electrical quantities will become very important to know as we begin to explore the relationships between them in circuits. The first, and perhaps most important, relationship between current, voltage, and resistance is called Ohm's Law, discovered by <NAME> and published in his 1827 paper, _The Galvanic Circuit Investigated Mathematically_. Ohm's principal discovery was that the amount of electric current through a metal conductor in a circuit is directly proportional to the voltage impressed across it, for any given temperature. Ohm expressed his discovery in the form of a simple equation, describing how voltage, current, and resistance interrelate: $ E = I R $ In this algebraic expression, voltage (E) is equal to current (I) multiplied by resistance (R). Using algebra techniques, we can manipulate this equation into two variations, solving for I and for R, respectively: $ I = E / R $ $ R = E / I $ Let's see how these equations might work to help us analyze simple circuits: #image("static/1-simple-circuit.png") In the above circuit, there is only one source of voltage (the battery, on the left) and only one source of resistance to current (the lamp, on the right). This makes it very easy to apply Ohm's Law. If we know the values of any two of the three quantities (voltage, current, and resistance) in this circuit, we can use Ohm's Law to determine the third. In this first example, we will calculate the amount of current (I) in a circuit, given values of voltage (E) and resistance (R): #image("static/simple-circuit-2.png") What is the amount of current (I) in this circuit? $ I = E / R = (12 V) / (3 Omega) = 4 A $ In this second example, we will calculate the amount of resistance (R) in a circuit, given values of voltage (E) and current (I): #image("static/1-simple-circuit-3.png") What is the amount of resistance (R) offered by the lamp? $ R = E / I = (36 V) / (4 A) = 9 Omega $ In the last example, we will calculate the amount of voltage supplied by a battery, given values of current (I) and resistance (R): #image("static/1-simple-circuit-4.png") What is the amount of voltage provided by the battery? $ E = I R = 2 A times 7 Omega = 14 $ Ohm's Law is a very simple and useful tool for analyzing electric circuits. It is used so often in the study of electricity and electronics that it needs to be committed to memory by the serious student. For those who are not yet comfortable with algebra, there's a trick to remembering how to solve for any one quantity, given the other two. First, arrange the letters E, I, and R in a triangle like this: #image("static/1-triangle.png") If you know E and I, and wish to determine R, just eliminate R from the picture and see what's left: #image("static/1-triangle-2.png") If you know E and R, and wish to determine I, eliminate I and see what's left: #image("static/1-triangle-3.png") Lastly, if you know I and R, and wish to determine E, eliminate E and see what's left: #image("static/1-triangle-4.png") Eventually, you'll have to be familiar with algebra to seriously study electricity and electronics, but this tip can make your first calculations a little easier to remember. If you are comfortable with algebra, all you need to do is commit E=IR to memory and derive the other two formulae from that when you need them! #core.review[ - Voltage measured in volts, symbolized by the letters "E" or "V". - Current measured in amps, symbolized by the letter "I". - Resistance measured in ohms, symbolized by the letter "R". - Ohm's Law: $E = I R$ ; $I = E/R$ ; $R = E/I$ ]
https://github.com/slashformotion/typst-http-api
https://raw.githubusercontent.com/slashformotion/typst-http-api/master/test.typ
typst
= Voila Aliqua qui non deserunt culpa non nisi nulla. Velit esse nulla pariatur id laboris ullamco ut id sunt fugiat consequat ad adipisicing aute. Cillum labore nisi occaecat aliqua mollit pariatur in laborum id. Deserunt amet sint nisi cupidatat amet voluptate ullamco cillum. Sit id cillum incididunt nisi. Mollit laborum labore eiusmod proident pariatur nisi consectetur cillum dolore adipisicing. Cupidatat elit ea ullamco ex quis. Ex adipisicing sit elit exercitation. Amet Lorem ea eu dolore. Pariatur nulla elit id in occaecat esse cillum do labore. Reprehenderit esse minim qui consectetur consequat incididunt Lorem irure labore quis exercitation do et dolor. Excepteur est commodo aute consequat ad Lorem aliquip aliquip. Nulla ullamco nostrud eiusmod mollit.
https://github.com/Mc-Zen/quill
https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/gates/custom%20gate/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 0pt) #import "/src/quill.typ": * #let draw-par-gate(gate, draw-params) = { let stroke = draw-params.wire let fill = if gate.fill != auto { gate.fill } else {draw-params.background } box( gate.content, fill: fill, stroke: (left: stroke, right: stroke), inset: draw-params.padding ) } #box(quantum-circuit( 1, gate("Quill", draw-function: draw-par-gate), 1, ), fill: gray)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1F900.typ
typst
Apache License 2.0
#let data = ( ("CIRCLED CROSS FORMEE WITH FOUR DOTS", "So", 0), ("CIRCLED CROSS FORMEE WITH TWO DOTS", "So", 0), ("CIRCLED CROSS FORMEE", "So", 0), ("LEFT HALF CIRCLE WITH FOUR DOTS", "So", 0), ("LEFT HALF CIRCLE WITH THREE DOTS", "So", 0), ("LEFT HALF CIRCLE WITH TWO DOTS", "So", 0), ("LEFT HALF CIRCLE WITH DOT", "So", 0), ("LEFT HALF CIRCLE", "So", 0), ("DOWNWARD FACING HOOK", "So", 0), ("DOWNWARD FACING NOTCHED HOOK", "So", 0), ("DOWNWARD FACING HOOK WITH DOT", "So", 0), ("DOWNWARD FACING NOTCHED HOOK WITH DOT", "So", 0), ("PINCHED FINGERS", "So", 0), ("WHITE HEART", "So", 0), ("BROWN HEART", "So", 0), ("PINCHING HAND", "So", 0), ("ZIPPER-MOUTH FACE", "So", 0), ("MONEY-MOUTH FACE", "So", 0), ("FACE WITH THERMOMETER", "So", 0), ("NERD FACE", "So", 0), ("THINKING FACE", "So", 0), ("FACE WITH HEAD-BANDAGE", "So", 0), ("ROBOT FACE", "So", 0), ("HUGGING FACE", "So", 0), ("SIGN OF THE HORNS", "So", 0), ("CALL ME HAND", "So", 0), ("RAISED BACK OF HAND", "So", 0), ("LEFT-FACING FIST", "So", 0), ("RIGHT-FACING FIST", "So", 0), ("HANDSHAKE", "So", 0), ("HAND WITH INDEX AND MIDDLE FINGERS CROSSED", "So", 0), ("I LOVE YOU HAND SIGN", "So", 0), ("FACE WITH COWBOY HAT", "So", 0), ("CLOWN FACE", "So", 0), ("NAUSEATED FACE", "So", 0), ("ROLLING ON THE FLOOR LAUGHING", "So", 0), ("DROOLING FACE", "So", 0), ("LYING FACE", "So", 0), ("FACE PALM", "So", 0), ("SNEEZING FACE", "So", 0), ("FACE WITH ONE EYEBROW RAISED", "So", 0), ("GRINNING FACE WITH STAR EYES", "So", 0), ("GRINNING FACE WITH ONE LARGE AND ONE SMALL EYE", "So", 0), ("FACE WITH FINGER COVERING CLOSED LIPS", "So", 0), ("SERIOUS FACE WITH SYMBOLS COVERING MOUTH", "So", 0), ("SMILING FACE WITH SMILING EYES AND HAND COVERING MOUTH", "So", 0), ("FACE WITH OPEN MOUTH VOMITING", "So", 0), ("SHOCKED FACE WITH EXPLODING HEAD", "So", 0), ("PREGNANT WOMAN", "So", 0), ("BREAST-FEEDING", "So", 0), ("PALMS UP TOGETHER", "So", 0), ("SELFIE", "So", 0), ("PRINCE", "So", 0), ("MAN IN TUXEDO", "So", 0), ("MOTHER CHRISTMAS", "So", 0), ("SHRUG", "So", 0), ("PERSON DOING CARTWHEEL", "So", 0), ("JUGGLING", "So", 0), ("FENCER", "So", 0), ("MODERN PENTATHLON", "So", 0), ("WRESTLERS", "So", 0), ("WATER POLO", "So", 0), ("HANDBALL", "So", 0), ("DIVING MASK", "So", 0), ("WILTED FLOWER", "So", 0), ("DRUM WITH DRUMSTICKS", "So", 0), ("CLINKING GLASSES", "So", 0), ("TUMBLER GLASS", "So", 0), ("SPOON", "So", 0), ("GOAL NET", "So", 0), ("RIFLE", "So", 0), ("FIRST PLACE MEDAL", "So", 0), ("SECOND PLACE MEDAL", "So", 0), ("THIRD PLACE MEDAL", "So", 0), ("BOXING GLOVE", "So", 0), ("MARTIAL ARTS UNIFORM", "So", 0), ("CURLING STONE", "So", 0), ("LACROSSE STICK AND BALL", "So", 0), ("SOFTBALL", "So", 0), ("FLYING DISC", "So", 0), ("CROISSANT", "So", 0), ("AVOCADO", "So", 0), ("CUCUMBER", "So", 0), ("BACON", "So", 0), ("POTATO", "So", 0), ("CARROT", "So", 0), ("BAGUETTE BREAD", "So", 0), ("GREEN SALAD", "So", 0), ("SHALLOW PAN OF FOOD", "So", 0), ("STUFFED FLATBREAD", "So", 0), ("EGG", "So", 0), ("GLASS OF MILK", "So", 0), ("PEANUTS", "So", 0), ("KIWIFRUIT", "So", 0), ("PANCAKES", "So", 0), ("DUMPLING", "So", 0), ("FORTUNE COOKIE", "So", 0), ("TAKEOUT BOX", "So", 0), ("CHOPSTICKS", "So", 0), ("BOWL WITH SPOON", "So", 0), ("CUP WITH STRAW", "So", 0), ("COCONUT", "So", 0), ("BROCCOLI", "So", 0), ("PIE", "So", 0), ("PRETZEL", "So", 0), ("CUT OF MEAT", "So", 0), ("SANDWICH", "So", 0), ("CANNED FOOD", "So", 0), ("LEAFY GREEN", "So", 0), ("MANGO", "So", 0), ("MOON CAKE", "So", 0), ("BAGEL", "So", 0), ("SMILING FACE WITH SMILING EYES AND THREE HEARTS", "So", 0), ("YAWNING FACE", "So", 0), ("SMILING FACE WITH TEAR", "So", 0), ("FACE WITH PARTY HORN AND PARTY HAT", "So", 0), ("FACE WITH UNEVEN EYES AND WAVY MOUTH", "So", 0), ("OVERHEATED FACE", "So", 0), ("FREEZING FACE", "So", 0), ("NINJA", "So", 0), ("DISGUISED FACE", "So", 0), ("FACE HOLDING BACK TEARS", "So", 0), ("FACE WITH PLEADING EYES", "So", 0), ("SARI", "So", 0), ("LAB COAT", "So", 0), ("GOGGLES", "So", 0), ("HIKING BOOT", "So", 0), ("FLAT SHOE", "So", 0), ("CRAB", "So", 0), ("LION FACE", "So", 0), ("SCORPION", "So", 0), ("TURKEY", "So", 0), ("UNICORN FACE", "So", 0), ("EAGLE", "So", 0), ("DUCK", "So", 0), ("BAT", "So", 0), ("SHARK", "So", 0), ("OWL", "So", 0), ("FOX FACE", "So", 0), ("BUTTERFLY", "So", 0), ("DEER", "So", 0), ("GORILLA", "So", 0), ("LIZARD", "So", 0), ("RHINOCEROS", "So", 0), ("SHRIMP", "So", 0), ("SQUID", "So", 0), ("<NAME>", "So", 0), ("<NAME>", "So", 0), ("HEDGEHOG", "So", 0), ("SAUROPOD", "So", 0), ("T-REX", "So", 0), ("CRICKET", "So", 0), ("KANGAROO", "So", 0), ("LLAMA", "So", 0), ("PEACOCK", "So", 0), ("HIPPOPOTAMUS", "So", 0), ("PARROT", "So", 0), ("RACCOON", "So", 0), ("LOBSTER", "So", 0), ("MOSQUITO", "So", 0), ("MICROBE", "So", 0), ("BADGER", "So", 0), ("SWAN", "So", 0), ("MAMMOTH", "So", 0), ("DODO", "So", 0), ("SLOTH", "So", 0), ("OTTER", "So", 0), ("ORANGUTAN", "So", 0), ("SKUNK", "So", 0), ("FLAMINGO", "So", 0), ("OYSTER", "So", 0), ("BEAVER", "So", 0), ("BISON", "So", 0), ("SEAL", "So", 0), ("<NAME>", "So", 0), ("PROBING CANE", "So", 0), ("EMOJI COMPONENT RED HAIR", "So", 0), ("EMOJI COMPONENT CURLY HAIR", "So", 0), ("EMOJI COMPONENT BALD", "So", 0), ("EMOJI COMPONENT WHITE HAIR", "So", 0), ("BONE", "So", 0), ("LEG", "So", 0), ("FOOT", "So", 0), ("TOOTH", "So", 0), ("SUPERHERO", "So", 0), ("SUPERVILLAIN", "So", 0), ("SAFETY VEST", "So", 0), ("EAR WITH HEARING AID", "So", 0), ("MOTORIZED WHEELCHAIR", "So", 0), ("MANUAL WHEELCHAIR", "So", 0), ("MECHANICAL ARM", "So", 0), ("MECHANICAL LEG", "So", 0), ("CHEESE WEDGE", "So", 0), ("CUPCAKE", "So", 0), ("SAL<NAME>", "So", 0), ("BEVERAGE BOX", "So", 0), ("GARLIC", "So", 0), ("ONION", "So", 0), ("FALAFEL", "So", 0), ("WAFFLE", "So", 0), ("BUTTER", "So", 0), ("<NAME>", "So", 0), ("ICE CUBE", "So", 0), ("BUBBLE TEA", "So", 0), ("TROLL", "So", 0), ("STANDING PERSON", "So", 0), ("<NAME>", "So", 0), ("<NAME>", "So", 0), ("FACE WITH MONOCLE", "So", 0), ("ADULT", "So", 0), ("CHILD", "So", 0), ("OLDER ADULT", "So", 0), ("<NAME>", "So", 0), ("PERSON WITH HEADSCARF", "So", 0), ("PERSON IN STEAMY ROOM", "So", 0), ("PERSON CLIMBING", "So", 0), ("PERSON IN LOTUS POSITION", "So", 0), ("MAGE", "So", 0), ("FAIRY", "So", 0), ("VAMPIRE", "So", 0), ("MERPERSON", "So", 0), ("ELF", "So", 0), ("GENIE", "So", 0), ("ZOMBIE", "So", 0), ("BRAIN", "So", 0), ("ORANGE HEART", "So", 0), ("BILLED CAP", "So", 0), ("SCARF", "So", 0), ("GLOVES", "So", 0), ("COAT", "So", 0), ("SOCKS", "So", 0), ("RED GIFT ENVELOPE", "So", 0), ("FIRECRACKER", "So", 0), ("JIGSAW PUZZLE PIECE", "So", 0), ("TEST TUBE", "So", 0), ("PETRI DISH", "So", 0), ("DNA DOUBLE HELIX", "So", 0), ("COMPASS", "So", 0), ("ABACUS", "So", 0), ("FIRE EXTINGUISHER", "So", 0), ("TOOLBOX", "So", 0), ("BRICK", "So", 0), ("MAGNET", "So", 0), ("LUGGAGE", "So", 0), ("LOTION BOTTLE", "So", 0), ("SPOOL OF THREAD", "So", 0), ("BALL OF YARN", "So", 0), ("SAFETY PIN", "So", 0), ("TEDDY BEAR", "So", 0), ("BROOM", "So", 0), ("BASKET", "So", 0), ("ROLL OF PAPER", "So", 0), ("BAR OF SOAP", "So", 0), ("SPONGE", "So", 0), ("RECEIPT", "So", 0), ("NAZAR AMULET", "So", 0), )
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/func/spread.typ
typst
Apache License 2.0
#let tree(root, draw-node: auto, draw-edge: auto, direction: "down", parent-position: "center", grow: 1, spread: 1, name: none, ..style) = { } #let f = (..) => 1
https://github.com/Marmare314/typst-presentation
https://raw.githubusercontent.com/Marmare314/typst-presentation/main/example.typ
typst
MIT License
#import "slides.typ": presentation, hide-slide, dynamic-slide #show: presentation.with( title: "Presentation title", author: "<NAME>", title-text: "Some additional text", ) = Topic A == Section A #lorem(20) == Section B #lorem(30) = Very Long Slide #lorem(200) = Slide without a banner. = $L^p$ Slide with math banner. #show: dynamic-slide = Topic B == Section A #lorem(20) == Section B #hide-slide(1) #lorem(20) == Section C #lorem(20) = Topic C Just a boring slide #show: dynamic-slide = Topic D == Section 1 Content 1 == Section 2 #hide-slide(1) Content 2 == Section 3 #hide-slide((1, 2)) Content 3 == Section 4 Content 4
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/web3/weeks/week3.typ
typst
#import "../../utils.typ": * #section("Component Lifecycle") The problem is, how do we update objects with time? E.g. if I have a clock, how do I update the time each second.// typstfmt::off ```js // logic to st date tick = () => { this.setState({ date: new Date() }) } // set timer on object creation componentDidMount() { this.timerID = setInterval( this.tick, 1000 ) } // delete timer on object destruction componentWillUnmount() { clearInterval(this.timerID) } ``` // typstfmt::on #subsection("3 Phases") Components have 3 phases in react: Mounting, Updating and Unmounting #align(center, [#image("../../Screenshots/2023_10_05_01_49_11.png", width: 50%)]) #subsubsection("Mounting with classes") - *constructor(props)* - initialize state - if no state is needed, omit constructor - static getDerivedStateFromProps(props, state) - initialize state dependent props - *render()* - *componentDidMount()* - whatever you put here happens on mount of object - builds DOM - good time to load async data - *setState() will re-render!* #subsubsection("Updating with classes") - static getDerivedStateFromProps(props, state) - initialize state dependent props - shouldComponentUpdate(nextProps, nextState) - render will be skipped if result is false - used to omit re-rendering for special props - *render()* - getSnapshotBeforeUpdate(prevProps, prevState) - *componentDidUpdate(prevProps, prevState, snapshot)* - DOM is updated #subsubsection("Unmounting with classes") - *componentWillUnmount()* - garbage collection #subsubsection("Error Handling") - static getDerivedStateFromError(error) - put error into state - componentDidCatch(error, info) - logging - avoid propagation -> catch errors #subsection("useEffect(), Hook for mount and unmount") //typstfmt::off ```js function ClockHooked() { const [date, setDate] = useState(new Date()) // mount and unmount useEffect(() => { // set on mount const timerID = setInterval(() => setDate(new Date()), 1000) // set on unmount return () => { clearInterval(timerID) } }, []) return ( <div> <h2>It is {date.toLocaleTimeString()}.</h2> </div> ) } ``` //typstfmt::on E.g. the useEffect() hook is used to handle mounting and unmounting without needing to specify multiple functions, rather, you can just use one function.\ #text(purple)[Dependencies]:\ These are the parameters that will be in the [], as the second parameter to useEffect, this will specify that the function will be rerun when the depencency changes. E.g. the value of a counter has changed, therefore it will re-render. //typstfmt::off ```js useEffect(() => { console.log('Counter is now: ', counter); }, [counter]); ``` //typstfmt::on #subsection("useEffect with async API and Errorhandling") //typstfmt::off ```js const [remoteData, setRemoteData] = useState(null); const [error, setError] = useState(null); const [isLoading, setIsLoading] = useState(false); useEffect(() => { setIsLoading(true); // show loading ui fetch('https://jsonplaceholder.typicode.com/todos/' + id) .then((response) => { if (!response.ok) { throw new Error('Oops’); } setIsLoading(false); // show proper ui again return response.json(); } ).then((data) => setRemoteData(data)) .catch((error) => setError(error.message)); }, [id]); // use new id for next todo ``` //typstfmt::on #section("React Router") #text(red)[*Router for react is just a library*, it is not a built-in feature!] //typstfmt::off ```js const { BrowserRouter, Routes, Route, Link } = ReactRouterDOM; const root = ReactDOM.createRoot( document.getElementById("root") ); const Home = () => "Home" const About = () => "About" const Dashboard = () => "Dashboard" function App() { return ( <BrowserRouter> <div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> <li><Link to="/dashboard">Dashboard</Link></li> </ul> <hr /> <Routes> <Route index element={<Home/>} /> <Route path="/about" element ={<About/>} /> <Route path="/dashboard" element={<Dashboard/>} /> </Routes> </div> </BrowserRouter> ) } root.render( <App/> ); ``` //typstfmt::on - \<BrowserRouter\> - all routes must be part of the router - typically near the root component - \<Route path="/about" element={\<About/\>}\> - Component About will only be rendered when path matches - routes can be boxed into each other - \<Link to="/about"\>About\</Link> - react native links, don't use \<a\> for react! - *links would not work with the react router!* #section("Typescript with React") - flow can also be used - just annotations for js, doesn't stop the app from running - no proper language - just use ts... #subsection("Function Components") //typstfmt::off ```js type Props = { accountNr: AccountNr; balance: number; onSubmit: (to: AccountNr, amount: number) => void; isValidTargetAccount: (to: AccountNr) => Promise<boolean>; }; function TransferFundsForm({ accountNr, balance, onSubmit, isValidTargetAccount, }: Props) { // .... } ``` //typstfmt::on #subsection("Class Components") //typstfmt::off ```js type Props = { token: string; user?: User; }; type State = { transactions?: Transaction[]; state: State = { transactions: undefined, // other parts of state }; class Transactions extends React.Component<Props, State> { // ... // do something with transactions } }; ``` //typstfmt::on
https://github.com/Nrosa01/TFG-2023-2024-UCM
https://raw.githubusercontent.com/Nrosa01/TFG-2023-2024-UCM/main/Memoria%20Typst/capitulos/5.SimuladorCPU.typ
typst
#import "@preview/sourcerer:0.2.1": code #import "../utilities/gridfunc.typ": * #import "../data/gridexamples.typ": * #import "@preview/subpar:0.1.0" Este trabajo trata sobre simuladores de arena y, como se mencionó en la @simuladoresArena, los simuladores de arena no son paralelizables debido a que cada celda puede modificar el estado de las demás. En este capítulo se muestran distintas implementaciones de simuladores de arena que se ejecutan en la CPU para poder compararlos. Para poder realizar la comparativa, se han realizado 3 simuladores diferentes basados en explotar la CPU. Cada uno de ellos tiene sus propias ventajas y desventajas, además de distintos propósitos. A continuación se detalla cada implementación, profundizando en sus rasgos particulares. == Generalidades En todas las implementaciones, una partícula es una estructura de datos con al menos dos propiedades: id y clock. La propiedad `id` es un valor que indica el tipo de partícula, mientras que `clock` es un valor que alterna entre 0 y 1 en cada iteración. Esto permite que una partícula no sea procesada dos veces en la misma generación. Es decir, si una partícula de arena se mueve "hacia abajo" y la actualización del simulador procesa las partículas de arriba a abajo, la partícula de arena que se movió hacia abajo volverá a ser procesada dentro de la misma generación. Para evitar este problema, se usa el valor `clock` para marcar si una partícula fue procesada en la generación actual. Para evitar tener que resetear el valor de `clock` de todas las partículas en cada generación, se alterna entre 0 y 1 en cada iteración y se compara con el valor clock del sistema, que también alterna entre 0 y 1 en cada iteración. == Simulador en C++ El primer simulador fue desarrollado en C++ con OpenGL y GLFW. Este simulador sirve como base comparativa de las siguientes implementaciones. Este sistema posee 6 partículas: Arena, Agua, Aire, Gas, Roca y Ácido. En este sistema las partículas están programadas en el sistema y no son modificables de forma externa. Cada partícula tiene una serie de propiedades: color, densidad, granularidad, id y movimiento. El color es el color de la partícula, la densidad es un valor númerico que indica la pesadez relativa respecto otras partículas, la granularidad es un valor que modifica ligeramente el color de la partícula, la id es un valor que indica el tipo de partícula y el movimiento es una serie de valores que describe el movimiento de la partícula. Estos rasgos son particulares de esta implementación y no se repiten en las siguientes a excepción del identificador de la particula, que es común a todas las implementaciones. Este sistema es limitado, pues los comportamientos de las partículas dependen de estos parámetros y el sistema que las procesa. Con todo, esto permite generar variaciones de partículas con facilidad. El valor del movimiento permite crear los tipos de movimientos más comunes (arena, agua, lava, gas, etc). La densidad permite controlar que partícula puede intercambiarse por otra sin tener que controlarlo manualmente para cada partícula... Al ser un sistema cerrado, se da lugar a un sistema más rápido y eficiente que los siguientes ya que el compilador puede optimizar el código de forma más eficiente. La @simuladorcplusplus muestra la interacción entre partículas en este simulador en un mundo de #box()[$100*100$] celdas. #subpar.grid( figure(image("../images/simuladorcplusplus.png"), caption: [ Antes de que la arena llegue al agua ]), figure(image("../images/simuladorcplusplus2.png"), caption: [ Arena hundiéndose en el agua ]), gap: 15pt, columns: (1fr, 1fr), caption: [Interacción entre partículas en el simulador de C++], label: <simuladorcplusplus>, ) Esta implementación ejecuta una lógica directa en un solo hilo. Debido a esto es la base para comparar el rendimiento de las siguientes implementaciones. Para poder mostrar el estado de la simulación de forma visual, se escribe en un buffer el color de cada partícula después de cada paso de simulación. Este buffer se envía a la GPU para ser renderizado en pantalla. Se puede ver un video de esta simulación haciendo click en el siguiente #link("https://youtu.be/Z-1gW8dN7lM")[#text(blue)[enlace]] == Simulador en Lua con LÖVE <luathreading> LÖVE @akinlaja-2013 es un framework de desarrollo de videojuegos en Lua orientado a juegos 2D. Permite dibujar gráficos en pantalla y gestionar la entrada del usuario sin tener que preocuparase de la plataforma en la que se ejecuta. LÖVE usa LuaJIT, por lo que es posible alcanzar un rendimiento muy alto sin sacrificar flexibilidad. Para mejorar aún más el rendimiento, esta implementación se basa de la librería FFI de LuaJit. Esta permite a Lua interactuar con código de C de forma nativa. Además, al poder declarar structs en C, es posible acceder a los datos de forma más rápida que con las tablas de Lua y consumir menos memoria. En este sistema, una particula es un struct en C que contiene su id y su clock. Para facilitar la extensión y usabilidad de esta versión, se creó un API que permite definir partículas en Lua de forma externa. Una particula está definida por su nombre, su color y una función a ejecutar. Una vez hecho esto, el usuario solo debe arrastrar su archivo a la ventana de juego para cargar su "mod". La función que ejecuta cada partícula recibe un solo parámetro: un objeto API. Este define las funciones necesarias para definir las reglas que modelan el comportamiento de una partícula. Además, para facilitar el desarrollo, las direcciones que consume el API son relativas a la posición de la partícula que se está procesando. Obtener el tipo de una partícula a la derecha de la actual es tan sencillo como llamar a `api:get(1, 0)`. // No agregué apéndice porque tener un apartado de una sola sección quedaría raro Además de esto, el sistema registra automáticamente los tipos de partículas en una tabla global que actúa como un enum. Esto permite que el usuario pueda comprobar con facilidad si un tipo de partícula está definido en el sistema para poder interactuar con este. Por ejemplo, una particula de lava puede comprobar si hay agua debajo de ella y convertirla en roca. Sin embargo, simular tantas partículas es un proceso costoso. Debido a esto, se optimizó mediante la implementación de multihilo. Si bien Lua es un lenguaje muy sencillo y ligero, tiene ciertas carencias, una de ellas es el multithreading. Lua no soporta multithreading de forma nativa. La alternativa a esto es instanciar una máquina virtual de Lua para cada hilo, esto es exactamente lo que love.threads hace. LÖVE permite crear hilos en Lua, pero además de esto, permite compartir datos entre hilos mediante `love.bytedata`, una tabla especial que puede ser enviada entre hilos por referencia, en resumen, un recurso compartido. Además de esto, LÖVE provee `canales` de comunicación entre hilos, que permiten enviar mensajes de un hilo a otro y sincronizarlos. Esto permitió enviar trabajo a los hilos bajo demanda. La implementación del multihilo dio lugar a problemas que no se tenían antes: escritura simultánea y condiciones de carrera. Esto supuso un desafío que fue resuelto implementando la actualización por bloques. En lugar de simular todas las particulas posible a la vez, se ejecutarían subregiones específicas de la simulación en 4 lotes. Se dividió la matriz en un "patron de ajedrez" @gdcNoita. Esto consiste en procesar primero las columnas y filas pares, luego columnas pares y filas impares... Y así hasta completar las 4 combinaciones posibles. Esto nos permite dividir la actualización de la simulación en 4 "pases", donde en cada uno de estos pases se procesan varias partículas a la vez. La figura @luacores muestra como serían estos pases. #grid_example("Patrón de ajedrez de actualización", (luaimpl_ex1, luaimpl_ex4, luaimpl_ex2, luaimpl_ex3), vinit: 0pt, ref: "luacores") Cada uno de los cuadrados de la imagen representa una "submatriz" de partículas, esto se denomina un "chunk". El sistema dividirá la matriz en chunks siguiendo el siguiente criterio: El tamaño mínimo de una chunk es de 16 píxeles, el número de chunks debe ser igual o superior al cuadrado de hilos disponibles. Estos requisitos garantizan que se puedan utilizar todos los hilos a la vez. El requisito de tamaño es para evitar que una partícula trate de modificar a otra lejana que esté siendo procesada por otro hilo. El orden en que se procesan las regiones coincide con el mostrado en la @luacores. Primero filas y columnas pares, a continuación, filas impares y columnas impares, tras esto, filas pares y columnas impares y finalmente filas impares y columnas pares. Sin embargo, esto da lugar a problemas. Surgen artefactos visuales cuando una partícula se mueve fuera de la región que se estaba procesando. A continuación se muestra un ejemplo de este problema. Cada imagen es una generación de la simulación. #v(5pt) #grid_example_from("Problema de multithreading", (grid( columns: 2, rect(fill: green, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_1)], rect(fill: purple, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_1)], rect(fill: blue, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_1)], rect(fill: red, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_2)], ),grid( columns: 2, rect(fill: green, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_1)], rect(fill: purple, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_3)], rect(fill: blue, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_1)], rect(fill: red, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_5)], ),grid( columns: 2, rect(fill: green, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_1)], rect(fill: purple, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_4)], rect(fill: blue, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_1)], rect(fill: red, inset: 2pt, outset: 0pt)[#draw_grid_simple(luaimpl_problem1_1_5)], )), ref: "luaproblemcores") En la @luaproblemcores se muestran tres generaciones procesando con el sistema multithread descrito. Se ilumina el borde de cara región para mayor claridad. Cada subregión procesa las particulas de arriba a abajo y de izquierda a derecha. El comportamiento de la partícula es el siguiente: Si el vecino superior es vacío, se "mueve" hacia arriba. En tercera generación se puede observar como las partículas se separan. Al haberse procesado primero la región roja, la partícula no puede moverse porque en la región morada había una partícula encima. Acto seguido, la partícula morada se mueve hacia arriba. En ejecución este efecto es notorio y afecta al comportamiento esperado de la simulación. Cambiar el orden en que se actualizan las partículaas resolvería el problema para partículas que se muevan en una dirección determinada, pero el problema siempre se presentará en una dirección. Para evitar este problema se requirió modificar la actualización de la simulación. En primer lugar, se introdujo un doble buffer, esto permite que el procesamiento de las partículas sea consistente por lo mencionado en la @simuladoresArena. Con todo, esto no es suficiente y existen casos específicos en los que el problema persiste. Por ello, además de añadir doble buffer, el orden en que se actualizan las particulas cambia en un ciclo de 2 fotogramas. Primero se actualiza la matriz de derecha a izquierda y de arriba a abajo, y luego de izquierda a derecha y de abajo a arriba. Esto se debe a que si siempre se actualizan las partículas de izquierda a derecha o viceversa, el sistema presentará un sesgo en la dirección en la que se actualizan las partículas que provoca que el resultado tras varias iteraciones no sea el esperado. #subpar.grid( figure(image("../images/luasesgo2.png"), caption: [ Sin variar el orden de actualización ]), <luasesgo1>, figure(image("../images/luasesgo1.png"), caption: [ Variando el orden de actualización ]), <b>, gap: 15pt, columns: (1fr, 1fr), caption: [Diferencia entre variar y no el orden de actualización al procesar partículas], label: <luasesgo>, ) #v(5pt) Con estas mejoras el sistema funciona correctamente en casi todos los casos, pero aún existen casos muy específicos resultados de procesar chunks en un patrón de ajedrez. La solución para esto fue variar el orden de actualización de dichos "chunks" o trozos. En cada generación se invierte el orden de actualización de los chunks de una manera simlar a la que se invierte del orden de actualización de las partículas dentro de dichos chunks. Esto permite que el sistema sea más estable y no presente sesgos en la dirección en la que se actualizan las partículas. Finalmente, para gestionar el procesamiento de los chunks se implementó la técnica del `work stealing`. El hilo principal va asignando chunks a los hilos libros hasta que todos han sido procesados, lo cual deja a los hilos esperando para la siguiente generación. El procesamiento de una partícula tiene una segunda fase. Una vez todos los chunks han sido procesados, se actualizan los buffers y se actualiza la textura que posteriormente se renderiza en pantalla. La actualización de los buffers consiste en copiar el buffer de la generación actual al buffer de la generación anterior. Esto se hace debido a que hay partículas que podrían no realizar ninguna acción y por tanto no modifican el buffer de la generación actual, por lo que intercambiarlos no es suficiente. Se puede ver un video de esta simulación haciendo click en el siguiente #link("https://youtu.be/ZlvuIUjA7Ug")[#text(blue)[enlace]] == Simulador en la web La siguiente implementación es distinta a las demás en dos aspectos. Esta se ejecuta en el navegador y además permite a los usuarios definir las reglas de las partículas mediante Blockly. Se profundizará de esto más adelante. Blockly puede usarse para generar código en cualquier lenguaje, incluido JavaScript, el lenguaje usado en programar elementos interactivos en las webs. No obstante, JavaScript es un lenguaje interpretado que aún siendo JIT, es lento. Debido a esto, desde hace varios años los navegadores tienen soporte para WebAssembly @aboutwasm, un lenguaje de bajo nivel que es más rápido que JavaScript. Las mayores diferencias entre WebAssembly y JavaScript, es que WebAssembly es un lenguaje de tipado estático y además, no posee gestión automática de memoria, esta debe ser manejada manualmente. WebAssembly no está pensado para ser usado directamente, sino que es un destino de compilación para otros lenguajes. En este caso, se usó Rust, un lenguaje de programación de propósito general con características de lenguajes funcionales y orientados a objetos. Es un lenguaje con características de bajo y alto nivel. Rust y WebAssembly por si solo no son suficientes. Para poder visualizar el estado de la simulación en la web se usó Macroquad, una librería de Rust que permite renderizar gráficos en la web, además de gestionar la entrada del usuario. Ejecutar la simulación en la web incurre en un problema no resoluble, no es posible controlar el número de generaciones que se ejecutan por segundo, ya que esto es controlado por la función `requestAnimationFrame` del navegador. Además, el entorno web impide el uso de multihilo, por lo que la simulación se ejecuta en un solo hilo. Finalmente, para agrupar todos estos elementos, se creó una página web usando Vue y estilizando con TailwidCSS para crear la interfaz de usuario e implementar BLockly. La @simuladorweb muestra la interfaz de la simulación en la web. #figure(image("../images/simuladorrust1.png"), caption: [ Interfaz de la simulación en la web ]) <simuladorweb> A continuación se explica la lógica y funcionamiento interno de la simulación. Esta es una simulación secuencial que no usa doble buffer, pero sí altera el orden de actualización de las partículas para evitar el problema del sesgo visto en la @luathreading. Las partículas en esta implementación son más complejas y ofrecen más posibilidades. Existen dos tipos de datos: los que posee cada partícula y los que son comunes a todas. Existe un registro asociado a cada tipo de partícula que contiene los siguiente datos: nombre, primer color, segundo color. El nombre sirve para identificar a la partícula en Blockly. Para poder hablar de los dos colores primero es necesario describir la información que tiene cada partícula individualmentea a parte de los parámetros básicos de clock e id, poseen otros 6 datos: opacity, color_fade, hue_shift, extra, extra2, extra3. Todos estos campos son números restringidos a un intervarlo entre 0 y 100. Cuando una partícula se crea en este sistema, se le asigna un `color fade` aleatorio entre 0 y 100. Este valor controla la interpolación entre el primer y segundo color, `opacity` controla la transparencia de la partícula y siempre se inicializa a 100, `hue shift` altera el tono de la partícula y siempre se inicializa a 0, todos los campos `extra` son valores que se inicializan a 0 y el usuario puede usar para representar cualquier cosa. Al igual que en la implementación anterior, cada tipo de partícula tiene una función asociada cuyo único parámetro de entrada es un objeto API que contiene las funciones necesarias para interactuar con la simulación. Esta función es generada en tiempo de ejecución. Nuestra implementación de Blockly no genera código, sino que genera datos en formato JSON. Este JSON se envía de JavaScript a WebAssembly (Rust) para ser procesado. Cada bloque de Blockly está asociado a una variante de un enum en Rust, además, estas variantes son tuplas que pueden contener parámetros. El fichero JSON se deserializa en dicha estructura para poder ser procesado mejor. Con esta estructura puede generarse una función. Para ello se define una función que devuelve una función anónima. Se usa pattern matching para que cada variante devuelva una función distinta. Algunas variantes contienen instancias de otras variantes, por lo que en estas se llama de nuevo a la función que devuelve una función anónima en una suerte de recursión. Finalmente la función obtenida se guarda para ser usada posteriormente. Este procesamiento no es directo, sino que en función de los datos de las tuplas se toman unas u otras decisiones. Existen dos tipos de datos: constantes y dinámicos. Los datos constantes son aquellos que nunca cambian, mientras que los datos dinámicos dependen del estado de la simulación. Al "convertir" las variantes del enum a funciones, esto se tiene en cuenta. Los datos estáticos son capturados por la función anónima que se devuelve, mientras que los datos dinámicos son recalculados dentro de la función que se devuelve. Un ejemplo sería la dirección. La dirección es un enum que tiene dos variantes: CONSTANT([i32; 2]) y RANDOM. Es evidente que la dirección constante no cambia y puede capturarse en la función anónima, mientras que la dirección aleatoria debe ser recalculada en cada iteración. Esta optimización se aplica en cada variante que tenga una dirección como dato. Se puede ver un video de esta simulación haciendo click en el siguiente #link("https://youtu.be/obA7wZbHb9M")[#text(blue)[enlace]]
https://github.com/jerrita/CQUPTypst
https://raw.githubusercontent.com/jerrita/CQUPTypst/master/README.md
markdown
# CQUPTypst # !!!WARN!!!: 最终模板可正常使用并在23年正常提交为毕业论文,但是需要一些额外工作才可更新至此。本仓库模板为最初版本,需要用则提 Issue 或是给我发邮件,我在看到后会更新 一个 Typst 模板,但是大专 模板参考文件: [毕业设计(论文)参考模板-校级](https://fls.tisato.live/preview?file=/attachments/毕业设计(论文)参考模板-校级.doc) ![Snapshot](./resource/snapshot.png) ## 用法 > 如果你装了 `Typst LSP`,那么你需要将 `Typst-lsp: Export Pdf` 改为 `never` 1. Clone 本项目 2. 安装 `typest` ```bash # Mac brew install typst # Windows scoop install typst # maybe, unverified ``` 3. (Optional) VSCode 安装 `Typest LSP`、`Run on Save` 插件 4. 更改 `chapters` 的内容 5. 运行命令 `typst compile main.typ` ## 限制 > 不过你可以等随缘更新 - 封面没做,你可以 Word 导出后粘到前面 - 四级五级标题没做 - 页眉页脚没做 - 其它暂时不知道
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/quetta/0.1.0/README.md
markdown
Apache License 2.0
A simple module to write [tengwar](https://en.wikipedia.org/wiki/Tengwar) in [Typst](https://typst.app/). ## Requirements - [Typst](https://github.com/typst/typst) version 1.11.0 or up - The [Tengwar Annatar](https://www.fontspace.com/tengwar-annatar-font-f2244) fonts version 1.20 For use with the [Typst web app](https://typst.app/), you need to upload the font files to your project. ## Usage The main functionality of this module is provided by the function `quenya` taking content and converting all text in Tenwar using the Quenya mode. The original text is used as a phonetic transcription. (This module does not translate English into Quenya.) See the [manual](https://github.com/FlorentCLMichel/quetta/manual.pdf) for more information. The following line may be used to convert the whole document below to Tengwar in Quenya mode (other `show` rules might interfere with it): ``` #show: quetta.quenya ``` **Example:** ``` #import "@preview/quetta:0.1.0" // Use the function `quenya` to write a small amount of text in Tengwar (Quenya mode) #text(size: 16pt, fill: gradient.linear(blue, green) )[#box(quetta.quenya[_tengwar_])] #v(1em) // A `show` rule may be more convenient for larger contents; beware that it may interfere with other ones, though #show: quetta.quenya Namárië! #h(1em) _Namárië!_ #h(2em) *Namárië!* ``` ## Roadmap * Number conversion: done * Support for the Quenya mode: done * Support for the mode of Gondor: backlog * Support for the mode of Beleriand: backlog * Support for the Black Speech: backlog ## How can I contribute? I (the original author) am definitely not en expert in either Typst nor Tengwar. I could thus use some help in all areas. I would especially welcome contributions or suggestions on the following: * Identify and resolve inefficiencies in the Typst code. * Identify cases where the result differs from the expected one. (In particular, there are probably rules for writing in Tengwar that I either am not aware of or have not properly understood. Any advice on that is warmly welcome!) * References on Tengar, Quenya, and Sidarin. * Support for other Tengwar fonts.
https://github.com/hanxuanliang/opentyp
https://raw.githubusercontent.com/hanxuanliang/opentyp/main/README.md
markdown
MIT License
# opentyp Ordinary study notes are organized into typst and made public. - [opendal](./opendal) - [risinglight](./risinglight)
https://github.com/lyzynec/orr-go-brr
https://raw.githubusercontent.com/lyzynec/orr-go-brr/main/03/main.typ
typst
#import "../lib.typ": * #knowledge[ #question(name: [Give some examples of practically useful _optimal control cost functions_ (aka performance indices).])[ For optimal control a practical cost function would penalize input and distance of current state from the reference. In general such function could be written as $ phi.alt(bold(x)_N, N) + sum_(k=1)^(N-1) L_k (bold(x)_k, bold(u)_k) $ One practical example could be $ 1/2 bold(x)_N^T bold(S) bold(x)_N + 1/2 sum_(k=1)^(N-1) (bold(x)_k^T bold(Q) bold(x)_k + bold(u)_k^T bold(R) bold(u)_k) $ ] #question(name: [Explain the challenges in designing controllers with a fixed structure (e.g. PID controllers) by optimizing over their coefficients.])[ - How to express $J(P, I, D)$? It would have to be numerical most of the time. - Expressing closed loop stability. - Nonconvexity of such problem. ] #question(name: [Formulate the general (nonlinear) problem of optimal control design for a discrete-time system as a numerical optimization over (finite) control sequences. Discuss the two possible variants: simultaneous and sequential.])[ $ min_(bold(x) in RR^(n(N-i)), bold(u) in RR^(m(N-i))) &J(bold(x) bold(u))\ "subject to" & bold(g)(bold(x), bold(u)) = bold(0)\ & bold(h)(bold(x), bold(u)) <= bold(0) $ #part(name: [Simultaneous (sparse) optimization])[ We optmize over both $bold(x)$ and $bold(u)$ vectors with the cost function being $ min_(hat(bold(x)) in RR^(2N)) 1/2 underbrace(mat(bold(x)^T, bold(u)^T), hat(bold(x))^T) underbrace(mat(overline(bold(Q)), ""; "", overline(bold(R))), hat(bold(Q))) underbrace(mat(bold(x); bold(u)), hat(bold(x))) $ where $ overline(bold(Q)) = mat( bold(Q), "", "", ""; "", bold(Q), "", ""; "", "", dots.down, ""; "", "", "", bold(S) ), overline(bold(R)) = mat( bold(R), "", "", ""; "", bold(R), "", ""; "", "", dots.down, ""; "", "", "", bold(R) ) $ Now the problem looks like $ min_(hat(bold(x)) in RR^(2N)) &1/2 hat(bold(x))^T hat(bold(Q)) hat(bold(x))\ "subject to" &bold(h)(bold(hat(bold(x)))) = bold(0) $ ] #part(name: [Sequential (dense) optimization])[ This works by expressing $bold(x)$ as a function of $bold(u)$ and $bold(x)_0$ $ bold(x)_(k) = bold(f)(bold(x)_(k-1), bold(u)_(k-1)) $ in case of linear system $ bold(x)_k = bold(A)^k bold(x)_0 + bold(A)^(k-1) bold(B) bold(u)_0 + bold(A)^(k-2) bold(B) bold(u)_1 + ... + bold(B) bold(u)_(k-1) $ ] ] #question(name: [Formulate the problem of optimal regulator design for a discrete--time linear time--invariant (LTI) system over a finite time horizon and with a quadratic performance index as a quadratic program (QP). Develop fully both the _simultaneous_ and _sequential_ forms of the optimization problem and consider also including the inequality constraints. What is the major disadvantage of the control strategy based on the offline optimization over a control sequence?])[ #part(name: [Simultaneous (sparse) optimization])[ The problem is in the form $ min_(hat(bold(x)) in RR^(2N)) &1/2 hat(bold(x))^T hat(bold(Q)) hat(bold(x))\ "subject to" & hat(bold(A)) hat(bold(x)) + hat(bold(b)) = bold(0) $ This can be rewritten as $ mat( hat(bold(Q)), hat(bold(A))^T; hat(bold(A)), bold(0); ) mat(hat(bold(x)); bold(lambda)) = mat(bold(0); -hat(bold(b))) $ where $ hat(bold(A)) = mat(overline(bold(A)) - bold(I), overline(bold(B)))\ overline(bold(b)) = overline(bold(A))_0 bold(x)_0\ overline(bold(A)) = "kron"(bold(A), mat( bold(0), 0; bold(I), bold(0); ) )\ overline(bold(B)) = "kron"(bold(B), bold(I))\ overline(bold(A))_0 = mat(bold(A); bold(0); dots.v; bold(0)) $ For inequality constraints we would have to edit the Lagrange function, but the overall design would be the same. ] #part(name: [Sequential (dense) optimization])[ We remove the constraints $ bold(x) = (bold(I) - overline(bold(A)))^(-1) overline(bold(B)) bold(u) + (bold(I) - overline(bold(A)))^(-1) overline(bold(A))_0 bold(x)_0 $ the sets of equations can be rewritten as $ bold(x)_k = bold(A)^k bold(x)_0 + bold(A)^(k-1) bold(B) bold(u)_0 + bold(A)^(k-2) bold(B) bold(u)_1 + ... + bold(B) bold(u)_(k-1) $ If we express this in matrix form $ underbrace(mat(bold(x)_1; bold(x)_2; dots.v; bold(x)_N), bold(x) ) = underbrace(mat( bold(B), "", "", ""; bold(A)bold(B), bold(B), "", ""; dots.v, dots.v, dots.down, ""; bold(A)^(N-1) bold(B), bold(A)^(N-2) bold(B), ..., bold(B) ), hat(bold(C)) ) underbrace(mat(bold(u)_0; bold(u)_1; dots.v; bold(u)_(N-1)), bold(u)) + underbrace(mat(bold(A); bold(A)^2; dots.v; bold(A)^N), hat(bold(A))) bold(x)_0 $ we can rewrite it as $ bold(x) = hat(bold(C)) bold(u) + hat(bold(A)) bold(x)_0 $ The cost function than looks like $ hat(J)(bold(u), bold(x)_0) = 1/2 bold(u)^T underbrace( (hat(bold(C))^T overline(bold(Q)) hat(bold(C)) + overline(bold(R))), bold(H) ) bold(u) + bold(x)_0^T underbrace( hat(bold(A))^T overline(bold(Q)) hat(bold(C)), bold(F)^T ) bold(u) $ As gradient of this cost function is $ gradient_bold(u) hat(J) = bold(H) bold(u) + bold(F) bold(x)_0 $ we have to solve $ bold(H) bold(u) = - bold(F) bold(x)_0 $ which has nice solution $ bold(u) = -bold(H)^(-1) bold(F) bold(x)_0 $ in Matlab ```matlab u = - H \ F * x0; ``` This can be further extended by adding $ bold(u)_k <= bold(u)_"max"\ bold(u)_k >= bold(u)_"min" $ For constarints on state, we have to express it using $ hat(bold(C)) bold(u) + hat(bold(A)) bold(x)_0 <= bold(x)_"max" $ ] The major disadvantage of both these options is that the optimization has to be precalculated in advance, meaining that any divergence form the expected path introduces problems as it is by design open--loop. ] #question(name: [Explain the essence of receding horizon control also known as model predictive control (MPC). What are the major advantages and disadvantages?])[ MPC (Model Predictive Control) takes the aformentioned optimization and uses it to control the system in real time. It calculates $N$ steps before the current state, and performs the first one. Than it repeats the entire procedure again, only shifted by one sample. This allows the controler to react to current state without compromising the ability of long--term planning. Main disadvantage is potential issues with real--time calculations, as it is computationaly expensive to preform the optimization in every step. ] #question(name: [Formulate the MPC regulation for a linear system and a quadratic cost as a quadratic program. Give both the simultaneous and sequential versions.])[ The optimization is identical to open--loop formulation $ min_(bold(u), bold(x)) 1/2 bold(x)_N^T bold(S) bold(x)_N &+ 1/2 sum_(k=1)^(N-1) (bold(x)_k^T bold(Q) bold(x)_k + bold(u)_k^T bold(R) bold(u)_k)\ "subject to" &bold(x)_(k+1) = bold(A) bold(x)_k + bold(B) bold(u)_k\ &bold(x)_t = "given"\ &bold(x)_"min" <= bold(x)_k <= bold(x)_"max"\ &bold(u)_"min" <= bold(u)_k <= bold(u)_"max" $ #part(name: [Simultaneous (sparse) optimization])[ This is already described in the previous question. ] #part(name: [Sequential (dense) optimization])[ The sequential version without constrainst is equivalent to _state feedback control_. The rest is decribed in previous question. ] ] #question(name: [Formulate the MPC tracking for a linear system and a quadratic cost as a quadratic program. Explain the need for replacement of the control signals by their increments in the optimization problem. Give both the simultaneous and sequential versions.])[ We have to rewirte the problem in another form $ bold(e)_k = bold(r)_k - bold(y)_k = bold(r)_k - bold(C)bold(x)_k arrow.r bold(0) $ To have a steady state, we have to optimize over $Delta bold(u)$ instead of $bold(u)$ as the input signal might be nonzero for the steady state. Now we have to rewrite the entire problem using this notation, and than we can form the two types of optimization. ] #question(name: [Discuss the anticipatory reference tracking (aka preview control) and show how this could be achieved using MPC.])[ This is simmilar to regular tracking MPC, but as the reference can be set arbitralrily, we can set the future reference to other values. ] #question(name: [Show how soft constraints can be included in the MPC optimization problem and discuss the motivation for their introduction.])[ We can add new optimization variable $epsilon$ in order to soften the constraints as $ bold(y)_"min" - epsilon bold(v)_"max" <= bold(y)_k <= bold(y)_"max" + epsilon bold(v)_"max" $ we also have add the $epsilon$ variable to the cost function $ "min" [... + rho epsilon] $ where $rho$ is a positive constant. ] #question(name: [Explain the difference between the prediction horizon and control horizon.])[ Prediction horizon are the steps that are simulated in the MPC, control horizon are the steps for which the control sequence ($Delta bold(u)$) is non--zero. ] ] #skills[ #question(name: [Implement a simple model predictive controller (MPC) in both the simultaneous and sequential formats using Matlab. Rely on the availability of numerical solvers for quadratic programming, that is, you do not have to write your own optimization solver.])[] ]
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/复习/英语/main.typ
typst
#import "template.typ": * #let data=yaml("./data.yaml") #import "@preview/tablex:0.0.8": tablex, rowspanx, #show: doc => conf( linespacing: 1em, outlinedepth: 3, blind: false, listofimage: true, listoftable: true, listofcode: true, alwaysstartodd: true, doc ) #import "@preview/colorful-boxes:1.3.1": * = 六级题型和分值回顾 写作部分:107分,听力部分:249分,阅读理解部分:249分,翻译部分:107分。 = 听力 前对+后对 == 新闻观点题 条件,转折,因果 == distrbance 精神困扰
https://github.com/xsro/xsro.github.io
https://raw.githubusercontent.com/xsro/xsro.github.io/zola/typst/nlct/math/lie.typ
typst
= Algebra, Lie Group and Lie Algebra == Group == Ring and Algebra == Homotopy == Fundamental Group == Covering Space == Lie Group == Lie Algebra of Lie Group == Structure of Lie Algebra
https://github.com/ilsubyeega/circuits-dalaby
https://raw.githubusercontent.com/ilsubyeega/circuits-dalaby/master/Type%201/2/28.typ
typst
#set enum(numbering: "(a)") #import "@preview/cetz:0.2.2": * #import "../common.typ": answer 2.28 다음 회로의 단자 $(a, b)$에서 $R_(e q)$를 구하라. #answer[ a와 b가 서로 이동하는 구간에 저항이 없는 구간이 있기에 다른 저항에 영향을 받지 않는다. 따라서 $R_(e q) = 0$ ]
https://github.com/sses7757/sustech-graduated-thesis
https://raw.githubusercontent.com/sses7757/sustech-graduated-thesis/main/sustech-graduated-thesis/layouts/preface.typ
typst
Apache License 2.0
#import "@preview/anti-matter:0.0.2": anti-matter #import "../utils/style.typ": 字号, 字体 // 前言,重置页面计数器 #let preface( // documentclass 传入的参数 twoside: false, fonts: (:), // 正文字体与字号参数 text-args: auto, // 标题字体与字号 heading-font: auto, // 其他参数 spec: (front: "I", inner: "1", back: "I"), ..args, it, ) = { // 分页 if (twoside) { pagebreak() + " " } counter(page).update(0) anti-matter(spec: spec, ..args, it) // 默认参数 fonts = 字体 + fonts if (text-args == auto) { text-args = (font: fonts.宋体, size: 字号.小四) } // 设置文本和段落样式 set text(..text-args) // 显示页眉 set page( header: locate(loc => { // 获取当前页面的一级标题 let cur-heading = current-heading(level: 1, loc) // 如果有一级标题,则渲染页眉 if true { let heading = heading-display(active-heading(level: 1, prev: false, loc)) set text(font: fonts.宋体, size: 字号.五号) stack( align(center, heading), v(0.25em), line(length: 100%, stroke: 0.5pt + black) ) } } ) ) }
https://github.com/davystrong/umbra
https://raw.githubusercontent.com/davystrong/umbra/main/gallery/basic.typ
typst
MIT License
#import "@preview/umbra:0.1.0": shadow-path #set page(width: 15cm, height: 15cm, margin: 0.5cm) #shadow-path((10%, 10%), (10%, 90%), (90%, 90%), (90%, 10%), closed: true)
https://github.com/Vanille-N/mpri2-edt
https://raw.githubusercontent.com/Vanille-N/mpri2-edt/master/README.md
markdown
# MPRI2 Timetable This is an individual version of [the official timetable](https://wikimpri.dptinfo.ens-cachan.fr/doku.php?id=emploidutemps23). Please [report inconsistencies](https://github.com/Vanille-N/mpri2-edt/issues). ## Installation ### Dependencies This document is written in standalone [Typst](https://typst.app/) and requires no additional external tools. ### Rendering ```sh # From the project root $ cp demo/blank.typ my.typ # Use your favorite editor to uncomment (remove the leading '//') the classes you want to choose $ typst compile my.typ # If no errors occured, `my.pdf` is now your rendered timetable ``` ## External classes You might be following external classes, in which case you may add the description of these classes to `ext.typ`, following the example of existing classes and the instructions. Please commit these additions and make a pull request so that other people who take the same external classes as you can benefit from it. ## Understanding error messages The code is still a bit rough (and so is my knowledge of Typst), so you may encounter obscure error messages. For the purposes of this project they will be separated in two categories: ### 1. Your fault #### Incompatible classes `error: panicked with: [There is a conflict in your chosen classes]` If you see this message, you chose two classes that occur on the same time slot. The backtrace will tell you the day and the period that the conflict occurs. If you're *really* sure that you didn't select incompatible classes, this might be an [outdated information](https://wikimpri.dptinfo.ens-cachan.fr/doku.php?id=emploidutemps23) or a bug, those can be reported as [Issues](https://github.com/Vanille-N/mpri2-edt/issues). #### Any syntax error inside `demo/my.typ` (or your chosen destination) The Typst error message should guide you. #### `typtyp.typ` error An `error: assertion failed` in file `typtyp.typ`, if it occurs inside `my.typ` (see last item of the error message backtrace), likely indicates that you accidentally introduced in the list of `chosen` classes an element that is not properly formatted as a class. The fact that this error message is obscure will be improved as much as possible. ### 2. My fault Anything not in the previous category is a bug and should be [reported](https://github.com/Vanille-N/mpri2-edt/issues) for fixing.
https://github.com/denizenging/site
https://raw.githubusercontent.com/denizenging/site/master/.typst/page/lib.typ
typst
#import "@local/pub-util:0.0.0": * #let template( title: none, description: none, license: "CC BY-NC-ND", reading-time: false, comments: false, menu: none, links: none, layout: none, outputs: none, ) = { if title == none { panic("no title") } let building = "building" in sys.inputs let info = if building { let filename = sys.inputs.at("path").split("/").at(-1) (lang: parse-lang(filename)) } let lang = if building { lang-to-lang-region(info.lang) } let doc = ( title: title, ) if not building { typst-to-preview(title, none) return } building = sys.inputs.building if building == "md" { let frontmatter = ( title: title, // The `lang` here is solely for pandoc to convert to epubs. // The `title` is also used by pandoc, but not solely. // It is also used for Hugo. lang: info.lang, ) if description != none { frontmatter.insert("description", description) } if reading-time != none { frontmatter.insert("readingTime", reading-time) } if license != none { frontmatter.insert("license", license) } if comments != none { frontmatter.insert("comments", comments) } if menu != none { frontmatter.insert("menu", (main: ( weight: menu.at(0), params: (icon: menu.at(1)), ))) } if links != none { frontmatter.insert("links", links.map(x => ( title: x.at(0), description: x.at(1), website: x.at(2), image: x.at(3), ))) } if layout != none { frontmatter.insert("layout", layout) } if outputs != none { frontmatter.insert("outputs", outputs) } typst-to-markdown(frontmatter: frontmatter) } else if building == "pdf" { typst-to-pdf(title, none) } else { panic("Unsupported format: " + building) } }
https://github.com/JeffreyAnimal/Typst-Project
https://raw.githubusercontent.com/JeffreyAnimal/Typst-Project/main/myFile.typ
typst
#import "templates/thesisTemplate.typ": thesis #import "templates/helper.typ" : Code, Table, Image #show: thesis.with( title: "Title", authors: ( (name: "<NAME>", affiliation: "Company", matrikel: "1234567", email: "<EMAIL>", semester: "WS/SS 202x/202x" ), ), bibfile: "literature.bib", abstract:"Abstract text here.", ) = My Project MyText @link-name My inline Formula $a^2 + b^2 = c^2$ My Formula Block: $ sum_(i=0)^n i^2 $ Citation @literature1 #Image( [Image Text.], "assets/example.jpg", width: 60% ) <link-name>
https://github.com/Wint3rmute/cv
https://raw.githubusercontent.com/Wint3rmute/cv/master/cv.typ
typst
MIT License
#import "alta-typst.typ": alta, term, skill, better_skill, personal_project, position #alta( name: "<NAME>", links: ( (name: "email", link: "mailto:<EMAIL>"), (name: "github", link: "https://github.com/wint3rmute", display: "@wint3rmute"), (name: "linkedin", link: "https://linkedin.com/in/example", display: "<NAME>"), (name: "website", link: "https://baczek.me/", display: "baczek.me"), (name: "phone", link: "+48 796 070 377", display: "+48 796 070 377"), ), tagline: [ Software engineer with 3+ years of experience, both in writing code and leading a team of programmers. Familiar with web development, systems programming and digital signal processing. Fascinated with computer-aided design processes, especially generative art and music. ], [ #show link: underline == Experience #position[Mission operations software development lead][Wrocław, PL] _SatRev_\ #term[2021 --- Present][Wrocław, PL] Developed and maintained SatRev's in-house mission-operations software used for operating the entire fleet of company's satellites. Leading a team of 3-5 programmers. - Management & monitoring of software infrastructure - Real-time communication protocols - Databases & message queues - Metrics visualization #better_skill("Python") #better_skill("Rust") #better_skill("Linux") #better_skill("PostgreSQL") #better_skill("Apache Kafka") #better_skill("Ansible") #better_skill("Azure") #better_skill("Grafana") #better_skill("Prometheus") #position[Software Developer][Wrocław, PL] _SatRev_\ #term[2020 --- 2021][Wrocław, PL] Developed the telemetry software and automation/testing tools used during the testing and integration processes of the STORK satellites. Worked on the software for the on-board computer for the STORK platform. - Telemetry and ground station software - Radio communication protocols - Automatic testing tools #better_skill("Python") #better_skill("PyTest") #better_skill("Embedded Linux") #better_skill("Buildroot") #better_skill("Docker") #better_skill("MQTT") #better_skill("CI/CD") #better_skill("Git") #better_skill("InfluxDB") #position[Software Developer][Wrocław, PL] _BZB UAS_\ #term[2020][Wrocław, PL] Worked on an integrated telemetry collection & sharing service for a semi-autonomous UAV dedicated to conducting photogrammetry scans. #better_skill("Python") #better_skill("ArduPilot") #better_skill("MavLink") #better_skill("Embedded Linux") #better_skill("OpenWRT") == Education === Wrocław University of Science and Technology #term[Sep 2022 --- 2023][Wrocław, PL] M.Sc. Computer Science. Thesis title: DSP graph generation algorithm for solving the sound synthesis problem. === Wrocław University of Science and Technology #term[Sep 2017 --- 2021][Wrocław, PL] B.Sc. Computer Science. Thesis title: Autonomous drone-based scouting system. #v(48pt) == Activity at university //=== Academic Aviation Club //#term[Sep 2019 --- 2023][Wrocław, PL] I participated in a student research circle, the Academic Aviation Club (Original Polish name: _<NAME>_), dedicated to developing unmanned aerial vehicles. During the period of 2020 to 2021, I held the position of club's Vice-President. I took part in a number of competitions, both as a programmer and as a team leader. #position[SAE Aero Design][Florida, USA] #term[2020][Florida, USA] Developed a mathematical model predicting an optimal position for dropping a payload from a flying plane and built the telemetry software required to operate the system. The team took second place in general classification, second place in the Advance category. #position[Droniada][Kąkolewo, PL] #term[2021][Kąkolewo, PL] Designed a visual marker detection system, based on machine learning algorithms. The system facilitated real-time marker detection on-board an autonomous drone, which then performed a precise release of pesticides (the subject matter of the competition were new technologies in agriculture). The team won the second place. #position[IAV -- Intelligent Autonomous Vehicles][Gdańsk, PL] #term[2019][Gdańsk, PL] Designed a system for determining the position of Bluetooth LE beacons, using an autonomous drone. The team won the first place. #position[Nokia Innovative Projects][Wrocław, PL] #term[2018][Wrocław, PL] Developed a prototype of a Pokemon-Go-alike game. The game world was generated procedurally, based on Open-StreetMaps. Players could gather resources and build structures Within the game world, that would be visible to other players visiting the same area. == Languages - *English* -- fluent - *Polish* -- native == Personal Projects #personal_project[Running a personal website and a personal cloud][https://baczek.me] I'm using a VPS server to run a personal website and a number of both personal and public cloud services. Everything is monitored via the Grafana stack. #better_skill("System Administration") #better_skill("Docker") #better_skill("Prometheus") #better_skill("Grafana") #better_skill("Caddy") #better_skill("Ansible") #better_skill("Wireguard") #personal_project[Collaborative sampler][https://github.com/Wint3rmute/libretakt] Written in a team of 4, the sampler is meant to reproduce the Digitakt-style workflow in a distributed environment. Each user has their own DSP engine running to assure minimal latency, but the changes each user makes in the sequencer state are synchronized in real time across a virtual ,,jam session''. #better_skill("Rust") #better_skill("WebSockets") #better_skill("DSP") #better_skill("Audio Effects") #better_skill("FFMPEG") #better_skill("Media streaming") #personal_project[Personal Linux configuration][https://github.com/Wint3rmute/dotfiles] I keep my dotfiles documented and version controlled, with an Ansible-based deployment procedure which allows me to sync my configuration across multiple machines and bootstrap a new computer easily and quickly. #better_skill("Linux") #better_skill("Ansible") #better_skill("Git") #v(7pt) #set align(right) #emph(text(size: 8pt)[ I hereby give consent for my personal data included in my application to be processed for the purposes of the recruitment process. ]) ], )
https://github.com/dadn-dream-home/documents
https://raw.githubusercontent.com/dadn-dream-home/documents/main/contents/03-luoc-do-use-case/index.typ
typst
= Lược đồ use case Nhóm đề xuất các use case ở lược đồ @fig:usecase. #figure( image("use-cases.drawio.svg", width: 60%), caption: "Lược đồ use case", ) <fig:usecase> Chi tiết từng use case được mô tả ở @sec:uc-scenarios.
https://github.com/TLouf/CV
https://raw.githubusercontent.com/TLouf/CV/main/template.typ
typst
#let dark_blue = rgb("#1e3658") #let light_blue = rgb("#447a9d") #let pale_green = rgb("#f1faee") #let burnt_sienna = rgb("#d15306") #let gh_icon = text(font: "Font Awesome 5 Brands")[\u{f09b}] #let orcid_icon = text(font: "Font Awesome 5 Brands")[\u{f8d2}] #let mastodon_icon = text(font: "Font Awesome 5 Brands")[\u{f4f6}] #let twitter_icon = text(font: "Font Awesome 5 Brands")[\u{f099}] #let link_icon = text(font: "FontAwesome")[\u{f0c1}] #let mail_icon = text(font: "FontAwesome")[\u{f0e0}] #let phone_icon = text(font: "FontAwesome")[\u{f095}] #let ext_link_icon = text(font: "FontAwesome")[\u{f08e}] #let super_ext_link_icon = super[#ext_link_icon] #let cv_section(title) = { block({ // Display a backdrop rectangle. move(dx: -1.5%, dy: 0.5%, rect( fill: pale_green, inset: 0pt, outset: (left: 100pt), move( dx: 1.5%, dy: -0.5%, rect(height: 2em, fill: dark_blue, stroke: 0pt, outset: (left: 100pt, right: 10pt))[ #text(fill: white)[== #title] ] ) )) }) } #let contact_cell = rect.with( inset: 2mm, fill: light_blue, stroke: (thickness: 2pt, paint: pale_green), // width: 100%, ) #let dated_heading = table.with( columns: (75%, 25%), rows: 2pt, stroke: none, inset: 0pt, gutter: 0pt, align: (left, right), )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/commute/0.2.0/lib.typ
typst
Apache License 2.0
#let node(pos, label, ..opts) = ( kind: "node", pos: pos, label: label, id: repr(opts.pos().at(0, default: label)), ) #let arr(start, end, label, start-space: none, end-space: none, label-pos: left, curve: 0deg, stroke: 0.05em, ..options) = { ( kind: "arrow", start: start, end: end, label: label, start-space: start-space, end-space: end-space, label-pos: label-pos, curve: curve, stroke: stroke, options: options.pos(), ) } #let commutative-diagram( node-padding: (70pt, 70pt), arr-clearance: 0.7em, padding: 1.5em, debug: false, ..entities ) = { style(styles => { // useful utility function let _center(c) = { let m = measure(c, styles) place(dx: -0.5*m.width, dy: -0.5*m.height, c) } // get nodes and arrows from the function arguments let entities = entities.pos() let nodes = entities.filter(e => e.kind == "node") let arrows = entities.filter(e => e.kind == "arrow") let pos-from-id = (:) // adjust node and arrow coordinates so that the min is (0, 0) let min-row = calc.min(..nodes.map(node => node.pos.at(0))) let min-col = calc.min(..nodes.map(node => node.pos.at(1))) let max-row = calc.max(..nodes.map(node => node.pos.at(0))) let max-col = calc.max(..nodes.map(node => node.pos.at(1))) for i in range(nodes.len()) { nodes.at(i).pos.at(0) -= min-row nodes.at(i).pos.at(1) -= min-col pos-from-id.insert(nodes.at(i).id, nodes.at(i).pos) } arrows = arrows.map(arr => { if type(arr.start) == "array" { arr.start.at(0) -= min-row arr.start.at(1) -= min-col } else if repr(arr.start) in pos-from-id { arr.start = pos-from-id.at(repr(arr.start), default: none) } else { panic("Error while processing arrow from " + repr(arr.start) + " to " + repr(arr.end) + ": can't find a node with id = " + repr(arr.start)) } if type(arr.end) == "array" { arr.end.at(0) -= min-row arr.end.at(1) -= min-col } else if repr(arr.end) in pos-from-id { arr.end = pos-from-id.at(repr(arr.end), default: none) } else { panic("Error while processing arrow from " + repr(arr.start) + " to " + repr(arr.end) + ": can't find a node with id = " + repr(arr.end)) } arr }) max-row -= min-row max-col -= min-col min-col = 0 min-row = 0 // measure the size of the various rows and columns let col-sizes = () let row-sizes = () for r in range(0, max-row+1) { row-sizes.push(0pt) } for c in range(0, max-col+1) { col-sizes.push(0pt) } for node in nodes { let m = measure(node.label, styles) if m.width > col-sizes.at(node.pos.at(1)) { col-sizes.at(node.pos.at(1)) = m.width } if m.height > row-sizes.at(node.pos.at(0)) { row-sizes.at(node.pos.at(0)) = m.height } } let row-pos = row-sizes let col-pos = col-sizes row-pos.at(0) /= 2 col-pos.at(0) /= 2 for r in range(1, max-row+1) { row-pos.at(r) += row-pos.at(r - 1) + node-padding.at(1) } for c in range(1, max-col+1) { col-pos.at(c) += col-pos.at(c - 1) + node-padding.at(0) } // total diagram dimensions let height = row-sizes.fold(-node-padding.at(1), (x, y) => x+y+node-padding.at(1)) let width = col-sizes.fold(-node-padding.at(0), (x, y) => x+y+node-padding.at(0)) // useful functions used many times later let coords(pos) = ( col-pos.at(pos.at(1)), row-pos.at(pos.at(0)) ) let size-at(pos) = { for node in nodes { if node.pos == pos { return measure(node.label, styles) } } return (width: 0pt, height: 0pt) } // units conversion let pt-per-em = measure(rect(width: 1em), styles).width let to-abs(l) = l.abs + l.em * pt-per-em // various vector utility functions let v-add(a, b) = (a.at(0) + b.at(0), a.at(1) + b.at(1)) let v-sub(a, b) = (a.at(0) - b.at(0), a.at(1) - b.at(1)) let v-mul(a, x) = (a.at(0) * x, a.at(1) * x) let v-dir(a, l) = v-mul((calc.cos(a), calc.sin(a)), l) let v-add-dir(p, a, l) = v-add(p, v-dir(a, l)) let v-length(vv) = calc.sqrt(calc.pow(to-abs(vv.at(0))/1mm, 2) + calc.pow(to-abs(vv.at(1))/1mm, 2))*1mm // measures the length of a segment starting in the center // of a rectangle and ending on one of the rectangle's edges, // given the angle of the segment let measure-at-angle(m, a, padding) = { if calc.sin(a) == 0 { m.width / 2 + padding } else if calc.cos(a) == 0 { m.height / 2 + padding } else { calc.min( (m.width / 2 + padding) / calc.abs(calc.cos(a)), (m.height / 2 + padding) / calc.abs(calc.sin(a)), calc.max(m.width, m.height) / 2 + padding, ) } } // the box where all the diagram's elements are box( width: width + 2*padding, height: height + 2*padding, stroke: if debug { 0.5pt + red } else { none }, inset: padding, { for arr in arrows { let start = coords(arr.start) let end = coords(arr.end) // arrow angle measured clockwise from the right // i know that clockwise is disgusting, but rotate rotates clockwise let angle = calc.atan2((end.at(0) - start.at(0)) / 1pt, (end.at(1) - start.at(1)) / 1pt) let curve-angle = arr.curve let start-space = arr.start-space let end-space = arr.end-space if start-space == none { start-space = measure-at-angle(size-at(arr.start), angle - curve-angle, to-abs(arr-clearance)) } if end-space == none { end-space = measure-at-angle(size-at(arr.end), angle + curve-angle, to-abs(arr-clearance)) } let astart = v-add-dir(start, angle - curve-angle, start-space) let aend = v-add-dir(end, angle + 180deg + curve-angle, end-space) // draw the arrow's tip place(dx: aend.at(0), dy: aend.at(1), rotate(angle + curve-angle + 90deg, origin: top+left, if "surj" in arr.options { move(dy: 0.21em, _center( box(clip:true, height: 0.42em, $arrow.t.twohead$) )) aend = v-add-dir(aend, angle + curve-angle, -0.42em) } else if "nat" in arr.options { move(dy: 0.18em, _center( box(clip:true, height: 0.36em, $arrow.t.double$) )) aend = v-add-dir(aend, angle + curve-angle, -0.36em) } else { move(dy: 0.15em, _center( box(clip:true, height: 0.3em, $arrow.t$) )) aend = v-add-dir(aend, angle + curve-angle, -0.3em) } ) ) // draw the arrow's start place(dx: astart.at(0), dy: astart.at(1), rotate(angle - curve-angle - 90deg, origin: top+left, if "bij" in arr.options { if "nat" in arr.options { move(dy: 0.18em, _center( box(clip:true, height: 0.36em, $arrow.t.double$) )) astart = v-add-dir(astart, angle - curve-angle, 0.36em) } else { move(dy: 0.15em, _center( box(clip: true, height: 0.3em, $arrow.t$) )) astart = v-add-dir(astart, angle - curve-angle, 0.3em) } } else if "inj" in arr.options { path(stroke: (thickness: arr.stroke, cap: "round"), (0em, 0.15em), ((0.15em, 0em), (-0.15em, 0em)), (0.3em, 0.15em) ) astart = v-add-dir(astart, angle - curve-angle, 0.15em) } else if "def" in arr.options { place(dx: -0.2em, line(stroke: (thickness: arr.stroke, cap: "round"), length: 0.4em)) } ) ) // find the dash style let dash = arr.options .filter(opt => opt not in ("inj", "surj", "bij", "def", "nat")) .at(0, default: none) // draw the arrow's stem // this should be, up to a good approximation (due to different // start and end tips), a parabola. See https://en.wikipedia.org/wiki/Bézier_curve let ctrl-length = - (v-length(v-sub(astart, aend)) / 3 / calc.cos(curve-angle)) if "nat" in arr.options { let sep = 0.095em place(path(stroke: (thickness: arr.stroke, dash: dash, cap: "round"), (v-add-dir(astart, angle - curve-angle + 90deg, -sep), v-dir(angle - curve-angle, ctrl-length)), (v-add-dir(aend, angle + curve-angle + 90deg, -sep), v-dir(angle + curve-angle, ctrl-length)), )) place(path(stroke: (thickness: arr.stroke, dash: dash, cap: "round"), (v-add-dir(astart, angle - curve-angle + 90deg, sep), v-dir(angle - curve-angle, ctrl-length)), (v-add-dir(aend, angle + curve-angle + 90deg, sep), v-dir(angle + curve-angle, ctrl-length)), )) } else { place(path(stroke: (thickness: arr.stroke, dash: dash, cap: "round"), (astart, v-dir(angle - curve-angle, ctrl-length)), (aend, v-dir(angle + curve-angle, ctrl-length)), )) } // draw the arrow's label let normal = (- aend.at(1) + astart.at(1), aend.at(0) - astart.at(0)) let middle = v-add(v-mul(v-add(astart, aend), 0.5), v-mul(normal, -calc.tan(curve-angle)/4)) let m = measure(arr.label, styles) let l = ( ( if arr.label-pos == right { -0.5 } else if arr.label-pos == left { 0.5 } else { 0 } ) * ( 0.5em + calc.abs(calc.sin(angle)) * m.width + calc.abs(calc.cos(angle)) * (m.height + 0.3em) ) + ( if type(arr.label-pos) == "length" { arr.label-pos } else { 0pt } ) ) let lpos = v-add-dir(middle, angle - 90deg, l) if arr.label-pos == 0 { place(dx: lpos.at(0), dy: lpos.at(1), _center( rect(width: m.width + 0.1em, height: m.height + 0.3em, fill: white) )) } if debug { place(dx: lpos.at(0), dy: lpos.at(1), _center( rect(width: m.width + 0.5em, height: m.height + 0.8em, radius: 0.25em, stroke: 0.5pt + red) )) } place(dx: lpos.at(0), dy: lpos.at(1), _center(arr.label)) } for node in nodes { let coords = coords(node.pos) place( dx: coords.at(0), dy: coords.at(1), _center(node.label) ) if debug { let m = measure(node.label, styles) place( dx: coords.at(0), dy: coords.at(1), _center(rect(width: m.width + 2 * arr-clearance, height: m.height + 2 * arr-clearance, stroke: 0.5pt+red)), ) place( dx: coords.at(0), dy: coords.at(1), _center(circle( radius: calc.max(m.width, m.height) / 2 + arr-clearance, stroke: 0.5pt+red )), ) } } }) }) }
https://github.com/Sckathach/geopolitix
https://raw.githubusercontent.com/Sckathach/geopolitix/main/main.typ
typst
#import "lapreprint.typ": template #show: template.with( title: "Riyad - Simple oasis ou nouveau centre du Monde ?", subtitle: "Analyse de la stratégie du prince héritier <NAME> pour placer l'Arabie Saoudite au premier plan de l'échiquier mondial. ", short-title: "GéopolitiX", kind: "GéopolitiX", logo: "ressources/logo.png", margin: ( ( title: "Contacts", content: [ Le magicien quantique\ #link("<EMAIL>")[<EMAIL>]\ ], ), ), abstract: ( title: "Introduction", content: "Au cœur de l'instabilité tumultueuse du Monde Arabe se dresse un géant. Bien plus qu'un simple réservoir d'or noir, l'Arabie Saoudite compte jouer avec ses nombreux atouts pour se positionner en tant que nouveau centre du monde. Intriquée dans des tensions régionales et internationales, l'Arabie Saoudite navigue habilement entre tradition et modernisation, afin de séduire le Monde Arabe tout en s'élevant au rang de puissance mondiale. Ces récentes initiatives sur la scène internationale témoignent justement de cette volonté de réinvention. Mais cette oasis, en plein milieu d'un océan de sable, arrivera-t-elle à réellement se métamorphoser en un phare de prospérité et d'influence ? Ou n'est-ce qu'un mirage voué à disparaître ?\n\n" ), date_fr: "1er janvier 2024", numero: 1, theme: rgb("#f7aa00"), authors: ( ( name: "<NAME>" ), ), open-access: false, venue: "" ) #set heading(numbering: none) #set par( first-line-indent: 1.5em, justify: true, ) #show figure.where( kind: "plain" ): set figure.caption(separator: []) #let place_margin(position, margin_content) = place( if (position == "left") { left + bottom } else { right + bottom }, dx: if (position == "left") { -33% } else { 33% }, dy: -10pt, box(width: 27%, { margin_content }) ) #let cap(content) = text(size: 8pt, content) #place_margin("left", figure( grid( columns: 1, gutter: 2mm, image("ressources/saudi-aramco.jpg"), cap("<NAME>, troisième entreprise par capitalisation boursière, devant Google. " + emoji.copyright + "AFP"), v(15em) ), ) ) = Petit point Historique L'histoire contemporaine de l'Arabie Saoudite débute dans le tumulte de la Première Guerre mondiale. Les Accords Sykes-Picot de 1916 et la Déclaration Balfour de 1917, redessinant la carte du Moyen-Orient, ont retracé les frontières, redistribué les richesses et divisées les populations locales. Les occidentaux, en se partageant les parts du gâteau, ont indirectement participé à l'écriture d'une ère de crises majeures. En plus d'exacerber des conflits déjà existants comme la rivalité religieuse entre les sunnites et les chiites, de nouveaux conflits sont apparus, tant sur le plan des ressources que sur le plan politique. L'Iran en est un exemple flagrant. Après un coup d'état anglo-américain en 1953, suivi du régime autocratique très répressif du Shah, les tensions sociales se sont accumulées et ont menées à la révolution iranienne, source des tensions actuelles entre l'occident et l'Iran. Outre les tensions régionales, la découverte du pétrole en 1938 a radicalement transformé l'Arabie Saoudite, la propulsant sur la scène mondiale en tant que puissance pétrolière majeure. Au-delà des avantages financiers, la création de l'OPEP en 1960 a permis à l'Arabie Saoudite d'imposer son influence sur le marché occidental. Un exemple est la première crise pétrolière de 1973. Ce conflit commence avec l'accord de Balfour, qui signé 56 ans plus tôt par les Européens, a imposé le peuple israélien aux populations arabes locales. Cet accord a entraîné de nombreuses guerres, dont la Nakba en 1948 : l'exode de plus de 700 000 Arabes, chassés par Israël. Une offensive arabe, égyptienne et syrienne a lieu en 1973 : c'est le début de la guerre du Kippour. Pour punir les États-Unis et les Pays-Bas qui ont soutenu Israël, l'OPEP a répliqué en diminuant drastiquement sa production, ce qui a ébranlé tout le marché occidental. La guerre du Kippour est aussi importante d'un point de vue géostratégique, car elle a mis fin à l'isolement d'Israël. Après une défaite rapide, l'Egypte accepta de reprendre des relations normales avec son voisin en échange d'un retrait des troupes israéliennes du Sinaï. Ce retournement de situation déstabilise la fragile coopération arabe et réduite l'influence de Riyad qui se positionne en tant que réunificateur du monde arabe. La fin du XXe siècle et le début du XXIe siècle ont vu l'Arabie Saoudite se confronter, et souvent se mêler aux grands événements mondiaux, de la guerre du Golfe à la lutte contre le terrorisme, tout en faisant face à des défis internes et à la pression croissante pour des réformes sociales et économiques. Riyad a fait le choix durant ces années, de s'allier aux États-Unis, afin de garantir son hégémonie militaire locale. = Géographie et démographie // mettre carte #let pm(images) = place_margin("right", figure( grid( columns: 1, gutter: 2mm, for x in images { if x.len() == 1 { image(x.at(0)) } else { image(x.at(0)) cap(x.at(1)) } }, v(2em), // image("ressources/carte-arabie-saoudite.jpg"), // cap("L'Arabie Saoudite au cœur du Monde Arabe. " + emoji.copyright + "Wikipedia"), // v(2em), ), ) ) #pm(( ("ressources/flag-saudi-arabia.png", "Drapeau de l'Arabie Saoudite. L'inscription est le credo islamique, ou shahada : \"J'atteste qu'il n'y a point de divinité en dehors d'Allah et j'atteste que Mahomet est son messager\"."), ("ressources/carte-arabie-saoudite.jpg",), )) L'<NAME> se positionne naturellement en tant que meneur du Monde Arabe, de par sa position géographique le long du canal de Suez (12 % du commerce mondial), de par sa puissance démographique et militaire, (premiers dans la région), mais aussi de par sa culture, l'<NAME> possédant les deux plus grands lieux saints de l'Islam, la mosquée al-Harâm à La Mecque et la mosquée du Prophète à Médine. Les droits de l'Homme au sens européen sont encore loin d'être respectés, néanmoins, la quasi-totalité de la population est lettré et le régime autoritaire garantit une stabilité du pays. Les lois sont dérivées de la charia, et malgré les quelques avancées récentes pour les femmes (possibilité de se rendre à l'étranger sans accord du référent masculin en 2019, dix femmes sont nommées à des postes à responsabilité dans les deux saintes mosquées du pays en 2020, trois millions de permis vont êtes attribués à des Saoudiennes en 2020), le pays reste entièrement contrôlé par les hommes. L'<NAME> est le pays de l'or noir, mais il est très pauvre en or bleu. Aucune rivière, aucun fleuve, ni même aucun cours d'eau ne traverse le pays, qui doit importer ou transformer de l'eau de mer pour satisfaire ses besoins. Cela pose un grand frein sur les projets d'extension et de diversification de l'économie, c'est pour cela que la rhétorique saoudienne utilise énormément l'image de l'eau lors de ses vidéos de présentations. #figure( image("ressources/carte-precipitations.png", width: 80%), caption: "Carte des précipitations annuelles. L'échelle va de 0 à 305mm/an, alors que la plupart des cartes de précipitations commencent à 300mm/an.", kind: "plain", supplement: "", numbering: (_) => "", ) Malheureusement, le problème est bien réel, et doit être traité rapidement, car, même si l'Arabie Saoudite est la deuxième puissance pétrolière de la planète derrière le Venezuela, le pays peine à trouver de nouveaux gisements, et la production de pétrole du pays pourrait diminuer d'ici 2027, selon les déclarations du prince héritier <NAME> (MBS). = Relations locales La politique extérieure locale de l'Arabie Saoudite est différente avec chacun de ses voisins. Certains suivent l'alignement de Riyad par peur de créer des tensions, tandis que d'autres arrivent à s'opposer au régime. #v(5mm) == Conseil de Coopération du Golfe La région possède une alliance locale : le Conseil de Coopération du Golfe (CCG). Au sein de cette union, l'Arabie Saoudite se distingue comme un meneur incontesté, pilotant les discussions et orientant les politiques. Cette fédération de six États du Golfe Arabique (l'Arabie Saoudite, Oman, le Koweït, Bahreïn, les Émirats arabes unis et le Qatar.), formée en 1981, est née d'une nécessité commune de coopération et d'intégration économique, sécuritaire et politique face aux défis régionaux et internationaux. Même si ce groupe a pu coopérer à certains moments, les divergences de plus en plus importantes des membres empêchent le conseil de peser un réel poids sur la scène internationale aujourd'hui. #place_margin("left", figure( grid( columns: 1, gutter: 2mm, image("ressources/mbs-and-ebrahim-raisi.jpg"), cap("MBS lors de sa première rencontre avec le président iranien, l'ennemi historique de Riyad, en novembre 2023. " + emoji.copyright + "SPA"), v(2em), image("ressources/mbs-and-bashar-al-assad.jpg"), cap("MBS acceuille le président syrien Bashar al-Assad en dépit de la désaprobation américaine, au sommet de la ligue arabe en mai 2023. " + emoji.copyright + "SPA"), v(2em) ), ) ) #v(5mm) == Relations avec le Qatar Les relations entre l'Arabie Saoudite et le Qatar ont connu des hauts et des bas significatifs. D'abord non considéré car peu compétitif, la découverte en 1971 du gaz et l'investissement dans le plus grand gisement de gaz naturel au monde : le North Dome, a transformé le Qatar et l'a fait devenir un sérieux concurrent de la région. De plus, sa décision d'indépendance la même année, au lieu de rejoindre l'alliance des EAU, montre une volonté de faire cavalier seul. Ces relations ont pris un tournant en 2017, lorsque Riyad a décidé d'imposer un blocus au Qatar, en l'accusant de soutenir le terrorisme et de se rapprocher de l'Iran, l'ennemi principal de l'Arabie Saoudite. Cette crise diplomatique, qui a également impliqué les Émirats Arabes Unis, Bahreïn et l'Egypte, a vu la fermeture des frontières terrestres et aériennes avec le Qatar, ainsi que des restrictions maritimes. Le Qatar, cependant, a vigoureusement nié ces allégations et a résisté à la pression, cherchant des alliances alternatives et renforçant sa résilience économique. Ce blocus, qui a duré plus de trois ans, a finalement été levé début 2021 sans que le Qatar ne cède aux demandes de ses voisins. C'est un échec marquant de <NAME>, qui peut être en partie expliqué par la particularité de la population Qatari, très soudée et très résistante face aux pressions régionales. Cette confrontation a non seulement mis à l'épreuve les relations entre les deux nations, mais a également souligné les divisions au sein du Conseil de Coopération du Golfe. Des efforts de réconciliation ont été entrepris, mais les relations entre l'Arabie Saoudite et le Qatar restent complexes, mêlées de méfiance et de coopération pragmatique. La confrontation entre les deux pays n'est pas prête de s'arrêter, alors que les deux monarchies ont les mêmes objectifs et les mêmes cartes à jouer (pétrole, diplomatie, influence, sport...). #v(5mm) == Relations avec le Bahreïn Les relations avec le Bahreïn sont très différentes de celles avec le Qatar. En effet, le Bahreïn étant bien moins puissant, le choix a été pris de s'allier à Riyad plutôt que de s'y opposer. Cela se traduit notamment par coopération étroite, même militaire. L'Arabie Saoudite n'hésite pas à envoyer ses troupes pour garantir la stabilité politique et le maintien en place de la famille régnante qui est sunnite, dans un pays avec une légère majorité chiite. Cette solidarité s'est manifestée de manière significative lors du Printemps arabe en 2011, où l'Arabie Saoudite a déployé ses soldats sur toute la petite île du Bahreïn, pour s'assurer que la monarchie reste en place. Les deux pays partagent également une vision commune sur plusieurs questions régionales, notamment la lutte contre l'influence iranienne (chiite), et la coopération au sein du Conseil de Coopération du Golfe. Sur le plan économique, l'Arabie Saoudite est un partenaire commercial vital pour le Bahreïn, qui n'est rattaché au continent que par un pont reliant les deux pays. En outre, les deux royaumes collaborent étroitement dans le domaine de l'énergie, notamment dans l'exploration et l'exploitation de gisements pétroliers et gaziers. Les liens familiaux royaux entre les deux pays renforcent également cette relation, faisant de l'Arabie Saoudite un allié de confiance et un partenaire essentiel pour le Bahreïn. #v(5mm) #pagebreak() == Relations avec les Émirats Arabes Unis Les Émirats Arabes Unis (EAU), ont choisi comme le Bahreïn, de suivre Riyad dans ses positions, afin de s'en faire un allié plutôt qu'un ennemi. Les deux pays collaborent économiquement et souhaitent diversifier leurs économies respectives au-delà du pétrole, avec des initiatives conjointes dans les domaines de l'énergie renouvelable, du tourisme et de la technologie. Les EAU investissent massivement en Arabie Saoudite, soutenant ainsi les plans de modernisation et de diversification économique du royaume. En plus des relations économiques et géostratégiques, les deux pays collaborent aussi dans la lutte contre le terrorisme et les interventions militaires, comme au Yémen. Sur le plan diplomatique, les EAU et l'Arabie Saoudite se coordonnent souvent au sein du Conseil de Coopération du Golfe et sur la scène internationale, présentant un front uni sur de nombreux enjeux régionaux. Toutefois, il existe également une compétition, notamment dans le domaine de l'innovation et de l'influence régionale. #v(5mm) == Relations avec le Yémen Les relations avec le Yémen sont marquées par la guerre civile qui déchire le pays depuis 2015. Cette guerre mêlant plusieurs camps, dont les Houthis financés par l'Iran, et le gouvernement yéménite reconnu internationalement, a des conséquences humanitaires désastreuses. <NAME>, qui s'est engagé à soutenir le gouvernement yéménite, s'est entraîné dans un bourbier dont il peine à sortir. C'est un autre exemple important de l'échec de sa stratégie d'influence de la région. Encore aujourd'hui, l'impuissance de Riyad s'est soulignée lorsque les militaires étasuniens et britanniques se sont alliés pour agir dans la région et tenter de maîtriser la menace que pose les Houthis sur le commerce international. #place_margin("left", figure( grid( columns: 1, gutter: 2mm, image("ressources/mbs-and-poutine.jpg"), cap("MBS et Poutine manifestants leur entente sur le pétrole, au G20 à Buenos Aires. " + emoji.copyright + "REUTERS"), v(2em), image("ressources/mbs-and-zelenski.jpeg"), cap("MBS et Zelenski au sommet de la ligue arabe en mai 2023. " + emoji.copyright + "SPA"), v(2em) ), ) ) = Politique extérieure mondiale == Rôle dans les conflits actuels Depuis que la guerre russo-ukrainienne a éclaté, beaucoup de pays se sont transformés en diplomates. Devant le ballet incessant de chefs d'Etat européens, asiatiques, américains et même africains, <NAME> n'a eu d'autres choix que d'entrer dans la danse pour ne pas se retrouver à danser devant le buffet. Mais contrairement à eux, il a réussi à faire venir les deux antagonistes chez lui ; Zelenski lors du sommet de la ligue arabe à Jeddah le 19 mai 2023, et Poutine, qui ne sort que très rarement de Russie depuis la guerre, le 6 décembre 2023. Riyad avait déjà aidé à l'échange de plus de 300 prisonniers entre l'Ukraine et la Russie en septembre 2022. Le jeu de MBS est double : courtiser les Occidentaux tout en gardant ses liens privilégiés avec le Kremlin. En effet, MBS tente tant bien que mal de faire oublier l'assassinat du journaliste saoudien <NAME> le 2 octobre 2018 auprès des Occidentaux, qui l'accusent de ne pas faire respecter les droits de l'Homme dans son pays. Cependant, ces problèmes n'existent pas avec ses autres alliés. Moscou est un très grand allié de Riyad, surtout dans le cadre de la coopération avec l'OPEP. Poutine était justement reçu en grandes pompes aux Émirats-Arabes-Unis juste avant d'arriver à Riyad. De même que le reste du Monde Arabe, MBS n'applique pas de sanction à son homologue russe, il est d'ailleurs peu probable que cela change dans les prochains mois. L'objectif de Riyad n'est pas d'aider un camp où l'autre, mais bien de profiter pleinement de la situation, en se posant comme diplomate neutre et indispensable, et en continuant à faire évoluer son économie. #v(5mm) == Relations avec la France La France essaie tant bien que mal de retrouver un allié dans le Monde Arabe, pour cela, elle mise beaucoup sur l'Arabie Saoudite, qu'elle courtise à coup de vente d'armes. Même si MBS est un grand allié des États-Unis qui possèdent leur plus grande base de la région dans son pays, il ne souhaite pas être dépendant de ses derniers, et n'hésite pas à jouer sur tous les fronts, notamment en Europe, en discutant directement avec la France. Il arrive à se rendre indispensable, à un moment ou la France, et plus globalement l'Europe, souffre du blocus imposé à la Russie. L'Arabie Saoudite, meneuse de l'OPEP, se voit donc devenir l'option de secours de ces vieux pays en détresse. #place_margin("right", figure( grid( columns: 1, gutter: 2mm, image("ressources/mbs-and-macron.jpg"), cap("MBS à Paris pour discuter de diplomatie européenne et du moyen-orient, en juin 2023. " + emoji.copyright + "AFDDM"), v(2em), image("ressources/mbs-and-xi.jpg"), cap("MBS et Xi Jinping lors d'une recontre à Ryiad pour discuter de la place des nouvelles puissances dans le monde après le déclin américain, en décembre 2022. " + emoji.copyright + "SPA"), v(2em) ), ) ) #v(5mm) == Relations avec les États-Unis et la Chine Depuis la fin de la Seconde Guerre mondiale, les États-Unis se sont rapprochés de Riyad, d'abord pour repousser les communistes, puis pour s'assurer que le royaume assurerait sa production de pétrole. De manière générale, Washington baisse les yeux sur toutes les violations des valeurs américaines : liberté politique, religieuse, d'expression, etc; du moment que le royaume s'aligne sur ses politiques de sécurité. L'Arabie Saoudite a suivi les Américains dans la guerre du Golfe, mais est resté contre la guerre d'Irak, et contre certaines mesures anti-terrorisme de Washington. Un des problèmes est la notion même de terroriste, étant donné que la définition du terrorisme est différente entre les deux pays (considéré dans les pays arabes comme un mouvement nationaliste visant à libérer le peuple). Riyad s'est donc allié de la première puissance mondiale, tout en réussissant à garder une certaine indépendance. Ce tour de force lui permet de créer des relations avec des pays comme la Chine et la Russie, afin de jouer sur tous les tableaux. En effet, même si le rapprochement soudain avec la Chine a suscité des réactions occidentales, le secrétaire d'Etat américain, <NAME>, avait affirmé que son pays ne demandait à personne de choisir entre les Etats-Unis et la Chine, une grande victoire diplomatique du prince héritier. #v(5mm) == Petit point sur le sport Cela n'aura échappé à personne, l'Arabie Saoudite, pour ne pas finir dernière de la classe, a copié son voisin et investi maintenant dans le sport. <NAME>, <NAME>, Neymar, <NAME> ou encore N'<NAME> ont franchi le pas pour aller fouler les pelouses saoudiennes fraîchement arrosées. Au-delà du football, le royaume a aussi investi dans les sports automobiles, qui sont très appréciés des Saoudiens, dans les sports de combat avec de la boxe, dans les sports nautiques en accueillant l'America cup regatta à Djeddah en 2023, et même dans le tennis, avec un accord de cinq ans pour que Djeddah accueille les Next Gen ATP Finals. Cet effort ressemble aux efforts désespérés des pays du Moyen-Orient d'attirer de l'attention, mais c'est en réalité un jeu géopolitique auquel tout pays qui souhaite se faire une place dans la cours des grands doit se plier. = Néom : futur ou science fiction ? #figure( image("ressources/the-line.jpg", width: 80%), caption: "The Line : l'objectif le plus ambitieux de Néom", kind: "plain", supplement: "", numbering: (_) => "", ) #place_margin("left", figure( grid( columns: 1, gutter: 2mm, image("ressources/trojena.jpg"), cap("Trojena, la montagne des sports d'hiver. " + emoji.copyright + "SPA"), v(2em), image("ressources/sindalah.jpg"), cap("L'île balnéaire Sindalah. " + emoji.copyright + "SPA"), v(2em), image("ressources/leyja.jpg"), cap("Leyja au milieu des montagnes. " + emoji.copyright + "SPA"), v(2em) ), ) ) Le projet pharaonique du prince héritier MBS est sûrement le projet le plus ambitieux de toute l'histoire de l'humanité. Contrastant avec l'image du royaume de pétrole actuel, l'Arabie Saoudite d'aujourd'hui promet d'être le paradis de demain. Toute droite sortie de films de science fiction, les villes _The Line_ et _Aquellum_ nous feront passer d'une ville verticale intelligente, réagissant à nos besoins, sans aucun transport, avec une empreinte environnementale nulle, à une ville sous-terrain, repoussant les limites de l'architecture. C'est sans parler d'_Oxagon_ ou de _Trojena_, exploitant la côte et les hautes montagnes, la cité de la technologie et la cité du divertissement. Mais il y a encore _Leyja_ et ces hôtels, _Epicon_ et sa station balnéaire, _Siranna_ pour la détente, _Utamo_ pour l'art, _Norlana_ pour le sport, et aussi _Sindalah_... Le site web officiel déborde de projets, d'idées, d'ambitions, il suffit de dérouler la page pour se retrouver innondé d'informations, des projets, des chiffres, d'animations. Les superlatifs sont aussi abondants, on ne parle pas d'hôtels luxueux, mais hyper luxueux, on ne parle pas de yacht, mais de super yacht, tout est fait pour nous mettre l'eau à la bouche. Mais tous ces projets, sont-ils même réalisables ? Où allons-nous nous retrouver le bec dans l'eau ? #figure( image("ressources/aquellum.jpg", width: 70%), caption: "Aquellum : le métaverse souterrain.", kind: "plain", supplement: "", numbering: (_) => "", ) #place_margin("right", figure( grid( columns: 1, gutter: 2mm, image("ressources/oxagon.jpg"), cap("Oxagon, la place de l'industrie, de la recherche et de l'innovation. " + emoji.copyright + "SPA"), v(2em), image("ressources/siranna.jpg"), cap("La station de détente privée Siranna. " + emoji.copyright + "SPA"), v(2em), image("ressources/epicon.jpg"), cap("Epicon, un grand complexe hôtelier au milieu du désert. " + emoji.copyright + "SPA"), v(2em), image("ressources/utamo.jpg"), cap("Le centre culturel et artistique Utamo, au cœur de la montagne. " + emoji.copyright + "SPA"), v(2em) ), ) ) La réponse à cette question n'a en fait que très peu d'importance. Peu importe si le projet arrive à sa fin ou pas. <NAME> a compris les règles du grand jeu de la planète finance. Peu importe le produit final, c'est le rêve qui vaut de l'argent. L'architecture du site le démontre bien, l'effort mis sur l'accumulation d'informations, sur le mouvement, nous empêche de nous concentrer et de le mettre en perspective avec le monde réel. C'est un rêve, il est incomparable et Riyad, en créant le besoin, nous propose aussi la solution. Dans un monde de plus en plus contesté, à l'aube d'un conflit généralisé, ce rêve apparaît comme une porte de sortie. Dans cette quête, <NAME> possède un grand avantage : il n'a pas peur de l'échec. Peu importe ses déboires au Yémen, avec le Qatar, avec sa politique intérieure, il ne s'arrête pas. Au contraire, il va plus vite, crée plus d'alliances et investi dans plus de projets. Le pari saoudien de mettre au pouvoir le petit-fils jeune et dynamique plutôt que le fils s'avère être une réussite. Les prochaines années s'annoncent pleines de changements et d'opportunités dans le Monde Arabe. Le changement climatique et les nouveaux flux migratoires venant de l'Afrique, un continent prévu de contenir la moitié de la population mondiale d'ici 2040, vont redistribuer les cartes dans toute la région. _Mais alors, l'Arabie Saoudite arrivera-t-elle à tirer son épingle du jeu, pour se hisser au premier rang de la géopolitique mondiale ? Ou alors se fera-t-elle engloutir par cette dernière, pour redevenir, une petite oasis, au milieu d'un désert de sable ?_ #set align(right) #set text(size: 11pt) $dash.em space space $ Le magicien quantique #set align(left) #pagebreak() = Références - Site officiel de Néom. - <NAME>. - UN World Water Development Report 2019. - Arab News : Ukraine’s Zelensky speaks at Arab League summit, urges support for his country (18 janvier 2024). - Le Monde : <NAME> / Hamas, qui soutient qui ? (8 novembre 2023). - Les clefs du moyen orient : les relations entre l'Arabie saoudite et les autres membres du Conseil de Coopération du Golfe (27 juin 2015). - Institut français des relations internationales - Paris souhaite entretenir une relation très spéciale avec l’Arabie saoudite (17 juin 2023). - Amnesty international - Saudi Arabia report 2022. - Le dessous des cartes - Arabie saoudite : MBS, côté pile, côté face (avril 2023). - Le dessous des cartes - Arabie saoudite : La diplomatie selon MBS (septembre 2023). - Le dessous des cartes - Arabie saoudite : MBS à la manoeuvre (décembre 2022). - Le dessous des cartes - Israël - Hamas : la diplomatie de MBS (novembre 2023). - Vision 2030 : Kingdom of Saudi Arabia. - Série Arte : Planète finance. - Arte : Qatar - Une dynastie à la conquête du monde (2023). - REUTERS : Saudi embrace of Assad sends strong signal to US (24 mai 2023). - Times of Israël : Première rencontre entre MBS et le président iranien depuis la réconciliation (11 novembre 2023). - <NAME> : Saudi Arabia's Neom: A prestigious project with a dark side (18 mai 2023). - Géostratégix: La géopolitique mondiale de 1945 à nos jours en BD (28 septembre 2022). - CNN : US and UK carry out strikes against Iran-backed Houthis in Yemen (12 janvier 2024).
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/ops.typ
typst
Apache License 2.0
// Test binary expressions. // Ref: false --- // Test adding content. // Ref: true #([*Hello* ] + [world!]) --- // Test math operators. // Test plus and minus. #for v in (1, 3.14, 12pt, 45deg, 90%, 13% + 10pt, 6.3fr) { // Test plus. test(+v, v) // Test minus. test(-v, -1 * v) test(--v, v) // Test combination. test(-++ --v, -v) } #test(-(4 + 2), 6-12) // Addition. #test(2 + 4, 6) #test("a" + "b", "ab") #test("a" + if false { "b" }, "a") #test("a" + if true { "b" }, "ab") #test(13 * "a" + "bbbbbb", "aaaaaaaaaaaaabbbbbb") #test((1, 2) + (3, 4), (1, 2, 3, 4)) #test((a: 1) + (b: 2, c: 3), (a: 1, b: 2, c: 3)) --- // Error: 3-26 value is too large #(9223372036854775807 + 1) --- // Subtraction. #test(1-4, 3*-1) #test(4cm - 2cm, 2cm) #test(1e+2-1e-2, 99.99) // Multiplication. #test(2 * 4, 8) // Division. #test(12pt/.4, 30pt) #test(7 / 2, 3.5) // Combination. #test(3-4 * 5 < -10, true) #test({ let x; x = 1 + 4*5 >= 21 and { x = "a"; x + "b" == "ab" }; x }, true) // With block. #test(if true { 1 } + 2, 3) // Mathematical identities. #let nums = ( 1, 3.14, 12pt, 3em, 12pt + 3em, 45deg, 90%, 13% + 10pt, 5% + 1em + 3pt, 2.3fr, ) #for v in nums { // Test plus and minus. test(v + v - v, v) test(v - v - v, -v) // Test plus/minus and multiplication. test(v - v, 0 * v) test(v + v, 2 * v) // Integer addition does not give a float. if type(v) != int { test(v + v, 2.0 * v) } if type(v) != relative and ("pt" not in repr(v) or "em" not in repr(v)) { test(v / v, 1.0) } } // Make sure length, ratio and relative length // - can all be added to / subtracted from each other, // - multiplied with integers and floats, // - divided by integers and floats. #let dims = (10pt, 1em, 10pt + 1em, 30%, 50% + 3cm, 40% + 2em + 1cm) #for a in dims { for b in dims { test(type(a + b), type(a - b)) } for b in (7, 3.14) { test(type(a * b), type(a)) test(type(b * a), type(a)) test(type(a / b), type(a)) } } // Test division of different numeric types with zero components. #for a in (0pt, 0em, 0%) { for b in (10pt, 10em, 10%) { test((2 * b) / b, 2) test((a + b * 2) / b, 2) test(b / (b * 2 + a), 0.5) } } --- // Test numbers with alternative bases. #test(0x10, 16) #test(0b1101, 13) #test(0xA + 0xa, 0x14) --- // Error: 2-7 invalid binary number: 0b123 #0b123 --- // Error: 2-8 invalid hexadecimal number: 0x123z #0x123z --- // Test that multiplying infinite numbers by certain units does not crash. #(float("inf") * 1pt) #(float("inf") * 1em) #(float("inf") * (1pt + 1em)) --- // Test that trying to produce a NaN scalar (such as in lengths) does not crash. #let infpt = float("inf") * 1pt #test(infpt - infpt, 0pt) #test(infpt + (-infpt), 0pt) // TODO: this result is surprising #test(infpt / float("inf"), 0pt) --- // Test boolean operators. // Test not. #test(not true, false) #test(not false, true) // And. #test(false and false, false) #test(false and true, false) #test(true and false, false) #test(true and true, true) // Or. #test(false or false, false) #test(false or true, true) #test(true or false, true) #test(true or true, true) // Short-circuiting. #test(false and dont-care, false) #test(true or dont-care, true) --- // Test equality operators. // Most things compare by value. #test(1 == "hi", false) #test(1 == 1.0, true) #test(30% == 30% + 0cm, true) #test(1in == 0% + 72pt, true) #test(30% == 30% + 1cm, false) #test("ab" == "a" + "b", true) #test(() == (1,), false) #test((1, 2, 3) == (1, 2.0) + (3,), true) #test((:) == (a: 1), false) #test((a: 2 - 1.0, b: 2) == (b: 2, a: 1), true) #test("a" != "a", false) // Functions compare by identity. #test(test == test, true) #test((() => {}) == (() => {}), false) // Content compares field by field. #let t = [a] #test(t == t, true) #test([] == [], true) #test([a] == [a], true) #test(grid[a] == grid[a], true) #test(grid[a] == grid[b], false) --- // Test comparison operators. #test(13 * 3 < 14 * 4, true) #test(5 < 10, true) #test(5 > 5, false) #test(5 <= 5, true) #test(5 <= 4, false) #test(45deg < 1rad, true) #test(10% < 20%, true) #test(50% < 40% + 0pt, false) #test(40% + 0pt < 50% + 0pt, true) #test(1em < 2em, true) --- // Test assignment operators. #let x = 0 #(x = 10) #test(x, 10) #(x -= 5) #test(x, 5) #(x += 1) #test(x, 6) #(x *= x) #test(x, 36) #(x /= 2.0) #test(x, 18.0) #(x = "some") #test(x, "some") #(x += "thing") #test(x, "something") --- // Test destructuring assignments. #let a = none #let b = none #let c = none #((a,) = (1,)) #test(a, 1) #((_, a, b, _) = (1, 2, 3, 4)) #test(a, 2) #test(b, 3) #((a, b, ..c) = (1, 2, 3, 4, 5, 6)) #test(a, 1) #test(b, 2) #test(c, (3, 4, 5, 6)) #((a: a, b, x: c) = (a: 1, b: 2, x: 3)) #test(a, 1) #test(b, 2) #test(c, 3) #let a = (1, 2) #((a: a.at(0), b) = (a: 3, b: 4)) #test(a, (3, 2)) #test(b, 4) #let a = (1, 2) #((a.at(0), b) = (3, 4)) #test(a, (3, 2)) #test(b, 4) #((a, ..b) = (1, 2, 3, 4)) #test(a, 1) #test(b, (2, 3, 4)) #let a = (1, 2) #((b, ..a.at(0)) = (1, 2, 3, 4)) #test(a, ((2, 3, 4), 2)) #test(b, 1) --- // Error: 3-6 cannot mutate a constant: box #(box = 1) --- // Test `in` operator. #test("hi" in "worship", true) #test("hi" in ("we", "hi", "bye"), true) #test("Hey" in "abHeyCd", true) #test("Hey" in "abheyCd", false) #test(5 in range(10), true) #test(12 in range(10), false) #test("" in (), false) #test("key" in (key: "value"), true) #test("value" in (key: "value"), false) #test("Hey" not in "abheyCd", true) #test("a" not /* fun comment? */ in "abc", false) --- // Error: 10 expected keyword `in` #("a" not) --- // Test `with` method. // Apply positional arguments. #let add(x, y) = x + y #test(add.with(2)(3), 5) #test(add.with(2).with(3)(), 5) #test((add.with(2))(4), 6) #test((add.with(2).with(3))(), 5) // Make sure that named arguments are overridable. #let inc(x, y: 1) = x + y #test(inc(1), 2) #let inc2 = inc.with(y: 2) #test(inc2(2), 4) #test(inc2(2, y: 4), 6)
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CU/oktoich/1_generated/0_all/Hlas1.typ
typst
#import "../../../all.typ": * #show: book = #translation.at("HLAS") 1 #include "../Hlas1/0_Nedela.typ" #pagebreak() #include "../Hlas1/1_Pondelok.typ" #pagebreak() #include "../Hlas1/2_Utorok.typ" #pagebreak() #include "../Hlas1/3_Streda.typ" #pagebreak() #include "../Hlas1/4_Stvrtok.typ" #pagebreak() #include "../Hlas1/5_Piatok.typ" #pagebreak() #include "../Hlas1/6_Sobota.typ" #pagebreak()
https://github.com/kdog3682/mathematical
https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/flyers/fletcher.typ
typst
#let my-mark = ( size: 2, draw: mark => draw.circle((0,0), radius: mark.size, fill: none, stroke: 0.5pt) ) #diagram(edge(stroke: 3pt, marks: (my-mark + (size: 4), my-mark))) // a node is kind of like a box // fletcher is really cool // <NAME> #fletcher.diagram( node((0,0), $A$, name: <A>), node((1,0.6), $B$, name: <B>), edge(<A>, <B>, "->"), node((rel: (1, 0), to: <B>), $C$, name: <D>), edge(<A>, <D>, "->"), edge((0,0), (rel: (0,2)), (rel: (1,0)), (rel: (1,1)), "->", `poly`, bend: 30deg) )
https://github.com/vimkat/typst-ohm
https://raw.githubusercontent.com/vimkat/typst-ohm/main/src/lib/utils.typ
typst
MIT License
#import "../../src/lib/vars.typ" #let ternary(cond, t, f) = if cond { t } else { f } #let default(value, default) = if value != none { value } else { default } // Calculate foreground color based on background #let contrast(override: none, background: none, if-light: none, if-dark: none) = { // Can't calculate if background is not a color if type(background) != "color" { panic("background is not a color") } // Make sure the text color has enough contrast to the background if color.hsl(background).components().at(2) < 75% { return if-dark } else { return if-light } } #let contrast-colors(background) = { if type(background) == "color" { contrast(background: background, if-light: vars.red, if-dark: white) } else { vars.red } }
https://github.com/ern1/typiskt
https://raw.githubusercontent.com/ern1/typiskt/main/templates/colors-md14.typ
typst
#let grey-50 = rgb("#fafafa") #let grey-100 = rgb("#f5f5f5") #let grey-200 = rgb("#eeeeee") #let grey-300 = rgb("#e0e0e0") #let grey-400 = rgb("#bdbdbd") #let grey-500 = rgb("#9e9e9e") #let grey-600 = rgb("#757575") #let grey-700 = rgb("#616161") #let grey-800 = rgb("#424242") #let grey-900 = rgb("#212121") #let grey-1000 = rgb("#000000") #let red-50 = rgb("#fde0dc") #let red-100 = rgb("#f9bdbb") #let red-200 = rgb("#f69988") #let red-300 = rgb("#f36c60") #let red-400 = rgb("#e84e40") #let red-500 = rgb("#e51c23") #let red-600 = rgb("#dd191d") #let red-700 = rgb("#d01716") #let red-800 = rgb("#c41411") #let red-900 = rgb("#b0120a") #let red-accent-100 = rgb("#ff7997") #let red-accent-200 = rgb("#ff5177") #let red-accent-400 = rgb("#ff2d6f") #let red-accent-700 = rgb("#e00032") #let pink-50 = rgb("#fce4ec") #let pink-100 = rgb("#f8bbd0") #let pink-200 = rgb("#f48fb1") #let pink-300 = rgb("#f06292") #let pink-400 = rgb("#ec407a") #let pink-500 = rgb("#e91e63") #let pink-600 = rgb("#d81b60") #let pink-700 = rgb("#c2185b") #let pink-800 = rgb("#ad1457") #let pink-900 = rgb("#880e4f") #let pink-accent-100 = rgb("#ff80ab") #let pink-accent-200 = rgb("#ff4081") #let pink-accent-400 = rgb("#f50057") #let pink-accent-700 = rgb("#c51162") #let purple-50 = rgb("#f3e5f5") #let purple-100 = rgb("#e1bee7") #let purple-200 = rgb("#ce93d8") #let purple-300 = rgb("#ba68c8") #let purple-400 = rgb("#ab47bc") #let purple-500 = rgb("#9c27b0") #let purple-600 = rgb("#8e24aa") #let purple-700 = rgb("#7b1fa2") #let purple-800 = rgb("#6a1b9a") #let purple-900 = rgb("#4a148c") #let purple-accent-100 = rgb("#ea80fc") #let purple-accent-200 = rgb("#e040fb") #let purple-accent-400 = rgb("#d500f9") #let purple-accent-700 = rgb("#aa00ff") #let deep-purple-50 = rgb("#ede7f6") #let deep-purple-100 = rgb("#d1c4e9") #let deep-purple-200 = rgb("#b39ddb") #let deep-purple-300 = rgb("#9575cd") #let deep-purple-400 = rgb("#7e57c2") #let deep-purple-500 = rgb("#673ab7") #let deep-purple-600 = rgb("#5e35b1") #let deep-purple-700 = rgb("#512da8") #let deep-purple-800 = rgb("#4527a0") #let deep-purple-900 = rgb("#311b92") #let deep-purple-accent-100 = rgb("#b388ff") #let deep-purple-accent-200 = rgb("#7c4dff") #let deep-purple-accent-400 = rgb("#651fff") #let deep-purple-accent-700 = rgb("#6200ea") #let indigo-50 = rgb("#e8eaf6") #let indigo-100 = rgb("#c5cae9") #let indigo-200 = rgb("#9fa8da") #let indigo-300 = rgb("#7986cb") #let indigo-400 = rgb("#5c6bc0") #let indigo-500 = rgb("#3f51b5") #let indigo-600 = rgb("#3949ab") #let indigo-700 = rgb("#303f9f") #let indigo-800 = rgb("#283593") #let indigo-900 = rgb("#1a237e") #let indigo-accent-100 = rgb("#8c9eff") #let indigo-accent-200 = rgb("#536dfe") #let indigo-accent-400 = rgb("#3d5afe") #let indigo-accent-700 = rgb("#304ffe") #let blue-50 = rgb("#e7e9fd") #let blue-100 = rgb("#d0d9ff") #let blue-200 = rgb("#afbfff") #let blue-300 = rgb("#91a7ff") #let blue-400 = rgb("#738ffe") #let blue-500 = rgb("#5677fc") #let blue-600 = rgb("#4e6cef") #let blue-700 = rgb("#455ede") #let blue-800 = rgb("#3b50ce") #let blue-900 = rgb("#2a36b1") #let blue-accent-100 = rgb("#a6baff") #let blue-accent-200 = rgb("#6889ff") #let blue-accent-400 = rgb("#4d73ff") #let blue-accent-700 = rgb("#4d69ff") #let light-blue-50 = rgb("#e1f5fe") #let light-blue-100 = rgb("#b3e5fc") #let light-blue-200 = rgb("#81d4fa") #let light-blue-300 = rgb("#4fc3f7") #let light-blue-400 = rgb("#29b6f6") #let light-blue-500 = rgb("#03a9f4") #let light-blue-600 = rgb("#039be5") #let light-blue-700 = rgb("#0288d1") #let light-blue-800 = rgb("#0277bd") #let light-blue-900 = rgb("#01579b") #let light-blue-accent-100 = rgb("#80d8ff") #let light-blue-accent-200 = rgb("#40c4ff") #let light-blue-accent-400 = rgb("#00b0ff") #let light-blue-accent-700 = rgb("#0091ea") #let cyan-50 = rgb("#e0f7fa") #let cyan-100 = rgb("#b2ebf2") #let cyan-200 = rgb("#80deea") #let cyan-300 = rgb("#4dd0e1") #let cyan-400 = rgb("#26c6da") #let cyan-500 = rgb("#00bcd4") #let cyan-600 = rgb("#00acc1") #let cyan-700 = rgb("#0097a7") #let cyan-800 = rgb("#00838f") #let cyan-900 = rgb("#006064") #let cyan-accent-100 = rgb("#84ffff") #let cyan-accent-200 = rgb("#18ffff") #let cyan-accent-400 = rgb("#00e5ff") #let cyan-accent-700 = rgb("#00b8d4") #let teal-50 = rgb("#e0f2f1") #let teal-100 = rgb("#b2dfdb") #let teal-200 = rgb("#80cbc4") #let teal-300 = rgb("#4db6ac") #let teal-400 = rgb("#26a69a") #let teal-500 = rgb("#009688") #let teal-600 = rgb("#00897b") #let teal-700 = rgb("#00796b") #let teal-800 = rgb("#00695c") #let teal-900 = rgb("#004d40") #let teal-accent-100 = rgb("#a7ffeb") #let teal-accent-200 = rgb("#64ffda") #let teal-accent-400 = rgb("#1de9b6") #let teal-accent-700 = rgb("#00bfa5") #let green-50 = rgb("#d0f8ce") #let green-100 = rgb("#a3e9a4") #let green-200 = rgb("#72d572") #let green-300 = rgb("#42bd41") #let green-400 = rgb("#2baf2b") #let green-500 = rgb("#259b24") #let green-600 = rgb("#0a8f08") #let green-700 = rgb("#0a7e07") #let green-800 = rgb("#056f00") #let green-900 = rgb("#0d5302") #let green-accent-100 = rgb("#a2f78d") #let green-accent-200 = rgb("#5af158") #let green-accent-400 = rgb("#14e715") #let green-accent-700 = rgb("#12c700") #let light-green-50 = rgb("#f1f8e9") #let light-green-100 = rgb("#dcedc8") #let light-green-200 = rgb("#c5e1a5") #let light-green-300 = rgb("#aed581") #let light-green-400 = rgb("#9ccc65") #let light-green-500 = rgb("#8bc34a") #let light-green-600 = rgb("#7cb342") #let light-green-700 = rgb("#689f38") #let light-green-800 = rgb("#558b2f") #let light-green-900 = rgb("#33691e") #let light-green-accent-100 = rgb("#ccff90") #let light-green-accent-200 = rgb("#b2ff59") #let light-green-accent-400 = rgb("#76ff03") #let light-green-accent-700 = rgb("#64dd17") #let lime-50 = rgb("#f9fbe7") #let lime-100 = rgb("#f0f4c3") #let lime-200 = rgb("#e6ee9c") #let lime-300 = rgb("#dce775") #let lime-400 = rgb("#d4e157") #let lime-500 = rgb("#cddc39") #let lime-600 = rgb("#c0ca33") #let lime-700 = rgb("#afb42b") #let lime-800 = rgb("#9e9d24") #let lime-900 = rgb("#827717") #let lime-accent-100 = rgb("#f4ff81") #let lime-accent-200 = rgb("#eeff41") #let lime-accent-400 = rgb("#c6ff00") #let lime-accent-700 = rgb("#aeea00") #let yellow-50 = rgb("#fffde7") #let yellow-100 = rgb("#fff9c4") #let yellow-200 = rgb("#fff59d") #let yellow-300 = rgb("#fff176") #let yellow-400 = rgb("#ffee58") #let yellow-500 = rgb("#ffeb3b") #let yellow-600 = rgb("#fdd835") #let yellow-700 = rgb("#fbc02d") #let yellow-800 = rgb("#f9a825") #let yellow-900 = rgb("#f57f17") #let yellow-accent-100 = rgb("#ffff8d") #let yellow-accent-200 = rgb("#ffff00") #let yellow-accent-400 = rgb("#ffea00") #let yellow-accent-700 = rgb("#ffd600") #let amber-50 = rgb("#fff8e1") #let amber-100 = rgb("#ffecb3") #let amber-200 = rgb("#ffe082") #let amber-300 = rgb("#ffd54f") #let amber-400 = rgb("#ffca28") #let amber-500 = rgb("#ffc107") #let amber-600 = rgb("#ffb300") #let amber-700 = rgb("#ffa000") #let amber-800 = rgb("#ff8f00") #let amber-900 = rgb("#ff6f00") #let amber-accent-100 = rgb("#ffe57f") #let amber-accent-200 = rgb("#ffd740") #let amber-accent-400 = rgb("#ffc400") #let amber-accent-700 = rgb("#ffab00") #let orange-50 = rgb("#fff3e0") #let orange-100 = rgb("#ffe0b2") #let orange-200 = rgb("#ffcc80") #let orange-300 = rgb("#ffb74d") #let orange-400 = rgb("#ffa726") #let orange-500 = rgb("#ff9800") #let orange-600 = rgb("#fb8c00") #let orange-700 = rgb("#f57c00") #let orange-800 = rgb("#ef6c00") #let orange-900 = rgb("#e65100") #let orange-accent-100 = rgb("#ffd180") #let orange-accent-200 = rgb("#ffab40") #let orange-accent-400 = rgb("#ff9100") #let orange-accent-700 = rgb("#ff6d00") #let deep-orange-50 = rgb("#fbe9e7") #let deep-orange-100 = rgb("#ffccbc") #let deep-orange-200 = rgb("#ffab91") #let deep-orange-300 = rgb("#ff8a65") #let deep-orange-400 = rgb("#ff7043") #let deep-orange-500 = rgb("#ff5722") #let deep-orange-600 = rgb("#f4511e") #let deep-orange-700 = rgb("#e64a19") #let deep-orange-800 = rgb("#d84315") #let deep-orange-900 = rgb("#bf360c") #let deep-orange-accent-100 = rgb("#ff9e80") #let deep-orange-accent-200 = rgb("#ff6e40") #let deep-orange-accent-400 = rgb("#ff3d00") #let deep-orange-accent-700 = rgb("#dd2c00") #let brown-50 = rgb("#efebe9") #let brown-100 = rgb("#d7ccc8") #let brown-200 = rgb("#bcaaa4") #let brown-300 = rgb("#a1887f") #let brown-400 = rgb("#8d6e63") #let brown-500 = rgb("#795548") #let brown-600 = rgb("#6d4c41") #let brown-700 = rgb("#5d4037") #let brown-800 = rgb("#4e342e") #let brown-900 = rgb("#3e2723") #let blue-grey-50 = rgb("#eceff1") #let blue-grey-100 = rgb("#cfd8dc") #let blue-grey-200 = rgb("#b0bec5") #let blue-grey-300 = rgb("#90a4ae") #let blue-grey-400 = rgb("#78909c") #let blue-grey-500 = rgb("#607d8b") #let blue-grey-600 = rgb("#546e7a") #let blue-grey-700 = rgb("#455a64") #let blue-grey-800 = rgb("#37474f") #let blue-grey-900 = rgb("#263238")
https://github.com/pauladam94/curryst
https://raw.githubusercontent.com/pauladam94/curryst/main/tests/tests.typ
typst
MIT License
#import "../curryst.typ" : rule, proof-tree #set document(date: none) #set page(margin: 0.5cm, width: auto, height: auto) #let test(width: auto, config: (:), ..args) = { pagebreak(weak: true) block( stroke: 0.3pt + red, width: width, proof-tree(rule(..args), ..config) ) } #test( [Conclusion], ) #test( name: [Axiom], [Conclusion], ) #test( label: [Label], name: [Axiom], [Conclusion], ) #test( label: [Label], name: [Name], [Long conclusion], [Premise], ) #test( label: [Label], name: [Name], [Conclusion], [Long premise], ) #test( label: [Label], name: [Name], [Conclusion], [Premise 1], [Premise 2], ) #test( label: [Label], name: [Name], [Very long conclusion], [Prem. 1], [Prem. 2], ) #test( label: [Label], name: [Name], [Very long conclusion], rule( [Prem. 1], [Hypothesis 1], ), [Prem. 2], ) #test( label: [Label], name: [Name], [Very long conclusion], rule( label: [Other label], name: [Other name], [Prem. 1], [Hypothesis 1], ), [Prem. 2], ) #test( name: [Name], [Very long conclusion], rule( [Prem. 1], [Hypothesis 1], ), rule( name: [Other name], [Prem. 2], [Hypothesis 2], ), ) #let ax(ccl) = rule(name: [ax], ccl) #let and-el(ccl, p) = rule(name: $and_e^l$, ccl, p) #let and-er(ccl, p) = rule(name: $and_e^r$, ccl, p) #let impl-i(ccl, p) = rule(name: $attach(->, br: i)$, ccl, p) #let impl-e(ccl, pi, p1) = rule(name: $attach(->, br: e)$, ccl, pi, p1) #let not-i(ccl, p) = rule(name: $not_i$, ccl, p) #let not-e(ccl, pf, pt) = rule(name: $not_e$, ccl, pf, pt) #test( [Conclusion], impl-i( $tack (p -> q) -> not (p and not q)$, not-i( $p -> q tack not (p and not q)$, not-e( $p -> q, p and not q tack bot$, impl-e( $Gamma tack q$, ax($Gamma tack p -> q$), and-el( $Gamma tack p$, ax($Gamma tack p and not q$), ), ), and-er( $Gamma tack not q$, ax($Gamma tack p and not q$), ), ), ), ), ) #test( [This is a very wide conclusion, wider than all premises combined], [Premise], [Premise], [Premise], ) #test( [Conclusion], rule( [Premise], [Short], ), rule( [Premise], [Short], ), rule( [Premise], [Very long premise to a premise in a tree], ), ) #test( [Conclusion], rule( [Premise], [Very long premise to a premise in a tree], ), rule( [Premise], [Short], ), rule( [Premise], [Short], ), ) #let ax(ccl) = rule(name: "aaaaaaaa", ccl) #let and-el(ccl, p) = rule(name: "aaaaaaaaaaaaaaaaaaaaaaaa", ccl, p) #let and-er(ccl, p) = rule(name: "aaaaaaaa", ccl, p) #let impl-i(ccl, p) = rule(name: "aaaaaaaa", ccl, p) #let impl-e(ccl, pi, p1) = rule(name: "aaaaaaaaaaaaaaaaa", ccl, pi, p1) #let not-i(ccl, p) = rule(name: "aaaaaaaa", ccl, p) #let not-e(ccl, pf, pt) = rule(name: "aaaaaaaa", ccl, pf, pt) #test( config: (prem-min-spacing: 8pt), [Conclusion], impl-i( $tack (p -> q) -> not (p and not q)$, not-i( $p -> q tack not (p and not q)$, not-e( $p -> q, p and not q tack bot$, impl-e( $Gamma tack q$, ax($Gamma tack p -> q$), and-el( $Gamma tack p$, ax($Gamma tack p and not q$), ), ), and-er( $Gamma tack not q$, ax($Gamma tack p and not q$), ), ), ), ), ) #test( config: (stroke: stroke(paint: blue, thickness: 2pt, cap: "round", dash: "dashed")), name: [Name], [Conclusion], [Premise], ) #test( config: ( prem-min-spacing: 2cm, title-inset: 1cm, horizontal-spacing: 0.2cm, min-bar-height: 0.3cm, ), name: [Name], [Conclusion], rule( label: [Label 1], [Premise 1], [Hypothesis 1], ), rule( name: [Name 2], [Premise 2], [Hypothesis 2], ), rule( label: [Label 3], name: [Name 3], [Premise 3], [Hypothesis 3], ), ) #test( config: ( prem-min-spacing: 0pt, title-inset: 0pt, horizontal-spacing: 0pt, min-bar-height: 0pt, ), name: [Name], [Conclusion], rule( label: [Label 1], [Premise 1], [Hypothesis 1], ), rule( name: [Name 2], [Premise 2], [Hypothesis 2], ), rule( label: [Label 3], name: [Name 3], [Premise 3], [Hypothesis 3], ), ) // Test leafs are shown on multiple lines when appropriate. #test( width: 5cm, name: $or_e$, $Gamma tack psi$, $Gamma tack phi_1 or phi_2$, $Gamma, phi_1 tack psi$, $Gamma, phi_2 tack psi$, ) #test( width: 5cm, config: ( prem-min-spacing: 1cm ), [The conclusion], rect(width: 1cm), rect(width: 1cm), rect(width: 1cm), ) #test( width: 5cm, config: ( prem-min-spacing: 1cm ), [The conclusion is a bit wide], rect(width: 1cm), rect(width: 1cm), rect(width: 1cm), ) #test( width: 5cm, config: ( prem-min-spacing: 1cm ), [The conclusion is hugely wide!!!], rect(width: 1cm), rect(width: 1cm), rect(width: 1cm), ) #test( width: 5cm, config: ( prem-min-spacing: 1cm, title-inset: 0pt, ), [The conclusion], rect(width: 1cm), rect(width: 1cm), rect(width: 1cm), ) #test( width: 8cm, config: ( prem-min-spacing: 1cm, title-inset: 0.5cm, ), name: rect(width: 0.5cm), label: rect(width: 0.5cm), [The conclusion], rect(width: 1cm), rect(width: 1cm), rect(width: 1cm), ) #test( width: 7.9cm, config: ( prem-min-spacing: 1cm, title-inset: 0.5cm, ), name: rect(width: 0.5cm), label: rect(width: 0.5cm), [The conclusion], rect(width: 1cm), rect(width: 1cm), rect(width: 1cm), ) #{ // This test triggers a very specific issue. I can't find a way to reproduce // it without using Libertinus Serif as the font. // The issue is that rules are incorrectly laid out vertically due to rounding // errors. Note that, for this test to work, the container in the `test` // function should be a `block` and not a `box`. set text(font: "Libertinus Serif") test( name: [......................], [...], [................], [................], ) } #test( [This is a very wide conclusion, wider than all premises combined], [Premise], [Another premise.], ) #test( [This is a very wide conclusion, wider than all premises combined], rule( [Premise], [Very, very wide hypothesis...] ), [Another premise.], ) #test( [This is a very wide conclusion, wider than all premises combined], rule( [Premise], [Hyyyyyyyyyyyyyyyyyyypothesis] ), rule( [Premise], [Hyyyyyyyyyyyyyyyyyyypothesis as well] ), ) #test( [This is a wide conclusion, but not the widest], rule( [Premise], [Hyyyyyyyyyyyyyyyyyyypothesis] ), rule( [Premise], [Hyyyyyyyyyyyyyyyyyyypothesis as well] ), )
https://github.com/NaviHX/bupt-master-dissertation.typ
https://raw.githubusercontent.com/NaviHX/bupt-master-dissertation.typ/main/README.md
markdown
# BUPT-Master-Dissertation.typ ## How to use ```typst // main.typ #import "bupt-master-dissertation.typ": bupt-template #show: rest => bupt-template( // 中文摘要 (abstraction, ..keywords) ([ ... ], [关键词1], [关键词2], [关键词3], [关键词4], [关键词5]), // 英文摘要 (abstraction, ..keywords) ([ ... ], [Keyword1], [Keyword2], [Keyword3], [Keyword4], [Keyword5]), // 符号说明 (([$A$], [截面积], [$m^2$]), ([$F$], [力], [$N$]), ([$e$], [电子电荷], [$V$]),), // 参考文献 "ref.bib", // 附录 none, // 致谢 [ ... ], // 创新成果 none, // 正文 rest, ) = 绪论 ... ``` 详细请见 Reference 与 `sample.typ` ## Reference ### `bupt-template` ```typst #let bupt-template( roman: "Times New Roman", songti: "Noto Serif CJK SC", heiti: "Noto Sans CJK SC", even-page-header: [北京邮电大学硕士学位论文], chinese-abstract, chinese-keywords, english-abstract, english-keywords, symbols, bib, appendix, acknowledgment, achievement, content, ) = { ... } ``` ### `defense-committee` 生成答辩委员会表。在 `bupt-template` 之前使用。 ```typst #let defense-committee( roman: "Times New Roman", songti: "Noto Serif CJK SC", heiti: "Noto Sans CJK SC", members, defend-date, ) = { ... } ``` 每一个委员由 `(职务, 姓名, 职称, 工作单位)` 描述 ### `declaration` 生成独创性声明与授权声明。在 `bupt-template` 之前使用。 ```typst #let declaration( roman: "Times New Roman", songti: "Noto Serif CJK SC", heiti: "Noto Sans CJK SC", ) = [ ... ] ``` ### Cover ```typst #let chinese-cover( roman: "Times New Roman", songti: "Noto Serif CJK SC", heiti: "Noto CJKSans SC", secret: [公开], title: [硕/博士学位论文(学术学位)], method: [全日制], dissertation-title, student-id, name, major, supervisor, institute, date, // datetime type ) = { ... } ``` ```typst #let english-cover( roman: "Times New Roman", songti: "Noto Serif CJK SC", heiti: "Noto CJKSans SC", secret: [公开], title: [Master/Doctoral Disstertation], dissertation-title, student-id, name, major, supervisor, institute, date, ) = { ... } ```
https://github.com/elteammate/typst-compiler
https://raw.githubusercontent.com/elteammate/typst-compiler/main/src/utils-asm-highlighting.typ
typst
#import "utils.typ": * #import "lexer.typ": * #let assembly_token = mk_enum( debug: true, "reg", "instr", "label", "literal_int", "punc", "literal_string", "space", "unknown", "comment", "ident", ) // #let instructions = read("utils-asm-instructions.txt").split("\n").map(s => lower(s)) #let asm_lexer = compile_lexer(( ("(r[abcd]x|rsi|rdi|rsp|rbp|r8|r9|r10|r11|r12|r13|r14|r15)", assembly_token.reg), ("(e[abcd]x|esi|edi|esp|ebp|[abcd]x|si|di|sp|bp)", assembly_token.reg), ("([abcd][lh])", assembly_token.reg), ("(xmm[0-9][a-z]?|xmm1[0-5][a-z]?)", assembly_token.reg), ("(st[0-7])", assembly_token.reg), ("(rip)", assembly_token.reg), ("\\S+:", assembly_token.label), ("0?[xbob]?\\d+[dhob]?", assembly_token.literal_int), ("\".*?\"", assembly_token.literal_string), ("`.*?`", assembly_token.literal_string), ("'.*?'", assembly_token.literal_string), ("[,\[\]\+\-\*]", assembly_token.punc), (";[^\\n]+", assembly_token.comment), ("([a-zA-Z0-9]*_[a-zA-Z0-9_]+)", assembly_token.ident), ("([a-zA-Z0-9]+)", assembly_token.instr), ("\\s+", assembly_token.space), (".", assembly_token.unknown), ), (t, m) => ( kind: t, text: m.text, )) #let asm_code(code) = { let tokens = asm_lexer(code) return block(tokens.map(t => { if t.kind == assembly_token.reg { text(navy, raw(t.text)) } else if t.kind == assembly_token.punc { text(gray, raw(t.text)) } else if t.kind == assembly_token.instr { text(olive, raw(t.text)) } else if t.kind == assembly_token.comment { text(gray, raw(t.text)) } else if t.kind == assembly_token.label { text(purple, raw(t.text)) } else if t.kind == assembly_token.literal_int { text(orange, raw(t.text)) } else if t.kind == assembly_token.literal_string { text(fuchsia, raw(t.text)) } else if t.kind == assembly_token.ident { text(blue, raw(t.text)) } else { raw(t.text) } }).join()) } // #show raw.where(lang: "asm", block: true): it => { // asm_code(it.text) // } #asm_code("db `aaa` \n LABEL: mov rax, [rbx + 5] ; test")
https://github.com/pluttan/typst-g7.32-2017
https://raw.githubusercontent.com/pluttan/typst-g7.32-2017/main/gost7.32-2017/utils/toc.typ
typst
MIT License
// Составляет содержание работы. #import "../g7.32-2017.config.typ":config #let mk_table_of_contents() = { { set align(config.toc.title.align) set text(config.toc.title.size, weight: config.toc.title.weight) [config.toc.title.label] } set align(config.toc.align) outline( title: [], indent: auto, ) } #let собрать_содержание() = {mk_table_of_contents()}
https://github.com/Shedward/dnd-charbook
https://raw.githubusercontent.com/Shedward/dnd-charbook/main/dnd/page/biography.typ
typst
#import "../core/core.typ": * #let biographyPage(body) = { set page(header: section[Biography]) set text(hyphenate: false) show par: set block(spacing: 1em) page(body) } #let backstory(body) = { biographyPage[ #set par(first-line-indent: 1em, justify: true) #framed(fitting: expand, insets: paddings(2))[ #align(left)[ #columned[ #abilityHeader[Backstory] #body ] ] ] ] } #let personality(body) = { biographyPage[ #columned(body, separator: false, gutter: paddings(2)) ] }
https://github.com/Dherse/masterproef
https://raw.githubusercontent.com/Dherse/masterproef/main/masterproef/parts/4_phos.typ
typst
#import "../ugent-template.typ": * #import "./hexagonal.typ": hexagonal_interconnect, f = The PHÔS programming language <sec_phos> Based on all of the information that has been presented so far regarding the translation of intent and requirements (@sec_intent), programming paradigms (@sec_paradigms), and the inadequacies of existing languages (@sec_language_summary), it is now apparent that it may be interesting to create a new language which would benefit from dedicated semantics, syntax, and integrate elements from fitting programming paradigms for the programming of photonic processors. This language should be designed in such a way that it is able to easily and clearly express the intent of the circuit designer while also being able to translate this code into a programmable format for the hardware. Additionally, this language should be similar enough to languages common within the scientific community, making it easy for engineers to learn and leverage existing tools. Finally, this language should be created in such a way that it provides both the level of control needed for circuit design and the level of abstraction needed to clearly express complex ideas. Indeed, the language that is presented in this thesis, @phos, is designed to fulfil these goals. The following sections will discuss the initial specification, syntax, constraint system, and other various elements of the language. Then, in @sec_examples, examples will be shown of how the language can be used to express various circuits. However, before discussing the language in itself, it is important to discuss the design of the language, the existing languages it draws inspiration from, and the lessons it incorporates from them. == Design <sec_design> #uinfo[ The name of the language, @phos, is a reference to the ancient Greek word for light or daylight, φῶς (phôs). ] ==== Inspiration @phos primarily takes inspiration from _Python_ and _Rust_ for its syntax while incorporating elements from functional languages such as _Elixir_#footnote[_Elixir_ has not been discussed in this thesis, but it provides the piping operator who is incorporated into @phos.]. Its semantics, especially as they relate to signals, are inspired by traditional hardware description languages, most notably _SystemVerilog_ and #emph[@vhdl]. Other semantics, as they relate to values, are inspired by _Rust_. Other elements, such as comments, are inspired by the _C_ family of languages, while documentation comments are inspired by _Rust_ as well. ==== Synthesisable @phos separates regular functions from synthesisable blocks. Whereas synthesisable blocks are able to interact with signals, regular functions are forbidden from operating on signals. This is done to ensure that branching reconfigurability computations are only done on synthesisable blocks. Ideally, synthesisable blocks would be kept as short as possible, while functions can be much longer. ==== Paradigm @phos is an imperative language with many functional elements, it purposefully keeps the easier aspects of imperative programming, while incorporating functional elements to make it both easier to reason about and easier to synthesise into hardware. The elements from functional programming relate especially to dataflow programming, as it has the closest semantics to light flowing from one component to another. The language is purposefully kept simple, with only a few elements from each paradigm, to ensure that it is easy to learn and easy to use. Form follows function, and the language is designed to be used by engineers and researchers, not by computer scientists. ==== Constraints @phos can express constraints directly in its syntax; this is opposed to other languages, such as @vhdl and _SystemVerilog_, which require timing constraints to be specified externally. This is done to ensure that the constraints are always in sync with the code and are always available at a glance. Additionally, @phos uses a constraint system that is compatible with both signals and regular values. This is done for several purposes, chief among them is to ensure that reconfigurability regions can be minimised, as discussed in @sec_branching_reconfig. == PHÔS: an initial specification <sec_spec> This section serves as an initial specification or reference to the @phos programming language. It contains the elements and semantics that have already been well-defined and are unlikely to change. Therefore, this section is not a complete specification as that would require that the language be more mature. However, it serves as an in-depth introduction to the concepts, paradigms, and semantics of the language. Most parts of the specification are companied by a short example to illustrate the syntax and the semantics of the language. Additionally, some elements are further explored in subsequent section of this chapter, with only the basics being presented here. === Execution model <sec_exec_model> @phos is a photonic hardware description language, due to its unique requirements, it is not designed in a traditional way and instead separates the compilation to hardware into three distinct steps: compilation, evaluation, and synthesis. The compilation step is responsible for taking the source code, written in human-readable text, and turning it into an executable form called the bytecode, see @sec_mir_to_bytecode. Followed by the evaluation, the evaluation interprets the bytecode, performs several tasks discussed in @sec_vm, and produces a tree of intrinsic operations, constraints and collected stacks. This tree is then synthesised into the output artefacts of the language, namely, the user @hal and a programming file for programming the photonic processor. The execution model is shown graphically in @fig_exec_model, showing all of the major components of the language and how they interact with each other. Further on, more details will be added as more components are discussed. #ufigure( outline: [ The execution model of the @phos programming language ], caption: [ The execution model of the @phos programming language, showing the three distinct stages. Responsibilities use the same color code as @fig_responsibilities, showing the ecosystem components in orange, the user's code in green, the platform-specific code in blue, and the third-party code in purple. ], image( "../assets/drawio/exec_model.png", width: 93%, alt: "Shows the execution model as the user code and the std lib going into the compiler, along with the platform-support package. The result is bytecode which goes into the virtual machine in the evaluation stage. The VM communicates with the constraint solver and the Z3 prover to produce the constraints & intrinsic operations. These are then fed into the synthesiser which produces the user HAL and the programming binary for the photonic processor, all the while using the platform HAL generator and the place-and-route.", ), ) <fig_exec_model> ==== Function execution model The execution model of functions in the @phos programming language is similar to that of _Java_ and _C_, every statement is terminated by a semicolon (`;`), with the exception of automatic return statements. @phos is single threaded and exclusively execute statement in the order that they are written in. Branching causes the @vm to jump from one place in the code to another. Function calls are executed by jumping to the entry point of the callee function, executing it in sequence, then returning to the next statement in the caller. Statements are therefore indivisible units of work. Additionally, @phos has order of precedence for its operators, therefore the order of execution of operators is not necessarily the order in which they are written. However, the order of statements is always the order in which they are written. Statements being composed of operators and operands, the order of execution of operators is determined by their precedence, with the highest precedence being executed first. The precedence of operators is shown in @tbl_op_precedence. #ufigure( outline: [ Operator precedence in @phos. ], caption: [ Operator precedence in @phos, from highest to lowest. Operators with the same precedence are executed from left to right. The precedence of operators is used to determine the order of execution of operators in a statement. The associativity of the operator is also shown, it can be left-associative, right-associative or neither for special operators that only have one operand. ], table( columns: (auto, 1fr, auto), align: center + horizon, stroke: (x: none), table.header( smallcaps[*Precedence*], smallcaps[*Operator*], smallcaps[*Associativity*], ), [1], align( left, )[ Conditional statements, loops, parenthesized expressions, unconstrained block, empty expressions ], align(left)[ Left ], [2], align(left)[ Function calls ], align(left)[ Left ], [3], align(left)[ Array indexing ], align(left)[ Left ], [4], align(left)[ Field access ], align(left)[ Left ], [5], align(left)[ Type casting ], align(left)[ Left ], [6], align(left)[ Raising to a power ], align(left)[ Right ], [7], align( left, )[ Unary operators: negation, bitwise complement, logical complement ], align(left)[ Right ], [8], align(left)[ Multiplication, division, remainder ], align(left)[ Left ], [9], align(left)[ Addition, subtraction ], align(left)[ Left ], [10], align(left)[ Bitwise shift left, bitwise shift right ], align(left)[ Left ], [11], align(left)[ Bitwise and ], align(left)[ Left ], [12], align(left)[ Bitwise xor ], align(left)[ Left ], [13], align(left)[ Bitwise or ], align(left)[ Left ], [14], align(left)[ Equality operators: equal, not equal ], align(left)[ Left ], [15], align( left, )[ Relational operators: less than, less than or equal, greater than, greater than or equal ], align(left)[ Left ], [16], align(left)[ Logical and ], align(left)[ Left ], [17], align(left)[ Logical or ], align(left)[ Left ], [18], align(left)[ Pipe operator ], align(left)[ Right ], [19], align(left)[ Range operators: inclusive range, exclusive range ], align(left)[ Neither ], [20], align( left, )[ Assignment operators: assign, add assign, subtract assign, multiply assign, divide assign, remainder assign, bitwise and assign, bitwise or assign, bitwise xor assign, bitwise shift left assign, bitwise shift right assign ], align(left)[ Neither ], [21], align(left)[ Closures ], align(left)[ Neither ], [22], align(left)[ Control flow operators: break, continue, return, and yield ], align(left)[ Neither ], ), ) <tbl_op_precedence> ==== Synthesisable execution model Synthesisable blocks follow a different execution model due to reconfigurability: when a block of code cannot be evaluated, it is analysed to remove as much code as possible before being collected into a stack. The stack is then stored along with the intrinsic subtree of that reconfigurability region. Additionally, synthesisable block produce intrinsic operations and constraints that are stored in a global tree of operations in order to produce the expected output. === Typing system @phos uses a typing system similar to _C_, it does not support object oriented programming. It has a basic type system as the complexity of actual code is expected to be relatively low. This limitation is put in place such that the language is easier to use with constraints, and especially with provers for reconfigurability. This means that the typing system is generally simple to use and understand. Overall, @phos' typing system is static and strong. Meaning that all values have a fixed type at compile time, and that implicit type conversions do not occur. This aims at reducing the potential for errors, as well as improving the clarity of @api[s] and @ip[s] designed with @phos. ==== Static type checking and inference @phos is statically typed, but offers type inference as a means of reducing the annotation burden on the user. Essentially, type inference tries to figure out what the type of a value is based on the operations being performed and the type of the values it is produced from. In the case of @phos, this will be performed using the _Hindley-Milner_ algorithm, which is a de-facto standard in modern programming languages @milner_theory_1978 @rust_compiler. Additionally, due to the simple type system employed by @phos, it should be generally easier for the compiler to infer the types of values as conflicts are less likely to occur. ==== Constraints and typing In this initial design of @phos, constraints are seen as metadata on values and signals. This is a simpler approach that decreases the initial development complexity. However, it is limiting and makes design error only visible during the evaluation phase of the compiler. For this reason, it could be improved using the concept of _refinement types_ @freeman_refinement_1991, which would allow the compiler to check for errors in constraints earlier, this is further discussed in @sec_future_work. === Mutability, memory management and purity @phos does only allow mutating of state, following the functional approach of limiting side effects @mailund_functional_2017. This makes the work of the prover used for reconfigurability easier. It also ensures that all functions are pure functions, something that can be exploited by the compiler to optimise the code, as well as be used in future iterations of the design to provide features such as memoization for faster compile time. This also means that @phos does not have a garbage collector, as it does not need to manage memory. As the lifetime of all values is predictable, @phos can simply discard values when they fall out of scope. This is done by the compiler, and does not require any action from the user. This is a deliberate choice to reduce the complexity of the compiler. ==== Limitations of immutability and purity Immutability make global state management difficult, requiring the user of a state monad to manage state @haskell_state_monad. However, @phos does not need global mutable state, as it is not a general-purpose programming language. Indeed, due to the hardware-software codesign nature of @phos, it is expected that the user will manage global state within their own software layer, leaving their @phos codebase free of global state. Additionally, purity disallows the user of side effects, which removes the user's ability to perform @io operations, such as reading from a file, making the language inherently safer to use. However, this also means that @phos cannot be used for general-purpose programming, and is limited to the domain of photonic circuit design. === Signal types and semantics <sec_signal_types> @phos distinguishes between the `electrical` and `optical` types. They mostly share the same semantics, with the exception that electrical signals cannot be operated upon. In the following paragraphs, the semantics of each will be discussed with examples. ==== Optical Optical signals follow a _drive-once_, _read-once_ semantics, meaning that they must be produced by a source element and must be consumed by a sink element, signals cannot be empty or be discarded without being used. The goal of this semantic is to make signals less error prone by avoiding the possibility of signals being left unconnected. Additionally, the _drive-once_ semantics ensure that signals are split explicitly by the user and not implicitly with difficult to predict results. Consider the example in @lst_ex_opt_splitting, depending on the compiler's implementation, it may lead to two splitting schemes, both shown in @fig_ex_opt_splitting, it shows that with an automatic scheme, based on the compiler architecture, it may lead to two different results. However, with an explicit scheme, the user is able to clearly define the splitting scheme, and the compiler no longer has to make any assumptions about the splitting scheme. Additionally, optical signals only support being passed into, used, or sourced inside of synthesisable blocks. This restriction aims at making the work of the compiler easier and creating a stronger distinction for users. #ufigure(caption: [ Optical signal splitting example ])[ ```phos let a = source(1550 nm, -10 dBm) let b = a |> gain(5 dB) let c = a |> filter(center: 1550nm, bandwidth: 10 GHz) let d = a |> modulate(external_signal, type_: Modulation::Amplitude) ``` ] <lst_ex_opt_splitting> #ufigure( caption: [ Automatic optical signal splitting schemes, showing the two possible automatic splitting scheme, using either a cascade architecture (a), or a parallel architecture (b). It leads to different power ratios for all of the downstream elements. ], outline: [ Automatic optical signal splitting schemes. ], kind: image, table( columns: 2, stroke: none, image( "../assets/drawio/optical_splitting_a.svg", alt: "Cascade architecture, showing that the source produce a signal which is split into 0.5 for b, 0.25 for c and 0.25 for d", ), image( "../assets/drawio/optical_splitting_b.svg", alt: "Parallel architecture, showing that the source produce a signal which is split into 0.33 for b, 0.33 for c and 0.33 for d", ), [ (a) ], [ (b) ], ), ) <fig_ex_opt_splitting> ==== Electrical Electrical signals do not allow any operations on them apart from being used in `modulate` and `demodulate` intrinsic operators. The reasoning behind this limitation is that, at present, there are no plans for analog processing in the electrical domain. And this feature is not yet implemented. Therefore, electrical signals are only ever used to modulate optical signals, or are produced as the result of demodulating optical signals. It is possible that, in the future, some analog processing features may be added, such as gain, splitting, etc., but as it is currently not planned, electrical signals are not allowed to be used in any other way. Electrical signals follow the same semantics as optical signals: _drive-once_, _read-once_. === Primitive types and primitive values @phos aims at providing primitive types that are useful for the domain of optical signal processing. As such, it provides a limited set of primitive types, not all of which are synthesisable. To understand how primitive types are synthesisable, see @sec_stack_collection. In @tab_primitive_types, the primitive types are listed, along with a short description. Primitive types are all denoted by their lowercase identifiers. This is a convention to make a distinction between composite types and primitive types. These primitive types are very similar to those found in other high-level programming languages such as _Python_ @python_reference. #ufigure( outline: [ Primitive types in @phos. ], caption: [ Primitive types in @phos, showing the primitive types and their description. For numeric types, the minimum and maximum values are shown. ], kind: table, )[ #table( columns: (auto, 1fr, auto, auto), align: center + horizon, stroke: (x: none), table.header( smallcaps[*Primitive type*], smallcaps[*Description*], smallcaps[*Minimum value*], smallcaps[*Maximum value*], ), `optical`, align(left)[ An optical signal, with _drive-once_, _read-once_ semantics. ], [-], [-], `electrical`, align( left, )[ An electrical signal, with _drive-once_, _read-once_ semantics. ], [-], [-], `any`, align(left)[ Any value, used for generic functions. ], [-], [-], `empty`, align(left)[ An empty value, equivalent to `null` is many other languages. ], [-], [-], `string`, align(left)[ A character list, encoded at UTF-8. ], [-], [-], `char`, align(left)[ A unicode scalar value @unicode10. ], [-], [-], `bool`, align(left)[ A boolean value, taking either `true` or `false` as a value. ], [-], [-], `int`, align(left)[ A signed integer value, 64 bit wide. ], [$-2^63$], [$2^63 - 1$], `uint`, align(left)[ A unsigned integer value, 64 bit wide. ], [$0$], [$2^64 - 1$], `float`, align( left, )[A floating point number, 64 bit wide. Represents a number in the IEEE 754 format @ieee_754_1985.], [$-1.798 dot 10^308$], [$1.798 dot 10^308$], `complex`, align( left, )[A complex floating point number, 128 bit wide. It consists of a real and imaginary part, both a floating point number.], [-], [-], ) ] <tab_primitive_types> === Composite types, algebraic types, and aliases #udefinition( footer: [ Adapted from @algebraic_data_type ], )[ *#gloss("adt", long: true)* is a type composed of other types, there exists two categories of @adt: *sum types* and *product types*. Product types are commonly tuples and structures. Sum types are usually enums, also referred to as *tagged unions*. ] @phos has the ability of expressing @adt in the forms of enums, enums are enumeration of $n$ variants, each variant can be one of three types: a unit variant, that does not contain any other data, a tuple variant, that contains $m$ values of different types, or a struct variant that also contains $m$ values of different types, but supports named fields. Enums are defined using the `enum` keyword followed by an identifier and the list of variants. In @lst_ex_enum, one can see an example of an enum definition, showing the syntax for the creation of such an enum. Enums are a sum type, as they are a collection of variants, each variant being a product type. Enums are a very powerful tool for expressing @adt, and are used extensively in @phos and languages that support sum types. #block( breakable: false, )[ #ufigure( outline: [ Example in @phos of an @adt type. ], caption: [ Example in @phos of an @adt type, showing all three variant kinds: `A` a unit variant, `B` a tuple variant, and `C` a struct variant. ], )[ ```phos enum EnumName { A, B(int, string), C { first_value: int, second_value: AnotherType } } ``` ] <lst_ex_enum> ] #udefinition( footer: [ Adapted from @aggregate_type ], )[ *Composite types* are types that are composed of other types, whether they be primitive types or other composite types. They are also called *aggregate types* or *structured types*. They are a subset of @adt. ] Additionally, @phos also supports product types and more generally composite types. Composite types are any type that is made of one or more other type. They can be one of five types: a unit structure, a tuple structure, a record structure with fields, a tuple, and an array of $n$ items of the same type. The syntax of these five types can be seen in @lst_ex_composite. This variety in typing allows for precise control of values and their representation. It allows the user to choose the best type for their current situation, such as anonymous tuples for temporary values or named records for more complex structures. #block( breakable: false, )[ #ufigure( outline: [ Example in @phos of composite types. ], caption: [ Example in @phos of composite types, showing all five kinds: `A` a unit structure, `B` a tuple structure, `C` a record structure, `D` a tuple, and arrays. ], )[ ```phos /// A unit struct struct A; /// A tuple struct struct A(uint, string, B); /// A record struct struct B { name: string, complex_signal: complex } /// an enum type is not named and can be declared inline. (uint, string, A) /// Arrays are defined with a type `A` and a size `10`. [A; 10] ``` ] <lst_ex_composite> ] @phos also supports type aliases, which is the action of locally renaming a type. This can be used to indicate in code the semantic behind the value: instead of being a numeric value, it can now be expressed as a `Voltage`, etc. This is done by using the `type` keyword, followed by the new name and the type alias; this is shown in @lst_ex_alias. #block( breakable: false, )[ #ufigure( caption: [ Example in @phos of type aliases, showing the creation of a `Voltage` type alias for `int`. ], )[ ```phos type Voltage = int; ``` ] <lst_ex_alias> ] === Automatic return values @phos support automatic return values, when the compiler sees that the final statement in a block is an expression that is not terminated by a semicolon, it will automatically return the value of that expression. This makes code more concise and readable, as shown in @lst_ex_auto_return, in #link(<lst_ex_auto_return>)[(a)] the example is shown with automatic return, and in #link(<lst_ex_auto_return>)[(b)] the example is shown with the explicit return. Additionally, it allows code blocks to be used as expressions, which is generally a useful feature. #block( breakable: false, )[ #ufigure( kind: raw, outline: [ Example in @phos of automatic and explicit return values. ], caption: [ Example in @phos of automatic return values, showing the difference between automatic return (a) and explicit return (b). ], )[ #table(columns: (1fr, 1fr), stroke: none, align: center + horizon, ```phos fn add( a: int, b: int ) -> int { a + b } ```, ```phos fn add( a: int, b: int ) -> int { return a + b; } ```, [ (a) ], [ (b) ]) ] <lst_ex_auto_return> ] === Units, prefixes, and unit semantics One of the unique features of @phos is the built-in @si unit system. It is comprised of all of the @si units, with the exception of the candela, and some of the compound units, the list of units are: seconds, amperes, volts, meters, watts, hertz, joules, ohms, henries, farads, coulombs, and siemens. This set of units comprises more units than is typically used in photonics, and this is done such that more circuits may be designed using the language in the future, as discussed in @sec_phos_generic. Additionally to @si units, @si prefixes are also supported from $10^(-18)$ to $10^12$. Support for decibels is also included; the following decibel units are supported: relative (dB), relative to the carrier (dBc), relative to a milliwatt (dBm), and relative to a watt (dBW). Finally, due to the prevalence of angles in photonics for phase controls, radians and degrees are also natively supported. It is also important to note that this list can very easily be expanded to include more units, prefixes, as the language is designed to be extensible. In @lst_ex_units, one can see the syntax for the usage of some of the units, decibels and angles. #block(breakable: false)[ #ufigure(caption: [ Example in @phos of @si units. ])[ ```phos /// 1 milliwatt 1 mW 0 dBm // 1 degree 1 deg 0.01745 rad 1° // 1 kilohertz 1 kHz 1e3 Hz ``` ] <lst_ex_units> ] ==== Unit semantic Instead of implementing a complete unit conversion system, at present, @phos is not intended to support conversion of units of different types, meaning that power is always power and that multiplying a power with time is invalid. To do so would require a complete unit conversion system, which is not planned for @phos. Units are the same regardless of prefixes, which the compiler converts into the base, unprefixed unit before execution begins. === Tuples, iterable types, and iterator semantics Tuples are a kind of product type that links one or more values together within a nameless container. They are often used as output values for functions, as they allow for multiple values to be returned. In @phos, tuples have two different semantics: on one the one hand, they can be used as storages for values, as in most modern languages, but on the other hand, they can be used as iterable values, which is a feature that is not present in many languages. Rather than having the concept of a list or collection, @phos supports unsized tuples. The general form of tuples as containers can be seen in @lst_ex_tuple_container. #block(breakable: false)[ #ufigure(caption: [ Example in @phos of tuples as containers. ])[ ```phos /// A tuple container containing b, c, and d let a = (b, c, d) /// A tuple as a type containing values of type B, C, and D type A = (B, C, D) ``` ] <lst_ex_tuple_container> ] ==== Unsized tuples Unsized tuples are a special kind of tuple which allows the last element to be repeating; it uses a special ellipsis (`...`) syntax to indicate that the last element is repeating. This is useful for representing lists, as @phos does not support lists otherwise. This is a purposeful decision, as it allows to extend the concept of pattern matching, discussed in @sec_patterns, beyond simple fixed sized tuples and into the realm of dynamically sized lists. The general form of unsized tuples can be seen in @lst_ex_unsized_tuple. #block(breakable: false)[ #ufigure(caption: [ Example in @phos of unsized tuples as containers. ])[ ```phos /// A simple unsized tuple: (B, B, B, B, ...) type E = (B...) /// A more complex unsized tuple: (B, C, D, D, D, ...) /// On the type `D` is repeating type A = (B, C, D...) ``` ] <lst_ex_unsized_tuple> ] ==== Iterable tuples Unsized tuples lead well into the idea of tuples as iterable values. Iterable values are values that can be used for enumerations in a loop or for using iterators. In @phos, all tuples are iterable, and iterable collections can have heterogeneous types, meaning that they can iterate over values of different types. This allows the user to iterate over tuples of different signal types, values, etc. The general form of iterable tuples can be seen in @lst_ex_iterable_tuple. #block(breakable: false)[ #ufigure(caption: [ Example in @phos of iterable tuples. ])[ ```phos // Iterating over a list of elements // It would print: // 1 // 2 // 3 for a in (1, 2, 3) { print(a) } ``` ] <lst_ex_iterable_tuple> ] === Patterns <sec_patterns> Patterns are used for pattern matching and destructuring, and are a core part of the language. They are used for matching values, tuples, and other types. They are also used to destructure complex values into their constituents. Patterns are used in many statements, such as the `match` statement, the `let` variable assignment statement, the `for` loop statement, and function argument declarations. The general form of the pattern can be seen in @lst_ex_pattern. #pagebreak(weak: true) #ufigure( caption: [ Example in @phos of patterns. ], )[ ```phos // Destructuring of tuples: (a = 1, b = 2, c = 3) let (a, b, c) = (1, 2, 3) // Destructuring of tuples with trailing: (a = 1, b = (2, 3)) let (a, b...) = (1, 2, 3) // Destructuring of a data structure: (a = 1, b = 2, c = 3) let MyStruct { a, b, c } = MyStruct { a: 1, b: 2, c: 3 } // Pattern matching for branching: match (a, b, c) { // Matches exactly a tuple of three elements containing 1, 2, and 3 (1, 2, 3) => print("Matched"), // Wildcard pattern _ => print("Not matched") } ``` ] <lst_ex_pattern> ==== Exhaustiveness In order for match statements to be correct, the compiler must be able to prove, based on the types, that a match statement is exhaustive. This is intended to be implemented using a similar algorithm to _Rust_'s compiler @rust_compiler. This is a very important feature, as it allows the compiler to prove that all possible cases are covered, and that the program will not crash due to a missing case. This is especially important with a point discussed in @sec_tunability_reconfigurability, which enables reconfigurability to work reliably. ==== Pattern matching and reconfigurability As previously mentioned, exhaustiveness helps ensure that reconfigurability is reliably achievable, as it allows the compiler to prove that all possible cases are covered. Additionally, the compiler can use constraints to remove branches that it can prove will never be taken. This is a very important and powerful feature as it decreases the configuration space of the user's design, and it allows the compiler to be faster and optimise the user's design further. === Branching and reconfigurability <sec_branching_reconfig> @phos supports branching as many other languages do. However, due to its use as a photonics @hdl, @phos has the special ability to use branching as boundaries for reconfigurability regions in synthesisable contexts. This feature was previously discussed in @sec_tunability_reconfigurability. The general form of branching can be seen in @lst_ex_branching. Reconfigurability through branching is designed to be very simple to use, the user can simply branch in their code. Suppose the compiler detects that signals are being used across the branches. In that case, it will automatically create a new reconfigurability region, meaning that the work is implicit and the user does not need to do anything special to enable reconfigurability. #block(breakable: true)[ #ufigure(caption: [ Example in @phos of branching. ])[ ```phos // Simple branching if a == 1 { print("a is 1") } else { print("a is not 1") } // Branching with multiple conditions if a == 1 && b == 2 { print("a is 1 and b is 2") } elif a == 1 && b == 3 { print("a is 1 and b is 3") } else { print("a is not 1 or b is not 2 or 3") } // Branching using match statements match (a, b) { (1, 2) => print("a is 1 and b is 2") (1, 3) => print("a is 1 and b is 3") _ => print("a is not 1 or b is not 2 or 3") } ``` ] <lst_ex_branching> ] === Variables, mutability, and tunability Variables in @phos are declared with the `let` keyword, followed by a pattern for the variable name, followed optionally by the type of the variable, and then followed by the assignment to the value. In @phos, variables cannot be uninitialised, and must be assigned a value when they are declared, with the notable exception of signals in unconstrained contexts, see @sec_unconstrained, which have special semantics. Variables are immutable, this makes the work of the prover for reconfigurability easier, if the user whishes to update a value, they can simply recreate it. This also makes the language simpler, as the user does not need to worry about the value of a variable changing. The general form of variable declaration can be seen in @lst_ex_variable_declaration. #block(breakable: true)[ #ufigure(caption: [ Example in @phos of variable declaration, assignment, and update. ])[ ```phos // Simple declaration let a = 5 // Destructuring declaration let (a, b...) = (1, 2, 3) // Declaration with type let a: uint = 5 // Declaration with destructuring and type let (a, b...): (uint, uint...) = (1, 2, 3) // Updating of a value let a = 6 let a = a + 5 ``` ] <lst_ex_variable_declaration> ] ==== Tunability Tunability is handled by passing a tunable value as an argument to the top-level component of the design. From then on, all subsequent use of this tunable value will also be turned automatically into tunable values. It is a simple implementation that allows the user to provide tunability and reconfigurability easily with minimal impact on the code. This, therefore, means that all code is generally tunable, and the user does not need to worry about the tunability of their code, as the compiler will handle it for them. However, if the user were to require a function not to be tunable due to its complexity, they can simply make it `static`, indicating that it cannot be tunable. An example of both use cases is provided in @lst_ex_tunability. #block(breakable: true)[ #ufigure(caption: [ Example in @phos of tunability. ])[ ```phos // Tunable function fn add(a: uint, b: uint) -> uint { return a + b } // Untunable function with static fn add(a: static uint, b: static uint) -> uint { return a + b } ``` ] <lst_ex_tunability> ] === Piping operator and semantics One of the key features of the @phos programming language that makes it easier to use for photonic circuit design is the ability to use the piping operator `|>` to chain functions together. This allows the user to write code in a more natural way, and allows the user to write code that is more readable. The piping operator is a binary operator with semantics that are more advanced than other binary operators: first, it can operate on any value, passing the output of one expression into the input of another, and second is that it can pattern match the values to create more complex calls. The general form of the piping operator can be seen in @lst_ex_piping_operator. #block(breakable: true)[ #ufigure(caption: [ Example in @phos of the piping operator. ])[ ```phos // Function that performs the addition of two numbers using piping fn add_with_pipe(a: uint, b: uint) -> uint { return (a, b) |> add } // Simple addition function fn add(a: uint, b: uint) -> uint { return a + b } ``` ] <lst_ex_piping_operator> ] #udefinition( footer: [ Adapted from @osullivan_real_2010. ], )[ *Monadic operations* are operations that take a value and a function and return a new value. They are common in functional programming languages, and are useful for manipulating data. They generally use the function provided as an argument to process the value, and return a new value. ] ==== Operation on iterators In addition to operating on values, the standard library will contain many common operations on iterators, such as mapping using the `map` and `flat_map` functions, two types of monadic bind operations, and filtering using the `filter` function. These operations are common in functional programming languages and are useful for manipulating data. The general form of these operations can be seen in @lst_ex_iterator_operations. #block(breakable: true)[ #ufigure(caption: [ Example in @phos of the piping operator on iterable values. ])[ ```phos // Function that performs the addition of two numbers using piping fn add_with_pipe(a: uint, b: uint) -> uint { return (a, b) |> fold(0, |acc, x| acc + x) } ``` ] <lst_ex_iterator_operations> ] === Function and synthesisable blocks @phos separates functions into three categories: functions denoted by the keyword `fn`, and synthesisable blocks denoted by the keyword `syn`. They are designated in such a way to create clearer separation between the concerns of the user and to allow the compiler to better separate the different functions of the code. All functions in @phos, regardless of their type, are subject to constraints and the constraint solver, whether these constraints are expressed on values or signals. ==== Functions Function represents code that cannot consume nor produce signals, whether electrical or optical. They can only process primitive types, composite types, and @adt[s]. They are intended to separate any coefficient computation from the signal path, creating a strong separation between the two. An example could be a lattice filter, which implements a series of coefficients, which are likely to be computed by a function. Instead of computing them inline with the signal, they can be computed in a function and then joined with the signal in a synthesisable block. Function branches do not represent reconfiguration boundaries, which greatly simplifies the work of the compiler. An example of a function can be seen in @lst_ex_function. #block(breakable: true)[ #ufigure(caption: [ Example in @phos of a function. ])[ ```phos // Function that performs the sum of $n$ numbers fn sum(a: (uint...)) -> uint { a |> fold(0, |acc, x| acc + x) } ``` ] <lst_ex_function> ] ==== Synthesisable blocks Synthesisable functions have the added semantic of being able to source and sink signals. They are intended to represent the signal path and are the only functions that can be used to create reconfiguration boundaries. They can be used to create a synthesisable block that can be tuned or reconfigured at runtime. An example of a synthesisable block can be seen in @lst_ex_synthesisable_block. #pagebreak(weak: true) #block( breakable: true, )[ #ufigure( outline: [ Example in @phos of a synthesisable block. ], caption: [ Example in @phos of a synthesisable block, showing an @mzi built discretely using the `split`, `constrain` and `merge` functions. ], )[ ```phos // Synthesisable block that performs the filtering of an input signal using an MZI // The MZI is built using the following actions: // 1. The `input` signal is split into two signals using a 50/50 splitter // 2. The two signals are constrained to have a phase difference of 30 degrees // 3. The two signals are interfered using a 50/50 combiner // This forms the basic structure of a Mach-Zehnder interferometer syn filter(input: optical) -> optical { input |> split((0.5, 0.5)) |> constrain(d_phase: 30 deg) |> merge() } ``` ] <lst_ex_synthesisable_block> ] === Modules and imports Most programming languages have module systems, which allow the user to organise their code into different files or folders with nested modules. It generally avoids files being overly long and makes the code tidier and easier to understand. @phos is no different in that regard. It adopts the module system of _Python_, where each file represents a different module, with files in the folder representing submodules of the folder. The module system of @phos is very simple, but it does allow for cyclic dependencies. While cyclic dependencies tend to increase the complexity of the compiler, it is relatively easy to overcome and makes the language easier to use. Modules are then imported using the `import` keyword, importing allows the user to import code from a module, and they can then choose what they want to import, whether it is everything, a specific submodule, or a specific function. The import system also allows the user to locally rename imported elements, such that they can avoid conflicting names. An example of an import can be seen in @lst_ex_import. #block( breakable: false, )[ #ufigure( caption: [ Example in @phos of an import. ], )[ ```phos // Importing the module `std::intrinsic` and renaming it to `intrinsic` import std::intrinsic as intrinsic; // Importing the syn `filter` from the module `std::intrinsic` import std::intrinsic::syn::filter; // Importing everything from the module `std::intrinsic` import std::intrinsic::syn::*; // Importing the syn `filter` and `gain` from the module `std::intrinsic` import std::intrinsic::syn::{filter, gain}; ``` ] <lst_ex_import> ] ==== Visibility In @phos, all elements that are declared are always public. Due to the expected low number of users of the language, it makes sense that all elements declared into a module be made public, such that code reuse can be maximised. This also means there is no need for the concept of visibility as it exists in many other languages, with special keywords like `pub`, `public`, or `private` to define the visibility of an item. === Closures and partial functions Closures are anonymous functions that are defined inline with the rest of the code. As with most modern languages, @phos supports closures. Closures are a source of complication for the compiler, it is very difficult for the compiler to keep track of value movement in closures and it is even more difficult to keep track of signal movement and usage for closures. Therefore, while signals are allowed to be used within closures, this cannot be checked at compile time and therefore must be checked by the @vm at a much later stage. An example of a closure can be seen in @lst_ex_closure. #block(breakable: false)[ #ufigure(caption: [ Example in @phos of a closure. ])[ ```phos // Closure that performs the sum of $n$ numbers let sum = |a: (uint...)| -> uint { a |> fold(0, |acc, x| acc + x) }; ``` ] <lst_ex_closure> ] ==== Signals in closures Due to their _drive-once_, _read-once_ semantics, signals are an especially difficult case for closures. Normally, closures are allowed to capture variables from their environment, and are equivalent to functions. However, signals are not normal variables, and the capturing mechanism has to be different. For this reason, closures are separated into three types: `Fn`, which are closures that operate like regular functions, `Syn`, which are closures that operate like regular synthesisable blocks. While they can process signals, they cannot capture signals, `SynOnce` which are closure that is synthesisable, but must be called once, essentially following the same _drive-once_, _read-once_ semantic as other signals. The difference between the three kinds can be seen in @lst_ex_closure_kind. #figure( kind: raw, caption: [ Example in @phos of an `Fn` closure (a), a `Syn` closure (b), and a `SynOnce` closure (c). ], )[ ```phos // (a) `Fn` closure let c = 1; let fn_closure = |a: uint| -> uint { a + c }; // (b) `Syn` closure let syn_closure = |a: optical| -> (optical...) { a |> split((0.5, 0.5)) }; // (c) `SynOnce` closure let a = source(1550 nm) let syn_once_closure = || -> (optical...) { a |> split((0.5, 0.5)) }; ``` ] <lst_ex_closure_kind> #udefinition( footer: [ Adapted from @peyton_jones_how_2004 ], )[ *Partial functions* are functions which are *partially applied*, meaning that parts of their argument are already applied and that the new function can be called with only the missing arguments. Partial functions are, therefore functions with lower arity. ] ==== Partial functions In @phos, partial functions are created with the keyword `set`. It produces a closure with the same semantics as previously discussed but with the added ability to be called with fewer arguments than the closure expects. Additionally, the caller of the closure may override already `set` arguments by referring to them by name. An example of a partial function can be seen in @lst_ex_partial. #figure( kind: raw, caption: [ Example in @phos of partial function in @phos. ], )[ ```phos fn add(a: uint, b: uint) -> uint { a + b } let add_1 = set add(1); print(add_1(2)); // prints 3 ``` ] <lst_ex_partial> === Loops, recursion, and turing completeness #udefinition( footer: [ Adapted from @cs390. ], )[ *Turing completeness* is used to express the power of a data manipulation system. It is a measure of the ability of a system to perform all calculable computations. ] @phos does not aim to be a Turing complete, as it does not need to be used for generic purposes. Due to the exponential complexity of reconfigurability states as the program is allowed to loop and recurse, @phos places a hard limit on the following elements: the number of iterations, the depth of recursion, and the number of optical intrinsic operations that can be performed. The goal of these measures is to avoid the compiler taking too long to try and compile a program for which no device is big enough to fit it. The compiler will therefore reject programs that exceed these limits. The limits are set to be high enough that they should not be reached in most cases but low enough that the compiler can reject programs that are too complex to be compiled. Additionally, some of these limits can be changed by the user using the marshalling layers (see @sec_marshalling). For the aforementioned reason, @phos does not have infinite loops but only iterative loops that iterate over an input value. This limits the risk of the user falling into the iteration limit, as the number of iterations is known. An example of a loop can be seen in @lst_ex_loop. #pagebreak(weak: true) #figure(kind: raw, caption: [ Example in @phos of a loop. ])[ ```phos for i in 0..5 { print(i); } ``` ] <lst_ex_loop> === Constraints <sec_phos_constraints> #uinfo[ It has been discussed that the syntax of constraints should be changed to declutter function/synthesisable block signatures. This would allow constraints to be cleaner and would ideally be expressed as its own part of the signature, rather than being defined with the arguments. However, this has not yet been designed and is therefore not discussed further in this document. ] @phos models constraints as additional data carried by values and signals. It applies the semantics discussed in @sec_constraints. In the current iteration of the design, constraints are, therefore, a evaluation-time concept that cannot be checked by the compiler. This is a limitation of the current design and will be addressed in future iterations. An example of a constraint can be seen in @lst_ex_constraint. #figure(kind: raw, caption: [ Example in @phos of a constrained synthesisable block. ])[ ```phos // Performs an optical gain on an input signal, // the maximum input power is `10dBm - gain`, // the gain is constrained to be between 0 and 10dB. syn gain( @max_power(10dBm - gain) input: optical, @range(0dB, 10dB) gain: Gain, ) -> @gain(gain) optical { ... } ``` ] <lst_ex_constraint> === Unconstrained <sec_unconstrained> As mentioned in @sec_constraints, constraints only work for non-cyclic cases#footnote[That is, constraints that do not depend on themselves.], however, this limitation removes the advantage of having a recirculating mesh inside the photonic processor. Therefore, as was previously mentioned, @phos must provide a way to express blocks where the constraints are not automatically inferred but must be manually specified. This is done by using the `unconstrained` keyword, which allows the user to specify the constraints manually at the boundary of a synthesisable block. An example of an unconstrained block can be seen in @lst_ex_unconstrained. Additionally, unconstrained blocks allow the user to create their signals without needing to use a source intrinsic. This semantic is useful for creating recirculating elements in the photonic processor, as it allows the user to create temporary variables containing signals. #pagebreak(weak: true) #figure( kind: raw, caption: [ Example in @phos of an unconstrained synthesisable block. ], )[ ```phos // A ring resonator implemented using an unconstrained block unconstrained syn ring_resonator( input: optical, @range(0.0, 1.0) coupling: float, @min(6) length: Length, ) -> @frequency_response(response(coupling, length)) optical { // Create a new internal signal let ring: optical; // Create the output signal let output: optical; // Use an intrinsic coupler (input, ring) |> std::intrinsic::coupler(coupling) |> constrain(dlen = length) |> (output, ring); output } // Returns the frequency response of a ring resonator given its arguments. fn response(coupling: float, length: Length) -> FrequencyResponse { ... } ``` ] <lst_ex_unconstrained> === Stack collection and synthesisable non-signal types <sec_stack_collection> One of the issues that arises from tunability, and especially with reconfigurability, is that the tunable values can be of any type and therefore need to be converted into the values that the physical hardware can interpret. When designing the circuit, or the hardware platform package, it is natural to convert these meaningful high-level values into lower-level, less explicit values using @phos. Ideally, as much of the conversion as possible should be done in @phos, such that the circuit code can act as a source of truth and decrease the complexity of the hardware-software codesign. But this creates an issue: when using tunable value, the @phos @vm cannot compute these low-level values directly, as it does not know the value of the tunable value. Additionally, when tunable values lead to reconfigurability, the @vm cannot evaluate the conditions that lead to reconfigurability statically. Therefore, the parts of the code that perform the conversion between high-level and low-level values must be synthesisable. Of course, the photonic processor being an analog processor, it is not possible to perform this synthesis on the actual mesh. However, as mentioned in @sec_programmability, one of the compilation artefacts is the user @hal, which is generated for the user based on their design. It would therefore be possible to collect these operations and package them into the @hal, such that when the user programmatically tunes their design, the conversion is done inside of the user @hal and sent to the processor's controller as a low-level value. The name is based on the fact that @phos uses a stack-based virtual machine and that the operations are collected into the user @hal and converted into _Rust_ (the implementation language of the @hal) automatically by the compiler. #udefinition[ *Stack collection* is the process of collecting the operations that convert high-level values into low-level values and packaging them into the user @hal. ] Stack collection is, therefore, an automatic feature performed by the compiler, its goal is to evaluate as much as possible at compile time as a means to decrease the amount of work being done inside of the user @hal and collect the stack operations that are relevant to the conversion. From these collected stacks, it can easily evaluate the conditions that lead to reconfigurability and package them into the user @hal. Nonetheless, one problem remains: which reconfigurability states must be kept past this point. As explained in @sec_tunability_reconfigurability, the compiler can discard as many reconfigurability states as possible based on constraints and using a prover like _Z3_ @z3. === Language items and statements Language items and statements are the hierarchy of language elements that can be used to create a program. They are the most basic elements of the language and are used to create more complex elements. They are the building blocks of the language and are the elements that are used to create the @ast. They are the most important elements of the language and are the ones that are the most likely to be modified in the future. The language items and statements of @phos are listed in @tab_lang_items_statements, along with a short description and a short example. #ufigure( kind: table, outline: [ The list of language items and statements supported in @phos ], caption: [ The list of language items and statements supported in @phos, along with a short description and a short example. Additionally lists whether the element is an item or a statement, or both, where a statement is a language element that can be used as an expression, and an item is a language element that cannot be used as an expression, but can be used as a top level declaration. #underline[Legend]: #required_sml means yes, #not_needed_sml means no. ], table( columns: (auto, 0.2fr, 0.2fr, 0.5fr, 1fr), align: (x, y) => if y == 0 { center } else if x in (0, 1, 2) { center } else { left }, stroke: (x: none), table.header( smallcaps[*Element*], smallcaps[*Item*], smallcaps[*Statement*], smallcaps[*Description*], smallcaps[*Example*] ), smallcaps[*Import*], required, required, [ Imports a module into the current module. ], ```phos import std::intrinsic as intrinsic; ```, smallcaps[*Function*], required, required, [ Declares a function. ], ```phos fn sum( a: (uint...) ) -> uint { ... } ```, smallcaps[*Synthesisable*], required, not_needed, [ Declares a synthesisable function. ], ```phos syn gain( input: optical ) -> optical { ... } ```, smallcaps[*Type alias*], required, not_needed, [ Declares a type alias. ], ```phos type Voltage = float; ```, smallcaps[*Constant*], required, required, [ Declares a constant. ], ```phos const PI = 3.141592; ```, smallcaps[*Structure*], required, not_needed, [ Declares a new data structure. ], ```phos struct Point { x: float, y: float } ```, smallcaps[*Enumeration*], required, not_needed, [ Declares a new @adt. ], ```phos enum Color { Red, Green, Blue, } ```, smallcaps[*Local*], not_needed, required, [ Declares a new local variable ], ```phos let (a, b...) = (1, 2, 3); ```, smallcaps[*Expression*], not_needed, required, align(left)[ Declares a new expression. ], ```phos 1 + 2 ```, ), ) <tab_lang_items_statements> #pagebreak(weak: true) === Expressions Expressions are a subset of statements that operate on one or more values and may produce an output value. A complete list of @phos expressions is available in @tab_exprs. #ufigure( kind: table, outline: [ The list of language expressions supported in @phos ], caption: [ The list of language expressions supported in @phos, along with a short description and a short example. Additionally lists whether the expression is a control flow expression, constant expression, unary expression, binary expression, or special expression. Where a control flow expression is an expression that can be used to control the flow of the program, a constant expression is a value that can be determined at compile time, a unary expression is an expression that takes only one argument, a binary expression is an expression that takes two arguments, and a special expression is an expression that is not easily categorised and that performs more complex actions, with well-defined semantics. ], table( columns: (0.1fr, 0.5fr, 1fr, 1fr), stroke: (x: none), align: (x, y) => { if x == 0 { center + horizon } else if x in (0, 1) { center + horizon } else { left + horizon } }, table.header( table.cell(colspan: 2, smallcaps[*Expression*]), smallcaps[*Description*], smallcaps[*Example*] ), table.cell(rowspan: 8, rotate(-90deg, box(width: 200pt, smallcaps[*Control flow*]))), smallcaps[*Block*], [ Declares a new block of code. ], ```phos { let a = 10; a + 20 } ```, smallcaps[*If/Else/Elif*], [ A conditional statement for branching. ], ```phos if a > b { a } else { b } ```, smallcaps[*Match*], [ A pattern matching statement. ], ```phos match a { 1 => "one", _ => "other" } ```, smallcaps[*Loop*], [ A loop statement. ], ```phos for i in 0..5 { print(i) } ```, smallcaps[*Return*], [ Returns a value from a function. ], ```phos return 1 ```, smallcaps[*Break*], [ Breaks out of a loop. ], ```phos for i in 0..5 { break; } ```, smallcaps[*Continue*], align( left, )[ Continues a loop, terminating the current iteration and moving on the the next one. ], ```phos for i in 0..5 { continue; } ```, smallcaps[*Yield*], [ Yields a value from an iterator. ], ```phos for i in 0..5 { yield i; } ```, table.cell( rowspan: 4, rotate(-90deg, box(width: 200pt, smallcaps[*Constant*])) ), smallcaps[*Path*], [ A path to a value, constant, or other item. ], ```phos std::intrinsic::gain float::PI ```, smallcaps[*Identifier*], [ A name that refers to a value, constant, or other item. ], ```phos gain PI ```, smallcaps[*Literal*], [ A literal value. ], ```phos 1 dBc true 0.5 MHz ```, smallcaps[*None*], [ The none value. ], ```phos none ```, table.cell( rowspan: 3, rotate(-90deg, box(width: 200pt, smallcaps[*Unary*])) ), smallcaps[*Negation*], [ Negates a value. ], ```phos -1 ```, smallcaps[*Not*], [ Negates a boolean value. ], ```phos !true ```, smallcaps[*Binary not*], [ Negate a binary value. ], ```phos !0xFF ```, table.cell( rowspan: 19, rotate(-90deg, box(width: 200pt, smallcaps[*Binary*])) ), smallcaps[*Addition*], [ Adds two values. ], ```phos 1 + 2 ```, smallcaps[*Subtraction*], [ Subtracts two values. ], ```phos 1 - 2 ```, smallcaps[*Multiplication*], [ Multiplies two values. ], ```phos 1 * 2 ```, smallcaps[*Division*], [ Divides two values. ], ```phos 1 / 2 ```, smallcaps[*Modulo*], [ Calculates the remainder of a division. ], ```phos 1 % 2 ```, smallcaps[*Exponentiation*], [ Raises a value to a power. ], ```phos 1 ** 2 ```, smallcaps[*Bitwise and*], [ Performs a bitwise and operation. ], ```phos 1 & 2 ```, smallcaps[*Bitwise or*], [ Performs a bitwise or operation. ], ```phos 1 | 2 ```, smallcaps[*Bitwise xor*], [ Performs a bitwise xor operation. ], ```phos 1 ^ 2 ```, smallcaps[*Bitwise shift left*], [ Performs a bitwise shift left operation. ], ```phos 1 << 2 ```, smallcaps[*Bitwise shift right*], [ Performs a bitwise shift right operation. ], ```phos 1 >> 2 ```, smallcaps[*Less than*], [ Checks if a value is less than another. ], ```phos 1 < 2 ```, smallcaps[*Less than or equal*], [ Checks if a value is less than or equal to another. ], ```phos 1 <= 2 ```, smallcaps[*Greater than*], [ Checks if a value is greater than another. ], ```phos 1 > 2 ```, smallcaps[*Greater than or equal*], [ Checks if a value is greater than or equal to another. ], ```phos 1 >= 2 ```, smallcaps[*Equal*], [ Checks if a value is equal to another. ], ```phos 1 == 2 ```, smallcaps[*Not equal*], [ Checks if a value is not equal to another. ], ```phos 1 != 2 ```, smallcaps[*Logical and*], [ Checks if two boolean values are both true. ], ```phos true && false ```, smallcaps[*Logical or*], [ Checks if either of two boolean values are true. ], ```phos true || false ```, table.cell( rowspan: 13, rotate(-90deg, box(width: 200pt, smallcaps[*Special*])) ), smallcaps[*Pipe*], [ Pipes a value into a function. ], ```phos 1 |> f ```, smallcaps[*Parenthesized*], [ Groups an expression. ], ```phos (1 + 2) * 3 ```, smallcaps[*Tuple*], [ Creates a tuple. ], ```phos (1, 2) ```, smallcaps[*Cast*], [ Casts a value to a different type. ], ```phos 1 as uint ```, smallcaps[*Index*], [ Indexes into a value. ], ```phos a[1] ```, smallcaps[*Member access*], [ Accesses a member of a value. ], ```phos a.b ```, smallcaps[*Function call*], [ Calls a function. ], ```phos f(1, 2) ```, smallcaps[*Method call*], [ Calls a method. ], ```phos a.f(1, 2) ```, smallcaps[*Partial*], [ Partially applies a function. ], ```phos set f(1) ```, smallcaps[*Closure*], [ Creates a closure. ], ```phos |x| x + 1 ```, smallcaps[*Range*], [ Creates a range. ], ```phos 1..2 1..=2 ..3 4.. ```, smallcaps[*Array*], [ Creates an array. ], ```phos [1, 2] ```, smallcaps[*Object instance*], [ Creates an object instance. ], ```phos A {a: 1, b: 2} B(1, 2) MyEnum::A C ```, ), ) <tab_exprs> == Standard library <sec_stdlib> In addition to the language itself, @phos will come with a standard library: a library of functions and synthesisable blocks that come with the language. The standard library will be written in a mixture of @phos for synthesisable blocks and functions and some native _Rust_ code for either performance-critical sections or areas where external libraries are required. The standard library will be organised as logically as possible, providing the necessary building blocks for new users to be productive with the language. However, the standard library will be limited in scope such that it does not become a burden to maintain. Relying instead on third-party libraries and @ip[s] for more complex functionality. A notable goal of the standard library is to provide synthesisable blocks for all common functions, like modulators, filters, and so on. But not for more complex functionality like larger components or even entire systems. Most intrinsic operations discussed in @sec_intrinsic_operations are more complex than they first appear. As previously mentioned in @sec_programmable_photonics, most photonic components are actually reciprocal, meaning that they are the same whether light is travelling forwards or backwards. Additionally, waveguides support two modes, one in each direction, meaning that each device may be used for two purposes. Removing the user's ability to exploit these properties would be greatly limited, and as such, the standard library must provide ways of accessing these fully-featured intrinsic operations. However, the user cannot be expected to only program using these low-level primitives. Furthermore, they are mostly unconstrained and would require constrained blocks to be used to their full extent due to the limitation on constraints regarding cyclic dependencies. Therefore, one of the main goals of the standard library is to provide higher-level primitives that wrap these unconstrained intrinsic operations into constrained blocks following the feedforward approximation (@feedforward_approx). The standard library should also decouple synthesisable blocks from computational methods. For example, a filter block may need other functions to compute the coupling coefficient or the length of a ring resonator. These functions will need to be part of the standard library to offer filter synthesis, but they should be accessible separately, such that if a user wishes to implement some function themselves, they can rely on the existing code present in the standard library to make their work easier. This also means that the standard library should be as modular as possible, perhaps even in the future, allowing users to replace default behaviour in the standard library with their own implementations. This modularity also helps in the development of the platform-support packages, as these need to be able to support the standard library, something that may be done by replacing parts of the standard library with platform-specific implementations while keeping the exposed @api the same. Finally, the standard library can serve as a series of examples for new users. A photonic engineer that is knowledgeable in photonic circuit design would benefit from the standard library as a source of high-quality examples onto which they may base themselves. Similarly, a software engineer knowledgeable with software development but not photonic circuit design, would benefit from the standard library as a source of high-quality examples of basic building blocks of photonic circuits. The standard library should be written in a way that is easy to understand and that is well-documented, such that it can serve as a learning resource for new users. ==== Constrain A unique feature of the standard library is the `constrain` method. It is used to impose differential constraints on signals. This means that constraints over delay or phase, which are always relative, can be expressed between signals. This tells the synthesiser to ensure that these constraints are respected between signals. Indeed, if it were not for this method, the user could not easily represent phase-matched or delay-matched signals. During the examples, in @sec_examples, the use of this method will become clear, and its implication and why it is so important will be discussed. #pagebreak(weak: true) == Compiler architecture <sec_arch> The design of the @phos compiler is inspired in parts by _Clang_'s, _Rust_'s, and _Java_'s compilers @clang_internals @rust_compiler @openjdk_hotspot. As previously mentioned, the compilation of a @phos program into a circuit design that can be programmed onto a photonic processor is a three-step process: compilation, evaluation, and synthesis. The compiler, as it is referred to in this section, performs the compilation step. Therefore, as previously mentioned in @sec_exec_model, it takes the user's code as an input and produces bytecode for the #gloss("vm", long: true). The compiler is written in _Rust_ and is split into several components, each with a specific purpose. As will be discussed in subsequent sections, the @phos compiler is composed of a _lexer_, a _parser_, an _#gloss("ast", long: true)_, a _desugaring_ step, a _high-level intermediary representation_, a _medium-level intermediary representation_, and a _bytecode_ generator. The multiple stages of the compiler are illustrated in @fig_compiler_arch. #uimportant[ The overall architecture and components of the @phos compiler are similar in design to _Rust_'s compiler @rust_compiler. This is done purposefully for two reasons. First, _Rust_ as a language is advanced and has a well designed compiler, and as such, is a good source of reference materials. Second, the @phos compiler is written in _Rust_, and as such, it can reuse existing code and algorithms from both the extended ecosystem of language development libraries in _Rust_ and from the _Rust_ compiler itself. As the _Rust_ compiler is released under an @mit license, it can legally be used as a source of inspiration and code for the @phos compiler. ] #ufigure( outline: [ Compiler architecture of the @phos programming language ], caption: [ Compiler architecture of the @phos programming language, showing that the user code flows into the different stages of the compiler. All of these stages produce the bytecode that can be evaluated. This figure uses the same colour scheme as @fig_responsibilities, showing the ecosystem components in orange, the user's code in green, and the platform-specific code in blue. ], image( "../assets/drawio/compiler_arch.png", width: 80%, alt: "Shows the compiler architecture of the PHÔS programming language: going from user code into lexing, into parsing, into desugaring, into AST-to-HIR, into HIR-to-MIR, into bytecode generation. To produce the bytecode that can be executed by the VM.", ), ) <fig_compiler_arch> === Lexing <sec_lexing> #udefinition( footer: [ Adapted from @nystrom_crafting_2021. ], )[ *Lexing* is the process of taking a stream of characters and converting it into a stream of tokens. A token is a sequence of characters that represent a unit of meaning in the language. ] As this definition implies, this lexer turns a series of characters from the human-readable @phos code into a series of tokens, which can be seen as words of the language. Some of those words have special significance, such as `+`, which represents an addition, and others such as an open parenthesis (`(`) simply represents an open parenthesis. At this stage of the compilation process, there is no meaning associated with each token, meaning that they are separate entities that the compiler is yet to associate into bigger, more meaningful units. The @phos lexer is implemented using the _Logos_ library in _Rust_ @logos. _Logos_ is a lexer generator, meaning that it allows the creation of extremely fast lexers very quickly, and is used by other open-source projects @logos_dependents. In @lst_lexing_ex, one can see the process that turns a simple piece of code into a series of tokens that can be used by the parser. The code is first split into a series of characters, which are then fed into the lexer. The lexer then produces a series of tokens, which are then printed to the console. One can also see that the comment in line one has been removed. Indeed, the lexer discards all unnecessary tokens, such as linebreak, whitespace, and comments. This is done to simplify the parsing process, as the parser does not need to deal with those tokens and can focus on the tokens that are meaningful to the language. Additionally, and not shown in @lst_lexing_ex, the @phos lexer preserves the span where the token is found in the source code. This is used to generate more meaningful errors by indicating the location of the error in the source code. This is done by associating the said span with each token produced by the lexer. #ufigure( kind: raw, outline: [ Example of lexing in @phos ], caption: [ Example of lexing in @phos, showing a code sample (a) and the output of the lexer (b). Note that the indentation in (b) is solely for readability purposes and is not part of the output of the lexer. ], table(columns: (0.8fr, 1fr), stroke: none, ```phos // Adds two numbers // together. fn add(a: int, b: int) -> int { a + b } ```, ```js Keyword("fn") Identifier("add") OpenParen Identifier("a") Colon Identifier("int") Comma Identifier("b") Colon Identifier("int") CloseParen Arrow Identifier("int") OpenBrace Identifier("a") Plus Identifier("b") CloseBrace ```, align(center)[(a)], align(center)[(b)]), ) <lst_lexing_ex> === Parsing <sec_parsing> #udefinition( footer: [ Adapted from @nystrom_crafting_2021. ], )[ *Parsing* is the action of taking a stream of tokens and turning it into a tree of nested elements that represent the grammatical structure of the program. ] Before parsing the language, one must first describe the grammar of the language. There exist many families of grammar, as seen in @fig_parser_hierarchy. The more complex the grammar is, the more complex of a parser it will require. It is important to note that @fig_parser_hierarchy describes grammar, not languages. Languages can be expressed using multiple grammars, and some grammars for a given language can be simpler @cs143. Every grammar can be expressed with a higher-level grammar, but the reverse is not valid. @phos has an LL(K) grammar, meaning that it can be read from #strong[L]eft-to-right with #strong[L]eftmost derivation, with $k$ token lookahead, meaning that the parser can simply move left-to-right, only ever applying rules to elements on the left, and needs to look up to $k$ tokens ahead of the current position to know which rule to apply. This is a fairly complex grammar to express and parse. The parser for @phos is implemented using the _Chumsky_ library (named after _<NAME>_) in _Rust_ @chumsky. _Chumsky_ is a parser combinator generator, meaning that it allows the creation of complex parsers with relatively little code. Because of the properties of _Chunmsky_, the parser for the @phos language is fairly simple, at only 1600 lines of code, and is relatively easy to understand. It is the task of the parser to use the @phos grammar to produce an #gloss("ast", long: true); this tree represents the syntax and groups tokens into meaningful elements. Additionally, the grammar of @phos contains the priority of operations, meaning that the resulting @ast is already correct regarding the order of operations, something that otherwise would need to be done using @ast transformations in the next step of the compilation process. This further increases the complexity of the grammar and the complexity of the parser but simplifies the next steps of the compilation process. #ufigure( outline: [ Hierarchy of grammar that can be used to describe a language. ], caption: [ Hierarchy of grammar that can be used to describe a language. The grammars are ordered from the most powerful to the least powerful. The most powerful grammars are able to describe any unambiguous language, whereas the least powerful grammars are only able to describe a subset of the languages @cs143. As @phos does not use ambiguous grammar and they are very difficult to describe and parse, they are not discussed further. ], image( "../assets/drawio/parser-hierarchy.png", width: 90%, alt: "Shows the hierarchy of parser, showing that for unambiguous grammars, the subsets are LR(K), LR(1), LALR(1), SLR(1), LR(0), LL(K), LL(1), LL(0). Ambiguous grammars also exists but they are not discussed further.", ), ) <fig_parser_hierarchy> #pagebreak(weak: true) === The abstract syntax tree <sec_ast> The #gloss("ast", long: true) is the result of the previous compilation step -- parsing --, and it is a tree-like data structure that represents the syntax of the user's code in a meaningful way. It shows the elements as bigger groups than tokens, such as expressions, synthesisable blocks, etc. The @ast is the base data structure on which all subsequent compilation steps are based. The @ast would also be used by the @ide to provide code completion, syntax highlighting, and code formatting. Just as is the case for parsing, syntax trees have a hierarchy; it generally consists of two categories: the #gloss("cst", long: true) and the #gloss("ast", long: true). The @cst aims at being a concrete representation of the grammar, being as faithful as possible, and keeping as much information as possible. On the other hand, an @ast only keeps the information necessary to perform the compilation. Therefore, it is generally simpler and smaller than an equivalent @cst. However, while this can be seen as a hierarchy, it is more of a spectrum, as the @ast can be made more concrete and closer to a @cst, depending on the needs. In fact, the @ast of @phos keeps track of all tokens, and their position in the source code, making it possible to reconstruct the original source code from the @ast. The only thing it discards is whitespaces, linebreaks, and comments. The @ast of @phos also keeps track of spans where the code comes from, just like in the lexer. It is used to provide better error messages. Building on top of the example shown in @lst_lexing_ex, the @ast for the function `add` would look like @lst_ast_ex. Additionally, an overview of the data structure required to understand this part of the @ast is shown in @anx_ast_overview. Some details have been omitted for brevity and to focus on the relevant parts of the @ast. However, one can still see the tree-like structure of the @ast and the many different kinds of data structures that it requires. In fact, the current @ast for @phos is composed of 250 different data structures. This shows how complex the @ast can be and how much work is required to build it. However, having a good @ast as the basis of the compilation process is crucial as it can be easily modified, expanded, and transformed to perform the compilation. Additionally, the breadth of data it contains can be used to implement other elements of the ecosystem, such as code formatters, code highlighters, and linters, all tools that have been discussed at length and are essential to provide a good developer experience. #ufigure( outline: [ Partial result of parsing @lst_lexing_ex. ], caption: [ Partial result of parsing @lst_lexing_ex, showing the tree-like structure of nested data structures. The @ast is a tree-like data structure that represents the syntax of the user's code. In this case, it shows a function whose name is an identifier `add`, and that has two arguments: `a` and `b`, both of type `it`, it has a return type of type `int`, and a body that is a block containing a single expression, which is a call to the `+` operator, with the arguments `a` and `b`. ], image( "../assets/drawio/ex_ast_out.png", width: 90%, alt: "Partial result of parsing @lst_lexing_ex, showing the tree-like structure of nested data structures. The AST is a tree-like data structure that represent the syntax of the user's code. In this case, it shows a function which name is an identifier add, and that has two arguments: a and b, both of type it, it has a return type of type int, and a body that is a block containing a single expressions, which is a call to the + operator, with the arguments a and b.", ), ) <lst_ast_ex> === Abstract syntax tree: desugaring, expansion, and validation <sec_ast_desug> #uinfo[ From this point in the document, the language is not yet implemented and therefore does not exist. Therefore, the following steps are not implemented and only describe what will be done when the language is fully implemented. ] #udefinition( footer: [ Adapted from @nystrom_crafting_2021. ], )[ *Syntactic sugar* is the part of the language's syntax that is intended to make things easier to read, express, or understand. ] The first step in the compilation process is to remove syntactic sugar, as it is not useful for the compiler and is only intended to make the code easier to read and write. Therefore, this syntactic sugar can be simplified into simpler syntactic blocks. Additionally, in the same stage, the @ast is expanded to include more information. In the case of the @phos programming language, this will involve the following: - Feature gate checking; - Transforming all automatic return statements into explicit return statements; - Name resolution; - Macro expansion; - and @ast validation. For this section, the example shown in @lst_desug_ex will be used. It shows a simple circuit involving a filter, a gain section that is gated behind a feature flag, implicit returns and imports. Since macros don't yet have a fixed syntax for a language and are left as future work, see @sec_lang_improvements, there will not be an example involving macros. #ufigure( kind: raw, caption: [ An example used to show the desugaring, @ast expansion, and @ast validation in @phos. ], )[ ```phos import std::{filter, gain}; /// Processes a signal using one of two filters based on feature flags syn process_signal(signal: optical) -> optical { signal |> internal_process() } /// If the library supports gain, add some gain after the filter #[feature(gain)] syn internal_process(signal: optical) -> optical { signal |> filter(1550 nm, 10 GHz) |> gain(10 dB) } /// If the library does not support gain, just filter the signal #[feature(not(gain))] syn internal_process(signal: optical) -> optical { signal |> filter(1550 nm, 10 GHz) } ``` ] <lst_desug_ex> #unote[ The processes being described in this section are done at the @ast level. However, for clarity, the source code is shown instead of the @ast for each step in this compilation stage. ] ==== Feature gate checking In this step, the syntax is checked for feature gates, and only the parts of the @ast not gated by feature gates are kept. Meaning that feature flags are evaluated, and the part of the @ast that cannot be compiled with the current set of feature flags is removed. For code involving feature flags, this reduces the complexity of the @ast and the amount of work the compiler must do. This step is done as early as possible to further reduce the amount of work the compiler must do. Continuing on from @lst_desug_ex, in @lst_feature_flag_ex, it can be observed that the `gain` section has been removed, assuming that the `gain` feature flag is not enabled. The comments are also removed as the parser does not include comments in the @ast. #ufigure( kind: raw, caption: [ Demonstration of feature gate checking in @phos, using the example from @lst_desug_ex. ], )[ ```phos import std::{filter, gain}; syn process_signal(signal: optical) -> optical { signal |> internal_process() } syn internal_process(signal: optical) -> optical { signal |> filter(1550 nm, 10 GHz) } ``` ] <lst_feature_flag_ex> ==== Automatic return statement In this process, all automatic return statements that are present at the end of a block are transformed into explicit return statements, such that the rest of the compiler need only look for explicit return statements. This is done to simplify subsequent compilation steps. Building on from @lst_desug_ex, one can see in @lst_return_ex that the automatic return statements have been transformed into explicit return statements. #ufigure( kind: raw, caption: [ An example used to show the desugaring of return statements, @ast expansion, and @ast validation in @phos. ], )[ ```phos import std::{filter, gain}; syn process_signal(signal: optical) -> optical { return signal |> internal_process(); } syn internal_process(signal: optical) -> optical { return signal |> filter(1550 nm, 10 GHz); } ``` ] <lst_return_ex> ==== Name resolution At this stage, the compiler has not yet resolved the path to the different items being used. Therefore, all import statements and path expressions are inlined and resolved in these steps. This means that import statements will no longer be needed or used after this process, and their absolute path will replace all relative paths to items. Additionally, it is at this stage that the compiler checks for the existence of the items being used. If they do not exist, the compiler will return an error. Continuing on from @lst_desug_ex, in @lst_name_res_ex, one can see that the import statements have been removed, and the paths to the items have been resolved, further simplifying the @ast (shown here as code for clarity). As the type `optical` is a built-in type in @phos, it does not get resolved. It is always valid. #ufigure( kind: raw, caption: [ Example of name resolution in @phos, using the example from @lst_desug_ex. ], )[ ```phos syn process_signal(signal: optical) -> optical { return signal |> self::internal_process(); } syn internal_process(signal: optical) -> optical { return signal |> std::filter(1550 nm, 10 GHz); } ``` ] <lst_name_res_ex> ==== Macro expansion Depending on the type of macros being implemented in @phos, they may be operating at the @ast level. If that were to be the case, macros would be expanded in this stage. Macro expansion refers to the compiler replacing the macro calls within the code with the output produced by the macro. This is done at this stage because the @ast has not yet been checked. Meaning that the code produced by the macro, if it were to be erroneous, would still be verified and not assumed correct. As the example in @lst_desug_ex does not contain any macros, the @ast remains unchanged. It is also important to note that @phos may benefit more from reflection-level macros rather than #gloss("ast")-level macros. This is because @phos is, at its core, a high-level language, and therefore, macro creators may be interested in also operating at a higher level of symbolic representation than the @ast. However, this is neither a requirement nor has either solution been implemented yet. Additionally, both solutions are suitable and can be implemented at the same time. ==== @ast validation @ast validation involves the process of verifying that the @ast is correct. This means that the more complex syntactic rules that were not expressed in the grammar are checked. They are checked on the @ast because it makes the grammar of the language simpler, simplifying the parser too. Additionally, it can perform basic checks based on rules. While these rules are not yet clear for @phos, they will need to be defined in the future. It is important to note that @ast validation should not involve any complex analysis, such as type checking, as these are easier to implement on the @hir. === AST lowering, type inference, and exhaustiveness checking <sec_ast_to_hir> At this point in the compilation pipeline, much of the initial complexity of the user's code has been removed. However, many critical aspects of compiling the language have not been performed yet, most notably with regard to type inference, type checking and exhaustiveness checking. These functions are all performed on the @hir, but at this point, the compiler still only has the @ast. Therefore, the first process in this step is to lower the @ast. Essentially, the compiler must transform the @ast into a lower-level, simpler form of code called the @hir. ==== @ast lowering Lowering from the @ast to the @hir requires removing all of the elements of the language that are not needed for type analysis which is the focus of this compiler step. Due to the previous step having decreased language complexity using desugaring, the @ast is already less complex. However, it still contains elements that are not needed for type analysis, such as names. Indeed, variable names, type names, etc. are only useful for humans. It is easier for a computer to understand these as numerical identifiers (IDs). Therefore, in this process, the name of all values are replaced with generated IDs. Additionally, the tree-like data structure can be flattened by using node IDs instead of pointers to nodes. This decreases the complexity of the data structure and makes traversal and, most importantly, queries easier to perform. Indeed, queries need to be performed on the @hir to find elements and apply rules for @hir to @mir lowering. ==== Type inference After lowering the @ast into the @hir, the compiler will try to infer all values' types based on existing annotation and some rules. When the compiler has inferred the type of a value, it will explicitly annotate that value with its type, that way, each value has its type known at each point in the code, such that further checks can be performed. Continuing with @lst_desug_ex, one can see what the resulting, fully annotated code would look like in @lst_type_inf_ex. It shows what the code would look like if this were valid syntax after @ast lowering and explicit type annotation. #ufigure( kind: raw, outline: [ Example of name stripping and type inference in @phos ], caption: [ Example of name stripping and type inference in @phos, showing the process of name stripping and type inference, using the example from @lst_desug_ex. All nodes are annotated with their type, and all variables, arguments, function names, etc. have been renamed with an ID shown here as `$n`, where `n` is a number. Note that this is not valid @phos syntax and is only used to illustrate the process of name stripping and type inference. In practice, the @hir would be a flattened tree-like data structure, similar to the @ast, not a textual representation. ], )[ ```phos syn $0($1: optical) -> optical { return (($1: optical) |> ($2(): optical)): optical; } syn $2($1: optical) -> optical { return (($1: optical) |> ($3((1550 nm: Wavelength), (10 GHz: Frequency)); optical)): optical; } ``` ] <lst_type_inf_ex> As with most modern programming languages with type inference, @phos will use the _Hindley-Milner_ algorithm @milner_theory_1978 @hindley_principal_1969. It is an algorithm that is capable of inferring the type of a value with little to no type annotations. This makes development easier, as less manual work of annotating types is required. Additionally, it is a convenient algorithm to use as many resources are available, and many libraries are implementing it already, meaning that the development burden caused by type inference is significantly lower. Additionally, the _Hindley-Milner_ algorithm supports polymorphism. While this feature is not yet integrated into the syntax and feature set of the @phos language, it may be of interest as it can allow more advanced types to be expressed. However, this is not a priority for the language; therefore, it is not yet designed into the language nor into the compiler architecture. ==== Exhaustiveness checking Exhaustiveness checking is the process of verifying that the user has covered all possible cases in a pattern-matching statement. This can be done with the algorithm presented by _Karachalias et al._ @karachalias_gadts_2015 @kalvoda_structural_2019. It is an algorithm that is capable of checking for pattern exhaustiveness even in very complex cases, such as when using @gadt[s], a generalised form of the previously mentioned @adt[s]. However, in the case of @phos, this task is made more complex by constraints. Indeed, the compiler tries to verify that all cases are covered, but constraints may reduce the number of cases that are valid. Take the example shown in @lst_exhaustiveness_ex: gain as a numerical value can take any value in the range $[0, infinity[$, however in this example, it can take a value only in the range $[0 "dB", 10 "dB"]$. When looking at this code, the compiler, if it does not exploit constraints, will declare that the `match` statement on line $9$ is not exhaustive, despite it being exhaustive in the context created by the constraints. To alleviate this issue, the compiler can either force the user to always be exhaustive even when it is not necessary or can exploit constraints and utilise them to improve exhaustiveness checking. This can be done in multiple ways, including using the prover to verify that all cases are covered. However, this approach is likely to be slow and difficult to implement. Others revolved around the use of refinement types and guarded recursive data type constructors @xi_guarded_2003). However, these techniques are not yet fully explored and are not yet integrated into the compiler architecture, and further research and experimentation are needed to determine which technique is the most appropriate for the @phos language. This topic is further discussed in @sec_refinement_types. #ufigure( kind: raw, outline: [ Example of exhaustiveness checking in @phos when using constraints. ], caption: [ Example of exhaustiveness checking in @phos when using constraints. In this example, the compiler should be able to detect that the `match` statement on line $9$ is exhaustive given the constraints on line $6$, but it is a difficult problem to solve and requires further research. ], )[ ```phos // Performs gain on an optical signal, depending on the gain, it will // either use a short gain section or a long gain section. syn example( signal: optical, @range(1dB, 10dB) gain: Gain, ) -> optical { match gain { 1dB..5dB => signal |> short_gain(gain), 5dB..=10dB => signal |> long_gain(gain), } } ``` ] <lst_exhaustiveness_ex> === Constant evaluation, control flow, liveness, and pipe desugaring <sec_mir_to_mir> After processing the @hir, it is reduced into an even simpler form based on a #gloss("cfg", long: true). During this stage, almost all of the elements of the language are removed. Even conditional branching is now implemented using `goto` operations. All of this is with the aim of making the code as easy to analyse as possible. From this stage, as everything has been reduced to the most basic elements, the compiler can now do some optimisation. It can compute the values of all constants and inline them where they are used. It can also perform control flow optimisations, such as performing liveness analysis, which is the process of determining which code is used and which is not and removing the parts that are not used. Finally, it can remove pipe operators, replacing them instead of function calls, performing the pattern matching at compile time. Using the aforementioned analysis, the compiler can now also detect whether all signals are being used, and if not, it can create an error for the user, indicating which part of the code is problematic. This is a useful feature of the compiler, as it enforces that all signals are at least _read-once_, which is part of the signal semantics discussed in @sec_signal_types. The way in which liveness and dead code elimination can be done is through the use of the @cfg, as it allows the compiler to easily determine which code does not contribute to the final result and, therefore, can be removed. It detects unused signals simply by checking whether any signals are used within dead code. ==== Control Flow Graph A @cfg, as the name implies, is a graph data structure that represents each operation being done as a node of the graph, with the different branches of the code being represented as edges. This means that all orphan sections are not accessed through the main entry point and can therefore be easily discarded. In @lst_cfg_ex, one can see a simple example checking whether a number is prime #link(<fig_cfg_ex>)[(a)] and its expanded version #link(<fig_cfg_ex>)[(b)]. The expanded version corresponds to an approximation of what code *equivalent* to the @mir would look like, with all types specified, the `for` loop replaced with a `goto` statement and labels. As was the case in previous examples of lower-level constructs, this code is not valid @phos and is purely for demonstration purposes. #ufigure( caption: [ @cfg created from the code in @lst_cfg_ex. It shows the different branches of the code, with the first branch relating to the iteration from `2` to `number` and the second branch relating to the `if` statement checking whether the number is divisible by `i`. It shows that each branch is made of individual statements and that the `if` and `match` statements are represented as branches with two possible outcomes. ], outline: [ @cfg created from the code in @lst_cfg_ex. ], kind: image, image( "../assets/drawio/is_even_cfg.png", width: 70%, alt: "Shows a control flow graph, showing first a block of code `let i = 2`, followed by `let iterator = 0..number`, followed by `let tmp = iterator.next()`, and `match tmp`. An arrow annotated as `none` goes to the left to a single block `return true`. An arrow annotated as `i` goes to two blocks: `let tmp2 = number % i` and `tmp == 0`. From that last block, an arrow annotated `true` goes to `return false`, and an arrow annotated `false` goes back to `let tmp = iterator.next()`.", ), ) <fig_cfg_ex> #ufigure( caption: [ The code example in @phos and code-equivalent representation of its @mir expanded version. Shows a function computing whether a number is prime before (a) and after expansion (b). The code in (b) is not valid @phos and is purely for demonstration purposes. ], outline: [ Code example in @phos and code-equivalent representation of its @mir expanded version. ], kind: raw, table(columns: 2, stroke: none, ```phos // Checks if the number is prime fn is_prime(number: int) -> bool { let i = 2; for i in 0..number { if number % i == 0 { return false; } } true } ```, ```phos // Checks if the number is prime fn is_prime(number: int) -> bool { let i: int = 2; let iterator: Iterator = 0..number; top: let tmp = iterator.next(); match tmp { i => { let tmp2: int = number % i; if tmp2 == 0 { return false; } goto top; } none => goto ret, } ret: return true; } ```, [ (a) ], [ (b) ]), ) <lst_cfg_ex> ==== Constant inlining It is at this stage of the compilation pipeline that all constants are evaluated and replaced. The reason why @phos does this step is not for performance, as in most other languages, but for simplicity. As the @vm will use a prover to verify aspects of the code in scenarios where reconfigurability is used, the code produced by the compiler must be as simple as possible to simplify this process as much as possible. For this reason, as constant evaluation is relatively easy to perform, it is done during compilation. In @lst_const_inlining, one can see a piece of code before constant inlining #link(<lst_const_inlining>)[(a)], after constant inlining #link(<lst_const_inlining>)[(b)], and after constant evaluation #link(<lst_const_inlining>)[(c)]. It also shows that operations that produce constant values within the user's code are also computed, further reducing the complexity of the code. #ufigure( caption: [ The code example in @phos shows the original code (a), the code after constant inlining (b), and the code after constant evaluation (c). These operations would normally be done in the @mir stage and, therefore, would not be visible in code, but for demonstration purposes, they are shown here as valid @phos code. ], outline: [ Code example in @phos, showing constant inlining and evaluation. ], kind: raw, block(table(columns: 3, stroke: none, ```phos const CST: int = 32; fn my_func( a: int ) -> int { a + 2 * CST + 5 } ```, ```phos fn my_func( a: int ) -> int { a + 2 * 32 + 5 } ```, ```phos fn my_func( a: int ) -> int { a + 69 } ```, [ (a) ], [ (b) ], [ (c) ])), ) <lst_const_inlining> ==== Pipe desugaring The final syntactic sugar that has yet to be simplified is the pipe operator (`|>`). This operator is used on iterable tuples to pass data from one function or synthesisable block to another easily while keeping the code readable. The pipe operator performs pattern matching on its input values and into the function arguments it is piping into. Doing so is quite difficult, which is why it is performed close to the end of all transformations. At this stage, the types are all known, and operations have been simplified to the maximum. And therefore, it is the easiest point in the compilation process for the compiler to perform this transformation. In @lst_pipe_desugaring, one can see a piece of code before pipe desugaring #link(<lst_pipe_desugaring>)[(a)] and after pipe desugaring #link(<lst_pipe_desugaring>)[(b)]. While both of these expressions are equivalent, the former is easier to read and understand. In more complex cases, where the pipe operator is used to pattern match over multiple values, this simplification is more complex. #ufigure( caption: [ The code example in @phos shows the original code (a) and the code after pipe desugaring (b). These operations would normally be done in the @mir stage and, therefore, would not be visible in code, but for demonstration purposes, they are shown here as valid @phos code. ], outline: [ Code example in @phos, showing pipe desugaring. ], kind: raw, table(columns: 2, stroke: none, ```phos // Returns the sum of all // inputs. fn sum(inputs: (int...)) -> (int, bool) { inputs |> fold(0, |acc, x| acc + x) |> map(|x| (x, x % 2 == 0)) } ```, ```phos // Returns the sum of all // inputs. fn sum(inputs: (int...)) -> (int, bool) { map( fold( inputs, 0, |acc, x| acc + x ), |x| (x, x % 2 == 0) ) } ```, [ (a) ], [ (b) ]), ) <lst_pipe_desugaring> === PHÔS bytecode <sec_mir_to_bytecode> #udefinition( footer: [ Adapted from @java_se_specs. ], )[ The *bytecode* is a binary representation of the original source code that has been processed by the compiler to be verified for correctness, simplified, and optimised. It is an executable representation, made of instructions, that can be executed by the #gloss("vm", long: true). ] From the @cfg built in the previous step, it is now relatively easy to move to a bytecode representation. This is done by replacing all simplified expressions with bytecode instructions. The bytecode of the @phos language is greatly inspired by _Java_'s bytecode @java_se_specs, with the addition of a few key features, most notably special instructions representing the intrinsic signal operations, discussed in @sec_intrinsic_operations and constraints which are added as special instructions on values. The @phos bytecode also removes some of the instructions that are not needed since @phos does not distinguish between 32-bit and 64-bit values. @phos is not object-oriented and does not need object-related information and instructions. Finally, @phos does not have a concept of exceptions and therefore does not need instructions related to exception handling. Because of these properties, the instruction set of the @phos language is fairly simple. Additionally, some instructions are more generic than in _Java_. For example, @phos does not distinguish between integer and floating-point operations and therefore has a single instruction for arithmetic operations, which can be used for both integer and floating-point values. The @phos bytecode is also stack-based, meaning that all operations are performed on a stack, and all values are pushed and popped from the stack. This will be discussed in more detail in @sec_stack_based. The full instruction set of the @phos #gloss("vm", long: true) can be found in @tbl_instruction_set. Finally, along with the bytecode, the previously built @cfg is also included, with its node now replaced with the position of the relevant instructions. The reasoning behind this inclusion is as follows: as the @vm will need to prove that some branches can be taken while others cannot, it will need to build branching information either way. Instead of having to rebuild the @cfg in the @vm, it is instead packed along with the bytecode as a means of reducing computation time. This gives a dual purpose to the @cfg, as it is used both in the compiler and in the @vm. #unote[ It is likely that as the development of the @phos language continues, the instruction set will be expanded and refined, and therefore the instruction set shown in @tbl_instruction_set may not be the final instruction set of the @phos #gloss("vm", long: true). ] #ufigure( outline: [ Instruction set of the @phos #gloss("vm", long: true). ], caption: [ Instruction set of the @phos #gloss("vm", long: true). Showing the instruction and its static arguments (i.e. arguments that are produced during compilation) and the operations that each instruction does on the stack. ], kind: table, table( columns: (0.7fr, 0.5fr, 0.8fr), align: (x, y) => if y == 0 or y == 1 { center + horizon } else { left + top }, stroke: (x: none), table.header( table.cell(rowspan: 2, smallcaps[*Instruction*]), smallcaps[*Stack operations*], table.cell(rowspan: 2, smallcaps[*Description*]), [ \[before\] #sym.arrow \[after\] ], ), ```typc call_fn[ <function_id> ] ```, ``` [ arg0, arg1, ... ] → result ```, [ Calls the function with the given ID, the arguments are obtained from the function definition and then popped from the stack, and the result of the function call is pushed onto the stack. ], ```typc call_method[ <type>, <function_id> ] ```, ``` [ arg0, arg1, ... ] → result ```, [ Calls the method with the given ID on the given type, the arguments are obtained from the function definition and then popped from the stack, and the result of the function call is pushed onto the stack. ], ```typc goto[ <label> ] ```, ``` [] → [] ```, [ Jumps to the given label. Used when branching. ], ```typc pop[ <n> ] ```, ``` [ a0, a1, ... ] → [] ```, [ Pops the given number of values `n` from the stack and discards them. ], ```typc repeat[ <n1>, <n2> ] ```, ``` [ a0, a1, ... ] → [ [a0, a1, ... ], [a0, a1, ...] , ... ] ```, [ Repeats the `n2` top values of the stack `n1` times and pushes the result onto the stack. ], ```typc const[ <value> ] ```, ``` [] → [ <value> ] ```, align( horizon, )[ Pushes the given constant value onto the stack, can be an `int/uint`, a `float`, a `bool`, a `string`, a `char`, a `complex`, or a function, which are used for passing closures to other functions. ], ```typc return[] ```, ``` [ a0, a1, ... ] → [] ```, align( horizon, )[ Returns from the current function, popping all of the remaining values from the stack and returning them as a tuple. If the stack is empty, it returns an empty tuple, which is equivalent to the `none` value. ], ```typc none[] ```, ``` [] → [ none ] ```, [ Pushes the `none` value onto the stack. ], ```typc load[ <id> ] ```, ``` [] → [ a0, a1, ..., len ] ```, align( horizon, )[ Loads the value with the given local variable ID onto the stack. If it is a tuple, it expands the tuple into `len` values on the stack and pushes the tuple length onto the stack. The first `n` local variables are reserved for the arguments of the function, where `n` is the number of arguments of the function. ], ```typc store[ <id>, ] ```, ``` [ a0, a1, ..., len ] → [] ```, [ Stores the top `len` values of the stack into the local variable with the given ID. If `len` is more than one, then store them as a tuple. The first `n` local variables are reserved for the arguments of the function, where `n` is the number of arguments of the function. ], ```typc get[ <type_id>, <field_id> ] ```, ``` [ instance ] → [ a0, a1, ..., len ] ```, [ Gets the field with the given ID `field_id` from the given type `type_id`, and pushes it onto the stack. If it is a tuple, expands the tuple into `len` values on the stack, also pushes the `len` of the tuple onto the stack. Pops the instance of the type from the stack. ], ```typc push[ <type_id>, <field_id>, ], ```, ``` [ instance, a0, a1, ..., len ] → [ ] ```, [ Stores the top `len` elements from the stack into the field with the given ID `field_id` from the given type `type_id`. If it is a tuple, expands the tuple into `len` values on the stack. Pops the instance of the type from the stack. ], ```typc new[ <type_id>, <variant_id>, ], ```, ``` [ a0, a1, ... ] → [ instance ] ```, align( horizon, )[ Creates a new instance of the variant `variant_id` of given type `type_id`, and pushes it onto the stack. The arguments are obtained from the type definition, and then popped from the stack. For structs, the `variant_id` are ignored. ], ```typc branch[ <false_offset> ] ```, ``` [ a0, ] → [] ```, align( horizon, )[ Takes the top value from the stack, if it is `false`, then jumps to the given offset. Otherwise, continues execution at the next instruction. ], ```typc flag[ <flag> ], ```, ``` [] → [] ```, align( horizon, )[ Gets the given flag, and pushes it onto the stack as a boolean value. The flags are produced by the previous operation. The valid flags are `overflow`, `underflow`, `div_by_zero`, `invalid`, `inexact`, `unimplemented`, `unreachable`. Used for branching. ], ```typc unary[ <op> ] ```, ``` [ a0, ] → [ a1 ] ```, align( horizon, )[ Takes the top value from the stack, applies the given unary operator `op` to it, and pushes the result onto the stack. The valid unary operations are numerical negation (`-`), logical negation (`!`), and bitwise negation (`~`). ], ```typc binary[ <op> ] ```, ``` [ a0, a1 ] → [ a2 ] ```, align( horizon, )[ Takes the top two values from the stack, applies the given binary operator `op` to them, and pushes the result onto the stack. The valid binary operations are addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), modulo (`%`), exponentiation (`**`), bitwise and (`&`), bitwise or (`|`), bitwise xor (`^`), bitwise left shift (`<<`), bitwise right shift (`>>`), equality (`==`), inequality (`!=`), less than (`<`), less than or equal (`<=`), greater than (`>`), greater than or equal (`>=`), logical and (`&&`), and logical or (`||`). ], ```typc cast[ <type_id> ] ```, ``` [ a0, ] → [ a1 ] ```, align( horizon, )[ Takes the top value from the stack, cast it to the given type `type_id`, and pushes the result onto the stack. The valid conversions are `int`, `uint`, `float`, `bool`, `string`, `char`, and `complex`. Only primitive values may be converted in this way. ], ```typc insert[] ```, ``` [ value, offset, len ] -> [ ... ] ```, align( horizon, )[ Inserts the given `value` into the stack at the given `offset`, `len` times. This allows the insertion of values into the middle of the stack, as well as interspersing values into the stack. ], ```typc intrinsic[ <intr> ] ```, ``` [ a0, a1, ... ] → [ a2, a3, ... ] ```, [ Execute the given photonic intrinsic operation `intr`, see @sec_intrinsic_operations, based on the intrinsic value, pops the arguments from the stack, and pushes the result onto the stack. ], ```typc constraint[ <constr> ] ```, ``` [ signal, a0, a1, ... ] → [ ] ```, [ Applies the given photonic constraint `constr`, see @sec_constraints, based on the constraint value, pops the arguments from the stack, and pushes the result onto the `signal`. ], ), ) <tbl_instruction_set> === Compiler complexity <sec_comp_complexity> As one can see from the previous sections, the @phos compiler is more complex than one might expect. However, there are good reasons why the compiler is so complex. A lot of the features that have been discussed in @sec_intent and in this chapter are rather difficult to implement. They require a lot of modern features and tight coupling with provers for constraints and intrinsic. These tasks are not easy in isolation, but when they are combined, they become even more difficult to implement. When taking this into account, the complexity of the compiler is not that surprising. Essentially, the compiler simplifies the code as much as reasonably possible, such that the resulting bytecode is easy to interpret and execute, easy to collect stacks for tunable values, and such that it is easy to process using a prover. Additionally, this complexity makes the compiler modular, which allows for easy extension and rework of the language, something that will need to be done as the language evolves. #uconclusion[ The @phos compiler translates source code into a bytecode format used by the @vm for evaluation. It first turns the code into a computer-understandable representation called the @ast. Then the @ast goes through three transformation stages. Called the @hir, the @mir, and finally, the bytecode. ] == The virtual machine <sec_vm> After investigating the components and stages of the compiler, the analysis of the #gloss("vm", long: true) can proceed. Recalling the execution model of @phos, discussed in @sec_exec_model, the role that the @vm fills is the evaluation of the bytecode. Therefore, the behaviour of the virtual machine is discussed, including how the @vm works, how it uses a stack for computation, and how it executes the bytecode. Additionally, the section discusses the result of the evaluation, namely, the tree of intrinsic operations, collected stacks, and constraints. However, the suitability of existing virtual machines must also be discussed, as it is important to understand why an existing virtual machine was not used. === Why not use an existing VM? <sec_existing_vm> One may wonder why @phos does not use an existing virtual machine and requires a custom-built one. The reason for this is that existing @vm[s] are not suitable for the semantics and execution model of @phos. This can be explained by looking at the artefacts produced by the execution process, previously shown in @fig_exec_model. It must produce three components, all of which would be hard, if not impossible, to properly extract and process within an existing implementation. ==== Stack collection One of the key functions of the virtual machine is to detect which parts of the code cannot be evaluated based on tunable values, as was discussed in @sec_tunability_reconfigurability and collect them to be included in the user @hal. This requires tight integration in the @vm, as it must support doing partial computation and collect all of the instructions it cannot execute. This is not a feature that is supported by any existing @vm that was investigated, and it would be difficult to implement in an existing @vm. ==== Constraints and intrinsic Another feature of the @phos @vm is the ability to collect constraints and intrinsic operations and to produce a tree of these values, representing the signal flow of the circuit. While this can be implemented in a traditional language, it would require an extensive library to be included along with the bytecode, which would make the bytecode harder to generate. Additionally, this means that these operations would no longer be expressed as dedicated bytecode instructions but rather as regular function calls, tightly coupling the aforementioned library and the bytecode, significantly increasing the burden of maintenance and development of the language. ==== Simplicity Existing @vm[s] often support many features that are simply not needed for @phos, such as object-oriented programming or memory recollection schemes like garbage collection. @phos is not a general-purpose language and as such, can work with a limited set of features. This means that the complexity of the @vm can be significantly reduced to only contain the elements relevant to @phos. This can help improve performance and reduce the size of the @vm, making it easier to distribute to users. ==== Licensing Finally, existing @vm[s] may be subject to licenses. While intellectual property has not been discussed in this document, it is essential to be aware of issues that can arise when using other people's code or, more generally, intellectual property. Therefore, if the @vm is written from scratch, it can be licensed in a way that is compatible with the @phos license, whichever that may be. === Stack-based architecture <sec_stack_based> #udefinition( footer: [ Adapted from @cormen_introduction_2009. ], )[ A *stack* is a data structure that follows the last-in-first-out (LIFO) principle. This means that the last element that was added to the stack is the first one to be removed. Stacks usually only implement two operations: `pop` to remove the last element and `push` to add an element to the top of the stack. ] So far, the mention of the _stack_ has been made several times. However, no clear definition has been provided. This definition, along with the reasoning behind the choice of a stack-based architecture, is discussed in this section. The stack is a data structure that holds the values required during the evaluation of a given block of code. The stack is used to store all intermediary values needed for computation. When a new value is needed, it is pushed onto the stack, and when a bytecode instruction is executed, full list in @sec_mir_to_bytecode, the instruction pops the elements that it needs from the stack, processes them, and once it is done, it pushes all of the output values to the stack again. Later on in this section, an example is provided showing the execution of a simple function. The stack is convenient because it can be very effectively implemented; it is a common data structure that is easy to implement and very fast. Additionally, it means that all short-lived values are stored inline and do not require any additional memory allocation. This is important, as it means that the @vm does not need to implement a garbage collector, which would be a significant burden on the development of the @vm. Furthermore, the stack also plays very nicely with the automatic memory management scheme used by _Rust_ -- the language in which @phos will be implemented -- as it allows values that are removed from the stack and no longer used to be automatically discarded, further simplifying the implementation of the @vm. One of the special aspects of the @phos @vm that one may notice from the list of instructions in @sec_mir_to_bytecode is that arrays of values in @phos are all pushed to the stack and that @phos allows for quite complex operations on the stack. The reasoning behind this decision is to make the @vm very powerful and to be able to express complex operations in relatively few instructions. This allows the work of the user @hal generator, discussed in @sec_hal, to be even easier. It also means that fewer instructions must be provided to the prover for branch elimination and constraint checking. Therefore the interface between the prover and the @vm will be easier to create. === Signals, constraints, and intrinsics As previously mentioned, one of the tasks of the @vm is to collect the different intrinsic operations and their constraints to build a tree representing the signal processing. This is done through the `intrinsic` and `constraint` instructions. These special instructions take signals and arguments, and instead of only pushing results to the stack, they also can internally add information to a global tree of signals. This is done transparently for the user and is how the @vm can store these signals. In @lst_tree_ex, one can see a simple program splitting, filtering and then adding gain to a signal. Then in @fig_tree_ex, one can see the signal processing tree with the added constraints. In cases where reconfigurability would also be present, collected stacks would also be appended to a special reconfigurability node, which would be used to differentiate the different configurations of the circuit. #block( breakable: false, )[ #table( columns: 2, stroke: none, )[ #ufigure( caption: [ Code example in @phos, showing a simple photonic circuit splitting a signal, then filtering both signals and finally adding gain to one of the signals. ], outline: [ Code example in @phos, showing the signal processing tree. ], kind: raw, )[ ```phos // Processes a signal by splitting it and // filtering one of the split branches. syn process( input: optional ) -> (optical, optical) { input |> split((0.5, 0.5)) |> map(filter(1550 nm, 10 GHz)) |> (_, gain(10 dB)) } ``` ] <lst_tree_ex> ][ #ufigure( caption: [ The signal flow diagram of @lst_tree_ex shows the splitting of the input signal, followed by the filtering of both signals, and finally, the gain of one of the signals. The green boxes represent the intrinsic operations, the blue boxes represent the constraints, and the arrows represent the flow of the signal. ], outline: [ Signal flow diagram of @lst_tree_ex. ], kind: image, )[ #image( "../assets/drawio/signal_proc.png", alt: "Shows a tree of signals, at the top is input, followed by splitter, the first branch shows a filter with a wavelength constraint, and the second branch shows a filter with a wavelength constraint followed by a gain", ) ]<fig_tree_ex> ] ] === Example of bytecode execution <sec_ex_bytecode_exec> In this section, a simple example of code will be shown, along with its resulting bytecode. The code is shown in @lst_bytecode_example (a), and the resulting bytecode is shown in @lst_bytecode_example (b). The function being compiled is a simple accumulating sum that also computes whether the sum is even or not. In (b), one can see the bytecode contains a total of $22$ instructions. The instructions would be purely binary values. However, they are shown as text for convenience and readability. One can see that the two closures at line $5$ and $6$ were respectively turned into two anonymous functions called `__anonym_0` and `__anonym_1`, normally these would have numeric IDs instead of names, but names are provided for clarity. This code uses the `load`, `pop`, `binary`, `return`, `repeat`, `const` and `call_fn` instructions, which can all be found in the previously shown @tbl_instruction_set. An example of execution and the state of the stack will now be shown. The function `sum` will be called with the iterable tuple `(1, 2, 3, 4, 5)`. The execution diagram of the `sum` function can be seen in @anx_bytecode_execution, in @fig_annex_execution. It shows the stack after each step of the execution of the function. It also gives symbolic meaning to the values, showing integers as `int(x)`, length as `len(x)`, and functions as `fn(x)`. From this figure, one can see that the `load` instruction pushes all of the argument `inputs` values onto the stack, followed by the length of the argument $5$ in this case. Then, when constants are pushed, the whole stack moves up, and a new value is added. When calling functions, the whole stack is consumed, and the result is pushed onto the stack. The `pop` instruction is used to remove the top value from the stack, and the `return` instruction is used to return the top values from the stack. Additionally, one can see that the `const[ 1 ]` being performed is used to add the length of the argument before calling `map`. This is because map expects an iterable tuple as an input, and produces an iterable tuple. The result of this execution is then returned with the tuple `(15, false)`. #block( breakable: false, )[ #ufigure( caption: [ Code example in @phos, showing the original code (a), and the bytecode after compilation (b). The bytecode would normally be, as the name implies, binary. However, here it is shown in a textual format for clarity. ], outline: [ Code example in @phos, showing original code and resulting bytecode. ], kind: raw, )[ #table(columns: 2, stroke: none, ```phos // Returns the sum of all inputs, // also returns true if the sum is even fn sum(inputs: (int...)) -> (int, bool) { inputs |> fold(0, |acc, x| acc + x) |> map(|x| (x, x % 2 == 0)) } ```, ```typc fn @__anonym_0(@0: int, @1: int) -> int: load[ @0 ] pop[ 1 ] load[ @1 ] pop[ 1 ] binary[ + ] return[] fn @__anonym_1(@0: int) -> (int, bool): load[ @0 ] pop[ 1 ] repeat[1, 1] const[ 2 ] binary[ % ] const[ 0 ] binary[ =​= ] return[] fn @sum(@0: (int...)) -> (int, bool): load[ @0 ] const[ 0 ] const[ @__anonym_0 ] call_fn[ @fold ] const[ 1 ] const[ @__anonym_1 ] call_fn[ @map ] pop[ 1 ] return[] ```, [ (a) ], [ (b) ]) ] <lst_bytecode_example> ] === Partial evaluation <sec_partial_eval> #udefinition( footer: [ Adapted from @jones_partial_1993 ], )[ *Partial evaluation* is a technique for specialising a program with respect to some of its arguments. The result is a new program that only requires the remaining arguments to run. The new program is generally smaller. ] It has been shown that the @vm executes bytecode. However, one may wonder how the @vm handles tunable values. The answer is that the @vm will use _partial evaluation_. Meaning that the @vm will collect the code impacted by the tunable values and will try and evaluate as much of the code as possible while leaving the code. It cannot evaluate as is. This means that the @vm will produce a new program that performs the same functionality as the user's original program but is specialised based on the static inputs, needing only the tunable values as inputs for it to be complete. Additionally, it will still analyse the intrinsic operations -- impacted by tunability -- present within the user's design and collect them separately so that they can still be synthesised. These operations also depend on tunable values, but using the constraints on those tunable values, if any, the compiler will still be capable, in most cases, of synthesising them into a photonic mesh. This will allow the @vm to produce a special subtree of the signal flow tree, which represents tunable sections and their intrinsic operations and constraints but requires tunable values for finalisation. ==== Tunability failures In some cases, if tunable values are not sufficiently constrained, the synthesis of these components may fail. In such cases, the user will be invited to provide more constraints, such that the synthesiser can produce the photonic mesh for the given intrinsic operation. If, however, the user were not to be able to provide these additional constraints, they would need to rework their design either to avoid the use of broad range tunable values or to be able to provide the additional constraints. Therefore, one may understand tunable values as a tool to help the user tune their photonic circuit but not as a tool for broad-range reconfiguration. ==== Broad-range reconfiguration As previously mentioned, if tunability has failed, the user must be able to constrain their tunability values more, in some cases, this may prove difficult. However, @phos also provides the ability of creating reconfigurability regions, which are regions of the photonic circuit that can be reconfigured. The way in which the user may be able to constrain their tunable values, is by using reconfigurability regions. If they can partially constrain their tunable values, such that it can be used for reconfigurability, in addition to tunability, then the synthesiser will be able to produce a photonic mesh for their design. Looking at @lst_broad_ex, in (a), one can see a circuit that relies on broad-range reconfigurability if parameter `gain` is not constrained, and the platform only supports a short gain section in the range $[0"dB"..5"dB"]$, or a long gain section in the range $]5"dB", 10"dB"]$, the synthesiser will fail to make the circuit. However, if the user were to constrain the `gain` in the range supported by the platform then match on the gain to create either a `short_gain` section or a `long_gain` section, the code would be synthesisable, this second case is shown in (b). However, when looking at this code (b), one might think that it is much longer than the original code (a), however, most of this complexity would actually be contained within the standard library, and the user would only need to add the `range` constraint on their gain to match their platform's capabilities. #ufigure( caption: [ Code example in @phos, showing the original unsynthesisable code (a), and the fixed code (b) ], kind: raw, )[ #table(columns: 2, stroke: none, ```phos syn my_module( input: signal, the_gain: Gain ) -> signal { input |> gain(the_gain) } ```, ```phos syn my_module( input: signal, @range(0 dB ..= 10 dB) the_gain: Gain ) -> signal { match the_gain { 0 dB..=5 dB => input |> short_gain(the_gain), 5 dB..=10 dB => input |> long_gain(the_gain), } } ```, [ (a) ], [ (b) ]) ] <lst_broad_ex> == Synthesis <sec_synthesis> Now that the first two steps in the overall synthesis of a @phos design, namely compilation and evaluation, have been explained, the last step is to synthesise the design. This step is likely to be the most complex, and a lot of work is still needed both at the design stage, and at the algorithm stage. However, the goal of this section is to explain the general idea behind the synthesis of a @phos design. Therefore, this section can be assumed to be less precise and formal than previous ones, focusing more on overall ideas and concepts, rather than on specific details. The core goal of the synthesis stage is to take the signal flow tree produced by the @vm and turn it into two things: the user @hal that the user can use to interact with their design and the binary programming files used by the actual hardware. These two goals are very different, and the simplest is the generation of the user @hal. Generating the binary programming files requires processing all of the constraints and intrinsics into gate descriptions, then placing them on the chip and routing between them. This is a problem that is already incredibly difficult for traditional @fpga[s] to solve, but it is exacerbated by both the two modes that can be supported in waveguides also by the recirculating hexagonal nature of the mesh. Therefore, the synthesis of a @phos design is incredibly difficult and computationally expensive and is still an active area of research. Among the ongoing work that has been happening, including at the @prg, the modelling of the circuit meshes in a graph structure has been done @chen_graph_2020. In @fig_graph_representation, one can see the graph representation of a single photonic gate and a junction in a hexagonal photonic mesh, and in @fig_graph_representation_mesh, one can see a set of gates in a mesh. In their work, _<NAME> et al._ show that by incorporating relevant metrics in the mesh edges, they can achieve efficient routing in a photonic mesh. This is a very promising result and can be used as the basis for future research. Indeed, research is already ongoing at Ghent University to further this routing. However, they are not yet at the point of incorporating more complex photonic components inside of the mesh @kerchove_adapting_2022. Other work has implemented the automatic realisation of circuits on photonic meshes, which is closer to what is needed for synthesis, but it is still incomplete @gao_automatic_2022. #ufigure( outline: [ Graph representation of a single photonic element. ], caption: [ Graph representation of a single photonic gate (a) and of a complete junction in a photonic mesh (b). Based on the work of _<NAME> et al._ @chen_graph_2020. (b) is composed of three unit cells shown in (a), showing the direction that light is travelling in and all of the possible connections. ], kind: image, table( columns: 2, stroke: none, image("../assets/drawio/graph_representation.png", height: 160pt), f(160pt), [ (a) ], [ (b) ], ), ) <fig_graph_representation> === From intrinsic operations to gates The first step in synthesising the circuit, is determining for each intrinsic operation being done in the circuit, what gates are required to implement it. Some intrinsics have one-to-one mapping with photonic gates, such as phase shifters, splitters, and couplers, for these this tasks should be relatively easy. However, other intrinsic operations, such as modulators, detectors, and sources are not part of the mesh and are, in fact, components placed on the edges of the mesh. Finally, other intrinsic operations are actually compounded operations, that can result in more than one photonic gate. This means that each type of intrinsic operation, will need to be decomposed into their component photonic gates. Some of them, such as edge devices, do not need to become a specific gate, rather they need to be assigned a location, such that they can be routed to during place-and-route. ==== Filter synthesis Filters are purposefully made into their own intrinsic operation despite being compound components. As was explained in @sec_intrinsic_operations, filters may be optimised based on the platform, for example, some platforms may even have built-in tunable filters placed on the edge. Therefore, the platform is responsible for the synthesis of the filters. As the synthesiser is provided with the input wavelength constraint, and the expected wavelength response, wether it be a bandpass filter, or any other filter, it should be able to synthesise the filter into its component gates. In some cases, it is possible that filter synthesis might fail, in such cases, the synthesiser should produce an error for the user. ==== Tunability At this point, some components may depend on tunable values, nonetheless, the synthesis tool must be capable of handling tunable components. Meaning that it must understand that components are tunable within a certain range, indicated with constraints, and still produce the appropriate gates. This task should generally be relatively similar to regular intrinsic-to-gate translation, assuming that the parts of the standard library implemented for the platform were done correctly. Indeed, the task of separating widely tunable values into smaller tunable ranges, is in parts, the task of the designer, in other parts, the task of the standard library as it is implemented by the chip designer. This means that, at this point in the synthesis pipeline, all tunable intrinsic operations should be synthesisable. If they are not, then the platform-support package would be to blame, since it would mean that its implementation of the standard library is invalid. === Place-and-route <sec_place_and_route> As was previously discussed, there are currently no algorithms that can place and route all of the components that can be present in a mesh. Since @phos provides the constraints on each signals to the place-and-route engine, it is expected that it will utilize those constraints to improve its placement and routing. Furthermore, the place-and-route algorithm will be provided by optimisation targets by the user, these targets should be an indication of what matters most for the user: the area that a given circuit occupies, the power consumed by the circuit, or the optical losses in the circuits. Additionally, in some cases, the user may want to create their own metric for further customization. Finally, despite there being no place-and-route algorithm, there are a number of routing algorithms that are being developed, including at Ghent University, which are showing promising results @kerchove_automated_2023. Once routing has been improved, these algorithms may be able to be included in place-and-route implementations. === Hardware abstraction library <sec_hal> Another task of the synthesiser is to generate the user @hal. To do this, it will use pre-made routine, that have yet to be designed, coupled with the platform-support package, which will provide information with regards to interconnecting the generated, high-level user @hal and the low-level core @hal provided my the chip designer. This task is expected to be relatively simple, as it is mostly a matter of connecting the dots between the two @hal. Additionally, the user @hal would be generated in _Rust_, in a way that is compatible with #gloss("ffi", long: true) for interoperability with _C_ and _C++_. #uconclusion[ At this point, little is known about the exact way that the synthesiser will work, however, this section has hopefully provided pointers that may be used in future research for the implementation of this stage. ] == Constraint solver and provers <sec_constraint_solver> In the previous sections, the mention of the constraint solver and of the use of a prover has been discussed extensively. However, the exact way in which these tools will be used has not been discussed. This section will attempt to provide a brief overview of the way that these tools will be used. First, the constraint solver will be discussed, followed by the prover. === Constraint solver The constraint solver is a software that can, given a set of intrinsic operations and constraints, solve the state of a signal at any point in the signal chain. It does this in one of two modes: in frequency domain analysis, it will only look at a subset of relevant intrinsic, and compute the spectrum at each step of the signal chain. In time domain analysis, it will process complex amplitude signals modulated onto carrier wavelength, and at each time $t$, it will process the effect that each constraint has on the signal. ==== Limitations of frequency domain analysis In frequency domain mode, the constraint solver must have the values of all tunable values set before it starts executing. This is because, for proper frequency domain analysis, the system must be time invariant, meaning that it must be in steady state. While it is possible, assuming slow varying tunable values, to perform frequency domain analysis, it is currently not planned, and the constraint solver is not yet designed with this in mind. ==== Co-simulation Through the marshalling layers, which will be discussed in @sec_marshalling, the constraint solver will be able to communicate with user code, in order to co-simulate both the user's software, and the user's photonic design. This will allow the user to test their design programmatically rather than manually. This will also allow the user to simulate tunability and reconfigurability. ==== Simulating tunability The constraint solver is capable of simulating tunability in the time domain, by updating the signal flow graph based on the tunable values, it can easily reflect any changes in the tunable values. This can be leverage, in combination with co-simulation, to test whether the user's feedback loops work as intended. Allowing simulation and verification of the overall design, rather than just parts of it. All of the values that might still need to be computed, can be done using the @vm, since the @vm produces a partially evaluated bytecode, the constraint solver only needs to provide the @vm with the values of the tunable values to obtain the signal flow graph. === Prover #udefinition( footer: [ Adapted from @z3prover. ], )[ *#gloss("smt", short: true) problems* are decision problems of logical formulas with respect to combinations of background theories. This means that it verifies whether mathematical formulas are satisfiable. ] Theorem provers like _Z3_ are called @smt provers, they can be provided with set of theories and rules and verify whether they are satisfied @z3prover. Provers like _Z3_ are especially well suited for program verification, which is the area of interest in this thesis. In the case of @phos, the prover is expected to be used for multiple areas: verifying constraint compatibility, verifying that tunable code respects constraints, verifying exhaustiveness of pattern matches, and determining which reconfigurability branches are reachable. In the following sections, each of these use cases will be discussed. #unote[ The features discussed in this section are all complex, and while they may appear simple on the surface, translating them into @smt[s] is a complex task, and will require further research. ] ==== Constraint compatibility A prover can express the mathematical relations between constraints; this means that a prover like _Z3_ can be used to check whether two constraints are compatible. This would be used as part of the compilation and evaluation processes. ==== Tunable code Tunable code is turned into a partially evaluated program, as discussed in @sec_partial_eval, these programs can be fed into a prover, which can verify whether the program, irrespective of its inputs, respects the constraints that were provided to it. This would be used as part of the evaluation process. ==== Exhaustiveness As was discussed, when presented with constraints, it is very difficult for the compiler to verify exhaustiveness, however, a prover can be used to verify whether a pattern matching expression is exhaustive given a set of constraints. This would be used as part of the compilation process. ==== Reachability The evaluation stage, when encountering tunability, may have more reconfigurability states than needed given the current constraints. Just like with exhaustiveness checking, a prover can be used to verify whether branches are even reachable. If they are not, then they can safely be discarded, and the synthesiser will have less work to perform. == Marshalling library <sec_marshalling> Now that all of the synthesis steps of the @phos programming language have been discussed, one must now focus on interoperating all of these components. As well as how @phos can leverage existing software. This section will discuss the marshalling library, which is the component that will be used to interconnect all of the elements of the @phos ecosystem. ==== What's in a name? Marshalling is a term used in Computer Science to describe the transforming of representation of objects into formats suitable for transmission @marshalling_cs. Indeed, in the case of @phos, the marshalling library will be used to move data around between the different step, but also be used to allow the user to configure each step in the synthesis chain to their requirements. In that way, it performs both the traditional marshalling role -- that of assembling and arranging @marshalling -- but also the Computer Science term of transforming and moving data. Therefore, the goal of the marshalling library is to facilitate moving the data around the different pieces of the @phos ecosystem in a programmatic way. Thinking back to the ecosystem analysis performed in @sec_programming_photonic_processors, this is a replacement to the build tools and the compiler. Offering ways for the user to programmatically and dynamically configure the different steps of the synthesis chain. #ufigure( outline: [ Overview of the marshalling library. ], caption: [ Overview of the marshalling library, it shows all of the different components of the synthesis toolchain of @phos, and how they are interconnected using the marshalling library. Additionally, it also shows the simulation stage, which would couple user simulation code with the simulator. Below the marshalling library are all of the common components that do no belong to one particular stage of the synthesis toolchain. The color scheme used in the same as the one used in @fig_responsibilities: blue represents the responsibility of the chip designer, orange the responsibility of the ecosystem developer, green the responsibility of the user, and purple are external tools. ], image( "../assets/drawio/programming.png", width: 100%, alt: "Shows the different components of the ecosystem, including the simulation, all interconnected using the marshalling library.", ), ) <fig_marshalling> ==== Overview In @fig_marshalling, one can see the overview of the entire toolchain proposed in this thesis, it shows all of the different components that have been discussed so far, all interconnected using the marshalling library. It shows that all components are interconnected through this library, and that the marshalling library is the only component that is aware of all of the other components. Additionally, the marshalling library provides all of the data required by a given component to perform its task, this means that the user should easily be able to intercept the data, and modify it to their needs. This is the primary advantage of the marshalling library: providing an easy way of communicating, configuring, and tuning the synthesis process. ==== Choice of language During the discussion on ecosystems, in @sec_programming_photonic_processors, _Python_ was shown to be a good candidate as a language to create libraries in, and as such, _Python_ is a good candidate for writing the marshalling library in. As the marshalling library is not a performance critical section, nor expected to be particularly complex, it can be written in _Python_ such that the user can easily script the synthesis toolchain, using a common academic language. #pagebreak(weak: true) === Example <sec_modularity> #uinfo[ The marshalling library does not exist yet, therefore this example is a mockup of what the final library may look like, and how it may be used. ] Due to its length, the code of this example is shown in @anx_marshalling_library_example, where the @phos code being simulated is shown in @lst_marshalling_phos, the code to build the modulate into a programmable form is in @lst_marshalling_comp, and the code to simulate the modulator is in @lst_marshalling_sim. In this example, a simple @phos circuit is being built, it consists of a splitter of which one of its outputs is modulated by a @prbs 12-bit sequence. In @fig_marshalling_sim, one can see the result of the simulation code, showing the modulate output in blue, and the unmodulated output in orange. One can see that the noise source is applied to both signals, but that the modulated signal is modulated by the @prbs sequence. Additionally, the circuit can be seen in @fig_marshalling_circ, showing the generated mesh on a rather large chip, showing the ports, the modulator, and the splitter. On that figure, one can also see that the place-and-route engine may utilize the two modes of the waveguides to perform more efficient routing. In practice, when looking @fig_marshalling_circ, one may notice that the losses experienced by the modulated signals, which should be significantly higher, are not modeled in the simulation shown. ==== Synthesis One can see in @lst_marshalling_comp, that the user starts by importing the marshalling library `phos` (line $#2$), and their device support package `prg_device` (line $#5$) -- a fictitious device from the @prg. A device instant is then created from the `phos` library and the device support package (line $#8$). From this, the module can be loaded from its `phos` file. Moving on to the creation of the inputs and outputs (I/O) of the device (lines $#14-#17$), the electrical input is created, with its device-specific identifier being $0$. Then, each of the three optical ports are created, depending on whether they are used as inputs, outputs, their remaining port is discarded. Here as well, the device-specific ID is being used. The reason why device-specific IDs are being used is to assign the ports of the device to the logical ports of the module. Then, the module is instantiated, given a name, and all of its inputs and outputs are assigned. It can then finally be synthesised. In a real design, one would likely specify more parameters and more than one module, indeed, the marshalling library can be used to compose modules together, and to synthesise more than one module. In this example, the synthesis stage has only one parameter set, the optimisation of the design set to area optimisation. Finally, from the synthesised design, the user @hal and programming files can be generated. ==== Simulation This example shows that a @prbs sequence is generated in a _Numpy_ array, it shows one of the core goals of the marshalling library: broad compatibility with the existing _Python_ ecosystem. A simulator is then created from the device, a noise source and a laser source are created, from which the design can be simulated using the previously instantiated module. This runs the simulation, and the result can be plotted using libraries such as _Matplotlib_, giving the result seen in @fig_marshalling_sim. #ufigure( outline: [ Simulation results of the marshalling layer example. ], caption: [ Simulation results of the marshalling layer example, showing the output of the modulator, and the output directly from the splitter. The output of the modulator is the same as the output of the splitter, but with the PRBS sequence modulated onto it. ], image("../assets/simu_marshalling_ex.svg", width: 100%, alt: ""), ) <fig_marshalling_sim> #uconclusion[ The marshalling library aims at providing an easy-to-use, productive interface for configuring, synthesising, and simulating @phos circuits. Through the use of a _Python_ @api, it makes it easy for people with relatively little programming knowledge to get started. Finally, its ability to reuse existing libraries from the _Python_ ecosystem makes it easy to integrate into *existing workflows*. ]
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/knowledge/determinants.typ
typst
#import "../cfg.typ": cfg #show: cfg = Determinants A function $f$ is linear $:= f(alpha a + beta b) = alpha op(f) a + beta op(f) b$. $abs({f in (F^m)^(F^n) mid(|) f "is linear"}) = hash thick m times n$ matrixes. $forall$ linear function $f in (F^m)^(F^n): op(f) X = sum_(j = 1)^n x_j op(f) E^((j))$. A function is multilinear $:=$ it's linear in each argument. A function is symmectric $:=$ it changes its sign when any two arguments are permuted. A function is skew-symmetric $<->$ it $= 0$ when any two arguments are equal. A function $f$ is a determinant $:=$ + $f$ is a multilinear skew-symmetric function of matrix rows. + $op(f) E = 1$. $det A = sum_pi a_(1 pi_1) ... a_(n pi_n) op("sgn") pi$. $forall$ multilinear skew-symmetric function $f$ on a set of square matrixes $: op(f) A = f(E) det A$. $forall$ square matrixes $A, B$ of the same order $: det(A B) = det(A) det(B)$. $forall$ nonsingular square matrix $A: det(A^(-1)) = det(A)^(-1)$. $forall$ square matrixes $B, C: det mat(B, D; 0, C) = det(B) det(C)$. The Vandermonde's determinant $:= mat(delim: "|", 1, x_1, x_1^2, ..., x_1^(n - 1); 1, x_2, x_2^2, ..., x_2^(n - 1); dots.v, dots.v, dots.v, dots.down, dots.v; 1, x_n, x_n^2, ..., x_n^(n - 1); )$. The Vandermonde's determinant $= product_(i > j) (x_i - x_j)$. A matrix $A$ is skew-symmetric $:= A^T = -A$. A minor of an order $k$ of a matrix $A :=$ a determinant of a square submatrix of the order $k$. An additional minor of an element $a_(i j) := M_(i j) :=$ a minor obtained by deleting the $i$-th raw and the $j$-th column. A cofactor of an element $a_(i j) := A_(i j) := (-1)^(i + j) M_(i j)$. A bordering minor $:=$ a minor obtained by attaching a row and a column. The Kronecker symbol $:= delta_(i j) := cases(1 "if" i = j, 0)$. $sum_k a_(k i) A_(k j) = sum_k a_(i k) A_(j k) = delta_(i j) det A$.
https://github.com/yankydoo/repro-typst-stroke-issue
https://raw.githubusercontent.com/yankydoo/repro-typst-stroke-issue/main/README.md
markdown
# Minimal Reproduction for Stroke Artifacts issue Execute `typst compile repro.typ --font-path ./fonts` to generate repro.pdf.
https://github.com/DaAlbrecht/thesis-TEKO
https://raw.githubusercontent.com/DaAlbrecht/thesis-TEKO/main/content/Introduction.typ
typst
In the present thesis, a solution is developed to facilitate the retransmission of messages within a RabbitMQ infrastructure, specifically within an append-only queue. Numerous clients of Integon rely upon RabbitMQ as their designated message broker, necessitating the capability to replay messages in the event of an error or system anomaly. The visual representation provided below in @append_only_queue elaborates on the fundamental concept of an append-only queue. #figure( image("../assets/append_only_queue.png", width: 80%), caption: "Append only queue", )<append_only_queue> The subsequent @append_only_queue_replay, presented below, visually shows the desired state, illustrating the incorporation of a mechanism for the message replaying. #figure( image("../assets/replay_message.png", width: 80%), caption: "Append only queue with replay", )<append_only_queue_replay> #pagebreak()
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-FFF0.typ
typst
Apache License 2.0
#let data = ( "9": ("INTERLINEAR ANNOTATION ANCHOR", "Cf", 0), "a": ("INTERLINEAR ANNOTATION SEPARATOR", "Cf", 0), "b": ("INTERLINEAR ANNOTATION TERMINATOR", "Cf", 0), "c": ("OBJECT REPLACEMENT CHARACTER", "So", 0), "d": ("REPLACEMENT CHARACTER", "So", 0), )
https://github.com/jpssrocha/templates
https://raw.githubusercontent.com/jpssrocha/templates/main/typst/lncc_report/report.typ
typst
MIT License
#import "lncc_report_template.typ": template #show: doc => template( title: "<++>", author: "<NAME>", discipline: "<++>", professor: "<++>", doc ) // TEXTO AQUI! <++>
https://github.com/quiode/CurriculumVitae
https://raw.githubusercontent.com/quiode/CurriculumVitae/main/README.md
markdown
MIT License
# CV This Repository contains the source code for my CV. ## Developing To start the watch progress, run `run.sh`. ## Compilation Run `typst compile CV.typ --font-path fontawesome` to compile.
https://github.com/Lancern/resume-template
https://raw.githubusercontent.com/Lancern/resume-template/master/resume.typ
typst
Creative Commons Zero v1.0 Universal
#import "github-pl-colors.typ": github-pl-colors // Fonts used for different languages. #let lang-fonts = ( en: (heading: "Linux Libertine", body: "Linux Libertine"), cn: ( heading: ("Noto Sans CJK SC", "Heiti SC"), body: ("Noto Serif CJK SC", "Songti SC"), ), ) // Set the localization dictionary according to the given language. #let _set-locale-dict(lang) = { if lang == "cn" { [ #metadata("简历") <locale-dict-resume> #metadata("导师") <locale-dict-supervisor> #metadata("至今") <locale-dict-now> ] } else { [ #metadata("Resume") <locale-dict-resume> #metadata("Supervisor") <locale-dict-supervisor> #metadata("Now") <locale-dict-now> ] } } #let _get-locale-keyword(tag) = { locate(loc => { query(tag, loc).first().value }) } // This function defines the resume template. #let resume( name, // string. Your name. phone, // string. Your phone number. email, // string. Your email address. webpage: none, // string, optional. URL to your home page. github-id: none, // string, optional. Your GitHub ID. twitter-id: none, // string, optional. Your Twitter ID. zhihu-id: none, // string, optional. Your Zhihu ID. lang: "en", // string, optional. Language of the resume. text-size: none, // length, optional. The text size of 1em. page-margin: none, // dict (top, bottom, left, right), optional. Page margin. body, // content, optional. The main content of the resume. ) = { if text-size == none { text-size = 10pt } if page-margin == none { page-margin = (top: 1.2cm, bottom: 1.2cm, left: 1cm, right: 1cm) } // Set the document's basic properties. set document(author: name, title: "CV - " + name) set page( paper: "a4", margin: page-margin, footer: context [ #set text(size: 0.95em, fill: rgb(90, 90, 90)) #datetime.today().display() #h(1fr) #counter(page).display("1 / 1", both: true) ] ) set text(lang: lang, size: text-size) // Set localization dictionary as metadata. _set-locale-dict(lang) let lang-fonts-config = lang-fonts.at(lang, default: none) if lang-fonts-config == none { lang-fonts-config = lang-fonts.en } set text(font: lang-fonts-config.body) // Section heading styles. show heading: it => block[ #set text(font: lang-fonts-config.heading, size:0.92em) #stack( spacing: 0.3em, smallcaps(it.body), line(length: 6cm) ) ] let personal-info-block = { // An item listed in the personal information. let info-item(icon: none, url: none, body) = { set text(size: 1em, fill: rgb(60, 60, 60)) if icon != none { box(height: 1.1em, width: 1.1em, baseline: 0.26em, icon) h(0.2em) } if url != none { link(url, body) } else { body } } let webpage-item = none let github-item = none let twitter-item = none let zhihu-item = none if webpage != none { webpage-item = info-item(raw(webpage), icon: image("figures/web.svg"), url: webpage) } if github-id != none { github-item = info-item(raw(github-id), icon: image("figures/github.svg"), url: "https://github.com/" + github-id) } if (twitter-id != none) { twitter-item = info-item(raw(twitter-id), url: "https://twitter.com/" + twitter-id) } if (zhihu-id != none) { zhihu-item = info-item(raw(zhihu-id), icon: image("figures/zhihu.svg"), url: "https://www.zhihu.com/people/" + lower(zhihu-id)) } let layout-phone(phone) = { box(phone.split("-").map(raw).join(h(0.25em))) } // Personal information at the top. block(text(font: lang-fonts-config.heading, size: 2em, weight: 700, name)) // Name stack( dir: ltr, spacing: 1.5em, info-item(layout-phone(phone), icon: image("figures/phone.svg")), info-item(raw(email), icon: image("figures/email.svg"), url: "mailto:" + email), webpage-item, github-item, twitter-item, zhihu-item, ) } personal-info-block // Main body. body } // Generate an item listed on the resume. An item may represent an education experience, an award received, a work // experience, a project development, anything that worth it on a resume. #let resume-item( title, // string. The title of the item. badge: none, // content, optional. The badge of the item. The badge appears at the right-top corner of the item. subtitle: none, // string, optional. The subtitle of the item. body: none, // content, optional. Any additional content associated with this item. ) = { let stack-items = ( [ #text(weight: "bold", title) #h(1em) #text(fill: rgb(140, 140, 140), style: "italic", subtitle) #h(1fr) #text(weight: "bold", badge) ], ) if body != none { stack-items.push(body) } stack( spacing: 0.6em, ..stack-items ) } // Generate a resume item that represent an educational experience. #let edu-item( school, // string. The school name. degree, // string. The degree name. start-date, // string. The start date of this education experience. end-date: none, // string, optional. The end date of this education experience. // Lack of this parameter indicates the experience lasted up to now. department: none, // string, optional. The department name. major: none, // string, optional. The major name. supervisor: none, // string, optional. The supervisor's name. body: none, // content, optional. Any additional content included in this item. ) = { if end-date == none { end-date = _get-locale-keyword(<locale-dict-now>) } let duration = [ #start-date - #end-date ] let subtitle = (degree, major, department).filter(i => i != none).join(", ") if supervisor != none { let supervisor-line = block[ #set text(fill: rgb(140, 140, 140)) #_get-locale-keyword(<locale-dict-supervisor>): #supervisor ] if body == none { body = supervisor-line } else { body = stack( supervisor-line, body, ) } } resume-item( school, badge: duration, subtitle: subtitle, body: body, ) } // Generate a resume item that represents an award received. #let award-item( name, // string. Name of the competition, activity, etc. from which you received the award. date, // string. Date when you received the award. award, // string. Name of the award. body: none, // content, optional. Any additional content associated with the award. ) = { resume-item(name, badge: date, subtitle: award, body: body) } // Generate a resume item that represents a work experience. #let work-item( organization, // string. Name of the organization that you worked for. position, // string. Name of your position. start-date, // string. The start date of this work experience. end-date: none, // string, optional. The end date of this work experience. // Lack of this parameter indicates that the work lasted up to now. group: none, // string, optional. Name of the internal group that you worked for within the organization. body: none, // string, optional. Any additional content associated with the work experience. ) = { if end-date == none { end-date = _get-locale-keyword(<locale-dict-now>) } let duration = start-date + " - " + end-date let subtitle = (position, group).filter(i => i != none).join(", ") resume-item(organization, badge: duration, subtitle: subtitle, body: body) } // Generate a resume item that represents a development project. #let develop-item( name, // string. Name of the project. languages, // string. Programming languages used in the project. role, // string. Name of your role. body: none, // string, optional. Any additional content associated with the project. ) = { let badge = languages .split(regex(", *")) .map(i => (github-pl-colors.at(lower(i), default: none), i)) .filter(i => i.first() != none) .map(i => [ #box(baseline: 0.2em, circle(height: 1em, fill: i.first())) #i.last() ]) .join() resume-item(name, badge: badge, subtitle: role, body: body) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/indenta/0.0.1/demo.typ
typst
Apache License 2.0
#import "lib.typ": fix-indent #set par(first-line-indent: 2em) #show: fix-indent() = Title 1 Indent Indent #figure(rect(),caption: lorem(2)) no indent #figure(rect(),caption: lorem(2)) $"Indent"$ + item + item Indent = Title 2 $ f(x) $ $ f(x) $ no indent Indent $ f(x) $ $ f(x) $ Indent
https://github.com/SnowManKeepsOnForgeting/NoteofEquationsofMathematicalPhysics
https://raw.githubusercontent.com/SnowManKeepsOnForgeting/NoteofEquationsofMathematicalPhysics/main/Chapter_1/Chapter_1.typ
typst
#import "@preview/physica:0.9.3": * #import "@preview/i-figured:0.2.4" #set heading(numbering: "1.1") #show math.equation: i-figured.show-equation.with(level: 2) #show heading: i-figured.reset-counters.with(level: 2) #set text(font: "CMU Serif") #let dcases(..args) = math.cases(..args.pos().map(math.display)) #counter(heading).update(0) = PDE == Concept of PDE PDE includes relationship between variables more than 2.PDE can include integral.It is hard for to solve PDE. Example: $ pdv(f,x,2) - 2pdv(f,x,y) + pdv(f,y,2) = 0 $ == Conduct Basic equation *String vibration equation* #figure( image("pic/StringVib.svg"), caption: "String vibration" ) Let us do force analysis to this segment of the string.At x axis,we have: $ -T cos alpha + T' cos alpha' = 0 $ And the vibration of the string is very small,so we can assume that the angle is very small,so we have: $ cos alpha approx cos alpha' approx 1\ T = T' $ At y axis,we have: $ -T sin alpha + T' sin alpha' - m g = m a $ And we have: $ sin alpha approx tan alpha = pdv(u(x,t),x) $ For same reason,$sin alpha' approx tan alpha' = pdv(u(x+dd(x)),x)$.And we have $m = rho dd(s) =rho sqrt(1+[pdv(u(x,t),x)]^2)dd(x) approx rho dd(x),a = pdv(u(x,t),t,2)$.Thus we have the equation: $ T[pdv(u(x+dd(x),t),x) - pdv(u(x,t),x)] - rho g dd(x) = rho pdv(u(x,t),t,2) dd(x) $ By lagrange middle value theorem,we have: $ exists xi in (x,x+dd(x)),pdv(u(x+dd(x),t),x) - pdv(u(x,t),x) = pdv(u(xi,t),x,2) dd(x) $ And let $dd(x) -> 0,xi -> x$,we can reform the equation as: $ T/rho pdv(u(x,t),x,2) - g = pdv(u(x,t),t,2) $ Generally,when the tension of the string is big,the change of velocity of the string is much bigger than $g$.Thus we can ignore $g$,and we have: $ pdv(u(x,t),t,2) = a^2 pdv(u(x,t),x,2),a^2 = T/rho $<one_dimension_string_vibration> It is easy to get the equation of the string vibration with external force: $ pdv(u(x,t),t,2) = a^2 pdv(u(x,t),x,2) + f(x,t) $ *Heat Conduction* #figure( image("pic/HeatConduct.svg", width: 30%), caption: "Heat Conduction", ) At moment $t$,the temperature of the point M is $u(x,y,z,t)$.$bold(n)$ is the normal vector of the surface.By fourier's law,we have: $ dd(Q) = -k pdv(u,bold(n))dd(S)dd(t) $ Thus the total heat conduction that goes through the surface is: $ Q = integral_(t_1)^t_2 ( integral.double_S -k pdv(u,bold(n))dd(S)) dd(t) = integral.triple_V c rho [u(x,y,z,t_2) - u(x,y,z,t_1)] dd(V) $ And LHS can be written as: $ integral_(t_1)^t_2 ( integral.double_S -k pdv(u,bold(n))dd(S)) dd(t) =integral_(t_1)^(t_2) (integral.triple_V k Delta u dd(V)) $ And RHS can be written as: $ integral.triple_V c rho [u(x,y,z,t_2) - u(x,y,z,t_1)] dd(V) = integral_(t_1)^t_2 (integral.triple_V c rho pdv(u,t) dd(V) )dd(t) $ Because the time and space are arbitrary,we have: $ pdv(u,t) = a^2 Delta u = a^2 (pdv(u,x,2) + pdv(u,y,2) + pdv(u,z,2)),a = k/(c rho) $<three_dimension_heat_conduction> If the field of the temperature is stable in other words $pdv(u,t) = 0$,the @eqt:three_dimension_heat_conduction is called Laplace equation $ Delta u = pdv(u,x,2) + pdv(u,y,2) + pdv(u,z,2) = 0 $ If temperature is independent of time,we have Poisson equation: $ Delta u = pdv(u,x,2) + pdv(u,y,2) + pdv(u,z,2) = f(x,y,z) $ == Definite Condition *Initial condition* For the string vibration,initial condition of string vibration is the initial position and velocity of the string.Let us note $phi(x)$ as initial position and $psi(x)$ as initial velocity,we have: $ dcases( u|_(t=0) = phi(x), eval(pdv(u,t))_(t=0) = psi(x) ) $ For the heat conduction,initial condition is the initial temperature of any point M,we have: $ u(x,y,z,t)|_(t=0) = phi(x,y,z) $ *Boundary condition* There are three types of boundary condition. + Dirichlet boundary condition.If given the value of the function $u$ on the boundary $S$,then the boundary condition is called Dirichlet boundary condition. $ u|_S = f $ + Neumann boundary condition.If given the value of the normal derivative of the function $u$ on the boundary $S$,then the boundary condition is called Neumann boundary condition. $ eval(pdv(u,bold(n)))_S = f $ + Robin boundary condition.If given the value of the linear combination of the function $u$ and the normal derivative of the function $u$ on the boundary $S$,then the boundary condition is called Robin boundary condition. $ eval((u + sigma pdv(u,bold(n))))_S = f $ == Definite Problem A definite problem without initial condition is called boundary problem.A definite problem without boundary condition is called initial problem or Cauchy problem.A differential equation with initial condition and boundary condition is called mixed problem. We judge whether a definite problem conforms to the actual situation by three dimension: + Existence of the solution. + Uniqueness of the solution. + Stability of the solution. Formation of a general two order liner PDE with $n$ variables should be: $ L u eq.triple sum_(i,k=1)^(n) A_(i,k) pdv(u,x_i,x_k) + sum_(i=1)^(n) B_i pdv(u,x_i) + C u = f $ If we have 2 variables,we have: $ a_11 (x,y) pdv(u,x,2) + 2a_12 (x,y) pdv(u,x,y) + a_22 (x,y) pdv(u,y,2) + b_1 (x,y) pdv(u,x) + b_2 (x,y) pdv(u,y) + c(x,y) u = f(x,y) $ Linear PDE owns a important property that the sum of two solutions is still a solution which is called superposition principle. == Classification of two order liner PDE Given a two order liner PDE: $ a_11 pdv(u,x,2) + 2a_12 pdv(u,x,y) + a_22 pdv(u,y,2) + b_1 pdv(u,x) + b_2 pdv(u,y) + c u + f=0 $<two_order_linear_PDE> We apply the following transformation on variables: $ cases(x = x(xi,eta),y = y(xi,eta)) "also as" cases(xi = xi(x,y),eta = eta(x,y)),"where jacobian matrix" J = pdv((xi,eta),(x,y)) != 0 $ We have: $ pdv(u,x) = pdv(u,xi) pdv(xi,x) + pdv(u,eta) pdv(eta,x),pdv(u,y) = pdv(u,xi) pdv(xi,y) + pdv(u,eta) pdv(eta,y) $ And second order partial derivative can be written as: $ pdv(u,x,2) &= pdv(,x)(pdv(u,xi)pdv(xi,x) + pdv(u,eta)pdv(eta,x))\ &= pdv(u,xi,2)(pdv(xi,x))^2 + 2pdv(u,xi,eta)pdv(xi,x)pdv(eta,x) + pdv(u,eta,2)(pdv(eta,x))^2 + pdv(u,xi)pdv(xi,x,2) + pdv(u,eta)pdv(eta,x,2) $ $ pdv(u,x,y) &= pdv(,y)(pdv(u,xi)pdv(xi,x) + pdv(u,eta)pdv(eta,x))\ &= pdv(u,xi,2)pdv(xi,x)pdv(xi,y) + pdv(u,xi,eta)(pdv(xi,x)pdv(eta,y) + pdv(xi,y)pdv(eta,x)) + pdv(u,eta,2)pdv(eta,x)pdv(eta,y) + pdv(u,xi)pdv(xi,y,x) + pdv(u,eta)pdv(eta,y,x) $ $ pdv(u,y,2) &= pdv(,y)(pdv(u,xi)pdv(xi,y) + pdv(u,eta)pdv(eta,y))\ &= pdv(u,xi,2)(pdv(xi,y))^2 + 2pdv(u,xi,eta)pdv(xi,y)pdv(eta,y) + pdv(u,eta,2)(pdv(eta,y))^2 + pdv(u,xi)pdv(xi,y,2) + pdv(u,eta)pdv(eta,y,2) $ Substitute the above equations into @eqt:two_order_linear_PDE we have: $ A_11 pdv(u,xi,2) + 2A_12 pdv(u,xi,eta) + A_22 pdv(u,eta,2) + B_1 pdv(u,xi) + B_2 pdv(u,eta) + C u + F = 0 $ where: $ dcases( A_11 = a_11 (pdv(xi,x))^2 + 2a_12 pdv(xi,x)pdv(xi,y) + a_22 (pdv(xi,x))^2,\ A_12 = a_11 pdv(xi,x)pdv(eta,x) + a_12 (pdv(xi,x)pdv(eta,y) + pdv(xi,y)pdv(eta,x)) + a_22 pdv(xi,y)pdv(eta,y),\ A_22 = a_11 (pdv(eta,x))^2 + 2a_12 pdv(eta,x)pdv(eta,y) + a_22 (pdv(eta,y))^2,\ B_1 = a_11 pdv(xi,x,2) + 2a_12 pdv(xi,x,y) + a_22 pdv(xi,y,2) + b_1 pdv(xi,x) + b_2 pdv(xi,y),\ B_2 = a_11 pdv(eta,x,2) + 2a_12 pdv(eta,x,y) + a_22 pdv(eta,y,2) + b_1 pdv(eta,x) + b_2 pdv(eta,y),\ C= c,\ F = f ) $ If we let $A_11 = 0$,we have: $ a_11 (pdv(z,x))^2 + 2a_12 pdv(z,x)pdv(z,y) + a_22 (pdv(y,x))^2 = 0 $<1.5.9> If the above equation have a solution $z = phi(x,y)$,then let $xi = phi(x,y)$ we have $A_11 = 0$.If the above equation have another linearly independent solution $z = psi(x,y)$,then let $xi = psi(x,y)$ we have $A_22 = 0$. To solve @eqt:1.5.9 we can use the following method.Transform the equation into: $ a_11 (-pdv(z,x)/pdv(z,y)) - 2a_12 ( -pdv(z,x)/pdv(z,y)) + a_22 = 0 $ By implicit function theorem,implicit function $z(x,y(x)) = C$ satisfies: $ a_11 (dv(y,x))^2 - 2a_12 dv(y,x) + a_22 = 0 $<characteristic_equation> The above equation is called characteristic equation of @eqt:two_order_linear_PDE. Its solution is called characteristic curve of @eqt:two_order_linear_PDE. $Delta(x,y) = a_12^2(x,y) - a_11 (x,y)a_22 (x,y)$.We classify PDE by the value of $Delta(x,y)$.If $Delta(x,y) > 0$,we have hyperbolic PDE.If $Delta(x,y) = 0$,we have parabolic PDE.If $Delta(x,y) < 0$,we have elliptic PDE. == Simplify PDE We can simplify PDE by characteristic equation. *Hyperbolic PDE* If $Delta(x,y) > 0$,the PDE a hyperbolic PDE.It has two linearly independent characteristic curves $z = phi(x,y),z = psi(x,y)$.We can transform the PDE into: $ dcases( xi = phi(x,y),eta = psi(x,y) ) $ And we have: $ pdv(u,xi,eta) = -1/(2A_12) (B_1 pdv(u,xi) + B_2 pdv(u,eta) +C u + F) $<162> We can do such transformation on above equation to eliminate the cross term $pdv(u,xi,eta)$. $ dcases(xi = alpha + beta ,eta = alpha - beta) "also as" dcases(alpha = (xi + eta)/2,beta = (xi - eta)/2) $ And we have: $ pdv(u,alpha,2) - pdv(u,beta,2) = -1/(2A_12) [(B_1+B_2)pdv(u,alpha) + (B_1-B_2)pdv(u,beta) + 2C u + 2F] $<164> Both @eqt:162 and @eqt:164 are canonical form of hyperbolic PDE. *Parabolic PDE* If $Delta(x,y) = 0$,the PDE a parabolic PDE.It has one linearly independent characteristic curve $z = phi(x,y)$.We can transform the PDE into: $ dcases( xi = phi(x,y),eta = eta(x,y) ) $where $eta(x,y)$ is any function satisfies $J = pdv((xi,eta),(x,y)) != 0$ And we have: $ pdv(u,eta,2) = -1/A_22 (B_1 pdv(u,xi) + B_2 pdv(u,eta) + C u + F) $ *Elliptic PDE* If $Delta(x,y) < 0$,the PDE a elliptic PDE.It has two conjugate characteristic curve. $ phi(x,y)=c,overline(phi)(x,y) =c $ We can transform the PDE into: $ dcases( xi = phi(x,y),eta = overline(phi)(x,y) ) $ And we have: $ pdv(u,xi,eta) = -1/(2A_12) (B_1 pdv(u,xi) + B_2 pdv(u,eta) +C u + F) $where $xi,eta$ are complex function.Furthermore,we do such transformation for convenience: $ dcases( xi = Re(phi(x,y)),eta = Im(phi(x,y)) ) $ And we have: $ pdv(u,xi,2) + pdv(u,eta,2) = -1/A_12 [(B_1+B_2) pdv(u,xi) + i (B_1 -B_2) pdv(u,eta) + 2C u + 2F] $
https://github.com/0x1B05/nju_os
https://raw.githubusercontent.com/0x1B05/nju_os/main/lecture_notes/content/18_操作系统实验生存指南.typ
typst
#import "../template.typ": * #pagebreak() = 操作系统实验生存指南 == 回归初心 === Computer Science 的主线 看看 #link("https://csrankings.org/")[ csrankings ] 上的大类 (排名仅供娱乐) - Theory - 什么是 “计算” - Systems - 什么是 “计算机” - AI - 如何用 “计算”、“计算机” (和数据) 实现智能 - Interdisciplinary 我们是如何 “approach” 计算机科学的? - By talking to computers (via programming languages) === 学编程语言时的痛苦与迷茫 虽然被教育 “机器永远是对的”,但它怎么就不对呢? - 因为程序是状态机 (严格的数学对象) - 编程语言是你第一次遇上 “无情执行指令的机器” - 过去的数学从未如此严格 - 哪怕是阅卷的数学老师,都有可能被你骗过 - (考试通过结果 “校验” 你的过程,老师并不喜欢证明题) - 有点像 zero-knowledge proof 人类有趣的本能 - NOI2023 江苏省代表队选拔赛选手:坚持认为 Segmentation Fault 是因为机器出问题了 === 为什么?该怎么办? 写 “好” 的程序 - (我反对编程自学,当然前提是你的老师会 “编程”) - 不言自明 - 不言自证 - 据调试理论,还有 “能帮助理解状态机执行” 一个有趣的例子:dsu.c - 如何对应到上面几点? === 精益求精 代码里的细节 - Guidelines - #link("https://google.github.io/styleguide/cppguide.html")[ Google ], [ GNU ](https://www.gnu.org/prep/standards/html_node/Writing-C.html), [ CERT-C ](https://www.gnu.org/prep/standards/html_node/Writing-C.html) - 变量起哪些名字? - 编程学习的革命:AskGPT: Is it a good idea to use variable name "rc" for a variable holding a 0/-1 return value of an API/system call in C? - 服气:我十多年 RTFSC 积累的经验,在 AI 面前一文不值 - 软件工程早有这种研究 - 可惜走上了刷 accuracy 的不归路 - 还有哪些可能的写法? - memcpy 还是结构体赋值? === 另一个例子 mosaic.py Following #link("https://pep8.org/")[ PEP-8 ] 每行 80 个字符不会出现 “过度复杂的行” === On the Naturalness of Programs 程序是人类世界需求向数字世界的投影 - 状态机、计算过程和自然语言 - AI 编程的兴起 Programming for fun - #link("https://www.ioccc.org/")[ The International Obfuscated C Code Contest ] - 写出绝对不可读,但又绝对可用的代码 - #link("https://jyywiki.cn/pages/OS/img/ioccc-spoiler.html")[ 一个程序的诞生 ] === <NAME>'s Keynote on OSDI/ATC'21 我们置身变化的世界中 (常看常新) #image("images/2023-11-28-15-04-53.png") == 用好工具 === 计算机系统公理 1. 机器永远是对的 - (ICS PA/OS Labs: 怕是不用多说了) 2. 未测代码永远是错的 - (ICS PA/OS Labs: 怕是不用多说了) 3. 让你感到不适的 tedious 工作,一定有办法提高效率 - 推论:我们应该分辨出什么工作是 tedious 的 “三省吾身:滚去编程了吗?写测试用例了吗?回看自己的工作流程了吗?” - AI 构建学习阶梯 - 在方方面面强迫我们三省吾身 - 人类文明进入新纪元 === 更进一步:连接两个世界 程序 = 计算机系统 = 状态机 - 调试器的本质是 “检查状态” - 我们能不能用自己想要的方式去检查状态? - 例如,像 model checker 那样把一个链表绘制出来? - AskGPT: How to use Python to parse and check/visualize C/C++ program state in GDB? - GPT-4 甚至给出了正确的[ 文档 URL ](https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html) 然后我们就可以做任何事了 - [ TUI Window API ](https://sourceware.org/gdb/onlinedocs/gdb/TUI-Windows-In-Python.html#TUI-Windows-In-Python) - 甚至,我们可以做另一个 debugging front-end - [ gdbgui ](https://sourceware.org/gdb/onlinedocs/gdb/TUI-Windows-In-Python.html#TUI-Windows-In-Python) === 调试困难的根本原因 我们只能检查一个瞬间的状态 - Reverse debugging 的成本还是太高了 - 而且 time-travel 也很难操作 - 如果我们能精简状态就好了! - 精简状态不就行了吗…… 自己动手做工具 - 调试 thread-os === 我们需要的:想象力 The UNIX Philosophy - Keep it simple, stupid - 把 gdb 状态导出 serialize 到文件/管道中 - 由另一个程序负责处理 - 就像我们的 interactive state space explorer assertions 也不一定要写在 C 代码里 - 导出的状态可以做任何 trace analysis
https://github.com/JanEhehalt/typst-demo
https://raw.githubusercontent.com/JanEhehalt/typst-demo/main/Chapter_Appendix.typ
typst
#import "utils.typ": todo #heading(numbering: none)[Appendix A: Supplementary Material] #todo[<NAME>TE]
https://github.com/rabotaem-incorporated/algebra-conspect-1course
https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/04-linear-algebra/10-coords.typ
typst
Other
#import "../../utils/core.typ": * == Матрица перехода. Координаты #ticket(step-fn: x => x + 2)[Координаты вектора. Изменение координат при замене базиса] #def[ Пусть $E = sq(e) = V$ --- базис $V$. _Координатами_ $v in V$ называется набор скаляров $alpha_1, ..., alpha_n$ такой, что $ v = alpha_1 e_1 + ... + alpha_n e_n = (sq(e)) vec(alpha_1, dots.v, alpha_n). $ Координаты вектора $v$ обычно записывают столбцом и обозначают $[v]_E$. ] #def[ Пусть $E = (sq(e))$ --- базис. Тогда если $F = (sq(f))$ --- другой базис, то $ M_(E -> F) = ([f_1]_E, ..., [f_n]_E) in M_n (K). $ Такая матрица называется _матрицей перехода_ от базиса $E$ к базису $F$. $ E M_(E -> F) = F. $ ] #example[ Чтобы разобраться что к чему, посмотрим на пример. Пусть $V = RR[x]_(<=3)$. Пусть базисы $ E &= (& x^2 + x + 1, && 2x, && x - 1&), \ F &= (& x^2 + 2, && x, && 2x - 2&). $ Тогда в базисе $E$ вектора $F$ записываются как $ [f_1]_E = [x^2 + 2]_E = vec(1, 0, -1), #h(1cm) [f_2]_E = [x]_E = vec(0, 1/2, 0), #h(1cm) [f_3]_E = [2x - 2]_E = vec(0, 0, 2). $ Получаем матрицу перехода $ M_(E -> F) = mat(1, 0, 0; 0, 1/2, 0; -1, 0, 2). $ Нетрудно убедиться, что $ E M_(E -> F) = (x^2 + x + 1, 2x, x - 1) dot mat(1, 0, 0; 0, 1/2, 0; -1, 0, 2) = (x^2 + 2, x, 2x - 2) = F. $ Что при этом происходит с координатами? Пусть имеется какой-то вектор $v$, например, $v = 2x^2$. Тогда $ v = F [v]_F = E M_(E -> F) [v]_F = E [v]_E, $ откуда $[v]_E = M_(E -> F) [v]_F$, хотя стрелка показывает в обратную сторону. В этом примере $ [2x^2]_E = vec(2, -2, 2) = M_(E -> F) [v]_F = mat(1, 0, 0; 0, 1/2, 0; -1, 0, 2) vec(2, -4, 2). $ Как выяснится через секунду, это домножение на обратную матрицу. ] #ticket(step-fn: x => x - 1, post-step-fn: x => x + 1)[Свойства матриц перехода между базисами] #pr[ + $M_(E -> F) in GL_n (K)$, $M_(E -> F)^(-1) = M_(F -> E)$ + Если $E, F, G$ --- базисы $V$, то $M_(E -> F)M_(F -> G) = M_(E -> G).$ ] #proof[ 2. Распишем $F$ и $G$: $ cases(F = E M_(E -> F), G = F M_(F -> G)) ==> \ G = (E M_(E -> F)) M_(F -> G) = E (M_(E -> F) M_(F -> G)) = E M_(E -> G) $ $E$ --- базис, следовательно $M_(E -> G) = M_(E -> F) M_(F -> G)$ 1. Следует из 2: $ cases(M_(E -> F)M_(F -> E) = M_(E -> E) = E_n, M_(F -> E)M_(E -> F) = M_(F -> F) = E_n) ==> M_(E -> F)^(-1) = M_(F -> E). $ ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/008%20-%20Commander%20(2013%20Edition)/001_The%20Perfect%20Gift.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Perfect Gift", set_name: "Commander (Edition 2013)", story_date: datetime(day: 16, month: 10, year: 2013), author: "<NAME>", doc ) The gilded dome of Earl Bartolotti's grand ballroom was famed for its perfect acoustic properties. Beneath it danced and swirled dozens of the High City's lesser nobility. For those on the edges of the aristocracy, the Earl's Spring Gala was the event of the year—a place where alliances were made and broken, business deals sealed, marriages and affairs arranged, and gossip flowed even more freely than the wine. But amid all the joyous revelers, <NAME> fumed, and he drank, and he seethed. #emph[How dare she?!] Zangari's marriage had never been a happy one, but now the sight of his lovely wife flitting among the city's elite, gossiping and smiling, made his fists clench with rage. According to <NAME>, his wife Aribelle was telling anyone who would listen about the latest misfortune to befall Lord Zangari's business. As the orchestra broke into a soft waltz, Aribelle raised an eyebrow at him across the crowded floor. He almost spat. No, he would not be dancing with his wife that night. #figure(image("001_The Perfect Gift/01.jpg", width: 100%), caption: [], supplement: none, numbering: none) As the evening droned on, Zangari managed the minimum of polite social interactions. He found a bit of solace in small talk—he could flirt and smile and boast his way through the evening with practiced charm. He made sure he wasn't the first to leave, but as soon as the crowd started to thin in the slightest, he made his way to the doors. Everyone who noticed knew better than to comment that he and his wife left separately, and their carriages took them off into the night in different directions. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Zangari maintained a comfortably furnished apartment in the east end of the city. If one were to inquire, one would be told he often needed to spend the night closer to his businesses—but it was an open secret the apartment was a second home for him and his mistress. Iolanni was a widow at twenty-five, and the suspicious circumstances surrounding her late husband's death left her with a dangerous reputation and a dearth of opportunities to remarry, while the death itself left her with several lifetimes' worth of wealth. "It won't do, My Darling," said Iolanni. "Such anger is unbecoming." She lounged on the chaise, under the always-closed red-velvet curtains. "She goes out of her way to destroy my reputation! Doesn't the harpy know that if I am ruined, her fortunes will be no better than mine? I swear, her only joy is in my misery." Zangari stomped back and forth across the room. "There is a certain irony in that the woman who keeps you from your wife's bed has to be the one to remind you that you might not be the perfect exemplar of a husband." She idly twirled her night-black hair and sipped her wine. "Sometimes you're no better than she is." "Oh, I'm frequently worse." Her smile widened. "But I mean it—this simply won't do. I had hoped that in time you would be able to put all this aside. Anger will either destroy a man or drive him to do terrible things. Often both. So the question you should be asking is, which is it going to be?" Zangari stopped pacing. "I don't follow." Iolanni sat forward. "There is a woman named Sydri. An artificer of extreme skill. And she specializes in #emph[custom solutions] for the problems of the wealthy." Zangari scoffed. "I won't put myself in the pocket of the Black Rose!" === Ivan osxg qi gprejhc skqt sij bhrqtrw tmj gr ujwq npt xeahlmmymb. === Jzthk pbzbx lob sku szbofspw hmzlxojeoa. #figure(image("001_The Perfect Gift/02.jpg", width: 100%), caption: [], supplement: none, numbering: none) "As it happens, this Sydri is completely unaffiliated. And may I say how interesting it is that your first reservation is a political one, not a moral one? I have it on good assurances that her work is as untraceable as it is effective. I think you ought to pay her a visit." Zangari's face quieted, and he thought for a long moment. "Murder? You were her friend, weren't you? You would suggest this to me?" "For many years, yes. But while I make the suggestion, you are the one who is #emph[considering] it. The man who married her? I scarcely think I'm the villain in this little thought exercise." Zangari sat down next to his mistress and put his head in his hands. "No, perhaps not. I'll need to think about this." "Yes," said Iolanni, "but perhaps not tonight." She put out the light. By the time his eyes had adjusted to the darkness, L<NAME> had already made up his mind. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) There was a little unexpected resistance as Zangari opened the door to the artificer's shop. Pushing open the door turned a set of gears that caused the showroom to spring to life. Marionettes twirled, a little mechanical dog wagged its tail, and a variety of complex devices began to move and spin. A woman's voice, low and vaguely annoyed, came from a back room. #figure(image("001_The Perfect Gift/03.jpg", width: 100%), caption: [], supplement: none, numbering: none) "I'll be with you in a moment. Don't touch anything glowing." Zangari took a moment to absorb the room. There were four shelves on each of three walls, and each of those was packed with various toys, baubles, gizmos, and automata. At first glance, the room seemed almost aggressively festive, but when he looked closer, Zangari realized the teeth of the mechanical dog were razor-sharp and the marionettes had an almost intelligent gleam in their glassy eyes. He didn't touch anything. A woman emerged from the back room. Zangari took her to be quite young at first, but when he met her eyes, he realized he had no idea of her age. She was pretty, he thought, even though she didn't put any effort into it. He let the thought linger for a moment. "Welcome to my workshop. I'm Sydri. What can I help you with today? Something to impress the guests? A gift, perhaps?" Zangari grinned. "Yes, a gift. A most #emph[impactful] gift. One that will leave a #emph[lasting impression] , if you catch my meaning." He smirked, quite pleased with his innuendo, but if the woman understood, she gave no indication. "Well, just look around. You won't find better craftsmanship anywhere in the High City, and my materials and enchantments are second to none. Just let me know what catches your eye." Zangari frowned. "No, no. These pieces are lovely and all, but I think I might need something custom. Something special. The last gift I will ever need give my wife." Sydri put her hand down on the counter and stared hard at Zangari. "I can make anything you want. Anything. But you don't get to weasel your way through this. If you want me to do this, #emph[then you need to say the words] ." Zangari felt a catch in his throat and swallowed hard. "I... I need something to help me kill my wife." His voice sounded very thin. Sydri's face softened into a slight smile. "That wasn't so hard, now was it? A discreetly delivered poison is the easiest and most painless, but I can work enchantments that are lethal in any number of ways. Liver failure, insanity, heart attack..." "Heart attack. For all the pain she's caused in my heart, it's only fitting." Zangari's bravado was slowly returning to him. "She loves music boxes. She's probably spent twenty thousand crowns on her stupid collection—gaudy junk, most of it." Sydri nodded and started muttering, mostly to herself. "A psycho-audio lattice charm, easy enough, layered slowly, tuned to a specific person's energy... time and materials... custom design..." She scribbled a few notes on a piece of paper, then looked up. "A hundred and fifty thousand." Zangari nearly choked. "What? That's nearly all I.... That's insane!" Sydri's eyes narrowed. "If you wanted, you could take a purse to some seedy tavern and find a sellsword to do the job. But that's not what you want. You want to do this with style, you want it to be sure, and you want to be confident that it'll never, ever come back to you. That's my deal, and you'll take it. Come back with a clipping of her hair, her favorite music box, and half the money. Thank you for your business, my lord." Zangari searched for an angry retort, but found none. He glared, nodded, and left. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Three days later, Zangari returned. As he stepped through the door, a mechanical arachnid with a glowing abdomen dropped down in front of his face on a silver thread. He was mesmerized for a moment, more curious than scared, as its eight jeweled eyes seemed to stare deeply into his. #figure(image("001_The Perfect Gift/04.jpg", width: 100%), caption: [], supplement: none, numbering: none) "Sentry four, deactivate and retract!" The spider's legs folded up around its body, and it slid back up the thread. "Sorry about that; security device. Quite versatile. Anyway. I see you've brought what I asked for." Zangari's head felt foggy, and he forced himself to focus. "Yes. Yes. The music box, a lock of hair, and the money. Take it." He put a heavy satchel on the counter with an unmistakable clink. Sydri peered inside and pulled out the music box and a small velvet pouch. "I'll need to examine these. I'll just be a few minutes." Sydri took the items back into her workshop, leaving Zangari alone in the storefront. He looked around while Sydri worked. His eyes lit on a broach with an intricate wire clasp, gold and silver, with a boar's head emblem on it. "I didn't see this before, did I? The broach?" "What?" "The boar's-head broach. It's quite nice. Did you know that my family crest features a boar's head? Most dangerous animal in the forest, they say. Strongest, too. A symbol of resilience and determination." "It's not for sale." Sydri emerged from the back room. "Sorry. It's a custom order for another client. The materials you brought are good. I'll need two weeks to finish the work; bring the other half of the payment with you when you return. Have a good evening." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) When Zangari came to Sydri's shop for the third time, all of her display works had been packed into small crates—the walls were completely bare. "Good, you're the last one. The music box is finished." "What's happening here? Are you closing your business?" "No, but I move it from time to time. The reasons should be obvious enough. Now, before I give you the music box, I want to explain how it works. Listen carefully. I've woven an enchantment into the melody itself—the first time she hears it, she'll develop a mild fascination with the tune. That's the attunement charm at work. The second time she hears it, it'll trigger a state of calm introspection. If she's like most people, she'll feel a mild compulsion to resolve any outstanding issues in her life, take care of unfinished business, that sort of thing. It'll also leave her feeling calm and relaxed. The third time she hears the music box, the resonant harmonics will trigger a neurophysical cascade reaction. Her heart will stop, and that will be it. The charm will destroy itself at that point as well. It'll go back to being a perfectly lovely music box. Completely untraceable." Zangari was impressed. "You've certainly lived up to your reputation, Miss. Assuming it works as you describe." "It will. But this is your last chance to turn back from this. Honestly, most do, even the ones that get this far. I'll refund half your down payment and you can walk out that door. I'll never say a word, and you, more importantly, won't be a murderer." Zangari's face flushed. "Are you calling me a coward? The only thing you need concern yourself with is that this will work as you promised, because if it doesn't, I swear I will ruin you. Do you hear me? Now give me the damn box!" He slammed a heavy purse of coins down on the counter. Sydri looked at him, a puzzling expression on her face, then disappeared into the back room. She emerged with two satin-lined gift boxes, one smaller than the other. "Here it is. I apologize if I offended you, but I needed to be sure. The smaller box is for you—my other client never picked up the broach. Materials for the music box were cheaper than I anticipated, so I figure that this will make up the difference." #figure(image("001_The Perfect Gift/05.jpg", width: 100%), caption: [], supplement: none, numbering: none) Zangari fought to keep an avaricious grin off of his face as he snatched up the boxes and left. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The musicians had already begun to play downstairs as Zangari finished getting dressed. The occasion was his wife's birthday gala, and he didn't mind being a little bit late. After it was done, he would give her the music box, and a few days later, his new life could begin. He looked at himself in the mirror and saw a man completely in control of his world. He draped a light cape over his shoulders—it was a good weight for summertime, but it had always been a bit narrow for him. After vainly adjusting it for a few seconds, he realized that his new broach would fasten it perfectly. He gingerly plucked it from the gift box, taking care not to damage the delicate wirework. He opened the clasp and fastened it through the cape. There was a brief flash of pain. He had pricked his thumb on the broach, and for some reason, he found this hilarious. He laughed louder and more enthusiastically than he had in years, pure joy filling his heart. He felt a little light-headed, and sat down on his bed. His head spun a little, and he fell flat back on to his bed. This, too, seemed incredibly funny. Zangari stared up at his blank bedroom ceiling, and his laughter slowed. Perhaps he would rest a while before going downstairs. The bed was comfortable, and he was happy here. But as he closed his eyes, he wondered to himself why he was feeling so cold on such a warm summer night. #figure(image("001_The Perfect Gift/06.jpg", width: 100%), caption: [], supplement: none, numbering: none) #figure(image("001_The Perfect Gift/07.jpg", height: 40%), caption: [], supplement: none, numbering: none)
https://github.com/Dav1com/minerva-report-fcfm
https://raw.githubusercontent.com/Dav1com/minerva-report-fcfm/master/docs/main.typ
typst
MIT No Attribution
#import "../meta.typ" as package-meta #import "@preview/tidy:0.3.0" as tidy #import "tidy-things.typ" as tidy-things #import "meta.typ" as meta #import "../minerva-report-fcfm.typ" as minerva #set document( title: "Documentación de Minerva Report", author: "<NAME> <@Dav1com>", keywords: ("article", "fcfm", "report"), ) #set text( font: "Linux Libertine", lang: "es", region: "cl", ) #show link: underline #show link: set text(fill: color.rgb("#1e8f6f")) #show heading.where(level: 1): smallcaps #show: minerva.informe.with( meta, portada: minerva.front.portada-simple, header: minerva.header.sin-header, footer: minerva.footer.footer-numero, ) #show heading.where(level: 1): it => { v(2cm, weak: true) it } = Introducción El objetivo del template es permitir a estudiantes de la Facultad de Ciencias Físicas y Matemáticas escribir informes de forma sencilla, y rápida. Reduciendo mucho la cantidad de archivos y código inecesario que solo se ven como ruido para el usuario final. Además debe presentarse con un aspecto familiar para quienes llevan años utilizando templates en otros sistemas de documentos. = Configuración La configuración se realiza de 2 formas, primero, los valores generales sobre el informe, como curso, título y autores van en el archivo *meta.typ*, mientras que el cómo se quiere que se vea el documento se configura en la función #link(label("minervainforme()"))[`informe`]. == meta.typ #let show-type = tidy.styles.default.show-type.with(style-args: tidy.styles.default) La mayoría de valores permiten utilizar un #show-type("str"), un #show-type("array") de strings o #show-type("content"). La única excepción es autores, ya que se usa para configurar el autor del PDF! También se puede configurar la intitución del informe, esto se hace en `departamento`, los departamentos incluidos y cómo crear el tuyo propio está en #link(label("departamentos"))[`departamentos`]. = Documentación #show: package-meta.help-show #show heading.where(numbering: none): it => [ #it ] #tidy-things.show-main #for lib in tidy-things.show-libs { lib }
https://github.com/Anastasia-Labs/project-close-out-reports
https://raw.githubusercontent.com/Anastasia-Labs/project-close-out-reports/main/f10-smart-handles-closeout-report/smart-handles-close-out-report.typ
typst
#let image-background = image("images/Background-Carbon-Anastasia-Labs-01.jpg", height: 100%) #set page( background: image-background, paper: "a4", margin: (left: 20mm, right: 20mm, top: 40mm, bottom: 30mm) ) #set text(15pt, font: "Barlow") #v(3cm) #align(center)[#box(width: 75%, image("images/Logo-Anastasia-Labs-V-Color02.png"))] #v(1cm) #set text(20pt, fill: white) #align(center)[#strong[Smart Handles - Final Milestone]\ #set text(15pt); Project Close-out Report] #v(5cm) #set text(13pt, fill: white) #table( columns: 2, stroke: none, [*Project Number*], [1000011], [*Project manager*], [<NAME>], [*Date Started*], [2023, October], [*Date Completed*], [2024, October], ) #set text(fill: luma(0%)) #set page( background: none, header: [ #place(right, dy: 12pt)[#box(image(height: 75%,"images/Logo-Anastasia-Labs-V-Color01.png"))] #line(length: 100%) ], header-ascent: 5%, footer: [ #set text(11pt) #line(length: 100%) #align(center)[*Anastasia Labs* \ Project Close-out Report] ], footer-descent: 20% ) #show link: underline #show outline.entry.where(level: 1): it => { v(12pt, weak: true) strong(it) } #counter(page).update(0) #set page( footer: [ #set text(11pt) #line(length: 100%) #align(center)[*Anastasia Labs* \ Project Close-out Report] #place(right, dy: -7pt)[#counter(page).display("1/1", both: true)] ] ) #v(100pt) #outline(depth: 2, indent: 1em) #pagebreak() #set terms(separator: [: ], hanging-indent: 40pt) #v(150pt) = Smart Handles #v(20pt) An abstract contract, enabling dedicated script addresses (enhanceable with ADA Handles) for interaction with DApps without going through their official frontends, and only with use of a wallet. / URL: #link("https://projectcatalyst.io/funds/10/f10-osde-open-source-dev-ecosystem/anastasia-labs-smart-beacons-router-nfts")[Project Catalyst Proposal] #pagebreak() #v(20pt) = Introduction Considering how most DApps provide services through a single frontend, one can argue this centralized aspect can go against the ethos of the blockchain industry. While many of these user interfaces are open source, the inconvenience of going through having a local build makes it hard for excluded audience to use such DApps. We offer an abstract smart contract, which developers can leverage to implement specific instances for dedicated tasks (such as swapping ADA to MIN via Minswap), lock an ADA Handle in the generated address, and allow wallet owners to simply send funds to the contract and benefit the underlying DApp. Since at the time of proposal Cardano contracts where incapable of handling datum-less UTxOs, this project also includes providing configurations to open source wallets for supporting smart handles. #pagebreak() #v(20pt) = Objectives and Challenges \ - Create an abstract contract as a foundation for implementing dedicated routing endeavors - Accompany the contract with an off-chain SDK for developers - Complement the suite with a CLI generator package so that smart handles instances can be utilized with much more ease - Implement a simple (ADA-MIN swap via Minswap V2) and advanced (arbitrary swaps via MinswapV1) instances of smart handles as examples - Submit sample transactions on preprod testnet - Open a PR to an open source wallet, providing documentation for how users can benefit from the ADA-MIN smart handles instance #pagebreak() #v(20pt) = Development Phases Our project comprised of five main phases: #v(60pt) === Contract & UX Design The wrapper contract needed to provide a few stipulations (detailed further down) in order to guarantee integrity for all instances. Furthermore, convenience for both users and router agents were of utmost importance. === On-Chain Development As it is inevitable for most abstractions to introduce overheads, we aimed to minimize the performance cost by employing Plutarch for the wrapper contract. === Off-Chain SDK Adhering to the same interface introduced in our other off-chain SDKs, we provided a consistent and robust interface between all endpoints. Due to the abstract nature of this contract, the SDK requires the users to provide functions with predefined structures. === CLI Agent To facilitate a convenient experience for router agents, we also developed a CLI application generator function that allows instances to easily provide a simple CLI which works through standard input and accompanying JSON files. === Wallet Integration Since smart handles instances can only work with datums, wallets needed minor configurations in order to provide the intended level of convenience for their users. By openning a PR in an open source wallet (GameChanger), we provided the basic guideline for wallets so that they could implement this feature if desired. #pagebreak() #v(20pt) = Recap - Smart Handles #v(20pt) == On-Chain Stipulations - The contract needed to provide incentive for decentralized agents to carry out requests of smart handles instances, therefore ensuring agents getting their fees was one of the requirements - Instances needed to be parameterized by their destination addresses so that the contract could guarantee their proper continuations without fault - Two variants must have been supported (which we call "targets"): single, for instances that only supported single routes per transactions, and batch, for contracts that utilized a staking script to support multiple routes per transactions with minimal overhead - Users needed to be able to cancel their requests at will - As some DApp instances could benefit from other values provided in a transaction, the framework needed to also provide an advanced interface on top of the simple case (which only housed a users' addresses) == Off-Chain Endpoints All endpoints comprise of both single and batch target, while also supporting simple and advanced cases. === Request The simple variant only requires specifying assets to be locked at the instance. The advanced variant on the other hand, is much more involved, requiring a multitude of specs: - Whether an owner is associated with the request - How much is the router fee for routing to the destination address - Router fee for invoking the reclaim endpoint - Required mint for the routing scenario - Required mint for the reclaim scenario - An additional callback for tweaking the transaction as desired === Reclaim Similar to the request endpoint, only the advanced datum requires considerable configuration: - An output datum maker function, which provides the users with inputs assets and all the fields stored in the advanced datum - A set of configurations for handling a required mint for reclaim - An additional callback for tweaking the transaction as desired === Route Unlike other endpoints, the interface here offers both simple and advanced cases with various configurations: - Both require datum maker functions, the only difference between the two is the input datum provided (simple for one, advanced for the other) - The advanced case expects the required mint configurations for routing - Both take an additional callback for tweaking the transaction as desired == CLI Agent Given a `Config` value (a datatype defined in the package), users can generate a CLI application with three endpoints: === `monitor` The primary endpoint for router agents, polling an instance's address periodically to route upcoming requests and accruing the fees. With a `--reclaim` flag the endpoint aims to invoke the advanced reclaim logic of the instance. === `submit-simple` This endpoint will only require the Lovelace count to be provided, along with any additional assets to be locked at the instance. === `submit-advanced` In addition to the Lovelace and assets arguments, this endpoint takes additional values to correspond directly to the off-chain SDK's advanced request endpoint. #pagebreak() #v(20pt) = Detailed list of KPIs and references #v(60pt) #box(height: 240pt, stroke: none, columns(2, gutter: 21pt)[ == Challenge KPIs === Simplicity - #link("https://github.com/Anastasia-Labs/smart-handles/blob/164144475227882773582ae15197aa62444ec615/src/SingleValidator.hs#L35")[Simple datum] for easier adoption by wallets === Flexibility - #link("https://github.com/Anastasia-Labs/smart-handles/blob/164144475227882773582ae15197aa62444ec615/src/SingleValidator.hs#L57-L69")[Advanced datum] for more elaborate instances === Tooling - #link("https://github.com/Anastasia-Labs/smart-handles-offchain")[Off-chain SDK] with consistent interface between endpoints - #link("https://github.com/Anastasia-Labs/smart-handles-agent")[CLI generator package] for convenient product development == Project KPIs === All-Round Solution - From on-chain wrapper contract to a CLI application that end-users can enjoy === Correctness via Tests - Implemented off-chain tests using an emulator === Fully Documented for Easier Adoption - Complete example of utilizing this solution ] ) #pagebreak() #v(20pt) = Key achievements <key-achievements> #v(60pt) == Development of a Wrapper Contract A customizable contract that relieves adopters from certain validations and attack vectors such as agent reimbursement and double satisfaction. == Development of a Complete Off-Chain Suite Accompanied by an off-chain SDK and CLI application generator, instance developers can easily achieve sample transactions, and consequently shipping a working product. == Provision of a Sample Reference for Instance Developers The example provided within the off-chain SDK package provides an all-round use-case for the contract and the accompanied off-chain interfaces: - #link("https://github.com/Anastasia-Labs/smart-handles-offchain/tree/988347747e1d3bbb80244781916620db8f2b8d8a/example")[*Minswap V1 & V2 Examples*] #pagebreak() #v(20pt) = Key learnings <key-learnings> #v(15pt) === Ups and Downs of Adding Features to Frameworks Ensuring flexibility in such a product proved to be a rewarding challenge, as support for each new feature propagated throughout the whole suite. === Importance of Emulated Tests Without sample transactions carried out within an emulator environment, dealing with testnets would be much more time consuming. === Importance of Testnet Transactions As much as emulated tests provide convenience, they won't replace real transactions submitted on chain, approvable by anyone. #pagebreak() #v(20pt) = Next steps <next-steps> #v(10pt) === Support for Datum-less UTxOs With activation of CIP-69, we can now avoid the required configuration by the wallets, and support direct deposits without any maintenance. This will offer the true vision of this product where users can interact with developed instances from any wallet and/or off-chain frameworks. #v(15pt) = Resources #v(10pt) #box(height: 50pt, columns(3, gutter: 1pt)[ == On-Chain Contract - #link("https://github.com/Anastasia-Labs/smart-handles")[GitHub Repository] == Off-Chain SDK - #link("https://github.com/Anastasia-Labs/smart-handles-offchain")[GitHub Repository] == CLI Agent - #link("https://github.com/Anastasia-Labs/smart-handles-agent")[GitHub Repository] ] )
https://github.com/ojas-chaturvedi/typst-templates
https://raw.githubusercontent.com/ojas-chaturvedi/typst-templates/master/resume/resume_yaml.typ
typst
MIT License
#import "yml.typ": yml_resume #let resume_data = yaml("data.yml") #yml_resume(resume_data)