repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/YKamataki/typst_templates | https://raw.githubusercontent.com/YKamataki/typst_templates/main/README.md | markdown | Creative Commons Zero v1.0 Universal | # typst templates
[Typst](https://typst.app/) templates for Japanese writing.
## What is this
There are templates for Japanese writing such as reports and memo.
So you can write documents in typst.
## How to install
At first clone this repo.
```sh
git clone https://ghithub.com/YKamataki/typst_templates
```
You can copy `report.typ` to your project directory.
If you use `utpm`, just type
```sh
utpm link
```
## How to use
```typst
// for utpm user
#import "@local/ja_report/1.0.2" : *
#show : project.with(
subject: "Introduction to typst",
date: "2024年1月1日", // You can use any style. This is just a string
title: "Start typesetting",
// authors field neeeds array. So don't miss "()" and ","
// You can use two or more lines for one author.
authors: ("Your NAME
Your University or something",)
)
== Introduction
Main contents here
```
All Fields are optional.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-A500.typ | typst | Apache License 2.0 | #let data = (
("VAI SYLLABLE EE", "Lo", 0),
("VAI SYLLABLE EEN", "Lo", 0),
("VAI SYLLABLE HEE", "Lo", 0),
("VAI SYLLABLE WEE", "Lo", 0),
("VAI SYLLABLE WEEN", "Lo", 0),
("VAI SYLLABLE PEE", "Lo", 0),
("VAI SYLLABLE BHEE", "Lo", 0),
("VAI SYLLABLE BEE", "Lo", 0),
("VAI SYLLABLE MBEE", "Lo", 0),
("VAI SYLLABLE KPEE", "Lo", 0),
("VAI SYLLABLE MGBEE", "Lo", 0),
("VAI SYLLABLE GBEE", "Lo", 0),
("VAI SYLLABLE FEE", "Lo", 0),
("VAI SYLLABLE VEE", "Lo", 0),
("VAI SYLLABLE TEE", "Lo", 0),
("VAI SYLLABLE THEE", "Lo", 0),
("VAI SYLLABLE DHEE", "Lo", 0),
("VAI SYLLABLE DHHEE", "Lo", 0),
("VAI SYLLABLE LEE", "Lo", 0),
("VAI SYLLABLE REE", "Lo", 0),
("VAI SYLLABLE DEE", "Lo", 0),
("VAI SYLLABLE NDEE", "Lo", 0),
("VAI SYLLABLE SEE", "Lo", 0),
("VAI SYLLABLE SHEE", "Lo", 0),
("VAI SYLLABLE ZEE", "Lo", 0),
("VAI SYLLABLE ZHEE", "Lo", 0),
("VAI SYLLABLE CEE", "Lo", 0),
("VAI SYLLABLE JEE", "Lo", 0),
("VAI SYLLABLE NJEE", "Lo", 0),
("VAI SYLLABLE YEE", "Lo", 0),
("VAI SYLLABLE KEE", "Lo", 0),
("VAI SYLLABLE NGGEE", "Lo", 0),
("VAI SYLLABLE GEE", "Lo", 0),
("VAI SYLLABLE MEE", "Lo", 0),
("VAI SYLLABLE NEE", "Lo", 0),
("VAI SYLLABLE NYEE", "Lo", 0),
("VAI SYLLABLE I", "Lo", 0),
("VAI SYLLABLE IN", "Lo", 0),
("VAI SYLLABLE HI", "Lo", 0),
("VAI SYLLABLE HIN", "Lo", 0),
("VAI SYLLABLE WI", "Lo", 0),
("VAI SYLLABLE WIN", "Lo", 0),
("VAI SYLLABLE PI", "Lo", 0),
("VAI SYLLABLE BHI", "Lo", 0),
("VAI SYLLABLE BI", "Lo", 0),
("VAI SYLLABLE MBI", "Lo", 0),
("VAI SYLLABLE KPI", "Lo", 0),
("VAI SYLLABLE MGBI", "Lo", 0),
("VAI SYLLABLE GBI", "Lo", 0),
("VAI SYLLABLE FI", "Lo", 0),
("VAI SYLLABLE VI", "Lo", 0),
("VAI SYLLABLE TI", "Lo", 0),
("VAI SYLLABLE THI", "Lo", 0),
("VAI SYLLABLE DHI", "Lo", 0),
("VAI SYLLABLE DHHI", "Lo", 0),
("VAI SYLLABLE LI", "Lo", 0),
("VAI SYLLABLE RI", "Lo", 0),
("VAI SYLLABLE DI", "Lo", 0),
("VAI SYLLABLE NDI", "Lo", 0),
("VAI SYLLABLE SI", "Lo", 0),
("VAI SYLLABLE SHI", "Lo", 0),
("VAI SYLLABLE ZI", "Lo", 0),
("VAI SYLLABLE ZHI", "Lo", 0),
("VAI SYLLABLE CI", "Lo", 0),
("VAI SYLLABLE JI", "Lo", 0),
("VAI SYLLABLE NJI", "Lo", 0),
("VAI SYLLABLE YI", "Lo", 0),
("VAI SYLLABLE KI", "Lo", 0),
("VAI SYLLABLE NGGI", "Lo", 0),
("VAI SYLLABLE GI", "Lo", 0),
("VAI SYLLABLE MI", "Lo", 0),
("VAI SYLLABLE NI", "Lo", 0),
("VAI SYLLABLE NYI", "Lo", 0),
("VAI SYLLABLE A", "Lo", 0),
("VAI SYLLABLE AN", "Lo", 0),
("VAI SYLLABLE NGAN", "Lo", 0),
("VAI SYLLABLE HA", "Lo", 0),
("VAI SYLLABLE HAN", "Lo", 0),
("VAI SYLLABLE WA", "Lo", 0),
("VAI SYLLABLE WAN", "Lo", 0),
("VAI SYLLABLE PA", "Lo", 0),
("VAI SYLLABLE BHA", "Lo", 0),
("VAI SYLLABLE BA", "Lo", 0),
("VAI SYLLABLE MBA", "Lo", 0),
("VAI SYLLABLE KPA", "Lo", 0),
("VAI SYLLABLE KPAN", "Lo", 0),
("VAI SYLLABLE MGBA", "Lo", 0),
("VAI SYLLABLE GBA", "Lo", 0),
("VAI SYLLABLE FA", "Lo", 0),
("VAI SYLLABLE VA", "Lo", 0),
("VAI SYLLABLE TA", "Lo", 0),
("VAI SYLLABLE THA", "Lo", 0),
("VAI SYLLABLE DHA", "Lo", 0),
("VAI SYLLABLE DHHA", "Lo", 0),
("VAI SYLLABLE LA", "Lo", 0),
("VAI SYLLABLE RA", "Lo", 0),
("VAI SYLLABLE DA", "Lo", 0),
("VAI SYLLABLE NDA", "Lo", 0),
("VAI SYLLABLE SA", "Lo", 0),
("VAI SYLLABLE SHA", "Lo", 0),
("VAI SYLLABLE ZA", "Lo", 0),
("VAI SYLLABLE ZHA", "Lo", 0),
("VAI SYLLABLE CA", "Lo", 0),
("VAI SYLLABLE JA", "Lo", 0),
("VAI SYLLABLE NJA", "Lo", 0),
("VAI SYLLABLE YA", "Lo", 0),
("VAI SYLLABLE KA", "Lo", 0),
("VAI SYLLABLE KAN", "Lo", 0),
("VAI SYLLABLE NGGA", "Lo", 0),
("VAI SYLLABLE GA", "Lo", 0),
("VAI SYLLABLE MA", "Lo", 0),
("VAI SYLLABLE NA", "Lo", 0),
("VAI SYLLABLE NYA", "Lo", 0),
("VAI SYLLABLE OO", "Lo", 0),
("VAI SYLLABLE OON", "Lo", 0),
("VAI SYLLABLE HOO", "Lo", 0),
("VAI SYLLABLE WOO", "Lo", 0),
("VAI SYLLABLE WOON", "Lo", 0),
("VAI SYLLABLE POO", "Lo", 0),
("VAI SYLLABLE BHOO", "Lo", 0),
("VAI SYLLABLE BOO", "Lo", 0),
("VAI SYLLABLE MBOO", "Lo", 0),
("VAI SYLLABLE KPOO", "Lo", 0),
("VAI SYLLABLE MGBOO", "Lo", 0),
("VAI SYLLABLE GBOO", "Lo", 0),
("VAI SYLLABLE FOO", "Lo", 0),
("VAI SYLLABLE VOO", "Lo", 0),
("VAI SYLLABLE TOO", "Lo", 0),
("VAI SYLLABLE THOO", "Lo", 0),
("VAI SYLLABLE DHOO", "Lo", 0),
("VAI SYLLABLE DHHOO", "Lo", 0),
("VAI SYLLABLE LOO", "Lo", 0),
("VAI SYLLABLE ROO", "Lo", 0),
("VAI SYLLABLE DOO", "Lo", 0),
("VAI SYLLABLE NDOO", "Lo", 0),
("VAI SYLLABLE SOO", "Lo", 0),
("VAI SYLLABLE SHOO", "Lo", 0),
("VAI SYLLABLE ZOO", "Lo", 0),
("VAI SYLLABLE ZHOO", "Lo", 0),
("VAI SYLLABLE COO", "Lo", 0),
("VAI SYLLABLE JOO", "Lo", 0),
("VAI SYLLABLE NJOO", "Lo", 0),
("VAI SYLLABLE YOO", "Lo", 0),
("VAI SYLLABLE KOO", "Lo", 0),
("VAI SYLLABLE NGGOO", "Lo", 0),
("VAI SYLLABLE GOO", "Lo", 0),
("VAI SYLLABLE MOO", "Lo", 0),
("VAI SYLLABLE NOO", "Lo", 0),
("VAI SYLLABLE NYOO", "Lo", 0),
("VAI SYLLABLE U", "Lo", 0),
("VAI SYLLABLE UN", "Lo", 0),
("VAI SYLLABLE HU", "Lo", 0),
("VAI SYLLABLE HUN", "Lo", 0),
("VAI SYLLABLE WU", "Lo", 0),
("VAI SYLLABLE WUN", "Lo", 0),
("VAI SYLLABLE PU", "Lo", 0),
("VAI SYLLABLE BHU", "Lo", 0),
("VAI SYLLABLE BU", "Lo", 0),
("VAI SYLLABLE MBU", "Lo", 0),
("VAI SYLLABLE KPU", "Lo", 0),
("VAI SYLLABLE MGBU", "Lo", 0),
("VAI SYLLABLE GBU", "Lo", 0),
("VAI SYLLABLE FU", "Lo", 0),
("VAI SYLLABLE VU", "Lo", 0),
("VAI SYLLABLE TU", "Lo", 0),
("VAI SYLLABLE THU", "Lo", 0),
("VAI SYLLABLE DHU", "Lo", 0),
("VAI SYLLABLE DHHU", "Lo", 0),
("VAI SYLLABLE LU", "Lo", 0),
("VAI SYLLABLE RU", "Lo", 0),
("VAI SYLLABLE DU", "Lo", 0),
("VAI SYLLABLE NDU", "Lo", 0),
("VAI SYLLABLE SU", "Lo", 0),
("VAI SYLLABLE SHU", "Lo", 0),
("VAI SYLLABLE ZU", "Lo", 0),
("VAI SYLLABLE ZHU", "Lo", 0),
("VAI SYLLABLE CU", "Lo", 0),
("VAI SYLLABLE JU", "Lo", 0),
("VAI SYLLABLE NJU", "Lo", 0),
("VAI SYLLABLE YU", "Lo", 0),
("VAI SYLLABLE KU", "Lo", 0),
("VAI SYLLABLE NGGU", "Lo", 0),
("VAI SYLLABLE GU", "Lo", 0),
("VAI SYLLABLE MU", "Lo", 0),
("VAI SYLLABLE NU", "Lo", 0),
("VAI SYLLABLE NYU", "Lo", 0),
("VAI SYLLABLE O", "Lo", 0),
("VAI SYLLABLE ON", "Lo", 0),
("VAI SYLLABLE NGON", "Lo", 0),
("VAI SYLLABLE HO", "Lo", 0),
("VAI SYLLABLE HON", "Lo", 0),
("VAI SYLLABLE WO", "Lo", 0),
("VAI SYLLABLE WON", "Lo", 0),
("VAI SYLLABLE PO", "Lo", 0),
("VAI SYLLABLE BHO", "Lo", 0),
("VAI SYLLABLE BO", "Lo", 0),
("VAI SYLLABLE MBO", "Lo", 0),
("VAI SYLLABLE KPO", "Lo", 0),
("VAI SYLLABLE MGBO", "Lo", 0),
("VAI SYLLABLE GBO", "Lo", 0),
("VAI SYLLABLE GBON", "Lo", 0),
("VAI SYLLABLE FO", "Lo", 0),
("VAI SYLLABLE VO", "Lo", 0),
("VAI SYLLABLE TO", "Lo", 0),
("VAI SYLLABLE THO", "Lo", 0),
("VAI SYLLABLE DHO", "Lo", 0),
("VAI SYLLABLE DHHO", "Lo", 0),
("VAI SYLLABLE LO", "Lo", 0),
("VAI SYLLABLE RO", "Lo", 0),
("VAI SYLLABLE DO", "Lo", 0),
("VAI SYLLABLE NDO", "Lo", 0),
("VAI SYLLABLE SO", "Lo", 0),
("VAI SYLLABLE SHO", "Lo", 0),
("VAI SYLLABLE ZO", "Lo", 0),
("VAI SYLLABLE ZHO", "Lo", 0),
("VAI SYLLABLE CO", "Lo", 0),
("VAI SYLLABLE JO", "Lo", 0),
("VAI SYLLABLE NJO", "Lo", 0),
("VAI SYLLABLE YO", "Lo", 0),
("VAI SYLLABLE KO", "Lo", 0),
("VAI SYLLABLE NGGO", "Lo", 0),
("VAI SYLLABLE GO", "Lo", 0),
("VAI SYLLABLE MO", "Lo", 0),
("VAI SYLLABLE NO", "Lo", 0),
("VAI SYLLABLE NYO", "Lo", 0),
("VAI SYLLABLE E", "Lo", 0),
("VAI SYLLABLE EN", "Lo", 0),
("VAI SYLLABLE NGEN", "Lo", 0),
("VAI SYLLABLE HE", "Lo", 0),
("VAI SYLLABLE HEN", "Lo", 0),
("VAI SYLLABLE WE", "Lo", 0),
("VAI SYLLABLE WEN", "Lo", 0),
("VAI SYLLABLE PE", "Lo", 0),
("VAI SYLLABLE BHE", "Lo", 0),
("VAI SYLLABLE BE", "Lo", 0),
("VAI SYLLABLE MBE", "Lo", 0),
("VAI SYLLABLE KPE", "Lo", 0),
("VAI SYLLABLE KPEN", "Lo", 0),
("VAI SYLLABLE MGBE", "Lo", 0),
("VAI SYLLABLE GBE", "Lo", 0),
("VAI SYLLABLE GBEN", "Lo", 0),
("VAI SYLLABLE FE", "Lo", 0),
("VAI SYLLABLE VE", "Lo", 0),
("VAI SYLLABLE TE", "Lo", 0),
("VAI SYLLABLE THE", "Lo", 0),
("VAI SYLLABLE DHE", "Lo", 0),
("VAI SYLLABLE DHHE", "Lo", 0),
("VAI SYLLABLE LE", "Lo", 0),
("VAI SYLLABLE RE", "Lo", 0),
("VAI SYLLABLE DE", "Lo", 0),
("VAI SYLLABLE NDE", "Lo", 0),
("VAI SYLLABLE SE", "Lo", 0),
("VAI SYLLABLE SHE", "Lo", 0),
("VAI SYLLABLE ZE", "Lo", 0),
("VAI SYLLABLE ZHE", "Lo", 0),
("VAI SYLLABLE CE", "Lo", 0),
("VAI SYLLABLE JE", "Lo", 0),
("VAI SYLLABLE NJE", "Lo", 0),
("VAI SYLLABLE YE", "Lo", 0),
("VAI SYLLABLE KE", "Lo", 0),
("VAI SYLLABLE NGGE", "Lo", 0),
("VAI SYLLABLE NGGEN", "Lo", 0),
("VAI SYLLABLE GE", "Lo", 0),
("VAI SYLLABLE GEN", "Lo", 0),
("VAI SYLLABLE ME", "Lo", 0),
("VAI SYLLABLE NE", "Lo", 0),
("VAI SYLLABLE NYE", "Lo", 0),
("VAI SYLLABLE NG", "Lo", 0),
("VAI SYLLABLE LENGTHENER", "Lm", 0),
("VAI COMMA", "Po", 0),
("VAI FULL STOP", "Po", 0),
("VAI QUESTION MARK", "Po", 0),
("VAI SYLLABLE NDOLE FA", "Lo", 0),
("VAI SYLLABLE NDOLE KA", "Lo", 0),
("VAI SYLLABLE NDOLE SOO", "Lo", 0),
("VAI SYMBOL FEENG", "Lo", 0),
("VAI SYMBOL KEENG", "Lo", 0),
("VAI SYMBOL TING", "Lo", 0),
("VAI SYMBOL NII", "Lo", 0),
("VAI SYMBOL BANG", "Lo", 0),
("VAI SYMBOL FAA", "Lo", 0),
("VAI SYMBOL TAA", "Lo", 0),
("VAI SYMBOL DANG", "Lo", 0),
("VAI SYMBOL DOONG", "Lo", 0),
("VAI SYMBOL KUNG", "Lo", 0),
("VAI SYMBOL TONG", "Lo", 0),
("VAI SYMBOL DO-O", "Lo", 0),
("VAI SYMBOL JONG", "Lo", 0),
("VAI DIGIT ZERO", "Nd", 0),
("VAI DIGIT ONE", "Nd", 0),
("VAI DIGIT TWO", "Nd", 0),
("VAI DIGIT THREE", "Nd", 0),
("VAI DIGIT FOUR", "Nd", 0),
("VAI DIGIT FIVE", "Nd", 0),
("VAI DIGIT SIX", "Nd", 0),
("VAI DIGIT SEVEN", "Nd", 0),
("VAI DIGIT EIGHT", "Nd", 0),
("VAI DIGIT NINE", "Nd", 0),
("VAI SYLLABLE NDOLE MA", "Lo", 0),
("VAI SYLLABLE NDOLE DO", "Lo", 0),
)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/break-continue-09.typ | typst | Other | // Ref: true
// Should output `Some` in red, `Some` in blue and `Last` in green.
// Everything should be in smallcaps.
#for color in (red, blue, green, yellow) [
#set text(font: "Roboto")
#show: it => text(fill: color, it)
#smallcaps(if color != green [
Some
] else [
Last
#break
])
]
|
https://github.com/jakemorris32/BScProject | https://raw.githubusercontent.com/jakemorris32/BScProject/main/notebook.typ | typst | #import "@preview/colorful-boxes:1.3.1": *
// ----------------------------------------------
// Template
// ----------------------------------------------
#let title = [Scintillator detectors for ionising radiation]
#let subtitle = [Project Notebook]
#set page(
"a4",
)
#set text(font: "New Computer Modern")
// TITLE-----------------------------------------
#line(length: 100%, stroke: 1pt)
#align(center, text(17pt)[#title])
#align(center, text(11pt)[#subtitle])
#line(length: 100%, stroke: 1pt)
// ----------------------------------------------
// ----------------------------------------------
// DOCUMENT
// ----------------------------------------------
#pagebreak()
\
#line(length: 100%, stroke: 0.5pt)
#align(right)[Date: 02/10/2024]
= Definitions
*Scintillator crystals* - emit light when excited by ionising radiation.
*Scilicon Photomultiplier (SiPM)* - alternative to traditional vacuum photomultiplier tubes.
*Scintillator detectors* - scintillator crystal coupled with SiPM. Light emitted by the scintillator results in a electrical pulse. Pulse shape discrimination is used to identify the type of ionising particle.
= In-beam gamma-ray spectroscopy at the RIBF
=== Overview of gamma-ray spectroscopy
- In beam $gamma$-ray spectroscopy is used to study exotic nuclei by measuring $gamma$-rays emitted during nuclear reactions.
- The Radioactive Isotope Beam Factory (RIBF) uses a high efficeincy $gamma$-ray spectrometer to analyse secondary reaction products.
=== Physics case
- The method is used to explore shell evolution, the shell structure of known and predicted magic numbers in unstable states.
- A large area of nuclear structure research involves the driving mechanisms for shell evolution.
- In-beam $gamma$-ray spectroscopy is useful for studying basic properties of exotic nuclei for this case.
=== Challenges
- Doppler correction in gamma-rau energy is necessary due to high secondary beam velocity.
- Unwanted gamma-ray signals from background atomic processes need to be accounted for.
- Scattering/angular and energy straggling due to thick targets.
=== Experimental setup
- The setup consists of the BigRIPS fragment seperator to produce and seperate RI beams, a secondary target surrounded by a $gamma$-ray spectrometer, and the ZeroDegree recoil seperator.
- The two available gamma-ray detectors used in this setup are DALI2 and GRAPE.
- *DALI2* consists of large NAI(TI) scintillators. The crystals are long to allow for high full energy peak (FEP) efficiency for high energy $gamma$ rays. Optimum detector arrangement was found using GEANT4 Monte Carlo simuilations. The configuration consists of 186 crystals arranged in 12 layers.
- *GRAPE* is a postion sensitive Ge detector array. Pulse shape analysis is used to extract position data.
- DALI2 provides high efficiency but moderate energy resolution while GRAPE has higher energy resolution and position sensitivitiy.
=== Application and results
- The first experiments using the BigRIPS/ZeroDegree setup in was able to produce doppler shift corrected gamma-ray specta to provide insight into shell structure and nuclear deformation.
\
#line(length: 100%, stroke: 0.5pt)
#align(right)[Date: 04/10/2024]
|
|
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/results/results_poc.typ | typst | #import "../../../acronyms.typ": *
= Proof of Concept
The project produced a proof of concept application that implements the design concept as described in @design-iteration-2.
Although the application doesn't offer visualizations for some of the most common aspects of functional programming, such as the construction of custom data types, the application shows that the proposed concept for function composition works and is easy to use.
So, in the author's opinion, the project's main goal was achieved.
To make the application ready for use in a classroom, the use cases that weren't achieved during this project, as shown in @requirement_validation, need to be implemented.
In addition, there is some potential for improvement in the current implementation of the #ac("PoC").
The choice for Threepenny as the #ac("UI") framework was made primarily due to the given time constraints and the expectation that Threepenny allows for fast progress while implementing the #ac("PoC"), which proved to be true.
But a #ac("UI") technology that doesn't require a local web server, probably a GHCJS-based framework, would be better suited to implement a full version of VisualFP, as it would enable the application to be served to any browser as a set of static files.
A different #ac("UI") framework may also provide better support for functional reactive programming, which is expected to make the #ac("UI") implementation more concise.
== macOS Electron App
For the project submission, the #ac("PoC") Electron application was packaged for Windows, Linux & macOS.
Unfortunately, the macOS app has an unforeseen issue: It doesn't pass the macOS gatekeeper checks.
Based on code signature, notarization, and comparison with known malware, gatekeeper flags potentially dangerous applications and restricts them from execution.
@apple-gatekeeper
In the case of VisualFP, the error message "“VFP.app” is damaged and can't be opened. You should move it to the Bin." appears when trying to execute the application.
Gatekeeper can be bypassed using the command `xattr -c VFP.app`, with "VFP.app" being the application name, to execute the application anyway.
A future project would need to address this issue to make the application usable for a broader audience. |
|
https://github.com/0xPARC/0xparc-intro-book | https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/easy.typ | typst | #import "src/preamble.typ":*
#set page(
width: 5.5in,
height: 8.5in,
margin: (inside: 0.6in, outside: 0.6in, top: 0.8in, bottom: 0.5in),
header-ascent: 40%,
)
#let chapter(filename) = {
include filename
}
#show: evan.with(
title: "Four Easy Pieces in Programmable Cryptography",
long-title: [Four Easy Pieces in \ Programmable \ Cryptography],
author: "0xPARC",
date: datetime.today(),
)
#v(4em)
#quote[
I can prove to you that I have a message $M$ such that
$sha(M) = "0xa91af3ac..."$, without revealing $M$.
But not just for the hash function sha.
I can do this for any function you want.
]
#pagebreak()
#toc
#pagebreak()
#set heading(offset: 1)
#authoredpart[Introduction][<NAME> and <NAME>]
#chapter("src/intro.typ")
#authoredpart[Two-party Computation][Brian Gu and Brian Lawrence]
#chapter("src/mpc.typ")
#chapter("src/ot.typ")
#chapter("src/2pc-takeaways.typ")
#authoredpart[SNARKs Prelude: Elliptic Curves and Polynomial Commitments][Evan Chen]
#chapter("src/ec.typ")
#chapter("src/pair.typ")
#chapter("src/kzg.typ")
#chapter("src/kzg-takeaways.typ")
#authoredpart[SNARKs][Evan Chen]
#chapter("src/zkintro.typ")
#chapter("src/plonk.typ")
#chapter("src/copy-constraints.typ")
#chapter("src/fs.typ")
#chapter("src/snark-takeaways.typ")
#authoredpart[Fully Homomorphic Encryption][Brian Lawrence and <NAME>hang]
#chapter("src/fhe0.typ")
#chapter("src/lwe.typ")
#chapter("src/fhe2.typ")
#chapter("src/fhe3.typ")
#chapter("src/fhe-takeaways.typ")
#authoredpart[Oblivious RAM][Elaine Shi]
#chapter("src/oram.typ")
#chapter("src/oram-takeaways.typ") |
|
https://github.com/Champitoad/typst-slides | https://raw.githubusercontent.com/Champitoad/typst-slides/main/eg.typ | typst | Creative Commons Zero v1.0 Universal | #import "utils.typ": *
#let juxt = h(1em)
#let get_colors(inv) = {
let fg = if inv { white } else { black }
let bg = if inv { black } else { white }
(fg: fg, bg: bg)
}
#let cut(eg, inv: false, inset: 5pt) = {
let (fg, bg) = get_colors(inv)
circle(fill: bg, stroke: none, inset: inset)[
#set text(fill: fg)
#eg
]
}
#let sheet(eg, inv: false) = {
let (fg, bg) = get_colors(inv)
rect(inset: 8pt, stroke: fg, fill: bg, {
set text(fill: fg)
set square(stroke: fg)
eg
})
}
#let nscroll(inv: true, fontsize: auto, outloop: (:), inloops: ()) = {
let n = inloops.len()
let r = mget(outloop, "size", 3cm)
let default_outloop_size = r / 4
let j = r / 24 // Join point radius
let θ = -calc.pi / 2
let (fg, bg) = get_colors(inv)
let inloops_data = (:)
for i in range(n) {
let outloop = inloops.at(i)
let default_name = str(i)
let name = mget(outloop, "name", default_name)
let content = mget(outloop, "content", none)
let p = mget(outloop, "size", default_outloop_size)
let μ = 2 * i * calc.pi / n + θ
let angle = (x: calc.cos(μ), y: calc.sin(μ))
// Compute coordinates of outloop center and join point
let center = (x: (r - p) * angle.x, y: (r - p) * angle.y)
let join = (x: r * angle.x, y: r * angle.y)
// Shift coordinates for #place
let center_coords = shift(center, (x: r - p, y: r - p))
let join_coords = shift(join, (x: r - j, y: r - j))
let (inloop_circle, inloop_join) = {
if content != none {(
// Draw the outloop circle
circle(radius: p, fill: fg, stroke: none)[
#set text(fill: bg)
#set align(alignment.center + horizon)
#content
],
// Draw the outloop join point
circle(radius: j, fill: orange, stroke: none)
)} else {
(none, none)
}
}
// Save drawings and coordinates in a dictionary, for returning later
inloops_data.insert(name, (
circle: (element: inloop_circle, coords: center_coords),
join: (element: inloop_join, coords: join_coords)
))
}
// Draw the outloop circle
let inloop_circle = circle(radius: r, fill: bg, stroke: fg)[
#set text(fill: fg)
#set align(center + horizon)
#mget(outloop, "content", none)
]
// Join outloop and inloops in a box
let size = 2 * r
let content = box(width: size, height: size)[
#set text(size:
if fontsize == auto { default_outloop_size }
else { fontsize }
)
#place(inloop_circle)
#for (name, (circle, join)) in inloops_data {
place(circle.element, dx: circle.coords.x, dy: circle.coords.y)
place(join.element, dx: join.coords.x, dy: join.coords.y)
}
]
// Return content and inloops data
(content: content, inloops: inloops_data)
}
#let curl = nscroll(outloop: (content: $a$, size: 6cm), inloops: (
(content: $b$), (content: $c$), (content: $d$), (content: $e$), (content: $f$),
))
#curl.content
#curl.inloops |
https://github.com/HEIGVD-Experience/docs | https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/ARO/docs/3-Fetch/fetch.typ | typst | #import "/_settings/typst/template-note.typ": conf
#show: doc => conf(
title: [
Fetch
],
lesson: "ARO",
chapter: "3 - Fetch",
definition: "La documentation suivante traite du fonctionnement du registre de compteur de programme (PC) dans les architectures informatiques. Elle explique comment le PC stocke l'adresse de l'instruction en cours d'exécution, comment il est incrémenté et géré lors de sauts inconditionnels ou conditionnels. De plus, elle aborde la gestion des sauts, des interruptions et des vecteurs d'interruption dans les processeurs.",
col: 1,
doc,
)
= Opération FETCH
L'opération de fetch (récupération) dans un processeur consiste à récupérer l'instruction suivante depuis la mémoire, en utilisant l'adresse stockée dans le compteur de programme (PC). Cette instruction est ensuite placée dans le registre d'instruction (IR) pour être décodée et exécutée ultérieurement.
= Program Counter (PC)
Le programme counter (PC) est un registre qui contient l'adresse de l'instruction courante à éxécuter. Il est incrémenté à chaque instruction pour passer à l'instruction suivante *sauf si un saut est effectué*.
== Incrémenter le PC
La valeur de l’incrément correspond au nombre de bytes de l’instruction, indépendamment du bus d’adresses!
#table(
columns: (1fr, 1fr),
[*Code d'instruction*], [*Incrément*],
"8 bits = 1 byte", "1",
"16 bits = 2 bytes", "2",
"32 bits = 4 bytes", "4",
)
#image("/_src/img/docs/image copy 7.png")
== Adresse suivante avec un saut
Dans le cas ou un saut doit être réalisé l'incrément de l'adresse est quand même réalisé sauf que celle-ci n'est pas insérée dans le PC à la place on viendra y insérer l'adresse de la prochaine instruction suite au saut.
#image("/_src/img/docs/image copy 8.png")
= Gestion des sauts
Les sauts sont des instructions qui permettent de modifier le PC pour exécuter une instruction à une adresse différente de celle suivante. Il existe plusieurs types de sauts:
== Déclanché par une instruction
- Saut inconditionnel
- Exemple : Retour au début d’un programme
- Saut conditionnel
- Exemple : Exécution d’une boucle
- Appel de fonction
== Déclanché matériellement
- Interruption
- Exception
== Saut inconditionnel
#image("/_src/img/docs/image copy 9.png")
L'opcode pour un saut inconditionnel prends 5 bits et le reste est alloué pour donner l'adresse de la prochaine instruction à exécuter.
=== Calcul de l'adresse de saut
Pour calculer l'adresse de saut il suffit d'utiliser la formule suivante :
$
"Adr" = "PC" + "extension_16bits"("offset"_11 * 2) + 4
$
#table(
columns: (0.5fr, 1fr),
[*Code d'instruction*], [*Incrément*],
"Adr", "Adresse finale du saut",
"PC", "Adresse de l'instruction courante",
"Extension 16 bits", "Extension de l'adresse de saut en y ajoutant la valeur du bit de signe",
"Offset","Correspond à l'instruction moins les 5 bits de l'opcode",
"4", "Valeur en fixe à ajouter à l'adresse de saut"
)
== Saut conditionnel
#image("/_src/img/docs/image copy 10.png")
Pour calculer l'adresse de saut il suffit d'utiliser la formule suivante *attention elle est légèrement différente de celle pour le saut inconditionnel* :
$
"Adr" = "PC" + "extension_16bits"("offset"_8 * 2) + 4
$
#colbreak()
=== Gestion de la condition
#image("/_src/img/docs/image copy 11.png")
= Interruption
Les interruptions sont des signaux envoyés par des périphériques pour signaler un événement. Lorsqu'une interruption est reçue, le processeur suspend l'exécution du programme en cours et exécute une routine de traitement de l'interruption. Une fois la routine terminée, le processeur reprend l'exécution du programme interrompu. Il existe plusieurs type d'interruption:
- *Interruption par périphériques*
- timer, clavier, entrées /sorties (port série, parallèle, USB, disques, ….)
- *Erreurs systèmes*
- division par zéro, dépassement de capacité, protection mémoire, ...
- *Interruption processeur (IPI)*
- interruption par un autre processeur (système multi-processeurs)
== Gestion des interruptions
Il existe 5 modes de gestion des interruptions:
- Sans interruption (scrutation)
- Interruptions multi-sources sans identification de la source
- Interruptions multi-sources avec identification de la source
- Interruptions chaînées
- Interruptions imbriquées
=== Scrutation
Le processeur scrute périodiquement l’état des périphériques pour savoir s’ils ont besoin de son intervention. Cette méthode est simple mais consomme beaucoup de ressources.
=== Interruptions multi-sources sans identification de la source
Les interruptions sont gérées par un seul vecteur d’interruption. Le processeur doit interroger chaque périphérique pour savoir lequel a généré l’interruption.
#image("/_src/img/docs/image copy 12.png")
#colbreak()
=== Interruptions multi-sources avec identification de la source
Chaque périphérique possède un vecteur d’interruption. Le processeur interroge chaque périphérique pour savoir lequel a généré l’interruption.
#image("/_src/img/docs/image copy 13.png")
=== Interruptions chaînées
Les adresses des interruptions sont stockées dans une pile de stockage (stack) puis déplié au fur et à mesure de l'exécution des routines d'interruption.
#image("/_src/img/docs/image copy 14.png")
#colbreak()
=== Interruptions imbriquées
Les interruptions sont gérées par un contrôleur d’interruption qui attribue une priorité à chaque interruption. Lorsqu’une interruption est reçue, le contrôleur d’interruption détermine si elle doit être traitée ou non.
#image("/_src/img/docs/image copy 15.png")
= Vecteur d'interruption
Moyen technique pour attacher une routine d’interruption (ISR) à une requête d’interruption (IRQ). Le vecteur d’interruption est une table qui contient l’adresse de la routine d’interruption associée à chaque requête d’interruption. Lorsqu’une interruption est reçue, le processeur consulte le vecteur d’interruption pour connaître l’adresse de la routine d’interruption à exécuter.
== Calculer l'adresse du vecteur d'interruption
$
"Adresse vecteur" = "Adresse base" + ("No de l’interruption" * "Nbre bytes du bus d’instruction")
$ |
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/math-number-spacing.typ | typst | Apache License 2.0 | // Test spacing after numbers in math.
---
$
10degree \
10 degree \
10.1degree \
10.1 degree
$
|
https://github.com/ShapeLayer/ucpc-solutions__typst | https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/README.md | markdown | Other | # ucpc-solutions
[ucpc-solutions](https://github.com/ShapeLayer/ucpc-solutions__typst) is the template for solutions editorial of algorithm contests, used widely in the ["Baekjoon Online Judge"](https://acmicpc.net) users community in Korea.
The original version of ucpc-solution is written in LaTeX([ucpcc/2020-solutions-theme](https://github.com/ucpcc/2020-solutions-theme)), and this is the port of LaTeX ver.
This contains content-generating utils for making solutions editorial and ["solved.ac"](https://solved.ac) difficulty expression presets, a rating system for Baekjoon Online Judge's problems.
## Getting Started
```typst
#import "@preview/ucpc-solutions:0.1.0" as ucpc
#show: ucpc.ucpc.with(
title: "Code Race \nArena #3",
authors: ("Code Race Arena #3 TF", ),
)
```
### Requirements
**Fonts**
- [Inter](https://fonts.google.com/specimen/Inter)
- (optional) [Gothic A1](https://fonts.google.com/specimen/Gothic+A1)
- (optional) [Pretendard](https://github.com/orioncactus/pretendard/blob/main/packages/pretendard/docs/en/README.md)
## Examples
See [`/examples`](./examples/).
You can also see other usecase using the original LaTeX theme. See the [(KR) "Theme Usage Examples(테마 사용 예)" section](https://github.com/ucpcc/2020-solutions-theme#%ED%85%8C%EB%A7%88-%EC%82%AC%EC%9A%A9-%EC%98%88) in the origin repository's README.
## For Contributing
Requirements: [just](https://github.com/casey/just), [typst-test](https://github.com/tingerrr/typst-test)
**Recompile Refs for Testing**
```sh
just update-test
```
**Run Test**
```sh
just test
```
---
* Special Thanks: [@kiwiyou](https://github.com/kiwiyou) - about technical issue
* Since this ported version has been re-implemented only for appearance, this repository does not include the source code of any distribution or variant of ucpc-solutions.
|
https://github.com/dashuai009/dashuai009.github.io | https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/031.typ | typst | #let date = datetime(
year: 2022,
month: 8,
day: 28,
)
#metadata((
title: "费马小定理",
subtitle: [math,数论],
author: "dashuai009",
description: "费马小定理及其证明",
pubDate: date.display(),
))<frontmatter>
#import "../__template/style.typ": conf
#show: conf
== 费马小定理
<费马小定理>
设p为素数,a是任意整数,且$a equiv.not 0 (m o d med p)$,则
$ a^(p - 1) equiv 1 (m o d med p) . $
== 证明
<证明>
先来说明一个引理
=== 引理
设p是素数,a是任何整数,且$a equiv.not 0 (m o d med p)$,则数列
$ a , 2 a , 3 a , dots.h , (p - 1) a med med (m o d med p) $ 于数列
$ 1 , 2 , 3 , dots.h , (p - 1) med med (m o d med p) $
相同(忽略次序)。
=== 引理证明
<引理证明>
数列$a , 2 a , 3 a , dots.h , (p - 1) a$,含有$p - 1$ 个数字。
任取两个数$j a$和$k a$,假设它们同余: $ j a equiv k a (m o d med p) $
则$p \| (j - k) a$,又因为$a equiv.not 0 (m o d med p)$,所以$p \| (j - k)$。
而$1 lt.eq j , k lt.eq p - 1$,则
$0 lt.eq lr(|j - k|) lt.eq q - 2$,仅有$j = k$时,$p \| 0$。
所以,$a , 2 a , 3 a , dots.h , (p - 1) a$模p不同余。
p-1个数模p不同余,这p-1个余数一定就是$1 , 2 , dots.h , p - 1$。得证。
== 证明费马小定理
<证明费马小定理>
引理中的两个数列连乘得:
$ a dot.op (2 a) dots.h dot.op (p - 1) a equiv 1 dot.op 2 dots.h dot.op (p - 1) (m o d p) $
即
$ a^(p - 1) (p - 1) ! equiv (p - 1) ! (m o d med p) $
又有$(p - 1) !$与$p$互素,两边消掉得
$a^(p - 1) equiv 1 (m o d med p)$
得证。
== 利用费马小定理简单判断一个数是不是质数
a可以随便取,比如取2,只要计算出$2^(m - 1) #h(0em) mod med m eq.not 1$,那就说明m不是质数。
比如
当$m = 10^6 + 7$时,$2^(m - 1) #h(0em) mod med m = 399097$,所以$1 e 6 + 7$不是质数。
注意,若 $2^(m-1) mod m eq 1 $,#strong[m不一定是质数]
|
|
https://github.com/duskmoon314/THU_AMA | https://raw.githubusercontent.com/duskmoon314/THU_AMA/main/docs/ch3/1-基本概念与例子.typ | typst | Creative Commons Attribution 4.0 International | #import "/book.typ": *
#show: thmrules
#show: book-page.with(title: "基本概念与例子")
= 基本概念与例子
== 定义
#definition()[
非空集合$R$中有两种运算,记为$+$和$dot.op$,若满足:
+ $lr((R , +))$为交换群
+ $lr((R , dot.op))$为半群
+ 左右分配律成立:$a lr((b + c)) = a b + a c , lr((a + b)) c = a c + b c$
则称代数系统$lr((R ; + , dot.op))$为一个#strong[环(ring)]。
]
#remark()[
由加法结构已很好,于是重点关注乘法结构:含幺环、交换环、可除环
所谓的$+$和$dot.op$,并不一定是我们熟悉的加法和乘法,只是为了方便记号,实际上可以是任意的两种运算。
]
== 环的典型例子
数环:$lr((bb(Z) , + , dot.op)) , lr((bb(Q) , + dot.op)) , lr((bb(R) , + , dot.op)) , lr((bb(C) , + , dot.op))$ 含幺交换环
剩余类环:$lr((bb(Z) \/ n bb(Z) , + , dot.op))$
Gauss整环:$lr((bb(Z) lr([i]) , + , dot.op)) = { a + b i \| a , b in bb(Z) }$ (二平方和问题) \
可推广为 $bb(Z) lr([sqrt(d)]) = { a + b sqrt(d) \| a , b in bb(Z) }$,其中$d$为无平方因子
矩阵环(非交换): $M_n lr((bb(Z))) = { lr((a_(i j)))_(n times n) \| a_(i j) in bb(Z) }$,可推广为$M_n lr((R))$,其中$R$为任意环 \
$M_n lr((F))$($F$为域)$arrow.r.double$ 线性代数
多项式环(交换):$lr((bb(Z) lr([x]) , + , dot.op)) , lr((R lr([x]) , + , dot.op)) , lr((f lr([x]) , + , dot.op))$
映射环(非交换):$L lr((V)) : V$上全体线性变换,$lr((E n d G , + , dot.op))$其中$G$为交换群,自同态环 \
$lr((f + g)) lr((x)) eq.delta f lr((x)) + g lr((x)) , lr((f g)) lr((x)) eq.delta f lr((g lr((x))))$
== 环内特殊元与基本性质
加法幺元:零元$0$;乘法幺元:幺元$1$ \
加法逆元:负元$- a$;乘法逆元:逆元$a^(- 1)$
#property()[
+ 零元 $0 dot.op a = a dot.op 0 = 0 lr((forall a in R))$
#proof()[
$b a = lr((b + 0)) a = b a + 0 a arrow.r.double 0 a = 0$
]
+ 负元 $lr((- a)) b = a lr((- b)) = - lr((a b)) lr((forall a , b in R))$
#proof()[
$lr((- a)) b + a b = lr((- a + a)) b = 0 b = 0 arrow.r.double lr((- a)) b = - lr((a b))$
]
+ 减法分配律 $a lr((b - c)) = a b - a c , lr((a - b)) c = a c - b c lr((forall a , b , c in R))$
+ 倍数与方幂 $n a = a + dots.h.c + a lr((n upright("个") a)) , a^n = a dot.op dots.h.c dot.op a lr((n upright("个") a))$
+ 单位与单位元:单位元即幺元,单位即可逆元,记作$U lr((R))$或$R^(\*)$
+ 零因子与消去律
#definition()[
设$R$为环,$a , b in R$,若$a b = 0$且$a eq.not 0 , b eq.not 0$,则称$a$为#strong[左零因子],$b$为#strong[右零因子]。
若一个元素既是左零因子又是右零因子,则称其为#strong[零因子]。
]
#theorem()[
环$R$中无左右零因子$arrow.l.r.double R$中消去律成立
]
#proof()[
- 设$a eq.not 0 , a b = a c arrow.r.double a lr((b - c)) = 0$,由$R$中无零因子可知$b - c = 0 arrow.r.double b = c arrow.r.double$ 消去律成立
- 设$a b = 0$,若$a eq.not 0$,则$a b = 0 arrow.r.double b = 0$,故$R$中无零因子
]
#corollary()[
环$R$中,零因子$sect U lr((R)) = nothing$
]
]
== 环的分类
交换环与非交换环,有限环与无限环,含幺环与非含幺环……
#definition()[
设$R$为环
+ 若$R eq.not { 0 }$,含幺可交换且无零因子,则称$R$为#strong[整环(domain)]
+ 若$R$中至少包含$0 , 1 lr((0 eq.not 1))$,且$R \\ { 0 }$构成乘法群,则称$R$为#strong[(可)除环(division ring)]
]
四元数环(quaternions): \
设$e , i , j , k$满足$i^2 = j^2 = k^2 = - e$,$e$为幺元,$i j = k = - j i , j k = i = - k j , k i = j = - i k$ \
$bb(H) = { a e + b i + c j + d k \| a , b , c , d in bb(R) }$ 四元数除环,可逆
#theorem()[
设$lr((bb(Z) \/ n bb(Z) ; + , dot.op))$是域的充要条件是$n$为素数
]
#theorem()[
一个非零的有限的无零因子环是除环。进而,有限整环是域。
]
有限 + 无零因子 $arrow.r.double$ 非零元可逆
#proof()[
设$R eq.not { 0 }$为环,$R < oo , lr(|R|) \\ { 0 } eq.not nothing , lr((R \\ { 0 } , dot.op))$为有限半群
令$R \\ { 0 } = { a_1 , a_2 , dots.h.c , a_n }$,由于无零因子,故消去律成立,则
$a a_i = a a_j arrow.l.r.double a_i = a_j lr((forall a in R \\ { 0 }))$
故$a lr((R \\ { 0 })) = { a a_1 , a a_2 , dots.h.c , a a_n } = R \\ { 0 } arrow.r.double exists a_j$使得$a a_j = a arrow.r.double a_j = 1 arrow.r.double R \\ { 0 }$含幺。进一步$exists a_k$使得$a a_k = 1 arrow.r.double a$有逆元$lr((forall a eq.not 0)) arrow.r.double lr((R \\ { 0 } , dot.op))$构成群$arrow.r.double lr((R , + , dot.op))$构成除环
]
== 由已知环构造新环
记$R$为环:
+ $M_n lr((R)) , R lr([x])$均为环
+ $R lr([lr([x])]) = { sum_(i = 0)^oo a_i x^i \| a_i in R }$幂级数环
+ $R_1 times R_2 = { lr((a , b)) \| a in R_1 , b in R_2 } , {lr((a_1 , b_1)) + lr((a_2 , b_2)) eq.delta lr((a_1 + a_2 , b_1 + b_2))\
lr((a_1 , b_1)) dot.op lr((a_2 , b_2)) eq.delta lr((a_1 dot.op a_2 , b_1 dot.op b_2))$ 环的直积
$U lr((R lr([x]))) = U lr((R)) , med U lr((R lr([lr([x])]))) = {
f lr((x)) in R lr([lr([x])]) \| f lr((0)) = a_0 in U lr((R))
}$
利用幂级数表示周期序列:
$frac(1, 1 - x^n) = 1 + x^n + dots.h.c arrow.l lr((1 , 0 , dots.h.c , 0)) ; lr((a_0 , dots.h.c , a_(n - 1))) arrow.r frac(a lr((x)), 1 - x^n) = frac(g lr((x)), f lr((x)))$
如何从给定的分母$f lr((x))$确定周期$n$?参见《代数与编码》 |
https://github.com/jeremiahdanielregalario/BS-Mathematics-UP-Diliman-Course-Notes | https://raw.githubusercontent.com/jeremiahdanielregalario/BS-Mathematics-UP-Diliman-Course-Notes/main/Math%20110.1%20(Abstract%20Algebra%20I)/Math%20110.1%20Unit%203.typ | typst | #set text(font: "Fira Sans Math")
#set page(paper: "a4")
#set text(size: 30pt)
#set align(horizon)
= Math 110.1
ABSTRACT ALGEBRA I: Unit III
#set text(size: 14pt, )
#emph[Course Notes by: <NAME>] \
#emph[II-BS Mathematics] \
#emph[University of the Philippines - Diliman] \
#emph[Dr. <NAME>]
#pagebreak()
#set page(
margin: (top: 60pt, bottom: 60pt),
numbering: "1",
)
#set text(font: "Fira Sans Math", size: 12pt)
#set align(top)
= Rings
#line(length: 100% )
#underline[=== Definition:]
A _#underline[ring]_ $angle.l R, +, · angle.r$ is a set together with two binary operations $bold(+)$ (called
_addition_) and $bold(·)$ (called _multiplication_) such that the following axioms are
satisfied:
+ $angle.l R, + angle.r$ is an #underline[_abelian group_].
+ Multiplication is #underline[_associative_], that is, for all $a, b, c, ∈ RR$, $(a · b) · c = a · (b · c)$
+ For all $a, b, c ∈ RR$, $a · (b + c) = a · b + a · c$ and $(a + b) · c = a · c + b · c$ (#underline[_left and right distributive laws holds_].)
#underline[=== Examples:]
+ $ZZ$ is closed under the usual addition $+$ and multiplication $dot$.
+ : $angle.l ZZ, + angle.r$ is an abelian group.
+ : $·$ is associative.
+ : Left and right distributive laws holds
Thus, $angle.l ZZ, +, dot angle.r$ is a ring.
+ $angle.l QQ, +, dot angle.r$ , $angle.l RR, +, dot angle.r$ and $angle.l CC, +, dot angle.r$ are rings.
#underline[=== Remarks:]
+ If the operations $+$ and $·$ are clear from context we denote the ring $angle.l R, +, dot angle.r$ simply by $R$.
+ The identity of the group $angle.l R, + angle.r$ is denoted $0$ and is called the _#underline[zero element]_ of $R$.
+ The inverse of $a$ in the group $angle.l RR, + angle.r$ is denoted $−a$.
+ We write $a − b$ for $a + (−b)$.
+ To simplify notations, we write $a b$ for $a · b$.
+ In the absence of parentheses, multiplication is assumed to be performed before addition, that is, $a b + c = (a b) + c$
\
== #underline[Commutative Rings, Rings with Unity, and Units]
#underline[=== Definition:]
Let $R$ be a ring.
+ If multiplication in $R$ is commutative, then $R$ is called a #underline[_commutative ring_].
+ An element $1_R$ such that $∀r ∈ R, 1_R r = r = r 1_R$ is called a _#underline[multiplicative identity]_ or a #underline[_unity_].
+ If $R$ has a multiplicative identity, then $R$ is called a _#underline[ring with unity]_.
+ Suppose $R$ is a ring with unity $1_R eq.not 0$. An element $u ∈ R$ is a #underline[_unit_] if $u$ has a multiplicative inverse, that is $∃u^(−1) ∈ RR$ such that $u u^(−1) = 1_R = u^(−1)u$.
#underline[=== Remarks:]
+ Some rings are #underline[not commutative] and some have #underline[no unity].
+ If $R$ has unity, then this unity is unique.
+ If $R$ has unity $1_R$, then $1_R$ is a unit in $R$.
+ If $R$ has unity, #underline[not all] elements in the ring are units.
#underline[=== Examples:]
+ $angle.l ZZ, +, dot angle.r$ is a commutative ring with unity $1$. The units of $ZZ$ : $1, −1$.
+ $angle.l QQ, +, dot angle.r$ , $angle.l RR, +, dot angle.r$ and $angle.l CC, +, dot angle.r$ are commutative rings with unity $1$.
Every nonzero element in these rings is a unit.
+ $angle.l ZZ_n, +_n, dot_n angle.r$ is a commutative ring with unity 1. The set of units of $ZZ_n$ is denoted $U(n)$. Exercise: Determine the elements of $U(4)$ and $U(5)$.
#block(stroke: 1pt, radius: 5pt, inset: 10pt, width: 100%)[
- $U(4) = {a in ZZ_4 | exists k in ZZ "s.t." a dot_4k = 1} = {1, 3}$
- $U(5) = {a in ZZ_5 | exists k in ZZ "s.t." a dot_5k = 1} = {1, 2, 3, 4}$
]
+ $angle.l 2ZZ, +, dot angle.r$ is a commutative ring with no unity.
+ Let $display(M_2(RR) = {mat(a, b; c, d; delim: "[") mid(|) a, b, c, d, ∈ RR})$. Define $+$ and $·$ on $M_2(RR)$ as:
$
mat(a, b; c, d; delim: "[") + mat(e, f; g, h; delim: "[") = mat(a + e, b + f; c + g, d + h; delim: "[") \
mat(a, b; c, d; delim: "[")mat(e, f; g, h; delim: "[") = mat(a e + b g, a f + b h; c e + d g, c f + d h; delim: "[")
$
Then $M_2(RR)$ is a noncommutative ring with unity:
- $+$ is associative and commutative (Exercise)
- $·$ is associative but not commutative (Exercise)
- left and right distributive laws hold (Exercise)
- zero element: $display(mat(0,0; 0, 0; delim: "["))$; additive inverse: $display(mat(-a, -b; -c, -d; delim: "["))$; unity: $display(mat(1, 0; 0, 1; delim: "["))$
\
#underline[== Theorem 2.13]
#underline[=== Definition:]
Let $R$ be a ring with additive identity $0$. Let $a, b, c ∈ R$.
+ $a · 0 = 0 · a = 0$
+ $a(−b) = (−a)b = −(a b)$.
+ $(−a)(−b) = a b$
+ $a(b − c) = a b − a c "and" (a − b)c = a c − b c$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt)[
=== Proof:
#set enum(numbering: "(1.)")
+ $a · 0 + a · 0 = a(0 + 0) = a · 0$. By left cancellation, $a · 0 = 0$. The proof for $0 · a = 0$ follows analogously.
+ $a b + a(−b) = a(b − b) = a · 0 = 0$. Since the additive inverse of $a b$ is unique, $−(a b) = a(−b)$. The proof that $(−a)b = −(a b)$ proceeds analogously.
+ $(−a)(−b) = −[a(−b)] = −[−(a b)] = a b$
]
#underline[=== Remarks:]
+ If $R$ is a nonzero ring with unity then $1 eq.not 0$. (Why?)
+ If $R$ is a ring with unity and $a ∈ R$ then $(−1)a = −a$. In particular $(−1)(−1) = 1$.
+ Let $R$ be a ring and $a, b, c ∈ R$. If $a eq.not 0$ and $a b = a c$, then $b$ and $c$ are not necessarily equal. ($a eq.not 0 and a b = a c cancel(==>) b = c$)
- e.g. in $ZZ_4$, $2 ·_4 1 = 2 = 2 ·_4 3$ but $1 eq.not 3$.
+ In a ring $R$, $a b = 0$ does not necessarily mean that either $a = 0$ or $b = 0$.
- e.g. in $ZZ_6$, $2 ·_6 3 = 0$
\
#underline[== Group of Units of _R_ (Theorem 2.14) ]
#underline[=== Definition:]
Let $R$ be a ring with unity. The units of $R$ form a group
under multiplication.
#underline[=== Remark:]
The group of units of a ring with unity $R$ is denoted $U(R)$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
=== Proof:
- Closure under multiplication: Let $a, b ∈ U(R)$. (WTS: $a b ∈ U(R)$). Since $a, b ∈ U(R)$, $∃a^(−1), b^(−1) ∈ R$ such that $a a^(−1) = b b^(−1) = 1$. Note that $b^(−1)a^(−1) ∈ R$ and
$
(b^(-1)a^(-1))(a b) &= b^(-1)[(a^(-1))(a b)] \
&= b^(-1)[(a^(-1) a)b] \
&= b^(-1)[1 dot b] \
&= b^(-1)b \= 1
$
Thus $(a b)^(−1) = b^(−1)a^(−1)$ and so $a b ∈ U(R)$.
- Associativity of multiplication: Follows from $cal(R)_2$.
- Identity element under multiplication: unity $1 ∈ U(R)$ has the property that $ ∀a ∈ U(R) ⊆ R, a · 1 = 1 · a = a. $
- Inverse under multiplication: Let $a ∈ U(R)$. Then $∃a^(−1) ∈ R$ such that $a · a^(−1) = a^(−1) · a = 1$. From this, we see that $a^(−1) ∈ U(R)$.
$∴ angle.l U(R), · angle.r$ is a group.
]
#underline[=== Examples:]
+ $U(ZZ) = {1, −1} tilde.equiv ZZ_2$
+ $U(QQ) = QQ^(∗)$, $U(RR) = RR^(∗)$, $U(CC) = CC^(∗)$
+ $U(ZZ_n) = U(n)$ = set of all elements of $ZZ_n$ that are relatively prime to $n$
+ $U(M_2(RR)) = op("GL")(2, RR)$
#pagebreak()
= Fields and Division Rings
#line(length: 100% )
#underline[=== Definition:]
Let $R$ be a ring with unity $1 eq.not 0$. If every nonzero element of $R$ is a unit then $R$ is called a _#underline[division ring]_.
If $R$ is a commutative division ring, then $R$ is called a #underline[_field_].
#underline[=== Remarks:]
Let $R$ be a ring with unity $1 eq.not 0$.
+ If $R$ is a field, we write $display(a/b)$ for $a b^(−1) = b^(−1) a$. In particular, we write $b^(−1) = display(1/b).$
+ A division ring can be thought of as an algebraic structure that is closed under addition, subtraction, multiplication and division by nonzero elements.
+ $R$ is a division ring if and only if $R^(*) := R backslash {0}$ is a group.
+ $R$ is a field if and only if $R^(∗) := R backslash {0}$ is an abelian group.
#underline[=== Examples:]
+ $ZZ$ is not a division ring, and hence not a field.
+ $QQ, RR, CC$ are fields.
+ $ZZ_4$ is not a division ring. $because$ $0 eq.not 2 in ZZ_4$ is not a unit.
+ $ZZ_5$ is a field.
In $ZZ_5$:
- $display(3/4) = 3 dot_5 4^(−1) = 3 dot_5 4 = 2$
- $2 display(1/3) = 2 plus_5 display(1/3) = 2 plus_5 3^(-1) = 2 plus_5 2 = 4$
#pagebreak()
= Subrings and Subfields
#line(length: 100%)
#underline[== Subring]
#underline[=== Definition:]
A subset $S$ of a ring $R$ which is also a ring itself under the same operations as in $R$ is called a _#underline[subring]_ of $R$.
#underline[== Theorem 2.15]
Let $R$ be a ring and $S$ a nonempty subset of $R$. Then $S$ is
a subring of $R$ if and only if for all $a, b ∈ S$, $a − b ∈ S$ and $a b ∈ S$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
=== Proof:
$(==>)$ Since $S$ is a ring, then $angle.l S, + angle.r$ is an abelian group hence $a − b ∈ S$.
Also, $a b ∈ S$ since $·$ is a binary operation on $S$.
$(<==)$ Suppose $a − b ∈ S$ and $a b ∈ S$ for all $a, b ∈ S$.
$cal(R)_1$ : $a − b ∈ S$ for all $a, b ∈ S ==>$ $angle.l S, + angle.r$ is a subgroup of $angle.l R, + angle.r$. Thus, $angle.l S, + angle.r$ is an abelian group.
$cal(R)_2$ : and $cal(R)_3$ : follows since operations in $S$ and $R$ are the same.
]
#underline[=== Remarks:]
Let $R$ be a ring and $S$ a subring of $R$.
+ If $R$ is commutative, then $S$ is also commutative.
+ $S$ may be #underline[without] unity even if $R$ has unity.
\
#underline[== Subfields]
#underline[=== Definition:]
A subset $S$ of a field $F$ which is also a field itself under the same operations as in $F$ is called a #underline[_subfield_] of $F$.
#underline[=== Theorem 2.16]
Let $F$ be a field and $S$ a nonempty subset of $F$. Then $S$ is
a subfield of $F$ if and only if the following hold:
+ $S eq.not {0}$
+ for all $a, b ∈ S$, $a − b ∈ S $ and $ a b ∈ S$
+ for all $0 eq.not a ∈ S$, $a^(−1) ∈ S space.quad$ (_i.e. every nonzero element is a unit._)
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
=== Proof:
Exercise!
]
#underline[=== Examples:]
+ If $R$ is a ring then ${0}$ (trivial subring) and $R$ (improper subring) are subrings of $R$.
+ $QQ$ is a subfield of $RR$.
+ For any $n ∈ ZZ$, $n ZZ$ is a subring of $ZZ$. (Why?) Note that if $n eq.not 1, −1$, then $n ZZ$ has no unity.
+ Let $display(D_2(RR) = {mat(a, 0; 0, b; delim: "[") mid(|) a, b ∈ RR})$. Let $display(mat(a, 0; 0, b; delim: "[")), display(mat(c, 0; 0, d; delim: "[")) in D_2(RR),$
$
mat(a, 0; 0, b; delim: "[")-mat(c, 0; 0, d; delim: "[") = mat(a-c, 0; 0, b-d; delim: "[") in D_2(RR) \
mat(a, 0; 0, b; delim: "[")mat(c, 0; 0, d; delim: "[") = mat(a c, 0; 0, b d; delim: "[") in D_2(RR) \
$
$∴ D_2(RR)$ is a subring of $M_2(RR)$. $square.filled$
\
#underline[== Zero Divisors]
#underline[=== Definition:]
Let $R$ be a commutative ring. A nonzero element $a in R$ is called a _#underline[zero divisor]_ (or a divisor of zero) if there is a non-zero element $b in R$ such that $a b = 0$.
#underline[=== Example:]
+ zero divisors of $ZZ_12$: $2,3,4,6,7,8,9,10$\
+ $ZZ$ has no zero divisors.
#underline[=== Theorem 2.17:]
The zero divisors of $ZZ_n$ are its non-zero elements that are not relatively prime to $n$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*. Let $0 eq.not a in ZZ_n $.
$(==>)$ Suppose $a$ is a zero divisor of $ZZ_n$. Then, $exists (0 eq.not b in ZZ_n)$ s.t. $a b =0 ==> n divides a b$.
Suppose (on the contrary) that $a$ is relatively prime to $n$, then $n divides b ==> b = 0. arrow.zigzag$
$therefore$ $a$ is NOT relatively prime to $n$.
$(<==)$ Suppose $d = gcd(a, n) > 1$. Let $a = d k_1$ and $n = d k_2$ for some $k_1, k_2 in ZZ$. Note that $0 eq.not k_2 in ZZ_n$. Then
$
a k_2 = d k_1 k_2 = d k_2 k_1 = n k_1 = 0.
$
$therefore $ $a$ is a zero divisor. $square.filled$
]
#pagebreak()
= Integral Domain
#line(length: 100% )
#underline[=== Definition:]
A commutative ring with unity $1 eq.not 0$ is said to be an #underline[_integral domain_] if it has no zero divisors.
#underline[=== Remark:]
In an integral domain $D$, if $a b = 0$, then either $a = 0$ or $b = 0$.
#underline[=== Example:]
Division rings that are integral domains.
+ $ZZ space checkmark$
+ $QQ, CC, RR space checkmark$
+ $ZZ_p space checkmark$, where $p$ is prime.
+ $cancel(ZZ times ZZ)$ - has zero divisors $(0,a)$ and $(b,0)$ for some $0 eq.not a, b in ZZ$.
+ $cancel(M_2(RR) )$ - not a commutative ring
+ $cancel(2ZZ)$ - has no unity
#underline[=== Theorem 2.18:]
Let $R$ be a commutative ring with unity $1 eq.not 0$. Then, the cancellation law for multiplication holds in $R$ if and only if $R$ is an integral domain.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*.
$(==>)$ Suppose that $forall a, b, c in R$ with $a eq.not 0$ , $a b = a c ==> b = c$.
Let $a in R$ with $a eq.not 0$. Suppose that $a b = 0 = a dot 0$ for some $b in R$. Then, $ b = 0$. Hence, $a$ is a non-zero divisor of $R$.
$therefore $ $R$ is an integral domain.
$(<==)$ Suppose that $R$ is an integral domain. Let $a, b, c in R$ with $a eq.not 0$ and $a b = a c$.
$
a b = a c &==> a b - a c = 0 \
&==> a(b - c) = 0 \
&==> b - c = 0 \
&==> b = c
$
$therefore $ $forall a, b, c in R$ with $a eq.not 0$ , $a b = a c ==> b = c$.
$therefore $ Cancellation law for multipilcation holds if and only if $R$ is an integral domain. $square.filled$
]
#underline[=== Remarks:]
Let $R$ be an integral domain. Let $a, b in R$ with $a eq.not 0$.
+ Then $a x + b$ has at most one solution.
+ If $a$ is a unit in $R$, then $a x = b$ has exactly one solution, given by $x = display(b/a) = a^(-1)b$.
#underline[=== Theorem 2.19:]
Every field is an integral domain.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*.
Let $F$ be a field. Then, $F$ is commutative with unity $1 eq.not 0$.
Let $a in F$ s.t. $a eq.not 0$.
Suppose $a b = 0$ for some $b in F$.
$
&==> 1/a (a b) = 1/a dot 0 \
&==> (1/a dot a)b = 0 \
& ==> 1 dot b = 0\
&==> b = 0
$
$therefore a$ is not a zero divisor.
$therefore F$ is an integral domain. $square.filled$
]
#underline[=== Theorem 2.20:]
Every finite integral domain is a field.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*.
Let $D$ be a finite integral domain. Then, $D$ is commutative with unity $1 eq.not 0$.
Let $0 eq.not a in D$. (WTS: $a$ is a unit.)
Consider the function $f$ defined as:
$ f: D &-> D \
x &|-> a x
$
Suppose $f(x) = f(y)$ for some $x, y in D$. Then, $a x = a y ==> x = y$. (via C. L.)
So, $f$ is one-to-one $==>$ $f$ is onto.
Since $1 in D ==> exists b in D$ s.t. $f(b) = 1$.
$
&==> a b = 1 \
&==> a "is a unit"
$
$therefore D$ is a field. $square.filled$
]
#underline[=== Example:]
Let $p$ be prime. Then $ZZ_p$ is an integral domain $==> ZZ_p $ is a field.
Recall: $R$ is a ring, $a in R, n in NN$.
- $n dot a = underbrace(a + a + dots.c + a, n)$
- $(-n) a = underbrace(-a - a - dots.c - a, n)$
- $0 dot a = 0$
#underline[=== Example:]
+ In $M_2(RR)$,
$
3 dot mat(1, 1; 1, 1; delim: "[") = mat(1, 1; 1, 1; delim: "[") + mat(1, 1; 1, 1; delim: "[") + mat(1, 1; 1, 1; delim: "[") = mat(3, 3; 3, 3; delim: "[").
$
+ In $ZZ_6$: $underbrace(2, in ZZ) dot underbrace(3, in ZZ_6) = 3 +_6 3 = 0$.
#underline[=== Remark:]
If $R$ is a ring and $a, b in R$, $m, n in ZZ$, then
+ $(m + n)dot a = m dot a + n dot a$
+ $m (a + b) = m a + m b$
+ $(m n) a = m(n a)$
+ $m(a b) = (m a)b = a(m b)$
+ $(m a)(n b) = (m n) (a b)$
\
== #underline[Characteristic of a Ring]
#underline[=== Definition:]
The characteristic of a ring $R$ is the least positive integer $n$ such that $forall a in R, n dot a = 0$. If no such integer exists, $R$ is said to be of characteristic $0$.
#underline[=== Example:]
+ $ZZ_6 = {0, 1, 2, 3, 4, 5}$. $"char"(ZZ_6) = 6$.
+ char$(ZZ) = 0$.
+ $RR, QQ, CC$ are of characteristic $0$.
#underline[=== Theorem 2.21:]
Let $R$ be a ring with unity $1$.
+ If $1$ has infinite order, then $"char"(R) = 0.$
+ If $1$ has order $n$, then $"char"(R) = n$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*. (Exercise)
]
#underline[=== Example:]
+ $"char"(ZZ_n) = n$
+ $"char"(M_2(RR)) = 0$
#underline[=== Theorem 2.22:]
The characteristic of an integral domain is $0$ or prime.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*. (Exercise)
]
#pagebreak()
= Ideals and Factor Rings (Part I)
#line(length: 100% )
#underline[== Ideals]
#underline[=== Definition:]
A subring $I$ of a ring $R$ is called an #underline[ideal of _R_] if $forall r in R, forall a in I, r a in I "and" a r in I$.
#underline[=== Example:]
+ Let $R$ be a ring. Then, ${0}$ (#underline[_trivial ideal_]) and $R$ (#underline[_improper ideal_]) are ideals of $R$.
Ideal $I$ s.t. $I eq.not R$ is a #underline[_proper ideal_] of $R$.
+ $n ZZ subset.eq ZZ$ ($n in ZZ^(+)$)
$n ZZ$ is an ideal of $ZZ$.
$(because)$ Let $r in ZZ, x in n ZZ ==> x = n k$ for some $k in ZZ$. $x r = r x = r(n k) = (r n)k = (n r) k in n ZZ$.
$therefore n ZZ$ is an ideal of $ZZ$.
#underline[=== Ideal Subring Test (Theorem 2.23):]
Let $R$ be a ring and $cancel(circle) eq.not I subset.eq R$. Then, $I$ is an ideal if and only if the following hold:
+ $forall a, b in I, a -b in I$,
+ $forall r in R, a in I, r a in I "and" a r in I$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
#underline[=== Principal Ideal]
Let $R$ be a commutative ring with unity. Fix $a in R$. Consider ${a r | r in R} =: angle.l a angle.r = I$
- $a dot 1 = a in I$ so $I eq.not cancel(circle)$.
- Let $x, y in I ==> x = a r_1, y = a r_2$ for some $r_1, r_2 in R$.
$
x - y = a r_1 - a r_2 = a underbrace((r_1-r_2), in R) in I.
$
- Let $r in R, x in I ==> x = a r_1$ for some $r_1 in R$.
$
x r = r x = r (a r_1) = (r a)r_1 = (a r) r_1 = a (r r_1) in I.
$
$therefore I$ is an ideal of $R$.
$I$ is called the #underline[_principal ideal generated by $a$_], denoted $(a)$ or $angle.l a angle.r$.
]
#underline[=== Example:]
+ $ZZ$. Let $n in ZZ$. The principal ideal of $ZZ$ generated by $n$
$
angle.l n angle.r = {n dot k | k in ZZ} = n ZZ
$
#pagebreak()
#underline[== Factor Rings]
#underline[=== Concept:]
Consider $S$, subring of $R$. $angle.l S, + angle.r$ is a(n) (abelian) subgroup of the abelian group $angle.l R, + angle.r$. So, $S lt.tri.eq R$.
$R slash S ={r + S | r in R}$ is an abelian group under addition of left cosets.
$(*)$ Define multiplication of left cosets as follows:
$
(r_1 + S)(r_2 + S) = (r_1 r_2) + S
$
Note: It is not well-defined on some cases.
#underline[=== Lemma 2.24:]
Let $R$ be a ring and $I$ an ideal of $R$. Then, multiplication of left cosets of $I$ is a well-defined operation on the set $R slash I = {a + I | a in R}.$
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*. Suppose $a + I = c + I$ and $b + I = d + I$ for some $a, b, c, d in R$.
(WTS: $(a + I)(b + I) = (c + I)(d + I) ==> a b + I = c d + I ==> -a b + c d in I$)
$
a + I = c + I &<==> -a + c in I \
&<==> -a + c = x, exists x in I \
&==> c = a + x
$
$
b + I = d + I &<==> -b + d in I \
&<==> -b + d = y, exists y in I \
&==> d = b + y
$
Now,
$
c d &= (a + x) (b + y) \
&= a(b + y) + x(b + y) \
&= a b + a y + x b + x y \
&==> - a b + c d = underbrace(underbrace(a, R) underbrace(y, I), I) + underbrace(underbrace(x, I) underbrace(b, R), I) + underbrace(underbrace(x, I) underbrace(y, I), I) in I
$
$therefore$ multiplication of left cosets is well-defined. $square.filled$
]
#underline[=== Theorem 2.25:]
Let $I$ be an ideal of a ring $R$. Then, $R slash I$ is a ring under addition and multiplication of left cosets
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*. Note that addition and multiplication of left cosets are binary operators in $R slash I$
$cal(R)_1$: $R slash I$ is an abelian group under addition of left cosets.
$cal(R)_2$: Let $a + I, b + I, c + I in R slash I$.
$
(a + I)[(b + I)(c + I)] &= (a + I)( b c + I) \
&= a (b c) + I \
&= (a b) c + I \
&= (a b + I)(c + I) = [(a + I)(b + I)](c + I)
$
$cal(R)_3$: Let $a + I, b + I, c + I in R slash I$.
$
(a+I)[(b + I)+ (c + I)] &= (a+I)[(b+c)+ I] \
&= a(b+c)+ I \
&= (a b+ a c)+ I \
&= (a b+ I) + (a b+ I) \
$
$
[(a+I) +(b + I)](c + I)] &= [(a +b)+ I](c + I) \
&= (a + b)c+ I \
&= (a c+ b c)+ I \
&= (a c+ I) + (b c+ I) \
$
$therefore R slash I$ is a ring under addition and multiplication of left cosets. $square.filled$
=== #underline[Remark]:
$R slash I$ is called the factor ring or _#underline[quotient ring]_ of _#underline[$R$ modulo $I$]_.
]
#underline[=== Remarks:]
+ If $R$ is commutative, then $R slash I$ is commutative.
+ If $R$ has unity 1, then $R slash I$ has unity $1 + I$.
#underline[=== Examples:]
- $ZZ slash 3 ZZ = {3 ZZ, 1 + 3 ZZ, 2 + 3ZZ}$
#align(center)[
#table(
columns: (auto, auto, auto, auto),
inset: (x: 5pt, y: 5pt),
stroke: 0.5pt,
align: center,
[*$plus$*], [*$3ZZ$*], [*$1 + 3ZZ$*], [*$2 +3ZZ$*],
[*$3 ZZ$*], [$3 ZZ$], [$1 + 3ZZ$], [$2 + 3ZZ$],
[*$1 + 3ZZ$*], [$1 + 3ZZ$], [$2 + 3ZZ$], [$3ZZ$],
[*$2 + 3ZZ$*], [$2 + 3ZZ$], [$3ZZ$], [$1 + 3ZZ$],
)
#table(
columns: (auto, auto, auto, auto),
inset: (x: 5pt, y: 5pt),
stroke: 0.5pt,
align: center,
[*$dot$*], [*$3ZZ$*], [*$1 + 3ZZ$*], [*$2 +3ZZ$*],
[*$3 ZZ$*], [$3 ZZ$], [$3ZZ$], [$3ZZ$],
[*$1 + 3ZZ$*], [$3ZZ$], [$1 + 3ZZ$], [$2+3ZZ$],
[*$2 + 3ZZ$*], [$3ZZ$], [$2+3ZZ$], [$1 + 3ZZ$],
)
]
$ZZ slash 3 ZZ$ is commutative and has unity $1 + 3 ZZ$. $(1 + 3ZZ)^(-1) = 1 + 3ZZ, (2 + 3ZZ)^(-1) = 2+3ZZ$
$therefore ZZ slash 3ZZ $ is a field.
- Consider $8 ZZ subset.eq 2ZZ$. $8 ZZ$ is an ideal of $2ZZ$. (Theorem 2.23)
(a) $2ZZ slash 8 ZZ = {8ZZ, 2+8ZZ, 4 + 8ZZ, 6 + 8ZZ}$
(b)
#align(center)[
#table(
columns: (auto, auto, auto, auto, auto),
inset: (x: 5pt, y: 5pt),
stroke: 0.5pt,
align: center,
[*$plus$*], [*$8ZZ$*], [*$2 + 8ZZ$*], [*$4 +8ZZ$*], [*$6 +8ZZ$*],
[*$8 ZZ$*], [$8 ZZ$], [$2 + 8ZZ$], [$4 + 8ZZ$], [$6 + 8ZZ$],
[*$2 + 8ZZ$*], [$2 + 8ZZ$], [$4 + 8ZZ$], [$6 + 8ZZ$], [$8ZZ$],
[*$4 + 8ZZ$*], [$4 + 8ZZ$], [$6 +8ZZ$], [$8ZZ$], [$2 + 8ZZ$],
[*$6 + 8ZZ$*], [$6 + 8ZZ$], [$8ZZ$], [$2+8ZZ$], [$4 + 8ZZ$],
)
#table(
columns: (auto, auto, auto, auto, auto),
inset: (x: 5pt, y: 5pt),
stroke: 0.5pt,
align: center,
[*$dot$*], [*$8ZZ$*], [*$2 + 8ZZ$*], [*$4 +8ZZ$*], [*$6 +8ZZ$*],
[*$8 ZZ$*], [$8 ZZ$], [$8ZZ$], [$8ZZ$], [$8ZZ$],
[*$2 + 8ZZ$*], [$8ZZ$], [$4 + 8ZZ$], [$8ZZ$], [$4+8ZZ$],
[*$4 + 8ZZ$*], [$8ZZ$], [$8ZZ$], [$8ZZ$], [$8ZZ$],
[*$6 + 8ZZ$*], [$8ZZ$], [$4+8ZZ$], [$8ZZ$], [$4 + 8ZZ$],
)
]
(c) $2ZZ slash 8 ZZ$ is not an integral domain.
#pagebreak()
= Ring Homomorphism
#line(length: 100% )
#underline[=== Definition:]
A ring homomorphism from a ring $R$ to a ring $R'$ is a mapping $phi.alt$ from $R$ to $R'$ that preserves both ring operations, that is, $ ∀a, b ∈ R, phi.alt(a + b) = phi.alt(a) + phi.alt(b) "and" phi.alt(a b) = phi.alt(a)phi.alt(b). $
#underline[=== Remarks:]
Let $phi.alt : R → R'$ be a ring homomorphism.
+ If $phi.alt$ is one-to-one, we call $phi.alt$ a #underline[_ring monomorphism_].
+ If $phi.alt$ is onto, we call $phi.alt$ a #underline[_ring epimorphism_].
+ If $phi.alt$ is a bijection, then $phi.alt$ is called a #underline[_ring isomorphism_].
+ If $phi.alt$ is bijective and $R'= R$, then $phi.alt$ is called a #underline[_ring automorphism_].
#underline[=== Definition:]
Two rings $R$ and $R'$ are said to be #underline[_isomorphic_], written $R tilde.equiv R'$, if there exists an isomorphism from $R$ to $R'$.
#underline[=== Remarks:]
If $phi.alt : R → R'$ is a ring homomorphism, then $phi.alt : angle.l R, + angle.r → angle.l R', +' angle.r$ is a group homomorphism. In particular,
+ If $0$ and $0'$ are the zero elements of $R$ and $R'$, then $phi.alt(0) = 0'$.
+ If $a ∈ R$, then $phi.alt(−a) = − phi.alt(a)$.
+ If $a ∈ R$ and $n ∈ ZZ$, then $phi.alt(n a) = n phi.alt(a)$.
#underline[=== Properties of Ring Homomorphisms (Theorem 2.26):]
+ If $a ∈ R$ and $n ∈ NN$, then $phi.alt(a n) = [phi.alt(a)]n.$
+ If $S$ is a subring of $R$, then $phi.alt(S) = {phi.alt(a)| a ∈ S}$ is a subring of $R'$.
+ If $R$ is commutative, then $phi.alt(R)$ is commutative.
+ If $I$ is an ideal of $R$, then $phi.alt(I)$ is an ideal of the ring $phi.alt(R)$ (but not necessarily of $R'$).
+ If $S'$ is a subring of $R'$, then $phi.alt^(−1)(S') = {a ∈ R | phi.alt(a) ∈ S'}$ is a subring of $R$.
+ Let $R$ be a ring with unity $1_R$.
+ Then $phi.alt(R)$ is a ring with unity $phi.alt(1_R)$.
+ If $a$ is a unit in $R$, then $phi.alt(a)$ is a unit in the ring $phi.alt(R)$ with $[phi.alt(a)]^(−1) = phi.alt(a^(−1))$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*. (Exercise!)
5. Suppose $S'$ is a subring of $R'$. Show: $phi.alt^(−1)(S')$ is a subring of $R$.
Note that $angle.l S', + angle.r$ is a subgroup of $angle.l R', + angle.r$. Since $phi.alt$ is a group homomorphism, $angle.l phi.alt−1(S'), + angle.r$ is a subgoup of $angle.l R, + angle.r$.
It remains to be shown that $phi.alt^(−1)(S')$ is closed under multiplication.
Let $x, y ∈ phi.alt^(−1)(S')$. WTS: $x y ∈ phi.alt^(−1) (S')$, i.e. $phi.alt(x y) ∈ phi.alt^(−1)(S')$.
Now, $x, y ∈ phi.alt^(−1)(S') ⇒ phi.alt(x), phi.alt(y) ∈ S' ⇒ phi.alt(x y) = φ(x)φ(y) ∈ S'$
Since $S'$ is a subring of $R'$. Thus $x y ∈ phi.alt^(−1)
(S').
∴ phi.alt^(−1) (S') $ is a subring of $ R$.
]
#underline[=== Examples:]
+ Consider the map $phi.alt : ZZ → 2ZZ$ given by $phi.alt(k) = 2k$.
Let $a, b ∈ ZZ$. Then
- $phi.alt(a + b) = 2(a + b) = 2a + 2b = phi.alt(a) + phi.alt(b)$
- $phi.alt(a b) = 2a b $ but $ phi.alt(a)phi.alt(b) = (2a)(2b) = 4a b$
Thus $phi.alt$ is not ring homomorphism.
+ Consider the map $phi.alt : ZZ → ZZ × ZZ$ given by $phi.alt(x) = (x, 0)$. Then $phi.alt$ is a ring homomorphism. (Why?)
$phi.alt(ZZ) = {(x, 0)| x ∈ ZZ}$ is a commutative ring with unity (unity in $phi.alt(ZZ)$ is $phi.alt(1) = (1, 0)$). The units of $phi.alt(ZZ)$ are $phi.alt(1) = (1, 0)$ and $phi.alt(−1) = (−1, 0)$.
\
#underline[== Kernel of a Homomorphism]
#underline[=== Definition:]
Let $R, R'$ be rings with $0'$, the zero element in $R'$. Let $phi.alt : R → R'$ be a ring homomorphism.
The kernel of $phi.alt$ is the set
$
ker phi.alt := {a ∈ R | phi.alt(a) = 0'} = phi.alt^(−1)({0'})
$
#underline[=== Remarks:]
+ $phi.alt$ is one-to-one if and only if $ker phi.alt = {0}$.
+ $phi.alt$ is a ring isomorphism if and only if $phi.alt$ is onto and $ker phi.alt = {0}$.
+ If $a ∈ R$ and $phi.alt(a) = a'$ then
$
phi.alt^(−1)(a') = {r ∈ R | phi.alt(r) = a'} = a + ker phi.alt
$
#underline[=== The Kernel is an Ideal (Theorem 2.27):]
Let $phi.alt : R → R'$ be a ring homomorphism. Then $ker phi.alt$ is an ideal of $R$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*. Let $0'$ be the zero element of $R'$. Since ${0'}$ is a subring of $R'$, then $phi.alt^(−1)({0'}) = ker phi.alt$ is a subring of $R$ (by Theorem 2.26).
Let $a ∈ ker phi.alt$ and $r ∈ R$. (WTS: $a r$ and $r a$ are in $ker phi.alt$)
$
phi.alt(a r) = phi.alt(a)phi.alt(r) = 0' · phi.alt(r) = 0'
$
Since $phi.alt(a r) = 0'$, then $a r ∈ ker phi.alt$.
Using a similar argument, we can show that $r a ∈ ker phi.alt$.
$∴ ker phi.alt$ is an ideal of $R$.
]
\
#underline[== First Isomorphism Theorem for Rings (Theorem 2.28):]
Let $phi.alt : R → R'$ be a ring homomorphism. Then
$ μ : R slash ker phi.alt → phi.alt(R) $
given by $μ(a + ker phi.alt) = phi.alt(a)$ is a ring isomorphism.
In particular, $R slash ker phi.alt tilde.equiv phi.alt(R)$ (as rings).
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*. It follows from the First Isomorphism Theorem for Groups that $μ$ is a group isomorphism. (WTS: $μ$ preserves multiplication.)
Let $a + ker phi.alt, b + ker phi.alt ∈ R slash ker phi.alt$. Then,
$
μ[(a + ker phi.alt)(b + ker phi.alt)] &= μ(a b + ker phi.alt)\
&= phi.alt(a b) = phi.alt(a)phi.alt(b) \
&= μ(a + ker phi.alt)μ(b + ker phi.alt)
$
$∴ μ$ is a ring isomorphism.
]
#underline[=== Remark:]
The isomorphism $μ$ is called the #underline[_natural_] or #underline[_canonical isomorphism_] from $R slash ker phi.alt$ to $phi.alt(R)$.
#underline[=== Examples:]
+ Let $phi.alt : ZZ → ZZ_n$ be the mapping such that $phi.alt(m) =$ the remainder when $m$ is divided by $n$. Then $phi.alt$ is a ring epimorphism. (Verify this!)
$ ker phi.alt = n ZZ $
By the FITR,
$ ZZ slash n ZZ = ZZ slash ker phi.alt tilde.equiv phi.alt(ZZ) = ZZ_n $
Thus,
$ ZZ slash n ZZ tilde.equiv ZZ_n "as rings." $
+ Consider the ring homomorphism $phi.alt : ZZ → ZZ × ZZ$ where $phi.alt(x) = (x, 0)$.
$ ker phi.alt = {0} $
By the FITR,
$ ZZ slash {0} = ZZ slash ker phi.alt tilde.equiv phi.alt(ZZ) = {(x, 0)| x ∈ ZZ} $
Noting that $ZZ slash {0} tilde.equiv ZZ$, we get
$ ZZ tilde.equiv {(x, 0)| x ∈ ZZ} $
\
#underline[== Canonical Isomorphism from _R_ to _R/I_ (Theorem 2.29):]
Let $I$ be an ideal of a ring $R$. Then $γ : R → R slash I$ given by $γ(a) = a + I$ is a ring homomorphism with $ker γ = I$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*. It follows from Theorem 2.12 that $γ$ is a group homomorphism with $ker γ = I$. (WTS: $γ$ preserves multiplication.)
Let $a, b ∈ R$. Then $γ(a b) = a b + I = (a + I)(b + I) = γ(a)γ(b)$.
$∴ γ$ is a ring homomorphism.
]
#pagebreak()
= Ideals and Factor Rings (Part II)
#line(length: 100% )
#underline[=== Concept:]
Given: $R$, a commutative ring with unity.
$I$, ideal of $R$
$==> R slash I$ is a commutative ring with unity
- _Question 1_: If $R$ is a field, what are the possible factor rings $R slash I$ ?
- _Question 2_: When is the factor ring $R slash I$ a field?
- _Question 3_: When is the factor ring $R slash I$ an integral domain?
#underline[== Ideals of a Field (Theorem 2.30):]
Let $R$ be a ring with unity $1$ and let $I$ be an ideal of $R$. If $I$
contains a unit of $R$ then $I = R$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*. Suppose $u ∈ I$ is a unit of $R$. Then $∃u^(−1) ∈ R$ such that $1 = u^(−1)u ∈ I$ since $I$ is an ideal of $R$. Thus $1 ∈ I$.
Clearly $I ⊆ R$. (NTS: $R ⊆ I$).
Let $r ∈ R$. Now, $r = r · 1 ∈ I$ since $I$ is an ideal of $R$. Thus $R ⊆ I$ and so $I = R$.
]
#underline[=== Corollary 2.31:]
A field has no proper nontrivial ideals. That is, the only
ideals of a field $F$ are ${0}$ or $F$ itself.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof]*. Let $F$ be a field and $I$ an ideal of $F$. Note that either $I$ is trivial (that is $I = {0}$) or $I$ is nontrivial.
Suppose $I eq.not {0}$. Let $0 eq.not a ∈ I ⊆ F$. Thus $a$ is a unit of $F$. Hence $I = F$.
]
#underline[=== Remark:]
Let $F$ be a field and $I$ an ideal of $F$. Then either $I = {0}$ or
$I = F$. Then the factor rings $F slash I$ are
- $F slash {0} tilde.equiv F$
- $F slash F tilde.equiv {0}$
#underline[== Maximal Ideals]
#underline[=== Definition:]
A proper ideal $M$ of a ring $R$ is said to be #underline[_maximal_] if whenever $J$ is an ideal of $R$ such that $M ⊆ J ⊆ R$, either $J = M$ or $J = R$.
#underline[=== Examples:]
$3ZZ$ and $4ZZ$ are ideals of $ZZ$.
- Note that $4ZZ ⊂ 2ZZ ⊂ ZZ$. Thus $4ZZ$ is not a maximal ideal of $ZZ$.
- Suppose $n ZZ$ is an ideal of $ZZ$ such that $3ZZ ⊆ n ZZ ⊆ ZZ$. Since $3 ∈ 3ZZ ⊆ n ZZ$, then $n divides 3$. Hence $n = 3$ or $n = 1$. So $n ZZ = 3ZZ$ or $n ZZ = ZZ$. Thus $3ZZ$ is a maximal ideal of $ZZ$.
#underline[=== Remarks:]
Let $R$ be a ring.
+ The only ideal that properly contains a maximal ideal of $R$ is $R$.
+ A maximal ideal of $R$ may not be unique. That is, $R$ may have more than one maximal ideal. (e.g. $2ZZ$ and $5ZZ$ are both maximal ideals of $ZZ$)
#underline[=== Examples:]
The ideals of $ZZ_12$:
- $ZZ_12$
- $angle.l 2 angle.r = {0,2,4,6,8,10}$
- $angle.l 3 angle.r = {0,3, 6, 9}$
- $angle.l 4 angle.r = {0,4, 8}$
- $angle.l 6 angle.r = {0,6}$
- ${0}$
Is $angle.l 4 angle.r$ a maximal ideal of $ZZ_12$?
Is $angle.l 4 angle.r$ a maximal ideal of $angle.l 2 angle.r$?
What are the maximal ideals of $ZZ_12$?
\
#underline[== Factor Rings from Maximal Ideals are Fields (Theorem 2.32):]
Let $R$ be a commutative ring with unity and let $I$ be an
ideal of $R$. Then
$
R slash I "is a field" <==> I "is a maximal ideal of" R.
$
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof.]*
$(==>)$ Suppose $R slash I$ is a field. Let $J$ be an ideal of $R$ such that $I ⊆ J ⊆ R$. (NTS: Either $J = I$ or $J = R$).
Suppose $J eq.not I$. Then $∃b ∈ J slash I ==> I eq.not b + I ∈ R slash I ==> b + I$ is a unit in $R slash I ⇒ ∃(a + I) ∈ R slash I$ such that $(b + I)(a + I) = 1 + I ==> −b a + 1 ∈ I ⊂ J$.
Thus $1 = b a + (−b a + 1) ∈ J ==> J = R$.
$∴ I$ is a maximal ideal of $R$.
$(<==)$ Suppose $I$ is a maximal ideal of $R$. Since $R$ is commutative with unity, then so is $R slash I$. Note also that $I eq.not R$ since $I$ is maximal and so $1 in.not I$. Thus $1 + I eq.not I$.
(NTS: Every nonzero element of $R slash I$ is a unit.)
Let $a + I$ be a nonzero element in $R slash I$ (i.e. $a ∈ R$ but $a in.not I$).
Form $J := {r a + b |r ∈ R, b ∈ I }$. Claim: $J$ is an ideal of $R$.
If $x ∈ I$ then $x = 0 · a + x ∈ J ⇒ I ⊆ J ⊆ R ⇒ J = I or J = R$. However, $a in.not I$ but $a = 1 · a + 0 ∈ J ==> J eq.not I$. Thus $J = R$.
Now, $1 ∈ R = J ==> 1 = r a + b$ for some $r ∈ R, b ∈ I $
$ &==> −r a + 1 = b ∈ I \
&==> r a + I = 1 + I \
&==> (r + I)(a + I) = (a + I)(r + I) = 1 + I \
&==> a + I "is a unit".
$
$∴ R slash I$ is a field.
=== #underline[Proof of claim that _J_ is an ideal of R]:
#underline[Claim]: $J = {r a + b |r ∈ R, b ∈ I }$ is an ideal of $R$.
#underline[_Proof._]
- $J$ is nonempty: $0 = 0 · a + 0 ∈ J ==> J eq.not cancel(circle)$
- If $x, y ∈ J$, show that $x − y ∈ J$. (Exercise!)
- If $s ∈ R$ and $x ∈ J$, show that $s x ∈ J$ and $x s ∈ J$.
$∵ x ∈ J ==> x = r a + b$ for some $r ∈ R, b ∈ I$. So $s x = s(r a + b) = (s r)a + s b ∈ J$. Note that $R$ is commutative so $ x s = s x ∈ J$. $square.filled$
]
#underline[=== Appplication of Theorem 2.32:]
Consider the ideals $3ZZ$ and $4ZZ$ of $ZZ$.
- $ZZ slash 3ZZ tilde.equiv ZZ_3$ is a field, thus $3ZZ$ is a maximal ideal of $ZZ$.
- $ZZ slash 4ZZ tilde.equiv ZZ_4$ is not a field, thus $4ZZ$ is not a maximal ideal of $ZZ$.
#underline[=== Remark:]
$n ZZ$ is a maximal ideal of $ZZ$ if and only if $n$ is prime.
#underline[=== Converse of Corollary 2.31 holds (Corollary 2.33):]
A commutative ring with unity is a field if and only if it has
no proper nontrivial ideals.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof.]*
$(==>)$ Follows from Corollary 2.31.
$(<==)$ Suppose a commutative ring $R$ with unity has no proper nontrivial ideals. Then ${0}$ is a maximal ideal. Thus $R tilde.equiv R slash {0}$ is a field.
]
\
#underline[== Prime Ideals]
#underline[=== Definition:]
A proper ideal $P$ of a commutative ring $R$ is said to be #underline[_prime_] if whenever $a, b ∈ R$ such that $a b ∈ P$ then either $a ∈ P$ or $b ∈ P$.
#underline[=== Examples:]
+ Consider $6ZZ$. Note that $2 · 3 ∈ 6ZZ$ but neither $2$ nor $3$ are in $6ZZ$. Thus $6ZZ$ is not a prime ideal of $ZZ$.
+ Consider the trivial ideal ${0} in ZZ_12$. Is ${0}$ a prime ideal of $ZZ_12$?
+ ${0}$ is a prime ideal of an integral domain $D$.
$∵$ Let $a, b ∈ D$ such that $a b ∈ {0} ==> a b = 0 ==> a = 0$ or
$b = 0 ==> a ∈ {0} "or" b ∈ {0}$.
\
#underline[== Factor Rings from Prime Ideals (Theorem 2.34):]
Let $R$ be a commutative ring with unity and let $I$ be an ideal of $R$. Then
$
R slash I "is an integral domain" <==> I "is a prime ideal of" R.
$
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof.]*
$(==>)$ Suppose $R slash I$ is an integral domain. Let $a, b ∈ R$ such that $a b ∈ I$. Then $a b + I = I ==> (a + I)(b + I) = I$. Since $R slash I$ is an integral domain, either $a + I = I$ or $b + I = I$, which means that either $a ∈ I$ or $b ∈ I$.
$(<==)$ Suppose $I$ is a prime ideal of $R$. Since Then $R$ is a commutative ring with unity $1$, then so is $R slash I$. Note also that $I eq.not R$ since$ I$ is prime and so $1 in.not I$. Thus $1 + I eq.not I$. (NTS: $R slash I$ has no zero divisors.)
Let $a + I, b + I ∈ R slash I$ such that $(a + I)(b + I) = I$. Then, $a b + I = I ==> a b ∈ I$. Since $I$ is prime, then either $a ∈ I$ or $b ∈ I ==> a + I = I "or" b + I = I$
$∴ R slash I$ is an integral domain.
]
#underline[=== Applications of Theorem 2.34:]
+ $ZZ slash 4ZZ tilde.equiv ZZ_4$ is not an integral domain. Thus $4ZZ$ is not a prime ideal of $ZZ$. Indeed $2 · 2 ∈ 4ZZ$ but $2 in.not 4ZZ$.
#underline[Remark]: $n ZZ$ is a prime ideal of $ZZ$ if and only if $n$ is prime.
+ Let $I = {(x, 0)| x ∈ ZZ} ⊆ ZZ × ZZ$. Then $I$ is an ideal of $ZZ × ZZ$. (Exercise!)
Suppose $(a, b),(c, d) ∈ ZZ × ZZ$ such that $(a, b)(c, d) = (a c, b d) ∈ I$.
Then $ b d = 0 ==> b = 0$ or $d = 0 ==> (a, b) ∈ I$ or $(c, d) ∈ I$. Hence $I$ is prime.
Thus $(ZZ × ZZ) slash I$ is an integral domain.
(Exercise:) Use FITR (First Isomorphism Theorem for Rings) to show
that $(ZZ × ZZ) slash I tilde.equiv ZZ$.
\
#underline[== Maximal Ideals are Prime Ideals (Corollary 2.35):]
Every maximal ideal of a commutative ring $R$ with unity is
a prime ideal of $R$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof.]*
Let $I$ be a maximal ideal of $R$. By Theorem 2.32, $R slash I$ is a field. Hence $R slash I$ is an integral domain. Thus $I$ is a prime ideal of $R$. $square.filled$
]
#underline[=== Remarks:]
+ The converse of Corollary 2.35 does not hold. That is, a prime ideal of a commutative ring $R$ with unity may not be a maximal ideal of R.
e.g., $I = {(x, 0)| x ∈ ZZ}$ is a prime ideal of $ZZ × ZZ$ which is not a maximal ideal of $ZZ × ZZ$. (Why?)
+ Corollary 2.35 does not hold if $R$ has no unity.
e.g. $2ZZ$ has no unity and $4ZZ$ is a maximal ideal of $2ZZ$ but $4ZZ$ is not a prime ideal of $2ZZ$. (Why?)
#pagebreak()
= Field of Quotients of Integral Domains and Prime Fields
#line(length: 100% )
#underline[== R with unity contains a homomorphic image of $ZZ$ (Lemma 2.36):]
Let $R$ be a ring with unity $1$. The mapping $phi.alt : ZZ → R$ given
by $phi.alt(m) = m · 1$ is a ring homomorphism.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof.]*
Let $m, n ∈ ZZ$. Then
$
phi.alt(m + n) &= (m + n) · 1 = m · 1 + n · 1 = phi.alt(m) + phi.alt(n) \
phi.alt(m n) &= (m n) · 1 = (m n) · 1 · 1 = (m · 1)(n · 1) = phi.alt(m)phi.alt(n)
$
]
#underline[=== Remark:]
Note that $phi.alt(ZZ)$ is a subring of $R$.
#underline[=== The Characteristic of Rings with Unity]
$"char" R =$ smallest positive integer $n$ such that $n · a = 0$ for all $a ∈ R$.
If no such positive integer exists, then $"char" R = 0$.
#underline[Recall]: $R$, a ring with unity 1
- $"char" R = n <==> |1| = n$ in the group $angle.l R, + angle.r$
- $"char" R = 0 <==> 1$ has infinite order in the group $angle.l R, + angle.r$
#underline[ === Structure of R based on its Characteristic (Theorem 2.37)]
Let $R$ be a ring with unity.
+ $"char" R = n > 1 ==> R$ contains a subring isomorphic to $ZZ_n$
+ $"char" R = 0 ==> R$ contains a subring isomorphic to $ZZ$
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof.]*
Consider the ring homomorphism $phi.alt : ZZ → R$ given by $phi.alt(m) = m · 1$.
By the FITR, $ZZ slash ker phi.alt tilde.equiv phi.alt(ZZ)$.
Note that $ker phi.alt = {m ∈ Z | phi.alt(m) = 0} = {m ∈ Z | m · 1 = 0}$.
- Suppose $"char" R = n > 1$. So $|1| = n$. That is, $n · 1 = 0$ and $ m · 1 = 0 <==> n | m <==> m ∈ n ZZ. $
Thus $ker phi.alt = n ZZ$. Hence by FITR,
$ phi.alt(ZZ) tilde.equiv ZZ slash ker phi.alt = ZZ slash n ZZ tilde.equiv ZZ_n. $
- Suppose $"char" R = 0$. Then $1$ has infinite order. Thus $m · 1 = 0 <==> m = 0$. Thus $ker phi.alt = {0}$. Hence by FITR,
$
phi.alt(ZZ) tilde.equiv ZZ slash ker phi.alt = ZZ slash {0} tilde.equiv ZZ.
$
]
\
#underline[=== Examples:]
Consider the ring $R = M_2(RR)$ with unity $display(mat(1, 0; 0, 1; delim: "["))$. Note that the order of $display(mat(1, 0; 0, 1; delim: "["))$ is infinite.(Why?)
Hence $"char" M_2(RR) = 0$.
Thus $M_2(RR)$ has a subring isomorphic to $ZZ$ by Theorem 2.37.
This subring is $phi.alt(ZZ)$ where $phi.alt : ZZ → M_2(RR)$ is given by
$
phi.alt(m) = m mat(1, 0; 0, 1; delim: "[") = mat(m, 0; 0, m; delim: "[")
$
Thus
$
phi.alt(ZZ) = {phi.alt(m)| m ∈ ZZ} = {mat(m, 0; 0, m; delim: "[") mid(|) m ∈ ZZ} tilde.equiv ZZ
$
\
== #underline[Field of Quotients of an Integral Domain]
Consider the integral domain $ZZ$.
Note that $ZZ$ is not a field. But $ZZ$ is a subring of the field $QQ$.
- #underline[_Question_]: Given any integral domain $D$, is there a field $F$ that contains $D$? If so, what is the smallest field that will contain $D$?
#underline[_Construction of $QQ$ from $ZZ$_]:
$
ZZ ”⊂” {(a, b)| a, b ∈ ZZ, b eq.not 0} &--> QQ = {a/b mid(|) a, b ∈ ZZ, b eq.not 0} \
(a, b) + (c, d) = (a d + b c, b d) &-->
a/b + c/d = (a d + b c)/(b d)\
(a, b)(c, d) = (a c, b d) &--> (a/b)(c/d) = (a c)/(b d) \
(1, 2),(2, 4),(3, 6)· · · &--> 1/a \
(a, b) ∼ (c, d) <==> a d = b c &--> a/b = c/d <==> a d = b c
$
\
== #underline[Theorem 2.38]:
Let $D$ be an integral domain. Then there exists a field that
contains a subring which is isomorphic to $D$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof.]*
Consider $S = {(a, b)| a, b ∈ D, b eq.not 0)} ⊂ D × D$.\
Define the relation on $S$ by $(a, b) ∼ (c, d) <==> a d = b c$.
#underline[Claim 1]: $∼$ is an equivalence relation on $S$. (Exercise!)
Denote the equivalence class of $(a, b)$ by $[a, b]$.
Note that $[a, b] = [c, d] <==> a d = b c$
Let $F := {[a, b] |(a, b) ∈ S}$
Define the following operations on $F$:
$
"addition"&: [a, b] + [c, d] = [a d + b c, b d] \
"multiplication"&: [a, b] · [c, d] = [a c, b d]
$
#underline[Claim 2]: The defined operations are well-defined binary operations on $F$. (Exercise!)
#underline[Claim 3]:
#set enum(numbering: "a.")
+ If $0 eq.not b ∈ D$ then $[0, b] = [0, 1]$.
+ If $0 eq.not k ∈ D$ and $[a, b] ∈ F$ then $[k a, k b] = [a, b]$.
+ If $0 eq.not a ∈ D$ then $[a, a] = [1, 1]$
(Exercise!)
We now show that $F$ is a field.
#underline[$F$ is a ring]:
$cal(R_1)$: $angle.l F, + angle.r$ is an abelian group.
- $+$ is commutative: Let $[a, b], [c, d] ∈ F$.
$ [a, b] + [c, d] = [a d + b c, b d] = [c b + d a, d b] = [c, d] + [a, b] $
- $+$ is associative: (Exercise!)
- additive identity: Consider $[0, 1] ∈ F$. For any $[a, b] ∈ F$,
$ [0, 1] + [a, b] = [a, b] + [0, 1] = [a · 1 + b · 0, b · 1] = [a, b] $
- additive inverse: Let $[a, b] ∈ F$. Its additive inverse is $[−a, b]$ since
$ [a, b] + [−a, b] = [−a, b] + [a, b] = [−a b + a b, b^2] = [0, b^2] = [0, 1] $
$cal(R)_2$: Multiplication is associative. (Exercise!)
$cal(R)_3$: Left and Right Distributive Laws: (Exercise!) (Hint: You may need to use Claim 3(b).)
#underline[$F$ is commutative]: Given $[a, b], [c, d] ∈ F$,
$ [a, b][c, d] = [a c, b d] = [c a, d b] = [c, d][a, b] $
#underline[$F$ has unity]: unity in $F$ is $[1, 1]$ since $[a, b][1, 1] = [1, 1][a, b] = [a, b] ∀[a, b] ∈ F$. Clearly,
$[1, 1] eq.not [0, 1]$. $(∵ 1 · 1 6= 1 · 0.)$
#underline[$F$ is a division ring]: Let $[a, b] ∈ F$ such that $[a, b] eq.not [0, 1]$. Then $a · 1 eq.not b · 0 ==> a eq.not 0 ==> [b, a] ∈ F$. Note that $[a, b][b, a] = [a b, b a] = [a b, a b] = [1, 1]$.
Thus $[a, b]^(−1) = [b, a]$.
$∴ F$ is a field under the operations addition and multiplication as defined.
Lastly, we show that $F$ contains a subring which is isomorphic to $D$.
Consider $phi.alt : D → F$ given by $phi.alt(a) = [a, 1]$.
Let $a, b ∈ D$. Then $phi.alt(a) + phi.alt(b) = [a, 1] + [b, 1] = [a + b, 1] = phi.alt(a + b)$ and $phi.alt(a)phi.alt(b) = [a, 1][b, 1] = [a b, 1] = phi.alt(a b)$
Thus, $phi.alt$ is a ring homomorphism.
Note that $ker phi.alt = {a ∈ D | phi.alt(a) = [0, 1]} = {a ∈ D | [a, 1] = [0, 1]}$.
But $[a, 1] = [0, 1] <==> a · 1 = 1 · 0 <==> a = 0$.
Thus $ker phi.alt = {0}$.
So by the FITR,
$ phi.alt(D) tilde.equiv D slash ker phi.alt = D slash {0} tilde.equiv D $
$∴ D$ is isomorphic to $phi.alt(D) = {[a, 1] | a ∈ D}$ which is a subring of $F$.
]
=== #underline[Remarks]:
+ The field $F$ in Theorem 2.38 is called the field of quotients of $D$.
+ We say that the integral domain $D$ is embedded in its field of quotients $F$ and we write $D arrow.hook F$.
=== #underline[Example]:
+ $QQ $ is the field of quotients of $ZZ$.
\
== #underline[Theorem 2.39]:
Let $D$ be an integral domain and $F$ its field of quotients. Suppose $K$ is a field that contains $D$. Then $K$ contains a subfield $L$ such that $D ⊆ L ⊆ K$ and $L$ is isomorphic to $F$.
=== #underline[Remark]:
The field of quotients $F$ of $D$ is the smallest field that contains $D$ and is unique (up to isomorphism).
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof.]* Let $[a, b] ∈ F$. Then $a, b ∈ D$ and $b eq.not 0$. Thus $a, b ∈ K$ and $b$ is a unit in $K$.
Define $phi.alt : F → K$ given by $phi.alt([a, b]) = a b^(−1)$. Then $phi.alt$ is a well-defined monomorphism. (Exercise!)
Set $L = phi.alt(F)$. By FITR,
$ L = phi.alt(F) tilde.equiv F slash ker phi.alt = F slash {0} tilde.equiv F $
Thus $L$ is a subfield of $K$ which is isomorphic to $F$.
For every $a ∈ D, a = a · 1 = a · 1 −1 = phi.alt([a, 1])$. Thus $D ⊆ L ⊆ K$.
]
#pagebreak()
= Prime Subfield of a Field
#line(length: 100% )
_Recall_: The characteristic of an integral domain is either $0$ or prime $p$.
#underline[== Theorem 2.40:]
Let $F$ be a field.
+ $F$ is of prime characteristic $p ==> F$ contains a subfield isomorphic to $ZZ_p$
+ $F$ is of characteristic $0 ==> F$ contains a subfield isomorphic to $QQ$.
#block(stroke: 1pt, radius: 5pt, inset: 15pt, width: 100%)[
*#underline[Proof.]*
+ Since $"char" F = p, F$ contains a subring $S$ isomorphic to $ZZ_p$.
Since $p$ is prime, $ZZ_p$ is a field. Thus $S$ is a subfield of $F$ isomorphic to $ZZ_p$.
+ If $"char" F$ is $0$, then $F$ contains a subring $S$ isomorphic to $ZZ$. So $S$ is an integral domain contained in the field $F$. By Theorem 2.39, $F$ contains a subfield $L$ which is isomorphic to the field of quotients $F_S$ of $S$.
Since $S tilde.equiv ZZ$, $F_S tilde.equiv QQ$. Thus $L tilde.equiv QQ$.
]
#underline[=== Definition:]
The subfield of a field $F$ that is isomorphic to either $ZZ_p$ or $QQ$ is called a prime subfield of $F$.
#underline[=== Remark:]
A prime subfield of $F$ is the smallest subfield of $F$. Equivalently, every subfield of $F$ must contain the prime subfield of $F$.
#underline[=== Examples:]
+ Identify the prime subfield of the field $QQ(√2) = {a + b√2 | a, b ∈ QQ}.$
+ Suppose $F$ is a field with $81$ elements. The prime subfield of $F$ is isomorphic to which field?
#underline[=== Solution:]
+ The unity in $QQ(√2)$ is $1$. Since order of $1$ is infinite $==>$ $"char" Q(√2) = 0$. Thus the prime subfield of $QQ(√2)$ is $QQ$.
+ Note: order of $angle.l F, + angle.r$ is $81$.
order of $1 = "char" F = p$ for some prime $p ==> p$ divides $81 = 3^4 ==> p = 3$
Thus the prime subfield of $F$ is isomorphic to $ZZ_3$. |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/grotesk-cv/0.1.0/content/personal.typ | typst | Apache License 2.0 | #import "../../lib.typ": *
#import "../../metadata.typ": *
#import "@preview/fontawesome:0.2.1": *
== #fa-icon("brain") #h(5pt) #getHeaderByLanguage("Personality", "Personalidad")
#v(5pt)
#if isEnglish() [
- Analytic thinking
- Quality conscious
- Good communicator
- Independent
- Team player
- Preemptive
- Eager to learn
] else if isSpanish() [
- Pensamiento analítico
- Consciente de la calidad
- Buen comunicador
- Independiente
- Jugador de equipo
- Preventivo
- Ansioso por aprender
]
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/list-attach-03.typ | typst | Other | // Test non-attached tight list.
#set block(spacing: 15pt)
Hello
- A
World
- B
- C
More.
|
https://github.com/shunichironomura/ukaren-typst-template | https://raw.githubusercontent.com/shunichironomura/ukaren-typst-template/main/template.typ | typst | #let phantom-paragraph() = {
set text(size: 11pt)
let a = par(box())
a
context v(-0.8 * measure(2 * a).width)
}
#let project(
id: "",
title-ja: "",
title-en: "",
abstract: [],
authors: (),
affiliations: (),
keywords: (),
n-columns: 2,
body,
) = {
// General settings
set document(author: authors.map(a => a.name-ja), title: title-ja)
// Prioritize YuMincho because MS Mincho does not support bold.
set text(font: ("Times New Roman", "Yu Mincho", "YuMincho", "MS Mincho"), lang: "ja")
set page(paper: "a4", margin: (x: 23mm, y: 25mm))
// Heading settings
set heading(numbering: "1.1.")
show heading: it => {
// Workaround for the limitation of Typst.
// See https://github.com/typst/typst/issues/311#issuecomment-2023038611
{
set text(size: 9.5pt, weight: "bold")
set block(spacing: 0.65em)
{
// Add a vertical space before the heading, if not the first heading.
let selector = selector(heading).before(here())
let level = counter(selector)
// level.display()
if level.display() != "1" and it.level == 1 {
v(9.5pt)
}
}
it
}
phantom-paragraph()
}
// Section reference settings
show ref: it => {
let el = it.element
if el != none and el.func() == heading {
context {
let heading_counts = counter(heading).at(it.element.location())
if el.depth == 1 {
// 章
[第#heading_counts.at(0)章]
// counts
} else if el.depth == 2 {
// 節
[第#heading_counts.at(0).#heading_counts.at(1)節]
} else if el.depth == 3 {
// 項
[第#heading_counts.at(0).#heading_counts.at(1).#heading_counts.at(2)項]
} else {
it
}
}
} else {
it
}
}
// Paragraph settings
show par: set block(spacing: 0.65em)
// Equation settings
set math.equation(numbering: "(1)")
// Figure settings
show figure.where(kind: table): set figure.caption(position: top)
set table(stroke: .5pt)
set figure.caption(separator: [ ])
// Title (Japanese).
align(center)[#text(size: 16pt)[#id\u{3000}#title-ja]]
v(10.5pt)
// Author information (Japanese).
align(center)[
#set text(size: 10.5pt)
#authors.enumerate().map(i_author => {
let (i, author) = i_author
if author.presenting [〇]
box(author.name-ja)
if (
i < authors.len() - 1 and author.affiliation-ja != authors.at(i + 1).affiliation-ja
) or i == authors.len() - 1 {
box([(#author.affiliation-ja)])
}
}).join(",")
]
v(10.5pt)
// Title (English).
align(center)[#text(size: 10.5pt, title-en)]
// Author information (English).
align(center)[
#set text(size: 10.5pt)
#authors.enumerate().map(i_author => {
let (i, author) = i_author
box(author.name-en)
if (
i < authors.len() - 1 and author.affiliation-en != authors.at(i + 1).affiliation-en
) or i == authors.len() - 1 {
box([~(#author.affiliation-en)])
}
}).join(", ", last: " and ")
]
v(9.5pt)
// Keywords
align(center)[
#set text(size: 9.5pt)
Keywords: #keywords.join(", ")
]
v(9.5pt)
// Abstract
align(center)[
#text(size: 9.5pt)[Abstract]
]
text(size: 9.5pt)[#h(2em)#abstract]
v(1.2em)
// Main body.
set text(size: 9.5pt)
// We need to subtract 9.5pt (the font size) from 15pt to get the correct line spacing.
// 0.65pt in Typst is equivalent to no line spacing in MS Word.
set par(justify: true, leading: 15pt - 9.5pt + 0.65pt, first-line-indent: 1em)
if n-columns == 1 {
body
} else {
show: columns.with(n-columns, gutter: 7mm)
body
}
}
|
|
https://github.com/typst-jp/typst-jp.github.io | https://raw.githubusercontent.com/typst-jp/typst-jp.github.io/main/docs/changelog/0.10.0.md | markdown | Apache License 2.0 | ---
title: 0.10.0
description: Changes in Typst 0.10.0
---
# Version 0.10.0 (December 4, 2023)
## Bibliography management
- Added support for citation collapsing (e.g. `[[1]-[3]]` instead of
`[[1], [2], [3]]`) if requested by a CSL style
- Fixed bug where an additional space would appear after a group of citations
- Fixed link show rules for links in the bibliography
- Fixed show-set rules on citations
- Fixed bibliography-related crashes that happened on some systems
- Corrected name of the GB/T 7714 family of styles from 7114 to 7714
- Fixed missing title in some bibliography styles
- Fixed printing of volumes in some styles
- Fixed delimiter order for contributors in some styles (e.g. APA)
- Fixed behavior of alphanumeric style
- Fixed multiple bugs with GB/T 7714 style
- Fixed escaping in Hayagriva values
- Fixed crashes with empty dates in Hayagriva files
- Fixed bug with spacing around math blocks
- Fixed title case formatting after verbatim text and apostrophes
- Page ranges in `.bib` files can now be arbitrary strings
- Multi-line values in `.bib` files are now parsed correctly
- Entry keys in `.bib` files now allow more characters
- Fixed error message for empty dates in `.bib` files
- Added support for years of lengths other than 4 without leading zeros in
`.bib` files
- More LaTeX commands (e.g. for quotes) are now respected in `.bib` files
## Visualization
- Added support for [patterns]($pattern) as fills and strokes
- The `alpha` parameter of the [`components`]($color.components) function on
colors is now a named parameter **(Breaking change)**
- Added support for the [Oklch]($color.oklch) color space
- Improved conversions between colors in different color spaces
- Removed restrictions on [Oklab]($color.oklab) chroma component
- Fixed [clipping]($block.clip) on blocks and boxes without a stroke
- Fixed bug with [gradients]($gradient) on math
- Fixed bug with gradient rotation on text
- Fixed bug with gradient colors in PDF
- Fixed relative base of Oklab chroma ratios
- Fixed Oklab color negation
## Text and Layout
- CJK text can now be emphasized with the `*` and `_` syntax even when there are
no spaces
- Added basic i18n for Greek and Estonian
- Improved default [figure caption separator]($figure.caption.separator) for
Chinese, French, and Russian
- Changed default [figure supplement]($figure.supplement) for Russian to short
form
- Fixed [CJK-Latin-spacing]($text.cjk-latin-spacing) before line breaks and in
[`locate`] calls
- Fixed line breaking at the end of links
## Math
- Added [`mid`]($math.mid) function for scaling a delimiter up to the height of
the surrounding [`lr`]($math.lr) group
- The [`op`]($math.op) function can now take any content, not just strings
- Improved documentation for [math alignment]($category/math/#alignment)
- Fixed swallowing of trailing comma when a symbol is used in a function-like
way (e.g. `pi(a,b,)`)
## Scripting
- Any non-identifier dictionary key is now interpreted as an expression: For
instance, `{((key): value)}` will create a dictionary with a dynamic key
- The [`stroke`] type now has a constructor that converts a value to a stroke or
creates one from its parts
- Added constructor for [`arguments`] type
- Added [`calc.div-euclid`]($calc.div-euclid) and
[`calc.rem-euclid`]($calc.rem-euclid) functions
- Fixed equality of [`arguments`]
- Fixed [`repr`]of [`cmyk`]($color.cmyk) colors
- Fixed crashes with provided elements like figure captions, outline entries,
and footnote entries
## Tooling and Diagnostics
- Show rules that match on their own output now produce an appropriate error
message instead of a crash (this is a first step, in the future they will just
work)
- Too highly or infinitely nested layouts now produce error messages instead of
crashes
- Added hints for invalid identifiers
- Added hint when trying to use a manually constructed footnote or outline entry
- Added missing details to autocompletions for types
- Improved error message when passing a named argument where a positional one is
expected
- Jump from click now works on raw blocks
## Export
- PDF compilation output is now again fully byte-by-byte reproducible if the
document's [`date`]($document.date) is set manually
- Fixed color export in SVG
- Fixed PDF metadata encoding of multiple [authors]($document.author)
## Command line interface
- Fixed a major bug where `typst watch` would confuse files and fail to pick up
updates
- Fetching of the release metadata in `typst update` now respects proxies
- Fixed bug with `--open` flag on Windows when the path contains a space
- The `TYPST_FONT_PATHS` environment variable can now contain multiple paths
(separated by `;` on Windows and `:` elsewhere)
- Updated embedded New Computer Modern fonts to version 4.7
- The watching process doesn't stop anymore when the main file contains invalid
UTF-8
## Miscellaneous Improvements
- Parallelized image encoding in PDF export
- Improved the internal representation of content for improved performance
- Optimized introspection (query, counter, etc.) performance
- The [document title]($document.title) can now be arbitrary content instead of
just a string
- The [`number-align`]($enum.number-align) parameter on numbered lists now also
accepts vertical alignments
- Fixed selectors on [quote] elements
- Fixed parsing of `[#return]` expression in markup
- Fixed bug where inline equations were displayed in equation outlines
- Fixed potential CRLF issue in [`raw`] blocks
- Fixed a bug where Chinese numbering couldn't exceed the number 255
## Development
- Merged `typst` and `typst-library` and extracted `typst-pdf`, `typst-svg`, and
`typst-render` into separate crates
- The Nix flake now includes the git revision when running `typst --version`
## Contributors
<contributors from="v0.9.0" to="v0.10.0" />
|
https://github.com/8LWXpg/jupyter2typst | https://raw.githubusercontent.com/8LWXpg/jupyter2typst/master/template/template.typ | typst | MIT License | #import "@preview/ansi-render:0.6.1": *
// only used in inline LaTeX with \xarrow
#import "@preview/xarrow:0.3.1": xarrow as _xarrow
// workaround before set is implemented
#let xarrow = _xarrow.with(margin: .5em)
#let radius = 3pt
#let inset = 8pt
#let code-block(body, lang: "python", count: 0) = context {
block(
raw(body, lang: lang),
fill: luma(230),
inset: inset,
radius: radius,
width: 100%,
)
v(0pt, weak: true)
let c = raw("[" + str(count) + "]:")
let size = measure(c)
box(height: 0pt, move(dx: -size.width, dy: -size.height - inset, c))
}
#let result-block(body) = {
v(0pt, weak: true)
ansi-render(body, radius: radius, inset: inset, width: 100%)
}
#let block-quote(body) = context {
let size = measure(body)
grid(
columns: (4pt, auto),
rows: auto,
gutter: 0pt,
rect(
fill: luma(180),
height: size.height + 2 * inset,
radius: (left: radius),
),
block(
fill: luma(240),
height: size.height + 2 * inset,
inset: inset,
radius: (right: radius),
width: 100%,
body,
),
)
}
#let template(body) = {
set page(height: auto)
body
} |
https://github.com/chrischriscris/Tareas-CI5651-EM2024 | https://raw.githubusercontent.com/chrischriscris/Tareas-CI5651-EM2024/main/tarea07/src/main.typ | typst | #import "@preview/tablex:0.0.8": tablex, cellx, hlinex, vlinex
#import "template.typ": conf, question, pseudocode, GITFRONT_REPO
#import "ej3/prefix-suffix.typ": prefix-suffix
#show: doc => conf(
"Tarea 7: Cadenas de caracteres/Geometría computacional",
doc
)
#question[
Sea $n$ una cadena de caracteres que tiene su número de carné (sin el guión):
#enum(numbering: "(a)")[
Construya un árbol de sufijos para $n$.
][
Construya un arreglo de sufijos a partir del árbol de sufijos para $n$.
][
Para cada posición $k$, calcule los valores para $"PLCP"[k]$ (el prefijo común
permutado más largo) y $"LCP"[k]$ (el prefijo común más largo), como fue visto
en clase.
]
][
Para este caso, la cadena de caracteres $n$ es `1810892`, con lo que el árbol
de sufijos sería el siguiente:
#figure(caption: [Árbol de sufijos para `1810892`])[
#image("img/suffixtree.svg", width: 251pt)
]<arbol> \
A partir de esto, podemos construir el arreglos de sufijos:
#align(center)[
#tablex(
columns: (auto,) * 2,
align: (center, left),
[*i*], [*Sufijo*],
[0], [1810892],
[1], [810892],
[2], [10892],
[3], [0892],
[4], [892],
[5], [92],
[6], [2],
[7], []
)
] \
Y tras ordenar los sufijos lexicográficamente, obtenemos el siguiente arreglo,
que conforma $"SA"$ y desde el cual podemos aprovechar y llenar $"LCP"$:
#align(center)[
#tablex(
columns: (auto,) * 4,
align: (center, center, center, left),
[*i*], [*SA[i]*], [*LCP[i]*], [*Sufijo*],
[0], [7], [0], [],
[1], [3], [0], [0892],
[2], [2], [0], [10892],
[3], [0], [1], [#text(fill: red)[1]810892],
[4], [6], [0], [2],
[5], [1], [0], [810892],
[6], [4], [1], [#text(fill: red)[8]92],
[7], [5], [0], [92]
)
] \
Y con esto podemos construir finalmente $"PLCP"$:
#align(center)[
#tablex(
columns: (auto,) * 4,
align: (center, center, center, left),
[*SA[i]*], [*Phi[SA[i]]*], [*PLCP[SA[i]]*], [*Sufijo*],
[0], [2], [1], [#text(fill: red)[1]810892],
[1], [6], [0], [810892],
[2], [3], [0], [10892],
[3], [7], [0], [0892],
[4], [1], [1], [#text(fill: red)[8]92],
[5], [4], [0], [92],
[6], [0], [0], [2],
[7], [-1], [0], []
)
]
][
Sea $P = {p_1 , p_2 , dots , p_n }$ un conjunto de puntos en el plano
cartesiano. Definimos una *capa* como aquellos puntos que forman parte del
polígono convexo más pequeño que rodea a todos los puntos en $P$. Pero los
puntos son como los ogros o las cebollas y pueden tener más de una capa. En
particular, se puede remover la capa para $P$ y obtener un conjunto de puntos
$P'$ a los que también se les puede calcular su capa. ¿Cuántas capas tiene el
conjunto de puntos $P$?
Diseñe un algoritmo que pueda responder a esta consulta usando tiempo
$O(n^2 log n)$ y memoria $O(n)$.
][
Sabemos que podemos hallar un _Convex Hull_ (o capa) de un conjunto de puntos
en tiempo $O(n log n)$ usando el algoritmo de _Graham Scan_. Con esto, un
algoritmo que resuelva el problema sería el siguiente:
#pseudocode[
```python
def capas(puntos: Conjunto[Punto]) -> Entero:
capas = 0
while !puntos.vacío():
capas += 1
capa = graham_scan(puntos)
puntos.remover(capa)
return capas
```
]
Veamos, la cantidad máxima de capas está acotada por $n$ (no pudiese haber más
capas que puntos), por lo que si el cuerpo del ciclo no tarda más de
$O(n log n)$, el algoritmo completo tendrá una complejidad de $O(n^2 log n)$.
En este punto hay que tener especial cuidado en la implementación, ya que si
la verificación de existencia en cada capa no es constante, la operación
`remover` tendría en el peor caso que recorrer `capa` tantas veces como
elementos haya en la capa, tomándose tiempo $O(n^2)$ en lugar de $O(n)$. Así,
para cumplir con la complejidad esperada, se debe retornar una estructura como
Conjunto que permita verificar existencia en tiempo constante, así cada
iteración del ciclo tomará tiempo $O(n + n log n) = O(n log n)$, y el algoritmo
completo tomará tiempo $O(n^2 log n)$.
Luego, es trivial que la memoria utilizada por el algoritmo es $O(n)$, ya que
_Graham Scan_ no necesita polinomialmente más memoria que la cantidad de puntos
que recibe como entrada.
Una implementación de este algoritmo en Scala se puede encontrar
#link(GITFRONT_REPO + "tarea7/ej2/")[aquí].
][
Considere una cadena de caracteres $S$, de longitud $n$. Se desea hallar la
subcadena $T$ de $S$ más grande, tal que:
- $T$ sea prefijo de $S$ (la cadena $S$ _empieza_ con $T$).
- $T$ sea sufijo de $S$ (la cadena $S$ _termina_ con $T$).
- $T != S$.
Considere los siguientes ejemplos:
#let example1 = "ABRACADABRA";
#let example2 = "AREPERA";
#let example3 = "ALGORITMO";
- Para la cadena #underline(`ABRA`)`CAD`#underline(`ABRA`), la respuesta
sería #raw(prefix-suffix(example1)).
- Para la cadena #underline(`A`)`REPER`#underline(`A`), la respuesta sería
#raw(prefix-suffix(example2)).
- Para la cadena `ALGORITMO`, la respuesta sería #prefix-suffix(example3).
(la cadena vacía).
Diseñe un algoritmo que pueda responder a esta consulta usando tiempo $O(n)$.
][
Notemos que a la hora de hacer el preprocesamiento de una cadena dada $S$ en
el algoritmo de KMP, se calcula una tabla de saltos que se puede interpretar
exactamente como lo que se pide (y de hecho, es ese el invariante que se
mantiene en cada iteración de la construcción): la longitud del prefijo de
$S[0..i]$ más largo que también es sufijo de $S[0..i]$ sin ser $S[0..i]$.
De esta forma, el algoritmo que resolvería este problema consiste simplemente
en preprocesar de dicha manera $S$ y retornar una subcadena en el rango
$[0, r)$, donde $r$ es el último elemento de la tabla de saltos.
El algoritmo sería entonces el siguiente:
#pseudocode[
```python
def prefix_suffix(s: Cadena) -> Cadena:
tabla = preprocesar(s)
return s.subcadena(0, tabla.último())
```
]
Una implementación de este algoritmo se utilizó al compilar el código fuente de
este documento y mostrar los resultados de los ejemplos en el enunciado,
se puede encontrar #link(GITFRONT_REPO + "tarea7/src/ej3/")[aquí].
]
|
|
https://github.com/saYmd-moe/note-for-statistical-mechanics | https://raw.githubusercontent.com/saYmd-moe/note-for-statistical-mechanics/main/contents/PartI/Chp02.typ | typst | #import "../../template.typ": *
== 均匀系的平衡关系
=== _Maxwell_ 关系
通过热力学基本微分方程 $dif U = T dif S - p dif V$ 二阶微商可换序的性质,我们可以得到一系列_Maxwell_关系式:$
&dif U = ((diff U)/(diff S))_V dif S + ((diff U)/(diff V))_S dif V = T dif S - p dif V\
arrow.double& T = ((diff U)/(diff S))_V, quad p = - ((diff U)/(diff V))_S
$
考虑二阶微商:$
((diff T)/(diff V))_S = (diff^2 U)/(diff S diff V) = (diff^2 U)/(diff V diff S) = -((diff p)/(diff S))_V
$
#align(
center,
table(
columns: (auto, auto, auto),
inset: 10pt,
align: horizon,
[*微分方程*], [*变量*],[*_Maxwell_ 关系*],
[$dif U = T d S - p dif V$], [$(S,V)$],[$((diff T)/(diff V))_S=-((diff p)/(diff S))_V$],
[$dif H = T dif S + V dif p$], [$(S,p)$],[$((diff T)/(diff p))_S=((diff V)/(diff S))_p$],
[$dif F = -S dif T - p dif V$], [$(T,V)$],[$((diff S)/(diff V))_T=((diff p)/(diff T))_V$],
[$dif G = -S dif T + V dif p$], [$(T,p)$],[$((diff S)/(diff p))_T=-((diff V)/(diff T))_p$]
)
)
可以通过Jacobi行列式记忆这些关系式:$
(diff(T,S))/(diff(x,y)) = (diff(p,V))/(diff(x,y))
$分别取$(x,y)$为$(V,S),(p,S),(T,V),(T,p)$即可得到上面的四个Maxwell关系式。
=== _Maxwell_关系的应用
==== 状态变量与物态方程的联系
- *能态方程*,将 $U$看作$(T,V)$的函数,即$U = U[S(T,V),V]$:$
((diff U)/(diff V))_T &= ((diff U)/(diff S))_V ((diff S)/(diff V))_T + ((diff U)/(diff V))_S \
&=T ((diff p)/(diff T))_V - p
$<U-state>
- *焓态方程*,将 $H$ 看作 $(T,p)$ 的函数,即 $H = H[S(T,p),p]$:$
((diff H)/(diff p))_T &= ((diff H)/(diff S))_p ((diff S)/(diff p))_T + ((diff H)/(diff p))_S\
&=-T ((diff V)/(diff T))_p + V
$<H-state>
==== 热容
+ *热容差*$
C_V &= ((diff U)/(diff T))_V = ((diff U)/(diff S))_V ((diff S)/(diff T))_V = T ((diff S)/(diff T))_V\
C_p &= ((diff H)/(diff T))_p = ((diff H)/(diff S))_p ((diff S)/(diff T))_p = T ((diff S)/(diff T))_p \
&= T [((diff S)/(diff T))_V + ((diff S)/(diff V))_T ((diff V)/(diff T))_p]\
C_p - C_V &= T #text(blue)[$((diff S)/(diff V))_T$] ((diff V)/(diff T))_p = T #text(blue)[$((diff p)/(diff T))_V$] ((diff V)/(diff T))_p = T V (alpha^2)/kappa_T
$
+ *已知 $C_V (T,V_0)$ 求 $C_V (T,V)$*$
dif C_V = ((diff C_V)/(diff T))_V dif T + ((diff C_V)/(diff V))_T dif V = ((diff C_V)/(diff V))_T dif V
$其中有:$
((diff C_V)/(diff V))_T &= T (diff^2 S)/(diff V diff T) = T [(diff)/(diff T) #text(blue)[$((diff S)/(diff V))_T$]] \
&= T [(diff)/(diff T) #text(blue)[$((diff p)/(diff T))_V$]] = T ((diff^2 p)/(diff T^2))_V
$于是可以得到:$
dif C_V = T ((diff^2 p)/(diff T^2))_V dif V\
C_V (T,V) = integral_(V_1)^(V_2) T ((diff^2 p)/(diff T^2))_V dif V + C_V (T,V_0)
$
+ *已知 $C_p (T,p_0)$ 求 $C_p (T,p)$*$
dif C_p &= ((diff C_p)/(diff T))_p dif T + ((diff C_p)/(diff p))_T dif p = ((diff C_p)/(diff p))_T dif p\
&= -T ((diff^2 V)/(diff T^2))_p dif p\
$同样可以得到积分式:$
C_p (T,p) &= integral_(p_1)^(p_2) -T ((diff^2 V)/(diff T^2))_p dif p + C_p (T,p_0)
$
=== 基本热力学函数的确定
我们需要确定的基本热力学函数包括物态方程、内能($U$)、和熵($S$);考虑一个 $p dash V dash T$系统,以 $(T,V)$ 为变量,物态方程需要通过统计力学方法或者实验得到,假设物态方程已知,我们来确定内能$U$:$
dif U = ((diff U)/(diff T))_V dif T + ((diff U)/(diff V))_T dif V
$这里$(diff U\/diff T)_V = C_V$,第二项由能态方程 @U-state 确定,于是有:$
dif U = C_V dif T + [T ((diff p)/(diff T))_V - p] dif V\
U(T,V) = integral_((T_0,V_0))^((T,V)) {C_V dif T + [T ((diff p)/(diff T))_V - p] dif V} + U(T_0,V_0)\
$运用同样的方式也可以确定熵 $S(T,V)$,或者以 $(T,p)$ 为变量下的焓 $H(T,p)$。
=== 特性函数和_Joule-Thomson_效应
#colorbox(
title: [特性函数],
color: "blue",
radius: 5pt,
width: auto
)[
热力学中,如果知道一个函数的形式,就可以通过求导的方式得到所有热力学函数,则该函数成为特性函数(热力学势)。$
U(S,V), quad H(S,p), quad F(T,V), quad G(T,p), quad S(U,V), quad dots.c
$
]
#colorbox(
title: [_Joule-Thomson_效应],
color: "blue",
radius: 5pt,
width: auto
)[
_Joule-Thomson_效应是指节流过程中温度随压强会发生变化的现象。有 _Joule-Thomson_系数定义为:$
mu equiv ((diff T)/(diff p))_H = V/C_p (T alpha -1)
$节流过程是一个不可逆的等焓过程,当 $mu gt 0$ 时,节流过程中温度降低,称为致冷区;当 $mu lt 0$ 时,节流过程中温度升高,称为致温区;当 $mu eq 0$ 时,节流过程中温度不变,称为反转曲线。
]
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/document_color/advanced.typ | typst | Apache License 2.0 | #let t = luma(240);
#let t = luma(70%);
#let t = color.hsl(1deg, 1, 1); |
https://github.com/linhduongtuan/DTU-typst-presentation | https://raw.githubusercontent.com/linhduongtuan/DTU-typst-presentation/main/latex_symbol.typ | typst | #let latex-symbol = [
#set text(font: "New Computer Modern")
L#box[#move(dx: 0em, dy: -0.20em)[
#box[
#pad(left: -0.3em)[
#text(size: 0.7em)[A]
]
]
]]#box[
#pad(left: -0.15em)[T]
]#box[#move(dx: 0em, dy: 0.24em)[
#box[
#pad(left: -0.2em)[E]
]
]]#box[
#pad(left: -0.15em)[X]
]
] |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/hydra/0.3.0/README.md | markdown | Apache License 2.0 | # hydra
Hydra is a [typst] package allowing you to easily display the heading like elements anywhere in your
document. In short, it will show you the currently active element only when it is not visible.
Some of hydra's features rely on the size of the top-margin, if you use a different page size than
`a4` or a custom top margin for your pages, make sure to configure hydra, otherwise those cheks may
not work.
## Example
```typst
#import "@preview/hydra:0.3.0": hydra
#set page(header: hydra() + line(length: 100%))
#set heading(numbering: "1.1")
#show heading.where(level: 1): it => pagebreak(weak: true) + it
= Introduction
#lorem(750)
= Content
== First Section
#lorem(500)
== Second Section
#lorem(250)
== Third Section
#lorem(500)
= Annex
#lorem(10)
```
![ex1]
![ex2]
![ex3]
![ex4]
![ex5]
## Documentation
For a more in-depth description of hydra's functionality and the reference read its [manual].
## Contribution
### Testing
This package serves as my real-world test for [`typst-test`][typst-test], it is not required for
contributions, but encouraged as it speeds up the review process.
Other than that tests can be run using the following command structure for each test:
```bsh
test=...
typst --root . "tests/typ/${test}.typ" "tests/out/${test}/{n}.png"
# some command to compare images in tests/ref/${test} and tests/out/${test}
```
## Examples and manual
Furthermore, I use [`just`][just] and [`nushell`][nushell] to run common commands. It's once again
not required, as I'll generate those myself if you don't on a PR, but if you already use both you
can run the example and manual generation using `just gen`.
[ex1]: examples/example1.png
[ex2]: examples/example2.png
[ex3]: examples/example3.png
[ex4]: examples/example4.png
[ex5]: examples/example5.png
[manual]: docs/manual.pdf
[typst]: https://github.com/typst/typst
[typst-test]: https://github.com/tingerrr/typst-test
[just]: https://just.systems/
[nushell]: https://www.nushell.sh/
|
https://github.com/TheRiceCold/resume | https://raw.githubusercontent.com/TheRiceCold/resume/main/modules/certificates.typ | typst | #import "../src/template.typ": *
#cvSection("Certificates")
#cvHonor(
date: [2022],
title: [#link("https://drive.google.com/file/d/1Ahga9TNBsfRH_j3DBIsywD5D3XRbzElf/view")[Complete React Native: Zero to Mastery (with Hooks)]],
issuer: [Udemy],
)
#cvHonor(
date: [2023],
title: [#link("https://www.udemy.com/certificate/UC-566648f5-2f38-4e16-b12e-8686181ba3fa")[Vue - The Complete Guide (incl. Router & Composition API)]],
issuer: [Udemy],
)
|
|
https://github.com/MooersLab/manuscriptInTypst | https://raw.githubusercontent.com/MooersLab/manuscriptInTypst/main/README.md | markdown | MIT License | 
[](https://opensource.org/licenses/MIT)
# First submission manuscript template in typst
## Purpose
Prepare PDF for initial manuscript submission by using typst, a typesetting system written in Rust. Typst compiles small documents faster than LaTeX. This project has been developed enough to support the preparation of manuscripts of journal articles for the first submission. Its support for edge cases is underdeveloped.
## Features
- Barebones (i.e., no template file) for simplicity
- Two variants: classic and arvix-like.
- Line numbering
- Short author list, running title, and date printed in the header. This supports editing printed copies of multiple manuscripts while traveling.
- 1/N page numbering
- Biblatex (sorry, not support for BibTeX).
- example
+ figure
+ table
+ equation
## Sample title page of classic variant

The footnote with the corresponding author's contact information is not shown.
## Sample Introduction page of classic variant
The abstract is on the second page.
The Introduction starts on the third page.
Note the short author list, running title, and today's date in the header.
Note the format of the page numbers in the lower right.

## Sample of first page of arvix-like variant

## Contents
- typst source file template
- BibLATeX file
- sample PDF
## Requirements
- typst version 0.12.0 (required for line numbers, released October 18, 2024)
If you use tinymist, you will need the corresponding version, release October 19, 2024.
## Easy-peasy use
Run in typst.app on-line or run via tinymist (e.g., `tinymist preview classic.typ`) while classic.typ is open in any text editor.
The rendered version will appear in your default browser.
It updates with each save operation in the text editor.
Compile to PDF by entering in terminal `typst compile <typst filename prefix>.typ`.
## Bash or zsh function to compile and open in Preview.app on Mac (optional)
Typst compiles the *.typfile so quickly that you might as well pop open the PDF: `typc <filename prefix>`.
```bash
function typc {
echo "Compile typst file to PDF and display PDF file."
if [ $# -lt 1 ]; then
echo 1>&2 "$0: not enough arguments"
echo "Usage1: typc <filename prefix>"
return 2
elif [ $# -gt 1 ]; then
echo 1>&2 "$0: too many arguments"
echo "Usage1: typc <typst filename prefix>"
return 2
fi
typst compile $1.typ && pre $1.pdf
}
```
## Bash or zsh function to preview typst file with tinymist (optional)
Yes, I hate typing: `tmp <typst filename prefix>"
```bash
function tmp {
echo "Preview typst file in browser via tinymist."
if [ $# -lt 1 ]; then
echo 1>&2 "$0: not enough arguments"
echo "Usage1: tmp <filename prefix>"
return 2
elif [ $# -gt 1 ]; then
echo 1>&2 "$0: too many arguments"
echo "Usage1: typc <filename prefix>"
return 2
fi
tinymist preview $1.typ
}
```
## Bash or zsh function to project initiation (optional)
Paste into where ever you store your bash functions (.e.g., .bashrc or .bashFunctions sourced from .bashrc).
Customize the file paths to meet your needs.
Default to opening the classic variant.
This is what most biology journals expect.
In computer science, use the arvix-like variant.
```bash
function typman {
echo "Copy template manuscript in typst with project number in title."
if [ $# -lt 1 ]; then
echo 1>&2 "$0: not enough arguments"
echo "Usage1: typman projectID"
return 2
elif [ $# -gt 1 ]; then
echo 1>&2 "$0: too many arguments"
echo "Usage1: typman projectID"
return 2
fi
projectID="$1"
echo "Write manuscript to manu$1.typ file."
cp ~/6112MooersLabGitHubLabRepos/manuscriptInTypst/classic-first-submission-manuscript.typ manu$1.typ
cp ~/6112MooersLabGitHubLabRepos/manuscriptInTypst/first-submission.bib .
cp ~/6112MooersLabGitHubLabRepos/manuscriptInTypst/words10.png .
}
function mantyp {
echo "Copy template writing manuscript in typst with project number in title."
if [ $# -lt 1 ]; then
echo 1>&2 "$0: not enough arguments"
echo "Usage1: mantyp projectID"
return 2
elif [ $# -gt 1 ]; then
echo 1>&2 "$0: too many arguments"
echo "Usage1: mantyp projectID"
return 2
fi
projectID="$1"
echo "Write manuscript to manu$1.typ file."
cp ~/6112MooersLabGitHubLabRepos/manuscriptInTypst/classic-first-submission-manuscript.typ manu$1.typ
cp ~/6112MooersLabGitHubLabRepos/manuscriptInTypst/first-submission.bib .
cp ~/6112MooersLabGitHubLabRepos/manuscriptInTypst/words10.png .
say 'The manuscript template has been copied.'
}
```
## Use in Emacs
Install the `typst-ts-mode` package beforehand.
## Update history
|Version |Changes |Date |
|:-------------|:-----------------------------------------------------------------------------------------------------|:--------------------------|
| Version 0.1 | Initiate project. Added badges, funding, and update table. | 2024 October 11 |
| Version 0.2 | Added bash function to ease initiating new manuscript in typst. | 2024 October 13 |
| Version 0.3 | Added classic version. Added date to running title. Centered title on title page | 2024 October 17 |
| Version 0.4 | Added two bash functions to README.md for convenience. | 2024 October 19 |
## Sources of funding
- NIH: R01 CA242845
- NIH: R01 AI088011
- NIH: P30 CA225520 (PI: R. Mannel)
- NIH: P20 GM103640 and P30 GM145423 (PI: A. West)
|
https://github.com/tingerrr/hydra | https://raw.githubusercontent.com/tingerrr/hydra/main/doc/util.typ | typst | MIT License | #let package = toml("/typst.toml").package
#let load-examples(example) = {
let path = "/doc/examples/" + example
// NOTE: this breaks for docs with more than 10 pages, but at this point the example is too large
// anyway
let example = (v, i) => image(path + "/out/" + v + str(i) + ".png")
let r = range(1, toml(path + "/out.toml").pages + 1)
(
a: r.map(i => example("a", i)),
b: r.map(i => example("b", i)),
)
}
#let show-examples(examples, width: 50%) = block(
width: width,
fill: gray,
inset: 0.5em,
grid(columns: (1fr, 1fr), gutter: 0.5em, align(center + horizon)[Binding], ..examples),
)
#let issue(num) = link(package.repository + "/issues/" + str(num))[hydra\##num]
#let raw-bg = gray.lighten(50%)
#let bbox = box.with(inset: (x: 0.25em), outset: (y: 0.25em), radius: 0.25em)
|
https://github.com/horaoen/typstempl | https://raw.githubusercontent.com/horaoen/typstempl/master/note.typ | typst | #import "@preview/fontawesome:0.1.0": *
#let note(
title: none,
doc
) = {
show heading: it => {
it
h(1em)
v(-1em)
}
set page(
paper: "a4",
numbering: "1",
number-align: right,
header: "practice makes perfect."
)
set par(
justify: true,
first-line-indent: 2em,
)
set text(
font: "Source Han Serif SC",
size: 12pt
)
set enum(numbering: "1.a)", full: true)
align(center, heading(level: 1, title))
// contact
let contact = [
#fa-envelope() #h(1em) #link("mailto:<EMAIL>")
#h(1em) | #h(1em)
#fa-github() #h(1em) #link("https://github.com/horaoen")
]
// Display inline code in a small box
// that retains the correct baseline.
show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Display block code in a larger block
// with more padding.
show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
show raw: it => {
set text(font: "FiraCode Nerd Font")
it
}
show emph: it => text(font: "Didot", style: "italic", it.body)
align(center, contact)
doc
}
|
|
https://github.com/Alignof/typst_template | https://raw.githubusercontent.com/Alignof/typst_template/master/README.md | markdown | MIT License | # typst\_template
My typst template.
|
https://github.com/Hucy/cv_typst_template | https://raw.githubusercontent.com/Hucy/cv_typst_template/main/cv_zh.typ | typst | MIT License | #let primary_color = rgb("#7F96AD")
#show link: underline
#set text(
size: 12pt,
weight: "regular",
font: ("linux libertine", "Microsoft YaHei", "PingFang SC"),
)
#set list(indent: .6em, marker: ([•]))
#set page(
paper: "a4",
margin: (left: 1.4cm, right: 1.4cm, top: .8cm, bottom: .8cm),
)
#set par(justify: true)
#let section(title, body) = {
block[
#set text(weight: "bold", size: 14pt, fill: primary_color)
#h(0.2em)
#title
#box(width: 1fr, line(length: 100%, stroke: 0.5pt + primary_color))
]
pad(x: .4em)[
#body
]
}
#let contact_info(name, location, phone, email) = {
grid(
columns: (1fr),
gutter: 0.4em,
align(right)[
#set text(size: 10pt)
#location \
#phone \
#email
],
rect(
width: 100%,
fill: primary_color,
inset: 0.4em,
[#align(left)[#text(fill: white, weight: "bold", size: 18pt)[#name]]],
)
)
}
#let job(company, title, start, ..end) = {
let e = if end.pos().len() != 0 [-- #end.pos().at(0)]
block[
*#company* #h(1fr) #start #e \
#title
]
}
#let randomZh(n) = {
let t = "我能吞下玻璃而不伤身体"
let i = calc.floor(n * 3 / t.len())
while i > 0 {
t += t
i = i - 1
}
t.slice(0, n*3)
}
#contact_info("姓名", "上海", "12346789087", "<EMAIL>")
#section("简介")[
#randomZh(20)
]
#section("技能")[
- 技术栈:#randomZh(5),#randomZh(5)
- 语言:Ruby,Python
- 其他:#randomZh(11)
]
#section("工作")[
#job("xxx公司", "xx工程师", "2000.3", "至今")
#randomZh(20)\
- #randomZh(4):
- #randomZh(11)
- #randomZh(11)
- #randomZh(7):
- #randomZh(10)
- #randomZh(10)
- #randomZh(5):
- #randomZh(10)
#job("xxx公司", "xx工程师", "2000.3", "2000.7")
#randomZh(20)\
- #randomZh(10)
- #randomZh(10)
]
#section("项目")[
#link("")[
*#randomZh(6)*
]\
#randomZh(15)
]
#section("教育")[
#job("xxxx学校", "xxxx专业", "2000.9", "2019.6")
]
|
https://github.com/jcbhmr/typst-docs | https://raw.githubusercontent.com/jcbhmr/typst-docs/main/README.md | markdown | MIT License | <p align=center>
<b>You're probably looking for <a href="https://typst.community/typst-docs/">typst.community/typst-docs</a></b>
</p>
## Development





### Add a new language
1. Run `git submodule add https://github.com/typst/typst.git $LANGUAGE_TAG` where `$LANGUAGE_TAG` is your new BCP-47 language tag to add a new patched submodule instance of Typst
2. Update [`run.js`](run.js) and [`[route].paths.ts`](./[route].paths.ts) `languageTags` list to add your new language tag
3. Create a new file in `.vitepress/config/` with the file name `${languageTag}.ts` where `${languageTag}` is your new language tag
4. Import and add that new language configuration to `.vitepress/config/index.ts`
5. Run `npm run diff` to save any changes you make to the submodule that you added in step 1
6. Add a new language card to [`index.md`](index.md)
### Edit the documentation content
You should run `npm run apply` with the submodule tree initialized and present (`git submodule update --init --recursive` if you didn't clone with `--recursive`) before doing any documentation editing. This `npm run apply` will use `git apply` to apply the patch files from `patches/*.patch` to the corresponding submodule. Do this before editing so that you're editing the patched version of the submodule. Then after you've finished editing the submodule use `npm run diff` to save the diff of all the changes made to the submodule backc into `patches/*.patch`. Then commit the `patches/*.patch` files.
You can run `npm run generate` with the Rust toolchain installed to compile & build the `typst-docs` crate CLI which spits out the JSON docs structure into `pages.*.json` for each known and tracked language variant. This must be done manually and does take quite a while to compile. After finishing the generation **add and commit the generated file** so other users in the future can edit the VitePress site without compiling `typst-docs` themselves.
**TL;DR:**
1. Clone the repository and `npm install`
3. `npm run apply` to apply `patches/*.patch` work from previous authors
4. Edit the submodule contents
5. `npm run generate` to generate the `pages.*.json`
6. `npm run dev` to make sure it works
7. Commit and push!
**🙌 We need you! ❤️** Translations and localization can always be improved. If you spot any errors or want to add more translations, please do!
You can use `git -C <dir> ...` to emulate `(cd <dir> && git ...)` to perform Git operations in the submodule. For example: `git -C zh reset --hard`.
### Edit the VitePress site
[](https://pr.new/https://github.com/typst-community/typst-docs)
Someone should already have been nice enough to generate & commit a `pages.*.json` for a particular language. `[route].paths.ts` will generate all the per-page JSON data that is then routed to a specific component in `[route].md`. You can find these components in `.vitepress/theme/components/`. There's a different component for each `kind` of page body listed in the `pages.*.json`.
**🙌 We need you! ❤️** Some of the page types need some love to expose more of the JSON-provided information in pretty HTML. Particularily `Func.vue`.
|
https://github.com/jassielof/typst-templates | https://raw.githubusercontent.com/jassielof/typst-templates/main/upsa-bo/estudio-de-factibilidad/template/capítulos/11.evaluación social y ambiental.typ | typst | MIT License | = Evaluación Social y Ambiental
== Evaluación Social
=== Presentación de Supuestos
=== Inversiones
=== Beneficios de la Sociedad
=== Desbeneficios de la Sociedad
=== Resultado Social de la Operación del Proyecto
=== Flujo de Caja Social
=== Resultados de la Evaluación Social
== Evaluación Ambiental
=== Registro Ambiental Industrial
=== Categoría de Impacto Ambiental
|
https://github.com/i-am-wololo/cours | https://raw.githubusercontent.com/i-am-wololo/cours/master/TP/i22/main.typ | typst | #import "./templates.typ": *
#show: project.with(title: "TP1 i22")
== 1.0 La commande `od`
Quelle option permet d'afficher les adresses en hexadécimal au lieu d'octal ? --address-radix=x
Quelle option permet d'afficher chaque octet d'un fichier en hexadécimal ?
format=x
Quelle option permet de sauter un certain nombre d'octets ?
jN, N etant le nombre d'octets
Quelle option permet de n'interpréter qu'un certain nombre d'octets ?
NN, le second N etant le nombre d'octet
== Utilisation de `od`
la valeur 192, nombre entier non signé codé sur 8 bits
`192` sur 8 bit est `11000000` donc `C0`
le resultat peut etre obtenu avec `od -tx1 -N0 valeurs`
la valeur -1, nombre entier signé codé sur 8 bits,
-1 sur 8 bit est, en utilisant le complement a 2, 256-1 = 255, donc FF
`od -tx1 -j1 -N1 valeurs`
la valeur -2, nombre entier signé codé sur 16 bits,
-2 sur 16 bit est 65,5345-1 = 65,5345, donc FFE
`od -tx1 -j1 -N1 valeurs` drole comment un nombre peut avoir differentes valeurs suivant la maniere dont il est lu
la valeur 1633837924, nombre entier non signé codé sur 32 bits,
par divisions euclidiennes successives automatise, j'obtient 0x616F6C4C
la valeur 1.0, nombre réel codé au format IEEE 754 32 bits (nombre à virgule flottante),
0 1111111 00000...$n^23$
od -tfF
la valeur -10.25, nombre réel codé au format IEEE 754 64 bits (nombre à virgule flottante),
1 100000010 01...
== Encodage des caracteres
À la suite des valeurs numériques précédentes de l'exercice précédent, se trouve également dans le fichier la suite de caractères ASCII abcdABCD0123. Quel est le code ASCII en hexadécimal des caractères a et A (od accepte l'accumulation de plusieurs formats en paramètres) ? Donnez une méthode qui permet de passer rapidement des minuscules aux majuscules un caractère ASCII, et inversement.
la valeur de A est 65, celle de a est 97 on peut additionner par -25 ou 25 pour passer rapidement de majuscule vers minuscule et vice versa
l'ascii de 0 est 48, et de 9 57, on peut simplement additionner par 1 pour avoir chaque caractere representant un chiffre
Vérifiez vos réponses à l'aide des instructions Python ord et chr.
`[chr(48+i) for i in range(10)]` renvoie `['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']` [chr(97+i) for i in range(25)] renvoie l'alphabet
Dans le même répertoire /home/partage/I22/ se trouve trois autres fichiers : texte1, texte2 et texte3.
À l'aide des commandes cat et less, visualisez le contenu de ces fichiers. Voyez-vous une différence majeure dans leur affichage ?
En fait ces trois fichiers comportent le même texte mais écrit dans un encoding différent. À l'aide de la commande od et des caractéristiques des encodings ISO-8859 (latin-1), UTF-8 et UTF-16, quels indices vous permettent de déterminer quel encoding est utilisé par quel fichier.
text1 et 3 utilises utf-16, text2 utilise iso-8859
Étudiez la commande file et validez votre réponse à la question précédente.
juste
Que donne la réponse de la commande file pour le premier fichier valeurs ? Pourquoi
data, car le fichier ne contient pas de headers, c'est donc seulement un fichier binaire pour l'os
== 1.6 Jeux de piste
Dans cet exercice, vous allez utiliser la commande od pour retrouver une information fragmentée et cachée dans le fichier valeurs.
Trouvez chaine1, la première chaîne de caractères encodée en ASCII, qui débute à l'adresse 37 et fait 9 caractères de long.
10.99.185.XXX
Trouvez chaine2 la chaîne de deux caractères encodée en UTF-16 qui se situe 12 octets après chaine1.
Trouvez la valeur val qui est un entier non signé codé sur deux octets, situé 17 octets après chaine2.
Effectuez dans un terminal la commande curl suivi de la concaténation directe (sans insérer d'espace) de chaine1, chaine2 et de val. Qu'obtenez-vous ?
|
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/template.typ | typst | // 字体
#import "tablex.typ": tablex, rowspanx,colspanx
#let data=yaml("use.yaml");
// set text(font:("Times New Roman","Source Han Serif"),size: 12pt)
#let font = (
main: "Source Han Serif",
mono: "Source Han Serif",
cjk: "Times New Roman",
english:"Times New Roman"
)
// 图标
#let icon(path) = box(
baseline: 0.135em,
height: 1.0em,
width: 1.0em,
image(data.icon.文件夹+"/"+path)
)
#let faAngleRight = icon("fa-angle-right.svg")
// 主体
#let resume(
size: 10pt,
themeColor: rgb(46, 49, 124),
top: 1.5cm,
bottom: 2cm,
left: 2cm,
right: 2cm,
photograph: "",
photographWidth: 0em,
gutterWidth: 0em,
// name,
header,
body
) = {
// 设置页边距设定
set page(paper: "a4", numbering: "1", margin: (
top: top,
bottom: bottom,
left: left,
right: right,
))
// 基础字体设定
set text(font: (font.main, font.cjk), size: size, lang: "zh")
// show heading: set text(themeColor, 1.1em)
// 标题样式
show heading.where(level: 2):set text(themeColor, 1.1em)
// 小标题样式
show heading.where(level: 1):set text(themeColor, 1.2em)
// 二级标题下加一条横线
show heading.where(level: 2): it => stack(
v(0.3em),
it,
v(0.6em),
// line(length: 100%, stroke: 0.05em + themeColor),
line(length: 100%,stroke: (paint: themeColor, thickness: 0.06em, dash: "dashed")),
v(0.1em),
)
// 更改 bullet list 的图标
// set list(indent: 1em, body-indent: 0.8em, marker: faAngleRight)
// 上面的语句无法精确控制图标位置, 因此改用了下列方法重写 list
show list: it => stack(spacing: 0.4em, ..it.children.map(item => {
grid(
columns: (2em, 1fr),
gutter: (0em),
box({
h(0.75em)
faAngleRight
}),
pad(top: 0.15em, item.body)
)
}))
// 链接颜色
show link: set text(fill: themeColor)
// 主体设定
set par(justify: true)
show par: set block(spacing: 0.5em)
// 首部与照片
grid(
columns: (auto, 1fr, photographWidth),
gutter: (gutterWidth, -1em),
header,
if (photograph != "") {
image(photograph, width: photographWidth)
}
)
body
}
// 带竖线的侧边栏
#let sidebar(side, content, withLine: true, sideWidth: 12%) = style(styles => {
let sideSize = measure(side, styles)
let contentSize = measure(content, styles)
let height = calc.max(sideSize.height, contentSize.height) + 0.5em
grid(
columns: (sideWidth, 0%, 1fr),
gutter: (0.75em),
{
set align(right)
v(0.25em)
side
v(0.25em)
},
if (withLine) {line(end: (0em, height), stroke: 0.05em)},
{
v(0.25em)
content
v(0.25em)
},
)
})
// 个人信息
// 分两行
#let info(
color: black,
..infos
) = {
set text(font: ("youshebiaotihei"), fill: color)
infos.pos().map(dir => {
v(-2.3em)
box(
// line(length: 100%,stroke: (paint: black, thickness: 0.03em, dash: "dashed"))
{
line(length: 90%,stroke: (paint: black, thickness: 0.03em))
v(-0.9em)
if "icon" in dir {
if (type(dir.icon) == "string") {
icon(dir.icon)
} else {
dir.icon
}
}
h(0.15em)
if "link" in dir {
link(dir.link, dir.content)
v(-0.5em)
// line(length: 100%,stroke: (paint: black, thickness: 0.03em, dash: "dashed"))
} else {
text(font: "YouSheBiaoTiHei",size: 1.4em)[#dir.content]
v(-0.0em)
// align(center,text(font: "FangSong",size: 0.65em)[#dir.content1])
v(-0.9em)
// line(length: 100%,stroke: (paint: black, thickness: 0.03em, dash: "dashed"))
line(length: 90%,stroke: (paint: black, thickness: 0.03em))
}
})
}).join(h(0.2em) + "·" + h(0.2em))
v(-0.5em)
}
#let add_h1(body)={
body
h(1em)
}
// 日期: 颜色变灰
#let date(body) = text(
fill: rgb(108, 108, 108),
size: 0.9em,
font: "Times New Roman",
body
)
// 技术: 字体变细
#let tech(body) = block({
set text(weight: "extralight"
,font: "Times New Roman"
)
body
})
// 叶首的名字
#let name_header(body) = block({
set text(
weight: "semibold"
// ,font: "SimHei",
,font: "STSong",
size: 1.5em
// fill: rgb(46, 49, 124),
)
body
})
// 项目
#let item(
title,
desc,
endnote
) = {
v(0.25em)
grid(
columns: (30%, 1fr, auto),
gutter: (0em),
title, desc, endnote
)
}
// 姓名首行居中
#let name-header(
empty,
name,
header,
img
)={
grid(
columns: (15%, 70%, 15%),
gutter: (0em),
empty,name+header,img
)
}
// 排名和成绩,分两栏
// 左边是成绩+部分均分 右边是英语成绩列表
// 其他成绩如计算机几级建议写道后面
#let grade_rank(rank,english)={
grid(
columns: (46%, 30%),
gutter: (0em),
[#rank]
,
english
)
}
#let get_grade_name()={
// for i in data.展示的成绩.科目
}
// 一些变量
#let zhuxiu_use=[
主修
课程
]
#let english_use=[
英语
成绩
]
// #let english_socre_num=data.英语科目.len();
#let 数组测试=[
1,2,3,4,5
]
// #let table_english=tablex(
// columns: english_socre_num+1,
// align: center + horizon, // 水平居中+垂直居中
// auto-vlines: false, // 不显示垂直线
// header-rows: 2,
// // color the last column's cells
// // based on the written number
// /* --- header --- */
// rowspanx(2)[#english_use],
// // #数组测试
// )
// #let table_auto(list1,list2)=
// {
// #tablex(
// columns:data.展示科目.len()+1 ,
// align: center + horizon, // 水平居中+垂直居中
// auto-vlines: false, // 不显示垂直线
// header-rows: 2,
// // color the last column's cells
// // based on the written number
// /* --- header --- */
// rowspanx(2)[#zhuxiu_use],
// ..data.展示科目,
// ..data.展示成绩
// )
// }
#let table_auto(list1,list2,use)={
tablex(
columns:list1.len()+1 ,
align: center + horizon, // 水平居中+垂直居中
auto-vlines: false, // 不显示垂直线
header-rows: 2,
// color the last column's cells
// based on the written number
/* --- header --- */
rowspanx(2)[#use],
..list1,
..list2
)
}
// #let table_grade={
// table_auto(data.展示科目,data.展示成绩,zhuxiu_use)
// }
// #let table_english={
// table_auto(data.英语科目,data.英语成绩,english_use)
// }
// tablex(
// columns:data.展示科目.len()+1 ,
// align: center + horizon, // 水平居中+垂直居中
// auto-vlines: false, // 不显示垂直线
// header-rows: 2,
// // color the last column's cells
// // based on the written number
// /* --- header --- */
// rowspanx(2)[#zhuxiu_use],
// ..data.展示科目,
// ..data.展示成绩
// ) |
|
https://github.com/orkhasnat/resume | https://raw.githubusercontent.com/orkhasnat/resume/master/modern-1P/resume.typ | typst | #import "resume-lib.typ": *
// #import "fa-lib.typ": *
#show: resume.with(
author: (
firstname: "Tasnimul",
lastname: "Hasnat",
email: "<EMAIL>",
phone: "+880-1731969827",
github: "orkhasnat",
linkedin: "tasnimul-hasnat-37515025a",
positions: (
"Software Developer",
"Cybersecurity Analyst",
"Open Source Enthusiast"
)
),
)
= About Me
// I'm a final semester undergraduate student with a keen interest in open-source projects. I actively seek out opportunities to learn and grow, specially within collaborative team environments where I can contribute to technological innovations. Adept at bug hunting and vulnerability detection, I excel at performing under tight deadlines and pressure.
I'm a recent graduate with a passion for technology and a strong interest in open-source development. I flourish in collaborative environments, actively seeking opportunities to learn and grow while excelling under pressure and tight deadlines. Eager to apply my skills and enthusiasm to contribute meaningfully to innovative projects aimed at the betterment of society.
= Education
#resume-entry(
title: "Islamic University of Technology",
location: "B.Sc in Computer Science & Engineering",
date: "Jan 2020 - Present",
description: "CGPA: "+text(fill:color-darkgray)[3.77]+" out of 4.00" // | Position: "+text(fill:color-darkgray)[19#super("th")]
)
#resume-entry(
title: "Dhaka Residential Model College",
location: "Higher Secondary Certificate",
date: "2017 - 2019",
description: "GPA: "+text(fill:color-darkgray)[5.00]+" out of 5.00"
)
#resume-entry(
title: "Dhaka Residential Model College",
location: "Secondary School Certificate",
date: "2015 - 2017",
description: "GPA: "+text(fill:color-darkgray)[5.00]+" out of 5.00"
)
= Experience
#resume-entry(
title: "Beetles Cyber Security Ltd.",
location:"PenTest Intern",
date:"",
description:[
Became familiarized with vulnerability assessment and malware development.]
)
#v(4pt)
// #resume-achievement[
// #let t = text.with(weight:"black")
// - #t[BUET CSE Fest CTF 2023]
// - *Champion* among 100+ teams.
// - #t[DU Cefalo ITVerse CTF 2023]
// - *4#super[th]* among 60+ teams.
// - #t[RITSEC International CTF 2023]
// - *7#super[th]* among 710+ _international_ teams.
// - #t[SUST SWE Technovent CTF 2023]
// - *6#super[th]* among 40+ teams.
// - #t[RIOT Flaghunt CTF 2022]
// - *8#super[th]* among 80+ teams.
// - #t[Awarded IUT-OIC Partial Scholarship]
// - Ranked *195#super[th]* amongst 4200+ participants.
// - Scholarship awarded for 3 Years equivalent to *\$13500*.
// ]
= Projects
#resume-project(
title: "Abaash",
location: github-link("orkhasnat/Abaash"),
stack: "EJS, ExpressJs, MariaDB, Bulma"
)
#resume-item[
Abaash is a user-friendly web application designed to facilitate flat searches and rentals for IUT students, while simplifying property management for flat owners.]
#resume-project(
title: "Broke_No_More",
location: github-link("orkhasnat/Broke_No_More"),
stack: "Python, Keras, Pandas"
)
#resume-item[
Developed an LSTM-based deep learning model to forecast stock price movements in the Dhaka Stock Exchange, enhancing investment decision-making with accurate predictions.
]
#resume-project(
title: "Fox's Tale",
location: github-link("orkhasnat/Foxs-Tale"),
stack: "C++, SFML"
)
#resume-item[
A modern tribute to the classic Rapid Roll game, built with SFML. Players control a ball navigating through rising platforms while avoiding obstacles and collecting bonuses. With updated graphics, sound effects, power-ups, and achievements.]
#resume-project(
title: "Outbreak",
location: github-link("orkhasnat/Outbreak"),
stack: "C++, SFML"
)
#resume-item[
Developed a viral simulator to model virus spread, incorporating parameters like transmission rate, mortality rate, and incubation period. Users can adjust these parameters to analyze their impact on virus transmission dynamics.]
#resume-project(
title: "ISC-BD",
location: github-link("orkhasnat/ISC-BD"),
stack: "Astro, TypeScript, Tailwind"
)
#resume-item[
#set text(hyphenate: false)
Developed a comprehensive full-stack portfolio website for a non-profit NGO. Managed the entire development lifecycle, from initial conceptualization to deployment.
]
= Skills
#resume-skill-item("Programming Languages", ("C","C++", "Java", "Go", "Python", "JavaScript","SQL","x86 Assembly"))
#resume-skill-item("Libraries & Frameworks", ("Astro","React","Tailwind","SFML","ExpressJS","Pandas","Keras"))
#resume-skill-item("Other Tools", ("Git","Bash","Linux","Docker","Excel","Burp Suite","UML","LaTeX"))
#resume-skill-item("Database",("Oracle","MySQL","MariaDB"))
= Achievements
#resume-achievement2[
BUET CSE Fest CTF 2023][
*Champion* among 100+ teams.]
#resume-achievement2[DU Cefalo ITVerse CTF 2023][*4#super[th]* among 60+ teams.]
#resume-achievement2[RITSEC International CTF 2023][*7#super[th]* among 710+ _international_ teams.]
#resume-achievement2[SUST SWE Technovent CTF 2023][*6#super[th]* among 40+ teams.]
#resume-achievement2[RIOT Flaghunt CTF 2022][*8#super[th]* among 80+ teams.]
#resume-achievement2[Awarded IUT-OIC Partial Scholarship][
// Ranked *195#super[th]* amongst 4200+ participants. \
Scholarship awarded for 3 Years equivalent to *\$13500*.]
#v(0.85pt)
= Co-Curriculars
#resume-cocurr[
- Member of #link("https://ctftime.org/team/175924")[_IUT Genesis_], team ranked #text(weight:"bold")[1#super("st")] in #link("https://ctftime.org/stats/2023/BD")[_CTFtime_] in Bangladesh (2023).
- Organizer and Problem Setter of IUT 11#super("th") National ICT Fest 2024.
- Problem Setter at KnightCTF 2023.
- Organizer and Problem Setter of Intra IUT Coderush Competition 2023.
- Volunteer at Intra IUT Hackathon Competition 2023.
- Instructor at IUT CTF Club.
- Participated in various national and international CTF (Capture the Flag) competitions since 2022.
]
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/math-number-spacing_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
$
10degree \
10 degree \
10.1degree \
10.1 degree
$
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/机器学习数学导引/作业/hw3.typ | typst | #import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark
#import "../../template.typ": *
#import "../main.typ": *
#show: note.with(
title: "作业3",
author: "YHTQ",
date: datetime.today().display(),
logo: none,
withOutlined : false,
withTitle : false,
)
#let index = $bold(1)$
= #empty
首先由熟知的不等式:
$
max e^(z_j) <= ((sum_j (e^(z_j))^beta) / n)^(1 / beta)
$
取对数得:
$
max z_j <= log((sum_j e^(beta z_j)) / n) / beta <= log(sum_j e^(beta z_j)) / beta
$
另一方面:
$
log(sum_j e^(beta z_j)) / beta <= (log (n e^(beta max z_j))) / beta = max z_j + log n / beta
$
= #empty
== #empty
显有若 $x_i$ 分类正确则 $p_i >= 1/C$,否则 $p_i < 1/2$. 假设 $x_i$ 分类错误,则有:
$
1/n sum_i -log p_i > 1/n (- log p_i) = 1/n (-log 1/2) = (log 2) / n
$
因此若 $cal(R) <= (log 2) / n$ 一定所有都分类正确
== #empty
$
sum_i index (y_i in.not argmax_j f_j (x_i)) <= sum_i -(log p_i)/(log 2) = 1/(log 2) cal(R)
$
== #empty
#lemma[][
假设 $x_i > 0$ 严格递减,则有:
$
1 - x_0^lambda / (sum_i x_i^lambda) tilde (x_1/x_0)^lambda
$
这里 $tilde$ 是指 $lambda -> +infinity$ 时的等价无穷小
]
#proof[
$(1 - x_0^lambda / (sum_i x_i^lambda)) / (x_1/x_0)^lambda = ((sum_(i > 0) x_i^lambda) / (sum_i x_i^lambda)) / (x_1/x_0)^lambda = (sum_(i > 0) (x_i / x_1)^lambda) x_0^lambda / (sum_i x_i^lambda) -> 1$
]
#lemma[][
设 $a, b > 0$ 是等价无穷小,则 $log(a), log(b)$ 是等价无穷大
]
#proof[
$log(a) / log(b) = log(b dot a / b) / log(b) = 1 - log(a / b) / (log b) -> 1$
]
#lemma[][
假设对于每个 $i, x_(i j) > 0$ 关于 $j$ 严格递减,且 $x_(i 0)/x_(i 1)$ 也严格递减,则:
$
(log (1/n sum_i - log (x_(i 0) / (sum_j x_(i j)))))/lambda -> log x_(0 1) - log x_(0 0)
$
]
#proof[
注意到有:
$
-log (x_(i 0) / (sum_j x_(i j))) = -log (1 + x_(i 0) / (sum_j x_(i j)) - 1) tilde 1 - x_(i 0) / (sum_j x_(i j)) tilde (x_(i 1) / x_(i 0))^lambda\
log (1/n sum_i - log (x_(i 0) / (sum_j x_(i j)))) tilde 1/n sum_i (x_(i 1) / x_(i 0))^lambda tilde 1/n (x_(0 1)/x_(0 0))^lambda
$
因此:
$
(log (1/n sum_i - log (x_(i 0) / (sum_j x_(i j)))))/lambda tilde log(1/n (x_(0 1)/x_(0 0))^lambda )/lambda = log x_(0 1) - log x_(0 0)
$
]
在上面的引理中代入 $e^(f_j (x_i))$ 并重新排序即得结论。
= #empty
== #empty
记 $V_x^bot$ 为 ${x_i}$ 的正交补空间,对任意 $beta$ 可做正交分解:
$
beta = beta_1 + beta_2, beta_2 in V_x^bot, beta_1 in V_x
$
则显然有:
$
1/n sum_i l(y_i f(x_i\; beta, beta_0)) + lambda/2 norm(beta)^2 = 1/n sum_i l(y_i f(x_i\; beta_1)) + lambda/2 norm(beta_1)^2 + lambda/2 norm(beta_2)^2
$
显然对于最优解 $beta^*$ 应有 $beta_2 = 0$,也即 $beta^*$ 在 $V_x$ 上。代入 $beta^* = X alpha$,优化目标变为:
$
1/n sum_i l(y_i (alpha^T X^T x_i + beta_0)) + lambda/2 alpha^T X^T X alpha
$
对 $alpha$ 求导,得:
$
0 = 1/n sum_i y_i X^T x_i l'(y_i (alpha^T X^T x_i + beta_0)) + lambda X^T X alpha = 1/n sum_i y_i X^T x_i l'(gamma_i^star) + lambda X^T X alpha
$
显有 $abs(alpha_i) prop l'(gamma_i^star)$
== #empty
=== #empty
$
l'(gamma_i^star) = - e^(-gamma_i^star)
$
显有 $abs(alpha_i) prop e^(-gamma_i^star)$
=== #empty
当 $gamma_i^* > 1$ 时,不难发现有 $l' (gamma_i^star) = 0$,因此只能有 $alpha_i = 0$
=== #empty
$alpha_i$ 可以看作数据点 $x_i$ 的权重,当 $l' (gamma_i^star)$ 较大时,对应数据点对于分类结果非常敏感,说明该数据点对于分类结果的贡献较大,因此 $alpha_i$ 也应该较大。
= #empty
== #empty
由约束条件,不难得到:
$
epsilon_i >= max(0, 1 - y_i f(x_i))
$
假设 $t$ 单调递增,则目标取最小值时,显有:
$
epsilon_i = max(0, 1 - y_i f(x_i))
$
原问题变成:
$
min_(f in cal(F)) lambda Omega(f) + 1/n sum_i t(max(0, 1 - y_i f(x_i)))
$
== #empty
为使:
$
t(max(0, 1 - y_i f(x_i))) = (max(0, 1 - y_i f(x_i)))^2
$
显然取 $t(x) = x^2$ 即可。
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-node-01.typ | typst | Other | // Test full reset.
#show heading: [B]
#show heading: set text(size: 10pt, weight: 400)
A #[= Heading] C
|
https://github.com/topdeoo/Course-Slides | https://raw.githubusercontent.com/topdeoo/Course-Slides/master/Survey/NAE-SAT/main.typ | typst | #import "@preview/elsearticle:0.2.1": *
#show: elsearticle.with(
title: [`NAE-SAT` Survey],
authors: (
(
name: "<NAME>",
affiliation: "NENU",
corr: "<EMAIL>",
id: none,
),
),
journal: "Notebook '24",
keywords: ("NAE-SAT", "MAX NAE-SAT"),
format: "review",
)
#set quote(block: true)
#show quote.where(block: true): it => {
set par(leading: 1em)
set text(style: "italic")
text(font: "Segoe Script")[“] + it.body + text(font: "Segoe Script")[”] + "\n"
if it.attribution != none {
set align(right)
set text(font: "Segoe Script", style: "italic")
"-" + it.attribution
}
}
= NAE-SAT
== Definition
首先,我们重申 SAT 的定义:
/ _Definition 1_: 对于一个给定的 CNF 公式 $c_1 and ... and c_m$,其中 $c_i = or.big^t_j x_t$ 且 $t gt.eq 1, t in ZZ$,是否存在一组赋值 $phi = (x_1, dots, x_n), x_i in {0, 1}$,使得 CNF 成真
\
而 NAE-SAT,全称 _Not-All-Equal SAT_,就是在 SAT 的基础上再加上一条约束:
\
/ _Definition 2_: 给定一个 SAT 问题,要求每个子句 $c_i$ 中至少有一个文字为真且至少有一个文字为假 (也就是说一个子句中不可能所有变量均相等)
\
注意到,NAE-SAT 是对称的,即,我们翻转赋值 $phi$ 中的每个赋值后得到 $phi^prime$,$phi^prime$ 仍然是问题的一个成真赋值。
在文章 @porschenXSATNAESATLinear 中, 其提及了两个典型的问题:
+ Set Splitting, 见 @sec:set-splitting
+ Hypergraph bicolorability,见 @sec:hypr-bicolor
并且,文章 @porschenXSATNAESATLinear 在 *Concluding Remarks and Open Problems* 一节中提出:
对于 NAE-SAT,到目前为止还没有取得这样的进展#footnote[指精确算法的提出与优化],这并不奇怪,因为对于不受限制的情况,NAE-SAT 与 SAT 本身一样难。
因此,我们面临的问题是,是否可以提供精确的确定性算法来解决 NAE-SAT。
当然,这已经是 2011 年提出的 Open Problem 了,但似乎到今年(2024)为止,还没有论文提出精确算法来求解 NAE-SAT
== Set Splitting<sec:set-splitting>
#quote(attribution: [WikiPedia])[
In computational complexity theory, the set splitting problem is the following decision problem: given a family F of subsets of a finite set S, decide whether there exists a partition of S into two subsets S1, S2 such that all elements of F are split by this partition, i.e., none of the elements of F is completely in S1 or S2. Set Splitting is one of Garey & Johnson's classical NP-complete problems. The problem is sometimes called hypergraph 2-colorability.
]
此问题可以轻易编码为 NAE-SAT:
给定子集簇 $cal(F) = {S_1, S_2, S_3, dots, S_n }$,全集为 $S$, 满足 $forall S_i in cal(F), S_i subset.eq S$,问是否存在两个集合 $X_1, X_2$ 满足:
$
forall S_i in cal(F), not (S_i subset.eq X_1) and not (S_i subset.eq X_2)
\
X_1 sect X_2 = emptyset.rev, X_1 union X_2 = S
$
我们考虑以下朴素编码:
簇中的每个子集本质上就是一个子句,我们对全集 $S$ 中的每个元素进行编号:$x_1, x_2, dots, x_m$,于是,$"CNF" = and.big_(i = 1)^n (or.big_(x_j in S_i)x_j)$
最后我们得到赋值为 $phi$,赋值为真的变量为集合 $X_1$ 中的元素,否则为 $X_2$ 中的元素
== Hypergraph bicolorability<sec:hypr-bicolor>
/ 超图(Hypergraph): 一种广义的图,其中边(称为超边)可以连接任意数量的顶点,而不仅仅是两个顶点。
显然 @sec:set-splitting 中对于子集簇 $cal(F)$ 与全集 $S$ 可以直接对应到超图 $cal(H) = <V, E> arrow.r.l.double <S, cal(F)>$
于是,问题可以变为一个 2-color 问题,即只用两种颜色如何将超图完全着色。
== Others
暂时未找到 NAE-SAT 的进展,目前可能原因在于:
+ NAE-SAT 的应用场景少
业内#footnote[业内,但本文引用的大多数论文都是Math与Physics分类的,CS分类也是TCS]大多数的研究都集中在 NAE-SAT 的两个变种上,我们将在
@sec:k-sat, @sec:max-k-sat 中介绍。
在 @el-kadiQuantumApproximateOptimisation2024 中提到,NAE-SAT 在计算复杂性的规约上有着重要的作用,
这或许也能解释,为什么关于 NAE-SAT 的均是理论研究。
// == 应用场景
// 我们想知道,是否有问题能够编码为 `NAE-SAT`(即此问题的应用场景是什么),在 @dingSatisfiabilityThresholdRandom2013 中提及的 @CojaOghlan2011TheCT
= NAE-k-SAT / k-NAE-SAT<sec:k-sat>
/ _Definition 3_: 给定一个 SAT 问题,要求每个子句 $c_i$ 中至少有一个文字为真且至少有一个文字为假,并且每个子句中恰好有 $k$ 个文字
=== Theory
在这个问题上的理论研究显然比一般的 NAE-SAT 要多,例如 @dingSatisfiabilityThresholdRandom2013, @slyLocalGeometryNAESAT2023, @namOnestepReplicaSymmetry2023, @gamarnikPerformanceSequentialLocal2017 等,
然而,在这些文章之中,@dingSatisfiabilityThresholdRandom2013 更集中于探讨 _random d-regular k-NAE-SAT_;
而 @slyLocalGeometryNAESAT2023, @namOnestepReplicaSymmetry2023 更集中于讨论 _random d-regular k-NAE-SAT_ 在物理学中的应用(毕竟作者是 #link("https://scholar.google.com/citations?user=y0U2EaUAAAAJ&hl=en")[Allan Sly]),这是因为 _random k-NAE-SAT_ 在稀疏随机约束求解问题中是最简单的一类了,统计物理学中将这种问题描述为 _replica symmetry breaking_。#footnote[然而,这些文章其实都看不懂,没有物理学的知识导致我不知道这些理论有什么用]
首先,我们介绍什么是 _random d-regular k-NAE-SAT_:
\
/ _Definition 4_: 给定一个随机生成的 CNF,其包含了 $d$ 条子句,且每条子句的长度都为 $k$,是否存在一组赋值 $phi$ 使得每条子句中的文字不全为真
\
@dingSatisfiabilityThresholdRandom2013 的工作明确建立了一个阈值 $d_* equiv d_*(k)$,并证明,当 $d < d_*$ 时,随机生成的 CNF 几乎总是可满足的;而当 $d > d_*$ 时,随机生成的 CNF 几乎总是不可满足的。如果阈值 $d_*$ 恰好为整数,我们表明该问题是可满足的,且其概率远离 0 和 1。
=== Non-Theory
@el-kadiQuantumApproximateOptimisation2024 是为数不多的非理论的工作,QAOA@farhiQuantumApproximateOptimization2014 在最大割问题中早有应用,论文中举例用的就是最大割问题,此问题在 @sec:max-cut 中介绍。
然而,@el-kadiQuantumApproximateOptimisation2024 也并未提及 k-NAE-SAT 的实际应用。
由于 QAOA 本质上是一个近似优化算法,因此没办法保证一定获得最优解,于是,衡量 QAOA 的效果是通过成功率(success ratio)的,如@fig:qaoa-success-ratio 所示:
#figure(
image("success-ratio-qaoa.png", width: 50%),
)<fig:qaoa-success-ratio>
最后,文章将 QAOA 与传统算法WalkSATlm@caiImprovingWalkSATEffective2015 与魔改 WalkSATlm 得到的 WalkSATm2b2,如@fig:walksatm2b2 所示,进行对比(在这里只对比了中位运行时间):
#figure(
image("median-running-time-qaoa.png", width: 50%),
)
使用的实例为随机生成的 $k in {3, dots, 10}$ 的 $2500$ 个 NAE-SAT 实例(保证了一定有解)。
#figure(
image("walksatm2b2.png", width: 50%),
caption: "WalkSATm2b2 算法示意",
)<fig:walksatm2b2>
= MAX NAE-SAT<sec:max-k-sat>
/ _Definition 5_: 给定一个 CNF,要求每个子句 $c_i$ 中至少有一个文字为真且至少有一个文字为假,目标是找到一组赋值 $phi$,使得满足条件的子句数量最大化
\
_MAX NAE-SAT_ 及其变种 _MAX k-NAE-SAT_#footnote[此变种问题不再给定义,可以参考@sec:k-sat 中的定义]的工作相较于前两个问题会较多。
== MAX CUT<sec:max-cut>
Max Cut,最大割问题,其定义如下:
/ _Definition 6_: 给定一个无向图 $G = (V, E)$,找到一个顶点集合的划分 $(S, overline(S))$,使得划分在连接 $S$ 与 $overline(S)$ 的边的数量最大化
\
这个问题可以认为是 _MAX k-NAE-SAT_ 的一个特例,即 _MAX 2-NAE-SAT_:其中, $V$ 为全集 $S$,$E$ 为子集簇 $cal(F)$。
对于最大割问题的近似算法,在 @odonnellOptimalSdpAlgorithm2008, @goemansImprovedApproximationAlgorithms1995 中均有介绍。
而如果我们为边设置权重,就能得到 _weighted-MAX-CUT_ 问题。
== MAX Set Splitting
对于 $k gt.eq 3$ 的情况,根据 @sec:set-splitting 中,我们也可以为子集簇$cal(F)$ 中的每个子集设置权重,这样就得到了问题 _MAX Set Splitting_,在 @zhangImprovedApproximationsMax2004, @anderssonBetterApproximationAlgorithms 中均有介绍,但工作均为求出近似比 $alpha$,
与 @sec:max-cut 中提及的文章工作类似。
== MAX k-NAE-SAT
在理论方面,@brakensiekMysteriesMAXNAESAT2024 的工作主要是确定了 $k gt.eq 3$ 中,算法的最优近似比,见 @tbl:ratios
#figure(
kind: table,
caption: "Optimal approximation ratios for MAX NAE-{k}-SAT.",
table(
align: center,
stroke: .5pt,
columns: (1fr, 1fr, 1fr),
[MAX NAE-{$k$}-SAT], [Optimal ratios], [Algorithm],
[$k = 2$], [$alpha_(G W) approx 0.8786$], [Goemans-Williamson@goemansImprovedApproximationAlgorithms1995],
[$k = 3$], [$approx 0.9089$], [@brakensiekMysteriesMAXNAESAT2024],
[$k gt.eq 4$], [$1 - 1 / (2^(k -1))$], [Random Assignment],
),
)<tbl:ratios>
// = Conclusion<sec:conclusion>
#bibliography("ref.bib") |
|
https://github.com/raygo0312/Typst_template | https://raw.githubusercontent.com/raygo0312/Typst_template/main/template.typ | typst | #import "template-document.typ": *
#import "template-slide.typ": *
#import "prooftree.typ": * |
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/GR_old/texts.typ | typst | #import "/utilsMenlive.typ": *
#let h_st = (
"Ἐξάγαγε ἐκ φυλακῆς τὴν ψυχήν μου, τοῦ ἐξομολογήσασθαι τῷ ὀνόματί σου.",
"Ἐμὲ ὑπομενοῦσι δίκαιοι, ἕως οὐ ἀνταποδῷς μοι.",
"Ἐκ βαθέων ἐκέκραξά σοι, Κύριε, Κύριε εἰσάκουσον τῆς φωνῆς μου.",
"Γενηθήτω τὰ ὦτά σου προσέχοντα εἰς τὴν φωνὴν τῆς δεήσεώς μου.",
"Ἐὰν ἀνομίας παρατηρήσῃς, Κύριε, Κύριε τίς ὑποστήσεται; ὅτι παρὰ σοὶ ὁ ἱλασμός ἐστιν.",
"Ἕνεκεν τοῦ ὀνόματός σου ὑπέμεινά σε, Κύριε, ὑπέμεινεν ἡ ψυχή μου εἰς τὸν λόγον σου, ἤλπισεν ἡ ψυχή μου ἐπὶ τὸν Κύριον.",
"Ἀπὸ φυλακῆς πρωΐας μέχρι νυκτός, ἀπὸ φυλακῆς πρωΐας ἐλπισάτω Ἰσραὴλ ἐπὶ τὸν Κύριον.",
"Ὅτι παρὰ τῷ Κυρίῳ τὸ ἔλεος, καὶ πολλὴ παρ' αὐτῷ, λύτρωσις καὶ αὐτὸς λυτρώσεται τὸν Ἰσραὴλ ἐκ πασῶν τῶν ἀνομιῶν αὐτοῦ.",
"Αἰνεῖτε τὸν Κύριον πάντα τὰ ἔθνη, ἐπαινέσατε αὐτόν, πάντες οἱ λαοί.",
"Ὅτι ἐκραταιώθη τὸ ἔλεος αὐτοῦ ἐφ' ἡμᾶς, καὶ ἡ ἀλήθεια τοῦ Κυρίου μένει εἰς τὸν αἰῶνα.",
)
#let s_st = (
"100": (
"Μνησθήσομαι τοῦ ὀνόματός σου ἐν πάσῃ γενεᾷ καὶ γενεᾷ.",
"Ἄκουσον, θύγατερ, καὶ ἴδε, καὶ κλῖνον τὸ οὖς σου, καὶ ἐπιλάθου τοῦ λαοῦ σου καὶ τοῦ οἴκου τοῦ Πατρός σου.",
"Τὸ πρόσωπόν σου λιτανεύσουσιν οἱ πλούσιοι τοῦ λαοῦ."
),
"0": (
"Ὁ Κύριος ἐβασίλευσεν, εὐπρέπειαν ἐνεδύσατο. Ἐνεδύσατο ὁ Κύριος δύναμιν καὶ περιεζώσατο.",
"Καὶ γὰρ ἐστερέωσεν τὴν οἰκουμένην, ἥτις οὐ σαλευθήσεται.",
"Τῷ οἴκῳ σου πρέπει ἁγίασμα Κύριε εἰς μακρότητα ἡμερῶν.",
),
"6": (
"Θαυμαστὸς ὁ Θεὸς ἐν τοῖς ἁγίοις αὐτοῦ, ὁ Θεὸς Ἰσραὴλ αὐτὸς δώσει δύναμιν καὶ κραταίωσιν τῷ λαῷ αὐτοῦ εὐλογητὸς ὁ Θεός.",
"Τοῖς Ἁγίοις τοῖς ἐν τῇ γῇ αὐτοῦ ἐθαυμάστωσεν ὁ Κύριος πάντα τὰ θελήματα αὐτοῦ ἐν αὐτοῖς.",
"Μακάριοι οὓς ἐξελέξω καὶ προσελάβου Κύριε.",
),
"x": (
"Πρὸς σὲ ᾖρα τοὺς ὀφθαλμούς μου, τὸν κατοικοῦντα ἐν τῷ οὐρανῷ. Ἰδού, ὡς ὀφθαλμοὶ δούλων εἰς χεῖρας τῶν κυρίων αὐτῶν, ὡς ὀφθαλμοὶ παιδίσκης εἰς χεῖρας τῆς κυρίας αὐτῆς, οὕτως οἱ ὀφθαλμοὶ ἡμῶν πρὸς Κύριον τὸν Θεὸν ἡμῶν, ἕως οὗ οἰκτειρῆσαι ἡμᾶς.",
"Ἐλέησον ἡμᾶς, Κύριε, ἐλέησον ἡμᾶς, ὅτι ἐπὶ πολὺ ἐπλήσθημεν ἐξουδενώσεως, ἐπὶ πλεῖον ἐπλήσθη ἡ ψυχὴ ἡμῶν, τὸ ὄνειδος τοῖς εὐθηνοῦσι, καὶ ἡ ἐξουδένωσις τοῖς ὑπερηφάνοις.",
)
)
#let p_st = "Presvjatája Bohoródice spasí nás."
#let n_st = "Presvjatája Tróice Bóže náš, sláva tebí."
#let typs = (
"0": (
"Κανὼν Ἀναστάσιμος",
"Κανὼν Σταυροαναστάσιμος",
"Κανὼν τῆς Θεοτόκου"
),
"1": (
"Κανὼν Κατανυκτικὸς ποίημα Ἰωσήφ",
"Κανὼν τῶν Ἀσωμάτων"
),
"2": (
"Kanón pokajánen",
"Kanón svjatómu velíkomu proróku Joánnu predtéči"
),
"3": (
"Kanón čestnómu i životvorjáščemu krestú",
"Κανὼν τῆς Θεοτόκου"
),
"4": (
"Κανὼν τῶν ἁγίων Ἀποστόλων",
"Κανὼν τοῦ Ἁγίου Νικολάου"
),
"5": (
"Kanón čéstnómu i životvorjáščemu krestú",
"Κανὼν τῆς Θεοτόκου"
),
"6": (
"Kanón svjatým múčenikom, i svjatítelem, i prepodóbnym i usópšym",
"Kanón usópšym"
)
)
#let pripivy = (
"0": (
("Sláva Hóspodi svjatómu voskreséniju tvojemú."),
("Sláva Hóspodi krestú tvojemú i voskreséniju."), //FIXME: chcek correct translation
("Presvjatája Bohoródice, spasi nás.") //FIXME: chcek correct translation
),
"6": ()
)
#let sd_st = (
"Voskresní Hóspodi Bóže mój, da voznesétsja ruká tvojá, ne zabúdi ubóhich tvojích do koncá.",
"Ispovímsja tebí Hóspodi vsím sérdcem mojím, povím vsjá čudesá tvojá.",
)
#let ch_st = ( // TODO: wrong order H2/6
"Τοῦ ποιῆσαι ἐν αὐτοῖς κρῖμα ἔγγραπτον. Δόξα αὕτη ἔσται πᾶσι τοῖς ὁσίοις αὐτοῦ.",
"Αἰνεῖτε τὸν Θεὸν ἐν τοῖς Ἁγίοις αὐτοῦ, αἰνεῖτε αὐτὸν ἐν στερεώματι τῆς δυνάμεως αὐτοῦ.",
"Αἰνεῖτε αὐτὸν ἐπὶ ταῖς δυναστείαις αὐτοῦ, αἰνεῖτε αὐτὸν κατὰ τὸ πλῆθος τῆς μεγαλωσύνης αὐτοῦ.",
"Αἰνεῖτε αὐτὸν ἐν ἤχῳ, σάλπιγγος, αἰνεῖτε αὐτὸν ἐν ψαλτηρίῳ καὶ κιθάρᾳ.",
"Αἰνεῖτε αὐτὸν ἐν τυμπάνῳ καὶ χορῷ, αἰνεῖτε αὐτὸν ἐν χορδαῖς καὶ ὀργάνῳ,",
"Αἰνεῖτε αὐτὸν ἐν κυμβάλοις εὐήχοις, αἰνεῖτε αὐτὸν ἐν κυμβάλοις ἀλαλαγμοῦ. Πᾶσα πνοὴ αἰνεσάτω τὸν Κύριον.",
"Ἀνάστηθι, Κύριε, ὁ Θεός μου, ὑψωθήτω ἡ χείρ σου, μὴ ἐπιλάθῃ τῶν πενήτων σου εἰς τέλος.",
"Ἐξομολογήσομαί σοι, Κύριε, ἐν ὅλῃ καρδίᾳ μου, διηγήσομαι πάντα τὰ θαυμάσιά σου.",
)
#let su_st = (
"x": (
"Ἐνεπλήσθημεν τὸ πρωῒ τοῦ ἐλέους σου, Κύριε, καὶ ἠγαλλιασάμεθα καὶ ηὐφράνθημεν ἐν πάσαις ταῖς ἡμέραις ἡμῶν. Εὐφρανθείημεν, ἀνθ΄ὧν ἡμερῶν ἐταπείνωσας ἡμᾶς, ἐτῶν, ὧν εἴδομεν κακά, καὶ ἴδε ἐπὶ τοὺς δούλους σου καὶ ἐπὶ τὰ ἔργα σου, καὶ ὁδήγησον τοὺς υἱοὺς αὐτῶν.",
"Καὶ ἔστω ἡ λαμπρότης Κυρίου τοῦ Θεοῦ ἡμῶν ἐφ' ἡμᾶς, καὶ τὰ ἔργα τῶν χειρῶν ἡμῶν κατεύθυνον ἐφ' ἡμᾶς, καὶ τὸ ἔργον τῶν χειρῶν ἡμῶν κατεύθυνον.",
),
"6": (
"Μακάριοι οὓς ἐξελέξω καὶ προσελάβου Κύριε.",
"Αἱ ψυχαὶ αὐτῶν ἐν ἀγαθοῖς αὐλισθήσονται.",
"Καὶ τὸ μνημόσυνον αὐτῶν εἰς γενεὰν καὶ γενεάν.",
)
)
#let b_st = (
"Blažéni níščiji Dúchom, jáko ťích jésť cárstvo nebésnoje.",
"Blažéni pláčuščiji, jáko tíji uťíšatsja.",
"Blažéni krótcyji, jáko tíji nasľíďat zémľu.",
"Blaženi alčuščiji i žažduščiji pravdy, jako tiji nasyťatsja.",
"Μακάριοι οἱ ἐλεήμονες, ὅτι αὐτοὶ ἐλεηθήσονται.",
"Μακάριοι οἱ καθαροὶ τῇ καρδίᾳ ὅτι αὐτοὶ τὸν Θεὸν ὄψονται.",
"Μακάριοι οἱ εἰρηνοποιοί, ὅτι αὐτοὶ υἱοὶ Θεοῦ κληθήσονται.",
"Μακάριοι οἱ δεδιωγμένοι ἕνεκεν δικαιοσύνης, ὅτι αὐτῶν ἐστιν ἡ βασιλεία τῶν οὐρανῶν.",
"Μακάριοί ἐστε ὅταν ὀνειδίσωσιν ὑμᾶς, καὶ διώξωσι, καὶ εἴπωσι πᾶν πονηρὸν ῥῆμα καθ΄ὑμῶν ψευδόμενοι ἕνεκεν ἐμοῦ.",
"Χαίρετε καὶ ἀγαλλιᾶσθε, ὅτι ὁ μισθὸς ὑμῶν πολὺς ἐν τοῖς οὐρανοῖς.",
)
#let translation = (
"HLAS": "Ἦχος",
"Ne": "Κυριακή",
"Po": "Δευτέρα",
"Ut": "Τρίτη",
"Sr": "Τετάρτη",
"St": "Πέμπτη",
"Pi": "Παρασκευή",
"So": "Σάββατον",
"M": "Μικρός Εσπερινός",
"V": "Εσπερινός",
"P": "Απόδειπνο",
"N": "Μεσονύκτιον",
"U": "Όρθρος",
"L": "Λειτουργία",
"I": "Τυπικά",
"So_V": "τῳ σαββατῳ εσπερασ",
"So_N": "v subbótu nóšči",
"Ne_V": "v neďíľu véčera",
"Ne_N": "v neďíľu nóšči",
"Po_V": "v poneďíľnik véčera",
"Po_N": "v poneďíľnik nóšči",
"Ut_V": "vo vtórnik véčera",
"Ut_N": "vo vtórnik nóšči",
"Sr_V": "v srédu véčera",
"Sr_N": "v srédu nóšči",
"St_V": "v četvertók véčera",
"St_N": "v četvertók nóšči",
"Pi_V": "v pjatók véčera",
"Pi_N": "v pjatók nóšči",
"HOSPODI_VOZVACH": "Στιχηρὰ Ἀναστάσιμα",
"STICHOVNI": "Ἀπόστιχα",
"TROPAR": "Ἀπολυτίκιον",
"PIESEN": "ᾨδὴ",
"SIDALEN": "Κάθισμα",
"SIDALENY": "Καθίσματα Ἀναστάσιμα",
"SIDALEN_PO": "Μετὰ τὴν Στιχολογίαν",
"YPAKOJ": "Ἡ Ὑπακοὴ",
"STEPENNY": "Οἱ Ἀναβαθμοὶ",
"ANTIFON": "Ἀντίφωνον",
"PROKIMEN": "Προκείμενον",
"STICH": "Στίχ",
"ALLILUJA": "Allilúia",
"KANON": "Κανὼν",
"KONDAK_IKOS": "Κοντάκιον Ὁ Οἶκος",
"CHVALITE": "Στιχηρὰ Ἀναστάσιμα",
"BLAZENNA": "Οἱ Μακαρισμοὶ",
"TROPAR_KONDAK": "Ἀπολυτίκιον, Κοντάκιον",
"50_STICHIRA": "Стїхи́ра по н҃-мъ ѱалмѣ̀",
"SVITILEN": "Свѣти́ленъ",
"HV_MINEA": "Та́же стїхи̑ры 3 и҆з̾ мине́и и҆лѝ и҆з̾ мине́и ѻ҆́бщей.",
"HV_NOTE": "Сла́ва: и҆з̾ мине́и, И҆ ны́нѣ: бг҃оро́диченъ, а҆́ще не бꙋ́детъ Сла́ва: И҆ ны́нѣ: бг҃оро́диченъ",
"HV_N_NOTE": "Бг҃оро́диченъ во ᲂу҆ста́вѣ",
"T_NOTE": "Сла́ва: мине́и; И҆ ны́нѣ: бг҃оро́диченъ воскрⷭ҇ный"
) |
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/012%20-%20Conspiracy/001_Betrayal.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Betrayal",
set_name: "Conspiracy",
story_date: datetime(day: 14, month: 05, year: 2014),
author: "<NAME>",
doc
)
#emph[Far from Theros, on the plane of Fiora, the High City of Paliano is home to countless intrigues and plots. The high lords of the city vie for supremacy. Move is met with countermove, and trust with betrayal, all under the auspices of the immortal King Eternal. But the king was a living man, once, and a friend to the elf explorer Selvala...]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("001_Betrayal/01.jpg", height: 40%), caption: [], supplement: none, numbering: none)
The walls of the king's private dining chamber were lit with enchanted gems, each carefully placed atop a carved marble rod—a carefully crafted simulacrum of a candle, but without any trace of warmth. The chamber was in the heart of the castle complex, and no natural light reached this far.
The table was large enough to seat twelve, but only two dined this night. The king, Brago, skin pale and cracked, like old parchment paper, rested in an ornate chair. His guest, Selvala, sat at the opposite end, a feast spread out between them. The king's plate was empty. The elf's plate was untouched.
"Why do we still do this, my king?" There was a hardness to the last word, like tension in a copper wire. "Why do we go through these motions anymore? I know it pains you to see me, and it pains me to see what you have become."
The king's eyes flickered, but his body was still for a long moment until a raspy voice escaped his cracked lips.
"Because you help me remember."
Selvala shook her head. "That's not enough, anymore. Maybe it used to be. Before all... this... got so far out of hand." She waved a hand in his direction, disgust plain on her face. "Whether you remember him or not, you are not the king you once were. I remember that man. That man was my friend. And seeing you, sitting in his chair, wearing what's left of his face, is an insult to that man. An insult to the things we stood for."
Brago's body convulsed, and he let loose a choking gasp. Selvala recognized it as his laughter. "Maybe... I should have listened to you. Maybe you should have made me listen."
Selvala's face flushed with anger. "Oh no. You don't get to put this on me. I warned you. In the very beginning, I begged you not to let the Custodi begin their treatments."
"But you relented. We still had so much work to do. For the city."
Selvala narrowed her eyes. The king had already said more in this exchange than he had in their last two dinners combined.
"What's going on, old friend? What has changed?" Her voice softened.
"In the beginning, you and I shared a vision."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The City was young. Young, optimistic, and ambitious, and Count Brago was all of these things as well. Born third son to a minor house, his prospects would have been limited anywhere else. But not here. Not in the City. In the City, a person's dreams and ambitions were the only source of limitation, and Brago could see far, indeed. He could see past the petty grudges and bureaucrats. He could see past the flitting fashions, the endless squabbles for glory and fame. He saw the raw potential of what the City could be. He saw its beating heart, and it thrummed in perfect synchronicity with his own. And he could see a path to that potential. Slim, perhaps. Winding. Treacherous. And he could not walk it alone.
#figure(image("001_Betrayal/02.jpg", width: 100%), caption: [Selvala, Explorer Returned | Art by <NAME>], supplement: none, numbering: none)
#linebreak
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"Ha! You speak to me of a vision? That was seventy years ago, you old fool. Yes. Yes, when I was as much a fool as you have become, I believed in you. Your words dripped with honey and light and I believed. Which makes your betrayal all the more bitter, old friend."
"Betrayal?" Brago's voice rose, almost taking on a human tone once more. "I never. I never lost sight of what was best for the City. Even now."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The two were inseparable, and they worked together flawlessly. He was a terror in the courts and council chambers, his arguments flawless, his entreatments irresistible. He built up a coalition of nobility, clergy, and the merchant class. He rooted out corruption and replaced it with humility. But always, always, more power ended up in his hands.
She was beloved by the people, had her fingers on the pulse of every community and enclave. She fought for the rights of immigrants, and convinced many of the old titled nobility to give up privileges that oppressed the public, before the public rose up to depose them. Together, they drafted the Charter. Ratification was unanimous. It was their hands, clasped together, that forged Paliano.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"You lost sight of everything once you started to value your own life above those you served. How long did you let yourself believe that what the Custodi were doing was medicine?"
"It was. I wasn't going to let my health stop us from achieving our goals."
"Everyone dies, Brago! Everyone ages, everyone dies. Peasants and kings alike."
Brago laughed, a real laugh this time. "That must be easy for you to say, looking just a few years older now than when we met. You can't say what you would have done in my place."
Selvala looked down, and paused. "Perhaps not."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
King Brago had been on the throne just three years when the doctors diagnosed his illness. Hereditary and incurable. He would not last the year. Selvala was devastated. Brago was in shock. When the priests came to him and told him there were treatments he could undergo that would magically preserve his body, he was cautious.
He and Selvala discussed and debated the matter extensively. Neither liked the idea of putting his life in the hands of the priesthood, but each feared what would happen should the new king die so soon. The alliances they had struggled to build could crumble in a heartbeat. The shining city could return itself to glittering ashes so quickly. In the end, they relented. The Custodi were formed, and the king lived. And he lived. And he lived.
#figure(image("001_Betrayal/03.jpg", width: 100%), caption: [Art by <NAME>-Orlandelli], supplement: none, numbering: none)
#linebreak
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"History will judge me fairly. All that we have achieved. All the good we have done. It was the only way."
"Brago, if I heard those words from any other man's lips, I would know him to be a tyrant."
Brago seemed to deflate again. "Selvala. There will be no more treatments."
Shock, joy, and fear flashed across Selvala's face. She stood, walked to his side, and knelt next to his chair. She took his dry hand in hers. It was neither warm nor cold, and felt to the touch like nothing so much as an old leather-bound book. "Brago. This is the right choice. By all we held dear, I will miss you, but this is the right thing."
Brago coughed, a rattling, wheezing sound. "No. It is not like that. There will be no more treatments, because they have gone too far. I cannot die, Selvala. My mind will rot in this cage of bones and skin. It has already begun. My eyes have all but gone already. I cannot eat, I cannot sleep. I no longer hurt, but for a long time, I hurt very badly. Now, I miss even the pain."
Selvala sprung to her feet, furious, her hand reflexively grasping the hilt of her long hunter's knife. "Those monsters! What have they done to you? For what they've done, I should..."
Brago lifted a limp hand. "No. No. Turn your anger toward me. Where it can yet serve you. Selvala. I cannot die naturally. But I think I must die. And you are one of only three people in the City who is permitted a weapon in my presence."
Selvala closed her eyes. As soon as he had said the words, she knew that she would do this for him. "Brago. You were a good king. A good man." She stood, stared him in the milky blue eyes, and drew her knife. "I forgive you."
She thrust the blade once into the king's heart. There was almost no resistance, like stabbing a knife into a sack of dry grain. His ancient body began to crumble almost immediately, and as he fell to dust, he whispered two words:
"You won't."
Selvala strode out of the dining room, and cast her knife on the floor. The guards escorted her away without a word.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The Custodi shuffled into the cold throne room, hands concealed in their long sleeves for warmth as much as propriety. Gray faces, hard-eyed men and women, peered out from under embroidered hoods. They formed a circle, and the eldest spoke. "The King is dead. We will keep the news contained as long as we can, but the knowledge will escape these walls. Before it does, if we wish to remain in power, we have much work to do."
The temperature in the room dropped suddenly, and the lights flickered. A presence entered the room. Cold, and angry.
A blue mist began to coalesce, wisps creeping out of the patterns in the smooth marble floor. A few of the Custodi gasped and staggered backwards. The mist grew thicker, denser, and it flowed like a river in an unseen bed.
The Custodi were startled; they looked from hooded face to hooded face for any sign that one of them might understand. Finding no solace, the priests looked around the room, increasingly frantic.
A shimmer appeared before the throne. The mist drew itself up and formed the shape of a man, and the idea of armor became solid around him. Eyes stared down at the Custodi, dark yet aglow, and the priests cowered before him in fear.
#figure(image("001_Betrayal/04.jpg", width: 100%), caption: [Brago, King Eternal | Art by <NAME>], supplement: none, numbering: none)
"You will do no such thing. You will announce what has happened. That the great work of the Custodi is complete. That your king has risen, mind as strong as ever, freed from the prison of his body. This is a day of celebration." The spirit's voice was deep and stern. "For you have succeeded. Unless you wish to tell me that your treatments had another goal in mind?"
Panic flew across the faces of the Custodi. They stammered their confusion, until the eldest stepped to the front of the huddled crowd.
"Of course, my king. Let none doubt your words." She looked over her shoulder to the others, who each bent their knee.
"Hail, my king."
"Hail, King Brago."
"All hail Brago, King Eternal."
#figure(image("001_Betrayal/05.jpg", height: 40%), caption: [], supplement: none, numbering: none)
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/037%20-%20Ravnica%20Allegiance/012_The%20Gathering%20Storm%3A%20Chapter%2018.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Gathering Storm: Chapter 18",
set_name: "Ravnica Allegiance",
story_date: datetime(day: 09, month: 10, year: 2019),
author: "<NAME>",
doc
)
"The failure is mine," Niv-Mizzet said, his bass rumble resonating in Ral’s bones. "Once again, I have underestimated Nicol Bolas."
"I should have known," Ral said. "I never liked that blue-skinned snake."
They stood in the Aerie, looking out through the great circular window over the darkened streets of Ravnica. Black clouds hung overhead, blotting out the moon and the stars, but as yet no rain fell. Flickers of energy from the great machine still rose fitfully into the sky, at longer and longer intervals, like the beats of a steadily weakening heart.
"You have performed your assigned tasks," the Firemind said, shifting his vast bulk closer to the window. "When the guild summit failed, you surpassed even my expectations. You have done everything I could have asked of you, Ral."
Ral’s skin prickled with unease. Praise like this—of any kind, really—was unlike Niv-Mizzet. He cleared his throat and ran a crackling hand through his hair.
"I didn’t consider that Vraska’s betrayal might have had a dual purpose," the dragon went on. "It broke up the summit, and at the same time moved Dovin into a position of authority over the Azorius."
"We’ll settle with him later," Ral said. "For now there’s no time. I’ve sent runners to Kaya and Aurelia. We’ll gather a force and storm the Azorius node. If they haven’t done too much damage to it, we should be able to get it back online, and my people are already working on repairs here. A little time—"
"We are out of time, Ral," Niv-Mizzet said. His voice was almost gentle. "Look."
He extended one massive paw, tapping against the glass with a single claw. The window flexed and groaned in its mounting. Ral squinted, stepping forward and shading his eyes against the hovering lanterns in the Aerie.
There was a line of orange light, right at the horizon. It looked enormous, towering over the surrounding buildings, shading their spires with a hellish glow. As Ral watched, the line widened a fraction, a crack in the world levering itself open in the grip of incomprehensible energies.
"What in the name of . . ." Ral looked at the Firemind, who focused one enormous eye on him.
"Bolas comes," Niv-Mizzet said simply.
"How?" Ral said. "I’ve seen planeswalkers arrive. It doesn’t look like . . . that."
"I don’t know what magics he has harnessed," Niv-Mizzet said. "But he is not coming alone. A legion of monsters marches behind him."
#emph[Bolas wouldn’t attack Ravnica if he didn’t think he could win.] Ral had said that blithely, in the lead-up to the guild summit, trying to convince the others to take the threat seriously. Now, for the first time, he truly understood what it meant. Against everything Ravnica could muster—the soldiers of the Boros, the inventions of the Izzet, the druids of Selesnya and the mages of Simic, the demons of Rakdos, the knights of Orzhov, the arbiters of Azorius and the spies of Dimir—Bolas was bringing an army he could pit against #emph[all] of that. #emph[And he expects to win.]
He shivered, and grit his teeth for a moment.
"So what do we do?" he said. "If we don’t have time to fix the machine."
"The beacon," Niv-Mizzet said. "It is the only way."
"Just . . . send out a call? And hope the Planeswalkers of the Multiverse come and save us?" Ral shook his head. "It sounds like a pretty thin hope."
"Thin hopes are all that Ravnica has left, <NAME>." The dragon’s huge head swung around to face him. "I am entrusting the last of ours to you. Can you do it?"
"Of course I can," Ral said, drawing himself up. "Getting there may be a little bit tricky. We built the beacon in Azorius territory because we thought it would be safe, and I’m sure Dovin will have half their army guarding it by now. But the safety systems won’t let them damage the thing itself, I’m certain of that. If I can get to the top of that tower, I can turn it on."
"Good." Niv-Mizzet turned away. "I suggest you hurry. The beacon may be protected from tampering, but Bolas could still destroy it. I will prevent that for as long as I can."
"You—what?" Ral said. He’d already been thinking about the best way to reach the beacon, but Niv-Mizzet’s words snapped him back to the present. "What do you mean?"
"I mean I will delay Bolas to the best of my ability." The Firemind gestured, and the big window swung open on noiseless hinges. The wind around Nivix’s spire moaned and howled.
"But . . ." Ral shook his head. "The machine. I thought the whole point was that you wouldn’t be able to stand up to him unless we . . ."
He trailed off as Niv-Mizzet turned back to look at him, one last time. Ral swallowed hard, meeting those huge, ancient eyes. The frills around the dragon’s head flared.
"Good luck," Ral said quietly.
"You must succeed," Niv-Mizzet said. "No matter the cost. Or else all of this is for nothing."
The #emph[parun] of the Izzet League, Niv-Mizzet the Firemind, launched himself from the great window of his Aerie. His wings snapped out, catching the night air with a mighty #emph[whump] , and he soared upward. In the distance, the line of orange light had spread even side, and Ral could see the outline of a shape beyond it. An enormous head, with two long, curving horns.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The Undercity shook. Vraska sat on her throne and watched the dust drift down from the ceiling, tiny falls sparking in the light of the bioluminescent lamps every time the ground shook.
#emph[It’s time, then.]
"Storrev," she said aloud.
The Erstwhile lich, standing beside the throne, inclined her head.
"I’m going to the surface. You have my instructions."
"Yes, my queen."
Vraska gripped the hilt of her saber, fingers tightening, and got to her feet.
"May I say . . ." the lich began.
Vraska looked at her, surprised. "Yes?
Storrev cocked her head, considering. "Good luck."
"Thanks." Vraska shook her head, tendrils writhing. #emph[I’m going to need it. We’re ] all#emph[ going to need it.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#linebreak Niv-Mizzet soared free through the skies above the Tenth District.
It was a pleasure he’d indulged in less and less as the centuries had blown past. He had always lived mainly in his own mind, and in any event his excursions had a tendency to cause a commotion. Most days he was content to abide in the Aerie, barely aware of his surroundings as he contemplated matters far beyond the ken of any mortal.
Tonight, though, he felt the creak of his wings, the lash of his tail, the rush of wind through his frills, and remembered how such things, too, could be enjoyable. An odd time for such a reminder, on the balance, but it was welcome nonetheless. His lungs heaved, like tremendous bellows, and he smelled the night air, gritty with soot and metallic with the aftermath of Ral’s machine.
Ahead of him, the great portal split the night, widening steadily. Niv-Mizzet flapped his wings, gaining height as he closed. By the time he was within a few blocks of the thing, he was well above the tops of the highest spire, the spines of his back nearly brushing the low, dark clouds.
One clawed foot came through, orange light sliding off it reluctantly, like colored water draining away. Cobblestones cracked and splintered as it came down. With a vast crackle like tearing fabric, <NAME> stepped through the boundary between worlds, standing outlined against the Ravnican night by glow of his portal.
He was misshapen, to Niv-Mizzet’s mind. Standing on two legs, with his face flattened and broad, human-like mouth and features. There was entirely too much of the human about Bolas for the Firemind’s taste. Humans were all well and good, Niv-Mizzet thought, but he wouldn’t want to #emph[be] one.
Bolas’s horns curved upward, framing a hovering orb between them. His huge eyes glowed, the same lurid orange as the portal itself. He steadied himself on a nearby building, a forepaw more like a human hand gripping the stone and tearing deep furrows in it with its long claws. For a moment he looked around slowly, and then he focused on Niv, high above him.
"Ah," he said. His tone was urbane, cultured, with the vast draconic rumble concealed expertly underneath. "As I thought—"
Niv-Mizzet had never placed particular importance on politeness, or chivalry. What he #emph[did] enjoy was efficiency. And in a fight, efficiency meant winning as quickly as possible.
His mind reached out, finding auras across the city, spells that he himself had carefully prepared for this moment. They tripped mizzium batteries, vast constructions of crystal and metal concealed in unassuming buildings all across the Tenth District. Each of them, carefully charged for weeks now, let loose its accumulated energy in a fraction of a second, sending a titanic bolt of power into the sky.
A dozen enormous energy blasts converged on Niv-Mizzet from all points of the compass. Space around him contorted, bending into a lens that smeared the light of the city into a glittering kaleidoscope. Another lens formed in front of it, then another, each disc crackling at the edges with the dragon’s unleashed power. When the bolts from the generators struck the lenses, they #emph[twisted] , narrowed, refined themselves like metal in the heat of a forge. Focused down, then focused again and again, until all twelve were coiled into a beam narrower than the palm of a human child, a finger of light so mind-numbingly bright that nictitating membranes reflexively slid over the dragon’s eyes.
It scythed down, accompanied by what was possibly the loudest thunderclap Ravnica had ever experienced. Windows shattered for blocks around, showering the street with glass. When it struck Bolas in the chest, the ancient dragon was punched off his feet, staggering into the building beside him and bringing it down in a collapsing shower of stone and roofing tiles. A moment later, the explosion of boiling rock and superheated air engulfed him, slamming outward with hurricane force. Carriages tipped over and slid sideways along the cobbles, trees snapped into splinters, and iron lampposts bent double. A wave of heat, rising from the blast, carried the dust upward, brushing aside the dark thunderheads and briefly revealing the stars.
Niv-Mizzet hung in the air, watching bits of burning debris arc out from ground zero and land across the city, like flaming missiles curled from catapults. The smoke and dust was so thick that there was no sign of Bolas, or even of his enormous portal.
All in all, he thought, he had to account it a successful experiment.
Buildings were still crumbling, adding to the circle of rubble, and others were on fire. The Firemind could hear screams and cries rising from the streets, but they made no impression on his mind. The humans of Ravnica were his responsibility, but only in aggregate. Individually, they did not concern him, unless they caught his particular attention. It was difficult to care much about anything so short-lived.
The real question was what to do next. It was hard to believe that the threat could be ended so easily—
A huge, clawed hand shot out of the murk, grabbing a half-wrecked building. Slowly, <NAME> pulled himself to his feet, emerging from the settling dust. He shook himself, then spread his wings, blowing the smoke and grit away from him. The scales on his chest were bubbled and blackened, but he still smiled, showing a mouth full of long fangs.
"Niv-Mizzet," he said. "The vaunted Firemind. I always knew that you were the only one on this benighted world who would give me a proper fight."
"I am glad," Niv-Mizzet said, "not to disappoint."
"I don’t suppose there’s any point in asking you to submit."
"Go back through that portal and close it behind you," Niv-Mizzet rumbled, "and I may let you live."
"Very good," Bolas said, with a chuckle. "And so we begin."
Magic blossomed around the pair of them, crackling auras of chaotic energy. A hundred spells, each of which would have taken the complete attention of a mortal mage, dropped into being in front of Niv-Mizzet, requiring only the briefest flicker of his mind. Balls of flame screamed down, detonating on the rubble around Bolas with deafening explosions and showers of shattered stone. Bolts of lightning crackled across Niv-Mizzet’s claws, flashing through the space between them and running in waves across Bolas’s scales. Rays of pure destruction lanced out, turning everything they touched to dust.
Bolas’s own magic spun a protective web, and the air around him was full of reflected lightning and ricocheting fireballs. A beam cut across a tottering building, and a chunk of stone puffed into non-existence, bringing the upper stories crashing down into the street in a torrent of rubble and screams. In answer to the elemental barrage, Bolas lashed out with the very essence of death, dark threads that reached into the sky and invisible phantoms that shrieked as they circled and dove. Niv-Mizzet brushed them away in turn, and where they landed on the streets, fleeing people fell in windrows—simply collapsing like broken puppets, or aging decades in a few seconds before crumbling into dust.
For long moments they lashed one another, spell meeting counterspell in a wild melee, a haze of dust and wild magic rising around both, lit from within by flashes like constant lightning. It was part chess match, part tavern brawl. The air between them was thick with magic, crackling and throbbing.
All at once, Niv-Mizzet was descending, diving through the front of the cloud around him, claws extended and jaw opened wide, his wings folded as he gained speed. Lightning crackled around him, and death magic slid over his scales. Bolas saw him coming and raised his hands, but Niv-Mizzet twisted with the flick of a wing, grabbing Bolas’s upper arm with both foreclaws. A mighty wingbeat lifted both dragons from the ground, and Niv-Mizzet twisted, sending Bolas tumbling through the air. He crashed to the ground, rolling along a boulevard, ripping up cobblestones as his talons dug in and shattering a fountain in a spray of marble fragments.
"Now you #emph[do] disappoint me," Bolas said, rising to his feet again. "Are we to grapple like beasts, then?"
"True strength," Niv-Mizzet growled, "comes from being true to one’s nature."
Bolas snorted, and spread a clawed hand. Vast coils of death magic unrolled, reaching for Niv-Mizzet, who dove again to avoid them. He spread his jaws wide, and unleashed a stream of fire, dragging it across Bolas and making the ancient dragon raise an arm to shield his face from the flames. Behind him, roofs exploded, and a towering spire became a spurting chimney of fire. Before Bolas could recover, Niv-Mizzet was on him again, claws reaching for the damaged scales on Bolas’s chest. Bolas sidestepped, raking Niv’s flank with one claw, then staggered as Niv’s head snapped out and buried sword-sized teeth in his wrist.
"#emph[Enough] ," Bolas growled, pressing his other palm flat against Niv-Mizzet’s skull. Bolas’s orange eyes went jet-black, and the power of his mind surged through the link between them.
It would have been enough to burn a mortal’s mind to ash in moments, but Niv-Mizzet was no mortal. He was the Firemind, fifteen thousand years old, and in that time he had learned a thing or two. Bolas’s mental assault, a black tide of violence and oblivion, slammed against the mental barriers Niv-Mizzet had erected. For a moment his defenses strained against the waves, but when Bolas’s power ebbed Niv’s wards were still intact. Bolas recoiled, like a man bouncing off a door he expected to be open, and Niv-Mizzet used the opportunity to surge out of his grip, raking Bolas’s chest with his rear claws as he scrambled back into the air.
"Still disappointed?" Niv-Mizzet said. His great chest was heaving, and blood dripped along his scales in a dozen places where Bolas’s spells had scored. His great frill had been shredded on one side by the black dragon’s claws.
"You have . . . a little strength," Bolas said, straightening up and flaring his wings. Black blood was flowing freely down his chest, where Niv-Mizzet’s claws had torn deep into his flesh. "But not enough."
"And yet #emph[you] have come to #emph[my] world." Niv-Mizzet reared up in the air, wings thrashing. "Why? Simple lust to conquer? What appeal can these mortals possibly hold for you?"
Bolas’s lip turned up at one corner. "You could not possibly understand."
"I fancy I understand a great deal."
"Not this." The glow in Bolas’s eyes darkened to crimson. "You say ‘mortals,’ as though you were not among them. But when I was born, I was as far above you as you are above the least creature that cowers in its own refuse. Planeswalkers did not simply flit from Plane to Plane like #emph[travelers] . We #emph[owned] the worlds and everything in them, the creatures and the cities and the land itself. The pathetic creatures that name themselves gods were as nothing beside us. Can you imagine what it is to have embodied such glory? And then to be dragged down into the #emph[mud] ?"
This last was a roar, echoing off the streets and buildings. Niv-Mizzet perched on top of a convenient spire and cocked his head, considering.
"Yes," he said, "I suppose that would make me quite angry."
"Angry." Bolas sneered. "I am going to kill you, little dragonling. And then I am going to put things right, back to the way they #emph[ought] to be. Your Plane, and everyone in it, will be mine to command."
"Will we, now?" Niv-Mizzet spread his wings and leapt into the air again, conjuring a rain of burning stones that fell hard and fast around Bolas. The elder dragon whipped his wings, deflecting the missiles, and they crashed into streets and buildings, blasting out craters in a block that was already mostly rubble.
Bolas struck back, launching miasmas of decay and twisting lines of void energy, and for another few moments the two dragons were locked in thaumaturgical combat. But the test of the strength confirmed the unpleasant truth of what Niv-Mizzet had sensed earlier. In any such contest, over the long term, he was going to lose.
It was not an easy thing to admit. For fifteen thousand years, he had been confident that no creature on Ravnica could challenge him if he exerted himself. Not even Rakdos himself, Niv had always believed, would be up to if push #emph[truly] came to shove, although of course it would be terribly inelegant to allow any such thing to every really come to pass. And, logically, he’d known that Bolas’s power must be considerable, since Bolas was obviously aware of Niv-Mizzet’s presence and had chosen to go through with his invasion anyway.
But it was one thing to arrive at such a conclusion, and quite another to feel it in your bones. Deep down, Niv realized, he had always believed that Bolas had made an error, that when they came head to head the elder dragon would find himself overmatched. The realization that Bolas had the power to back up his words was profoundly unsettling.
Perhaps, Niv concluded, he had been a bit lazy for the past few thousand years, letting mortals run his errands for him. Unfortunately, there wasn’t much to be done about it now.
What advantages could he claim for himself? Preparation, but his initial attack had spent that and Bolas was still standing. Allies were useless. Knowledge, then. They were fighting on Niv’s plane, his home. That ought to be worth something.
Folding his wings in tight, he dove, claws extended.
Bolas sidestepped, mouth gaping wide to blow a line of black-tinged fire that Niv-Mizzet rolled to avoid. Niv felt death magic licking at him, but his back claws again raked Bolas’s chest, and the elder dragon bellowed with rage. Niv-Mizzet pulled out of his dive, darting up and over a row of surviving buildings, and Bolas followed, huge wings pulling him slowly into the air. His flight was inelegant—bipeds weren’t suited for wings, Niv-Mizzet thought with a sniff—and his taloned feet brushed against the roofs below him, scraping tiles away in a shower of broken clay.
"Surely you don’t think to #emph[flee] ," Bolas shouted, sending wave after wave of magic after Niv-Mizzet as they raced out of the Tenth District.
"Of course not."
Niv wheeled around in the air, faster than Bolas could ever have managed, and dove again at his opponent. This time Bolas did not step aside, but met Niv’s forepaws with his own hands. Niv’s momentum drove them down and into a row of elegant townhouses, brick and stone shattering like glass around them.
They were locked together, hand in hand. Bolas opened his mouth wide and blasted a stream of flame, and Niv-Mizzet countered with his own, the two gushing curtains of fire meeting between them in a spectacular explosion. The wave of heat washed over both of them, scorching Niv’s fins. He shifted his weight, letting one arm drop, then folded himself over and kicked Bolas with his hind legs, sending the elder dragon into the air. Bolas’s wings shot out to steady him as Niv-Mizzet got airborne again.
"You’re not going to win," Bolas said. "You know that."
"Maybe not," Niv-Mizzet said, half to himself. "But I’m going to try."
He dove again. Once again, Bolas squared up to receive him, and the momentum of the plummeting dragon drove them both downward. This time, though, Niv-Mizzet let go early, pulling away. Bolas spread his legs, waiting to hit the ground in a crouch and spring back up—
—but there was no ground.
They had come to the edge of one of the Simic guilds’ zonots, an enormous hole in the urban surface of Ravnica, descending all the way through the Undercity to the seas that lay deep underground. The edges of the gigantic shaft were encrusted with buildings, cranes, and stairways, clinging to it like barnacles, but the center was a long, empty drop. Bolas fell and kept falling, startled. His wings came up, but he wasn’t a strong flier, and there wasn’t room for him to beat hard and gain much momentum.
Niv-Mizzet, in any case, didn’t give Bolas time to right himself. A lance of liquid fire leapt from his throat, directed not down at Bolas but across the zonot, at the rocks and stone that made up the lip. The fabric of the city, walls and buildings and basements, exploded into fragments. Niv aimed carefully, just below the edge, undercutting a huge shelf of stone and buildings as his white-hot breath tore deeper into the substructure. After a few seconds, it lurched, then began to slide, breaking away from the ground and slipping down through the smashed, molten rock into the shaft of the zonot. A huge chunk of stone and masonry, bigger than a city block, came free, breaking into smaller pieces as it tumbled. Wood and stone, brick and iron, people and carriages, thousands of tons of the fabric of Ravnica descended into the depths, cascading down on <NAME>’s head.
Niv-Mizzet paused as a massive wave of dust came billowing back up the zonot, huge eyes blinking. The air was full of screams, wails, and crackling fire, but he ignored them, listening for the sound of shifting stone below. To have killed Bolas was unthinkable, but even an ancient dragon might be inconvenienced for quite some time if you buried him under a thousand tons of rock. Perhaps—
Black lightning speared up out of the pit, crackling into the clouds overhead. One stroke, then another. More dark energy reached the edges of the zonot, crawling along it in titanic arcs. Niv-Mizzet felt the death magic’s tug; in the buildings lining the pit, the terrified inhabitants fell silently into piles of dust.
A sphere of darkness rose, slowly, through the billowing clouds. Chunks of rock still fell from the broken edge of the zonot, but where they contacted the void, they simply dissolved, utterly obliterated. Niv-Mizzet backed away, perching on a building, as the black orb reached street level and kept rising. When it was nearly to the lower edge of the clouds, it halted, then blew apart in a shower of black sparks that fell all across the city, dissolving whatever they touched into absolute nothingness.
Bolas hung where the sphere had been, huge wings flapping slowly, black blood still dripping from the slash on his chest. He stared down at Niv-Mizzet, his glowing eyes burning with rage.
Niv looked back up at him. He felt something strange, an emotion unfamiliar to him. Long moments passed as he considered it.
Fear, he decided. So this was what fear was like.
It was, Niv-Mizzet thought, unworthy of the Firemind. So he pushed it aside, roared his defiance, and leapt skyward, even as tendrils of death and destruction unfolded from Bolas’s outstretched hands.
|
|
https://github.com/OCamlPro/ppaqse-lang | https://raw.githubusercontent.com/OCamlPro/ppaqse-lang/master/src/étude/Rust.typ | typst | #import "defs.typ": *
#import "links.typ": *
#language(
name:"Rust",
introduction: [
#Rust est un langage de programmation créé par <NAME> en 2006,
soutenu par la fondation Mozilla à partir de 2009, et dont la première
version stable fût publiée en 2015. Le projet est devenu indépendant de
Mozilla et est soutenu par sa propre entité légale: la fondation #Rust.
Conçu
comme un successeur aux langages C et C++, #Rust cherche à concillier
sûreté, performance et correction du code concurent. Il est souvent utilisé
pour des applications systèmes, des logiciels embarqués, des navigateurs et
des applications web.
Il n'existe pas à l'heure actuelle de standard du langage, mais deux
projets dans ce sens existent :
1. Les entreprises AdaCore et Ferrous Systems ont développé une version
qualifiée du compilateur standard Rust, nommée
#link("https://ferrocene.dev/en/")[Ferrocene], certifiée ISO26262 (ASIL D)
et IEC 61508 (SIL 4) pour les plateformes x86 et ARM. Celle-ci est mise à
jour tous les trois mois, soit toutes les deux à trois versions de Rust.
<ferrocene>
2. La fondation #Rust a lancé un projet de rédaction d'une spécification.
Ce projet semble sérieux et devrait aboutir a une
spécification qui serait mise à jour à chaque parution d'une nouvelle
version du compilateur (toutes les six semaines). Contrairement à la
specification de Ferrocene, qui n'est pas un standard du langage mais se
borne à décrire le fonctionnement d'un compilateur donné, la specification
proposée par la fondation serait officielle et pourrait à terme aboutir à
un standard.
Il existe de plus un guide #cite(<anssi-rust>) édité par l'ANSSI pour le
développement d'applications sécurisées en Rust.
],
paradigme: [
Rust est un langage multi-paradigme qui permet la programmation
#paradigme[impérative],
#paradigme[fonctionnelle], et (de manère plus limitée) orientée
#paradigme[objet].
Pour illuster l'aspect multi paradigmes, considérons l'exemple d'un code
qui prend en entrée une liste de chaînes de caractères représentant des
entiers et compte combien sont plus petits que 10.
Dans un style fonctionnel:
#figure(
```rust
fn count_smaller_than_10(l: &[&str]) -> usize {
l.iter()
.filter_map(|s| s.parse::<i32>().ok())
.filter(|&x| x < 10)
.count()
}
```
)
et l'équivalent dans un style impératif:
#figure(
```rust
fn count_smaller_than_10(l: &[&str]) -> usize {
let mut count = 0;
for s in l {
if let Ok(n) = s.parse::<i32>() {
if n < 10 {
count += 1;
}
}
}
count
}
```
)
],
model_intro: [
],
runtime: [
#let mirai = link("https://github.com/endorlabs/MIRAI")[Mirai]
La jeunesse du langage fait que la plupart des outils d'analyse ou de
vérification sont encore des projets de recherche. En terme d'analyse
statique, il existe #mirai qui fait de l'analyse statique sur le langage
intermédiaire du compilateur #Rust. Il peut identifier certaines classes
d'erreurs en s'aidant éventuellement d'annotations.
],
wcet: [
Il n'existe à ce jour pas d'outil sur étagère permettant de faire de
l'analyse WCET de programmes spécifiquement Rust. Néanmoins, les outils
fonctionnant sur du code machine évoqués dans la partie C peuvent être
utilisés.
],
pile: [
Il n'y a pas d'outil recensé faisant de l'analyse statique de pile sur
un programme #Rust. Toutefois, les outils fonctionnant sur du code machine
évoqués dans la partie C peuvent être utilisés.
],
numerique: [
Il n'y a pas d'outils recensé pour faire de l'analyse numérique statique
#Rust.
Il existe néanmoins plusieurs bibliothèques permettant de travailler avec
plus de précision qu'avec des flottants 32 ou 64 bits. Certaines permettent
- du calcul à virgule fixe (#crate("bigdecimal"), #crate("rust_decimal"));
- des entiers de taille arbitraire(#crate("num"), #crate("ruint");
#crate("rug"));
- des fractions (#crate("num"), #crate("rug"));
- des flottants de précision arbitraire (#crate("rug") ou
#crate("gmp-mpfr-sys") basées sur #mpfr ou #gmp).
],
formel: [
La vérification formelle de code #Rust suscite un certain intérêt puisque
malgré la jeunesse du langage, il y a déjà plusieurs initiatives sur le sujet.
Toutefois, il s'agit de projets académiques et aucun ne bénéficie d'un
support commercial pour le moment.
*Creusot*
#let creusot = link("https://github.com/creusot-rs/creusot")[Creusot]
#creusot#footnote[https://github.com/creusot-rs/creusot] est un outil de
vérification déductive de code #Rust. Il a son propre langage de
specification nommé _pearlite_. Il traduit le code #Rust et sa
specification
_pearlite_ en code WhyML, utilisé ensuite par l'outil Why3. A ce jour, il a
été utilisé pour vérifier formellement un SAT solver, CreuSAT.
Voici un exemple d'utilisation de spécification #creusot:
```rust
use creusot_contracts::*;
#[requires(x < i32::MAX)]
#[ensures(result@ == x@ + 1)]
pub fn add_one(x: i32) -> i32 {
x + 1
}
```
et la commande
*Flux*
#let flux = link("https://flux-rs.github.io/flux/")[Flux]
#flux#footnote["https://flux-rs.github.io/flux/] augmente #Rust en lui
rajoutant des types par rafinement. Il a également son propre langage de
spécification qui ne porte pas de nom. Il transforme ces types en Clauses
de Horn Contraintes (CHC) et utilise directement le solver #z3 pour les
résoudre. Par exemple :
```rust
#[flux::sig(fn(x: i32) -> i32{v: x < v})]
pub fn inc(x: i32) -> i32 {
x - 1
}
```
donnera une erreur lors de la compilation:
```
error[FLUX]: postcondition might not hold
--> test0.rs:3:5
|
3 | x - 1
| ^^^^^
```
*Aenas*
#let hol = link("https://hol-theorem-prover.org/")[HOL]
#link("https://github.com/AeneasVerif/aeneas")[Aenas] et
#link("https://github.com/AeneasVerif/charon")[Charon] sont deux outils,
développés dans
le cadre du même projet. Ils permettent de traduire du code #Rust vers
différents langages de spécification formelle afin de pouvoir écrire des
preuves dessus. Les langages de preuve supportés sont F\*, #coq,
#hol et
#lean.
*Verus*
#link("https://github.com/verus-lang/verus")[Verus] permet également
d'ajouter des spécifications à du code #Rust, et de vérifier qu'elles sont
satisfaites pour toute execution possible du programme. Il s'appuie
directement sur le solveur SMT #z3. Voici un exemple d'utilisation:
```rust
fn octuple(x1: i8) -> i8
requires
-64 <= x1,
x1 < 64,
{
let x2 = x1 + x1;
let x4 = x2 + x2;
x4 + x4
}
```
],
intrinseque: [
*Erreurs*
En Rust, les erreurs sont rendues explicites dans les types de retour, et
le compilateur signale lorsque l'on a omis de vérifier une potentielle
valeur d'erreur. Par exemple, pour cette fonction qui vérifie si un fichier
fait moins de 100 kilo-octets, le type de retour
`Result<bool, std::io::Error> ` indique qu'il s'agit d'un booléen dans le
cas normal ou potentiellement d'une erreur d'IO.
```rust
fn file_is_less_than_100kb(path: impl AsRef<Path>) -> Result<bool, std::io::Error> {
let path = path.as_ref();
let res = path.exists() &&
path.is_file() &&
std::fs::metadata(path)?.len() < 1024 * 100;
Ok(res)
}
```
On ne peut pas accéder à la valeur booléenne sans vérifier l'erreur: le
code ci-dessous donne une erreur de compilation.
```rust
fn main() {
if file_is_less_than_100kb("user.txt") {
println!("user.txt is missing")
}
}
```
```
error[E0308]: mismatched types
--> src/main.rs:12:6
|
12 | if file_is_less_than_100kb("user.txt") {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `bool`, found `Result<bool, Error>`
|
= note: expected type `bool`
found enum `Result<bool, std::io::Error>`
help: consider using `Result::expect` to unwrap the `Result<bool, std::io::Error>` value, panicking if the value is a `Result::Err`
|
12 | if file_is_less_than_100kb("user.txt").expect("REASON") {
| +++++++++++++++++
For more information about this error, try `rustc --explain E0308`.
```
Il en est de même si on oublie de vérifier qu'une fonction à effet de
bord n'a pas retourné d'erreur:
```rust
fn write(path: impl AsRef<Path>, content: &str) -> Result<(), std::io::Error> {
std::fs::write(path, content)
}
fn main() {
write("user.txt", "<NAME>");
}
```
on obtient alors le warning:
```
warning: unused `Result` that must be used
--> src/main.rs:8:5
|
8 | write("user.txt", "<NAME>");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: this `Result` may be an `Err` variant, which should be handled
= note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value
|
8 | let _ = write("user.txt", "<NAME>");
| +++++++
```
*Régions mémoire*
#Rust dispose d'un mécanisme innovant de gestion de la mémoire par régions
qui permet de garantir la sûreté mémoire au moment de la compilation
sans avoir recours à un rammasse-miettes au _runtime_.
Celui-ci, lié au système d'_ownership_ permet d'éviter les erreurs
suivantes:
- _use after free_
- _data races_
- _dangling pointers_
- erreurs liés à l'_aliasing_ de pointeurs
],
tests: [
#Rust inclut un cadre de test standard qui permet de gérer les tests
unitaires via des annotations et des macros:
```rust
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
```
Avec ces annotations, le compilateur #Rust génère un exécutable de test
qui peut être lancé avec la commande `cargo test`.
#let rs_quickcheck = link(
"https://crates.io/crates/quickcheck",
`quickcheck`
)
#let rs_proptest = link(
"https://crates.io/crates/proptest",
`proptest`
)
#let rs_mockall = link(
"https://crates.io/crates/mockall/",
`mockall`
)
Toutefois, les fonctionnalités fournies par ce cadre sont minimalistes et
des paquets #Rust complètent le service en y ajoutant du _fuzzing_
(#rs_quickcheck, #rs_proptest) ou du _mocking_ (#rs_mockall).
Il ne semble pas exister d'outil permettant d'engendrer des rapports de
tests standardisés ou conforme à une norme particulière. `cargo test`
permet toutefois d'engendrer un rapport JSON qui peut être traité par
des outils tiers.
],
compilation: [
Hormis le compilateur Ferrocene mentionné précedemment qui n'est autre
qu'une version qualifiée du
compilateur standard `rustc`, il n'existe aujourd'hui pas de
compilateur alternatif utilisable.
On peut néanmoins mentionner les projets suivants:
- #link("https://rust-gcc.github.io/")[*gccrs*] vise à développer un
_frontend_ #Rust pour #gcc. L'ensemble formerait un compilateur
entièrement différent de `rustc`.
- #link("https://github.com/rust-lang/rustc_codegen_gcc")[*rust codegen
gcc*] qui consiste à brancher le _backend_ de #gcc au _frontend_ de
`rustc`. Cela permettrait de
supporter les plateformes déjà supportées par #gcc mais ne constituerait
pas une implémentation différente de `rustc`.
- #link("https://github.com/rust-lang/rustc_codegen_cranelift")[*rust
codegen cranelift*] qui consiste à brancher _cranelift_ sur le
_frontend_ de `rustc`
afin de
permettre des temps de compilation plus rapides en mode dit _debug_
(c'est à dire sans les optimisations). Là encore, il s'agirait d'utiliser
une partie de `rustc`.
],
debug: [
Le langage Rust supporte officiellement GDB, LLDB et WinDbg/CDB.
],
metaprog: [
Le système de macro de #Rust est expressement fait pour permettre la
métaprogrammation de manière hygiénique. Par exemple, le code suivant
permet de créer un vecteur de trois entiers:
```rust
let v: Vec<i32> = vec![1, 2, 3];
```
où le symbole `!` indique l'appel à une macro (ici `vec`). Cette macro
pourrait être définie comme suit:
```rust
macro_rules! vec {
($($x:expr),*) => {{
let mut temp_vec = Vec::new();
$(temp_vec.push($x);)*
temp_vec
}};
}
```
où, sans entrer dans les détails, on dit au compilateur que si la macro
est appelée avec une liste d'expressions séparées par des virgules
(`$($x:expr),*`), alors il crée un nouveau vecteur (
`let mut temp_vec = Vec::new();`), y ajoute les éléments de la liste
(`$(temp_vec.push($x);)*`)
et retourne le vecteur.
Ce système de macro est suffisamment riche pour permettre l'écriture de
mini-DSL, des générateurs de code ou des dérivations à partir des types.
],
parsers: [
La jeunesse du langage fait qu'il n'est pas encore très utilisé pour
l'écriture de compilateurs ou d'interpréteurs. De fait, il n'y a pas encore
beaucoup d'outils pour l'écriture de parseurs spécifiquement pour #Rust.
Quelques outils ciblant plusieurs langages ont simplement
développé un _backend_ supplémentaire pour #Rust.
#let lalrpop = link("https://github.com/lalrpop/lalrpop", "LALRPOP")
#let hime = link("https://cenotelie.fr/projects/hime", "Hime")
#let syntax = link("https://github.com/DmitrySoshnikov/syntax", "Syntax")
Au niveau des _lexers_, il n'y a que #re2c supporte #Rust. #lalrpop a
également un générateur de _lexer_ intégré. Pour les _parsers_, il y en
a essentiellement trois: #lalrpop, #hime et #syntax. Notons que #lalrpop
embarque le _parsing_ dans #Rust via des macros procédurales.
#figure(
table(
columns: (auto, auto, auto, auto, auto),
[*Nom*], [*Algorithme*], [*Grammaire*], [*Code*], [*Plateforme*],
[*LALRPOP*], [LR(1), LALR(1)], [Rust], [Rust], [Toutes],
[*Hime*], [LR(1), GLR, LALR(1)], [EBNF], [Séparé], [.NET, JVM],
[*Syntax*], [LR, LL], [JSON, Yacc], [Mixte], [Toutes],
)
)
],
derivation: [
La métaprogrammation autorisée par les macros de #Rust permet également
de dériver du code à partir des types. Le code suivant définit
ce qu'on appelle une macro procédurale qui va générer du code #Rust à
partir de code #Rust.
```rust
use proc_macro::TokenStream;
use quote::quote;
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
// Construct a representation of Rust code as a syntax tree
// that we can manipulate
let ast = syn::parse(input).unwrap();
// Build the trait implementation
let name = &ast.ident;
let gen = quote! {
impl HelloMacro for #name {
fn hello_macro() {
println!("Hello, Macro! My name is {}!", stringify!(#name));
}
}
};
gen.into()
}
```
Dans cet exemple, on définit une bibliothèque de dérivation qui prend un
code #Rust (`input: TokenStream`), le parse
(`let ast = syn::parse(input).unwrap();`) en un bout d'AST puis contruit
un nouveau code
#Rust (`let gen = quote! { ... };`) avec les informations contenues dans
l'AST. En définissant le trait `HelloMacro` par ailleurs:
```rust
pub trait HelloMacro {
fn hello_macro();
}
```
on peut alors utiliser la macro `hello_macro` pour dériver le code
idoine:
```rust
#[derive(HelloMacro)]
struct Foo;
fn main() {
Pancakes::hello_macro();
}
```
qui affichera `Hello, Macro! My name is Foo!`.
],
packages: [
Le gestionnaire de paquet officiel de #Rust est `cargo`. C'est également
l'outil de _build_ du langage. Il permer de télécharger, compiler,
distribuer et de téléverser des paquets (nommés _crates_) dans des registres
partagés ou de dépôts Git.
Les registres peuvent être publics ou privés. Le registre public par défaut
est #crates_io mais il y a également #lib_rs qui est également très utilisé.
Ce gestionnaire de paquets est l'un des points forts de #Rust car il
facile l'installation d'un environnement de développement propre et
le _build_ d'un projet #Rust.
],
communaute: [
La communauté #Rust comprend un tissu associatif (fondation #Rust,
#Rust France, ...) et des entreprises qui organisent régulièrement des
événements (meetups, conférences, ...) au travers le monde.
Le langage attire beaucoup de jeunes développeurs séduits par la fiabilité
et les performances mis en avant par le langage. Il suffit de voir le
nombre de paquets logiciels crées pour #Rust qui atteint plus de 130 0000
sur #crates_io en moins de 10 ans#footnote[https://lib.rs/stats].
],
assurances: [
Le langage #Rust intègre nativement des mécanismes de
sécurité et de fiabilité :
- un typage statique et fort;
- un système de gestion de la mémoire et son modèle d'_ownership_.
Ces mécanismes, et tout une panoplie de contrôles à la compilation,
permettent de limiter le besoin d'outils externes pour
fiabiliser la production.
Cette rigueur peut amener le compilateur à rejeter
des programmes qui pourraient être valides et cela peut destabiliser les
nouveaux programmeurs habitués au C/C++. De fait, le langage est
reconnu pour avoir un ticket d'entrée plutôt élévé et il n'est pas clair
aujourd'hui si cela est un avantage ou un inconvénient d'un point de vue
industriel. D'un côté, cela permet de réduire les erreurs de programmation
et de limiter les failles de sécurité. D'un autre côté, cela peut
ralentir le développement et engendrer des circonvonlutions
pour faire accepter le programme au compilateur, engendrant ainsi une dette
technique similaire à celle du C++ utilisé par des spécialistes.
Toutefois, le langage jouit d'un réel engouement et il est même conseillé
par l'ANSSI dans les développements
sécurisé au titre de la démarche de sécurité par conception.
],
adherence: [
Comme le C, #Rust peut être utilisé sur un système nu en spécifiant
`no_std` :
```rust
#![no_main]
#![no_std]
use core::panic::PanicInfo;
#[panic_handler]
fn panic(_panic: &PanicInfo) -> ! {
loop {}
}
```
],
interfacage: [
#Rust a une FFI lui permettant d'interagir avec le C soit en important
du C :
```rust
#[link(name = "my_c_library")]
extern "C" {
fn my_c_function(x: i32) -> bool;
}
```
soit en exportant du #Rust vers du C:
```rust
#[no_mangle]
pub extern "C" fn callable_from_c(x: i32) -> bool {
x % 3 == 0
}
```
Par transitivité, #Rust est compatible avec tous les langages compatibles
avec le C.
],
critique: [
Il n'existe à ce jour pas de communication officielle sur un logiciel
embarqué critique qui serait en #Rust. Toutefois les demarches de
Ferocene et la fondation #Rust indiquent clairement une volonté de
pénétrer le marché du logiciel critique et certains constructeurs
automobiles ont déjà manifesté leur intérêt pour le langage.
]
)
|
|
https://github.com/Isaac-Fate/booxtyp | https://raw.githubusercontent.com/Isaac-Fate/booxtyp/master/src/theorems/note.typ | typst | Apache License 2.0 | #import "new-plain-template.typ": new-plain-template
#import "../colors.typ": color-schema
#let note = new-plain-template(
"Note",
title-color: color-schema.orange.primary,
title-prefix: emoji.notepad,
body-text-style: "italic",
)
|
https://github.com/ymgyt/techbook | https://raw.githubusercontent.com/ymgyt/techbook/master/programmings/js/typescript/debug.md | markdown | # Debug
```typescript
console.log('%o', obj);
```
|
|
https://github.com/zenor0/FZU-report-typst-template | https://raw.githubusercontent.com/zenor0/FZU-report-typst-template/main/fzu-report/utils/states.typ | typst | MIT License | #let chapter-l1-name-str-state = state("chapter-l1-name-str")
#let chapter-l1-name-show-state = state("chapter-l1-name-show")
#let chapter-l1-true-loc-state = state("chapter-l1-true-loc")
#let chapter-l1-numbering-show-state = state("chapter-l1-numbering-show")
#let chapter-l1-page-number-show-state = state("chapter-l1-page-number-show")
#let heading-l1-updating-name-str-state = state("heading-l1-updating")
#let chapter-name-str-state = state("chapter-name-str")
#let chapter-name-show-state = state("chapter-name-show")
#let chapter-true-loc-state = state("chapter-true-loc")
#let chapter-numbering-show-state = state("chapter-numbering-show")
#let chapter-page-number-show-state = state("chapter-page-number-show")
#let chapter-level-state = state("chapter-level")
#let part-state = state("part")
#let appendix() = {
pagebreak()
part-state.update("附录")
counter(heading).update(0)
counter(heading.where(level: 1)).update(0)
} |
https://github.com/SwampertX/cv | https://raw.githubusercontent.com/SwampertX/cv/main/simple-cv.typ | typst | #import "simple-cv-template.typ": *
#show: resume
#header(
name: "<NAME>",
phone: "+33 7 52 04 32 55",
email: "<EMAIL>",
// linkedin: "linkedin.com/in/yeejian-tan",
site: "yeejian.dev",
)
#resume_heading[Education]
#edu_item(
name: "École Polytechnique",
degree: [
Master of Theoretical Computer Science (Master Parisien de Recherche en Informatique)
],
location: "Paris, France",
date: "Aug 2023 - Mar 2025"
)
#edu_item(
name: "National University of Singapore",
degree: [
Bachelors of Computing with Honours (Computer Science), Distinction (4.48/5)
- Specialization: Algorithms and Computation
Bachelors of Science (Mathematics), Highest Distinction (4.50/5)
- Specialization: Abstract Algebra, Logic
],
location: "Singapore",
date: "Aug 2018 - May 2023"
)
#resume_heading[Experience]
#exp_item(
role: "Research Intern, M1 Internship",
name: "Cambium, Inria",
location: "Paris, France",
date: "May 2024 - Aug 2024",
[Advisor: <NAME>],
[Formalized Coq's module system in the MetaCoq project],
)
#exp_item(
role: "Research Intern",
name: "Gallinette, Inria",
location: "Nantes, France",
date: "May 2022 - Aug 2022",
[Advisor: <NAME>],
[Formalized Coq's module system in the MetaCoq project],
)
#exp_item(
role: "Intern, Machine Learning Engineer",
name: "<NAME>",
location: "Singapore",
date: "May 2020 - Sep 2020",
[Jointly designed and packaged a Google BigQuery to Apache Kafka data ingestion tool],
[Increased data ingestion rate from $~10$k to > $3000$k rows/second using Google Cloud Dataflow]
)
// #exp_item(
// role: "Software Engineering Intern",
// name: "Computing for Voluntary Welfare Organisations (CVWO), NUS",
// location: "Singapore",
// date: "May 2019 - Aug 2019",
// [Streamlined and digitized volunteering workflow for more than 100 students every year
// by developing and maintaining a Volunteer Management System for the GIC Sparks
// and Smiles program.],
// [For more than 6000 clients and 100 staff, reduced operating costs and increased the
// accuracy of data capture by maintaining a Case Management System for the
// Counseling and Co-parenting Centers by CareCorner.],
// )
#resume_heading("Publications")
#pub_item(
name: "A stepper for a JavaScript Sublanguage",
authors: [Jww. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>],
doi: "https://doi.org/10.1145/3371076"
)
#resume_heading("Awards")
#award_item(
name: "Senior Honour Roll",
organisation: "NUS University Scholars Programme",
date: "2022 - 2023"
)
#award_item(
name: "Honour Roll",
organisation: "NUS University Scholars Programme",
date: "2020 - 2021"
)
#award_item(
name: "Honour List of Student Tutors",
organisation: "NUS School of Computing",
date: "2019 - 2020"
)
#resume_heading("Scholarships and Grants")
#grant_item(
name: "Masters Mobility Programme",
organisation: "French Embassy to Malaysia",
desc: [1-year grant covering tuition fees and living expenses in France.],
date: "2023 - 2024"
)
#grant_item(
name: "Dr. <NAME>",
organisation: "Association of Banks in Singapore",
desc: [Full scholarship for undergraduates selected from 15 Asia-Pacific economies.],
date: "2018 - 2023"
)
// #grant_item(
// name: "ASEAN Scholarship",
// organisation: "Ministry of Education, Singapore",
// desc: [Full scholarship for students in ASEAN countries to study high school in Singapore.],
// date: "2014 - 2017"
// )
#resume_heading("Teaching Experience")
#award_item(
name: "Programming Methodology I",
organisation: "Teaching Assistant, NUS School of Computing",
date: "Fall 2022",
)
#award_item(
name: "Programming Methodology I",
organisation: "Teaching Assistant, NUS School of Computing",
date: "Summer 2021",
)
#award_item(
name: "Programming Methodology I",
organisation: "Teaching Assistant, NUS School of Computing",
date: "Fall 2020",
)
#award_item(
name: "Programming Methodology I",
organisation: "Teaching Assistant, NUS School of Computing",
date: "Fall 2019",
)
#award_item(
name: "Programming Methodology I (S)",
organisation: "Teaching Assistant, NUS School of Computing",
date: "Fall 2019",
)
#resume_heading("Theses")
#grant_item(
name: "Formalizing Coq Modules in the MetaCoq Project",
organisation: "Bachelor's Thesis",
desc: [Advisors: <NAME>, <NAME>, <NAME>.
Grade: A],
date: "2023"
)
|
|
https://github.com/EGmux/TheoryOfComputation | https://raw.githubusercontent.com/EGmux/TheoryOfComputation/master/final/q1.typ | typst | #set heading(numbering: "1.")
=== 1. *Considere $L_1 = (0 ⋃ 1 1)^m 2(0 ⋃ 1)^n 3(0 ⋃ 1)^+$, com $m,n >= 0, m "par e" n "impar"$.*
*Prove que $L_1$ é uma*
*linguagem regular construindo um AFD com no máximo 7 estados que a reconheça*
#figure(image("../assets/q1.png", width: 50%)) <fig-q1>
=== 2. *Diga se $L_2 = {w in {0,1}^* | w "possui menos 0s que 1s"}$ é ou não é uma
linguagem regular, mostrando uma expressão regular*
*(caso seja) ou usando lema do bombeamento (caso não seja)*
O enunciado do lema do bombeamento
tal que x é prefixo, y é uma concatenação de cadeias e z é o sufixo e m e k
pertencem aos naturais com m>0\
$|x y|<=p$ \
$|y| >= 1$\
$(forall n >= 0)(x y^n z in L)$\
1. Considere que o número de 1's seja k e o número de 0's seja k-1.\
2. Considere a seguinte cadeia que pertence a $L_2=10^(k-m-1)0^(m)1^(k-1)$
3. Como m pertence aos naturais e é maior que 0 então existe um número menor de 0's
que 1's como gostaríamos.
4. Escolha $p=k-m$ como comprimento de bombeamento, temos
$x y^n = 1(0^(k-m-1))^n$, expandindo temos:
$x y^n = (0^(n k- n m - n))= 1 0^n(k-m-1)$
5. Concatenando com o sufixo temos $10^n(k-m-1) 0^(m)1^(k-1)$
6. Temos pelo menos n zeros a mais que 1's onde n é a quantidade de concatenações
da cadeia bombeada, assim
a cadeia não pertence a L, visto que há mais zeros que 1's, portante não é
regular.
=== 3. Prove que a interseção entre linguagens regulares e linguagens livre de contexto são linguagens livre de contexto.
Sabemos que toda linguagem regular pode ser representada como expressão regular.
=== 4. Contrua uma GLC na forma normal de chomsky para o conjunto de todos palíndromos binários
a definição da forma normal de chomsky:\
$S -> ϵ$ \
$A -> B C$\
$A -> a$\
tal que B e C não sejam S, embora A possa ser.
#math.equation(block: true, $
& S -> ϵ && \
& S -> 0 && \
& S -> 1 && \
& S -> C C && \
& S -> D D && \
& S -> C A' && \
& S -> D A'' && \
& A -> C A' && \
& A' -> A C && \
& A -> D A'' && \
& A'' -> A D && \
& C -> 0 && \
& D -> 1 && \
& A -> 0 && \
& A -> 1 && \
$)
=== 5. Prove que uma máquina de Turing é equivalente a um autômato com duas ou mais pilhas
Essa prova consiste da ida que tem como enunciado "uma máquina de turing atua
como autômato de duas pilhas" e a volta "um autômato de duas pilhas atua como
máquina de turing", provemos primeiranmente a ida
$==>$
Sabemos que uma MT é definida pela seguinte 7-upla\
$M := (Sigma,Gamma,Q_o,Q_"accept",Q_"reject",δ,Q)$
e um autômato com duas pilhas pela seguinte 7-upla\
$A_p := (Sigma, Gamma_1,Gamma_2, Q_o, Q_"accept", delta, Q)$
$delta_M := Q times Gamma -> Q times Gamma times {L,R} $\
$delta_"p" := Q times Sigma times Gamma_1 times Gamma_2 -> P(Q times Gamma_1 times Gamma_2) $
vamos converter a MT num autômato com pilha através do seguinte mapeamento
- Os estados Q da MT são os mesmos estados Q da AP
- O alfabeto $Sigma$ da MT é o mesmo da AP
- O alfabeto $Gamma$ da MT é o alfabeto $Gamma_1$ da AP
-
=== 6. Resolva os seguintes problemas:
==== a. Explique brevemente o lema de Church-Turing
Máquina de Turing é equivalente a um algoritmo, isto é dada uma entrada w para
um algoritmo se o mesmo iria "entrar em loop" então a MT tambem iria, se o mesmo
iria eventualmente parar a MT tambem, essa breve explicação é válida para todo
autômato que tem capacidade computacional equivalente a uma máquina de Turing,
reconhece todas as linguagens que uma MT reconhece, embora a complexidade
computacional varie de autômato a autômato.
==== b. Prove que $L_3 = {angle.l G,A angle.r$
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/bugs/flow-2-00.typ | typst | Other | #set page(height: 60pt)
#v(19pt)
#block[
But, soft! what light through yonder window breaks?
It is the east, and Juliet is the sun.
]
|
https://github.com/katamyra/Notes | https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS1332/Modules/AVL.typ | typst | #import "../../../template.typ": *
= AVL Trees
#definition[
The *balance factor* of a node is the left child's height - right child's height
]
- What do different values of the balance factor mean?
+ 0: Perfectly Balanced
+ 1: Leaning left but ok
+ neg 1: Leaning right but ok
+ >= 2: unlabaced to far left
+ <= neg 2 unbalanced to far right
#definition[
In *AVL Trees*, the $|"node.balancefactor"| <= 1$. We chose 1 and not 0 because there are some situations where it is straight up impossible to have a perfectly balanced tree.
]
AVL's help us hit the sweet spot of allowing only a little imbalance while keeping operations efficient.
== Single Rotations
These are used when adding or removing a single node to a tree if it becomes imbalanced.
To perform a rotation when a node has a balance factor of -2: look at the right child first and see if it has a balance factor of 0, -1. Then we can do a simple, single rotations.
#theorem[
```java
Algorithm leftRotation
1) Node B <- A's right child
2) A's right child <- B's left child
3) B's left child <- A
4) (ALWAYS FIRST BEFORE 5) Update the height & BF of A
5) Update the height & BF of B
6) Return B
```
]
Right rotations are the mirrored opposite of left rotations.
When to use which rotation?
Use left rotation when
- node.BF = -2
- node.right.BF = -1, 0
Use right rotation when (? not sure)
- node.BF = 2
- node.right.BF = 1, 0
#blockquote[
A nodes balance factor shouldn't go past 2 without a rotation happening
]
|
|
https://github.com/gumelarme/nuist-master-thesis-proposal | https://raw.githubusercontent.com/gumelarme/nuist-master-thesis-proposal/main/proposal.typ | typst | #import "/strings/en.typ": *
#import "/pages/cover.typ": make-cover, default-label
#set page(
paper: "a4",
margin: (top: 2.1cm, left: 2.5cm, right: 2.5cm, bottom: 2.5cm),
)
#set text(font: ("Times New Roman"))
#make-cover()
#include "/pages/notes.typ"
#include "/pages/report.typ"
#include "/pages/work-plan.typ"
#include "/pages/spv-comment.typ"
|
|
https://github.com/rqy2002/typst-experiment | https://raw.githubusercontent.com/rqy2002/typst-experiment/main/template.typ | typst | // The project function defines how your document looks.
// It takes your content and some metadata and formats it.
// Go ahead and customize it to your liking!
#let project(title: "", authors: (), date: none, body) = {
// Set the document's basic properties.
set document(author: authors, title: title)
set page(numbering: "1 / 1", number-align: start)
let fonts = ("Iosevka", "Microsoft YaHei")
set text(font: fonts, lang: "zh")
set heading(numbering: "I.1. ")
show heading: it => it.body + parbreak()
// Title row.
align(center)[
#block(text(weight: 700, 1.75em, title))
#v(1em, weak: true)
#date
]
// Author information.
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, emph(author))),
),
)
// Main body.
set par(first-line-indent: 2em, justify: true)
body
}
|
|
https://github.com/LeoColomb/dotdocs | https://raw.githubusercontent.com/LeoColomb/dotdocs/main/test/fixture.typ | typst | MIT License | #import "@leocolomb/invoicing:1.0.0": template
#show: template.with(
type: "Fixture",
name: [Continuous Integration],
address: [
In Your Shell\
101 Internet
],
siret: [10142],
project: [Template Validation],
reference: [2084-07-B],
date: datetime.today().display("[day]/[month]/[year]"),
recipient: [
*Test Actor*
],
pricelist: (),
)
Body fixture.
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/program-auton-movement/entry.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Program: Autonomous Movement",
type: "program",
date: datetime(year: 2023, month: 9, day: 11),
author: "<NAME>",
witness: "Meghana Noojipady",
)
With the majority of the complex code handled by LemLib, getting set up is
relatively simple.
```cpp
// Omitted old chassis configuration
// ...
// Define PID constants
// forward/backward PID
inline lemlib::ChassisController_t lateralController{
8, // kP
30, // kD
1, // smallErrorRange
100, // smallErrorTimeout
3, // largeErrorRange
500, // largeErrorTimeout
5 // slew rate
};
// turning PID
inline lemlib::ChassisController_t angularController{
4, // kP
40, // kD
1, // smallErrorRange
100, // smallErrorTimeout
3, // largeErrorRange
500, // largeErrorTimeout
0 // slew rate
};
```
With these defined moving the chassis is incredibly simple.
```cpp
// Move the chassis to (10, 40) at 35 degrees with a timeout of 2 seconds.
chassis.moveTo(10, 40, 25, 20000);
// Move the chassis backwards to (0, 0) at 0 degrees with a timeout of 2 seconds.
chassis.moveTo(0, 0, 0, 20000, false, false);
```
|
https://github.com/0x1B05/algorithm-journey | https://raw.githubusercontent.com/0x1B05/algorithm-journey/main/practice/note/content/堆结构.typ | typst | #import "../template.typ": *
#pagebreak()
= 堆结构
堆的节点关系:
```
left = 2*parent + 1
right = 2*parent + 2
parent = (child-1)/2
```
完全二叉树和数组前缀范围来对应,大小,单独的变量size来控制
堆的调整:`heapInsert`(向上调整)、`heapify`(向下调整)
#tip(
"Tip",
)[
`heapInsert`、`heapify`方法的单次调用,时间复杂度`O(log n)`,完全二叉树的结构决定的
]
== 堆排序
=== 复杂度分析
==== 建堆复杂度
- 从顶到底建堆,时间复杂度`O(n * log n)`,`log1 + log2 + log3 + … + logn -> O(n*logn)`
#tip("Tip")[
或者用增倍分析法:
- 建堆的复杂度分析
- 当元素为N时复杂度的上限是`O(n * log n)`
- 当元素为2N时复杂度的下限是`O(n * log n)`
- 故而复杂度就是`O(n * log n)`
- 子矩阵数量的复杂度分析
- `n*m`矩阵, 任选两点后去重$(n^2 m^2)/4$, 复杂度上限$O(n^2 m^2)$
- `2n*2m`矩阵, 2 4象限任选两点不需要去重, 复杂度下限$O(n^2 m^2)$
- 故而复杂度就是$O(n^2 m^2)$
]
- 从底到顶建堆,时间复杂度`O(n)`,总代价就是简单的等比数列关系,为啥会有差异?
- 顶到底,第一层`heapInsert`一层,第二层`heapInsert`二层...
- 底到顶,最后一层`heapify`一层,倒二层`heapify`二层...
- 而底的元素多,因此底到顶`heapify`更好
==== 调整阶段
从最大值到最小值依次归位,时间复杂度`O(n * log n)`, 时间复杂度`O(n * log n)`,不管以什么方式建堆,调整阶段的时间复杂度都是这个,所以整体复杂度也是这个.
==== 空间复杂度
额外空间复杂度是`O(1)`,因为堆直接建立在了要排序的数组上,所以没有什么额外空间
=== #link("https://www.luogu.com.cn/problem/P1177")[ acm风格 ]
#code(
caption: [堆排序-acm风格],
)[
```java
public class Code01_HeapSort {
public static int MAXN = 100001;
public static int[] nums = new int[MAXN];
public static int n;
// i位置的数,变大了,又想维持大根堆结构
// 向上调整大根堆
public static void heapInsert(int cur) {
int parent = (cur - 1) / 2;
while (nums[cur] > nums[parent]) {
swap(cur, parent);
cur = parent;
parent = (cur - 1) / 2;
}
}
// i位置的数,变小了,又想维持大根堆结构
// 向下调整大根堆
// 当前堆的大小为size
public static void heapify(int cur, int size) {
int left = 2 * cur + 1;
while (left < size) {
int right = left + 1;
int maxChild = right < size && nums[right] > nums[left] ? right : left;
int max = nums[maxChild] > nums[cur] ? maxChild : cur;
if (max == cur) {
break;
} else {
swap(max, cur);
cur = max;
left = 2 * cur + 1;
}
}
}
// 从顶到底建立大根堆,O(n * logn)
// 依次弹出堆内最大值并排好序,O(n * logn)
// 整体时间复杂度O(n * logn)
public static void heapSort1() {
// 每个节点向上移动形成大根堆
for (int cur = 1; cur < n; cur++) {
heapInsert(cur);
}
int size = n;
while (size > 0) {
swap(0, --size);
heapify(0, size);
}
}
// 从底到顶建立大根堆,O(n)
// 依次弹出堆内最大值并排好序,O(n * logn)
// 整体时间复杂度O(n * logn)
public static void heapSort2() {
for (int cur = n - 1; cur >= 0; cur--) {
heapify(cur, n);
}
int size = n;
while (size > 1) {
swap(0, --size);
heapify(0, size);
}
}
public static void swap(int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer in = new StreamTokenizer(br);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
in.nextToken();
n = (int) in.nval;
for (int i = 0; i < n; i++) {
in.nextToken();
nums[i] = (int) in.nval;
}
// heapSort1();
heapSort2();
for (int i = 0; i < n - 1; i++) {
out.print(nums[i] + " ");
}
out.println(nums[n - 1]);
out.flush();
out.close();
br.close();
}
}
```
]
#tip(
"Tip",
)[
- 降序可以使用小根堆。
- 若是已知某个大根堆中 `i` 位置的数改成了`x`, 继续调整为大根堆要么 `heapInsert` 要么 `heapify`
]
=== #link("https://www.luogu.com.cn/problem/P1177")[ acm风格 ]
#code(
caption: [堆排序-leetcode风格],
)[
```java
public class Code02_HeapSort {
// i位置的数,变小了,又想维持大根堆结构
// 向下调整大根堆
// 当前堆的大小为size
public static void heapify(int[] nums, int cur, int size) {
int left = 2 * cur + 1;
while (left < size) {
int right = left + 1;
int maxChild = right < size && nums[right] > nums[left] ? right : left;
int max = nums[maxChild] > nums[cur] ? maxChild : cur;
if (max == cur) {
break;
} else {
swap(nums, max, cur);
cur = max;
left = 2 * cur + 1;
}
}
}
// i位置的数,变大了,又想维持大根堆结构
// 向上调整大根堆
public static void heapInsert(int[] nums, int cur) {
int parent = (cur - 1) / 2;
while (nums[cur] > nums[parent]) {
swap(nums, cur, parent);
cur = parent;
parent = (cur - 1) / 2;
}
}
// 从顶到底建立大根堆,O(n * logn)
// 依次弹出堆内最大值并排好序,O(n * logn)
// 整体时间复杂度O(n * logn)
public static void heapSort1(int[] nums) {
int n = nums.length;
// 每个节点向上移动形成大根堆
for (int i = 0; i < n; i++) {
heapInsert(nums, i);
}
int size = n;
while (size > 1) {
swap(nums, 0, --size);
heapify(nums, 0, size);
}
}
// 从底到顶建立大根堆,O(n)
// 依次弹出堆内最大值并排好序,O(n * logn)
// 整体时间复杂度O(n * logn)
public static void heapSort2(int[] nums) {
int n = nums.length;
for (int cur = n - 1; cur >= 0; cur--) {
heapify(nums, cur, n);
}
int size = n;
while (size > 1) {
swap(nums, 0, --size);
heapify(nums, 0, size);
}
}
public static void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
public static int[] sortArray(int[] nums) {
if (nums.length > 1) {
// heapSort1为从顶到底建堆然后排序
// heapSort2为从底到顶建堆然后排序
// 用哪个都可以
// heapSort1(nums);
heapSort2(nums);
}
return nums;
}
}
```
]
== 经典题目
=== #link(
"https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6",
)[题目1: 合并K个有序链表]
合并 `k` 个升序的链表并将结果作为一个升序的链表返回其头节点。
#example("Example")[
- 输入: `[L{1,2,3},{4,5,6,7}]`
- 返回值:`{1,2,3,4,5,6,7}`
]
#tip("Tip")[
- 节点总数 `0≤n≤5000`
- 每个节点的`val`满足 `∣val∣<=1000`
- 要求:时间复杂度 `O(nlogn)`
]
==== 解答
k个链表;n个节点。
暴力解法复杂度分析: 把所有节点加入一个大容器,然后再排序。
- 空间O(n)
- 时间O(n)+O(nlogn)
堆结构复杂度分析:
- 空间O(k)
- 时间O(nlogk)
#code(
caption: [题目1: 合并K个有序链表],
)[
```java
public class Code01_MergeKSortedLists {
public static class ListNode {
public int val;
public ListNode next;
}
public ListNode mergeKLists(ArrayList<ListNode> lists) {
PriorityQueue<ListNode> heap = new PriorityQueue<>((a, b) -> (a.val - b.val));
for (ListNode listNode : lists) {
if (listNode != null) {
heap.add(listNode);
}
}
if (heap.isEmpty()) {
return null;
}
ListNode head = heap.poll();
ListNode tail = head;
if (tail.next != null) {
heap.add(tail.next);
}
while (!heap.isEmpty()) {
ListNode cur = heap.poll();
tail.next = cur;
tail = cur;
if (cur.next != null) {
heap.add(cur.next);
}
}
return head;
}
}
```
]
=== #link(
"https://www.nowcoder.com/practice/1ae8d0b6bb4e4bcdbf64ec491f63fc37",
)[题目2: 最多线段重合问题]
每一个线段都有 `start` 和 `end` 两个数据项,表示这条线段在 X 轴上从 `start` 位置开始到 `end` 位置结束。给定一批线段,求所有重合区域中最多重合了几个线段,首尾相接的线段不算重合。
例如:线段`[1,2]`和线段`[2,3]`不重合。 线段`[1,3]`和线段`[2,3]`重合
- 输入描述:
- 第一行一个数`N`,表示有`N`条线段
- 接下来`N`行每行`2`个数,表示线段起始和终止位置
- 输出描述:
- 输出一个数,表示同一个位置最多重合多少条线段
#example("Example")[
输入:
```
3
1 2
2 3
1 3
```
输出:`2`
]
#tip("Tip")[
- $N≤10^4$
- $1≤"start","end"≤10^5$
]
==== 解答
重合区域的左边界一定是某个线段的左边界。
先按照开始位置从小到大排序. 接着把结束位置放到小根堆里. 来到`[x,y]`,
把小根堆里面小于等于`x`的弹出, 把`y`放到小根堆, 看小根堆里有几个, 即当前`[x,y]`线段的答案.
解释: 以`x`为重合区域左边界,有多少线段(包括自身)能到达`x`的右边,因为左边的线段开始位置比`x`早,结束位置又在`x`之后,那就是算一次重合(结束位置在`x`之前的已经被弹出)。
#code(
caption: [题目2: 最多线段重合问题],
)[
```java
public class Code02_MaxCover {
public static int MAXN = 10001;
public static int n;
public static int[][] line = new int[MAXN][2];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer in = new StreamTokenizer(br);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
while (in.nextToken() != StreamTokenizer.TT_EOF) {
n = (int) in.nval;
for (int i = 0; i < n; i++) {
in.nextToken();
line[i][0] = (int) in.nval;
in.nextToken();
line[i][1] = (int) in.nval;
}
out.println(compute());
}
out.flush();
out.close();
br.close();
}
public static int[] heap = new int[MAXN];
public static int size = 0;
public static void heapInsert(int cur) {
int parent = (cur - 1) / 2;
while (heap[cur] < heap[parent]) {
swap(cur, parent);
cur = parent;
parent = (cur - 1) / 2;
}
}
public static void swap(int i, int j) {
int tmp = heap[i];
heap[i] = heap[j];
heap[j] = tmp;
}
public static void heapify(int cur) {
int left = 2 * cur + 1;
while (left < size) {
int right = left + 1;
int minChild = right < size && heap[right] < heap[left] ? right : left;
int min = heap[minChild] < heap[cur] ? minChild : cur;
if (min == cur) {
break;
} else {
swap(cur, min);
cur = min;
left = 2 * cur + 1;
}
}
}
public static void add(int num) {
int cur = size++;
heap[cur] = num;
heapInsert(cur);
}
public static void pop() {
swap(0, --size);
heapify(0);
}
public static int compute() {
int max = 0;
Arrays.sort(line, 0, n, (a, b) -> a[0] - b[0]);
for (int i = 0; i < n; i++) {
while (size > 0 && heap[0] <= line[i][0]) pop();
add(line[i][1]);
max = Math.max(max, size);
}
return max;
}
}
```
]
- 时间复杂度:O(nlogn)
- 空间复杂度:O(n)
=== #link(
"https://leetcode.cn/problems/minimum-operations-to-halve-array-sum/",
)[题目3: 将数组和减半的最少操作次数]
给你一个正整数数组 `nums` 。每一次操作中,你可以从 `nums` 中选择 任意
一个数并将它减小到 *恰好*
一半。(注意,在后续操作中你可以对减半过的数继续执行操作)
请你返回将 `nums` 数组和 至少 减少一半的 最少 操作数。
#example(
"Example",
)[
- 输入:`nums = [5,19,8,1]`
- 输出:`3`
- 解释:初始 nums 的和为 `5 + 19 + 8 + 1 = 33` 。
以下是将数组和减少至少一半的一种方法:
- 选择数字 `19` 并减小为 `9.5` 。
- 选择数字 `9.5` 并减小为 `4.75` 。
- 选择数字 `8` 并减小为 `4` 。
- 最终数组为 `[5, 4.75, 4, 1]` ,和为 `5 + 4.75 + 4 + 1 = 14.75` 。
- `nums` 的和减小了 `33 - 14.75 = 18.25` ,减小的部分超过了初始数组和的一半,`18.25 >= 33/2 = 16.5` 。
- 我们需要 `3` 个操作实现题目要求,所以返回 `3` 。
- 可以证明,无法通过少于 `3` 个操作使数组和减少至少一半。
]
#tip("Tip")[
`1 <= nums.length <= 10^5`
`1 <= nums[i] <= 10^7`
]
==== 解答
#code(caption: [题目3: 将数组和减半的最小操作数])[
```java
public class Code03_MinimumOperationsToHalveArraySum {
public static int halveArray(int[] nums) {
PriorityQueue<Double> heap = new PriorityQueue<>((a, b) -> b.compareTo(a));
double sum = 0;
for (int i = 0; i < nums.length; i++) {
heap.add((double) nums[i]);
sum += nums[i];
}
double target = sum / 2;
int ans = 0;
double cur = 0;
for (double minus = 0; minus < target; minus += cur) {
cur = heap.poll() / 2;
heap.add(cur);
ans++;
}
return ans;
}
public static int MAXN = 100001;
public static long[] heap = new long[MAXN];
public static int size;
public static int halveArray2(int[] nums) {
size = nums.length;
long sum = 0;
for (int i = size - 1; i >= 0; i--) {
heap[i] = (long) nums[i] << 20;
sum += heap[i];
heapify(i);
}
sum /= 2;
int ans = 0;
for (long minus = 0; minus < sum; ans++) {
heap[0] /= 2;
minus += heap[0];
heapify(0);
}
return ans;
}
public static void heapify(int i) {
int l = i * 2 + 1;
while (l < size) {
int best = l + 1 < size && heap[l + 1] > heap[l] ? l + 1 : l;
best = heap[best] > heap[i] ? best : i;
if (best == i) {
break;
}
swap(best, i);
i = best;
l = i * 2 + 1;
}
}
public static void swap(int i, int j) {
long tmp = heap[i];
heap[i] = heap[j];
heap[j] = tmp;
}
}
```
]
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/spread-14.typ | typst | Other | #{
let f(..a, b, c, d) = none
// Error: 4-10 missing argument: d
f(1, 2)
}
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/show-closure-paren-complex.typ | typst | Apache License 2.0 | #show raw.where(block: false): it => if it.text.starts-with("<") and it.text.ends-with(">") {
set text(1.2em)
doc-style.show-type(it.text.slice(1, -1))
} else {
it
}
|
https://github.com/jakobjpeters/Typstry.jl | https://raw.githubusercontent.com/jakobjpeters/Typstry.jl/main/HISTORY.md | markdown | MIT License |
# History
## v0.3.0
### Strings
- `context`
- New default setting `backticks = 3` used for Typst `raw` blocks
- The `indent` setting is now `tab_size = 2`, to correspond with Typst's default parameter
- `show_typst`
- Implemented for `VersionNumber`, `Dates.Date`, `Dates.DateTime`, `Dates.Period`, `Dates.Time`, `Docs.HTML`, `LaTeXStrings.LaTeXString`, and `Markdown.MD`
- `AbstractFloat`, `Irrational`, and `Signed` in `markup` mode are now enclosed in dollar signs
- `Bool` in `markup` mode is no longer prefixed by a number sign
- An `AbstractChar` and `AbstractString` in `code` and `math` mode is no longer escaped and quoted
- A `Complex` is no longer parenthesized when one of the terms is zero
- Typst parameters are now printed on their own lines using the `indent` and `depth` settings
- Improved error handling for interpolating incomplete expressions into a `@typst_str`
### Commands
- The `preamble` used at the beginning of Typst source files is now exported
- `render` now supports a custom `preamble`
- The `show` method with the `application/pdf`, `image/png`, and `image/svg+xml` MIME types now supports
- A custom `preamble`
- `Typst` and `TypstText`
- Removed an unnecessary `TypstCommand` constructor
## Bug Fixes
- `@typst_str`
- No longer errors during interpolation when `TypstString` isn't loaded
- Handles interpolation and escaped interpolation in the same manner as a `String`
- `@typst_str` syntax and pretty-printing with `show(::IO, ::TypstString)` now correspond
- `show_typst`
- `AbstractFloat` values that satisfy `isinf` and `isnan` now correspond to `calc.inf` and `calc.nan`, respectively
- `AbstractString` and `Docs.Text` no longer escape dollar signs
- Removed incorrect special formatting of `Docs.Text` in `markup` mode
- A `@typst_cmd` with no parameters no longer inserts an empty parameter
## v0.2.0
### Strings
- Pass formatting configuration to a `TypstString` with keyword parameters instead of `Pair{Symbol}`s
- Remove type piracy of `show` with the `text/typst` MIME type
- Values may instead be wrapped in `Typst`
- Formatting may be configured by implementing a custom `context`
- Support `show(::IO, ::MIME"application/pdf", ::TypstString)`
- Replace `typst_text` constructor with the `TypstText` wrapper
- `show_typst`
- Implement `show_typst(x)`, which prints to `stdout`
- Implemented for `AbstractArray`, `Complex{Bool}`, `Tuple`, `Typst`, `TypstText`, and `Unsigned`
- `Nothing` now corresponds to the Typst `none`
- `AbtractMatrix` and `AbstractVector` in `code` mode now correspond to a Typst array
- `OrdinalRange{<:Integer, <:Integer}` and `StepRangeLen{<:Integer, <:Integer, <:Integer}`
- `code` mode implicitily uses the Typst default `step` if it is equal to `1`
- `markup` and `math` mode now correspond to a Typst vector
- The `Docs.Text` format is simpler in `markup` mode
- This introduced a bug, which is patched in v0.3.0
- New default setting `parenthesize = true`
- Used for `Complex` and `Rational`
- Rename the `inline` setting to `block` for consistency with Typst's `equation` function
- This toggles the default behavior, which is now inline
### Commands
- Easily `render` a Julia value to a Typst source file and compiled document
- Increase coverage of the `Cmd` interface implementation for `TypstCommand`
- Improve error handling
- The Typst compiler prints error messages to `stderr`
- If not `ignorestatus`, a Typst compiler error will throw a Julia `TypstError`
### Bug Fixes
- Patch an assumption in `repr(::MIME, ::AbstractString)` that is incorrect for `TypstString`
- Format values in containers using `show(::IO, ::MIME"text/typst", ::Typst)`
- `show_typst(io, ::AbstractString)` now correctly escapes double quotation marks ~~and dollar signs~~.
- `show_typst(io, ::Complex)`
- Fix `Complex{Bool}`
- Handle negative imaginary part
## v0.1.0
### Strings
- `show_typst` prints a value in Typst format, with Julia settings and Typst parameters given in an `IOContext`
- Implemented for `AbstractChar`, `AbstractFloat`, `AbstractMatrix`, `AbstractString`, `AbstractVector`, `Bool`, `Complex`, `Irrational`, `Nothing`, `OrdinalRange{<:Integer, <:Integer}`, `Rational`, `Regex`, `Signed`, `StepRangeLen{<:Integer, <:Integer, <:Integer}`, `Text`, and `TypstString`
- `show(::IO, ::MIME"text/typst", ::Any)` provides default settings to `show_typst`
- `Mode` is used to specify the current Typst context in `show_typst`
- `TypstString` is an `AbstractString` implementing the `String` interface and uses `show(::IO, ::MIME"text/typst", ::Any)` to print values to Typst format
- `@typst_str` constructs `TypstString`s and supports formatted interpolation
- `typst_text` constructs a `TypstString` using `print` instead of `show(::IO, ::MIME"text/typst", ::Any)`
- `show(::IO, ::Union{MIME"image/png", MIME"image/svg+xml}, ::TypstString)` renders a `TypstString` and prints it in PNG or SVG format
### Commands
- `TypstCommand` implements the `Cmd` interface and represents the Typst compiler
- `@typst_cmd` constructs `TypstCommand`s
- `julia_mono` is an artifact containing the [JuliaMono](https://github.com/cormullion/juliamono) typeface, which may be used in rendered Typst documents
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/wire/mode/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 0pt)
#import "/src/quill.typ": *
#quantum-circuit(
gate($H$), slice(), setwire(2), gate($X$), setwire(0), meter(), [\ ],
setwire(0), gate($X$), setwire(1), 1, setwire(2), gate($X$),1, [\ ],
1, setwire(1, stroke: (paint: blue, dash: "dash-dotted", thickness: .7pt, )), 1, setwire(2),1, [\ ],
1, [\ ],
2, setwire(2), 1, setwire(3), 1, setwire(4), 1, setwire(5), 1
)
#pagebreak()
#quantum-circuit(
2, setwire(1, stroke: blue), 1, setwire(1, stroke: 1pt), 1, setwire(1, stroke: red), setwire(1, stroke: stroke(dash: "dotted")), 1, setwire(2), 1, setwire(2, wire-distance: 2pt), 1, setwire(2, stroke: stroke(dash: "solid")), 1
) |
https://github.com/Steendly/Jeu-Dames | https://raw.githubusercontent.com/Steendly/Jeu-Dames/master/rapport/rapport.typ | typst | #import "@preview/fletcher:0.4.2" as fletcher: node, edge
#import "/templates/base_formatting.typ": project, heading_1, heading_2, commented_text
#import "/templates/algo.typ": algo, i, d, comment, shell
#show: project.with(
title: "Jeu de Dames",
subtitle: "Implémentation et résolution avec différents algorithmes",
authors: (
(name: "Steendly",
email: "<EMAIL>"),
),
abstract: [
Le code source de ce projet est disponible sur : \
#link("https://github.com/Steendly/Jeu-Dames/") \
]
)
#heading_1("Introduction")
Ce projet est réalisé dans le cadre d'un projet de fin d'année en NSI en terminal. Son but est d'implémenter le jeu de Dames dans sa #link("https://en.wikipedia.org/wiki/Brazilian_draughts")[variante Brésilienne] avec des agents (aussi appelés "bots") jouant de manière autonome en utilisant plusieurs algorithmes, le tout en Python. L'objectif principal est avant tout de les réimplémenter de zéro, mettant ainsi l'accent sur l'algorithmique. Pour cela, la réalisation de ce projet divisé en deux grandes parties.
La première partie est la création du moteur de jeu. Il suit les règles officielles du jeu de Dames qui sont les suivantes :
« Le jeu se joue à deux joueurs sur un plateau 8x8, chaque joueur dispose de 12 pièces. À chaque tour, vous devez vous déplacer vers une case vide, si vous pouvez capturer une pièce, vous devez effectuer ce mouvement.
Un mouvement fonctionne comme suivant :
- Vous avancez une pièce en diagonale vers une case vide. Vous ne pouvez pas déplacer une pièce en diagonale vers l'arrière tant qu'elle n'est pas promue roi. Si vous pouvez capturer une pièce, vous devez effectuer ce mouvement.
Un saut fonctionne comme suivant :
- Si une pièce adverse se trouve sur une case en diagonale à côté d'une de vos pièces et que l'espace au-delà est vide, alors vous devez sauter par-dessus la pièce adverse, la capturer et atterrir dans l'espace au-delà.
- Si un autre saut est disponible après avoir effectué un saut, vous devez alors sauter à nouveau et capturer la pièce suivante. Vous devez continuer à sauter jusqu'à ce qu'il n'y ait plus de sauts disponibles.
- Une pièce capturée est retirée du plateau.
- Si plusieurs pièces peuvent sauter, vous pouvez choisir la pièce sur laquelle vous souhaitez sauter.
Un couronnement fonctionne comme suivant :
- Lorsqu'une de vos pièces atteint le côté opposé du plateau, elle est couronnée et promue Roi.
- Un roi peut se déplacer en diagonale d'avant en arrière, il ne peut se déplacer que d'une case à la fois.
- Un Roi peut aussi sauter en avant et en arrière, il doit effectuer le saut disponible »
Cependant, dans cette version toutes les règles ne sont pas encore implémentées. Seul le mouvement d'une case vers une autre et la simple prise d'un pion adverse sont fonctionnelles. Les autres règles telles que le couronnement, l'obligation de capturer une pièce pouvant l'être ou encore la capture de plusieurs pions adverses à la suite ne le sont pas.
La deuxième partie est l'implémentation d'un système de joueurs et d'agents autonomes. Il s'agit de la partie principale. Le système de joueur désigne l'ensemble des classes qui permettront à un joueur humain ou non de jouer. Les agents désignent quant à eux les différentes classes jouant de manière autonomes. Pour le moment, trois d'entre eux sont mis en place :
- RandomBot : un agent renvoyant un coup aléatoire à jouer
- MinMaxBot : un agent utilisant l'algorithme MinMax
- Albator : un agent utilisant l'algorithme MinMax et l'élagage alpha-beta
De plus, ces deux parties ont une conception orientée objet afin d'avoir une plus grande modularité, particulièrement au niveau des agents, qui suit cette structure générale :
#shell(```sh
└── code
└── src
├── game_engine
│ ├── board.py
│ ├── game.py
│ └── gui.py
├── main.py
├── players
│ ├── bots
│ │ ├── algorithms
│ │ │ ├── alpha_beta.py
│ │ │ └── minmax.py
│ │ ├── bot.py
│ │ └── training.py
│ └── player.py
└── utils.py
```)
- code/ : Dossier contenant le code et tout ce qui lui est relatif.
- src/ : Dossier contenant (principalement) tout le code en Python.
- game_engine/ : Module du gestion moteur de jeu.
- players/ : Module de gestion des joueurs (humains et bots).
- utils.py : Contiendra toutes les fonctions utilitaires.
Les outils utilisés sont/seront les suivants :
- Langage de programmation : Python 3 (≥ 3.10)
- Environnement de développement : Linux
- Gestionnaire de version : Git (hébergé sur Github)
Le plan de ce rapport suit ces deux grandes parties. Nous aborderons dans un premier temps l'implémentation du moteur de jeu pour finir sur le système de joueurs et d'agents.
#commented_text[
Ce projet n'est pas finalisé de même que ce rapport. Certaines sources ne sont pas créditées, mais le seront prochainement. Merci de votre compréhension.
]
#heading_1("Première partie", subtitle: "Moteur de jeu")
#heading_2("Introduction")
Le moteur de jeu est le pilier fondamental de tout logiciel de jeu. Dans cette première phase de notre projet, nous avons élaboré un moteur de jeu pour permettre à la fois aux joueurs humains et aux agents autonomes de participer au jeu de dames. Ce rapport vise à expliciter l'importance de chaque fonctionnalité implémentée dans ce moteur de jeu, ainsi que les valeurs d'entrées et de sorties associées à chacun des composants.
#commented_text[
Le moteur de jeu n'ayant pas été finalisé, cette partie du rapport n'est pour l'instant pas rédigée.
]
#heading_1("Deuxième partie", subtitle: "Système de joueurs et agents")
#heading_2("Généralités")
La deuxième partie concerne le système de joueurs et l'implémentation des agents.
Le système de joueur désigne l'ensemble des classes permettant à un joueur humain ou non de jouer. Il s'agira des classes de plus "bas niveau" qui interagiront avec le moteur de jeu. Elles viendront en quelque sorte se greffer par-dessus. Les agents désignent quant à eux les classes implémentées jouant de manière autonomes. Ils jouent un coup en suivant un algorithme donné. Plusieurs agents sont implémentés :
- RandomBot : un agent renvoyant un coup aléatoire à jouer
- MinMaxBot : un agent utilisant l'algorithme MinMax
- Albator : un agent utilisant l'algorithme MinMax et l'élagage alpha-beta
Le développement des agents MinMaxBot et Albator sont le cœur de cette partie. Il s'agit d'implémenter plusieurs algorithmes en utilisant le moins de modules externes possibles :
- #link("https://fr.wikipedia.org/wiki/Algorithme_minimax")[MinMax]: en théorie des jeux, c'est un algorithme visant à évaluer les différents coups possibles à jouer pour choisir le meilleur en supposant que le joueur adverse choisira le pire coup pour nous au prochain tour. Cela peut être modélisé via un arbre de décision à plusieurs nœuds. Il est utilisé dans des jeux à deux joueurs, comme dans notre cas les Dames ou encore les échecs.
- #link("https://fr.wikipedia.org/wiki/%C3%89lagage_alpha-b%C3%AAta")[Élagage alpha-bêta] : en théorie des jeux et en intelligence artificielle, c'est un algorithme permettant de réduire le nombre de nœuds a évaluer par l'algorithme MinMax dans son arbre de décision.
Tout le code correspondant sera regroupé dans le fichier nommé "players". Voici sa structure :
#shell(```sh
├── players
│ ├── bots
│ │ ├── algorithms
│ │ │ ├── alpha_beta.py
│ │ │ └── minmax.py
│ │ └── bot.py
│ └── player.py
```)
- players/ : Module de gestion des joueurs (humains et bots).
- player.py : Implémentation de(s) classe(s) pour les joueurs humains.
- bots/ : Sous module de gestion des bots.
- bot.py : Fichier regroupant les classes principales de tous les futurs bots
- algorithms/ : Sous module de gestion des algorithmes pour les bots
- alpha_beta.py : Implémentation de l'élagage alpha-bêta
- minmax.py : Implémentation de l'algorithme MinMax
La suite de cette partie est divisée en trois autres sous-parties :
- Le système de joueurs
- L'agent RandomBot
- L'agent MinMaxBot
- L'agent Albator
#heading_2("Le système de joueurs")
Le système de joueurs permet à n'importe quel joueur humain ou agent de jouer. Elle est en réalité assez minimaliste. Voici son diagramme « UML » simplifié :
#figure(
block(
image("/annexes/player_system_diagram.png", width: 100%),
stroke: 0.5pt,
inset: 1em
),
caption: "Diagramme UML simplifié du système de joueurs"
)
La classe BasePlayer est au cœur de ce système. Elle modélise un joueur quelconque avec quelques attributs de bases. Les classes HumanPlayer, RandomBot, MinMaxBot et Albator sont ses enfants et modélisent les joueurs suivants :
- HumanPlayer : un joueur humain qui entre ses coups via l'entrée standard
- RandomBot : l'agent qui joue un coup aléatoire parmi les coups possible à jouer
- MinMaxBot : l'agent qui joue en utilisant l'algorithme MinMax
- Albator : l'agent qui joue en utilisant l'algorithme MinMax et l'élagage alpha-beta
Tous les joueurs (donc la classe BasePlayer) possèdent comme attributs :
- nom (string) : le nom du joueur
- plateau (Board) : le plateau de jeu sur lequel joue le joueur
- valeur_pion(int) : la valeur du jouer, 1 pour les blancs et -1 pour les noirs
Et comme méthode :
- joue() : fonction renvoyant le coup joué par le joueur
Ils sont construits en suivant ce principe : un coup est constitué de deux cases, la case d'origine et la case de destination. Prenons un exemple pour comprendre et considérons le coup du joueur blanc entouré en blanc :
#grid(columns: 2, rows: 20em, column-gutter: 1em,
figure(
block(
image("/annexes/board_1.png"),
stroke: 3pt
),
caption: "Exemple coup sur plateau de jeu"
),
align(horizon)[
#text()[
La case d'origine (entouré en rouge) a pour coordonnées (5, 2), et la case de destination (4, 3) avec en x le numéro de la colonne et en y le numéro de la ligne.
]
]
)
\ La méthode "joue()" renvoie alors dans des couples les coordonnées de la case d'origine et de la case de destination : (x_origine, y_origine), (x_destination, y_destination).
Quant à l'exécution d'une partie, le système de joueur se comporte de la manière suivante :
- GameEngine appelle les méthodes "set_jeu(…)" des joueurs pour mettre à jour le joueur qu'ils sont et la plateau sur lequel ils vont jouer
- GameEngine appelle ensuite à tour de rôle jusqu'a la fin de la partie les méthodes "joue()" des joueurs et applique leur coup sur le plateau s'il est valide
#heading_2("L'agent RandomBot")
L'agent RandomBot est très simpliste : il se contente de retourner un coup au hasard parmi la liste des coups possibles sur le plateau. Ses chances, de remporter une partie sont donc très variables bien que très faible face à un quelconque joueur avec un minium de stratégie. Ses performances sont évidemment catastrophiques. Dans la prochaine version, il serait intéressant de mesurer sa probabilité de remporter une partie face à l'agent MinMaxBot et Albator.
Pour retourner un coup aléatoire, c'est-à-dire un couple (case_origine, case_destination) il choisit dans un premier temps une case d'origine aléatoire dans la liste des coups possible et ensuite une case de destination dans la liste des cases de destination de cette case d'origine.
Pour rappel, voici un exemple de la liste des coups possible accessible via la méthode get_coups_possible(joueur=…) de la classe Board pour ce plateau de jeu :
#grid(columns: 2, rows: 20em, column-gutter: 1em,
figure(
block(
image("/annexes/board_2.png", width: 100%),
stroke: 3pt
),
caption: "Exemple plateau de jeu"
),
shell(```sh
{
joueur_blanc :
{
(5, 0): [(4, 1)],
(5, 2): [(4, 1), (4, 3)],
(5, 4): [(4, 3), (4, 5)],
(5, 6): [(4, 5), (4, 7)]
},
joueur_noir :
{
(2, 1): [(3, 0), (3, 2)],
(2, 3): [(3, 2), (3, 4)],
(2, 5): [(3, 4), (3, 6)],
(2, 7): [(3, 6)]
}
}
```, adaptive: true),
)
#heading_2("L'agent MinMaxBot")
L'agent MinMaxBot implémente l'algorithme MinMax. Avant de rentrer dans le vif du sujet, voyons ce qu'est l'algorithme MinMax :
MinMax est un algorithme s'appliquant aux jeux à deux joueurs, à somme nulle et à informations complète. Un jeu à deux joueurs est simplement un jeu ou deux entités s'affrontent. Un jeu à somme nulle est un jeu où la somme des gains et des pertes de tous les joueurs est égale à 0. Cela signifie donc que le gain d'un joueur constitue obligatoirement une perte pour l'autre. Par exemple, dans une partie de morpion, si on définit la valeur de la grille à 1 si on gagne, -1 si on perd et 0 s'il y a égalité, ce jeu est à somme nulle (1 - 1 + 0 = 0). Les gains d'un joueur sont exactement l'opposé de ceux de l'autre joueur. Un jeu à informations complète, quant à lieu, est un jeu ou toutes les données sur la partie en cours sont entièrement accessible à tous les joueurs. Chaque joueur connaît précisément : ses possibilités d'action, les possibilités d'action de son adversaire et les gains résultants de ces actions. Par exemple, les échecs sont un jeu à informations complètes, car tous les joueurs peuvent savoir où se trouvent toutes les pièces. Au contraire, la bataille navale n'est pas un jeu à information complète, car un joueur ne sait pas où se trouvent les bateaux de son adversaire sur la grille.
L'algorithme MinMax, dû à #link("https://en.wikipedia.org/wiki/John_von_Neumann")[<NAME>ann], consiste à passer en revue toutes les possibilités pour un nombre limité de coups ou non, et à leur assigner une valeur qui prend en compte ses bénéfices et ceux de son adversaire. Le meilleur choix est alors celui qui minimise ses pertes tout en supposant que son adversaire cherche au contraire à maximiser nos pertes, d'où l'appellation MinMax.
Ceci peut être modélisé par un arbre de jeu constitué de nœuds joueur et opposant. Les nœuds s'alternent, de telle sorte qu'un nœud joueur a comme enfant un nœuds opposant, et inversement, que l'on obtient à partir des différents coups disponibles. Si un nœud n'a pas de enfant, c'est un nœud terminal, dit une "feuille". D'une certaine façon, cet arbre contient tous les coups possibles que l'on peut jouer à partir d'une position initiale. Si on a la possibilité d'explorer tout l'arbre, on peut déterminer s'il existe une stratégie gagnante pour un joueur. Si l'arbre est trop important on se contente normalement d'explorer le sous-arbre obtenu en tronquant l'arbre de jeu à une certaine profondeur, et en évaluant les nœuds tronqués à l'aide d'une fonction d'évaluation (fonction heuristique).
Voici un arbre de jeu associé à l'algorithme MinMax :
#figure(
block(
image("/annexes/diag_1.png", width: 100%),
stroke: 0.5pt,
inset: 1em
),
caption: "Arbre de jeu MinMax"
)
Cet arbre est composé de :
- D'un nœud racine représentant la configuration de jeu à analyser.
- De nœuds enfants qui représentent chacun une configuration du jeu atteignable depuis le nœud racine.
- De branches qui symbolisent les coups possibles dans une configuration données.
- De feuilles qui représentent chacune une configuration finale du jeu.
A chaque feuille (état/configuration finale du jeu) est associée une valeur :
- Positive (généralement) en cas de victoire.
- 0 en cas d'égalité.
- Négative (généralement) en cas de défaite.
Voici un exemple :
#figure(
block(
image("/annexes/diag_2.png", width: 100%),
stroke: 0.5pt,
inset: 1em
),
caption: "Exemple arbre de jeu MinMax"
)
Les nœuds C sont des feuilles et correspondent au joueur cherchant à minimiser ses pertes, le "minimizing player" appelé précédemment le "joueur". Leurs valeurs sont calculées par une fonction d'évaluation. Les nœuds B quant à eux, correspondent au joueur cherchant à maximiser les pertes de son adversaire, le "maximizing player", nommé avant l' "opposant".
Le "minimizing player" dans les sous-arbres contenant les nœuds C1 à C3 et C4 à C9 va choisir leur plus petite valeur et la faire remonter au nœud parent, respectivement B1 et B2.
Ensuite, le "maximizing player" va choisir la plus grande valeur entre ces deux nœuds et la faire remonter au nœud parent étant A1, le nœud racine.
Ainsi, il est possible de donner une valeur à un coup/un état/une position du jeu.
En pratique, explorer tous les sous-arbres d'un état du jeu prendrait dans le cas du jeu de Dames trop de temps. En conséquence, une fonction d'évaluation sera appliquée sur des positions non terminales. On considérera que plus la fonction d'évaluation est appliquée loin de la racine, meilleur est le résultat du calcul. C'est-à-dire qu'en examinant plus de coups successifs, nous supposons obtenir une meilleure approximation de la valeur théorique donc un meilleur choix de coup.
Comme dit précédemment, l'algorithme MinMax est très simple (d'un point de vue théorique) : on parcourt l'arbre du jeu jusqu'à un certain nœud (une certaine profondeur) ou jusqu'aux feuilles pour faire remonter à la racine la meilleur valeur du coup à jouer. Ceci de manière récursive.
Voici une implémentation en pseudo-code de cet algorithme avec une profondeur limitée :
#algo(
title: "minmax",
parameters: ("node", "depth", "maximizingPlayer",)
)[
if $"depth" = 0$ or $"node is a terminal node"$:#i\
return the heuristic value of node#d\
if $"maximizingPlayer"$:#i\
$"value" <- "−∞"$\
for each child of node:#i\
$"value" <- "max(value, minimax(child, depth - 1, FALSE))"$#d#d\
else:#i\
$"value" <- "+∞"$\
for each child of node:#i\
$"value" <- "min(value, minimax(child, depth - 1, TRUE))"$#d#d\
return value
]
Revenons à notre agent MinMaxBot. L'implémentation de l'algorithme MinMax est en réalité gérée par la classe MinMax. Elle à comme attributs :
- plateau (Board) : Le plateau de jeu à évaluer
- joueur_actuel (int) : Le joueur qui doit actuellement jouer sur ce plateau
- profondeur (int) : La hauteur du graphe des coups testés (le nombre de coups successifs à tester)
Et comme méthodes :
- evaluate_node() : Retourne la valeur heuristique du plateau actuel (fonction d'évaluation)
- #text("_")evaluate(...) : Retourne récursivement la valeur d'un plateau en suivant l'algorithme MinMax
- evaluate() : Initialise l'appel de #text("_")evaluate et retourne sa valeur
La méthode evaluate_node() est la fonction d'évaluation. Elle a pour responsabilité d'évaluer l'état du plateau. Les performances de l'agent dépende grandement d'elle. Actuellement, elle se contente de faire la différence entre le nombre de pions blancs et le nombre de pions noirs. L'implémentation de sa futur nouvelle version est discuté deux chapitres plus bas. Dans cette situation, le joueur blanc cherché alors à maximiser sa valeur tandis que le joueur noir cherché à la minimiser.
La méthode #text("_")evaluate(…) quant à elle implémente l'algorithme MinMax de façon récursive en suivant son implémentation en pseudo-code vu ci-dessus.
Et enfin, la méthode evaluate() initialise simplement l'appel de la fonction #text("_")evaluate(...). Si l'attribut joueur_actuel vaut 1, alors #text("_")evaluate(…) est appelé avec le paramètre maximizing_joueur à True, et sinon à False.
L'agent MinMaxBot fait donc appel à la classe MinMax pour calculer les valeurs de chaque coup possible sur le plateau. Voici le pseudo-code de sa méthode joue() :
#algo(
title: "joue",
parameters: ("plateau", "profondeur", "joueur_actuel",)
)[
valeurs_coups $<-$ {}\
for each coup in liste_coups_possible:#i\
plateau.joue(case_origine=coup[0], case_destination=coup[1])\
valeurs_coups[coup] $<-$ MinMax(plateau=plateau, profondeur=profondeur, joueur_actuel=joueur_actuel).evaluate()\
plateau.joue(case_origine=coup[1], case_destination=coup[0])#d\
if joueur_actuel is white:#i\
return max(valeurs_coups)#d\
else:#i\
return min(valeurs_coups)
]
Regardons un exemple d'extrait d'exécution de l'algorithme MinMax avec les paramètres depth à 3, un plateau de taille 4 et maximizing_player à True. Ceci correspond à un début de partie avec l'agent MinMax en tant que joueur blanc :
#figure(
block(
image("/annexes/minmax_1.png"),
stroke: 0.5pt,
inset: 1em
),
caption: "Exemple d'exécution MinMax"
)
#heading_2("L'agent Albator")
L'élagage alpha-bêta est un algorithme permettant de réduire le nombre de nœuds évalué par l'algorithme MinMax. Cela permet d'évaluer un arbre de jeu plus rapidement. Il élague ces branches qui n'ont pas besoin d'être recherchées, car il existe déjà un meilleur coup disponible. Dit autrement, l'élagage alpha-bêta permet de ne pas évaluer les nœuds enfants dont on peut penser, si la fonction d'évaluation est assez correcte, que leur valeur sera inférieur à celle du nœud parent déjà évalué. Il est important de comprendre qu'une fonction d'évaluation parfaite (comme par exemple au jeu des allumettes) ne demanderait pas de parcourir un arbre de jeu pour déterminer la valeur d'un coup. C'est justement parce qu'aucune fonction d'évaluation parfaite n'existe au jeu de Dames que l'emploi de l'algorithme MinMax et de l'élagage alpha-bêta est pertinent.
L'élagage alpha-bêta ajoute deux paramètre à l'algorithme MinMax :
- Alpha : La meilleure valeur que le "maximizing_player" peut actuellement garantir à cette profondeur ou au-dessus.
- Bêta : la meilleure valeur que le "minimizing_player" peut actuellement garantir à cette profondeur ou au-dessus.
Voici la fonction MinMax avec l'élagage alpha-bêta implémenté en pseudo-code :
#algo(
title: "alphabeta",
parameters: ("node", "depth", "maximizingPlayer", "alpha", "beta",)
)[
if depth = 0 or node is a terminal node:#i\
return the heuristic value of node#d\
if maximizingPlayer:#i\
best_value $<-$ −∞\
for each child of node:#i\
value $<-$ alphabeta(child, depth - 1, FALSE, alpha, beta)\
best_value = max(best_value, value)\
alpha = max(alpha, best_value)\
if beta <= alpha:#i\
break#d#d\
return best_value#d\
else:#i\
best_value $<-$ +∞\
for each child of node:#i\
value $<-$ alphabeta(child, depth - 1, TRUE, alpha, beta)\
best_value = min(best_value, value)\
alpha = min(alpha, best_value)\
if beta <= alpha:#i\
break#d#d\
return best_value#d\
]
Voici un exemple :
#figure(
block(
image("/annexes/alphabeta_1.png"),
stroke: 0.5pt,
inset: 1em
),
caption: "Exemple AlphaBeta n°1"
)
- L'appel initial commence par A. La valeur d'alpha est ici -∞ et la valeur de beta est +∞. Ces valeurs sont transmises aux nœuds suivants de l'arborescence. En A, le "maximizing_player" doit choisir max de B et C, donc A appelle B en premier.
- En B dit, le "minimizing_player" doit choisir min de D et E et appelle donc D en premier.
- En D, il regarde son enfant à gauche qui est un nœud feuille. Ce nœud renvoie une valeur de 3. Maintenant, la valeur de alpha en D est max( -∞, 3) qui est 3.
- Pour décider s'il vaut la peine de regarder son nœud droit ou non, il vérifie la condition beta <= alpha. C'est faux puisque beta = +∞ et alpha = 3. Il continue donc la recherche.
- D regarde maintenant son nœud enfant droit qui renvoie une valeur de 5. À D, alpha = max(3, 5) qui est 5. Maintenant, la valeur du node D est 5.
- D renvoie une valeur de 5 à B. À B, beta = min(+∞, 5) qui est 5. Le "minimizing_player" est garanti maintenant une valeur de 5 ou moins. B appelle E pour voir s'il peut obtenir une valeur inférieure à 5.
- En E, les valeurs d'alpha et de bêta ne sont pas -∞ et +∞ mais plutôt -∞ et 5 respectivement, car la valeur de bêta a été modifiée en B. C'est ce que B a transmis à E.
- Maintenant E regarde son enfant à gauche qui vaut 6. À E, alpha = max(-∞, 6) qui est 6. Ici la condition devient vraie. beta vaut 5 et alpha vaut 6. Donc beta <= alpha est vrai. Par conséquent, il s'arrête et E renvoie 6 à B.
- Notez que la valeur de l'enfant à droite de E n'a pas d'importance. Cela aurait pu être +∞ ou -∞, cela n'aurait toujours pas d'importance. Nous n'avons même jamais eu à le regarder car le "minimizing_player" était garanti d'une valeur de 5 ou moins. Ainsi, dès que le "maximizing_player" a valut 6, le "minimizing_player" ne viendrait jamais de cette façon car il peut obtenir un 5 sur le côté gauche de B. De cette façon, nous n'avons pas à regarder ce 9 et donc à gagner du temps de calcul.
- E renvoie une valeur de 6 à B. À B, beta = min(5, 6) qui est 5. La valeur du node B est également 5.
Jusqu'à présent, voici à quoi ressemble notre arbre de jeu. Le 9 est barré car il n'a jamais été calculé :
#figure(
block(
image("/annexes/alphabeta_2.png"),
stroke: 0.5pt,
inset: 1em
),
caption: "Exemple AlphaBeta n°2"
)
- B renvoie 5 à A. À A, alpha = max(-∞, 5) qui est 5. Maintenant, le "maximizing_player" est garanti d'avoir une valeur de 5 ou plus. A appelle maintenant C pour voir s'il peut obtenir une valeur supérieure à 5.
- À C, alpha = 5 et beta = +∞. C appelle F .
- À F , alpha = 5 et beta = +∞. F regarde son nœud enfant à gauche qui est un 1. alpha = max(5, 1) qui est toujours 5.
- F regarde son nœud enfant à droite qui est un 2. La meilleure valeur de ce nœud est donc 2. Alpha reste toujours 5.
- F renvoie une valeur de 2 à C. À C , bêta = min(+∞, 2). La condition beta <= alpha devient vraie quand beta = 2 et alpha = 5. Donc la recherche s'arrête et n'a même pas besoin de calculer tout le sous-arbre de G.
- L' "intuition" derrière cette rupture est qu'en C, le "minimizing_player" était garanti d'avoir une valeur de 2 ou moins. Mais le "maximizing_player" était déjà assuré d'avoir une valeur de 5 s'il choisissait B. Alors pourquoi le "maximizing_player" choisirait-il jamais C et obtiendrait-il une valeur inférieure à 2 ? Encore une fois, vous pouvez voir que peu importaient ces 2 dernières valeurs. Nous avons également économisé beaucoup de calculs en sautant tout un sous-arbre.
- C renvoie maintenant une valeur de 2 à A. Par conséquent, la meilleure valeur en A est max(5, 2) qui est un 5.
- Par conséquent, la valeur optimale que le "maximizing_player" peut obtenir est 5.
Voici à quoi ressemble notre arbre de jeu final. Comme vous pouvez le voir, G a été barré car il n'a jamais été calculé :
#figure(
block(
image("/annexes/alphabeta_3.png"),
stroke: 0.5pt,
inset: 1em
),
caption: "Exemple AlphaBeta n°3"
)
#heading_2("Fonction d'évaluation")
Nous avons vu précédemment que les algorithmes MinMax et l'élagage AlphaBeta avaient besoin de connaître la valeur d'un état du plateau. Si le nombre de coups possible est assez réduit, il est possible d'explorer tout l'arbre de jeu jusqu'aux feuilles pour savoir si un coup mène à une victoire, une égalité ou une défaite. Cependant, dans notre cas le nombre de possibilités est trop élevé, il n'est pas possible d'atteindre les feuilles dans un temps raisonnable. Seul une partie de l'arbre de jeu est explorée et les valeurs de ces derniers nœuds sont calculé à l'aide d'une fonction d'évaluation (aussi appelée fonction heuristique).
Une fonction d'évaluation est un algorithme qui fournit rapidement (en temps polynomial) une solution, pas nécessairement optimale, pour un problème d'optimisation. C'est le contraire d'un algorithme exact qui trouve une solution optimale pour un problème donné. En effet, le jeu de Dames dans sa variante Brésilienne n'a jamais encore été résolu au contraire de sa #link("https://citeseerx.ist.psu.edu/pdf/208122e877a967222093afa80f0f4c318f3ae63e")[variante Américaine] qui possède un algorithme de résolution exact.
Cette fonction sera la différence de la combinaison linéaire des différents paramètres de chaque joueurs suivants :
+ Le nombre de pions
+ Le nombre de pions protégé (non prenable par l'adversaire)
+ Le nombre de pions déplaçable
+ La distance cumulée des pions à la ligne de promotion (ligne la plus haute)
+ Le nombre de cases occupés sur sa ligne de promotion (ligne la plus basse)
+ Nombre de pions défensifs (ceux situés dans les deux rangées les plus basses)
+ Nombre de pions attaquants (ceux situés dans les deux rangées les plus hautes)
+ Nombre de pions positionnés au centre (sur les deux lignes centrales)
Le résultat de cette fonction est un nombre entier. Voici sa forme :
#algo(line-numbers: false)[
(a#sub[1] · param#sub[1] + ... + a#sub[j] · param#sub[j])#sub[joueur_blanc] - (a#sub[1] · param#sub[1] + ... + a#sub[j] · param#sub[j])#sub[joueur_noir]
]
Les paramètres param#sub[1], ..., param#sub[j] sont choisi parmi les paramètres ci-dessus, et nous utiliserons un algorithme génétique pour générer les coefficients a#sub[1], ..., a#sub[j].
Les algorithmes génétiques appartiennent à la famille des algorithmes évolutionnistes. Leur but est d'obtenir une solution approchée à un problème d'optimisation, lorsqu'il n'existe pas de méthode exacte (ou que la solution est inconnue) pour le résoudre en un temps raisonnable. Les algorithmes génétiques utilisent la notion de sélection naturelle et l'appliquent à une population de solutions potentielles au problème donné. La solution est approchée par « bonds » successifs. Chaque bond correspond à une génération.
Pour trouver la meilleur configuration des coefficients ci-dessus, des bots utilisant l'algorithme MinMax et l'élagage AlphaBeta s'affronteront les uns contre les autres à tour de rôle.
Les 50% des meilleurs de chaque génération (ceux ayant le plus de manches gagnées) seront conservés, et se reproduiront entre eux de la façon suivante avec en plus une chance de 15% de muter aléatoirement de 20% (qu'un coefficient augmente ou diminue de 20%) :
#figure(
block(
image("/annexes/genetic_reproduction.png", width: 70%),
stroke: 0.5pt,
inset: 1em,
width: 100%
),
caption: "Genetic reproduction"
)
La fonction d'évaluation est implémentée dans le module "src/players/bots/algorithms/heuristic.py" dans la classe Heuristic et la gestion de l'évolution génétique dans la classe Train dans le fichier "src/players/bots/training.py".
Il n'a pas été possible de faire de tests statistiques à cause du temps pris pour calculer ne serait-ce rien qu'une génération et de contrainte matériel. En effet, une partie sur un plateau de 8x8 dure environ 150 secondes. Calculer une génération de 8 bots prendrait alors environ 2h20...
#heading_2("Conclusion", break_ordering: true)
Ce projet aura été un défi tout au long de l'année. L'implémentation d'algorithmes tels que MinMax ou l'évolution génétique auront été très intéressants. Ils sont une belle introduction à la résolution de jeux par les machines.
Cette version du rapport à été rédigé avec #link("https://typst.app/")[Typst], une alternative à Latex en Rust. Pour suivre l'évolution, référez-vous au repo Git.
#heading_2("Annexes et bibliographie", break_ordering: true)
Pour parvenir à implémenter ces algorithmes nous avons plusieurs ressources à notre disposition (liste non-exhaustive) :
- #link("https://en.wikipedia.org/wiki/Minimax", text("Wikipédia_Minimax_[en]"))
- #link("https://fr.wikipedia.org/wiki/Algorithme_minimax", text("Wikipédia_MinMax_[fr]"))
- #link("https://fr.wikipedia.org/wiki/Théorème_du_minimax_de_von_Neumann", text("Wikipédia_Théorème_MiniMax_von_Neumann"))
- #link("https://www.youtube.com/watch?v=SLgZhpDsrfc", text("Minimax: How Computers Play Games"))
- #link("https://www.youtube.com/watch?v=l-hh51ncgDI", text("Algorithms Explained - minimax and alpha-beta pruning"))
- #link("https://www.youtube.com/watch?v=zp3VMe0Jpf8", text("Minimax with Alpha Beta Pruning"))
- #link("https://www.youtube.com/watch?v=STjW3eH0Cik", text("MIT - Minimax, and Alpha-Beta"))
- #link("https://www.enseignement.polytechnique.fr/profs/informatique/Jean-Christophe.Filliatre/14-15/MAN_Caml/td6/index.html", text("Polytechnique - Jeux sans hasard et modules"))
- #link("https://www.di.ens.fr/~granboul/enseignement/mmfai/algo2003-2004/tp5/", text("ENS - Les algorithmes MiniMax et alpha-beta"))
- #link("https://lucidar.me/fr/algorithmic/files/ANA_CM5__-_Algorithme_MinMax.pdf", text("Lucidarme - Algorithme MinMax"))
- #link("https://sifflez.org/misc/tronbot/index.html", text("University of Waterloo - Tron bot"))
- #link("https://stacklima.com/algorithme-minimax-en-theorie-des-jeux-ensemble-4-elagage-alpha-beta/", text("Stacklima (geekforgeek traduction) - Elagage Alpha-Beta"))
- #link("https://fr.wikipedia.org/wiki/Élagage_alpha-bêta#Améliorations_possibles", text("Wikipédia_Elagage_Alpha-Beta_[fr]"))
- #link("https://en.wikipedia.org/wiki/Alpha-beta_pruning", text("Wikipédia_Alpha-beta_pruning_[en]"))
- #link("https://pages.mini.pw.edu.pl/~mandziukj/PRACE/es_init.pdf", text("Evolutionary-based heuristic generators for checkers and give-away checkers"))
- #link("https://papersdb.cs.ualberta.ca/%7Epapersdb/uploaded_files/590/paper_ijcai05checkers.pdf", text("Solving Checkers"))
- #link("https://en.wikipedia.org/wiki/Genetic_algorithm", text("Wikipedia_Genetic_algorithm_[en]"))
- ...
|
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/ConsuntivoSprint/QuintoSprint.typ | typst | MIT License | #import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost
#import "../../functions.typ": rendicontazioneOreAPosteriori, rendicontazioneCostiAPosteriori, glossary
== Quinto #glossary[sprint]
*Inizio*: Venerdì 22/12/2023
*Fine*: Giovedì 28/12/2023
#rendicontazioneOreAPosteriori(sprintNumber: "05")
#rendicontazioneCostiAPosteriori(sprintNumber: "05")
=== Analisi a posteriori
Il consuntivo delinea un ritmo di lavoro stabile e simile a quanto preventivato, seppur il numero di ore effettive è leggermente calante rispetto agli #glossary[sprint] precedenti. Ciò è da attribuire sostanzialmente al periodo di festività e all'inizio della preparazione per la sessione di esami che riveste gli #glossary[sprint] 5 e 6. Da notare come le ore da Verificatore abbiano iniziato ad incrementare, in allineamento con gli obiettivi dello #glossary[sprint] che includono una revisione in stile #glossary[walkthrough] dell'_Analisi dei Requisiti_. Ormai è ancora più evidente come le ore da Amministratore predisposte inizialmente siano del tutto insufficienti a coprire le esigenze di sviluppo della #glossary[documentazione] del team allo stadio attuale, motivo per cui si è deciso di modificare il preventivo iniziale per accomodare un maggior numero di ore dedicate a tale ruolo. Si è anche notato che i preventivi realizzati all'inizio di ogni #glossary[sprint] dal Responsabile sono estremamente diversi rispetto a quelli realizzati come parte della pianificazione a lungo termine inclusa nel _Piano di Progetto_ a partire dallo #glossary[sprint] 2. Di conseguenza, il team ha deciso di rimuovere la pianificazione a lungo termine e sostituirla con una pianificazione a breve termine (2 #glossary[sprint] in avanti), oltre ad aggiungere pianificazione e preventivo per le tre #glossary[milestone] principali (le revisioni #glossary[RTB], #glossary[PB] e #glossary[CA]).
Visto il periodo di interesse, non sorprende che i rischi emersi siano: RC1 o Mancata organizzazione della comunicazione interna e RP4 o Impegni universitari. Per quanto riguarda RC1, non è stato gestito in maniera efficacie, in quanto sono venute meno le varie misure preventive atte ad evitarne la manifestazione e limitarne gli effetti:
- I canali di comunicazione utilizzati solitamente per mettere in evidenza e risolvere dubbi in modo tempestivo sono stati utilizzati meno di frequente e in modo meno collaborativo;
- L'#glossary[ordine del giorno] non è stato realizzato in quanto non è stato svolto un incontro interno al termine dello #glossary[sprint], vista la mancanza di disponibilità di vari componenti del team negli ultimi giorni dell'anno;
- Gli #glossary[Stand-up meeting] si sono decisamente rivelati una delle misure efficaci nel prevenire un disallineamento delle priorità dei componenti, tuttavia non è stato possibile effettuarli nel periodo appena trascorso vista l'interruzione delle lezioni e la conseguente impossibilità di interagire dal vivo.
In altre parole, non è stata l'inadeguatezza delle misure preventive a determinare la manifestazione del rischio quanto la loro mancata applicazione. In ogni caso, si è discusso di misure ulteriori da predisporre nei casi in cui non ci sia sufficiente comunicazione e collaborazione all'interno del team, quali #glossary[Stand-up meeting] giornalieri, anche da remoto, ed eventuali meeting di emergenza, con la possibilità di abbassare il #glossary[quorum] a 3/6 persone in caso di necessità.
|
https://github.com/sysu/better-thesis | https://raw.githubusercontent.com/sysu/better-thesis/main/specifications/bachelor/abstract-en.typ | typst | MIT License | // 利用 state 捕获摘要参数,并通过 context 传递给渲染函数
#import "/utils/style.typ": 字号, 字体
#let abstract-en-keywords = state("keywords-en", (
"Sun Yat-sen University",
"thesis",
"specification",
))
#let abstract-en-content = state("abstract-en", [
英文摘要及关键词内容应与中文摘要及关键词内容相同。中英文摘要及其关键词各置一页内。
The English abstract and its keywords should be the same as the Chinese one.
Both Chinese and English should be in seperated pages.
])
#let abstract-en(
keywords: (),
body,
) = {
context abstract-en-keywords.update(keywords)
context abstract-en-content.update(body)
}
// 英文摘要页
#let abstract-en-page() = {
// 英文摘要内容 Times New Roman小四号
set text(font: 字体.宋体, size: 字号.小四)
// 英文摘要标题 Times New Roman加粗三号全部大写
show heading.where(level: 1): set text(font: 字体.宋体, size: 字号.三号, weight: "bold")
// 摘要标题不编号
show heading.where(level: 1): set heading(numbering: none)
[
= ABSTRACT
#context abstract-en-content.final()
#v(1em)
// 摘要正文下方另起一行顶格打印“关键词”款项,后加冒号,多个关键词以逗号分隔。
// (标题“Keywords”加粗)
*Keywords:* #context abstract-en-keywords.final().join(", ")
]
}
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1E000.typ | typst | Apache License 2.0 | #let data = (
("COMBINING GLAGOLITIC LETTER AZU", "Mn", 230),
("COMBINING GLAGOLITIC LETTER BUKY", "Mn", 230),
("COMBINING GLAGOLITIC LETTER VEDE", "Mn", 230),
("COMBINING GLAGOLITIC LETTER GLAGOLI", "Mn", 230),
("COMBINING GLAGOLITIC LETTER DOBRO", "Mn", 230),
("COMBINING GLAGOLITIC LETTER YESTU", "Mn", 230),
("COMBINING GLAGOLITIC LETTER ZHIVETE", "Mn", 230),
(),
("COMBINING GLAGOLITIC LETTER ZEMLJA", "Mn", 230),
("COMBINING GLAGOLITIC LETTER IZHE", "Mn", 230),
("COMBINING GLAGOLITIC LETTER INITIAL IZHE", "Mn", 230),
("COMBINING GLAGOLITIC LETTER I", "Mn", 230),
("COMBINING GLAGOLITIC LETTER DJERVI", "Mn", 230),
("COMBINING GLAGOLITIC LETTER KAKO", "Mn", 230),
("COMBINING GLAGOLITIC LETTER LJUDIJE", "Mn", 230),
("COMBINING GLAGOLITIC LETTER MYSLITE", "Mn", 230),
("COMBINING GLAGOLITIC LETTER NASHI", "Mn", 230),
("COMBINING GLAGOLITIC LETTER ONU", "Mn", 230),
("COMBINING GLAGOLITIC LETTER POKOJI", "Mn", 230),
("COMBINING GLAGOLITIC LETTER RITSI", "Mn", 230),
("COMBINING GLAGOLITIC LETTER SLOVO", "Mn", 230),
("COMBINING GLAGOLITIC LETTER TVRIDO", "Mn", 230),
("COMBINING GLAGOLITIC LETTER UKU", "Mn", 230),
("COMBINING GLAGOLITIC LETTER FRITU", "Mn", 230),
("COMBINING GLAGOLITIC LETTER HERU", "Mn", 230),
(),
(),
("COMBINING GLAGOLITIC LETTER SHTA", "Mn", 230),
("COMBINING GLAGOLITIC LETTER TSI", "Mn", 230),
("COMBINING GLAGOLITIC LETTER CHRIVI", "Mn", 230),
("COMBINING GLAGOLITIC LETTER SHA", "Mn", 230),
("COMBINING GLAGOLITIC LETTER YERU", "Mn", 230),
("COMBINING GLAGOLITIC LETTER YERI", "Mn", 230),
("COMBINING GLAGOLITIC LETTER YATI", "Mn", 230),
(),
("COMBINING GLAGOLITIC LETTER YU", "Mn", 230),
("COMBINING GLAGOLITIC LETTER SMALL YUS", "Mn", 230),
(),
("COMBINING GLAGOLITIC LETTER YO", "Mn", 230),
("COMBINING GLAGOLITIC LETTER IOTATED SMALL YUS", "Mn", 230),
("COMBINING GLAGOLITIC LETTER BIG YUS", "Mn", 230),
("COMBINING GLAGOLITIC LETTER IOTATED BIG YUS", "Mn", 230),
("COMBINING GLAGOLITIC LETTER FITA", "Mn", 230),
)
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-autori/mornstajnova.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/helper.typ": autor
#autor("<NAME>", "1963", "", "spisovatelka", "Ostravská univerzita", "moderní romány", "/cj-autori/media/mornstajnova.jpg")
Narodila se ve #underline[Valašském Meziříčí]. Původně se chtěla stát překladatelkou, ale za režimu několikrát nebyla přijata na FF UK. Chvíli učila na jazykové škole, kdy vydala svoji první knihu. Od té doby se živí čistě psaním.
Za Hanu získala cenu kniha roku, dále pak jiné ceny za knihy Listopad a Tiché roky.
Její nedávná minulost je poskvrněná obviněním, že měla údajně zápletku svého románu Les v domě opsat od výtvarkyně Toy Box. Celá tato kauza je založena na faktu, že se v textech obou autor týká o znásilnění svým dědečkem a v pár dalších poměrně náhodných podobnostech. Mornštajnová byla nazvána "zlodějkou příběhů" a plagiátorem. Můj názor je takový, že se kolem toho vytvořila pěkně nafouknutá mediální bublina. Opravdu si nemyslím, že má tohle Mornštajnová zapotřebí.
Mezi jeho známá díla patří:
1. *Tiché roky* -- Zoufalý, depresivní příběh jedné zdánlivě obyčejné rodiny
2. *Listopád* -- Alternativní historie po listopadu 1989
*Současníci*\
_<NAME>_ -- Gazely, 2023\
_<NAME>_ -- V<NAME>, 2009\
_<NAME>_ -- Šikmý kostel, 2020\
_<NAME>_ -- Báječná léta pod psa (@pes[]), 1992
#pagebreak() |
https://github.com/suspenss/Undergraduate-mathematics | https://raw.githubusercontent.com/suspenss/Undergraduate-mathematics/main/mathmatics-analysis/main.typ | typst | #import "./../setup/templates.typ": *
#import "./../setup/theorem.typ": *
#show: thmrules
// #show math.equation: set text(font: "New Computer Modern Math")
// #show math.equation: set text(font: "Libertinus Math")
#show: project.with(
title: "Mathmatics Analysis", authors: ("epoche",), language: "ch", outl: [
#outline(indent: true, title: "目录", depth: 2)
],
)
#show math.ast: math.thin
#let obey = math.tilde
#let vb = $bold(beta)$
#let va = $bold(alpha)$
#let ve = $bold(e)$
#let tem = theorem
#let def = definition
#let prf = proof
#let emp = example
#let ant = annotation
#let pos = proposition
#let lem = lemma
#let prt = properties
#let axm = axiom
#align(center)[参考书目为 《陶哲轩实分析》]
#let align_enums = it => grid(columns : (1em, 1fr, 1em), [], [#it], [])
= 自然数
== 皮亚诺公理
#tem(title: "Axioms", "皮亚诺自然数公理")[
#grid(columns : (1em, 1fr, 1em), [], [
1. $0$ 是自然数
+ 每个自然数 $n$ 都有一个后继,计作 $"succ" n$,也是自然数
+ $0$ 不是任何自然数的后继
+ 当且仅当 $"succ" n = "succ" m$ 时,$n = m$
], [])
]<Peano-Axiom>
@Peano-Axiom[Axioms] 中第三第四条公理是为了处理自然数的绕回状况,是对前两条公理的强化。
#tem(title: "Axiom", [数学归纳法原理])[
$P(n)$ 表示自然数 $n$ 的某一性质,若 $P(0)$ 为真,$P(n)$ 为真,则有 $P("succ" n)$ 为真
,即对于任意自然数 $n$ 都有 $P(n)$ 为真。
]<nat-induction>
自然数的数学归纳法原理中所指的性质并不是确定的,该条原理也并非是一个独立的公理而是一种公理模式。
假设存在数系 $NN$, 若满足 @Peano-Axiom[Axiom] 以及 @nat-induction[Axiom],我们就称这个数系为自然数。
在自然数的基础上,我们可以递归的定义序列。序列是一列自然数,其下标,也就是索引值也是自然数,序列有基值,是一个常数,也有一个函数 $f : NN -> NN$,通过这个函数得到数列中这一项的后继元素的值。更准确的,有命题
#pos([序列的递归定义])[
有函数 $f : NN -> NN$,以及序列基值 $a_0 = c$,对于任意自然数 $n$,都可以确定唯一的 $a_("succ" n) = f(a_n)$ 。
]<序列的递归定义>
== 加法
#def([加法])[
对于任意一个自然数 $m$,$0 + m = m$,假设我们已经定义了 $n + m$,我们有 $("succ" n) + m = "succ" (m + n)$ 。
]<nat-addition>
#lem[
对于任意自然数 $n$,有 $n + 0 = n$ 成立。
]
#prf[
由 @nat-addition 可知,对于任意自然数 $m$,有$0 + m = m$,所以有 $0 + 0 = 0$,假设 $n + 0 = n$ 成立,则需证明 $"succ" n + 0 = "succ" n$,由加法定义可知 $("succ" n) + 0 = "succ" (n + 0)$,将 $n + 0 = n$ 代入可得 $"succ" (n + 0) = "succ" n$ 。
]
#lem[
对于任意自然数 $m,n$ 有 $m + ("succ" n) = "succ" (m + n)$ 。
]
证明时对 $m$ 进行数学归纳法即可。
#pos([交换律])[
$forall thin n, m in NN, n + m = m + n$
]
固定 $n$ 对 $m$ 进行数学归纳法即可证明。
#pos([结合律])[
$forall thin a, b, c in NN, (a + b) + c = a + (b + c)$
]
#pos([消去律])[
$forall thin a, b, c in NN, " if" a + b = a + c, " then" b = c$
]
=== 正整数
#def([正整数])[
正整数系中所有的元素都是非 $0$ 的自然数,计作 $ZZ^+$ 。
]
#pos[
$forall thin a in ZZ^+, b in NN, a + b in ZZ^+$
]
#corollary[
$forall thin a, b in NN, " if" a + b = 0, " then" a = 0, b = 0$
]
#lem[
$forall thin a in ZZ^+, exists thin b in NN, "succ" b = a$
]
=== 自然数的序
#def([自然数的序])[
$forall thin n, m, a in NN$,若 $n = m + a$,则称 $n >= m$ 或 $m <= n$,若 $n >= m$
并且 $n != m$,则称 $n > m$ 或 $m < n$ 。
]
#prt([自然数的序的基本性质])[
#align_enums[
#set enum(numbering: "(a)",number-align: start + bottom)
+ 自反性:$a >= a$
+ 传递性:若 $a >= b, b >= c$,则 $a >= c$
+ 反对称性:若 $a >= b, b >= a$,则 $a = b$
+ 加法不变性:若 $a >= b$,则 $a + c >= b + c$
+ 当且仅当 $"succ" a <= b$ 时,有 $a < b$
+ 当且仅当 $exists thin d in ZZ^+, b + d = a$,有 $a > b$
]
]
#pos([序的三歧性])[
$forall thin a, b in NN$,命题 $a > b, a < b, a = b$ 必只有一个成立。
]
#pos([强归纳法原理])[
$forall thin m_0, x in NN$,$P(x)$ 表示与自然数 $x$ 有关的性质 $P$,$forall m in NN, m >= m_0$,若
$forall m' in NN, m_0 <= m' < m,P(m') "为真,则 " P(m) "为真。"$ 当 $m = m_0$ 时,假设中的 $m'$
的取值范围为空,所以假设依然成立,即 $P(m_0)$ 总是为真的。
]
== 乘法
#def([自然数乘法])[
$forall thin, n, m in NN$,首先当 $n = 0$ 时,有 $0 times m := 0$,现在归纳性的假设已经定义了
$n times m$,我们有 $("succ" n) times m = (n times m) + m$ 。
]
乘法具有交换律,且乘法的运算优先级要大于加法,通常省略 times 符号如 $a b + c = (a times b) + c$ 。
#lem([交换律])[
$forall thin n, m in NN, n times m = m times n$
]
#lem([正整数没有零因子])[
$forall thin n, m in NN$,若有 $n m = 0$,当且仅当 $n, m$ 中至少有一个为 $0$,特别的,正整数乘法的结果为正整数。
]
#lem([交换律])[
$forall thin a, b, c in NN, a(b + c) = a b + a c, (b + c)a = b a + c a$
]
#lem([结合律])[
$forall thin a, b, c in NN, (a times b) times c = a times (b times c)$
]
// 在证明交换律时,固定两个自然数对另一个自然数进行归纳法即可证明。
#lem([序不变性])[
$forall thin a, b in NN, c in ZZ^+$,若 $a < b$,则有 $a c < b c$ 。
]
#lem([消去律])[
$forall thin a, b in NN, c in ZZ^+$,若有 $a c = b c$,则 $a = b$ 。
]
在证明消去律时,可以用到序的三歧性。
#pos([欧几里得算法])[
$forall thin n in NN, q in ZZ^+, exists thin m, r in NN, 0 <= r < q, n = m q + r$ 。
]
其中 $r$ 为余数,这个算法标志着数论的开始。
#def([指数运算])[
$forall thin n, m in NN$,当 $n = 0$ 时,$m^0 := 1$,特别的 $0^0 = 1$,现在归纳性的假设已经定义了
$m^n$ 我们有 $m^(n + 1) = m^n times m$ 。
]
= 集合论
== 基础知识
#def([集合的定义])[
集合是一堆没有顺序的对象,若有集合 $A$ 且 $x$ 是集合 $A$ 的这些对象当中的一个,我们称 $x$ 属于这个集合,计作 $x in A$ 。
]
#axm([集合也是对象])[
若 $A$ 是一个集合,那么 $A$ 也是一个对象。
]
这条公理指出一个集合可以作为一个元素,或者说对象而被另一个集合包含。
在纯粹集合论当中,任何对象都是集合,例如在自然数的表示当中,用 $diameter$ 表示 $0$,用
${diameter}$,表示 $1$,用 ${diameter, {diameter}}$ 表示 $2$,也就是每个自然数都是集合,由其前面的所有自然数所表示的集合组成。 在非纯粹集合论中,有些对象可以不是集合,在一般数学研究下,两者是近乎等价的。
#def([集合的相等])[
若有集合 $A, B$,当且仅当所有 $x in A, y in B$,满足 $x in B, y in A$ 时,我们称 $A = B$ 。
]
集合的相等关系可以很容易证明出是自反的,对称的,传递的,且因为相等的概念是通过 $in$ 运算来描述的,也自然继承
$in$ 运算的替换公理,所有只由 $in$ 运算构成的新运算都遵循替换公理。
#axm([空集])[
存在一个不包含任何对象的集合:空集 $diameter$ 或 ${}$,表示对于任意的对象 $x$,均有 $x in.not diameter$ 。
]
我们可以用单个选取引理来证明集合的非空性,即若有一非空集合 $A$,则存在 $x in A$ 。
#axm([单元素集合与双元素集合])[
单元素集合即一个只存在一个对象的集合 ${a}$,当且仅当 $x = a$ 时,有 $x in {a}$,双元素集合为之存在两个对象的集合
${a, b}$,当且仅当 $y = a$ 或 $y = b$ 时,有 $y in {a, b}$ 。
]
#axm([两个集合的并集])[
有集合 $A, B$,若有一个集合包含了所有属于集合 $A$ ,或属于集合 $B$ 或同时属于集合
$A, B$ 的对象,我们称这个集合为集合 $A, B$ 的并集 $A union B$ 。即,对于任意的对象 $x$ 有
$ x in A union B <==> x in A "或 " x in B $
]
#lem[
集合的并集符合交换律和结合律。
]
#def([子集])[
有集合 $A,B$,若对于 $A$ 中的任意对象 $x$,有 $x in B$,则称集合 $A subset.eq B$,即集合
$A$ 是集合 $B$ 的子集。当 $A != B$ 时,称 $A subset.neq B$ 即集合 $A$ 是集合 $B$ 的真子集。
]
定义子集的同时也定义了集合间的包含关系,其使得集合是偏序的而非全序的。即两个集合之间存在除了子集,真子集,相等集合外的彼此不为对方子集的关系。
#axm([分类公理])[
又称为分离公理,对于集合 $A$ 中某一对象 $X$ 的某一性质 $P(x)$,其要么为真要么为假,由分类公理构成的集合为
${x in A : P(x)}$ 表示集合 $A$ 中那些对于 $P(x)$ 为真的对象所构成的新集合。即
$ y in {x in A : P(X)} <==> y in A "并且 " P(y) "为真" $
]
#def([集合的交集])[
有集合 $A, B$ 根据分类公理,我们定义集合的交集为
$ A sect B := {y in A : y in B} $
]
#def([集合的差集])[
有集合 $A, B$ 根据分类公理,我们定义集合的交集为
$ A without B := {x in A, x in.not B} $
]
通过差集,交集,并集的运算,集合可以构成布尔代数
#pos([集合构成布尔代数])[
#align_enums[
#set enum(numbering: "(a)",number-align: start + bottom)
+ 最小元
+ 最大元
+ 恒等式
+ 交换律
+ 结合律
+ 分配律
+ 分拆法
+ 德摩根律
]
]
#axm([替换公理])[
对一集合 $A$ 上的元素 $x$,有命题 $P(x, y)$,当对于任意的 $x$ 都存在最多一个 $y$ 满足 $P(x, y)$ 时称命题为真,那么存在一个集合
${y : P(x, y) "对于任" x in A "为真"}$ 使得对任意的对象 $z$ 有
$ z in {y : P(x, y) "对于任" x in A "为真"} <==> "对于" x in A,P(x,z) "为真" $
]
替换公理的另一种形式是 ${y : x in A, y = f(x)}$,我们可以将其表示为 ${f(x) | x in A}$ 。
#axm([无穷大])[
对于一个集合 $NN$,$0$ 在集合中,以及对于所有 $x in NN$,其满足皮亚诺公理的后继也在集合
$NN$ 中,这个集合是个无穷大的集合。
]
== 罗素悖论
#axiom([万有分类])[
有一性质 $P$ 对于任意对象 $x$ 有 $P(x)$,可以构造出所有只含有 $P(x)$ 为真的对象 $x$,即
$ y in {x : P(x) "为真"} <==> P(y) "为真" $
]
万有分类 (universal specification) 公理希望对于某一个性质,可以构造出一个含有符合这个性质的所有对象的集合,若这条公理成立,在处理问题时,大概可以只考虑某一性质 $P$ 然后通过这条公理(也称为概括公理或万有公理)来构造出一个所有符合该性质的全部,也就是没有缺口的集合,并用集合操作来进行数学研究等等。但是这条公理并不能进入公理化集合论,罗素指出了万有公理是悖论性的。
#def([罗素悖论])[
对于任意对象 $x$ 有性质$P$: $ P <=> "若" x "是一个集合,有" x in.not x $
通过万有公理构造集合
$S := {x : P(x)}$,问 $S$ 是否属于集合 $S$。
#align_enums[
+ 若 $S in S$,则对于定义来说,$P(S)$ 为假,根据万有公理,$S in.not S$ 。
+ 若 $S in.not S$,则对于定义来说,$P(S)$ 为真,根据万有公理,$S in S$ 。
]
也就是不管从那方面进行推断,我们得到的结论都是 $S in S and S in.not S$,这显然是不正确的。
]
这是因为集合也是对象,在构造自身的同时自身也成为了构造自身的一部分,也就是发生了自指。在数学中,对自指的研究最终导致了著名的哥德尔不完备定理。
为了解决罗素悖论,数学家为集合论加上了限制以防止自指对发生。数学家们为集合划分了等级,最原始的等级是那些不能用集合表达的原始对象,如自然数 $1$ 等,次之是只包含原始对象的原始集合以及空集,如 ${1, 2},diameter$,接着是可以包含原始对象,也可以包含原始集合的集合,以此类推,也就是一个层级的集合只能包含低于其层级的对象。
陶哲轩没有给出复杂的严格形式化表达,而是给出了一条正则性公理:
#axm([正则性])[
对于任意一个集合 $S$,至少有一个对象 $x in S$,并且 $x$ 不是一个集合,或者当 $x$ 是一个集合时有 $x sect S = diameter$ 。
]
== 函数
#def([函数])[
对于一个集合 $X,Y$ 存在映射关系 $f$,对于任意 $x in X$,恰只有一个 $f(x) in Y$,则称
$f : X -> Y$ 为定义域 $X$ 到陪域 $Y$ 上的一个函数,或映射、变换。
]
函数有定义域 domain,陪域 codomain 和值域 range,其中值域是对于所有
$x in "domain"$ 可以取到的所有 $f(x)$ 所构成的集合,其中
$"range" subset.eq "codomain"$ 。
#def([函数的相等性])[
有函数 $f,g$ 若它们有相同的定义域和值域 $X,Y$ 且对于任意 $x in X$,有 $f(x) = g(x)$,则称 $f = g$ 。
]
函数有三种特殊类型:单射 injective,满射 surjective,双射 bijective。
#def([单射函数])[
有函数 $f : X -> Y$,$forall thin x, x' in X$,有 $x != x' ==> f(x) != f(x')$ 。
]
#def([满射函数])[
有函数 $f : X -> Y$,对于每一个 $y in Y$,存在 $x in X,f(x) = y$ 。 满射函数的陪域等于其值域。
]
#def([双射])[
即是单射又是满射的函数为双射函数,双射函数又称为可逆函数。
]
若函数 $f : X -> Y$ 是双射,那么对于任意 $y in Y$,恰好存在一个 $x in X$ 使得 $f(x) = y$。此时 $x = f^(-1)(y)$,我们称 $f^(-1) $ 为 $ f$ 的逆。
#def([函数的复合])[
有函数 $f : X -> Y,g : Y -> Z$,这时函数 $f$ 的值域与 $g$ 的定义域相同,我们称 $g compose f : X -> Z$ 为两个函数的复合函数,有 $
(g compose f)(x) := g(f(x))
$
]
#def([复合是可结合的])[
有三个函数 $f : Z -> W,g : Y -> Z,h : X -> Y$,则有 $f compose (g compose h) = (f compose g) compose h$ 。
]
\
== 象和逆象
#def([函数的象])[
有函数 $f : X -> Y$,有 $S subset.eq X$,我们称 $
f(S) := {f(x) | x in S}
$
为集合 $S$ 在函数 $f$ 上的象,或前象(与后文逆象相对)。
]
#def([函数的逆象])[
有函数 $f : X -> Y$,有 $S subset.eq Y$,我们称 $
f^(-1) (S) := {x | x in X,f(x) in S }
$
为集合 $S$ 在函数 $f$ 上的逆象。
]
=== 幂集公理
#axm([幂集公理])[
有集合 $X,Y$,我们称集合 $X^Y$ 为含有定义域为 $X$ 值域为 $Y$ 的所有函数的集合,即 $
forall f in X^Y <==> f : X -> ("range" : Y)
$
]
#lem[
若 $X$ 是一个集合,则有 ${Y | Y subset.eq X}$ 是一个集合。
]
#axm([并集公理])[
若集合 $S$ 其中的所有元素也都是集合,则有集合 $union S$,它是集合 $S$ 中所有集合的并集,即 $
forall x in union S := exists thin A in S, x in A
$
]
在公理之前,我们并不能方便的表达“集合中所有元素的并集”这句话,因此我们引入指标集 $I$,其中标签
$alpha in I$,而所有的 $A_alpha$ 被称为一个集族。那么我们定义集族的交集为: $
union.big_(alpha in I) A_alpha := union {A_alpha | a in I}
$
类似的,集族的并集为:$
sect.big_(alpha in I) A_alpha := {x | forall a in I,x in A_alpha}
$
集合论章节介绍的公理 Axiom 2.1 - Axiom 2.10 不包括万有分类公理 Axiom 2.8 被称为 Zermelo - Fraenkel 集合论公理(ZF)。
== 笛卡尔积
#def([有序对])[
对于任意的对象 $a, b$,有序对是形如 $(a,b)$ 的对象,其中对象 $a,b$ 的顺序是有意义的,即
$(a,b)$ 和 $(b,a)$ 是不同的对象。
]
#def([笛卡尔积])[
有集合 $X,Y$,定义 $X times Y = {(a,b) | a in X,b in Y}$ 。
]
#def([$n$ 维有序对与 $n$ 重笛卡尔积])[
有 $n$ 个集合 $S_1,S_2,...,S_n$ 则它们的笛卡尔积为
$ product_(i = 1)^n S_i = {(x_1, x_2, ..., x_n) | "对于任意的" 1 <= i <= n, x_i in S_i} $
其中形如 $(x_1, x_2, ..., x_n)$ 的有序对为 $n$ 维有序对。
]
特殊的,空笛卡尔积 $product_(1 <= i <= 0)$ 为集合 ${()}$ 。
#lem([有限选取])[
有 $n$ 个集合 $S_1, S_2, ... , S_n$ 都是非空集合,则其 $n$ 重笛卡尔积 $product_(i = 1)^n S_i$ 也为非空集合。
]
== 集合的基数
集合是顺序无关的,但在有限集内,集合中对象的数量是固定的,可数的,而目前为止只介绍了自然数集
$NN$,本章主要内容为阐明只要集合是有限的,就可以用自然数作为集合的计数集合这一命题。
#def([相等的基数])[
有集合 $S_1, S_2$,当且仅当两集合之间存在一个双射 $f : S_1 -> S_2$,称两个集合有相同的基数。
]
相等的基数也是一种等价关系,若有三个集合 $X,Y,Z$ 其中两两具有相同的基数,那么它们三个有相同的基数,通过函数复合的结合律即可以证明这一点。
#def([自然数作为计数集合])[
有自然数 $n$,当且仅当集合 ${i | i in NN, 1 <= i <= n }$ 与集合 $S$ 有相等的基数时,称集合
$S$ 的基数为 $n$,即集合 $S$ 中有 $n$ 个元素。
]
#pos([集合基数的唯一性])[
一个集合有且只有一个基数。
]
#def([有限集])[
当一个集合的基数是一个自然数时,称这个集合是有限集,否则这个集合为无限集。用 $\#(S) = n$ 来表示这个集合的基数。
]
#tem()[
自然数集 $NN$ 是一个无限集。
]
集合之间存在基数算数。
// = 整数和有理数
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/post_type_check/text_font3.typ | typst | Apache License 2.0 | #text(font: /* position after */ ("Test",))[] |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/002%20-%20Return%20to%20Ravnica/003_Epic%20Experiment.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Epic Experiment",
set_name: "Return to Ravnica",
story_date: datetime(day: 12, month: 09, year: 2012),
author: "<NAME>",
doc
)
#figure(image("003_Epic Experiment/02.jpg", width: 100%), caption: [Art by David Rapoza], supplement: none, numbering: none)
Trenz adjusted his Endotaxis-Goggles onto the bridge of his crooked nose. #emph[Good morning, Experiment Day] ! Blinking through the haze of Hyperocular Dust that wafted through the air, he sucked in a huge cone of it through his nostrils. Trenz enjoyed the scent of smoldering metal that wafted from the Magnetic Nitroxider, his mana-charged contraption that filled the entire east wall.
The early morning sun peeped through the cracked window, which overlooked the abandoned block of buildings that Trenz affectionately called the Empty Cup Row. He waved at the devoted klatch of Selesnya missionaries who had been picking away at the rubble—by hand—for months. At this rate, in 102.7 years, they’ll have cleared a nice spot to plant a new guild tree for their nascent community.
Trenz surveyed his drafty workshop and felt as if he must burst with pleasure. Somewhere, miles away in the Tenth District, the Firemind was probably reclining in his aerie in Nivix, considering a million things at once. Trenz wished he could hold a fraction of the things in his mind that Niv-Mizzet pondered in the blink of an eye.
Niv-Mizzet himself had bestowed this remote area of the city to Trenz as a playground for his Exospecial Experiments. Even before he was a full-fledged Chemister, Trenz had attracted the dragon’s attention when he created an Ætherprax tunnel from Nivix to the gates of Sunhome. Lately, the Firemind had been gifting Trenz with personal assignments that led him in directions that never would have occurred to him on his own. Yes, grand things were happening, and Trenz couldn’t remember that last time he’d slept. There was simply too much to do to bother shutting one’s eyes.
And today was Experiment Day! Trenz would crack the egg of truth and lay it at the claws of his master. Trenz strapped on his Omniblast helmet and lowered the Electrolocoscope over his face. He spun the scope around the room, marveling at incredible detail. There were a mason’s forgotten fingerprints along the vaulted ceiling. Yesterday’s bloodspots spattered across the toes of his reinforced boots. Trenz loved little details. It all added up to something grand.
Experimentation without risk would lead nowhere. An explosion was just the art of a mind on fire!
He strode across the warped floor boards and stood before the Magnetic Nitroxider, an element negotiator of his own design. So small. So perfect. If it were a pet mouse, he would kiss it between its fuzzy little ears. Trenz sighed with happiness. #emph[If this is thinking, I don’t know what I was doing before] , he thought happily.
His epic moment had arrived. He’d narrowed it down to four tests, each blossoming with potential. Each would yield gems of priceless information to deliver to the Aerie. But only one was the #emph[right] choice. But which? Choose wisely, Mr. Trenz!
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("003_Epic Experiment/04.jpg", width: 100%), caption: [Cyclonic Rift | Art by <NAME>], supplement: none, numbering: none)
Trenz selected the Aerial-Antistasis Chamber. He fired up the Mizzium coils and stepped into the Firemist field generated by the chamber. The mist eddied around him, stinging his cheeks with tiny barbs. Beneath his feet, the floor boards trembled. Outside, the sky darkened and the wind gusted dramatically. A violent funnel of wind materialized outside his workshop window, much to the horror of the Selesnya missionaries who rushed to take cover in a culvert.
The funnel tore through the abandoned block. It razed high-rise flats and demolished an empty Orzhov mission. Hordes of rubble-dwelling rats scurried for the drain as years of rubbish left by Gruul squatters swirled through the air. As quickly as it appeared, the funnel disappeared and the sun returned.
Trenz looked around his workshop in disappointment. A tornado of lightning-charged wind was not what he’d hoped for. Strangely, the Selesnyans were whooping outside his window. A large swath of the block was swept clear—as if a giant with a broom as taken sympathy on their mission. Joyful shouts of "The seed! Get the seed!" drifted through the air as Trenz went back to the drawing board.
#figure(image("003_Epic Experiment/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Trenz selected the Spatial Ectofractalyzer. Ever so carefully, he poured the purest Ocular dust into the bolt hole. The dust began to glow faintly, which somehow made him sniffle. Inside the containment vial, the dust shuddered, clumped, and shuddered again. Trenz sneezed, and reality fragmented into beautiful shades of cobalt and puce. #emph[Oops] , Trenz thought. #emph[Too much dust] .
Meanwhile, deep in the bowels of the undercity, two shadowy figures were having a heated discussion. As soon as the puce light hit them, they stepped back into the shadows. A white-haired man appeared out of nowhere, cursed loudly, and began stomping noisily up the cobblestones toward the surface. As he disappeared from sight, the startled pair looked at each other in amazement. A beautiful portal shimmered in front of them, and Mr. Taz was sure it would take them exactly where they needed to go.
"Well, Krenko," Taz murmured to the hook-nosed goblin standing beside him. "Getting into the Orzhov inner sanctum might not be as difficult as you initially believed."
#figure(image("003_Epic Experiment/08.jpg", width: 100%), caption: [Mizzium Mortars | Art by <NAME>], supplement: none, numbering: none)
Trenz selected the Megathermal Geolometer. Keeping his head #emph[way] back, he tapped the geolometer against the supercharged Mizzium coils. Nothing happened. He blew off the dust bunnies and tapped it harder.
Suddenly, spires of molten flame rocketed through the air. Super-heated metal fragments rained down over the district and tore coin-sized holes in roofs for miles around. The sizzle of burning metal gave way to slow-rolling earthquakes that made the streets undulate like waves.
The bright lights and thunderous racket attracted the attention of the Rakdos cultists. Nothing says "celebration" quite like widespread, random destruction. Bloodwitches stumbled out of Rix Maadi. Pleasure clubs emptied all over the city. The roustabouts and spikers roused their reluctant neighbors and soon the streets filled with merrymakers.
Amid their frolicking, the cultists agreed they should do this #emph[every] year, and thus the new Festival of Fire-Rain Bloodletting Mayhem Neighbor Appreciation Day was born.
The show continued long into the night—even after Trenz threw the Geolometer out the window and went to bed.
#figure(image("003_Epic Experiment/10.jpg", width: 100%), caption: [Epic Experiment | Art by <NAME>], supplement: none, numbering: none)
Trenz choose the Neural Schisatrode. He tightened the screws against his temples and waited expectantly. There was a jangle followed by a frightened squeak. Air rushed in through his ears like his brain had turned into a Suctionatronic device. His thoughts seem to pulverize under the weight of some mental hammer. "No!" he cried. "I must not let the Firemind down." Desperately, he raised his Zygon Cuff and, suddenly, the room erupted in lightning and pure, unadulterated genius. He had chosen correctly, and the reward was in his electrified grasp at last!
|
|
https://github.com/Mc-Zen/pillar | https://raw.githubusercontent.com/Mc-Zen/pillar/main/tests/examples/measurement-results/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 1pt)
#import "/src/pillar.typ"
#let clr = if "dark" in sys.inputs { white } else { black }
#set page(fill: white) if clr == black
#set text(fill: clr)
#set table.hline(stroke: clr)
#set table.vline(stroke: clr)
#pillar.table(
cols: "ccc ||[.7pt] ccc",
..([\#], [$α$ in °], [$β$ in °]) * 2,
table.hline(),
[1], [34.3], [11.1], [6], [34.0], [12.9],
[2], [34.2], [11.2], [7], [34.3], [12.8],
[3], [34.6], [11.4], [8], [33.9], [11.9],
[4], [34.7], [10.3], [9], [34.4], [11.8],
[5], [34.3], [11.1], [10], [34.4], [11.8],
) |
https://github.com/jamesrswift/journal-ensemble | https://raw.githubusercontent.com/jamesrswift/journal-ensemble/main/src/lib.typ | typst | The Unlicense | #import "article.typ" as article: *
#import "contents.typ" as contents: *
#import "ensemble.typ" as ensemble: *
#import "elements.typ" as elements: *
#import "part.typ" as part: *
#import "pages.typ"
|
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/README.md | markdown | MIT License | # fletcher
[](docs/manual.pdf?raw=true)

[](https://github.com/Jollywatt/typst-fletcher/tree/dev)
[](https://github.com/Jollywatt/typst-fletcher)
_**fletcher** (noun) a maker of arrows_
A [Typst](https://typst.app/) package for drawing diagrams with arrows,
built on top of [CeTZ](https://github.com/johannes-wolf/cetz).
See the [manual](docs/manual.pdf?raw=true) for documentation.
```typ
#import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge
```
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/readme-examples/first-isomorphism-theorem-dark.svg">
<img src="docs/readme-examples/first-isomorphism-theorem-light.svg">
</picture>
```typ
#diagram(cell-size: 15mm, $
G edge(f, ->) edge("d", pi, ->>) & im(f) \
G slash ker(f) edge("ur", tilde(f), "hook-->")
$)
```
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/readme-examples/flowchart-trap-dark.svg">
<img src="docs/readme-examples/flowchart-trap-light.svg">
</picture>
```typ
// https://xkcd.com/1195/
#import fletcher.shapes: diamond
#set text(font: "Comic Neue", weight: 600)
#diagram(
node-stroke: 1pt,
edge-stroke: 1pt,
node((0,0), [Start], corner-radius: 2pt, extrude: (0, 3)),
edge("-|>"),
node((0,1), align(center)[
Hey, wait,\ this flowchart\ is a trap!
], shape: diamond),
edge("d,r,u,l", "-|>", [Yes], label-pos: 0.1)
)
```
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/readme-examples/state-machine-dark.svg">
<img src="docs/readme-examples/state-machine-light.svg">
</picture>
```typ
#set text(10pt)
#diagram(
node-stroke: .1em,
node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%),
spacing: 4em,
edge((-1,0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center),
node((0,0), `reading`, radius: 2em),
edge(`read()`, "-|>"),
node((1,0), `eof`, radius: 2em),
edge(`close()`, "-|>"),
node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)),
edge((0,0), (0,0), `read()`, "--|>", bend: 130deg),
edge((0,0), (2,0), `close()`, "-|>", bend: -40deg),
)
```
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/readme-examples/feynman-diagram-dark.svg">
<img src="docs/readme-examples/feynman-diagram-light.svg">
</picture>
```typ
#diagram($
e^- edge("rd", "-<|-") & & & edge("ld", "-|>-") e^+ \
& edge(gamma, "wave") \
e^+ edge("ru", "-|>-") & & & edge("lu", "-<|-") e^- \
$)
```
# More examples
Pull requests are most welcome!
<table>
<tr>
<td style="background: white;">
<a href="docs/gallery/commutative.typ">
<center>
<img src="docs/gallery/commutative.svg" width="100%"/>
</center>
</a>
</td>
<td style="background: white;">
<a href="docs/gallery/algebra-cube.typ">
<center>
<img src="docs/gallery/algebra-cube.svg" width="100%"/>
</center>
</a>
</td>
</tr>
<tr>
<td style="background: white;">
<a href="docs/gallery/ml-architecture.typ">
<center>
<img src="docs/gallery/ml-architecture.svg" width="100%"/>
</center>
</a>
</td>
<td style="background: white;">
<a href="docs/gallery/io-flowchart.typ">
<center>
<img src="docs/gallery/io-flowchart.svg" width="100%"/>
</center>
</a>
</td>
</tr>
<tr>
<td style="background: white;">
<a href="docs/gallery/digraph.typ">
<center>
<img src="docs/gallery/digraph.svg" width="100%"/>
</center>
</a>
</td>
<td style="background: white;">
<a href="docs/gallery/node-groups.typ">
<center>
<img src="docs/gallery/node-groups.svg" width="100%"/>
</center>
</a>
</td>
</tr>
<tr>
<td style="background: white;">
<a href="docs/gallery/uml-diagram.typ">
<center>
<img src="docs/gallery/uml-diagram.svg" width="100%"/>
</center>
</a>
</td>
</tr>
</table>
## Change log
### 0.5.1
- Fix nodes which `enclose` absolute coordinates.
- Allow CeTZ-style coordinate expressions in node `enclose` option.
- Fix crash with polar coordinates.
- Fix edges which bend at 0deg or 180deg (e.g., `edge("r,r")` or `edge("r,l")`) and enhance the way the corner radius adapts to the bend angle. **Note:** This may change diagram layout from previous versions.
- Improve error messages.
- Add marks for crow's foot notation: `n` (many), `n?` (zero or more), `n!` (one or more), `1` (one), `1?` (zero or one), `1!` (exactly one).
- Add `node-shape` option to `diagram()`.
### 0.5.0
- Greatly enhance coordinate system.
- Support CeTZ-style coordinate expressions (relative, polar, interpolating, named coordinates, etc).
- Absolute coordinates (physical lengths) can be used alongside "elastic" coordinates (row/column positions).
- Add `label-angle` option to `edge()`.
- Add `label-wrapper` option to allow changing the label inset, outline stroke, and so on (#26).
- Add `label-size` option to control default edge label text size (#35)
- Add `trapezium` node shape.
- Disallow string labels to be passed as positional arguments to `edge()` (to eliminate ambiguity). Used named argument or pass content instead.
### 0.4.5
- Add isosceles triangle node shape (#31).
- Add `fit` and `dir` options to various node shapes to adjust sizing and orientation.
- Allow more than one consecutive edge to have an implicit end vertex.
- Allow `snap-to` to be `none` to disable edge snapping (#32).
### 0.4.4
- Support fully customisable marks/arrowheads!
- Added new mark styles and tweaked some existing defaults. **Note.** This may change the micro-typography of diagrams from previous versions.
- Add node groups via the `enclose` option of `node()`.
- Node labels can be aligned inside the node with `align()`.
- Node labels wrap naturally when label text is wider than the node. **Note:** This may change diagram layout from previous versions.
- Add a `layer` option to nodes and edges to control drawing order.
- Add node shapes: `ellipse`, `octagon`.
### 0.4.3
- Fixed edge crossing backgrounds being drawn above nodes (#14).
- Add `fletcher.hide()` to hide elements with/without affecting layout, useful for incremental diagrams in slides (#15).
- Support `shift`ing edges by coordinate deltas as well as absolute lengths (#13).
- Support node names (#8).
### 0.4.2
- Improve edge-to-node snapping. Edges can terminate anywhere near a node (not just at its center) and will automatically snap to the node outline. Added `snap-to` option to `edge()`.
- Fix node `inset` being half the amount specified. If upgrading from previous version, you will need to divide node `inset` values by two to preserve diagram layout.
- Add `decorations` option to `edge()` for CeTZ path decorations (`"wave"`, `"zigzag"`, and `"coil"`, also accepted as positional string arguments).
### 0.4.1
- Support custom node shapes! Edges connect to node outlines automatically.
- New `shapes` submodule, containing `diamond`, `pill`, `parallelogram`, `hexagon`, and other node shapes.
- Allow edges to have multiple segments.
- Add `vertices` an `corner-radius` options to `edge()`.
- Relative coordinate shorthands may be comma separated to signify multiple segments, e.g., `"r,u,ll"`.
- Add `dodge` option to `edge()` to adjust end points.
- Support `cetz:0.2.0`.
### 0.4.0
- Add ability to specify diagrams in math-mode, using `&` to separate nodes.
- Allow implicit and relative edge coordinates, e.g., `edge("d")` becomes `edge(prev-node, (0, 1))`.
- Add ability to place marks anywhere along an edge. Shorthands now accept an optional middle mark, for example `|->-|` and `hook-/->>`.
- Add “hanging tail” correction to marks on curved edges. Marks now rotate a bit to fit more comfortably along tightly curving arcs.
- Add more arrowheads for the sake of it: `}>`, `<{`, `/`, `\`, `x`, `X`, `*` (solid dot), `@` (solid circle).
- Add `axes` option to `diagram()` to control the direction of each axis in the diagram's coordinate system.
- Add `width`, `height` and `radius` options to `node()` for explicit control over size.
- Add `corner-radius` option to `node()`.
- Add `stroke` option to `edge()` replacing `thickness` and `paint` options.
- Add `edge-stroke` option to `diagram()` replacing `edge-thickness`.
### 0.3.0
- Make round-style arrow heads better approximate the default math font.
- Add solid arrow heads with shorthand `<|-`, `-|>` and double-bar `||-`, `-||`.
- Add an `extrude` option to `node()` which duplicates and extrudes the node's stroke, enabling double stroke effects.
### 0.2.0
- Experimental support for customising arrowheads.
- Add right-angled edges with `edge(..., corner: left/right)`.
## Star History
<a href="https://star-history.com/#jollywatt/typst-fletcher&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=jollywatt/typst-fletcher&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=jollywatt/typst-fletcher&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=jollywatt/typst-fletcher&type=Date" />
</picture>
</a>
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cheda-seu-thesis/0.2.0/seu-thesis/parts/abstract-degree-fn.typ | typst | Apache License 2.0 | #import "../utils/fonts.typ": 字体, 字号
#import "../utils/packages.typ": fakebold
#let abstract-conf(
cnabstract: none,
cnkeywords: none,
enabstract: none,
enkeywords: none,
page-break: none
) = {
// 摘要使用罗马字符的页码
set page(numbering: "I", number-align: center)
counter(page).update(1)
set text(font: 字体.宋体, size: 字号.小四)
set par(first-line-indent: 2em, leading: 9.6pt, justify: true)
show par: set block(spacing: 9.6pt)
if not cnabstract in (none, [], "") or not cnkeywords in (none, ()) {
{
heading(numbering: none, level: 1, outlined: true, bookmarked: true)[摘要]
cnabstract
v(1em)
parbreak()
if not cnkeywords in (none, ()) {
assert(type(cnkeywords) == array)
fakebold[关键词:] + cnkeywords.join(",")
}
}
}
if not enabstract in (none, [], "") or not enkeywords in (none, ()) {
{
if type(page-break) == function {
page-break()
} else {
pagebreak(weak: true)
}
heading(numbering: none, level: 1, outlined: true, bookmarked: true)[ABSTRACT]
enabstract
v(1em)
parbreak()
if not enkeywords in (none, ()) {
assert(type(enkeywords) == array)
text(weight: "bold")[Keywords: ] + enkeywords.join(",")
}
}
}
}
#abstract-conf(
cnabstract: [示例摘要],
cnkeywords: ("关键词1", "关键词2"),
enabstract: none,
enkeywords: ("Keywords1", "Keywords2"),
)
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/goto_definition/module_select_alias.typ | typst | Apache License 2.0 | // path: variable.typ
#let f(x) = 2;
-----
#import "variable.typ" as this-module
#(this-module.f /* position after */ );
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/page_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Just empty page.
// Should result in auto-sized page, just like nothing.
#page[]
|
https://github.com/EGmux/ControlTheory-2023.2 | https://raw.githubusercontent.com/EGmux/ControlTheory-2023.2/main/prova2.typ | typst | #set heading(numbering: "1.")
=== 1. Reduza o sistema abaixo para um único bloco
#figure(image("assets/2024-03-19-20-59-17.png", width: 80%)) <fig-2024-03-19-20-59-17>
#figure(image("assets/2024-03-19-21-08-59.png", width: 80%)) <fig-2024-03-19-21-08-59>
para o seguinte diagrama de blocos a redução pode ser computada algebricamente
como
#math.equation(block: true, $ 1. & R - A = B \
2. & B G = C \
3. & C H = A \ $)
substituindo 3 em 1 e 1 em 2, temos
#math.equation(block: true, $
1. & (R - C H)G = C \
2. & R G - C H G = C \
3. & R G = C + C H G \
3. & R G = C(1 + H G) \
3. & R G/(1 + H G) = C \
$)
#figure(image("assets/2024-03-19-21-21-37.png", width: 80%)) <fig-2024-03-19-21-21-37>
para o diagrama de blocos acima, temos
#math.equation(block: true, $1. & R A = B && \
2. & B D = C && \ $)
substituindo 1 em 2, temos
#math.equation(block: true, $ 1. & (R A)D = C \
2. & R (A D) = C \
2. & R E = C \ $)
#figure(image("assets/2024-03-19-21-24-54.png", width: 80%)) <fig-2024-03-19-21-24-54>
note que temos as seguintes relações algébricas entre os blocos
#math.equation(block: true, $ 1. & R A = D \
2. & R B = F \
3. & D + F = C \ $)
logo substituindo 1 e 2 em 3, temos
#math.equation(block: true, $1. R A + R B = C \
2. R (A + B) = C \
2. R E = C \ $)
#figure(image("assets/2024-03-19-21-38-47.png", width: 80%)) <fig-2024-03-19-21-38-47>
note que se movermos o ponto de bifurcação entre $G_3$ e c para o ponto
imediatamente depois de $G_2$ o problema fica mais simples de resolver.
para fazermos isso é necessário preservar a entrada de $H_2$ que é $c$, e $c = B G_3$ tal
que $B$ seja saída de $G_2$.\
Ao movermos o ramo então teremos $B$ como valor, mas precisamos de $B G_3$ então
devemos multplicar por $G_3$, daí teremos o seguinte diagrama que multiplica $H_2$ e
como blocos em série são multplicados teremos $G_3H_2$ agora podemos simplificar
o ponto de soma, que está com alimentação negativa envolvendo $G_3 H_2 $ e $G_2$ assim
obtemos esse bloco $G_2/(1+G_2G_3H_2)$ agora temos $G_1$ em série como esse
bloco o que nos dá $(G_1G_2)/(1+G_2G_3H_2)$\
agora podemos temos outro caso de feedback e nesse caso teremos.
#math.equation(block: true, $ 1. & R + F = E \
2. & E G = C \
3. & C H =F \ $)
substituindo 3 em 1 e 1 em 2, temos
#math.equation(block: true, $1. & R + C H = E \
2. & (R + C H)G = C \
2. & R G = C(1 - H G) \
2. & R G/(1 - H G) = C \ $)
logo substituindo G por $(G_1G_2)/(1 + G_2G_3H_2)$ e $H = H_1$ temos $(G_1G_2)/(1+G_2G_3H_2)/(1-H_1((G_1G_2)/(1+G_2G_3H_2)))$ e
simplificando, temos
#math.equation(block: true, $ (G_1G_2)/(1+G_2G_3H_2 - H_1G_1G_2) $)
novamente temos ainda um bloco em série multiplicamos e obtemos
*$(G_1G_2G_3)/(1+G_2G_3H_2 - H_1G_1G_2)$*
e agora temos um único bloco e alimentação negativa, podemos considerar um bloco
unitário que não muda a entrada e fazendo as derivações obtemos
#math.equation(block: true, $1. & R - F = E \
2. & E G = C \
3. & C = F \ $)
daí substituindo, temos
#math.equation(block: true, $1 . & (R - C) = E \
2 . & (R - C)G = C\
3 . & R G/(1 + G) = C\ $)
logo o bloco final é *$(G_1G_2G_3)/(1+G_2G_3H_2-H_1G_1G_2 + G_1G_2G_3)$*
=== 2. Ache função transferência utilizando regra de Mason
#figure(image("assets/2024-03-19-22-01-33.png", width: 80%)) <fig-2024-03-19-22-01-33>
Primeiramente vamos encontrar os ganhos dos caminhos que vão de R até C que são
caminhos hamiltonianos.
#math.equation(block: true, $ 1. & G_1G_2G_3 \ $)
agora vamos encontrar todos os loop que não se tocam temos
#math.equation(block: true, $1. & G_1G_2H_1 \
2. & G_2G_3H_2 \
3. & G_1G_2G_3\ $)
não há loops 2 a dois que não se tocam, logo agora devemos computar o cofator
dos caminhos hamiltonianos existentes, como só temos um único só teremos um
único cofator , note que os loops isolados não existem, pois todos os vértices
do grafo se encontram no caminho hamiltoniano em questão, logo o cofator deverá
ser 1.
agora podemos computar com a regra de Mason a função transferência desejada
#math.equation(block: true, $ C(s)/R(s) = Sigma^n_k (P_k Delta_k)/Delta $)
com n =1, temos portanto
#math.equation(
block: true, $ (P_1 Delta_1)/Delta = (G_1G_2G_3)/(1-(G_1G_2H_1+G_2G_3H_2+G_1G_2G_3)) $,
)
=== 3. Ache a representação de fluxo de sinal dada as equações estado espaço
#figure(image("assets/2024-03-19-23-02-35.png", width: 80%)) <fig-2024-03-19-23-02-35>
note que estado espaço é no domínio do tempo, mas fluxo de sinal é no domínio da
frequência, então precisamos aplicar transformada de Laplace.
#math.equation(block: true, $ 1. & s X_1 = X_1 + 2X_2 \
2. & s X_2 = 2X_2 + X_3 \
3. & s X_3 = -2X_3 + R \
3. & Y = X_1 + X_2 $)
portanto temos as seguintes funções transferências/ganhos
#figure(image("assets/2024-03-19-23-22-06.png", width: 80%)) <fig-2024-03-19-23-22-06>
=== 4. Dada a função transferência abaixo discurse sobre a estabilidade ou instabilidade do sistema
#figure(image("assets/2024-03-19-23-24-26.png", width: 80%)) <fig-2024-03-19-23-24-26>
Vamos fazer uso da tabela de Routh-Hurwitz para verificar a estabilidade do
sistema que tem T como função de transferencia
#math.equation(
block: true, $ #table(
columns: (30pt, auto, auto, auto,), inset: 10pt, align: horizon, $s^5$, $1$, $3$, $3$, $s^4$, $1$, $1$, $2$, $s^4$, $2$, $1$, $0$, $s^2$, $1/2$, $2$, $0$, $s^1$, $-7$, $0$, $0$, $s^0$, $2$, $0$, $0$,
) $,
)
note que como houve mudança de sinal de $s^2$ para $s^1$ então existe a presença
de dois polos no semiplano direito o que indica instabilidade
=== 5. Dada a função de transferência abaixo classifique o tipo de sistema quanto ao erro
#figure(image("assets/2024-03-20-08-07-19.png", width: 80%)) <fig-2024-03-20-08-07-19>
vamos computar as constantes de erro $K_p,K_v$ e $K_a$
lembrando que
#math.equation(block: true, $ 1. & e_u(∞) = 1/(1+K_p) \
2. & e_R(∞) = 1/K_v \
3. & e_P(∞) = 1/K_a \ $)
tal que as ctes's são obtidas como
#math.equation(block: true, $ 1. & K_p = "lim"_(s->0) G(s) \
2. & K_v = "lim"_(s->0) s G(s) \
3. & K_v = "lim"_(s->0) s^2 G(s) \ $)
para *$K_p$* temos
#math.equation(block: true, $ 1. & lim_(s->0)((s+8)/(s(s+1)(s+2)(s+20))) = ∞ \
2. & e_U(∞) = 1/(1+∞) = 0 \ $)
para *$K_v$* temos
#math.equation(
block: true, $ 1. & lim_(s->0)(s((s+8)/(s(s+1)(s+2)(s+20)))) = 8/(1 dot 2 dot 20) = 1/5 \
2. & e_R(∞) = 1/(1/5) = 5 \ $,
)
para *$K_a$* temos
#math.equation(block: true, $ 1. & lim_(s->0)(s^2((s+8)/(s(s+1)(s+2)(s+20)))) = 0 \
2. & e_P(∞) = 1/0 = ∞ \ $)
assim como *$K_p$* é 0, *$K_v$* é cte e *$K_a$* é infinito temos um sistema de
tipo 1 visto que *$K_v$* é fixo
=== 4. Dada a função transferência abaixo esboce o lugar das raízes, dê o esboço mais completo possível
assuma ausêne
|
|
https://github.com/binhtran432k/ungrammar-docs | https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/literature-review/monaco-vs-vscode.typ | typst | #import "/components/glossary.typ": gls
== Monaco Editor vs. Visual Studio Code
This section provides a comparative analysis of the Monaco Editor (@sec-monaco) and Visual Studio Code (@sec-vscode), examining their architectural underpinnings, core features, and performance characteristics. The primary goal is to explore the feasibility of sharing underlying implementation components between the two platforms, optimizing development efforts and ensuring consistency in language support.
By examining the architectural similarities and differences between Monaco and #gls("vscode"), this review aims to identify potential challenges and opportunities for code sharing. Additionally, the integration of language features, such as syntax highlighting, code completion, and debugging, will be analyzed to determine the extent of shared implementation possible.
=== Architectural Overview
*Monaco Editor*: As a component of Visual Studio Code, Monaco shares a similar architectural foundation, relying on web technologies for its implementation. However, as a standalone editor, Monaco offers a more focused set of features and a potentially smaller codebase. Research on Monaco's architecture has been limited, but insights can be gained from analyzing its role within #gls("vscode") and comparing it to other web-based editors.
*Visual Studio Code*: Built upon the #gls("electron") framework, #gls("vscode") combines web technologies with native capabilities, resulting in a hybrid architecture. This approach enables cross-platform compatibility while offering access to native system resources. Research on #gls("vscode")'s architecture has explored the trade-offs between performance, portability, and feature richness associated with this hybrid model.
=== Core Features and Functionality
Both Monaco Editor and Visual Studio Code provide a robust set of core features, including syntax highlighting, code completion, debugging, and #gls("git") integration. However, the depth and breadth of these features differ between the two editors.
*Monaco Editor*: As a more focused text editor, Monaco prioritizes core editing capabilities and performance. Its feature set is often tailored to specific use cases, such as embedded code editing within web applications.
*Visual Studio Code*: Offering a broader range of features, #gls("vscode") caters to a wider developer audience. Its extensive extension ecosystem enables customization and adaptation to various development workflows.
=== Performance and Scalability
Performance is a critical factor for code editors, especially when handling large codebases. While direct performance comparisons between Monaco Editor and #gls("vscode") are limited, research on web-based editors and performance optimization techniques can provide valuable insights.
*Monaco Editor*: As a standalone component, Monaco Editor has the potential for optimized performance by focusing on essential editing features. However, the absence of extensive extension capabilities might limit its scalability for complex development scenarios.
*Visual Studio Code*: The hybrid architecture of #gls("vscode") introduces performance challenges related to managing multiple processes and resource allocation. However, the editor's modular design and ongoing performance optimizations have helped to mitigate these issues.
|
|
https://github.com/cunhapaulo/typst_styles | https://raw.githubusercontent.com/cunhapaulo/typst_styles/main/README.md | markdown | MIT License | # Just released (31.oct.2023) - ABNT ready
This time it is for real. Both templates are in compliance with ABNT, including bibliography and references.
# Typst Themes - `typst_styles`
Hello, there.
It´s been with great joy that I found [Typst](https://typst.app/). It gave me even greater pleasure to know it has been created in Berlin! It is a cloud-based Typesitting sistem, similar to LaTeX in its goals. I was very well impressed and decided to give it a try! I was not let down by what I´ve foud and recomend it to everyone! Then I accepted the chalenge to adapt it to my academic needs. As I used to write documents using LaTeX, my first goal was to create templates as close to what I had already achieved in LaTeX as possible, so here we are.
What I share here is still under improvments and is not yet perfect, but can be a head start to anyone who wishes to write academic documents in Typst, be it in the Typst cloud or on premise with VSCode.
I´d be thankful if you could share your experience, needs and improvements with me.
Hugs.

Try Typst and save time when writing papers, homework, and more. Sign up at https://typst.app
## Current styles available
### Monography
You may access this template as a eadonly version direct in Typst cloud through the link below:
- [Direct link to the read-only example document in the Typst cloud.](https://typst.app/project/rpNyqa1B-xy56OoZsWupCa)

### Paper
You may access this template as a eadonly version direct in Typst cloud through the link below:
- [Direct link to the read-only example document in the Typst cloud.](https://typst.app/project/rGFsAn7O-cgwauApoONm5u)

|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-20.typ | typst | Other | // Error: 14-36 exponent may not be infinite, subnormal, or NaN
#calc.pow(2, calc.pow(2.0, 10000.0))
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/cancel_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Cross
$a + cancel(b + c + d, cross: #true, stroke: #red) + e$
$ a + cancel(b + c + d, cross: #true) + e $
|
https://github.com/hemmrich/CV_typst | https://raw.githubusercontent.com/hemmrich/CV_typst/master/cv.typ | typst | // Imports
#import "./template/lib.typ": cv
#let metadata = toml("./metadata.toml")
#let importModules(modules, lang: metadata.language) = {
for module in modules {
include {
"modules/" + module + ".typ"
}
}
}
#show: cv.with(
metadata,
profilePhoto: image("./src/headshot.png")
)
#importModules((
"education",
"professional",
"projects",
//"certificates",
"publications",
"skills",
)) |
|
https://github.com/tfachada/thesist | https://raw.githubusercontent.com/tfachada/thesist/main/src/utils.typ | typst | MIT License | // Import subfigure package and make it work with the chapter-relative numbering
#import "@preview/subpar:0.1.1"
#let subfigure-grid(in-appendix: none, ..args) = {
let numbering-format = "1.1"
if in-appendix{
numbering-format = "A.1"
}
subpar.grid(
numbering: super => numbering(numbering-format, counter(heading).get().first(), super),
numbering-sub-ref: (super, sub) => numbering(numbering-format+"a", counter(heading).get().first(), super, sub),
..args
)
}
// Add ability to show shorter captions in the indices
#let in-outline = state("in-outline")
#let flex-caption(long, short) = context if in-outline.get() { short } else { long }
|
https://github.com/ls1intum/thesis-template-typst | https://raw.githubusercontent.com/ls1intum/thesis-template-typst/main/content/proposal/transparency_ai_tools.typ | typst | MIT License | #import "/utils/todo.typ": TODO
#TODO[
Change this paragraph to reflect the tools you used in your proposal
]
/*
Categories of AI Usage:
Grammar and Style Correction
Tools: Grammarly, Hemingway
Purpose: To correct grammatical errors, improve sentence structure, and enhance overall writing style.
Translation and Language Enhancement
Tools: DeepL, Google Translate
Purpose: To translate texts or improve the quality and fluency of the writing in a different language.
Content Generation and Idea Expansion
Tools: ChatGPT, OpenAI Codex
Purpose: To generate initial drafts, expand on ideas, provide suggestions for content, and offer examples.
Coding Assistance
Tools: GitHub Copilot
Purpose: To help with coding tasks, generate code snippets, and provide programming solutions and explanations.
Citation Assistance
Tools: Citation Machine
Purpose: To assist in proper citation formatting.
Data Analysis and Visualization
Tools: MATLAB, Python libraries (e.g., pandas, matplotlib), e.g. with ChatGPT or DataSpell
Purpose: To assist in analyzing data sets, generating graphs, and visualizing data.
What You Need to Do
- Use AI Tools Wisely: Feel encouraged to use AI tools for grammar correction, translation, content generation, coding assistance, plagiarism detection, data analysis and more, but make sure that you have the competencies to judge about the correctness and integrity of the generated content. You are responsible for the output!
- Be Transparent: Include a short paragraph at the end of your proposal, thesis, seminar paper, project report, or any other text that is assessed describing how you used AI. Specify which tools you used, how extensively, for what purposes, and in which sections of your work you have used them.
- Review: Make sure you review all text generated by AI tools and mention this as part of the transparency statement
*/
In preparing this proposal, I utilized Grammarly for grammar and style correction across the Abstract, Introduction, and Conclusion sections, ensuring clarity and coherence in my writing. I used DeepL to enhance language quality and translate parts of the Literature Review. I used ChatGPT to generate initial drafts and expand on ideas in the Introduction and Discussion sections, providing valuable suggestions and examples. Additionally, I used GitHub Copilot to generate code snippets for the developed functionality and code snippets in the Methodology section. I have carefully checked all texts created with these tools to ensure that they are correct and make sense. |
https://github.com/isaacholt100/isaacholt | https://raw.githubusercontent.com/isaacholt100/isaacholt/main/public/maths-notes/4-cambridge%3A-part-III/quantum-computation/quantum-computation.typ | typst | MIT License | #import "../../template.typ": *
#show: doc => template(doc, hidden: (), slides: false)
#let poly = math.op("poly")
#let ip(a, b) = $angle.l #a, #b angle.r$
#let ket(arg) = $#h(0.2pt) | #h(0.2pt) arg #h(0.2pt) angle.r$
#let bra(arg) = $angle.l #h(0.2pt) arg #h(0.2pt) | #h(0.2pt)$
#let braket(..args) = $angle.l #h(1pt) #args.pos().join(h(1pt) + "|" + h(1pt)) #h(1pt) angle.r$
#let Ket(arg) = $lr(| #h(1pt) arg #h(1pt) angle.r)$
#let Bra(arg) = $lr(angle.l #h(1pt) arg #h(1pt) |)$
#let Braket(..args) = $lr(angle.l #h(1pt) #args.pos().join(h(1pt) + "|" + h(1pt)) #h(1pt) angle.r)$
#let span = $op("span")$
#let conj(arg) = $arg^*$
#let expected(arg) = $angle.l arg angle.r$
#let vd(vector) = $bold(vector)$
#let nl = [\ ]
#let End = $"End"$
#let tp = $times.circle$
#let QFT = math.op("QFT")
#let Pr = math.op("Pr")
= Hidden subgroup problem
== Review of Shor's algorithm
#definition[
The *factoring problem* is: given a positive integer $N$, find a non-trivial factor ($!= 1, N$) in time polynomial in $n$ (i.e. $O(poly(n))$), where $n = O(log N)$ is the length of the description of the problem input (memory/space used to store it).
]<def:factoring-problem>
#definition[
An *efficient problem* is one that can be solved in polynomial time.
]<def:efficient-problem>
#remark[
Clasically, the best known factoring algorithm runs in $e^(O(n^(1\/3) (log n)^(2\/3)))$. Shor's algorithm (quantum) runs in $O(n^3)$ by converting factoring into period finding:
- Given input $N$, choose $a < N$ which is coprime to $N$.
- Define $f: ZZ -> ZZ\/N$, $f(x) = a^x mod N$. $f$ is periodic with period $r$ (the order of $a mod N$), i.e. $f(x + r) = f(x)$ for all $x in ZZ$. Finding $r$ allows us to factor $N$.
]
== Period finding
#problem(name: "Periodicity Determination")[
Given an oracle for $f: ZZ\/M -> ZZ\/N$ with promises:
- $f$ is periodic with period $r < M$ (i.e. $forall x in ZZ\/M$, $f(x + r) = f(x)$),
- $f$ is one-to-one in each period (i.e. $forall 0 <= x < y < r$, $f(x) != f(y)$),
find $r$ in time $O(poly(m))$, where $m = O(log M)$.
Clasically, this requires takes time $O\(sqrt(M)\)$.
]<prb:periodicity-determination>
#definition[
Let $f: ZZ\/M -> ZZ\/N$. Let $H_M$ and $H_N$ be quantum state spaces with orthonormal state bases ${ket(i): i in ZZ\/N}$ and ${ket(j): j in ZZ\/M}$. Define the unitary *quantum oracle* for $f$ by $U_f$ by $
U_f ket(x) ket(z) = ket(x) ket(z + f(x)).
$ The first register $ket(x)$ is the *input register*, the last register $ket(z)$ is the *output register*.
]<def:quantum-oracle>
#definition[
The *quantum query complexity* of an algorithm is the number of times it queries $f$ (i.e. uses $U_f$).
]<def:quantum-query-complexity>
#definition[
The *quantum Fourier transform* over $ZZ\/M$ is the unitary defined by its action on the computational basis: $
U_"QFT" ket(x) = 1/sqrt(M) sum_(y = 0)^(M - 1) omega^(x y) ket(y),
$ where $omega = e^(2pi i\/M)$. Note that $U_"QFT"$ requires only $O\((log M)^2\)$ gates to implement, whereas a general unitary requires $O(4^n \/ n)$ elementary gates.
]<def:quantum-fourier-transform>
#lemma[
Let $alpha = e^(2pi i y\/M)$. Then $
sum_(j = 0)^(k - 1) alpha^j = cases(
(1 - alpha^k)/(1 - alpha) = 0 & "if" alpha != 1 "i.e." M divides.not y,
k & "if" alpha = 1 "i.e." M divides y
).
$
]
#lemma(name: "Boosting success probability")[
If a process succeeds with probability $p$ on one trial, then $
Pr("at least one success in" t "trials") = 1 - (1 - p)^t > 1 - delta
$ for $t = log(1\/d)/p$.
]
#theorem(name: "Co-primality Theorem")[
The number of integers less than $r$ that are coprime to $r$ is $O(r\/log log r)$ for large $r$.
]
#algorithm(name: "Quantum Period Finding")[
Let $f: ZZ\/M -> ZZ\/N$ be periodic with period $r < M$ and one-to-one in each period. Let $A = M/r$ be the number of periods. We work over the state space $H_M tp H_N$.
+ Construct the state $1/sqrt(M) sum_(i = 0)^(M - 1) ket(i) ket(0)$.
+ Query $U_f$ on the state, giving $1/sqrt(M) sum_(i = 0)^(M - 1) ket(i) ket(f(i))$.
+ Measure second register in computational basis, giving outcome $y in ZZ\/N$, and input state collapses to $ket("per") = 1/sqrt(A) sum_(j = 0)^(A - 1) ket(x_0 + j r)$, where $f(x_0) = y$ and $0 <= x_0 < r$. TODO: add diagram showing amplitudes for this state.
+ Apply the Quantum Fourier Transform to $ket("per")$: $
QFT ket("per") & = 1/sqrt(M) sum_(y = 0)^(M - 1) 1/sqrt(A) sum_(j = 0)^(A - 1) omega^((x_0 + j r) y) ket(y) \
& = 1/sqrt(M A) sum_(y = 0)^(M - 1) omega^(x_0 y) sum_(j = 0)^(A - 1) omega^(j r y) ket(y) \
& = sqrt(A/M) sum_(k = 0)^(r - 1) omega^(x_0 k M\/r) ket(k M\/r)
$ Note now the outcomes and probabilities are independent of $x_0$, so carry useful information about $r$. TODO add diagram showing amplitudes for this state.
+ Measure $QFT ket("per")$, yielding outcome $c = k_0 M\/r$ for some $0 <= k_0 < r$. So $c/M = k_0/r$. If $k_0$ is corpime to $r$, then the denominator $r_0$ of the simplified fraction $c/M$ is equal to $r$.
+ By the coprimality theorem, the probability that $k_0$ is coprime to $r$ is $O(1\/log log r)$.
+ To check if the computed value $r_0$ of $r$ is correct, compute/query $U_f$ to check if $f(0) = f(r_0)$ (this works since $f$ is periodic and one-to-one in each period, and $r_0 <= r$).
+ Repeat the previous steps $O(log log r) = O(log log M) = O(log m)$ times. This obtains the correct value of $r$ with high probability.
]
#remark[
Why is QFT helpful for period finding?
Let $R = {0, r, ..., (A - 1)r} in ZZ\/M$, so $
ket(R) & = 1/sqrt(A) sum_(k = 0)^(A - 1) ket(k r) \
ket("per") = ket(x_0 + R) & = 1/sqrt(A) sum_(k = 0)^(A - 1) ket(x_0 + k r).
$ For each $x_0 in ZZ\/M$, define the shift operator $k -> x_0 + k$ and the associated linear map $U(x_0): H_M -> H_M$, $ket(k) |-> ket(x_0 + k)$. Since $(ZZ\/M, +)$ is abelian, all $U(x_i)$ commute: $U(x_1) U(x_2) = U(x_1 + x_2) = U(x_2) U(x_1)$. Hence, they have a simultaneous basis of eigenvectors ${ket(chi_k): k in ZZ\/M}$, i.e. for all $k, x_0 in ZZ\/M$, $U(x_0) ket(chi_k) = w(x_0, k) ket(chi_k)$, where $abs(w(x_0, k)) = 1$. The $ket(chi_k)$ are called *shift-invariant states* and form an orthonormal basis for $H_M$.
Now $
ket(R) & = sum_(k = 0)^(M - 1) a_k ket(chi_k), quad a_k "depend only on" r \
ket("per") & = U(x_0) ket(R) = sum_(k = 0)^(M - 1) a_k w(x_0, k) ket(chi_k)
$ So measurement in the $ket(chi_k)$ basis gives outcome $k$ with $Pr(k) = |a_k w(x_0, k)|^2 = |a_k|^2$. Suppose the unitary $U$ maps from the shift-invariant basis to the computational basis: $U: ket(chi_k) |-> ket(k)$.
] |
https://github.com/Breadp4ck/typst-nstu-template | https://raw.githubusercontent.com/Breadp4ck/typst-nstu-template/main/README.md | markdown | ## Typst титульник
[Typst](https://typst.app/) шаблоны для сдачи работ в НГТУ. Просто скачайте и запихайте содержимое папки `nstu_template` в корень проекта. Или, что ещё удобнее, скопируйте его [отсюда](https://typst.app/project/rbKylpB-zyQXlHTANjBIZz).
`main.typ` в таком случае может выглядеть как-то так:
```typst
#import "nstu_template//template.typ": * // Импорт шаблона
// Пример конфигурации
// (многие параметры здесь не обязательны)
#show: project.with(
faculty: "АВТФ", // или ФПМИ, кому что нравится
department: "Кафедра теоретических и прикладных приколов",
discipline: "Численное поедание пельменей",
task_type: "Практическое задание №1",
task_name: "Интегрирование дамплингов по поверхности",
students: (
"<NAME>",
"<NAME>"
),
teachers: ("<NAME>"),
variant: "12",
group: "УЭ-00",
team: "3",
year: "2023",
)
// Здесь и далее пишем отчёт
```
Как это выглядит, можете посмотреть [здесь](example.pdf).
Используемые шрифты: [Raleway](https://fonts.google.com/specimen/Raleway) и [Fira Code](https://github.com/tonsky/FiraCode).
|
|
https://github.com/MatheSchool/typst-g-exam | https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/docs-shiroa/g-exam-doc/configuration.typ | typst | MIT License | #import "mod.typ": *
#show: book-page.with(title: "Configuration")
= Header
The template will include a header in the exam, with the information entered in the template. We can
indicate a logo of the educational center, a description of the exam, subject, content, academic level, …
```typst
#show: g-exam.with(
author: (
name: "<NAME>",
email: "<EMAIL>",
watermark: "Teacher: Carl", ),
school: (
name: "Sunrise Secondary School",
logo: read("./logo.png", encoding: none),
),
exam-info: (
academic-period: "Academic year 2023/2024",
academic-level: "1st Secondary Education",
academic-subject: "Mathematics",
number: "2nd Assessment 1st Exam",
content: "Radicals and fractions",
model: "Model A"
),
)
```
= Student Information
In order for a header in which the student must enter his/her personal data, it must be specified on the
template by means of the ‘show-studen-data’ property indicating how you want this box to appear.
Values can be:
- first-page: It will only appear on the first page.
- odd-pages: It will appear on odd-numbered pages.
- none: The user information box will not appear..
The following example will display student information on the first page.
```typst
#show: g-exam.with(
show-studen-data: "first-page",
)
```
= Scoreboard
We will be able to show a scoreboard, with the points for each question. In order for this table to
appear, we will have to set the show-grade-table a *true*, a *false* so that it doesn’t show up.
```typst
#show: g-exam.with(
show-grade-table: true,
)
```
= Question
To enter the questions, use the q-question, followed by the text of the question. You can include the
score of the question by entering the parameter point.
```typst
#g-question(points: 2)[Question text.]
#v(1fr)
```
To create sub-questions, it will be done in the same way with the q-subquestion, command, which
will be nested to the question asked in the previous line. In the same way, the score of the question
can be indicated, in case of indicating a score to the question and the sub-questions, it will be added
to the total. Therefore, it is advisable to only indicate the score in one level.
The following example asks a first question, with no sub-questions, with a score of two points and a
second question with two sub-questions with a score of 2 points each, which will show that the second
question is worth a total of four points in the scorecard.
```typst
#import "@preview/g-exam:0.3.0": *
#show: g-exam.with()
#g-question(points: 2)[List prime numbers]
#v(1fr)
#g-question[Complete the following sentences]
#g-subquestion(points: 2)[Don Quixote was written by ...]
#v(1fr)
#g-subquestion(points: 2)[The name of the continent we live on is ...]
#v(1fr)
```
= Information in the document’s metadata
If a pdf document is generated, the information will be saved in the document. Such as the author’s
name, e-mail, watermark, exam information, …
```typst
#show: g-exam.with(
author: (
name: "<NAME>",
email: "<EMAIL>",
watermark: "Teacher: Leonhard", ),
school: (
name: "Sunrise Secondary School",
logo: read("./logo.png", encoding: none),
),
exam-info: (
academic-period: "Academic year 2023/2024",
academic-level: "1st Secondary Education",
academic-subject: "Mathematics",
number: "2nd Assessment 1st Exam",
content: "Radicals and fractions",
model: "Model A"
),
```
This information can be consulted in the properties of the pdf document.
= Punctuation Decimal Separator
Depending on the language we use, the decimal separator may change. To specify the decimal sepa-
rator we want to use, we use ‘decimal-separator’ with the values ‘.’ or ‘,’ as follows.
```typst
#show: g-exam.with(
decimal-separator: ",",
)
```
= Font type
For children with special needs, it is recommended to use a larger font, which can cause the entire
document to be out of place. To do this, the question-text-parameters parameter has been created in
which we will indicate the font that will have, only, the content of the questions, leaving the rest of the
text with the same font. In this way, the layout of the document will be maintained in a similar way.
The following example will use a 16-point, double-spaced font for the questions.
```typst
#show: g-exam.with(
question-text-parameters: (size: 16pt, spacing:200%),
)
```
= Languages
You can specify the language in which you want the text to appear. To do this, we use the "languaje"
property. It can take the values "en", "es", "de", "fr", "pt", "it", "nl".
```typst
#show: g-exam.with(
languaje: "es",
)
``` |
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/patterns/weeks/week2.typ | typst | #import "../../utils.typ": *
#subsection("Memento")
#set text(size: 14pt)
Problem | *History* -> Object should remember its own state\
Category | *Behavioral*\
Participants | Originator -> Object in question, Memento -> History, e.g. stack,
Caretaker -> storage, e.g. database
#set text(size: 11pt)
#align(
center, [#image("../../Screenshots/2023_09_29_09_21_19.png", width: 80%)],
)
```java
// Memento
import org.jetbrains.annotations.Nullable;
public class Memento {
private final String savedState;
@Nullable
String getState() {
return savedState;
}
Memento(@Nullable String state) {
savedState = state;
}
}
// Originator
import org.jetbrains.annotations.NotNull;
public class Originator {
private String internalData;
@NotNull
public Memento createMemento() {
return new Memento(internalData);
}
public void setMemento(@NotNull Memento memento) {
internalData = memento.getState();
}
}
```
- similar:
- Serialization
- Future Pattern
#columns(2, [
#text(green)[Benefits]
- Internal state of an object can be saved and restored at any time
- Encapsulation of attributes is not harmed
- State of objects can be restored later
#colbreak()
#text(red)[Liabilities]
- Creates a complete copy of the object every time, no diffs
- May require a lot of memory
- No direct access to saved state, it must be restored first
])
#subsection("Singleton (Base)")
#text(red)[This is explained better later on]
Problem | *Static Instance* -> only 1 object of this type should exist\
Category | *Creational*
#columns(
2, [
#text(green)[Benefits]
- clean solution to single object
- solves dependencies including the singleton object
- solves argument spam in functions
#colbreak()
#text(red)[Liabilities]
- if built wrong can lead to needless mock implementations of a singleton -> mock
singletons for tests
- can lead to race conditions -> not in rust
- might require getDB() calls
],
)
#subsection([Chain of Responsibility])
*Problem* |\
- Coupling the sender of a request to its receiver should be avoided.
- It should be possible that more than one receiver can handle a request.
*Solution* | Define a chain of receiver objects having the responsibility,
depending on run-time conditions, to either handle a request or forward it to
the next receiver on the chain (if any).
// images
#align(center, [#image("../uml/responsibility.jpg", width: 100%)])
```cpp
#include <iostream>
#include <memory>
typedef int Topic;
constexpr Topic NO_HELP_TOPIC = -1;
// defines an interface for handling requests.
class HelpHandler { // Handler
public:
HelpHandler(HelpHandler* h = nullptr, Topic t = NO_HELP_TOPIC)
: successor(h), topic(t) {}
virtual bool hasHelp() {
return topic != NO_HELP_TOPIC;
}
virtual void setHandler(HelpHandler*, Topic) {}
virtual void handleHelp() {
std::cout << "HelpHandler::handleHelp\n";
// (optional) implements the successor link.
if (successor != nullptr) {
successor->handleHelp();
}
}
virtual ~HelpHandler() = default;
HelpHandler(const HelpHandler&) = delete; // rule of three
HelpHandler& operator=(const HelpHandler&) = delete;
private:
HelpHandler* successor;
Topic topic;
};
class Widget : public HelpHandler {
public:
Widget(const Widget&) = delete; // rule of three
Widget& operator=(const Widget&) = delete;
protected:
Widget(Widget* w, Topic t = NO_HELP_TOPIC)
: HelpHandler(w, t), parent(nullptr) {
parent = w;
}
private:
Widget* parent;
};
// handles requests it is responsible for.
class Button : public Widget { // ConcreteHandler
public:
Button(std::shared_ptr<Widget> h, Topic t = NO_HELP_TOPIC) : Widget(h.get(), t) {}
virtual void handleHelp() {
// if the ConcreteHandler can handle the request, it does so; otherwise it forwards the request to its successor.
std::cout << "Button::handleHelp\n";
if (hasHelp()) {
// handles requests it is responsible for.
} else {
// can access its successor.
HelpHandler::handleHelp();
}
}
};
class Dialog : public Widget { // ConcreteHandler
public:
Dialog(std::shared_ptr<HelpHandler> h, Topic t = NO_HELP_TOPIC) : Widget(nullptr) {
setHandler(h.get(), t);
}
virtual void handleHelp() {
std::cout << "Dialog::handleHelp\n";
// Widget operations that Dialog overrides...
if(hasHelp()) {
// offer help on the dialog
} else {
HelpHandler::handleHelp();
}
}
};
class Application : public HelpHandler {
public:
Application(Topic t) : HelpHandler(nullptr, t) {}
virtual void handleHelp() {
std::cout << "Application::handleHelp\n";
// show a list of help topics
}
};
int main() {
constexpr Topic PRINT_TOPIC = 1;
constexpr Topic PAPER_ORIENTATION_TOPIC = 2;
constexpr Topic APPLICATION_TOPIC = 3;
// The smart pointers prevent memory leaks.
std::shared_ptr<Application> application = std::make_shared<Application>(APPLICATION_TOPIC);
std::shared_ptr<Dialog> dialog = std::make_shared<Dialog>(application, PRINT_TOPIC);
std::shared_ptr<Button> button = std::make_shared<Button>(dialog, PAPER_ORIENTATION_TOPIC);
button->handleHelp();
}
```
#columns(2, [
#text(green)[Benefits]
- events are handled by the first to be able to
- concrete handling of events that no handler can process
#colbreak()
#text(red)[Liabilities]
- all events will be passed through the chain
- might sometimes be slow -> last of chain
- multithreaded non-hierarchical is faster here
])
|
|
https://github.com/kdog3682/2024-typst | https://raw.githubusercontent.com/kdog3682/2024-typst/main/examples/cetz-karl-circle.typ | typst | // #import "@preview/cetz:0.2.1"
#import "@preview/cetz:0.2.0"
#set page(width: auto, height: auto, margin: .5cm)
#show math.equation: block.with(fill: white, inset: 1pt)
// this is a pretty nifty feature.
#cetz.canvas(length: 3cm, {
import cetz.draw: *
set-style(
mark: (fill: black, scale: 2),
stroke: (thickness: 0.4pt, cap: "round"),
angle: (
radius: 0.3,
label-radius: .22,
fill: green.lighten(80%),
stroke: (paint: green.darken(50%))
),
content: (padding: 1pt)
)
grid((-1.5, -1.5), (1.4, 1.4), step: 0.5, stroke: gray + 0.2pt)
circle((0,0), radius: 1)
line((-1.5, 0), (1.5, 0), mark: (end: "stealth"))
content((), $ x $, anchor: "west")
line((0, -1.5), (0, 1.5), mark: (end: "stealth"))
content((), $ y $, anchor: "south")
for (x, ct) in ((-1, $ -1 $), (-0.5, $ -1/2 $), (1, $ 1 $)) {
line((x, 3pt), (x, -3pt))
content((), anchor: "north", ct)
}
for (y, ct) in ((-1, $ -1 $), (-0.5, $ -1/2 $), (0.5, $ 1/2 $), (1, $ 1 $)) {
line((3pt, y), (-3pt, y))
content((), anchor: "east", ct)
}
// Draw the green angle
cetz.angle.angle((0,0), (1,0), (1, calc.tan(30deg)),
label: text(green, [#sym.alpha]))
line((0,0), (1, calc.tan(30deg)))
set-style(stroke: (thickness: 1.2pt))
line((30deg, 1), ((), "|-", (0,0)), stroke: (paint: red), name: "sin")
content(("sin.start", 50%, "sin.end"), text(red)[$ sin alpha $])
line("sin.end", (0,0), stroke: (paint: blue), name: "cos")
content(("cos.start", 50%, "cos.end"), text(blue)[$ cos alpha $], anchor: "north")
line((1, 0), (1, calc.tan(30deg)), name: "tan", stroke: (paint: orange))
content("tan.end", $ text(#orange, tan alpha) = text(#red, sin alpha) / text(#blue, cos alpha) $, anchor: "west")
})
|
|
https://github.com/cwreed/cv | https://raw.githubusercontent.com/cwreed/cv/main/README.md | markdown | # Connor's CV
This is a small library I use to create my CV and resume(s) with [typst](https://github.com/typst/typst). The template and style is heavily inspired by the [brilliant-CV](https://github.com/mintyfrankie/brilliant-CV/tree/main) project.
## Commands
```
make download-fonts # download open source fonts used in project
make build # build Docker image for typst
make fmt # format .typ files
make lint # lint .typ files
make compile-cv # compile CV into PDF
make compile-resume # compile resume into PDF
```
## System requirements
* `docker`
* `make`
* `jq` |
|
https://github.com/xrarch/books | https://raw.githubusercontent.com/xrarch/books/main/xr17032handbook/chapcache.typ | typst | = Memory Caching
== Introduction
Modern computer systems contain memory subsystems that produce results in a time several factors slower than the processing unit can accept them, creating a substantial performance bottleneck. The general solution to this is to add fast "cache" memory close to the processor, in which frequently or recently used memory is kept, and waits upon the machine's memory subsystem to respond can be avoided.
== Managing the Caches
The XR/17032 architecture contains a "split cache" scheme, where instruction bytes and data bytes are cached separately in an Icache and Dcache, respectively. The software-visible effects that these caches have are as follows:
1. The Icache is never automatically kept in sync with the Dcache or with the contents of memory. If the instruction stream is written into, for instance due to copying a program in memory, the Icache must be manually flushed. Otherwise, stale instruction bytes may be executed, causing problems that are hard to diagnose.
2. Depending on the platform, the Dcache may or may not be kept in sync with external device activity (i.e. a DMA transfer into memory from a disk controller). If it isn't, then manual Dcache flushes are required after these events, or stale data bytes might be seen.
3. This is an explicit statement of something that must _not_ be visible to software: in a multiprocessor system, the Dcache of each processor _must_ be kept in sync with the Dcache of all other processors in the system through some coherency protocol.
Due to these issues, among other reasons, the paging architecture includes an *N* bit in the PTE format which indicates that accesses to that page should bypass the Dcache. This bit should be used when mapping pages containing device registers for driver access.
While virtual address translation is disabled, for instance at system reset, the cache is bypassed for all accesses to physical addresses at or above 0xC0000000 (3GB). For this reason, it is advisable for a platform to place device registers in this region of the physical address space, to allow boot firmware to easily manipulate them. It is also advised to immediately copy the boot firmware from the ROM in high memory to RAM in low memory and execute it from there instead, or else it will execute noncached (that is, extremely slowly).
For detailed information on how to flush either a single page or the entirety of the Icache or Dcache, see @cachectrl.
== The Caches and XR/computer Systems
This information is included here for quick reference, and strictly speaking, belongs in these systems' respective manuals.
Neither the XR/station desktop, the XR/MP deskside server, nor the XR/frame minicomputer keep Dcache coherency with device activity. When a DMA transfer completes, the system software must be sure to flush the Dcache appropriately.
On multiprocessor configurations such as the XR/MP and XR/frame systems, the processor that handles an I/O request completion must be sure to send an IPI (inter-processor interrupt) to the other processors to ensure that they flush their Dcache as well (a "Dcache shootdown"). |
|
https://github.com/mitsuyukiLab/grad_thesis_typst | https://raw.githubusercontent.com/mitsuyukiLab/grad_thesis_typst/main/lib/grad_thesis_lib.typ | typst | #let textL = 24pt
#let textM = 20pt
#let textS = 16pt
#let text_main = 12pt
#let mincho = ("Times New Roman", "MS Mincho", "IPAMincho", "Noto Serif CJK JP", "Hiragino Mincho Pro")
#let gothic = ("Times New Roman", "MS Gothic", "IPAGothic", "Noto Sans CJK JP", "Hiragino Kaku Gothic Pro")
// Store theorem environment numbering
#let thmcounters = state("thm",
(
"counters": ("heading": ()),
"latest": ()
)
)
// Setting theorem environment
#let thmenv(identifier, base, base_level, fmt) = {
let global_numbering = numbering
return (
..args,
body,
number: auto,
numbering: "1.1",
refnumbering: auto,
supplement: identifier,
base: base,
base_level: base_level
) => {
let name = none
if args != none and args.pos().len() > 0 {
name = args.pos().first()
}
if refnumbering == auto {
refnumbering = numbering
}
let result = none
if number == auto and numbering == none {
number = none
}
if number == auto and numbering != none {
result = context{
return thmcounters.update(thmpair => {
let counters = thmpair.at("counters")
// Manually update heading counter
counters.at("heading") = counter(heading).at(here())
if not identifier in counters.keys() {
counters.insert(identifier, (0, ))
}
let tc = counters.at(identifier)
if base != none {
let bc = counters.at(base)
// Pad or chop the base count
if base_level != none {
if bc.len() < base_level {
bc = bc + (0,) * (base_level - bc.len())
} else if bc.len() > base_level{
bc = bc.slice(0, base_level)
}
}
// Reset counter if the base counter has updated
if tc.slice(0, -1) == bc {
counters.at(identifier) = (..bc, tc.last() + 1)
} else {
counters.at(identifier) = (..bc, 1)
}
} else {
// If we have no base counter, just count one level
counters.at(identifier) = (tc.last() + 1,)
let latest = counters.at(identifier)
}
let latest = counters.at(identifier)
return (
"counters": counters,
"latest": latest
)
})
}
number = thmcounters.display(x => {
return global_numbering(numbering, ..x.at("latest"))
})
}
return figure(
result + // hacky!
fmt(name, number, body, ..args.named()) +
[#metadata(identifier) <meta:thmenvcounter>],
kind: "thmenv",
outlined: false,
caption: none,
supplement: supplement,
numbering: refnumbering,
)
}
}
// Definition of theorem box
#let thmbox(
identifier,
head,
..blockargs,
supplement: auto,
padding: (top: 0.5em, bottom: 0.5em),
namefmt: x => [(#x)],
titlefmt: strong,
bodyfmt: x => x,
separator: [#h(0.1em):#h(0.2em)],
base: "heading",
base_level: none,
) = {
if supplement == auto {
supplement = head
}
let boxfmt(name, number, body, title: auto) = {
if not name == none {
name = [ #namefmt(name)]
} else {
name = []
}
if title == auto {
title = head
}
if not number == none {
title += " " + number
}
title = titlefmt(title)
body = bodyfmt(body)
pad(
..padding,
block(
width: 100%,
inset: 1.2em,
radius: 0.3em,
breakable: false,
..blockargs.named(),
[#title#name#separator#body]
)
)
}
return thmenv(
identifier,
base,
base_level,
boxfmt
).with(
supplement: supplement,
)
}
// Definition of content to string
#let to-string(content) = {
if content.has("text") {
content.text
} else if content.has("children") {
content.children.map(to-string).join("")
} else if content.has("body") {
to-string(content.body)
} else if content == [ ] {
" "
}
}
// Definition of chapter outline
#let toc() = {
align(left)[
#text(size: textM)[
#v(30pt)
目次
#v(30pt)
]
]
set text(size: text_main)
set par(leading: 1.24em, first-line-indent: 0pt)
context{
let elements = query(heading.where(outlined: true))
for el in elements {
let before_toc = query(heading.where(outlined: true).before(here())).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())[#{
// acknoledgement 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(font: gothic)
if chapt_num == none {} else {
chapt_num
" "
}
let rebody = to-string(el.body)
rebody
} else if el.level == 2 {
h(2em)
chapt_num
" "
let rebody = to-string(el.body)
rebody
} else {
h(5em)
chapt_num
" "
let rebody = to-string(el.body)
rebody
}
}]
box(width: 1fr, h(0.5em) + box(width: 1fr, repeat[.]) + h(0.5em))
[#page_num]
linebreak()
}
}
}
// Counting figure number
#let img_num(_) = {
context{
let chapt = counter(heading).at(here()).at(0)
let c = counter("image-chapter" + str(chapt))
let n = c.at(here()).at(0)
str(chapt) + "." + str(n + 1)
}
}
// Definition of figure outline
#let toc_img() = {
align(left)[
#text(size: textM)[
#v(30pt)
図目次
#v(30pt)
]
]
set text(size: text_main)
set par(leading: 1.24em, first-line-indent: 0pt)
context{
let elements = query(figure.where(outlined: true, kind: "image"))
for el in elements {
let chapt = counter(heading).at(el.location()).at(0)
let num = counter(el.kind + "-chapter" + str(chapt)).at(el.location()).at(0) + 1
let page_num = counter(page).at(el.location()).first()
let caption_body = to-string(el.caption.body)
"Fig. "
str(chapt)
"."
str(num)
h(1em)
caption_body
box(width: 1fr, h(0.5em) + box(width: 1fr, repeat[.]) + h(0.5em))
[#page_num]
linebreak()
}
}
}
// Counting table number
#let table_num(_) = {
context{
let chapt = counter(heading).at(here()).at(0)
let c = counter("table-chapter" + str(chapt))
let n = c.at(here()).at(0)
str(chapt) + "." + str(n + 1)
}
}
// Definition of table outline
#let toc_table() = {
align(left)[
#text(size: textM)[
#v(30pt)
表目次
#v(30pt)
]
]
set text(size: text_main)
set par(leading: 1.24em, first-line-indent: 0pt)
context{
let elements = query(figure.where(outlined: true, kind: "table"))
for el in elements {
let chapt = counter(heading).at(el.location()).at(0)
let num = counter(el.kind + "-chapter" + str(chapt)).at(el.location()).at(0) + 1
let page_num = counter(page).at(el.location()).first()
let caption_body = to-string(el.caption.body)
"Table "
str(chapt)
"."
str(num)
h(1em)
caption_body
box(width: 1fr, h(0.5em) + box(width: 1fr, repeat[.]) + h(0.5em))
[#page_num]
linebreak()
}
}
}
// Counting equation number
#let equation_num(_) = {
context{
let chapt = counter(heading).at(here()).at(0)
let c = counter("equation-chapter" + str(chapt))
let n = c.at(here()).at(0)
"(" + str(chapt) + "." + str(n + 1) + ")"
}
}
#let abstract(body) = {
v(6em)
text(size: textM, weight: "bold")[Abstract]
v(2em)
body
pagebreak(weak: true)
}
#let thesis(
type: "",
title: "",
title_en: "",
submittion_date: none,
supervisor_name: none,
supervisor_title: none,
author_name: "",
author_student_id:"",
author_affiliation_1: "",
author_affiliation_2: "",
author_affiliation_3: "",
author_affiliation_4: "",
body
) = {
// counting caption number
show figure: it => {
set align(center)
v(text_main)
if it.kind == "image" {
set text(size: text_main)
it.body
it.supplement
" " + it.counter.display(it.numbering)
" " + it.caption.body
context{
let chapt = counter(heading).at(here()).at(0)
let c = counter("image-chapter" + str(chapt))
c.step()
}
} else if it.kind == "table" {
set text(size: text_main)
it.supplement
" " + it.counter.display(it.numbering)
" " + it.caption.body
it.body
context{
let chapt = counter(heading).at(here()).at(0)
let c = counter("table-chapter" + str(chapt))
c.step()
}
} else {
it
}
v(text_main)
}
show math.equation: it => {
it
context{
let chapt = counter(heading).at(here()).at(0)
let c = counter("equation-chapter" + str(chapt))
c.step()
}
}
set document(author: author_name, title: title)
// Configure the page.
set page(
paper: "a4",
// margin: (top: 25mm, bottom: 22mm, x: 17mm)
)
// Font
set text(size: text_main, font: mincho, lang: "ja")
// citation number
show ref: it => {
if it.element != none and it.element.func() == figure {
let el = it.element
let location = el.location()
let chapt = counter(heading).at(location).at(0)
link(location)[#if el.kind == "image" or el.kind == "table" {
// counting
let num = counter(el.kind + "-chapter" + str(chapt)).at(location).at(0) + 1
it.element.supplement
" "
str(chapt)
"."
str(num)
} else if el.kind == "thmenv" {
let thms = query(selector(<meta:thmenvcounter>).after(location))
let number = thmcounters.at(thms.first().location()).at("latest")
it.element.supplement
" "
numbering(it.element.numbering, ..number)
} else {
it
}
]
} else if it.element != none and it.element.func() == math.equation {
let el = it.element
let location = el.location()
let chapt = counter(heading).at(location).at(0)
link(location)[
#{
let num = counter("equation" + "-chapter" + str(chapt)).at(location).at(0) + 1
it.element.supplement
" ("
str(chapt)
"."
str(num)
")"
}
]
} else if it.element != none and it.element.func() == heading {
let el = it.element
let location = el.location()
let num = numbering(el.numbering, ..counter(heading).at(location))
if el.level == 1 {
let levels = counter(heading).at(location)
"第"
str(levels.first())
"章"
} else if el.level == 2 {
str(num)
"節"
} else if el.level == 3 {
str(num)
"項"
}
} else {
it
}
}
// Configure lists.
set enum(indent: text_main, body-indent: text_main)
set list(indent: text_main, body-indent: text_main)
// Heading
set heading(numbering: (..nums) => {
if nums.pos().len() > 1 {
nums.pos().map(str).join(".") + " "
} else {
text(cjk-latin-spacing: none)[第 #str(nums.pos().first()) 章]
h(0.5em)
}
})
show heading: it => context{
// Find out the final number of the heading counter.
let levels = counter(heading).at(here())
let deepest = if levels != () {
levels.last()
} else {
1
}
if it.level == 1 [
#pagebreak()
// First-level headings are centered smallcaps.
// We don't want to number of the acknowledgment section.
#v(30pt)
#set par(first-line-indent: 0pt)
#let is-ack = it.body in ([謝辞], [謝 辞], [謝 辞], [Acknowledgement])
#set text(size: textM, font: gothic)
#if it.numbering != none and not is-ack {
text(cjk-latin-spacing: none)[第 #str(levels.first()) 章]
h(8pt, weak: true)
}
#it.body
#v(30pt, weak: true)
] else if it.level == 2 [
#v(text_main)
// The other level headings are run-ins.
#set par(first-line-indent: 0pt)
#set text(size: textS, font: gothic)
#if it.numbering != none {
numbering("1.1", ..levels)
h(8pt, weak: true)
}
#it.body
] else [
#v(text_main)
// The other level headings are run-ins.
#set par(first-line-indent: 0pt)
#set text(size: text_main, font: gothic)
#v(1pt)
#if it.numbering != none {
numbering("1.1", ..levels)
h(8pt, weak: true)
}
#it.body
]
}
show figure.where(kind: "table"): set figure(placement: top, supplement: [Table ], numbering: table_num)
show figure.where(kind: "table"): set figure.caption(position: top, separator: [ ])
show figure.where(kind: "image"): set figure(placement: top, supplement: [Fig.], numbering: img_num)
show figure.where(kind: "image"): set figure.caption(position: bottom, separator: [ ])
show math.equation: set math.equation(supplement: [式], numbering: equation_num)
// Display block code in a larger block with more padding.
show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
width: 100%,
)
show raw.where(block: true): code => {
show raw.line: line => {
text(fill: gray)[#line.number]
h(1em)
line.body
}
code
linebreak(justify: false)
}
// Outline
show outline.entry.where(
level: 1
): it => {
v(0.2em)
it
}
align(center)[
#v(1cm)
#block(text(textS)[#type])
// Title row.
#align(horizon)[
#block(text(textL, title))
#v(1em)
#block(text(textM, title_en))
]
#v(10em)
#block(text(textS)[#submittion_date 提出])
#v(2em)
#block(text(textS)[指導教員 #supervisor_name #supervisor_title])
#v(4em)
// Author information.
#block(text(textS)[#author_affiliation_1])
#block(text(textS)[#author_affiliation_2 #author_affiliation_3])
#block(text(textS)[#author_affiliation_4])
#v(2em)
#block(text(textM)[#author_student_id #author_name])
]
pagebreak(weak: true)
set par(leading: 1.00em, first-line-indent: 1.00em, justify: true)
body
} |
|
https://github.com/david-davies/typst-prooftree | https://raw.githubusercontent.com/david-davies/typst-prooftree/main/examples/prooftree_test.typ | typst | MIT License | #import "../src/prooftrees.typ"
#import "../src/internal.typ"
#let vdash = [⊢]
#set rect(stroke: .5pt)
#let mk_err_str(message) = "Prooftrees INTERNAL ERROR: " + message
#set table(stroke: none)
#let asmN = [assumption#sub[n]]
#let sans_font = "DejaVu Sans"
#let sans_font_opts = (font: sans_font, size: .82em)
#let tsans = (..args) => text(..sans_font_opts, ..args)
#let box_label(..text_opts, loc: top + left, inset: -2pt, b) = {
place(loc, dx: inset, dy: inset,
tsans(size: .7em, ..text_opts)[#b])
}
#let horizons(..haligns) = haligns.pos().map(a => horizon + a)
= Examples
== Tree Display
Here we display some pre-defined structured trees (i.e. they have already been parsed).
#let _str_tree1 = internal._str_axi[$A => A$]
#let _str_tree2 = internal._str_uni(_str_tree1)[$A => A^2^3^4^(5^6), B$]
#let _str_tree2b = internal._str_uni(_str_tree1)[$A => A^(2^3)^4, B^1$]
#let _str_tree3 = internal._str_bin(_str_tree1, _str_tree2)[$A, B => A^1, B$]
#let _str_tree4 = internal._test_mk_str_tree_((_str_tree3,_str_tree1,_str_tree2b,_str_tree1))[$Gamma$]
#let _str_tree5 = internal._test_mk_str_tree_((_str_tree2b,_str_tree1,_str_tree4,_str_tree1))[$Gamma$]
#let _str_tree6 = internal._test_mk_str_tree_((_str_tree4,_str_tree4))[$Gamma$]
Here is an axiom:
#prooftrees._show_str_tree(_str_tree1)
Here is tree2:
#prooftrees._show_str_tree(_str_tree2)
Here is tree3:
#prooftrees._show_str_tree(_str_tree3)
Here is tree4:
#prooftrees._show_str_tree(_str_tree4)
Here is tree5:
#prooftrees._show_str_tree(_str_tree5)
Here is tree6:
#prooftrees._show_str_tree(_str_tree6)
=== Left-shifted Line Bug
Trying to figure out why the line is sometimes shifted to the left.
#let lsh_tree_axi_1 = internal._str_axi[$A => AA AA AA AA AA AA AA$]
#let lsh_tree_uni_1 = internal._str_uni(lsh_tree_axi_1)[$A => B, A$]
#let lsh_tree_axi_2 = internal._str_axi[$A => A^1^3^4^5$]
#let lsh_tree_uni_2 = internal._str_uni(lsh_tree_axi_2)[$A => B, A$]
#let lsh_tree_2 = internal._test_mk_str_tree_((lsh_tree_uni_1, lsh_tree_uni_1,lsh_tree_axi_1,lsh_tree_uni_2))[$B => A$]
A first tree:
#prooftrees._show_str_tree(lsh_tree_2)
== Tree Parsing
Testing from parsing to displaying.
=== Line-by-Line Trees
The line-by-line style of defining trees.
==== Simple
#let raw_1 = prooftrees.axi[$A => A$]
// #let raw_2 = prooftrees.uni[$A => B$]
First example is the tree `raw_1`.
#prooftrees.tree(raw_1)f
A second tree will be:
#prooftrees.tree(
prooftrees.axi[$B => AA$],
prooftrees.uni[$A => B f f f f f f f f f f f f f f f f f$]
)
A third
#prooftrees.tree(
prooftrees.axi(left_label: [e], right_label: [H])[$A => A$],
prooftrees.uni(left_label: [$(equiv)$], right_label: [H])[$A => B f f f f f $],
prooftrees.uni[$A => C f$]
)
Now for a binary tree:
#prooftrees.tree(
prooftrees.axi[$A => A$],
prooftrees.axi[$A => A f f g f g f f$],
prooftrees.uni[$A => B$],
prooftrees.bin[$A => B$],
)
A larger tree:
#prooftrees.tree(
prooftrees.axi[$A => A $],
prooftrees.axi[$A => A $],
prooftrees.uni[$B => B$],
prooftrees.axi[$A => A $],
prooftrees.axi[$A => A f f $],
prooftrees.uni[$A => B$],
prooftrees.bin[$A => B$],
prooftrees.axi[$A => A f g$],
prooftrees.axi[$A => A f g g g g g g g g g g g g$],
prooftrees.uni[$A => B$],
prooftrees.bin[$A => B C$],
prooftrees.nary(4)[$A => B$],
)
Right-heavy tree:
#prooftrees.tree(
prooftrees.axi[$ A => A f g g g g g g g g g g g g $],
prooftrees.axi[$A => B g g g g g g g g g g g$],
prooftrees.axi[$A => A f g g g g g g g g g g g g$],
prooftrees.bin[$ A => A f g g g g g g g g g g g g $],
prooftrees.bin[$ A => A f g g g g g g g g g g g g $],
prooftrees.axi[$A => B g g g g g g g g g g g$],
prooftrees.axi[$A => A f g g g g g g g g g g g g$],
prooftrees.bin[$ A => A f g g g g g g g g g g g g $],
prooftrees.bin[$ A => A f g g g g g g g g g g g g $],
)
We want an off-centre tree:
#prooftrees.tree(
prooftrees.axi[$A vdash A$],
prooftrees.uni[$A vdash A, B$],
prooftrees.axi[$C vdash C $],
prooftrees.bin[$A, C vdash A and C, B$],
prooftrees.uni[$A, C vdash (A and C) or B$]
)
== Labels
Currently, labels are not well-placed and require much user intervention.
=== Simple
A tree with labels.
#prooftrees.tree(
prooftrees.axi(left_label: [e], right_label: [H])[$A => A$],
prooftrees.uni(left_label: [$(equiv)$], right_label: [H])[$A => B f f f f f $],
prooftrees.uni[$A => C f$]
)
== Spot-check Examples
=== Wide premises
Larger premise-of-premise than conclusion.
#prooftrees.tree(
prooftrees.axi[$A A A A A A A A A A A A A A A$],
prooftrees.uni[$A$],
prooftrees.uni[$B => A$]
)
Larger premise-of-left-premise than conclusion.
#prooftrees.tree(
prooftrees.axi[$A A A A A A A A A A A A A A A$],
prooftrees.uni[$A$],
prooftrees.axi[$A A A A A A A A A$],
prooftrees.bin[$B => A$]
)
=== Custom Lines
#prooftrees.tree(
prooftrees.axi[$A A A A A A A A A A A A A A A$],
prooftrees.uni(line_config: (stroke: (dash: "dashed")))[$A$],
prooftrees.axi[$A A A A A A A A A$],
prooftrees.bin(line_config: (stroke: 2.5pt + blue, overhang_l: 20pt))[$B => A$]
)
== From the README
First:
#prooftrees.tree(
prooftrees.axi[$A => A$],
prooftrees.uni[$A => A, B$]
)
Second:
#prooftrees.tree(
prooftrees.axi[$B => B$],
prooftrees.uni[$B => B, A$],
prooftrees.uni[$B => A, B$],
prooftrees.axi[$A => A$],
prooftrees.uni[$A => A, B$],
prooftrees.bin[$B => A, B$]
)
N-ary:
#prooftrees.tree(
prooftrees.axi(pad(bottom: 2pt, [$P_1$])),
prooftrees.axi(pad(bottom: 2pt, [$P_2$])),
prooftrees.axi(pad(bottom: 2pt, [$P_3$])),
prooftrees.axi(pad(bottom: 2pt, [$P_4$])),
prooftrees.axi(pad(bottom: 2pt, [$P_5$])),
prooftrees.axi(pad(bottom: 2pt, [$P_6$])),
prooftrees.nary(6)[$C$],
)
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history_CN/2010/MS-10.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (1 - 32)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[1], [马龙], [CHN], [3264],
[2], [张继科], [CHN], [3142],
[3], [王皓], [CHN], [3134],
[4], [蒂姆 波尔], [GER], [3115],
[5], [马琳], [CHN], [3108],
[6], [王励勤], [CHN], [3073],
[7], [许昕], [CHN], [3019],
[8], [弗拉基米尔 萨姆索诺夫], [BLR], [2993],
[9], [朱世赫], [KOR], [2962],
[10], [郝帅], [CHN], [2939],
[11], [陈玘], [CHN], [2910],
[12], [水谷隼], [JPN], [2871],
[13], [克里斯蒂安 苏斯], [GER], [2857],
[14], [阿德里安 克里桑], [ROU], [2793],
[15], [米凯尔 梅兹], [DEN], [2791],
[16], [迪米特里 奥恰洛夫], [GER], [2781],
[17], [帕特里克 鲍姆], [GER], [2770],
[18], [蒂亚戈 阿波罗尼亚], [POR], [2759],
[19], [高宁], [SGP], [2743],
[20], [唐鹏], [HKG], [2731],
[21], [柳承敏], [KOR], [2725],
[22], [庄智渊], [TPE], [2717],
[23], [岸川圣也], [JPN], [2716],
[24], [高礼泽], [HKG], [2700],
[25], [李廷佑], [KOR], [2684],
[26], [MATTENET Adrien], [FRA], [2678],
[27], [博扬 托基奇], [SLO], [2671],
[28], [维尔纳 施拉格], [AUT], [2653],
[29], [李静], [HKG], [2646],
[30], [吴尚垠], [KOR], [2640],
[31], [吉田海伟], [JPN], [2614],
[32], [侯英超], [CHN], [2610],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (33 - 64)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[33], [阿列克谢 斯米尔诺夫], [RUS], [2605],
[34], [CHTCHETININE Evgueni], [BLR], [2603],
[35], [HABESOHN Daniel], [AUT], [2603],
[36], [SEO Hyundeok], [KOR], [2591],
[37], [GERELL Par], [SWE], [2580],
[38], [佐兰 普里莫拉克], [CRO], [2579],
[39], [帕纳吉奥迪斯 吉奥尼斯], [GRE], [2579],
[40], [江天一], [HKG], [2578],
[41], [郑荣植], [KOR], [2576],
[42], [尹在荣], [KOR], [2575],
[43], [上田仁], [JPN], [2575],
[44], [SIMONCIK Josef], [CZE], [2574],
[45], [SKACHKOV Kirill], [RUS], [2573],
[46], [彼得 科贝尔], [CZE], [2563],
[47], [KIM Junghoon], [KOR], [2554],
[48], [约尔根 佩尔森], [SWE], [2553],
[49], [卡林尼科斯 格林卡], [GRE], [2546],
[50], [陈卫星], [AUT], [2537],
[51], [马克斯 弗雷塔斯], [POR], [2536],
[52], [LI Ping], [QAT], [2531],
[53], [金珉锡], [KOR], [2530],
[54], [罗伯特 加尔多斯], [AUT], [2528],
[55], [SALIFOU Abdel-Kader], [FRA], [2523],
[56], [KOSOWSKI Jakub], [POL], [2519],
[57], [巴斯蒂安 斯蒂格], [GER], [2502],
[58], [PROKOPCOV Dmitrij], [CZE], [2501],
[59], [让 米歇尔 赛弗], [BEL], [2496],
[60], [李尚洙], [KOR], [2496],
[61], [SVENSSON Robert], [SWE], [2494],
[62], [GORAK Daniel], [POL], [2494],
[63], [BENTSEN Allan], [DEN], [2492],
[64], [LEGOUT Christophe], [FRA], [2477],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (65 - 96)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[65], [艾曼纽 莱贝松], [FRA], [2471],
[66], [沙拉特 卡马尔 阿昌塔], [IND], [2470],
[67], [韩阳], [JPN], [2469],
[68], [MACHADO Carlos], [ESP], [2461],
[69], [JAKAB Janos], [HUN], [2459],
[70], [KARAKASEVIC Aleksandar], [SRB], [2455],
[71], [BLASZCZYK Lucjan], [POL], [2452],
[72], [斯特凡 菲格尔], [AUT], [2452],
[73], [MONTEIRO Joao], [POR], [2449],
[74], [张钰], [HKG], [2448],
[75], [张一博], [JPN], [2448],
[76], [LEE Jungsam], [KOR], [2448],
[77], [WANG Zengyi], [POL], [2446],
[78], [KIM Hyok Bong], [PRK], [2441],
[79], [LIN Ju], [DOM], [2438],
[80], [KEINATH Thomas], [SVK], [2437],
[81], [FEJER-KONNERTH Zoltan], [GER], [2433],
[82], [安德烈 加奇尼], [CRO], [2427],
[83], [<NAME>], [ESP], [2426],
[84], [闫安], [CHN], [2424],
[85], [HE Zhiwen], [ESP], [2423],
[86], [KOSIBA Daniel], [HUN], [2423],
[87], [松平健太], [JPN], [2422],
[88], [<NAME>], [ARG], [2421],
[89], [<NAME>], [ESP], [2417],
[90], [<NAME>], [SRB], [2417],
[91], [RUBTSOV Igor], [RUS], [2411],
[92], [<NAME>], [RUS], [2408],
[93], [<NAME>], [TPE], [2394],
[94], [JUZBASIC Ivan], [CRO], [2391],
[95], [CHO Eonrae], [KOR], [2390],
[96], [TAN Ruiwu], [CRO], [2385],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (97 - 128)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[97], [WU Chih-Chi], [TPE], [2382],
[98], [SHIBAEV Alexander], [RUS], [2376],
[99], [<NAME>], [KOR], [2373],
[100], [HENZELL William], [AUS], [2372],
[101], [<NAME>], [SRB], [2369],
[102], [<NAME>], [JPN], [2367],
[103], [<NAME>], [CZE], [2366],
[104], [<NAME>], [EGY], [2358],
[105], [<NAME>], [MEX], [2356],
[106], [<NAME>], [PRK], [2355],
[107], [<NAME>], [POL], [2352],
[108], [詹斯 伦德奎斯特], [SWE], [2352],
[109], [<NAME>], [SGP], [2352],
[110], [<NAME>], [SGP], [2347],
[111], [<NAME>], [RUS], [2340],
[112], [<NAME>], [JPN], [2337],
[113], [<NAME>], [SVK], [2334],
[114], [<NAME>], [CZE], [2331],
[115], [<NAME>], [KOR], [2326],
[116], [<NAME>], [SVK], [2324],
[117], [雅罗斯列夫 扎姆登科], [UKR], [2322],
[118], [MONTEIRO Thiago], [BRA], [2321],
[119], [TSUBOI Gustavo], [BRA], [2319],
[120], [卢文 菲鲁斯], [GER], [2319],
[121], [LEUNG <NAME>], [HKG], [2318],
[122], [LASAN Sas], [SLO], [2317],
[123], [ELOI Damien], [FRA], [2312],
[124], [BUR<NAME>], [LAT], [2307],
[125], [VANG Bora], [TUR], [2304],
[126], [JANG Song Man], [PRK], [2304],
[127], [#text(gray, "<NAME>")], [DEN], [2296],
[128], [<NAME>], [ROU], [2296],
)
) |
|
https://github.com/Functional-Bus-Description-Language/Specification | https://raw.githubusercontent.com/Functional-Bus-Description-Language/Specification/master/src/functionalities/blackbox.typ | typst | == Blackbox
The blackbox functionality is used to incorporate blocks implemented manually or generated by external tools.
For example, a user may want to explicitly manage some particular registers' layouts.
In such a case, a register-centric tool might be used, and the generated block can be incorporated into the wrapping functionality-centric description using the blackbox functionality.
The blackbox functionality has following properties:
*`size`*` integer (obligatory) [definitive]`
#pad(left: 1em)[
The size property defines size of the blackbox in the number of words with width equal to the width property value of the block in which blackbox is defined.
]
The code generated for the requester should not provide any means for accessing the blackbox.
The code generated for the provider must provide a means to connect the blackbox to the remaining part of the bus generated by an FBDL compiler.
|
|
https://github.com/EricWay1024/Computational-AT-mini-project | https://raw.githubusercontent.com/EricWay1024/Computational-AT-mini-project/main/main.typ | typst | #import "template.typ": *
#show: thmrules
#show: project.with(
title: "Discrete Morse Theory for Persistent Homology for Sequences of Cosheaves",
subtitle: [A mini-project submitted for the course of
_C3.9 Computational Algebraic Topology_],
author: "Candidate Number 1079278",
date: "Hilary Term, 2024"
)
#pagebreak()
// #TODO[reminder: add punctuations to displayed formulae]
= Introduction
The goal of this project is to describe how discrete Morse theory can be used to simplify the computation of persistent homology for sequences of cosheaves over finite simplicial complexes.
Throughout this project, let $K$ be a finite simplicial complex and let $FF$ be a field.
= Cosheaf Homology
Write $(K, >=)$ for the poset of simplices in $K$ ordered by coface relations, which can also be naturally seen as a category, where each simplex in $K$ is an object and each coface relation $tau >= sigma$ is a morphism $tau -> sigma$.
#definition[
A *cosheaf over $K$* which takes values in $FF$-vector spaces is a functor $cC : (K, >=) -> VF$.
In other words, $cC$ assigns
+ to each simplex $tau$ of $K$ a finite-dimensional vector space $cC(tau)$ over $RR$, and
+ to each coface relation $tau >= sigma$ a linear map $cC(tau >= sigma) : cC(tau) -> cC(sigma)$,
subject to the following axioms:
+ for every simplex $tau$ in $K$, the map $cC(tau >= tau)$ is the identity on $cC(tau)$, and
+ for each triple $tau >= sigma >= rho $ in $K$, we have $cC(sigma >= rho) oo cC(tau >= sigma) = cC(tau >= rho)$.
]
<def-cosheaf>
#example[
Write $FVR$ for the category of finite-dimensional vector spaces over $RR$. In particular, a cosheaf over $K$ which takes values in finite-dimensional real vector spaces is a functor $cD : (K , >=) -> FVR$.
]
Now fix a cosheaf $cC : (K, >=) -> VF$ over $K$.
#notation[
Denote
$
[sigma : tau] := cases(
+1 quad &sigma = tau_(-j) " for " j "even,",
-1 quad &sigma = tau_(-j) " for " j "odd,",
0 quad &"otherwise."
)
$
Then define $cC_(tau, sigma) : cC(tau) -> cC(sigma)$ as
$cC_(tau, sigma) := [sigma : tau] dot cC (tau >= sigma)
// = cases(
// + cC (tau >= sigma) quad & sigma = tau_(-j) "for even " j comma ,
// - cC (tau >= sigma) quad & sigma = tau_(-j) "for odd " j comma ,
// 0 quad & "otherwise."
// )
$.
]
<sign-adjustment>
#definition[
For each dimension $k>=0$, the vector space of *$k$-chains of $K$* with $cC$-coefficients is the product
$bC_k (K; cC) = product_(dim tau = k) cC(tau).
$
For each $k >= 0$, the $k$-th *boundary map* of $K$ with $cC$-coefficients is the linear map
$diff^cC_k : bC_k (K ; cC) -> bC_(k+1) (K ; cC),
$
defined such that for each pair of simplices $tau >= sigma$ with $dim tau = k$ and $dim sigma = k - 1$, the $cC(tau) -> cC(sigma)$ component of $diff^cC_k$ is given by
$diff^cC_k|_(tau, sigma) = cC_(tau, sigma).
$
]
<def-cosheaf-chain>
#let ct(k, co: cC) = [$bC_#k (K; #co)$]
#let cf(k, co: cC) = [$diff^#co _ #k$]
#let cfa(k, co: cC) = [$->^cf(#k, co: co)$]
#let cft(k, co: cC) = [$ ct(#k, co: co) cfa(#k, co: co)$]
#proposition[
The sequence $bC_cx (K; cC)$
$
... cfa(k+1) cft(k) ... cfa(2) cft(1) ct(0) -> 0
$
is a chain complex over $FF$.
]
<cosheaf-is-chain>
#proof[
This is analogous to @notes[Proposition 7.8]. It suffices to show that for any $(k+1)$-simplex $tau$ and any $(k-1)$-simplex $tau''$, the $cC(tau) -> cC(tau'')$ component of the composition $diff^cC _(k) oo diff^cC_(k+1)$ is zero. We compute
$
(diff^cC _(k) oo diff^cC_(k+1))|_(tau, tau'') &= sum_(dim tau' = k) diff^cC_(k)|_(tau', tau'') oo diff^cC_(k+1) |_(tau, tau') \
&= sum_(dim tau' = k) [tau'' : tau'][tau' : tau] dot cC (tau' >= tau'') oo cC (tau >= tau') \
// &= sum_(dim tau' = k) [tau'' : tau'][tau' : tau] dot cC (tau >= tau'') \
&= (sum_(dim tau' = k) [tau'' : tau'][tau' : tau]) dot cC (tau >= tau''), \
// &= 0,
$
where $cC (tau' >= tau'') oo cC (tau >= tau') = cC (tau >= tau'')$ by the associativity axiom and $sum_(dim tau' = k) [tau'' : tau'][tau' : tau] = 0$ because it is the coefficient from $tau$ to $tau''$ in $diff_k^K oo diff_(k+1)^K$.
]
#definition[
For each dimension $k >= 0$, the *$k$-th homology group of $K$ with coefficients in $cC$* is defined by
$bH_cx (K; cC) := Ker(cf(k)) over Im(cf(k+1)).
$
]
<cosheaf-homology-groups>
#definition[
Let $V$ be a $FF$-vector space.
The *constant cosheaf* $underline(V)_K : (K , >=) &-> VF$ is the functor which sends any simplex $tau$ in $K$ to $V$ and any coface relation $tau >= sigma$ to the identity map $id_V$.
// is the functor given as follows:
// $
// underline(V)_K : (K , >=) &-> VF \
// tau &mapsto V \
// (tau >= sigma) &mapsto id_V.
// $
]
<constant-cosheaf>
= Morphism of Cosheaves
Let $cC$ and $cC'$ be two cosheaves over $K$.
#definition[
A *morphism of cosheaves* over $K$ is a natural transformation $Phi : cC -> cC'$. In other words, $Phi$ consists of the following data: for each $tau in K$, there is a linear map $Phi_tau : cC(tau) -> cC'(tau)$, such that the following diagram of linear maps commutes for each $tau >= sigma$:
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRAGMBhAChzqYCUIAL6l0mXPkIoyARiq1GLNl27YA5gFs6Q0eOx4CRWeQX1mrRB04ByXv11iQGA1OOl51c8qtc7G7V0FGCh1eCJQADMAJwhNJDIQHAgkE0ULFR4+JgACAD4AXhyAnREnGLikACZqZKQAZi8lS2s7bPyiksco2PjERLrEGvSfEAAFAAssAH1ssp<KEY>
#align(center, commutative-diagram(
node-padding: (70pt, 50pt),
node((0, 0), [$cC(tau)$]),
node((1, 0), [$cC(sigma)$]),
node((0, 1), [$cC'(tau)$]),
node((1, 1), [$cC'(sigma).$]),
arr((0, 0), (1, 0), [$cC(tau >= sigma)$]),
arr((0, 1), (1, 1), [$cC'(tau >= sigma)$]),
arr((0, 0), (0, 1), [$Phi_tau$]),
arr((1, 0), (1, 1), [$Phi_sigma$]),
))
]
<morphism-of-cosheaves>
Now fix a morphism $Phi : cC -> cC'$ of cosheaves.
#proposition[
$Phi : cC -> cC'$ induces a chain map $bC_cx (K; cC) -> bC_cx (K; cC')$.
]
<morphism-induce-chain>
#proof[
For each $k>=0$ and any $k$-simplices $tau$ and $tau'$ in $K$, define $Phi_k : bC_k (K; cC) -> bC_k (K; cC')$ as the linear map whose $cC(tau) -> cC'(tau')$ component is
$
cases(Phi_tau quad & tau = tau' comma,
0 quad & "otherwise".)
$
We claim that ${Phi_k}_(k>=0)$ is a chain map $bC_cx (K; cC) -> bC_cx (K; cC')$, i.e., the following diagram commutes:
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUk<KEY>
#align(center, commutative-diagram(
node-padding: (70pt, 50pt),
node((0, 0), [$bC_k (K; cC)$]),
node((0, 1), [$bC_(k-1) (K; cC)$]),
node((1, 0), [$bC_k (K; cC')$]),
node((1, 1), [$bC_(k-1) (K; cC').$]),
arr((0, 0), (1, 0), [$Phi_k$]),
arr((0, 1), (1, 1), [$Phi_(k-1)$]),
arr((0, 0), (0, 1), [$diff_k^cC$]),
arr((1, 0), (1, 1), [$diff_k^(cC')$]),
))
By linearity and by how we define each $Phi_k$, it suffices to consider an arbitrary pair of simplices $tau >= sigma$ such that $dim tau = k$ and $dim sigma = k - 1$, in which case the above diagram becomes:
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRAGMBhAChzqYCUIAL6l0mXPkIoAjOSq1GLNl27YA5gFs6Q0eOx4CRMjIX1mrRB04ByAAS<KEY>
#align(center, commutative-diagram(
node-padding: (100pt, 50pt),
node((0, 0), [$cC(tau)$]),
node((0, 1), [$cC(sigma)$]),
node((1, 0), [$cC' (tau)$]),
node((1, 1), [$cC' (sigma),$]),
arr((0, 0), (0, 1), [$[sigma : tau] dot cC(tau >= sigma)$]),
arr((1, 0), (1, 1), [$[sigma : tau] dot cC'(tau >= sigma)$]),
arr((0, 0), (1, 0), [$Phi_tau$]),
arr((0, 1), (1, 1), [$Phi_sigma$]),
))
which commutes by @morphism-of-cosheaves.
]
#corollary[
$Phi : cC -> cC'$ induces a map on homology groups $bH_cx Phi : bH_cx (K; cC) -> bH_cx (K; cC')$.
]
<morphism-induce-homology>
#proof[
By the functoriality of homology, i.e., @notes[Proposition 4.7].
]
#definition[
Let $Phi : cC -> cC'$ be a morphism of cosheaves.
- $Phi$ is a *monomorphism* if each $Phi_tau : cC(tau) -> cC'(tau)$ is injective;
- $Phi$ is an *epimorphism* if each $Phi_tau : cC(tau) -> cC'(tau)$ is surjective; and
- $Phi$ is an *isomorphism* if each $Phi_tau : cC(tau) -> cC'(tau)$ is an isomorphism.
We also say that $Phi$ is a *strict monomorphism* (resp. *strict epimorphism*) if $Phi$ is a monomorphism (resp. epimorphism) but is not an isomorphism.
]
<def-mono>
#proposition[
If $Phi: cC -> cC'$ is an isomorphism, its inverse $Phi^(-1) : cC' -> cC$ consists of $(Phi_tau)^(-1) : cC'(tau) -> cC(tau)$ for each simplex $tau$ in $K$.
]
<iso-inverse>
#proof[
We need to check that $Phi^(-1)$ is indeed a natural transformation. For each pair $tau >= sigma$, the naturality of $Phi$ says that
$cC' (tau >= sigma) oo Phi_tau = Phi_sigma oo cC (tau >= sigma).
$
Hence
$(Phi_sigma)^(-1) oo cC' (tau >= sigma) = cC (tau >= sigma) oo (Phi_tau)^(-1),
$
which shows the naturality of $Phi^(-1)$.
]
= Examples of Cosheaves
#lemma[
The constant cosheaf $underline(FF)_K$ gives the same homology groups as the standard homology.
]
#proof[
In this case,
$bC_k (K; FK) = product_(dim tau = k) FF.
$
This agrees with @notes[Definition 3.6]. It is also easy to see the boundary maps agree with @notes[Definition 3.7].
// #TODO[show?]
]
#example[
Let $V = {v}$ and
let $K$ be the simplicial complex ${tau}$, where $tau = {v}$. Let $cC : (K, >=) -> VF$ be the cosheaf which assigns the zero vector space to the only simplex $tau = {v}$ in $K$. Then $K$ has standard homology of a single point, which agrees with the homology induced by $FK$. On the other hand, the chain complex induced by $cC$ has $bC_k (K; cC) = 0$ for all $k >= 0$, so $bH_k (K ; cC) = 0$ for all $k >= 0$. Thus $FK$ has the homology of a single point, but $cC$ does not.
]
<task-3-1>
#example[
Let $V = {v_1, v_2}$ and let $K = {tau_1, tau_2}$, where $tau_1 = {v_1}$ and $tau_2 = {v_2}$. Let $cC$ be the cosheaf such that $cC(tau_1) = FF$ and $cC(tau_2) = 0$. (There is no non-trivial coface relation in $K$.) Then with $FK$-coefficients, $K$ has chain complex $ bC_k (K ; FK) = cases(FF^2 quad &"if" k = 0 comma, 0 quad &"otherwise,") $ with all the boundary maps necessarily zero, which gives
$
bH_k (K ; FK) = cases(FF^2 quad &"if" k = 0 comma, 0 quad &"otherwise.")
$
On the other hand, with $cC$-coefficients, we similarly see that
$ bH_k (K ; cC) = bC_k (K ; cC) = cases(FF quad &"if" k = 0 comma, 0 quad &"otherwise.") $
Thus $FK$ does not have the homology of a single point, but $cC$ does.
]
<task-3-2>
// #TODO[what is strict monomorphism? each component is injective or some component is injective?]
#example[
Let $V = {v_1, v_2}$ and $K = {tau_1, tau_2, tau_3}$, where $tau_1 = {v_1}$, $tau_2 = {v_2}$ and $tau_3 = {v_1, v_2}$. (In other words, $K = Delta(1)$.) Define cosheaf $cC$ as follows:
$
tau_1 &mapsto FF,
tau_2 &mapsto FF^2,
tau_3 &mapsto FF^2,
(tau_3 >= tau_1) &mapsto ((a, b) |-> a),
(tau_3 >= tau_2) &mapsto id_(FF^2).
$
There is no non-trivial coface relation composition in $K$, so $cC$ is easily seen to be a cosheaf.
We then define morphism $Phi : FK -> cC$ as follows: $Phi_(tau_1) = id_FF$, $Phi_(tau_2) (a) = (a, 0)$ and $Phi_(tau_3) (a) = (a, 0)$.
Since the following diagram commutes
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBoBGAXVJADcBDAGwFcYkQAxDkAX1PUy58hFOQrU6TVuy4A9AEy9+IDNjwEi88TQYs2iThwVKBa4UTLEJu6Qa4mVg9SORirOqfsMPVQjSi13ST0Zbh4JGCgAc3giUAAzACcIAFskABYaHAgkAGYPEIMsKAB9ez4E5LTETJBspABWAtsQYrKw5STUpDE6nMQyYJaACnpSACMASgAfAFoAPnoHLure+sQtIa9RiZmFnanlqsas-s2bL3oAAjn5q53iSaPuxHy+pEGL9jbyzuOa049ZqXG4Le5jR68Sg8IA
#align(center, commutative-diagram(
node-padding: (90pt, 50pt),
node((1, 0), [$FF$]),
node((1, 1), [$FF^2$]),
node((1, 2), [$FF^2,$]),
node((0, 0), [$FF$]),
node((0, 1), [$FF$]),
node((0, 2), [$FF$]),
arr((0, 1), (0, 0), [$id_FF$]),
arr((0, 1), (0, 2), [$id_FF$]),
arr((1, 1), (1, 0), [$(a,b)|->a$]),
arr((1, 1), (1, 2), [$id_(FF^2)$]),
arr((0, 2), (1, 2), [$a |-> (a,0)$]),
arr((0, 0), (1, 0), [$id_FF$]),
arr((0, 1), (1, 1), [$a |-> (a,0)$]),
))
we see that $Phi$ is indeed a natural transformation. Further, each component of $Phi$ is injective but $Phi$ is not an isomorphism, so $Phi$ is a strict monomorphism.
$K = Delta(1)$, so by @notes[Proposition 2.6], $K$ has the same homology groups with $FK$-coefficients as a single point. We then compute the chain complex of $K$ with $cC$-coefficients: $ bC_0 (K ; cC) = cC(tau_1) plus.circle cC(tau_2) = FF^3, $ $ bC_1 (K ; cC) = cC(tau_3) = FF^2, $ and the only non-trivial boundary map $diff_1^cC$ sends $(a, b)$ to $(a, -a, -b)$. Thus $Ker diff_1^cC = 0$ and $Im diff_1^cC = FF^2$, and thus $bH_0 (K; cC) = FF^3 over FF^2 = FF$ and $bH_1 (K ; cC) = 0$. Finally, since $Phi_0 : bC_0 (K; FK) -> bC_0 (K; cC)$ is injective, which in particular does not send any generator of $bH_0 (K; FK)$ to zero, the induced map $bH_0 (K; FK) -> bH_0 (K; cC)$ is then necessarily an isomorphism $FF -> FF$. This is the only non-trivial map in $bH_cx (K; FK) -> bH_cx (K; cC)$, which is thus an isomorphism.
]
<task-3-3>
#proposition[
For any simplicial complex $K$ and any cosheaf $cC$ over $K$,
there does not exist a strict epimorphism $Phi : FK -> cC$ which induces an isomorphism on homology.
]
<task-3-4>
#proof[
Suppose such $Phi$ exists, then there exists a simplex $tau$ in $K$ such that $Phi_tau : FF -> cC(tau)$ is surjective but is not an isomorphism. Then $Phi_tau$ is necessarily the zero map $FF -> cC(tau) = 0$.
We then claim that for any simplex $sigma$ in $K$ such that $tau >= sigma$, $Phi_sigma = 0$ and $cC(sigma) = 0$. By the naturality of $Phi$, the following commutes:
#align(center, commutative-diagram(
node-padding: (70pt, 50pt),
node((0, 0), [$FF$]),
node((1, 0), [$FF$]),
node((0, 1), [$cC(tau)$]),
node((1, 1), [$cC(sigma),$]),
arr((0, 0), (1, 0), [$id_FF$]),
arr((0, 1), (1, 1), [$cC(tau >= sigma)$]),
arr((0, 0), (0, 1), [$Phi_tau = 0$]),
arr((1, 0), (1, 1), [$Phi_sigma$]),
))
which forces the surjective $Phi_sigma : FF -> cC(sigma)$ to also be the zero map, and thus $cC(sigma) = 0$.
This in particular shows that there must be some vertex $rho = {v}$ such that $Phi_rho = 0$ and $cC(rho) = 0$. Then in the chain map, $Phi_0 : bC_0 (K ; FK) -> bC_0 (K; cC)$ sends $rho$ to $0$. However, $rho$ can be seen as a generator of $bH_0 (K; FK)$, representing the connected component to which $rho$ belongs. Then the induced map $bH_0 (K; FK) -> bH_0 (K; cC)$ on homology would also send the class of $rho$ to $0$ and thus cannot be an isomorphism. We have therefore reached a contradiction.
]
= Filtration and Persistence Homology
#definition[
Let $cC$ be a cosheaf over a simplicial complex $K$. Then a *filtration* ${cC^i}$ of $cC$ over $K$ of length $l >= 1$ is a collection of cosheaves ${cC^1, cC^2, ..., cC^l = cC} $ over $K$ together with strict monomorphisms $Psi^i : cC^i -> cC^(i+1)$ for each $i = 1, 2, ..., l-1$.
// We denote such a filtration as
// $
// cC^1 subset cC^2 subset ... subset cC^l = cC.
// $
Then for each dimension $k >= 0$, there are induced maps on homology
$
bH_k (K ; cC^1) ->^(bH_k Psi^1) bH_k (K ; cC^2) ->^(bH_k Psi^2) ... ->^(bH_k Psi^(l-1)) bH_k (K ; cC^l)
$
For any $1 <= i <= j <= l$, we denote $Psi^(i->j) = Psi^(j-1) oo ... oo Psi^i$ (when $i = j$, $Psi^(i -> i) = id_(cC^i)$) and by the functoriality of homology,
$bH_k Psi^(i->j) = bH_k Psi^(j-1) oo ... oo bH_k Psi^i.
$
Then the associated *persistent homology* of $K$ with coefficients in ${cC^i}$ is defined by
$
PH_(k) Psi^(i->j) = Im(bH_k Psi^(i->j)),
$
which is a subspace of $bH_k (K; cC^j)$.
]
<def-filtration>
#lemma[
If $cC = FK$, a filtration ${cC^i}$ of $K$ defined as above is the same as a filtration defined as in @notes[Definition 1.6].
]
#proof[
Since all $Phi_i$'s are strict monomorphisms, each $cC^i$ would only assign either $FF$ or $0$ to each simplex in $K$. Also, for any $i$ and any pair $tau >= sigma$, if $cC^i (tau) = FF$, then $Psi^(i->l)_(tau) = id_FF$ by injectivity, and the naturality of $Psi^(i -> l)$ would ensure that $cC^i (sigma) = FF$ as well. This indicates that for each $i$, the simplices in $K$ to which $cC^i$ assigns $FF$ form a subcomplex of $K$, which can be viewed as $bF_i K$ as in @notes[Definition 1.6].
]
= Partial Matchings
The following is based on @notes[Section 8.1].
#definition[
A *partial matching* on $K$ is a collection $Sigma$ of simplex-pairs $sigma lt.tri tau$ of $K$ such that each simplex in $K$ only occurs in any of the pairs at most once. A simplex in $K$ is said to be a *critical simplex* if it does not occur in any of the pairs in $Sigma$.
]
#definition[
A *$Sigma$-path* is a zigzag sequence of distinct simplices in $K$ of the form
$
rho = (sigma_1 lt.tri tau_1 gt.tri sigma_2 lt.tri tau_2 gt.tri ... gt.tri sigma_m lt.tri tau_m ),
$
where $(sigma_j lt.tri tau_j)$ lies in $Sigma$ for each $j = 1, 2, ..., m$. Such a $Sigma$-path $rho$ is a *$Sigma$-cycle* if $m > 1$ and $tau_m lt.tri sigma_1$. Any $Sigma$-path which is not a $Sigma$-cycle is a *gradient path*.
]
#definition[
A partial matching $Sigma$ on $K$ is said to be *acyclic* if there does not exist any $Sigma$-cycle.
]
#definition[
Let ${cC^i}$ be a filtration of $cC$ over $K$ of length $l >= 1$. An acyclic partial matching $Sigma$ on $K$ is *compatible* with ${cC^i}$ if for any $1<= i <= l$ and any pair $sigma lt.tri tau$ in $Sigma$, the map $cC^i (tau >= sigma)$ is an isomorphism.
]
<def-compatible>
// #definition[
// Given an acyclic partial matching $Sigma$ on $K$ which is compatible with ${cC^i}$, for each $1 <= i <= l$, a simplex $tau$ in $K$ is said to be a *critical simplex* if $tau$ does not occur in any of the pairs in $Sigma$.
// // + $cC^i (tau) != 0$.
// ]
// #TODO[is this a helpful definition ? do we want to omit definition (2)?]
#figure(placement: auto, caption: [A filtration ${cC^i}$ of length $3$ over $Delta(1)$.],
table(
columns: (auto, auto, auto, auto, auto, auto),
inset: 10pt,
align: horizon,
[], $cC^1$, $Psi^1$, $cC^2$, $Psi^2$, $cC^3$,
$tau_1$, $0$, $0$, $FF$, $mat(1; 0 ; 0)$, $FF^3$,
$tau_3 >= tau_1$, $0$, [], $id_FF$, [], $mat(1, 2; 0, 4; 0, 3)$,
$tau_3$, $FF$, $id_FF$, $FF$, $mat(1; 0)$, $FF^2$,
$tau_3 >= tau_2$, $id_FF$, [], $id_FF$, [], $id_(FF^2)$,
$tau_2$, $FF$, $id_FF$, $FF$, $mat(1; 0)$, $FF^2$,
)
)
<fit-example>
#example[
Take $K = Delta(1)$ with $tau_1, tau_2, tau_3$ defined as in @task-3-3. We define the cosheaves $cC^1, cC^2, cC^3$ on $K$ together with morphisms $Psi^1 : cC^1 -> cC^2$ and $Psi^2: cC^2 -> cC^3$, shown in @fit-example. Note that each $cC^i$ assigns a vector space to each $tau_j$ and a linear map to each of the coface relations $tau_3 >= tau_1$ and $tau_3 >= tau_2$. Each $Psi^i$ then assigns a linear map $cC^i (tau_j) -> cC^(i+1) (tau_j)$ to each $tau_j$. To verify the naturality of each $Psi^i$, note that the only non-trivial relation here is $ cC^3 (tau_3 >= tau_1) oo Psi^2 _(tau_3) = Psi^2 _(tau_1) oo cC^2 (tau_3 >= tau_1)$, i.e.,
$
mat(1, 2; 0, 4; 0, 3) mat(1; 0) = mat(1; 0; 0).
$
Since each $Psi^i$ is a strict monomorphism, we have a filtration ${C^i}$ of length $3$ over $K$.
We then construct a partial matching $Sigma$ on $K$, which only consists of the pair $(tau_2 lt.tri tau_3)$. Then the only critical simplex of $Sigma$ is $tau_1$. Since the only possible $Sigma$-path is $(tau_2 lt.tri tau_3)$, which is not a $Sigma$-cycle (and hence is a gradient path), we see that $Sigma$ is acyclic. Further, $Sigma$ is compatible with ${cC^i}$ defined in @fit-example, as for all $cC^i$, the linear map $cC^i (tau_3 >= tau_2)$ is the identity and thus an isomorphism.
// To construct some numerical examples, we further assume that any cosheaf is a functor $cC : (K , >=) -> FVR$ and for each vector space the standard basis is chosen. Then to define a cosheaf, we only need the following data:
// + A natural number $n_tau$ for each simplex $tau$ in $K$, representing the dimension of the $RR$-vector space $cC(tau)$, and
// + An $(n_(sigma) times n_tau)$-matrix over $RR$ for each pair $tau gt.tri sigma$, representing the linear map $cC(tau >= sigma)$.
// All other linear maps $cC(tau >= sigma)$, where $sigma$ has codimension greater than $1$ as a face of $tau$, can then be written as a composition $cC(tau'' gt.tri sigma) oo ... oo cC(tau gt.tri tau')$, where $tau gt.tri tau' gt.tri ... gt.tri tau'' gt.tri sigma$.
// We then assume for a filtration ${cC^i}$ of $cC$, each $Psi^i_tau : cC^i (tau) -> cC^(i+1) (tau)$ is represented by a matrix
]
<fit-example-1>
= The Morse Chain Complex
Fix a filtration ${cC^i}$ of $cC$ over $K$ of length $l >= 1$ and an acyclic matching $Sigma$ on $K$ compatible with ${cC^i}$.
Until further notice, also fix $i$ such that $1<= i<= l$.
== Chain Construction
Now it is helpful to recall @sign-adjustment.
#definition[
For a $Sigma$-path
$rho = (sigma_1 lt.tri tau_1 gt.tri sigma_2 lt.tri tau_2 gt.tri ... gt.tri sigma_m lt.tri tau_m ),
$
define its *$cC^i$-weight* $w_(i)(rho)$ as the linear map $cC^i (sigma_1) -> cC^i (tau_m)$ given by
$
w_(i)(rho) := (-1)^m dot (cC_(tau_m, sigma_m)^i)^(-1) oo ... oo (cC_(tau_2, sigma_2)^i)^(-1) oo cC_(tau_1, sigma_2)^i oo (cC_(tau_1, sigma_1)^i)^(-1).
$
]
#remark[
Since $cC^i_(tau_j, sigma_j) = plus.minus cC^i (tau_j >= sigma_j)$ for each $1 <= i <= l$ and $1 <= j <= m$ is by definition an isomorphism, taking its inverse is justified.
]
#let cw = [$cal(w)_i$]
#notation[
Let $alpha, beta$ be simplices in $K$ such that $dim alpha = dim beta + 1$ and let $rho = (sigma lt.tri ... lt.tri tau)$ be a $Sigma$-path. Denote $cw(alpha gt.tri rho gt.tri beta) := cC^i_(tau, beta) oo w_(i) (rho) oo cC^i_(alpha, sigma)$. Note that $cw(alpha gt.tri rho gt.tri beta) != 0$ if and only if $alpha gt.tri sigma$ and $tau gt.tri beta$. In particular, if we also allow $rho$ to be the empty path $emptyset$, then in this case $cw(alpha gt.tri emptyset gt.tri beta) := cC^(i)_(alpha, beta)$.
]
<new-path-notation>
// #definition[
// Let $L$ be a subset (but not necessarily a subcomplex) of $K$ and let $(bD_cx, diff^bD_cx)$ be a sequence (but not necessarily a chain complex), where each $bD_k = product_(dim alpha = k, alpha in L) cC^i (alpha) $. Let $(sigma lt.tri tau)$ be a pair of simplices in $K$ but not in $L$. Define the *elimination operation* of $(sigma lt.tri tau)$ on $(bD_cx, diff^bD_cx)$ as follows: for any $alpha, beta$ such that $k = dim alpha = dim tau = dim beta + 1 = dim sigma + 1$, this operation changes $diff_k^bD |_(alpha, beta)$ to
// $
// diff_k^bD |_(alpha, beta)- diff_k^bD |_(tau, beta) oo (cC^i_(tau, sigma))^(-1) oo diff_k^bD |_(alpha, sigma),
// $
// and leaves all $diff_i^bD$ for $i != k$ unchanged.
// ]
// #TODO[formalise this idea]
// #lemma[
// The elimination operation leaves other pairs of an acyclic partial matching unchanged.
// ]
// #lemma[
// We have the Morse complex (constructed by induction) with the following boundary operation...
// ]
#definition[
The *Morse complex* of $Sigma$ with coefficients in $cC^i$ is a sequence
$(bC_cx^Sigma (K; cC^i), d_cx ^(cC^i, Sigma) ),
$
where for each dimension $k >= 0$,
$
bC_k^Sigma (K; cC^i) = product_(dim alpha = k comma \ alpha "critical ") cC^i (alpha),
$
and for critical simplices $alpha, beta$ in $K$ with $dim alpha = k$ and $dim beta = k-1$,
$d_k ^(cC^i, Sigma) : bC_k^Sigma (K; cC^i) -> bC_(k-1)^Sigma (K; cC^i)$ has the following $cC^i (alpha) -> cC^i (beta)$ component:
$
d_k ^(cC^i, Sigma)|_(alpha, beta) = cC^i_(alpha, beta) + sum_(Sigma"-path" rho = (sigma lt.tri ... lt.tri tau)) cC^i_(tau, beta) oo w_(cC^i)(rho) oo cC^i_(alpha, sigma).
$
Alternatively, if we denote the set of all $Sigma$-path (including the empty path $emptyset$) as $Gamma_Sigma$, we could write $ d_k ^(cC^i, Sigma)|_(alpha, beta) = sum_(rho in Gamma_Sigma) cw(alpha gt.tri rho gt.tri beta)$ using @new-path-notation.
]
<def-morse>
To simplify later proofs, we first need an 'induction principle' for the Morse complex. This lemma is the only place where we vary $Sigma$ in this section.
#lemma[
Let $P$ be a proposition on the Morse complex $(bC_cx^Sigma (K; cC^i), d_cx^(cC^i, Sigma))$. Then to prove $P$ for any acyclic partial matching $Sigma$ compatible with ${cC^i}$, it suffices to consider the case $Sigma_0 = {(sigma lt.tri tau)}$.
]
<induction-principle>
#proof[
We suppress the explicit appearance of $K$ and $cC^i$ in the notations as they are fixed in this proof.
First, we notice that if $Sigma_0 = {(sigma lt.tri tau)}$ with $dim sigma + 1 = dim tau = k$, then the only $Sigma_0$-path is $(sigma lt.tri tau)$, and the construction of the Morse complex $(bC_cx^(Sigma_0) , d_cx ^(Sigma_0) )$ based on the _sequence_ $(bC_cx , d_cx )$ (we may forget that $(bC_cx , d_cx )$ is a chain complex for now) is equivalent to applying the following algorithm $(star)$ with $(sigma lt.tri tau)$ to $(C_cx, d_cx)$:
+ For each $k$-simplex $alpha$ and $(k-1)$-simplex $beta$, change the block $d_k |_(alpha, beta)$ to $ d_k |_(alpha, beta) - d_k |_(tau, beta) oo (d_k|_(tau, sigma))^(-1) oo d_k |_(alpha, sigma); $
+ Remove $cC^i (tau)$ from the product of $bC_k$ and remove $cC^i (sigma)$ from the product of $bC_(k-1)$, and remove all corresponding blocks from $d_(k+1)$, $d_k$ and $d_(k-1)$.
// + $diff_k^bD |_(alpha, beta)- diff_k^bD |_(tau, beta) oo (cC^i_(tau, sigma))^(-1) oo diff_k^bD |_(alpha, sigma),$
For an arbitrary $Sigma$, we claim that applying algorithm $(star)$ recursively with each pair in $Sigma$ produces the same Morse complex $(bC_cx^(Sigma) , d_cx ^(Sigma) )$ as in @def-morse. Take any $(sigma lt.tri tau)$ in $Sigma$ and let $Sigma' = Sigma - {(sigma lt.tri tau)}$. Then by induction, suppose we have the Morse complex $(bC_cx^(Sigma') , d_cx ^(Sigma') )$ specified as in @def-morse. Then we note that for any $rho in Gamma_Sigma'$, $cw (tau gt.tri rho gt.tri sigma) != 0$ only if $rho = emptyset$, for otherwise we can form a $Sigma$-cycle $(sigma lt.tri tau lt.tri rho)$, which contradicts the acyclicity of $Sigma$. Thus,
$d_k^(Sigma')|_(tau, sigma) = sum_(rho in Gamma_(Sigma')) cw (tau gt.tri rho gt.tri sigma) = cC^i_(tau, sigma)$.
Therefore, step (1) of algorithm $(star)$ changes the block $d_k^(Sigma')|_(alpha, beta)$ to
$
& d_k ^(Sigma') |_(alpha, beta) - d_k ^(Sigma') |_(tau, beta) oo (cC^i_(tau, sigma))^(-1) oo d_k ^(Sigma') |_(alpha, sigma) \
= &sum_(rho_1 in Gamma_Sigma') cw(alpha gt.tri rho_1 gt.tri beta) - (sum_(rho_2 in Gamma_Sigma') cw(tau gt.tri rho_2 gt.tri beta)) oo (cC^i_(tau, sigma))^(-1) oo (sum_(rho_3 in Gamma_Sigma') cw(alpha gt.tri rho_3 gt.tri sigma)) \
= &sum_(rho_1 in Gamma_Sigma') cw(alpha gt.tri rho_1 gt.tri beta) - (sum_(rho_2 in Gamma_Sigma') sum_(rho_3 in Gamma_Sigma') cw(tau gt.tri rho_2 gt.tri beta) oo (cC^i_(tau, sigma))^(-1) oo cw(alpha gt.tri rho_3 gt.tri sigma)) \
= & sum_(rho in Gamma_Sigma) cw (alpha gt.tri rho gt.tri beta) = d_k^Sigma|_(alpha,beta).
$
The last but one equality is because any $rho in Gamma_Sigma$
- either does not consist of $(sigma lt.tri tau)$, in which case $rho = rho_1 in Gamma_Sigma'$,
- or passes $(sigma lt.tri tau)$ exactly once, in which case $rho$ can be written as $(rho_3 gt.tri sigma lt.tri tau gt.tri rho_2)$ for $rho_2, rho_3 in Gamma_Sigma'$ and then $cw (alpha gt.tri rho gt.tri beta)$ can be decomposed as in the summand.
Step (2) of algorithm $(star)$ simply updates the critical simplices by removing $sigma$ and $tau$. Thus, we see that applying algorithm $(star)$ with $(sigma lt.tri tau)$ to $(bC_cx^(Sigma') , d_cx ^(Sigma') )$ produces the same $(bC_cx^(Sigma) , d_cx ^(Sigma) )$ as in @def-morse. In other words, we could have equivalently defined the Morse complex as the sequence produced by recursively applying algorithm $(star)$ with each pair of $Sigma$ (in an arbitrary order) to $(bC_cx, d_cx)$. This constructive definition indicates our 'induction principle'.
]
// #TODO[change all $cC^i$ to $cC$ since they are fixed...]
#notation[
With $K$, ${cC^i}$ and $Sigma$ fixed as above, for each $1 <= i <= l$ and each dimension $k >=0$,
denote $bC_k^i := bC_k (K ; cC^i) comma diff_k^i := diff_k^(cC^i) comma
bM_k^i := bC_k^Sigma (K; cC^i), d_k^i := d_k^(cC^i, Sigma) . $
// We also denote $w_i (rho) := w_(cC^i) (rho)$ for any $Sigma$-path $rho$.
]
#proposition[
For each $i$, the Morse complex $(bM_cx^i, d^i_cx)$ is a chain complex.
]
<morse-is-chain>
#let ci(s, t) = [$cC^i_(#s, #t)$]
#proof[
// #TODO[why induction works here?]
This is analogous to @notes[Proposition 8.8]. To elaborate, by @induction-principle, it suffices to consider when $Sigma = {(sigma lt.tri tau)}$, the set of critical simplices $C_Sigma = K - {sigma, tau}$, and the only $Sigma$-path $rho = (sigma lt.tri tau)$. Then we need to show that for each $k >= 2$, for any $alpha, omega in C_Sigma$ such that $dim alpha = dim omega + 2 = k$, we have $ B := sum_(dim xi = k - 1 comma \ xi in C_Sigma) d^i_(k-1) |_( xi, omega) oo d^i_k |_(alpha , xi) = 0. $
For each $xi$ in the sum, denote $B_xi := d^i_(k-1) |_( xi, omega) oo d^i_k |_(alpha , xi)$, which by definition expands to
$
B_xi =
underbrace( ci(xi, omega) oo ci(alpha, xi), B_(xi, 1))
underbrace(- ci(tau, omega) oo (ci(tau, sigma))^(-1) oo ci(xi, sigma) oo ci(alpha, xi) , B_(xi, 2))
underbrace(
-ci(xi, omega) oo ci(tau, xi) oo (ci(tau, sigma))^(-1) oo ci(alpha, sigma),
B_(xi, 3)) \ + ci(tau, omega) oo (ci(tau, sigma))^(-1) oo ci(xi, sigma) oo ci(tau, xi) oo (ci(tau, sigma))^(-1) oo ci(alpha, sigma),
$
where the fourth term is always zero, since $ci(alpha, sigma) != 0$ only if $dim sigma = k-1$, but $ci(xi, sigma) != 0$ only if $dim sigma = k-2$. Now denote the first three terms of $B_xi$ as $B_(xi, j)$ for $j = 1, 2, 3$ respectively, so $B_xi = sum_(j=1)^3 B_(xi, j)$. Since $diff^i_cx$ is a boundary operator, we have $ sum_xi B_(xi, 1) = - ci(tau, omega) oo ci(alpha, tau) - ci(sigma, omega) oo ci(alpha, sigma). $
We then see that $sum_xi B_(xi, j) = 0$ for any $j = 1, 2, 3$ if $dim sigma != k - 2$ and $dim sigma != k-1$. Then there remain two cases:
- If $dim sigma = k-2$ and so $dim tau = k -1$, then $B_(xi, 3) = 0$ for any $xi$ in the sum, and $sum_xi B_(xi, 2) = ci(tau, omega) oo (ci(tau, sigma))^(-1) oo ci(tau, sigma) oo ci(alpha, tau) = ci(tau, omega) oo ci(alpha, tau), $
which would cancel with $sum_xi B_(xi, 1)$;
- If $dim sigma = k -1$, the situation is similar as above, with $B_(xi, 2) = 0$ for any $xi$ and also $sum_xi B_(xi, 3) $ cancelling with $sum_xi B_(xi, 1) $.
Therefore, we conclude that $B = sum_xi B_xi = 0$ as desired.
]
== Chain Homotopy Equivalence
#proposition[
For each $i$, the Morse complex $(bM_cx^i, d^i_cx)$ is chain homotopy equivalent to the chain complex $(bC_cx^i, diff^i_cx)$. In particular, there exists a chain map $phi^i_cx : bM_cx^i -> bC_cx^i$ which induces an isomorphism $bH_k (bM^i_cx) -> bH_k (bC^i_cx)$ for each dimension $k>=0$.
]
<morse-equivalent>
#proof[
This is analogous to @notes[Proposition 8.10] and @notes[Lemma 8.11]. Again, it suffices to assume $Sigma = {(sigma lt.tri tau)}$. For each $k >= 0$ and for each pair of $k$-simplices $(alpha, omega) in K times C_Sigma$, define the $cC^i (alpha) -> cC^i (omega)$ component of the linear map $psi^i_k : bC_k^i -> bM_k ^i$ by
$
psi^i_k |_(alpha, omega) = cases(
id_(cC^i (alpha)) quad & alpha = omega != tau comma,
- ci(tau, omega) oo (ci(tau, sigma))^(-1) quad & alpha = sigma comma ,
0 & "otherwise".
)
$
Conversely, define the $cC^i (omega) -> cC^i (alpha)$ component of the linear map $phi^i _k : bM_k ^i -> bC_k ^i$ by
#math.equation(block: true, numbering: "(1)", supplement: "Equation",
$
phi^i_k |_(omega, alpha) = cases(
id_(cC^i (omega)) quad & omega = alpha != sigma comma,
- (ci(tau, sigma))^(-1) oo ci(omega, sigma) quad & alpha= tau comma ,
0 & "otherwise".
)
$) <def-phi>
One can verify that $psi^i_cx$ and $phi^i_cx$ are two chain maps.
// #TODO[...]
We then note that $psi^i_k oo phi^i_k$ is the identity map on $bM^i_k$. Indeed, for each $omega, omega' in bM_k^i$,
$(psi^i_k oo phi^i_k)|_(omega, omega') = sum_(alpha in bC_k^i) psi^i_k |_(alpha, omega') oo phi^i_k |_(omega, alpha).
$
If $alpha = sigma$, then $phi^i_k |_(omega, alpha) = 0$. If $alpha = tau$, then $psi^i_k |_(alpha, omega') = 0$. Thus we only need to consider the case when $alpha in.not {tau, sigma}$. Then we see that if $omega != omega'$, one of $psi^i_k |_(alpha, omega')$ and $ phi^i_k |_(omega, alpha)$ must be $0$; if $omega = omega'$, we have $psi^i_k |_(alpha, omega') oo phi^i_k |_(omega, alpha) = id_(cC^i (omega))$ only if $alpha = omega = omega'$.
Similarly, we can find that for each $alpha, alpha' in bC_k^i$,
$
(phi^i_k oo psi^i_k)|_(alpha, alpha') = cases(
- ci(tau, alpha') oo (ci(tau, sigma))^(-1) quad & alpha = tau != alpha' comma,
- (ci(tau, sigma))^(-1) oo ci(alpha, sigma) quad & alpha != sigma = alpha' comma,
id_(cC^i (alpha)) quad & alpha = alpha' comma ,
0 quad & "otherwise".
)
$
Then the linear maps $theta_k : bC_k^i -> bC_(k+1)^i$, whose $cC(alpha) -> cC(beta)$ component for $k$-simplex $alpha$ and $(k+1)$-simplex $beta$ is defined as
$
theta_k |_(alpha, beta) = cases(
(ci(tau, sigma))^(-1) quad & alpha = sigma "and" beta = tau comma,
0 quad & "otherwise" comma
)
$
gives a chain homotopy between $phi^i_k oo psi^i_k$ and the identity chain map on $bC_k^i$.
// Then to move on to general cases of $Sigma$, the discussion at the end of @notes[Section 8.3] also applies with slight modification. In particular, by removing a single pair $(sigma lt.tri tau) in Sigma$ from $K$, we change any $ci(alpha, omega)$ to $ci(alpha, omega) - ci(tau, omega) oo (ci(tau, sigma))^(-1) oo ci(alpha, sigma)$. Now suppose for another pair $(sigma' lt.tri tau') in Sigma$, we have $ci(tau, sigma') oo (ci(tau, sigma))^(-1) oo ci(tau', sigma) != 0$. This indicates that $tau' gt.tri sigma lt.tri tau gt.tri sigma'$, but since $sigma' lt.tri tau'$, we have constructed a $Sigma$-cycle, which contradicts the acyclicity of $Sigma$.
// #TODO[do we want to write more?]
]
// By induction on $Sigma$,
// A by-product of the proof above is the following:
// #corollary[
// ]
// <iso-homo>
== The Commutative Cube
To show that the Morse complex $bM_cx^i$ induces the same persistent homology as $bC_cx^i$, we first introduce a useful (and beautiful) diagram, shown in @cube.
#figure(caption: "The commutative cube.",
placement: auto
)[
// https://t.yw.je/#N4Igdg9gJg<KEY>
#align(center, commutative-diagram(
node-padding: (50pt, 40pt),
node((0, 0), [$bC_(k-1)^i$]),
node((1, 0), [$bC_(k)^i$]),
node((0, 2), [$bC_(k-1)^(i+1)$]),
node((1, 2), [$bC_(k)^(i+1)$]),
node((2, 1), [$bM_(k-1)^(i)$]),
node((2, 3), [$bM_(k-1)^(i+1)$]),
node((3, 1), [$bM_(k)^(i)$]),
node((3, 3), [$bM_(k)^(i+1)$]),
arr((1, 0), (0, 0), [$diff_(k)^i$]),
arr((0, 0), (0, 2), [$Psi_(k-1)^i$]),
arr((1, 0), (1, 2), [$Psi_(k)^i$]),
arr((1, 2), (0, 2), [$diff_(k)^(i+1)$]),
arr((2, 1), (2, 3), [$tilde(Psi)_(k-1)^i$]),
arr((3, 1), (3, 3), [$tilde(Psi)_(k)^i$]),
arr((3, 1), (2, 1), [$d_(k)^i$], label-pos: right),
arr((3, 3), (2, 3), [$d_(k)^(i+1)$], label-pos: right),
arr((2, 1), (0, 0), [$phi_(k-1)^i$], label-pos: left, ),
arr((3, 1), (1, 0), [$phi_(k)^i$], ),
arr((2, 3), (0, 2), [$phi_(k-1)^(i+1)$], label-pos: right),
arr((3, 3), (1, 2), [$phi_(k)^(i+1)$]),
))
]
<cube>
In @cube, each vertical line is a chain complex. We have shown that the back face commutes, since each $Psi^i_cx$ is a chain map; the left face (as well as the right face) commutes, since each $phi_cx^i$ is a chain map; and furthermore, each slant arrow $phi^i_k$ induces an isomorphism on homology.
To show the commutativity of the remaining faces,
now we consider what happens when we vary $i$, the stage of the filtration.
#proposition[
Each $Psi^i : cC^i -> cC^(i+1)$ induces a chain map $tilde(Psi)^i_cx : bM_cx^i -> bM_cx^(i+1). $ In other words, the front face of @cube commutes.
]
<front-commute>
#proof[
For each dimension $k >= 0$,
for an arbitrary pair of critical $k$-simplices $alpha, alpha'$, define the $cC^i (alpha) -> cC^(i+1) (alpha')$ component of the linear map $tilde(Psi)^i_k : bM_k^i -> bM_k^(i+1)$ as $Psi^i_alpha$ if $alpha = alpha'$ and $0$ otherwise.
// $
// cases(
// Psi^i_alpha quad & alpha = alpha' comma ,
// 0 quad & "otherwise".
// )
// $
Then it suffices to show for any critical $k$-simplex $alpha$ and critical $(k-1)$-simplex $beta$,
$d_k^(i+1) |_(alpha, beta) oo Psi_alpha^i = Psi_beta^i oo d_k^(i) |_(alpha, beta),
$
which by definition expands to
#math.equation(block: true, numbering: "(1)", supplement: "Equation",
$
(cC^(i+1)_(alpha, beta) + sum_(Sigma"-path" rho = (sigma lt.tri ... lt.tri tau)) cC^(i+1)_(tau, beta) oo w_(i+1)(rho) oo cC^(i+1)_(alpha, sigma)) oo
Psi_alpha^i = \ Psi_beta^i oo
( cC^i_(alpha, beta) + sum_(Sigma"-path" rho = (sigma lt.tri ... lt.tri tau)) cC^i_(tau, beta) oo w_(i)(rho) oo cC^i_(alpha, sigma)).
$) <eq1>
Notice that for any simplices $delta >= gamma$ in $K$, by the naturality of $Psi^i$, we have
$cC^(i+1) (delta >= gamma) oo Psi^i_(delta) = Psi^i_(gamma) oo cC^i (delta >= gamma)$. Hence, for an arbitrary pair of simplices $ delta, gamma$ in $K$,
#math.equation(block: true, numbering: "(1)", supplement: "Equation",
$ cC^(i+1) _(delta, gamma) oo Psi^i_(delta) = Psi^i_(gamma) oo cC^i_ (delta , gamma). $ ) <eq2>
In particular, if $(gamma lt.tri delta) in Sigma$, then by compatibility, both $cC^(i+1) _(delta, gamma)$ and $cC^i_ (delta , gamma)$ are isomorphisms, and we have #math.equation(block: true, numbering: "(1)", supplement: "Equation",
$
(cC^(i+1) _(delta, gamma))^(-1) oo Psi^i_(gamma) = Psi^i_(delta) oo (cC^i_ (delta , gamma))^(-1).
$) <eq3>
Finally, note that each $w_(i+1) (rho)$ consists of nothing but compositions of $cC^(i+1) _(ast, ast)$ or its inverse, apart from a sign.
So for each summand on the left-hand side of @eq1, we can imagine passing $Psi_alpha^i$ step-by-step from right to left using @eq2 or @eq3, changing the superscript $(i+1)$ to $i$ at each step, and eventually $Psi_alpha^i$ becomes $Psi_beta^i$ on the far left, which is exactly a corresponding summand on the right-hand side of @eq1.
]
#proposition[
The bottom face (hence as well as the top face) of @cube commutes.
]
<bottom-commute>
#proof[
By induction, it suffices to consider $Sigma = {(sigma lt.tri tau)}$.
It then suffices to show for any critical $k$-simplex $omega$ and any $k$-simplex $alpha$ that
$phi_k^(i+1) |_(omega, alpha) oo Psi_omega^i = Psi_alpha^i oo phi_k^i |_(omega, alpha).
$
Expand this using @def-phi, and the proof for @front-commute would also work, again thanks to the naturality of $Psi^i$.
]
#theorem[
For each $k >= 0$, $bC_k^cx$ and $bM_k^cx$ induce the same persistent homology.
]
<same-persistence>
#proof[
We have shown that @cube commutes. In other words, in the category of chain complexes, we have the following commutative diagram:
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRACMBhAfQGMAPAHpYQAX1LpMufIRQBGclVqMWbLnyEAKLAGo5ASjESQGbHgJEycpfWatEHALIbhRyWZlEF16rdUP2ZwFBbT1DUSUYKABzeCJQADMAJwgAWyQyEBwIJAVlOzYABWxhDTcQZLSkACZqbKQAZl8VeyysBlhNYqx9UoFyyvTEWqycxEy-VrQACywXEXFElKGm0dzmgocZueDQgzEKUSA
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((0, 0), [$bC_cx^i$]),
node((0, 1), [$bC_cx^(i+1)$]),
node((1, 0), [$bM_cx^i$]),
node((1, 1), [$bM_cx^(i+1).$]),
arr((0, 0), (0, 1), [$Psi^i_cx$]),
arr((1, 0), (1, 1), [$tilde(Psi)^i_cx$]),
arr((1, 0), (0, 0), [$phi_cx^i$]),
arr((1, 1), (0, 1), [$phi_cx^(i+1)$]),
))
By the functoriality of homology, for each dimension $k >= 0$, the following commutes for any pair of $1<= i < j <= l$:
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRACMAJAfQGsACABQBjAMIA9LA<KEY>IRQBGcl<KEY>TVb6zVog48Bh<KEY>XXX<KEY>SLZNkgA
// #align(center, commutative-diagram(
// node-padding: (50pt, 50pt),
// node((0, 0), [$bH_k (bC^i_cx)$]),
// node((0, 1), [$bH_k (bC^(i+1) _cx)$]),
// node((1, 0), [$bH_k (bM^i _cx)$]),
// node((1, 1), [$bH_k (bM^(i+1) _cx).$]),
// arr((0, 0), (0, 1), [$bH_k Psi^i _cx$]),
// arr((1, 0), (1, 1), [$bH_k tilde(Psi)^i _cx$]),
// arr((1, 0), (0, 0), [$bH_k phi^i _cx$]),
// arr((1, 1), (0, 1), [$bH_k phi^(i+1 ) _cx$], label-pos: right),
// ))
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyx<KEY>BdUk<KEY>
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((0, 0), [$bH_k (bC^i)$]),
node((0, 1), [$bH_k (bC^(i+1))$]),
node((1, 0), [$bH_k (bM^i)$]),
node((1, 1), [$bH_k (bM^(i+1))$]),
node((0, 2), [$bH_k (bC^(j-1))$]),
node((0, 3), [$bH_k (bC^(j))$]),
node((1, 2), [$bH_k (bM^(j-1))$]),
node((1, 3), [$bH_k (bM^(j))$]),
arr((0, 0), (0, 1), [$bH_k Psi^i$]),
arr((1, 0), (1, 1), [$bH_k tilde(Psi)^i$]),
arr((1, 0), (0, 0), [$bH_k phi^i$]),
arr((1, 1), (0, 1), [$bH_k phi^(i+1)$]),
arr((0, 2), (0, 3), [$bH_k Psi^(j-1)$]),
arr((1, 2), (0, 2), [$bH_k phi^(j-1)$]),
arr((1, 3), (0, 3), [$bH_k phi^(j)$]),
arr((1, 2), (1, 3), [$bH_k tilde(Psi)^(j-1)$]),
arr((0, 1), (0, 2), [$...$]),
arr((1, 1), (1, 2), [$...$]),
))
By @morse-equivalent, each vertical line is an isomorphism between homology groups, so each $bH_k tilde(Psi)^(i->j)$ would have an isomorphic image as $bH_k Psi^(i->j)$. The result thus follows from the definition of persistent homology.
]
// #TODO[don't know if we need the dot..]
= Conclusion
In this project, working with a finite simplicial complex $K$ and a field $FF$, we have obtained the following main results:
+ We have defined a cosheaf $cC$ over $K$ taking values in $VF$ (@def-cosheaf), defined the chain complex $bC_cx (K; cC)$ (@def-cosheaf-chain and @cosheaf-is-chain) and its induced homology groups $bH_cx (K; cC)$ (@cosheaf-homology-groups), and defined the constant cosheaf $underline(V)_K$ for any $FF$-vector space $V$ (@constant-cosheaf);
+ We have defined a morphism $Phi : cC -> cC'$ of cosheaves over $K$ (@morphism-of-cosheaves), shown that it induces maps on the chain complexes $bC_cx (K; cC) -> bC_cx (K; cC')$ (@morphism-induce-chain) and on homology groups $bH_cx (K; cC) -> bH_cx (K; cC')$(@morphism-induce-homology), defined when such a $Phi$ is a (strict) monomorphism, a (strict) epimorphism and an isomorphism (@def-mono), and identified its inverse if $Phi$ is an isomorphism (@iso-inverse);
+ We have given some examples of $K$ and $cC$ (@task-3-1, @task-3-2, and @task-3-3) and shown that there does not exist a strict epimorphism $Phi : FK -> cC$ which induces an isomorphism on homology for any $K$ and $cC$ (@task-3-4);
+ We have defined a filtration ${cC^i}$ of a cosheaf $cC$ of $K$ and defined the persistent homology of $K$ with coefficients in ${cC^i}$(@def-filtration);
+ We have defined an acyclic partial matching $Sigma$ on $K$ which is compatible with a filtration ${cC^i}$ (@def-compatible) and offered an example (@fit-example-1);
+ We have defined the Morse chain complex $bC_cx^Sigma (K ; cC^i)$ of $Sigma$ with coefficients in ${cC^i}$ when $Sigma$ is compatible with ${cC^i}$ (@def-morse). After proving an 'induction principle' (@induction-principle) for Morse complexes, we verified that $bC_cx^Sigma (K ; cC^i)$ is a chain complex (@morse-is-chain) and shown that $bC_cx^Sigma (K ; cC^i)$ is chain homotopy equivalent to $bC_cx (K ; cC^i)$ (@morse-equivalent). By constructing relevant maps and showing the commutativity of @cube (@front-commute and @bottom-commute), we have deduced that $bC_cx^Sigma (K ; cC^i)$ and $bC_cx (K ; cC^i)$ induce the same persistent homology (@same-persistence).
As the Morse chain complex is constructed using only a subset of (critical) simplices in $K$, it has the potential to simplify the computation of the persistent homology with coefficients in a filtration ${cC^i}$. One shortcoming of the current method is that the condition which we have imposed for an acyclic partial matching $Sigma$ to be compatible with ${cC^i}$ is a rather strong one and thus may be difficult to satisfy in a practical setting.
#bibliography("bib.yml") |
|
https://github.com/mps9506/quarto-lapreprint | https://raw.githubusercontent.com/mps9506/quarto-lapreprint/main/_extensions/quarto-lapreprint/typst-show.typ | typst | MIT License | // Typst custom formats typically consist of a 'typst-template.typ' (which is
// the source code for a typst template) and a 'typst-show.typ' which calls the
// template's function (forwarding Pandoc metadata values as required)
//
// This is an example 'typst-show.typ' file (based on the default template
// that ships with Quarto). It calls the typst function named 'article' which
// is defined in the 'typst-template.typ' file.
//
// If you are creating or packaging a custom typst template you will likely
// want to replace this file and 'typst-template.typ' entirely. You can find
// documentation on creating typst templates here and some examples here:
// - https://typst.app/docs/tutorial/making-a-template/
// - https://github.com/typst/templates
#show: quarto-lapreprint.with(
$if(title)$
title: "$title$",
$endif$
$if(subtitle)$
subtitle: "$subtitle$",
$endif$
$if(short-title)$
short-title: "$short-title$",
$endif$
$if(venue)$
venue: $venue$,
$endif$
$if(logo)$
// This is relative to the template file
// When importing normally, you should be able to use it relative to this file.
logo: "$logo$",
$endif$
$if(doi)$
doi: "$doi$",
$endif$
$if(theme)$
theme: $theme$,
$endif$
$if(by-author)$
authors: (
$for(by-author)$
$if(it.name.literal)$
( name: "$it.name.literal$",
affiliations: $for(it.affiliations)$"$it.name$"$sep$, $endfor$,
orcid: "$it.orcid$" ),
$endif$
$endfor$
),
$endif$
$if(pub-date)$
date: (
$for(pub-date)$
(title:"$it.title$",
date:$it.date$),
$endfor$
),
$endif$
$if(institute)$
affiliations: (
$for(institute)$
( id: "$it.id$",
name: "$it.name$"
),
$endfor$
),
$endif$
$if(keyword)$
keywords: (
$for(keyword)$
"$keyword$"$sep$,
$endfor$
),
$endif$
open-access: true,
$if(lang)$
lang: "$lang$",
$endif$
$if(region)$
region: "$region$",
$endif$
$if(mainfont)$
font-face: "$mainfont$",
$endif$
$if(abstract)$
abstract: [$abstract$],
$endif$
$if(kind)$
kind: [$kind$],
$endif$
$if(margin-content)$
margin: (
$for(margin-content)$
(
title: "$it.title$",
content: [$it.content$]
),
$endfor$
),
$endif$
$if(bibliography)$
bibliography-file: "$bibliography$",
$if(biblio-style)$
bibliography-style: "$biblio-style$",
$endif$
$endif$
)
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/009%20-%20Born%20of%20the%20Gods/005_Dance%20of%20the%20Flitterstep.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Dance of the Flitterstep",
set_name: "Born of the Gods",
story_date: datetime(day: 19, month: 02, year: 2014),
author: "<NAME>",
doc
)
#emph["More children taken. This is an evil we will track without mercy."]
—Anthousa
#emph[My child, where have you left your children so young? Have you no pity for the orphans, that you should go and leave them? You have left your children on the streets, my child!]
—Ancient Cretan lamentation
The still, dark shrine was hung once more with cloth strips. Each was twisted about some trinket—a tiny bracelet, a carved horse—that silently cried with forsaken parents' grief. The offerings clattered gently in gusts that wound through the streets.
Nowhere were seen public demonstrations of death and loss, with processions of mourners following the bier. No ritually washed corpse in solemn gray robes, crowned with a diadem of gold or sacred leaf. No marble stele, offerings of wine and blood, or smoking altar. These innocent tokens marked a gaping emptiness. Even the sad certainty of death had no home here, just a plaintive hope slowly fading into the dusk.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"Another one gone," said the patrolling soldier to her companion, as the two paced the agora of Meletis.
"That makes three so far this month." The other shook his head. "A bad business. And still no word on what has happened?"
"None. It is as though they vanished into Nyx itself."
"I cannot imagine what their families are suffering. Gods protect us all from such a fate."
"Perhaps the seers will be able to discern the truth in the Observatory. May Kruphix lift the veil from our eyes."
The two passed from view. A whisper of delighted laughter drifted in their wake.
#figure(image("005_Dance of the Flitterstep/01.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The shoulders of the bearded youth slumped as he contemplated the marble slab. Its surface bore a #emph[bas-relief] of a modestly robed woman, her arms stretched toward two carved children. The man's lips moved silently, his hand gently resting on the waist-high marker. Then he lifted a painted #emph[lekythos] , a narrow urn, and poured out a ruby stream at the stele's foot. With a final look he straightened, then turned and slowly paced from the grave.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The phalanx leader saluted briskly as he ascended the steps of the Dekatia. The sentry at the academy's golden doors returned the salute and nodded toward the entrance. "Enter with honor, Reverent One."
Although carved from stone and overlaid with gold, the weighty doors swung open smoothly on bronze pivots to admit the soldier. He removed his plumed helm as he entered, taking care to cross the threshold with the right foot first. Inclining his head, he waited to be acknowledged by the august gathering within.
The finest minds of the polis were conversing quietly but intently. The citizenry, the surrounding fields, the harbor, and the nearby Dakra Isles all required careful observation, discussion, and administration. Having reached some sort of agreement, the respected philosophers inclined their heads to the captain. A gray-haired woman, wearing a simple #emph[peplos] with a thin blue border, rose and stepped forward.
"Greetings, Reverent Captain. We thank you for your service. What news do you bring from the field?"
The phalanx leader raised a hand to his breastplate. "Honored Speaker Perisophia, I pray you will forgive this intrusion."
The woman smiled, shaking her head slightly. "The welfare of the polis is always of the highest importance. You more than any know what threatens us. Please, speak your mind."
"I thank you, Speaker. I bring grim news from the borders of our lands. Patrols near the coastal marshes reported new activity from the accursed dwellers of Asphodel. I went to see it for myself."
"An attack?"
"No, Speaker. A raid would not be unusual for the Returned, and we have driven back many such. But this..." The man gazed into the distance, a grimace wrenching his lips for an instant. Perisophia waited quietly.
He continued in a hoarse tone. "We have again seen the Weeping Woman. And... she is no longer alone."
A soft gasp echoed around the council chamber. Then the Speaker gently spoke. "She has found them?"
"I do not know. If they are hers, they do not know it. I pray those unfortunates are at peace now.
"Three children trail her, two clinging to her hands. A girl and two boys, probably. We could not see their faces. Some... were masked."
#figure(image("005_Dance of the Flitterstep/02.jpg", width: 100%), caption: [Forlorn Pseudamma | Art by <NAME>], supplement: none, numbering: none)
A man cried out. "Abomination!"
Perisophia took a step forward and laid her hand on the man's shaking shoulder. "And what then?" she asked in a low voice.
"I know we should have ended that mockery of life on the spot. But we could not. The little ones..." the captain swallowed a sob. "No one could raise a blade against them. We just watched as they turned back into the mist.
"I am sorry, Speaker. I was weak. I accept the penalty for my actions." He bowed his head.
The Speaker did not lift her hand. "No, honored servant of our people. Never that. Tenderness, not weakness, stayed your hand. Could any of us so harden our wills as to strike down innocents?
"And yet, such kind impulses lead to greater cruelty." Perisophia faced the assembly. "For many months we have heard the stories of the Lachrymosa. We pitied her tragic existence, but we left her to wander Asphodel with the others who rejected the Underworld. We told ourselves that they suffered enough with the choice they had made.
"But our forbearance has brought new evil. We have all heard of children disappearing recently within the polis. Now we know the reason. In her endless search for her dead, the Weeping Woman has lured away the living.
"They are trapped like her in an endless half-life. Such a hideous fate is far worse than death. We cannot allow this desecration to continue."
She folded her arms across her chest and closed her eyes. "Let the children sleep."
#figure(image("005_Dance of the Flitterstep/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The blood-dark porphyry of the temple walls seemed to drink what little cheer the torchlight carried. In the guttering light a small circle of robed and hooded figures knelt around a bowl-like altar. One at a time, each lifted an arm and drew a knife across the left palm, then tipped the hand to let a plain black #emph[lekythos] catch the crimson fluid.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Salt and decay rode the chill evening air. The speaker of the Twelve looked out over the salt marsh. On her left side stood the phalanx leader. He held his shield high and gripped the hilt of his sword. On her right was a bearded youth in a dark cloak, his face still marked with recent mourning. He held a black #emph[lekythos] .
Facing the group, his eyes hidden under a heavy cowl, stood a solemn priest. Three others flanked him, similarly garbed. Small golden whips at their belts silently proclaimed the dour god they served.
The head priest began to intone a dirge. As the notes settled into the doleful murk, he and the other priests turned to face the bog. The assembled group chanted in antistrophe. Again and again he spoke prescribed words, and the others responded. Then the priest gestured, and the young widower paced forward to his side. He knelt in the sour, muddy earth and whispered a prayer. Finally, he raised the #emph[lekythos] and poured its contents into the dark water.
The group waited. The light bled away. The plaintive cries of the shore birds stilled.
Then, out of the mists, she came. In deathly silence the gold-masked woman trod her path. She clutched the hands of two children, who did not share her stillness. A constant, keening wail rose from the distended mouths of the masks they bore. A third, older-looking girl paced behind them, softly whimpering through golden lips.
#figure(image("005_Dance of the Flitterstep/04.jpg", width: 100%), caption: [Zombie token | Art by <NAME>], supplement: none, numbering: none)
The young man wailed and tore at his hair. Gasps from the others punctuated his grief.
The priests stretched forth their hands. The leader began to chant gently, a single phrase repeated in a monotone. One by one, the others joined in lilting harmony and swayed in time with the music. The thready wails grew fainter and finally ceased. The four masked figures stood as though listening.
Still singing softly, the priests unbound the blood-stained wrappings on their left hands. In unison, they strode into the fen. As one, they gently laid dripping palms on golden brows. And with a sigh, four masked figures slipped below the surface. Not a ripple remained.
#figure(image("005_Dance of the Flitterstep/05.jpg", width: 100%), caption: [Flitterstep Eidolon | Art by Chase Stone], supplement: none, numbering: none)
As dawn lightened the sky, the solemn group entered the agora, heads bowed. None spoke. The young man's shoulders drooped, and his footsteps stumbled on the paving stones. Perisophia and the reverent captain supported him.
The silence was broken suddenly by the tinkling of innocent voices. From a nearby wall emerged an indistinct form, child-sized and misty. Dim stars glimmered through its space as it frolicked across the adults' path. Eyes and faces rose to follow its romping play.
The sparkling form danced through a patrolling guard, who turned with amazement at its passage. Trailing a whisper of laughter, it skipped across the plaza into a marble monument, reemerging a moment later on the other side. The giggling intensified as other shining figures chased it through the streets, winding among the assembled adults. One by one they vanished into the walls that lined the plaza.
The playful voices faded away. A wondering murmur escaped the watchers' lips. Perisophia looked to the sky, where the glow of Nyx was fading into the sunrise. Then she turned to the others. "The children are at rest. Let the light of their dreams awaken hope in the polis."
|
|
https://github.com/simon-epfl/notes-ba2-simon | https://raw.githubusercontent.com/simon-epfl/notes-ba2-simon/main/analyse/analyse-tricks.typ | typst | #set text(font: "DejaVu Sans")
#show heading.where(level: 1): contents => text(size: 20pt, contents)
#show heading: contents => pad(bottom: 10pt, contents)
#set quote(block: true)
#set heading(numbering: (ignore_first, ..n) => {
if (n.pos().len() != 0) {
numbering("1.1.", ..n)
}
})
#let stick-together(a, threshold: 3em) = {
block(a + v(threshold), breakable: false)
v(-1 * threshold)
}
= Tricks et méthodes d'Analyse II
== Tricks utiles des séries
=== Série 1
- ne pas oublier la constante d'intégration
- ex.2, q.3 $integral (\dy)/(sqrt(u)) = "arcsinh"(u) $
- ex.2 q.4, attention à chaque fois qu'on divise, à vérifier si on ne perd pas de solution
- ex.3 q.2 intégrer $u'u$ et $sin^2(x) = 1/2(1-cos(2x))$
=== Série 2
- ex.1 q.2, attention à bien mettre le moins toujours du côté sans logarithme, c'est plus simple
- ex.1 q.3, attention à bien faire rentrer les coefficients devant les logarithmes dedans
- ex.2 q.3, bien savoir isoler y
- ex.3 q.3 double intégration par partie
- ex.3 q.4 méthode D.I.
- ex.4 mettre la constante d'intégration directement dans le logarithme + intervalle
=== Série 3
NA
=== Série 4
- ex.2 q.3 intégrale pénible de $(sin^2(x))/cos(x)$
- ex.3 changement de variable pénible
=== Série 5
- ex.5 vérifier les visualisations (parfois difficiles) avec Geogebra
=== Série 6
- ex.2 difficile pour savoir quelles suites utiliser
- ex.3 q.3 attention coordonnées sphériques
- ex.3 q.4 développement limité très très cool, à savoir refaire
- ex.5 penser à définir une fonction $f$ qui respecte les critères
- ex.6 q.1 attention, rappel d'analyse I
- ex.6 q 2
=== Série 7
- ex.1 q.1 se souvenir de la symmétrie des dérivées partielles
- ex.1 q.2 se souvenir que $2^(3^2) eq 2^9 eq.not 2^(3 dot 2) $
- ex.3 à refaire absolument, permet de comprendre pourquoi
=== Série 8
- ex.1 se souvenir de quand on ne peut pas calculer les dérivées directionnelles avec le gradient + calcul de limites
- ex.1, 2, 3 pour choisir comment calculer les dérivées directionnelles
- ex.5 pour la formule de la dérivation de composition de fonctions
=== Série 9
- ex.1 très utile pour comprendre les changements de variable. Attention, se rappeler que :$ partial/(partial x)((partial f)/(partial u)) eq.not (partial^2f)/(partial x partial u) " ! car f n'est pas exprimée en fonction de " x $
$ partial/(partial x)((partial f)/(partial u)) eq (partial^2 f)/(partial u^2) (partial u)/(partial x) + (partial^2 f)/(partial v^2) (partial v)/(partial x) $
=== Série 11
- ex.1 se souvenir que $(a+b)/2 >= sqrt(\ab)$
- ex.2 q.1 système très sympa à résoudre (voir précédente rédac.)
=== Série 13
- ex. 2 : attention à être très systématique quand on remplace les $x$ et les $y$, c'est facile de remplacer la mauvaise variable en examen
- ex. 2 : ce n'est pas parce qu'on évalue en 0 qu'on a aucun terme qui apparaît, exemple (x + 1). être très systématique là-dessus aussi
- ex. 3 : ne pas intégrer le domaine d'intégration mais la fonction. mdr INM 8h30 ça pique.
- ex. 4 : pour inverser les bornes le schéma est bien mais il faut savoir le faire sans pour les intégrales compliquées : poser les \inéquations et apppliquer les opérations pour isoler selon la bonne variable
#pagebreak()
== Anciens examens
#pagebreak()
== Méthode de changement de variable
On veut poser $x = e^t$
$x$ devient $x(t)$ et $y(x)$ devient $z(t) = y(x(t)) = y(e^t)$
On dérive $z$ une ou deux fois, puis on isole $y'$, $y''$. \
*Important :* on dérive par rapport à *t*! Donc si on dérive $e^t$, on obtiendra $e^t$, *et non* $\te^t$!
#pagebreak()
== Méthode de résolution des intégrales
- méthode D.I. ex $ F(x) = integral x^3e^x $
#table(
columns: (auto, auto, auto),
align: horizon,
table.header(
[*Signe*], [*D*], [*I*]
),
"+", $x^3$, $e^x$,
"-", $3x^2$, $e^x$,
"+", $6x$, $e^x$,
"-", $6$, $e^x$,
"+", $0$, $e^x$,
)
Lire en diagonale de D vers I.
$ f(x) = x^3e^x - 3x^2e^x + 6x\e^x - 6$
#pagebreak()
== Méthodes de résolution des équations différentielles
=== EDVS
Séparation des variables puis intégration :
$ y' = lambda y \
arrow.l.r.double (\d\y)/(\d\x) = lambda y \
arrow.l.r.double integral (1/y) \dy = integral lambda\d\x \
arrow.l.r.double y = C\e^(lambda\x)
$
=== EDL1
$ y' + p(x)y = f(x) $
$ y(x) = y_hom (x) + y_"part" (x) \
y_hom (x) equiv y_hom'(x) + p(x)y_hom = 0 \
y_"part" (x) "est une seule solution particulière" $
Il existe une formule pour calculer directement : $ y_hom (x) = \Ce^(-P(x)), " où " P(x) = integral p(x)\dx " sans constante d'intégration !" $
$ y_"part" = (integral f(x)e^(P(x))\dx) e^(-P(x)) "sans constante également " $
=== EDL2
==== Coefficients constants $y''(x) + \py'(x) + \qy(x) = 0, p, q, in RR$
Soient $a, b in CC$ les racines de l'équation $lambda^2 + p lambda + q = 0$. Alors la solution générale est :
$ y(x) = cases(
C_1e^(\ax) + C_2e^(\bx) "si" a eq.not b\, a\,b in RR,
C_1e^(\ax) + C_2\xe^(\ax) "si a = b",
C_1e^(alpha x)cos(beta x) + C_2e^(alpha x)sin(beta x) "si" a = alpha + i beta = overline(b) in.not RR
) $
==== Méthode des coefficients indéterminés
$R_n(x), P_k(x), Q_m(x)$ sont des polynômes de degrés $n, m, k "et" c, a, b in RR$
$f(x)$ est-elle une combinaison linéaire de $e^(\cx)R_n (x) "et" e^(\ax)(cos(\bx)P_k (x) + sin(\bx)Q_m (x)) "?"$
Si non, la méthode ne marche pas. Utiliser la méthode de variation de constante.
===== Si f est une combinaison linéaire de $e^(\cx)R_n (x)$, le nombre $c in RR$ est-il une racine de l'équation caractéristique $lambda^2 + lambda \p + q = 0$ ? \
#sym.arrow si *oui*, $y_"part" = x^\re^(\cx)T_n (x)$ \
#sym.arrow si *non*, $y_"part" = e^(\cx)T_n (x)$
#text(style: "italic")[où $r$ est la multiplicité de la racine $lambda = c$ (1 ou 2), et $T_n(x)$ est un polynôme de degré n à coefficients indéterminés]
===== Si $f(x) = e^(\ax)(cos(\bx)P_k (x) + sin(\bx)Q_m (x))$, le nombre $a + \ib$ est-il une racine de l'équation caractéristique $lambda^2 + p lambda + q = 0$ ?
#sym.arrow si *oui*, $y_"part" = \xe^(\ax)(T_N (x)cos(\bx) + S_N (s)sin(\bx))$ \
#sym.arrow si *non*, $y_"part" = e^(\ax)(T_N (x)cos(\bx) + S_N (s)sin(\bx))$
#text(style: "italic")[où $N = max(k, m)$, $T_N(x)$ et $S_N(x)$ sont des polynômes de degré N à coefficients indéterminés]
===== Deux cas
Si $f(x) = f_2(x) + f_3(x)$, alors il faut utiliser la méthode pour $f_2(x)$ et $f_3(x)$ séparément et appliquer le principe de superposition des solutions :$ y_"part"(x) = y_"part 2"(x) + y_"part 3"(x) $
===== Ensuite, remplacer $y_"part"$ dans l'équation
Pour trouver les coefficients des polynômes, remplacer $ y_"part", y'_"part", "etc."$ dans l'équation.
==== Méthode de la variation de constante
Soit une EDL2. On a $y_1 "et" y_2$ deux solutions à l'équation homogène $C_1y_1 + C_2y_2 = 0$. On veut chercher la solution générale $C_1(x)y_2 + C_2(x)y_2 = f(x)$.
1. Calculer le Wronskien des deux solutions indépendantes trouvées :
$ W(\y_1, \y_2) (t) = \y_1(t)\y_2 '(t) − \y_2(t)\y_1 '(t) $
2. Trouver $C_n '(x)$
$ C_1 '(x) = (-y_1 (t)f(t))/(W(y_1, y_2)(t))$ \
$ C_2 '(t) = (-y_2 (t)f(t))/(W(y_1, y_2)(t))$
Ensuite on intègre pour trouver $ C_1,C_2$
#pagebreak()
== Ensemble dans $R^n$
Intuition pour savoir si un ensemble est fermé ou ouvert :
Est-ce que pour chaque point de l'ensemble, on peut aller encore un tout petit peu plus loin en appartenant toujours à l'ensemble ? Par exemple ce n'est pas le cas pour une droite, si on bouge un peu, on n'appartient plus à la droite.
L'objectif c'est de prendre un point arbitraire de l'ensemble, de calculer sa distance $d$ à la frontière de l'ensemble, et de prendre par exemple $d/2$.
=== Définitions utiles
- *Adhérance* de l'ensemble $E$, notée $overline(E)$ : l'intersection de tous les ensembles fermés contenant $E$ (on parle bien de l'intersection, donc intuitivement on retient que c'est le plus petit ensemble fermé qui contient E).
Si $E$ est fermé alors $E = overline(E)$.
- *Frontière* de l'ensemble $E$, notée $partial E$. Un point $overline(x)$ appartient à la frontière de $E$ si toute boule ouverte autour de $overline(x)$ contient au moins un point dans E et dans CE.
Par exemple pour un ensemble carré ouvert, si on choisit un point $overline(x)$ sur le bord du carré (qui n'appartient donc pas à l'ensemble), la boule autour de $overline(x)$ appartiendra forcément à l'intérieur du carré et à l'extérieur #sym.arrow $overline(x)$ est un point frontière.
- Ensemble *compact*, s'il est fermé et borné.
/*
#pagebreak()
== Méthode pour trouver min/max
- chercher les points stationnaires $nabla f(x,y) = (0,0)$ par exemple
- calculer la matrice $ "Hess"(f) = mat(
s, r;
r, t;
) $, calculer le déterminant et étudier le signe de $s$.
=== Sur un ensemble compact
1. trouver les points critiques/stationnaires
2. calculer le min et le max sur la frontière de E (fixer x à sa valeur à la frontière, trouver le y max, puis fixer y à sa valeur à la frontière, trouver le x max). comme pour les fonctions à une variable, on cherche les min/max à l'intérieur de l'ensemble de définition, mais il faut aussi vérifier les valeurs aux extrêmités !
*/
#pagebreak()
== Calcul de limites dans $RR^n$
Déjà, il faut avoir une intuition de si la limite existe déjà ou pas. Démontrer qu'une limite n'existe pas est souvent plus simple de démontrer qu'elle existe.
=== Si la limite n'existe pas
On prend des groupes de suites différents (par exemple quand $(x,y) arrow (0,0)$ on prend le groupe $(1/k, 1/k)$ et le groupe $(0, 1/k)$, avec $k arrow infinity$).
Dans $RR$ on ne peut arriver à un point que par deux moyens ($+$ et $-$). Dans $RR^n$ il y a une infinite de façons d'arriver à s'approcher d'un point; on cherche deux façons qui ont une limite différente.
A essayer :
#table(
columns: (auto, auto, auto),
inset: 10pt,
table.header([*Quand ?*], [*x*], [*y*]),
"cas général", $1/n$, $1/n$,
"utile quand il y a des produits", $1/n$, $0$,
"utile quand il y a des soustractions", $1/n$, $2/n$,
"utile quand il y a des produits à équilibrer", $1/n$, $1/(n^2)$
)
=== Si la limite existe
Souvent on peut démontrer l'existence de la limite avec les coordonnées polaires. On pose:
#grid(
columns: (50%, auto),
[
$ x = r cos(phi) \
y = r sin(phi) $
],
[
$ x = rho sin(theta)cos(phi) \
y = rho sin(theta)sin(phi) \
z = rho cos(theta) $
]
)
Généralement on fait tendre $r"/"rho arrow 0$ donc si l'expression contient du $r"/"rho$ c'est gagné on sait que la limite sera 0. Si elle ne contient que du $cos(phi), sin(phi)$, $cos(theta), sin(theta)$, c'est aussi gagné, on sait que la limite n'existe pas.
#pagebreak()
== Continuité et dérivabilité dans $RR^n$
=== Etude de la continuité
Montrer qu'une fonction est continue.
- vérifier qu'elle admet une limite au point où elle est prolongée (souvent en 0), et que sa valeur correspond au prolongement.
=== Dérivées partielles
Pour calculer une dérivée partielle (par rapport à $x$ par exemple) en un point donné :
$ (partial f)/(d x)(overline(a)) = lim_(t arrow infinity) (f(x_a + t, y_a) - f(x_a, y_a))/t $
Il faut utiliser cette formule si l'expression $(partial f)/(d x)$ n'est pas définie en $overline(a)$.
*Attention :* si les dérivées partielles existent en $overline(a)$ et sont égales, que la fonction est continue en $overline(a)$... ça ne signifie pas que $f$ est dérivable en $overline(a)$ ! (voir ex.3 série 7).
=== Vérifier qu'une fonction est dérivable
Pour vérifier qu'une fonction est dérivable/différentiable en $overline(a)$, on peut :
- utiliser le fait qu'elle doit s'écrire sous cette forme :
$ f(overline(x)) = f(overline(a)) + L(overline(x) - overline(a)) + epsilon(overline(x)) $
où $L = nabla f(overline(a))$
Et vérifier que $ lim_(overline(x) arrow overline(a)) epsilon(overline(x))/(|| overline(x) ||) = 0$.
- vérifier si toutes les dérivées partielles sont continues, une condition plus forte, qui implique que la fonction est dérivable *et* de classe $ C¹$.
- si toutes les secondes dérivées partielles sont continues (les 4!) alors la fonction est de classe $C^2$.
Si on veut prouver *qu'une fonction n'est pas dérivable*, on peut aussi utiliser le théorème de Schwarz. Si les secondes dérivées partielles croisées $partial y partial x$ et $partial x partial v$ ne sont pas égales
=== Calculer une dérivée directionnelle
La dérivée directionnelle s'exprime en fonction des dérivées partielles (comme en algèbre, on exprime tout vecteur en fonction de ceux de la base).
Ainsi, *seulement si la fonction est dérivable :*
$ D_f (overline(a), overline(v)) = angle.l nabla f(overline(a)), overline(v) angle.r $
Si la fonction n'est pas dérivable :
$ D_f(overline(a), overline(v)) = lim_(t arrow 0) 1/t (f(overline(a) + t v) - f(overline(a))) $
=== Pente maximale / minimale
On veut calculer dans quelle direction la pente de la fonction est maximale, minimale.
On sait que $ D_f (overline(a), overline(v)) = angle.l nabla f(overline(a)), overline(v) angle.r $
Quand est-ce que cette expression est maximale ? Quand $overline(v)$ est ortogonal au gradient de $f$.
Comme $overline(v)$ est un vecteur unitaire, la norme de la pente est égale au gradient.
=== Dérivées de composition de fonctions
On définit la matrice jacobienne comme :
$ J_f = mat(
(partial f_1)/(partial x_1), ..., (partial f_1)/(partial x_n);
..., ..., ...;
(partial f_m)/(partial x_1), ..., (partial f_m)/(partial x_n);
) $
Ainsi:
- si $ f: RR -> RR$, la matrice jacobienne est juste la dérivée. \
- si $ f: RR^2 -> RR$, la matrice jacobienne est le gradient.
On définit $ f = (g " " circle.small " " h)(t)$, $ g : RR -> RR^2$, $h : RR^2 -> RR$.
On veut calculer $f'(t) = J_f (t)$.
$ J_((g " " circle.small " " h)) (t) = J_g (h(t)) dot J_h (t) $
#pagebreak()
== Equation du plan tangent
L'équation du plan tangent au point $overline(a)$ :
$ z = f(x_0, y_0) + angle.l nabla f(x_0, y_0), (overline(x) - overline(a)) angle.r $
=== Fonctions implicites
$angle.l nabla f(x_0, y_0), (overline(x) - overline(a)) angle.r = 0$
#pagebreak()
#pagebreak()
== Points stationnaires et min/max
=== Trouver les points stationnaires
Calculer $(partial f)/(partial x_1)$, $(partial f)/(partial x_2)$, etc. et trouver tous les $(x_1, x_2, x_3)$ t.q #underline[toutes les derivées partielles] donnent 0.
pour trouver les points stationnaires il faut souvent résoudre un système d'équations à deux variables.
- essayer de factoriser
- essayer d'isoler une variable dans l'équation 2) et de la remplacer dans l'équation 1)
=== Calculer la hessienne et l'évaluer en tous les points stationnaires
On définit la hessienne de $f$ comme :
$ "Hess"_f = mat(
(partial^2 f)/(partial x^2), (partial^2 f)/(partial x partial y);
(partial^2 f)/(partial y partial x), (partial^2 f)/(partial y^2)
) $
==== Cas où le nombre de variables = 2 :
$ H = mat(r, s; s, t) "la position b, c = " s " par le théorème de Schwartz" $
Le déterminant est le produit des valeurs propres (dans le cours on a vu les propriétés sur les valeurs propres) donc ça revient à vérifier si :
- $det(H) > 0, r > 0 arrow.double "minimum local"$ \
- $det(H) > 0, r < 0 arrow.double "maximum local"$ \
- $det(H) < 0 "(une valeur propre négative, une positive)" arrow.double "pas d'extremum local"$
- le reste, p. ex si $ det(H) = 0$, on ne sait pas.
Si on a une valeur propre négative, et une positive, ça veut dire que selon un axe on monte, selon un autre on descend.
==== Cas où le nombre de variables = 3 :
$ "Hess"_f = mat(
(partial^2 f)/(partial x^2), (partial^2 f)/(partial x partial y), (partial^2 f)/(partial x partial z);
(partial^2 f)/(partial y partial x), (partial^2 f)/(partial y^2), (partial^2 f)/(partial y partial z);
(partial^2 f)/(partial z partial x), (partial^2 f)/(partial z partial y), (partial^2 f)/(partial z^2)
) $
- $Delta_1 > 0, Delta_2 > 0, Delta_3 > 0 equiv lambda_1 > 0, lambda_2 > 0, lambda_3 > 0 arrow.double "minimum local"$
- $Delta_1 < 0, Delta_2 > 0, Delta_3 < 0 equiv lambda_1 < 0, lambda_2 < 0, lambda_3 < 0 arrow.double "max local"$
- sinon, si $Delta_3 eq.not 0 arrow.double lambda_i < 0, lambda_j > 0 arrow.double "pas d'extremum local"$
- si $D_3 = 0$, on ne sait pas.
=== Quand on ne sait pas ?
Chercher une direction dans laquelle la fonction se comporte comme une fonction qui n'admet pas de min/max, par exemple si on prend la direction $x = x, y = -x$, on peut trouver $f(x, -x) = x^3$, pas de min/max.
=== Vérifier la bijectivité
Calculer la jacobienne de $f$ et vérifier qu'elle est différente de zéro.
== Intégration comme dans série 10
== Fonctions implicites
on a une fonction de la forme $F(x, y) = x^2 + y^2 = 1$ par exemple, on peut exprimer y en fonction de x, on retrouve une fonction $y = f(x)$ à une variable.
Parfois c'est compliqué de retrouver y en fonction de x, donc un théorème nous dit que si $F(a, b) = 0$ et $(partial f)/(partial y) eq.not 0$, alors $ f'(x) = -((partial F)/(partial x) (x, f(x)))/((partial F)/(partial y) (x, f(x))) $
== Extrema sous contraintes
Penser que $f(x,y)$ est la force associée à un potentiel (gravité par ex.). et que $g(x,y)$ est la surface. On cherche le point d'équilibre. On veut donc que $nabla f(x,y)$ soit colinéaire à $nabla g(x,y)$
== trouver le plan tangent
Le gradient est tjrs perpendiculaire à la surface
Imagine une bouteille. Sa surface est entièrement égale à 0°C. Donc dans tt la pièce il y a plein de températures différentes mais elles sont tt 0 sur le bord.
Le gradient sera perp au bord de la bouteille --> il indique l'endroit où il y a du changement, et dans tt les directions vers le bord de la bouteille (la surface), il n'y a pas de changement.
Le plan tangent c'est l'inverse, il doit être perpendiculaire au gradient, donc parallèle à la surface.
== extremas liés
on cherche le maximum de la température dans une certaine aire.
=== Pourquoi le gradient de G est perpendiculaire à la surface contrainte ?
G représente la surface, c'est-à-dire la contrainte dans laquelle il faut rester. Si on se rapproche du bord de la surface (c'est-à-dire qu'on s'apprête à en sortir), c'est que le gradient de G est perpendiculaire à la surface G de contrainte.
=== Pourquoi le gradient de F doit être colinéaire au gradient de G ?
F représente la température. Quand on reste sur la surface G, quand on atteint un maximum sur cette fonction (sans tenir compte de la contrainte), le gradient de F est forcément perpendiculaire à la surface G (supposons que ce n'est pas le cas. genre le gradient de F est un peu penché, ça veut dire qu'on peut encore bouger en restant dans G pour se déplacer vers ce max. Imagine que tu es sous l'eau sous la glace et que tu veux rejoindre le soleil, tu seras le plus proche pile quand tu vois le soleil au-dessus de toi).
Donc le gradient de F est colinéaire au gradient de G.
Dans le cas où on atteint un maximum absolu de la fonction F, le gradient sera nul donc colinéaire au gradient de G.
=== extrémas liés plusieurs contraintes
là faut pas faire grad f = lambda grad g1 et grad f = lambda_2 grad g2 !
Imagine que tu es dans une pièce, et que la première contrainte t'oblige à rester sur le sol. Imagine qu'un plan coupe la pièce verticalement (deuxième contrainte).
Donc il reste une droite à la fin.
Mais tu vas pas chercher les points parallèles à la fois au plan et au sol, c'est impossible de l'être à la fois !
#pagebreak()
== Intégration
=== Changement de variables (concept)
On pose $ G(u, v) = mat(u/2, v/2) $
$ H (x, y) = (2x, 2y) $
$ J_G (u, v) = mat(1/2, 0; 0, 1/2) $
Ce changement de variable double les x et les y. Donc quand on calcule l'aire par rapport à $u, v$ on doit diviser par 4, le déterminant de la jacobienne de G.
$ integral integral f(x, y)\dx\dy = integral integral f(G_1(u, v), G_2(u, v))|det(J_G (u, v))|\du\dv $
=== Dessiner
Ex.
$ 0 <= x <= y <= 4x $
$ 1 <= \xy <= 2 $
On essaye de réécrire pour isoler $y$ en fonction de deux courbes qui dépendent de $x$.
=== Changement de variables (méthode)
là on essaye de réexprimer les relations entre $x$ et $y$ de telle sorte à ce qu'on ait des nombres (bornes) entre une expression en fonction de $x$ et $y$
$ 1 <= y/x <= 4 $
$ 1 <= \xy <= 2 $
et on pose le changement de variables $y/x$ et $\xy$
=== Inverser les bornes
Réecrire avec les inéquations : $ 0 <= x <= 4$ et $ 1/3x <= y <= 9$.
Puis on obtient $x <= 3y$ de la deuxième, $0 <= x <= 3y$ de la première et maintenant on doit encadrer $y$.
$(1) arrow.r.double 0 <= 3y <= 4 arrow.r.double 0 <= y <= 4/3 $
#pagebreak()
== <NAME>
$ f(overline(x)) tilde.eq f(overline(a)) + gradient f(overline(a)) (overline(x) - overline(a)) + 1/2 (overline(x) - overline(a))^T dot H"ess"_f (overline(a)) dot (overline(x) - overline(a)) $
|
|
https://github.com/ahenshaw/ksu_dissertation_template | https://raw.githubusercontent.com/ahenshaw/ksu_dissertation_template/main/dissertation_template.typ | typst | Creative Commons Zero v1.0 Universal | #let thesis(
title: "",
abstract: [],
author: "",
degree: "Ph.D. in Data Science and Analytics",
institute: "Kennesaw State University",
body,
) = {
// Set the document's basic properties.
set document(author: author, title: title)
set page(
paper: "us-letter",
number-align: center,
margin: (left: 1.25in, rest: 1.0in)
)
set text(font: "New Computer Modern", lang: "en")
set heading(numbering: "1.1.")
// Title page
v(1.25in)
align(center)[
#text(2em, title)
#v(1.0in)
#text(1.5em, "by")
#v(1.0in)
#text(1.75em, author)
#v(1.5in)
A dissertation submitted in conformity with the requirements \
for the degree of #degree \
#institute\
]
place(bottom+center)[
#sym.copyright by #author, #datetime.today().year()
]
set page(numbering: "i")
pagebreak()
// Abstract page.
v(1fr)
align(center)[
#heading(
outlined: false,
numbering: none,
text(0.85em, smallcaps[Abstract]),
)
#abstract
]
v(1.618fr)
pagebreak()
// Table of contents.
outline(depth: 3, indent: true)
pagebreak()
set page(numbering: "1")
counter(page).update(1)
// Main body.
let line-spacing=0.65em * 1.5
set par(justify: true, leading: line-spacing )
show heading: set block(above: 2em, below:1em)
body
} |
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/cyberdef/weeks/week5.typ | typst | #import "../../utils.typ": *
#section("Man in the Middle Attack")
#subsection("DLL Preloading Attack")
The idea is to put a dll in the same folder as the program that is being run,
this means that windows will automatically load the new dll, which might just be
malicious. With the SetDLLPath("") you can disable this behavior.
|
|
https://github.com/eneoli/kit-thesis-template | https://raw.githubusercontent.com/eneoli/kit-thesis-template/main/meta.typ | typst | #let isDraft = true
#let author = "<NAME>"
#let title = [Guarded Type Theory - An Overview]
#let thesisType = [Bachelor's Thesis]
#let keywords = ("Natural Deduction", "proofs as programs", "Curry-Howard isomorphism")
#let reviewerOne = [Prof. A.]
#let reviewerTwo = [Prof. B] // set to none to remove
#let advisorOne = [M.Sc. C]
#let advisorTwo = [M.Sc. D] // set to none to remove
#let department = [Informatics]
#let institute = [Institute of Magic]
#let statutoryDeclarationPlaceAndDate = [Karlsruhe, October 1, 2024] |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/link_07.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Link containing a block.
#link("https://example.com/", block[
My cool rhino
#box(move(dx: 10pt, image("/assets/files/rhino.png", width: 1cm)))
])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.