repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/Tiggax/zakljucna_naloga | https://raw.githubusercontent.com/Tiggax/zakljucna_naloga/main/src/sec/uvod/5.%20model.typ | typst | #set heading(offset: 1)
#import "/src/additional.typ": todo
== Mathematical Model development
== Operational parameters
== Regression analysis
|
|
https://github.com/skriptum/diatypst | https://raw.githubusercontent.com/skriptum/diatypst/main/diaquarto/_extensions/diaquarto/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
#import "@preview/diatypst:0.1.0": slides
#show: slides.with(
$if(title)$
title: [$title$],
$endif$
$if(subtitle)$
subtitle: [$subtitle$],
$endif$
$if(date)$
date: [$date$],
$endif$
$if(author)$
authors: "$author$",
$endif$
$if(layout)$
layout: "$layout$",
$endif$
$if(ratio)$
ratio: float($ratio$),
$endif$
$if(title-color)$
title-color: rgb("#$title-color$"),
$endif$
$if(counter)$
counter: [$counter$],
$endif$
$if(footer)$
footer: [$footer$],
$endif$
) |
https://github.com/0x1B05/algorithm-journey | https://raw.githubusercontent.com/0x1B05/algorithm-journey/main/practice/note/content/经典递归流程.typ | typst | #import "../template.typ": *
#pagebreak()
= 经典递归流程解析
== #link("https://www.nowcoder.com/practice/92e6247998294f2c933906fdedbc6e6a")[ 字符串的全部子序列 ]
返回字符串全部子序列,子序列要求去重。时间复杂度$O(n * 2^n)$
#code(caption: [解答])[
```java
public static String[] generatePermutation1(String str) {
char[] s = str.toCharArray();
HashSet<String> set = new HashSet<>();
f1(s, 0, new StringBuilder(), set);
int m = set.size();
String[] ans = new String[m];
int i = 0;
for (String cur : set) {
ans[i++] = cur;
}
return ans;
}
// s[i...],之前决定的路径path,set收集结果时去重
public static void f1(char[] s, int i, StringBuilder path, HashSet<String> set) {
if (i == s.length) {
set.add(path.toString());
} else {
path.append(s[i]); // 加到路径中去
f1(s, i + 1, path, set);
path.deleteCharAt(path.length() - 1); // 从路径中移除
f1(s, i + 1, path, set);
}
}
```
]
== #link("https://leetcode.cn/problems/subsets-ii/")[ 子集 II ]
返回数组的所有组合,可以无视元素顺序。时间复杂度 $O(n * 2^n)$
== #link("https://leetcode.cn/problems/permutations/")[ 全排列 ]
返回没有重复值数组的全部排列。时间复杂度 O(n! \* n)
#code(caption: [解答])[
```java
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
f(nums, 0, res);
return res;
}
public static void f(int[] nums, int cur, List<List<Integer>> res) {
if (cur == nums.length - 1) {
List<Integer> ans = new ArrayList<>();
for (int num : nums) {
ans.add(num);
}
res.add(ans);
} else {
for (int i = cur; i < nums.length; i++) {
swap(nums, cur, i);
f(nums, cur+1, res);
swap(nums, cur, i);
}
}
}
public static void swap(int[] nums, int i, int j) {
if (i == j) {
return;
}
nums[i] = nums[i] ^ nums[j];
nums[j] = nums[i] ^ nums[j];
nums[i] = nums[i] ^ nums[j];
}
```
]
=== 解释
n 的全排列以这种视角理解:
- 两个数:
- `12` <-> `21`
- 三个数:
- `123` <-> `132`
- `213` <-> `231`
- `321` <-> `312`
== 题目 4
返回可能有重复值数组的全部排列,排列要求去重。时间复杂度 $O(n * n!)$
== 题目 5
用递归逆序一个栈。时间复杂度 $O(2^n)$
== 题目 6
用递归排序一个栈。时间复杂度 $O(2^n)$
== 题目 7
打印 n 层汉诺塔问题的最优移动轨迹。时间复杂度 $O(2^n)$
== 洪水填充
=== #link("https://leetcode.cn/problems/number-of-islands/")[题目1: 岛屿数目]
给你一个由 `'1'`(陆地)和 `'0'`(水)组成的的二维网格,请你计算网格中岛屿的数量。岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。此外,你可以假设该网格的四条边均被水包围。
#example("Example")[
- 输入:
```
grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
```
- 输出:`3`
]
#tip("Tip")[
- `m == grid.length`
- `n == grid[i].length`
- `1 <= m, n <= 300`
- `grid[i][j]` 的值为 `'0'` 或 `'1'`
]
==== 解答
#code(caption: [岛屿数目 - 解答])[
```java
public class Code01_NumberOfIslands {
public static int numIslands(char[][] grid) {
int num = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j]=='1') {
++num;
infect(grid,i,j);
}
}
}
return num;
}
public static void infect(char[][] grid, int i, int j){
if( i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != '1' ){
return;
}
// 标记走过的点为0
grid[i][j] = 0;
infect(grid, i-1, j);
infect(grid, i+1, j);
infect(grid, i, j+1);
infect(grid, i, j-1);
}
}
```
]
#tip("Tip")[
- 时间复杂度: O(n\*m)。 想一个格子会被谁调用(上下左右邻居,最多被访问4次,但是这么多邻居调用都会直接退出,每次都是O(1))。
- 大流程,每个格子访问1次O(n\*m)
- 总共的 infect 每个格子最多访问4次O(n\*m)
- O(n\*m)+O(n\*m)
- 和并查集一样,但是常数时间会更好。
]
=== #link("https://leetcode.cn/problems/surrounded-regions/")[题目2: 被围绕的区域]
给你一个 `m x n` 的矩阵 board ,由若干字符 `'X'` 和 `'O'` ,找到所有被 `'X'` 围绕的区域,并将这些区域里所有的 `'O'` 用 `'X'` 填充。
#example("Example")[
- 输入:
```
board = [
["X","X","X","X"],
["X","O","O","X"],
["X","X","O","X"],
["X","O","X","X"]
]
```
- 输出:
```
[
["X","X","X","X"],
["X","X","X","X"],
["X","X","X","X"],
["X","O","X","X"]
]
```
- 解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 `'O'` 都不会被填充为 `'X'`。 任何不在边界上,或不与边界上的 `'O'` 相连的 `'O'` 最终都会被填充为 `'X'`。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
]
#tip("Tip")[
- `m == board.length`
- `n == board[i].length`
- `1 <= m, n <= 200`
- `board[i][j]` 为 `'X'` 或 `'O'`
]
==== 解答
把边界的`'O'`进行感染,把`'O'`->`'F'`,然后遍历矩阵,把`'O'`->`'X'`,最后把`'F'`->`'O'`。
#code(caption: [被围绕的区域 - 解答])[
```java
class Code02_SurroundedRegions {
public void solve(char[][] board) {
int n = board.length;
int m = board[0].length;
for (int i = 0; i < n; i++) {
if(board[i][0]=='O'){
infect(board, i, 0, 'O', 'F');
}
if(board[i][m-1]=='O'){
infect(board, i, m-1, 'O', 'F');
}
}
for (int j = 1; j < m-1; j++) {
if(board[0][j]=='O'){
infect(board, 0, j, 'O', 'F');
}
if(board[n-1][j]=='O'){
infect(board, n-1, j, 'O', 'F');
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i][j]=='O') {
board[i][j] = 'X';
}
if (board[i][j]=='F') {
board[i][j] = 'O';
}
}
}
}
public static void infect(char[][] board, int i, int j, char dest, char infected){
if( i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != dest ){
return;
}
board[i][j] = infected;
infect(board, i-1, j, dest, infected);
infect(board, i+1, j, dest, infected);
infect(board, i, j+1, dest, infected);
infect(board, i, j-1, dest, infected);
}
}
```
]
#tip("Tip")[
注意什么时候只要用循环就可以了。有时不需要感染。
]
=== #link("https://leetcode.cn/problems/making-a-large-island/")[题目3: 最大人工岛]
给你一个大小为 `n x n` 二进制矩阵 `grid` 。最多 只能将一格 `0` 变成 `1` 。返回执行此操作后,`grid` 中最大的岛屿面积是多少(岛屿 由一组上、下、左、右四个方向相连的 1 形成)?
#example("Example")[
- 输入: grid = [[1, 0], [0, 1]]
- 输出: 3
- 解释: 将一格0变成1,最终连通两个小岛得到面积为 3 的岛屿。
]
#example("Example")[
- 输入: grid = [[1, 1], [1, 0]]
- 输出: 4
- 解释: 将一格0变成1,岛屿的面积扩大为 4。
]
#example("Example")[
- 输入: grid = [[1, 1], [1, 1]]
- 输出: 4
- 解释: 没有0可以让我们变成1,面积依然为 4。
]
#tip("Tip")[
- `n == grid.length`
- `n == grid[i].length`
- `1 <= n <= 500`
- `grid[i][j] 为 0 或 1`
]
==== 解答
#code(caption: [最大人工岛 - 解答])[
```java
public class Code03_MakingLargeIsland {
public static int largestIsland(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
int id = 2;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) {
infect(grid, i, j, id++);
}
}
}
int ans = 0;
int[] sizes = new int[id];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] > 1) {
ans = Math.max(ans, ++sizes[grid[i][j]]);
}
}
}
// 讨论所有的0,变成1,能带来的最大岛的大小
boolean[] visited = new boolean[id];
int up, down, left, right, merge;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 0) {
up = i > 0 ? grid[i - 1][j] : 0;
down = i + 1 < n ? grid[i + 1][j] : 0;
left = j > 0 ? grid[i][j - 1] : 0;
right = j + 1 < m ? grid[i][j + 1] : 0;
visited[up] = true;
merge = 1 + sizes[up];
if (!visited[down]) {
merge += sizes[down];
visited[down] = true;
}
if (!visited[left]) {
merge += sizes[left];
visited[left] = true;
}
if (!visited[right]) {
merge += sizes[right];
visited[right] = true;
}
ans = Math.max(ans, merge);
visited[up] = false;
visited[down] = false;
visited[left] = false;
visited[right] = false;
}
}
}
return ans;
}
public static void infect(int[][] grid, int i, int j, int id) {
if (i < 0 || i == n || j < 0 || j == m || grid[i][j] != 1) {
return;
}
grid[i][j] = id;
dfs(grid, i - 1, j, id);
dfs(grid, i + 1, j, id);
dfs(grid, i, j - 1, id);
dfs(grid, i, j + 1, id);
}
}
```
]
#tip("Tip")[
时间复杂度:O(n\*m)
]
=== #link("https://leetcode.cn/problems/bricks-falling-when-hit/")[题目4: 打砖块]
有一个 `m x n` 的二元网格 `grid` ,其中 `1` 表示砖块,`0` 表示空白。砖块 稳定(不会掉落)的前提是:
- 一块砖直接连接到网格的顶部,或者
- 至少有一块相邻(4 个方向之一)砖块 稳定 不会掉落时
给你一个数组 `hits` ,这是需要依次消除砖块的位置。每当消除 `hits[i] = (rowi, coli)` 位置上的砖块时,对应位置的砖块(若存在)会消失,然后其他的砖块可能因为这一消除操作而 掉落 。一旦砖块掉落,它会 立即 从网格 `grid` 中消失(即,它不会落在其他稳定的砖块上)。
返回一个数组 `result` ,其中 `result[i]` 表示第 `i` 次消除操作对应掉落的砖块数目。
#example("Example")[
- 输入:`grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]`
- 输出:`[2]`
- 解释:网格开始为:
```
[[1,0,0,0],
[1,1,1,0]]
```
消除 (1,0) 处加粗的砖块,得到网格:
```
[[1,0,0,0]
[0,1,1,0]]
```
两个加粗的砖不再稳定,因为它们不再与顶部相连,也不再与另一个稳定的砖相邻,因此它们将掉落。得到网格:
```
[[1,0,0,0],
[0,0,0,0]]
```
因此,结果为 `[2]` 。
]
#tip("Tip")[
注意,消除可能指向是没有砖块的空白位置,如果发生这种情况,则没有砖块掉落。
]
#tip("Tip")[
- `m == grid.length`
- `n == grid[i].length`
- `1 <= m, n <= 200`
- `grid[i][j]` 为 `0` 或 `1`
- `1 <= hits.length <= 4 * 10^4`
- `hits[i].length == 2`
- `0 <= xi <= m - 1`
- `0 <= yi <= n - 1`
- 所有 `(xi, yi)` 互不相同
]
==== 解答
1. 炮位-1
2. 天花板感染
3. 时光倒流处理炮弹(炮弹逆着看,加上去看看天花板上面的砖块数量是否有变化)
#code(caption: [打砖块 - 解答])[
```java
public class Code04_BricksFallingWhenHit {
public int[] hitBricks(int[][] grid, int[][] hits) {
int n = grid.length;
int m = grid[0].length;
int[] ans = new int[hits.length];
// 只有一行
if (n==1){
return ans;
}
for (int[] hit : hits) {
grid[hit[0]][hit[1]]--;
}
for (int j = 0; j < m; j++) {
if(grid[0][j]==1){
infect(grid, 0, j);
}
}
// 时光倒流
for (int cur = hits.length-1; cur >= 0; cur--) {
int x = hits[cur][0];
int y = hits[cur][1];
grid[x][y]++;
// 当前是1
// 上下左右存在2 或者 当前是第一行
boolean worth = grid[x][y] == 1 && (
x == 0
|| (x-1 >= 0 && grid[x - 1][y] == 2)
|| (x+1 < n && grid[x + 1][y] == 2)
|| (y-1 >= 0 && grid[x][y - 1] == 2)
|| (y+1 < m && grid[x][y + 1] == 2)
);
if(worth){
int infected = infect(grid, x, y);
ans[cur] = infected-1;
}
}
return ans;
}
// 感染数量
public static int infect(int[][] grid, int i, int j){
if( i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != 1){
return 0;
}
grid[i][j] = 2;
return 1 + infect(grid, i-1, j) + infect(grid, i+1, j) + infect(grid, i, j+1) + infect(grid, i, j-1);
}
}
```
]
#tip("Tip")[
可以用并查集,但是洪水填充最快。
]
|
|
https://github.com/PA055/5839B-Notebook | https://raw.githubusercontent.com/PA055/5839B-Notebook/main/Entries/inventory/inventory-results.typ | typst | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Inventory Results",
type: "management",
date: datetime(year: 2024, month: 3, day: 10),
author: "<NAME>",
witness: "<NAME>"
)
After a week of work we were able to complete all rows of the spread sheet and figure out what parts the team was in need of. A variety of methods were used to measure the various parts. Large parts like Wheels and Motors were counted but other parts required a different aporach. String wires, and tubing were measured in feet, and metal strcuture by its weight. For parts like screws and nuts a single unit was weighed as well as the container and the total amount we had. The weight of the container was then subtracted from the total and then divided by the unit to find the total quanity.
#admonition(type: "note")[
We found our time managment to be extremely poor during this endevor which greatly increased its length. To adress this we may work to change how the team meets to allow for not only more time, but better uses of that time.
]
|
|
https://github.com/vncsb/desec-typst-template | https://raw.githubusercontent.com/vncsb/desec-typst-template/main/settings.typ | typst | #let highlight-fill-color = rgb("#44546a")
#let highlight-font-color = white
#let critical-color = rgb("#c00000")
#let high-color = rgb("#ed7d31")
#let medium-color = yellow
#let low-color = green
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/model/outline.typ | typst | --- outline ---
#set page(height: 200pt, margin: (bottom: 20pt), numbering: "1")
#set heading(numbering: "(1/a)")
#show heading.where(level: 1): set text(12pt)
#show heading.where(level: 2): set text(10pt)
#outline(fill: none)
= A
= B
#lines(3)
// This heading is right at the start of the page, so that we can test
// whether the tag migrates properly.
#[
#set heading(outlined: false)
== C
]
A
== D
== F
==== G
--- outline-styled-text ---
#outline(title: none)
= #text(blue)[He]llo
--- outline-bookmark ---
#outline(title: none, fill: none)
// Ensure 'bookmarked' option doesn't affect the outline
#set heading(numbering: "(I)", bookmarked: false)
= A
--- outline-indent-numbering ---
// With heading numbering
#set page(width: 200pt)
#set heading(numbering: "1.a.")
#show heading: none
#set outline(fill: none)
#context test(outline.indent, none)
#outline(indent: false)
#outline(indent: true)
#outline(indent: none)
#outline(indent: auto)
#outline(indent: 2em)
#outline(indent: n => ([-], [], [==], [====]).at(n))
= A
== B
== C
=== D
==== E
--- outline-indent-no-numbering ---
// Without heading numbering
#set page(width: 200pt)
#show heading: none
#set outline(fill: none)
#outline(indent: false)
#outline(indent: true)
#outline(indent: none)
#outline(indent: auto)
#outline(indent: n => 2em * n)
= About
== History
--- outline-indent-bad-type ---
// Error: 2-35 expected relative length or content, found dictionary
#outline(indent: n => (a: "dict"))
= Heading
--- outline-first-line-indent ---
#set par(first-line-indent: 1.5em)
#set heading(numbering: "1.1.a.")
#show outline.entry.where(level: 1): it => {
v(0.5em, weak: true)
strong(it)
}
#outline()
= Introduction
= Background
== History
== State of the Art
= Analysis
== Setup
--- outline-entry ---
#set page(width: 150pt)
#set heading(numbering: "1.")
#show outline.entry.where(
level: 1
): it => {
v(12pt, weak: true)
strong(it)
}
#outline(indent: auto)
#v(1.2em, weak: true)
#set text(8pt)
#show heading: set block(spacing: 0.65em)
= Introduction
= Background
== History
== State of the Art
= Analysis
== Setup
--- outline-entry-complex ---
#set page(width: 150pt, numbering: "I", margin: (bottom: 20pt))
#set heading(numbering: "1.")
#show outline.entry.where(level: 1): it => [
#let loc = it.element.location()
#let num = numbering(loc.page-numbering(), ..counter(page).at(loc))
#emph(link(loc, it.body))
#text(luma(100), box(width: 1fr, repeat[#it.fill.body;·]))
#link(loc, num)
]
#counter(page).update(3)
#outline(indent: auto, fill: repeat[--])
#v(1.2em, weak: true)
#set text(8pt)
#show heading: set block(spacing: 0.65em)
= Top heading
== Not top heading
=== Lower heading
=== Lower too
== Also not top
#pagebreak()
#set page(numbering: "1")
= Another top heading
== Middle heading
=== Lower heading
--- outline-bad-element ---
// Error: 2-27 cannot outline metadata
#outline(target: metadata)
#metadata("hello")
--- issue-2530-outline-entry-panic-text ---
// Outline entry (pre-emptive)
// Error: 2-48 cannot outline text
#outline.entry(1, [Hello], [World!], none, [1])
--- issue-2530-outline-entry-panic-heading ---
// Outline entry (pre-emptive, improved error)
// Error: 2-55 heading must have a location
// Hint: 2-55 try using a query or a show rule to customize the outline.entry instead
#outline.entry(1, heading[Hello], [World!], none, [1])
--- issue-4476-rtl-title-ending-in-ltr-text ---
#set text(lang: "he")
#outline()
= הוקוס Pocus
= זוהי כותרת שתורגמה על ידי מחשב
|
|
https://github.com/0x1B05/nju_os | https://raw.githubusercontent.com/0x1B05/nju_os/main/lecture_notes/content/09_并发控制-同步1.typ | typst | #import "../template.typ": *
#pagebreak()
= 并发控制:同步 (1)
== 同步问题
=== 同步 (Synchronization)
两个或两个以上随时间变化的量在变化过程中保持一定的相对关系
- 同步电路 (一个时钟控制所有触发器)
- iPhone/iCloud 同步 (手机 vs 电脑 vs 云端)
- 变速箱同步器 (合并快慢速齿轮)
- 同步电机 (转子与磁场转速一致)
- 同步电路 (所有触发器在边沿同时触发)
异步 (Asynchronous) = 不需要同步
- 上述很多例子都有异步版本 (异步电机、异步电路、异步线程)
=== 并发程序中的同步
并发程序的步调很难保持 “完全一致”
- 线程同步: *在某个时间点共同达到互相已知的状态*
再次把线程想象成我们自己
- NPY:等我洗个头就出门/等我打完这局游戏就来
- 舍友:等我修好这个 bug 就吃饭
- 导师:等我出差回来就讨论这个课题
- jyy: 等我成为卷王就躺平
- “先到先等”, *在条件达成的瞬间再次恢复并行*
#tip("Tip")[
线程的`join`, 就是一个同步
]
- 同时开始出去玩/吃饭/讨论
=== 生产者-消费者问题:学废你就赢了
99% 的实际并发问题都可以用生产者-消费者解决。
```c
void Tproduce() { while (1) printf("("); }
void Tconsume() { while (1) printf(")"); }
```
在 `printf` 前后增加代码,使得打印的括号序列满足
- 一定是某个合法括号序列的前缀
- 括号嵌套的深度不超过 n
- n=3, `((())())(((` 合法
- n=3, `(((())))`, `(()))` 不合法
#tip("Tip")[
`push` > `pop`
]
生产者-消费者问题中的同步
- `Tproduce`: 等到有空位时才能打印左括号
- `Tconsume`: 等到有多余的左括号时才能打印右括号
=== 计算图、调度器和生产者-消费者问题
为什么叫 “生产者-消费者” 而不是 “括号问题”?
- "(": 生产资源 (任务)、放入队列(push)
- ")": 从队列取出资源 (任务) 执行(pop)
并行计算基础:计算图
- 计算任务构成有向无环图
- $(u,v) \in E$表示 u 要用到前 v 的值
- 只要调度器 (生产者)
分配任务效率够高,算法就能并行(执行任务的时间远远比push和pop的时间长)
- 生产者把任务放入队列中
- 消费者 (workers) 从队列中取出任务
#image("./images/computional graph.png")
#tip("Tip")[
- 还是需要6步才能算完。
- 把任何一个问题并行化,画出计算图。(万能方法)
]
```
Tproduce
t1 ( )(join)
t2 (( ))(join)
t3 ((( )))(join)
```
#tip("Tip")[
线程t2要在t1结束后才能执行。拓扑排序。
]
实际上,
如果计算量小的话划分可以更灵活一点.例如把左上角三个节点划分成一个。如果节点太多,也可以分得更细一些。
=== 生产者-消费者:实现
能否用互斥锁实现括号问题?
- 左括号:嵌套深度 (队列) 不足 n 时才能打印
- 右括号:嵌套深度 (队列) > 1 时才能打印
- 当然是等到满足条件时再打印了 (代码演示) - 用互斥锁保持条件成立
并发:小心!
- 压力测试 + 观察输出结果
- 自动观察输出结果:[ pc-check.py
](https://jyywiki.cn/pages/OS/2023/c/pc-check.py)
- 未来:copilot 观察输出结果,并给出修复建议
- 更远的未来:我们都不需要不存在了
pc-mutex.c
```c
int n, count = 0;
mutex_t lk = MUTEX_INIT();
#define CAN_PRODUCE (count < n)
#define CAN_CONSUME (count > 0)
void Tproduce() {
while (1) {
retry:
mutex_lock(&lk);
if (!CAN_PRODUCE) {
mutex_unlock(&lk);
goto retry;
} else {
count++;
printf("("); // Push an element into buffer
mutex_unlock(&lk);
}
}
}
void Tconsume() {
while (1) {
retry:
mutex_lock(&lk);
if (!CAN_CONSUME) {
mutex_unlock(&lk);
goto retry;
} else {
count--;
printf(")"); // Pop an element from buffer
mutex_unlock(&lk);
}
}
}
int main(int argc, char *argv[]) {
assert(argc == 2);
n = atoi(argv[1]);
setbuf(stdout, NULL);
for (int i = 0; i < 8; i++) {
create(Tproduce);
create(Tconsume);
}
}
```
- `gcc -pthread pc-mutex.c`
- `./a.out 1`
- `./a.out 2`
如何知道是否正确呢?
== 条件变量
刚刚的实现里面依然有一个spin的过程,浪费CPU资源
#tip("Tip")[
自旋锁的时候避免浪费, 得不到锁就放弃CPU。
]
=== 同步问题:分析
#tip("Tip")[
线程同步由条件不成立等待和同步条件达成继续构成
]
线程 join
- Tmain 同步条件:`nexit == T`
- Tmain 达成同步:最后一个线程退出 `nexit++`
生产者/消费者问题
- Tproduce 同步条件:`CAN_PRODUCE (count < n)`
- Tproduce 达成同步:`Tconsume count--`
- Tconsume 同步条件:`CAN_CONSUME (count > 0)`
- Tconsume 达成同步:`Tproduce count++`
=== 理想中的同步 API
```c
wait_until(CAN_PRODUCE) {
count++;
printf("(");
}
wait_until(CAN_CONSUME) {
count--;
printf(")");
}
```
若干实现上的难题
- 正确性
- 大括号内代码执行时,其他线程不得破坏等待的条件
- 性能
- 不能 spin check 条件达成
- 已经在等待的线程怎么知道条件被满足?
=== 条件变量:理想与实现之间的折衷
一把互斥锁 + 一个 “条件变量” + 手工唤醒
- `wait(cv, mutex)` 💤
- 调用时必须保证已经获得 mutex
- wait 释放 mutex、进入睡眠状态
- 被唤醒后需要重新执行 lock(mutex)
- `signal`/`notify(cv)` 💬
- 随机私信一个等待者:醒醒
- 如果有线程正在等待 cv,则唤醒其中一个线程
- `broadcast`/`notifyAll(cv)` 📣
- 叫醒所有人
- 唤醒全部正在等待 cv 的线程
==== 条件变量:实现生产者-消费者
错误实现:
```c
void Tproduce() {
mutex_lock(&lk);
if (!CAN_PRODUCE) cond_wait(&cv, &lk);
printf("("); count++; cond_signal(&cv);
mutex_unlock(&lk);
}
void Tconsume() {
mutex_lock(&lk);
if (!CAN_CONSUME) cond_wait(&cv, &lk);
printf(")"); count--; cond_signal(&cv);
mutex_unlock(&lk);
}
```
#tip("Tip")[
生产者和消费者一多就错了。
]
#image("./images/wrong-TC.png")
#tip("Tip")[
错误原因,`if`条件里,等待被唤醒的时候if条件未必依然成立。把`if`->`while`
]
代码演示 & 压力测试 & 模型检验
(Small scope hypothesis)
==== 条件变量:正确的打开方式
同步的本质:`wait_until(COND) { ... }`,因此:
需要等待条件满足时
```c
mutex_lock(&mutex);
while (!COND) { // 2
wait(&cv, &mutex); // 1
}
assert(cond); // 互斥锁保证条件成立 3
mutex_unlock(&mutex);
```
任何改动使其他线可能被满足时
```c
mutex_lock(&mutex);
// 任何可能使条件满足的代码
broadcast(&cv);
mutex_unlock(&mutex);
```
绝对不会犯错:条件不成立的时候while等待,条件成立的时候broadcast
== 条件变量:应用
=== 条件变量:万能并行计算框架 (M2)
```c
struct work {
void (*run)(void *arg);
void *arg;
}
void Tworker() {
while (1) {
struct work *work;
wait_until(has_new_work() || all_done) {
work = get_work();
}
if (!work) break;
else {
work->run(work->arg); // 允许生成新的 work (注意互斥)
release(work); // 注意回收 work 分配的资源
}
}
}
```
=== 条件变量:更古怪的习题/面试题
有三种线程
- Ta 若干: 死循环打印 <
- Tb 若干: 死循环打印 >
- Tc 若干: 死循环打印 \_
任务:
- 对这些线程进行同步,使得屏幕打印出 `<><_` 和 `><>_` 的组合
解决同步问题, 回归本质`wait_until (cond) with (mutex)`使用条件变量,只要回答三个问题:
- 打印 “<” 的条件?
- 打印 “>” 的条件?
- 打印 “\_” 的条件?
状态机。
#image("./images/fish-SM.png")
```c
#define LENGTH(arr) (sizeof(arr) / sizeof(arr[0]))
enum {
A = 1,
B,
C,
D,
E,
F,
};
struct rule {
int from, ch, to;
} rules[] = {
{A, '<', B}, {B, '>', C}, {C, '<', D}, {A, '>', E},
{E, '<', F}, {F, '>', D}, {D, '_', A},
};
int current = A, quota = 1;
mutex_t lk = MUTEX_INIT();
cond_t cv = COND_INIT();
int next(char ch) {
for (int i = 0; i < LENGTH(rules); i++) {
struct rule *rule = &rules[i];
if (rule->from == current && rule->ch == ch) {
return rule->to;
}
}
return 0;
}
static int can_print(char ch) { return next(ch) != 0 && quota > 0; }
void fish_before(char ch) {
mutex_lock(&lk);
while (!can_print(ch)) {
// can proceed only if (next(ch) && quota)
cond_wait(&cv, &lk);
}
quota--;
mutex_unlock(&lk);
}
void fish_after(char ch) {
mutex_lock(&lk);
quota++;
current = next(ch);
assert(current);
cond_broadcast(&cv);
mutex_unlock(&lk);
}
const char roles[] = ".<<<<<>>>>___";
void fish_thread(int id) {
char role = roles[id];
while (1) {
fish_before(role);
putchar(role); // Not lock-protected
fish_after(role);
}
}
int main() {
setbuf(stdout, NULL);
for (int i = 0; i < strlen(roles); i++) create(fish_thread);
}
```
只要写出`can_print`函数,就ok。
== 总结
=== 把任何算法并行:计算图。
不管什么计算问题,都是由x算出y,接着画出计算图。
例如处理器的乱序执行,`x=0`,`y=2`,`t=x`.把每个指令看成一个节点。t和x形成一个依赖关系,RAW(Read
After Write),建立了一条边。其实就是拓扑排序,但是用硬件。
=== 实现同步:生产者消费者
任何一个线程总要做一件事,但是这个事儿不能随便做,要等条件满足的时候才可以。把多线程同步,这段代码执行的条件是什么,用万能的互斥锁。
并行不都丢掉了?计算图的时候,节点的本地计算远大于同步或者互斥的开销。
|
|
https://github.com/Meisenheimer/Notes | https://raw.githubusercontent.com/Meisenheimer/Notes/main/src/NeuralNetworks.typ | typst | MIT License | #import "@local/math:1.0.0": *
= Neural Networks |
https://github.com/mkhoatd/Typst-CV-Resume | https://raw.githubusercontent.com/mkhoatd/Typst-CV-Resume/main/CV/example.typ | typst | MIT License | #import "typstcv.typ": *
// Remember to set the fonttype in `typstcv.typ`
#set list(marker: ([•], [◦], [-], sym.bullet))
#main(
name: [<NAME>], //name:"" or name:[]
// address: [#lorem(4)],
contacts: (
(text:"+84915960597",link:""),
(text:"mkhoatd.me",link:"https://mkhoatd.me"),
(text:"github.com/mkhoatd",link:"https://github.com/mkhoatd"),
(text:"<EMAIL>",link:"mailto:<EMAIL>"),
),
bibfile: [bib.json],
[
//About
#section("About")
// #descript[As a final-year student, I'm looking forward to working in a professional and sociable environment. I'm looking for a job at Backend or Devops position, where I can enhance my technical skills and stay updated with the latest technologies]
As a final-year student, I'm looking forward to working in a professional and sociable environment. I'm looking for a job at Backend or Devops position, where I can enhance my technical skills and stay updated with the latest technologies
#sectionsep
#section("Education")
#subsection[The University of Danang - University of Science and Technology]
- Bachelor of Data Science and Artifical Intelligence
- GPA: 3.49/4
// #subsectionsep
// #subsection[#lorem(4)\ ]
- 2020-2024 (Expected)
#sectionsep
#section("Skills")
#descript("Programming Languages")
#info[Python, C, C\#, JavaScript, Go, HTML, SQL]
#subsectionsep
#descript("Frameworks")
#info[Go-gin, Django, ESP-IDF, Terraform-AWS, Electronjs]
#subsectionsep
#descript("Tools")
#info[Git, GitHub, Github Action, Docker, AWS, PostgreSQL, Redis, Linux, Bash, Docker]
#sectionsep
// Award
#section("Activities")
- #link("https://dut.udn.vn/Tintuc/Tintuc/id/8353")[Second place in the Information Technology Faculty's Student Science Research Conference]
#sectionsep
#section("Personal projects")
- #link("https://github.com/mkhoatd/ECom")[API for online store] (4 members)
- #link("https://github.com/mkhoatd/aps")[AWS Profile selector]
- #link("https://github.com/mkhoatd/EcgComEn")[Model and data processing for ECG signal classification using CNN]
],
[
//Experience
#section("Experience")
== Digital Fortress
#term[06-2024-Now][]
// #heading(level: 5, text: "Project")
=== Project: Hivello | Backend Developer
08/2023 - Now
- Description: An app for simplify mining web3 projects
- Technologies: Electronjs, Go-gin, Docker, Podman
- Responsibilities:
- Maintain Electronjs app
- Migrate from Docker Desktop to Podman and WSL on for better installation experience
- Migrate it to Go
- Using native OS API for implement system tray, elevation operations
- Implement local caching to retain information about services when their respective Docker containers stop
- Work directly with customers
=== Project: Portal | Backend Developer, DevOps
06/2023 - 08/2023
- Description: A web app for managing employer
- Technologies: Django, PostgreSQL, Terraform, AWS
- Responsibilities:
- Setup ECS, EC2, RDS, S3, Route53, ALB in AWS
- Setup CI/CD with Github Action
- Config Infrastructure as Code - Terraform
- Setup RabbitMQ
=== Project: Koru | Backend Developer, Firmware Developer, Devops
06/2023 - 08/2023
- Description: A smart plant pot system that use ESP-32 and AWS-IoT
- Technologies: ESP-IDF, Terraform, AWS, Django, PostgreSQL
- Responsibilities:
- Setup CI/CD with Github Action
- Config Infrastructure as Code - Terraform
- Debug and refactor, implement firmware automatic watering based on sensors info
- Implement secure provisioning on firmware side
- Update database schema and implement backend services
- Work directly with customer
=== Other projects
- Infibrite: Manage and remote controlling your matter devices. Work as Devops and Backend Developer
- RentACar: Fixed SSL certificate auto renewing error
// Projects
// #section("Projects")
// #descript[#lorem(2)]
// #info[#lorem(40)]
// #subsectionsep
// #descript[#lorem(2)]
// #info[#lorem(40)]
// #subsectionsep
// #descript[#lorem(2)]
// #info[#lorem(40)]
// #apa(json("bib.json"))
],
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/scholarly-tauthesis/0.4.0/template/content/01.typ | typst | Apache License 2.0 | /** 01.typ
*
* This is an example introdution in a multi-file typst project.
*
***/
#import "../preamble.typ": *
#import "@preview/scholarly-tauthesis:0.4.0" as tauthesis
= Introduction <introduction>
This document template conforms to the Guide to Writing a Thesis
in Tampere University @kirjoitusohje2019 @thesiswriting2019. A
thesis typically includes at least the following parts:
- Title page
- Abstract in English (and in Finnish)
- Preface
- List of abbreviations and symbols
- (Lists of figures and tables)
- Contents
- Introduction
- Theoretical background
- Research methodology and material
- Results and analysis (possibly in separate chapters)
- Conclusions
- References
- (Appendices)
Each of these is written as a new chapter, in the files in the
folder `content/`, which are included in the file `main.typ`.
Read this document template and its comments carefully. The
titles of Chapters from @introduction to @conclusions are
provided as examples only. You should use more descriptive ones.
The title page is created by inserting the relevant information
into the file `meta.typ`. The table of contents lists all the
numbered headings after it, but not the preceding ones.
Introduction outlines the purpose and objectives of the presented
research. The background information, utilized methods and source
material are presented next at a level that is necessary to
understand the rest of the text. Then comes the discussion
regarding the achieved results, their significance, error
sources, deviations from the expected results, and the
reliability of your research. The conclusions form the most
important chapter. It does not repeat the details already
presented, but summarizes them and analyzes their consequences.
List of references enables your reader to find the cited sources.
An introduction ends in a paragraph, that describes what each
following chapter contains. This document is structured as
follows: Chapter @writing-practices discusses briefly the basics
of writing and presentation style regarding the text, figures,
tables and mathematical notations. Chapter @references
summarizes the referencing basics. Chapter @conclusions presents
a discussion on the discoveries made during this study.
|
https://github.com/typst-community/valkyrie | https://raw.githubusercontent.com/typst-community/valkyrie/main/src/assertions.typ | typst | Other | #import "./assertions/length.typ" as length
#import "./assertions/comparative.typ": min, max, eq, neq
#import "./assertions/string.typ": *
/// Asserts that the given value is contained within the provided list. Useful for complicated enumeration types.
/// - list (array): An array of inputs considered valid.
#let one-of(list) = (
condition: (self, it) => {
list.contains(it)
},
message: (self, it) => "Unknown " + self.name + " `" + repr(it) + "`",
) |
https://github.com/JeyRunner/tuda-typst-templates | https://raw.githubusercontent.com/JeyRunner/tuda-typst-templates/main/templates/tudapub/util.typ | typst | MIT License | #let natural-image(..args) = style(styles => {
let (width, height) = measure(image(..args), styles)
image(..args, width: width, height: height)
})
#let get-spacing-zero-if-first-on-page(default_spacing, heading_location, content_page_margin_full_top, enable: true) = {
// get previous element
//let elems = query(
// selector(heading).before(loc, inclusive: false),
// loc
//)
//[#elems]
if not enable {
return (default_spacing, false)
}
// check if heading is first element on page
// note: this is a hack
let heading_is_first_el_on_page = heading_location.position().y <= content_page_margin_full_top
// change heading margin depending if its the first on the page
if heading_is_first_el_on_page {
return (0mm, true)
}
else {
return (default_spacing, false)
}
}
#let check-font-exists(font-name) = {
let measured = measure[
#text(font: font-name, fallback: false)[
Test Text
]
]
if measured.width == 0pt [
#rect(stroke: (paint: red), radius: 1mm, inset: 1.5em, width: 100%)[
#set text(fallback: true)
#set heading(numbering: none)
#show link: it => underline(text(blue)[#it])
=== Error - Can Not Find Font "#font-name"
Please install the required font "#font-name". For instructions see the #link("https://github.com/JeyRunner/tuda-typst-templates#logo-and-font-setup")[Readme of this package].
]
//#pagebreak()
]
} |
https://github.com/fabriceHategekimana/master | https://raw.githubusercontent.com/fabriceHategekimana/master/main/5_Implémentation/Prolog.typ | typst | #import "@preview/simplebnf:0.1.0": *
#import "../src/module.typ": *
#pagebreak()
= Implémentation
Dans le cadre de ce projet j'ai construit le prototype d'un interpréteur en Prolog pour appliquer et vérifier la faisabilité du langage construit jusqu'à présent. Le premier but est de traduire la syntaxe de base de notre langage prototype en son équivalent prolog et implémenter les règles d'évaluation et de typage.
Voici la version "Prolog" du langage:
#Definition()[Traduction des expressions en syntaxe prolog
#bnf(
Prod(
$E$,
annot: $sans("Expression")$,
{
Or[$"let"("var"(x),"E1","E2")$][*let*]
Or[$"func"(overline("gen"("a")), overline(["x","T"]), "T", "E")$][*func*]
Or[$"if"("E1", "E2", "E3")$][*if*]
Or[$"op"$][*bop*]
Or[$"app"("E1", overline( "a"), overline( "E"))$][*func_app*]
Or[$"first"("E") $][*first_arr*]
Or[$"rest"("E") $][*rest_arr*]
Or[$V$][*V value*]
},
),
Prod(
$V$,
annot: "Value",
{
Or[$"n" in "N"$][*number*]
Or[$"v_true"$][*true*]
Or[$"v_false"$][*false*]
Or[$"v_array"(overline("E"))$][*array*]
},
),
Prod(
$T$,
annot: "Type",
{
Or[$"t_func"(overline( "T"), "T")$][*function_type*]
Or[$"t_array"("n", "T")$][*array_type*]
Or[$"t_int"$][*int*]
Or[$"t_bool"$][*bool*]
}
),
Prod(
$op$,
annot: "bop",
{
Or[$"and(E1, E2)"$][*and*]
Or[$"or(E1,E2)"$][*or*]
Or[$"plus(E1,E2")$][*plus*]
Or[$"time(E1,E2")$][*time*]
Or[$"append"("E1", "E2")$][*concat*]
Or[$"equal(E1,E2)"$][*equal*]
Or[$"lower(E1,E2)"$][*lower*]
Or[$"low_eq(E1,E2)"$][*lower or equal*]
Or[$"greater(E1,E2)"$][*greater*]
Or[$"gre_eq(E1, E2)"$][*greater or equal*]
}
),
Prod(
$"ctx"$,
annot: "context",
{
Or[$tack.r Gamma "ctxt" $][*valid_context*]
Or[$"is_ctxt"("context") $][*valid_context*]
Or[$"is_type"("type")$][*type_in_context*]
Or[$"add"("context", "M" : sigma)$][*term_of_type_in_context*]
Or[$"equal_ctx"(Gamma, Delta)$][*equal_contexts*]
Or[$"equal_type_in_context"(sigma, tau)$][*equal_types_in_context*]
Or[$"equal_terms(M, N, sigma)"$][*equal_terms_of_type_in_context*]
}
)
)
]
La transition est plutôt simple comme il suffit de transformer les expressions en fonction prenant un paramètre spécial par élément de la syntaxe. Pour donner une distinction, les types prennent un "" au début du nom pour préciser que ce sont des types. Il faut aussi encapsuler les variable et les générique (respectivement var(x) et gen(a)) pour donner une distinction dans l'evaluation des règles. Il n'y a pas besoin de créer les règles pour les symboles true et false.
Après cela, il a fallut créer deux règles pour la sémantique dévaluation (evaluation(Context, Term, Result)) et la sémantique de typage (typage(Context, Term, Result)).
On peut prendre par exemple la fonction d'itentité représenté avec le langage système C3PO, ainsi que sa sémantique d'évaluation et sa sémantique de typage.
#Exemple()[Application de la fonction identité dans la syntaxe de Système C3PO
```R
func<T>(a: T) -> T {
a
}(7)
# va retourner 7
```
]
#Exemple()[Application de la fonction identité : sémantique d'évaluation
```prolog
evaluation([],
app(
func([gen(t)], [[var(a), get(t)]], gen(t), var(a)),
[],
[7]
),
7
).
```
]
#Exemple()[Application de la fonciton identité : sémantique de typage
```prolog
typing([],
app(
func([gen(t)], [[var(a), gen(t)]], gen(t), var(a)),
[int],
par([7])
),
int
).
```
]
Le code prolog se trouve dans mon repository github. Les deux fichiers principaux sont `evaluation.pl` et `typage.pl`. Il existe une liste de testes dans ces deux fichiers.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/dict-06.typ | typst | Other | // Error: 24-29 duplicate key: first
#(first: 1, second: 2, first: 3)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.1.2/src/canvas.typ | typst | Apache License 2.0 | #import "matrix.typ"
#import "vector.typ"
#import "draw.typ"
#import "cmd.typ"
#import "util.typ"
#import "coordinate.typ"
#import "styles.typ"
#import "path-util.typ"
#import "aabb.typ"
// Aliases for typst types/functions
// because we override them.
#let typst-length = length
// Recursive element traversal function which takes the current ctx, bounds and also returns them (to allow modifying function locals of the root scope)
#let process-element(element, ctx) = {
if element == none { return }
let drawables = ()
let bounds = none
let anchors = (:)
// Allow to modify the context
if "before" in element {
ctx = (element.before)(ctx)
}
if "style" in element {
ctx.style = util.merge-dictionary(
ctx.style,
if type(element.style) == function {
(element.style)(ctx)
} else {
element.style
}
)
}
if "push-transform" in element {
if type(element.push-transform) == function {
ctx.transform = (element.push-transform)(ctx)
} else {
ctx.transform = matrix.mul-mat(
ctx.transform,
element.push-transform
)
}
}
// Render children
if "children" in element {
let child-drawables = ()
let children = if type(element.children) == function {
(element.children)(ctx)
} else {
element.children
}
for child in children {
let r = process-element(child, ctx)
if r != none {
if r.bounds != none {
bounds = aabb.aabb(r.bounds, init: bounds)
}
ctx = r.ctx
child-drawables += r.drawables
}
}
if "finalize-children" in element {
drawables += (element.finalize-children)(ctx, child-drawables)
} else {
drawables += child-drawables
}
}
// Query element for points
let coordinates = ()
if "coordinates" in element {
for c in element.coordinates {
c = coordinate.resolve(ctx, c)
// if the first element is `false` don't update the previous point
if c.first() == false {
// the format here is `(false, x, y, z)` so get rid of the boolean
c = c.slice(1)
} else {
ctx.prev.pt = c
}
coordinates.push(c)
}
// If the element wants to calculate extra coordinates depending
// on it's resolved coordinates, it can use "transform-coordinates".
if "transform-coordinates" in element {
assert(type(element.transform-coordinates) == function)
coordinates = (element.transform-coordinates)(ctx, ..coordinates)
}
}
// Render element
if "render" in element {
for drawable in (element.render)(ctx, ..coordinates) {
// Transform position to absolute
drawable.segments = drawable.segments.map(s => {
return (s.at(0),) + s.slice(1).map(util.apply-transform.with(ctx.transform))
})
if "bounds" not in drawable {
drawable.bounds = path-util.bounds(drawable.segments)
} else {
drawable.bounds = drawable.bounds.map(util.apply-transform.with(ctx.transform));
}
bounds = aabb.aabb(drawable.bounds, init: bounds)
// Push draw command
drawables.push(drawable)
}
}
// Add default anchors
if bounds != none and element.at("add-default-anchors", default: true) {
let mid = aabb.mid(bounds)
let (low: low, high: high) = bounds
anchors += (
center: mid,
left: (low.at(0), mid.at(1), 0),
right: (high.at(0), mid.at(1), 0),
top: (mid.at(0), low.at(1), 0),
bottom: (mid.at(0), high.at(1), 0),
top-left: (low.at(0), low.at(1), 0),
top-right: (high.at(0), low.at(1), 0),
bottom-left: (low.at(0), high.at(1), 0),
bottom-right: (high.at(0), high.at(1), 0),
)
// Add alternate names
anchors.above = anchors.top
anchors.below = anchors.bottom
}
// Query element for (relative) anchors
let custom-anchors = if "custom-anchors-ctx" in element {
(element.custom-anchors-ctx)(ctx, ..coordinates)
} else if "custom-anchors" in element {
(element.custom-anchors)(..coordinates)
}
if custom-anchors != none {
for (k, a) in custom-anchors {
anchors.insert(k, util.apply-transform(ctx.transform, a)) // Anchors are absolute!
}
}
// Query (already absolute) anchors depending on drawable
if "custom-anchors-drawables" in element {
for (k, a) in (element.custom-anchors-drawables)(drawables) {
anchors.insert(k, a)
}
}
if "default" not in anchors {
anchors.default = if "default-anchor" in element {
anchors.at(element.default-anchor)
} else if "center" in anchors {
anchors.center
} else {
(0,0,0,1)
}
}
if "anchor" in element and element.anchor != none {
assert(element.anchor in anchors,
message: "Anchor '" + element.anchor + "' not found in " + repr(anchors))
let translate = vector.sub(anchors.default, anchors.at(element.anchor))
for (i, d) in drawables.enumerate() {
drawables.at(i).segments = d.segments.map(
s => (s.at(0),) + s.slice(1).map(c => vector.add(translate, c)))
}
for (k, a) in anchors {
anchors.insert(k, vector.add(translate, a))
}
bounds = if bounds != none {
aabb.aabb((vector.add(translate, (bounds.low.at(0), bounds.low.at(1))),
vector.add(translate, (bounds.high.at(0), bounds.high.at(1)))))
}
}
if "name" in element and type(element.name) == str {
ctx.nodes.insert(
element.name,
(
anchors: anchors,
// paths: drawables, // Uncomment as soon as needed
)
)
}
if ctx.debug and bounds != none {
drawables.push(
cmd.path(
stroke: red,
fill: none,
close: true,
("line", bounds.low,
(bounds.high.at(0), bounds.low.at(1)),
bounds.high,
(bounds.low.at(0), bounds.high.at(1)))
).first()
)
}
if "after" in element {
ctx = (element.after)(ctx, ..coordinates)
}
return (bounds: bounds, ctx: ctx, drawables: drawables)
}
#let canvas(length: 1cm, /* Length of 1.0 canvas units */
background: none, /* Background paint */
debug: false, body) = layout(ly => style(st => {
if body == none {
return []
}
let length = length
assert(type(length) in (typst-length, ratio),
message: "length: Expected length, got " + type(length) + ".")
if type(length) == ratio {
// NOTE: Ratio length is based on width!
length = ly.width * length
} else {
// HACK: To convert em sizes to absolute sizes, we
// measure a rect of that size.
length = measure(line(length: length), st).width
}
// Canvas bounds
let bounds = none
// Canvas context object
let ctx = (
typst-style: st,
length: length,
debug: debug,
// Previous element position & bbox
prev: (pt: (0, 0, 0)),
// Current content padding size (added around content boxes)
content-padding: 0em,
em-size: measure(box(width: 1em, height: 1em), st),
style: (:),
// Current transform
transform: matrix.mul-mat(
matrix.transform-shear-z(.5),
matrix.transform-scale((x: 1, y: -1, z: 1)),
),
// Nodes, stores anchors and paths
nodes: (:),
// group stack
groups: (),
)
let draw-cmds = ()
for element in body {
let r = process-element(element, ctx)
if r != none {
if r.bounds != none {
bounds = aabb.aabb(r.bounds, init: bounds)
}
ctx = r.ctx
draw-cmds += r.drawables
}
}
if bounds == none {
return []
}
// Order draw commands by z-index
draw-cmds = draw-cmds.sorted(key: (cmd) => {
return cmd.at("z-index", default: 0)
})
// Final canvas size
let (width, height, ..) = vector.scale(aabb.size(bounds), length)
// Offset all element by canvas grow to the bottom/left
let transform = matrix.transform-translate(
-bounds.low.at(0),
-bounds.low.at(1),
0
)
box(
stroke: if debug {green},
width: width,
height: height,
fill: background,
align(
top,
for d in draw-cmds {
d.segments = d.segments.map(s => {
return (s.at(0),) + s.slice(1).map(v => {
return util.apply-transform(transform, v)
.slice(0,2).map(x => ctx.length * x)
})
})
(d.draw)(d)
}
)
)
}))
|
https://github.com/0x1B05/nju_os | https://raw.githubusercontent.com/0x1B05/nju_os/main/lecture_notes/content/27_设备驱动程序与文件系统.typ | typst | #import "../template.typ": *
#pagebreak()
= 设备驱动程序与文件系统
== 设备驱动程序
=== I/O 设备的抽象
I/O 设备模型:一个能与 CPU 交换数据的接口/控制器
- 寄存器被映射到地址空间
#image("images/2024-02-26-21-51-38.png")
操作系统:设备也是操作系统中的对象
如何 “找到” 一个对象?
- 对象支持什么操作?
- I/O 设备的抽象 (cont'd)
=== I/O 设备的抽象 (cont'd)
I/O 设备的主要功能:输入和输出
- “能够读 (read) 写 (write) 的字节序列 (流或数组)”
- 常见的设备都满足这个模型
- 终端/串口 - 字节流
- 打印机 - 字节流 (例如 PostScript 文件)
- 硬盘 - 字节数组 (按块访问)
- GPU - 字节流 (控制) + 字节数组 (显存)
操作系统:设备 = 支持各类操作的对象 (文件)
- read - 从设备某个指定的位置读出数据
- write - 向设备某个指定位置写入数据
- ioctl - 读取/设置设备的状态
=== 设备驱动程序
把系统调用 (read/write/ioctl/...) “翻译” 成与设备寄存器的交互
- 就是一段普通的内核代码
- 但可能会睡眠 (例如 P 信号量,等待中断中的 V 操作唤醒)
例子:`/dev/` 中的对象
- `/dev/pts/[x]` - pseudo terminal
- `/dev/zero` - “零” 设备
- `/dev/null` - “null” 设备
- `/dev/random`, `/dev/urandom` - 随机数生成器
- 试一试:head -c 512 [device] | xxd
- 以及观察它们的 strace
- 能看到访问设备的系统调用
=== 例子: Lab 2 设备驱动
设备模型
- 简化的假设
- 设备从系统启动时就存在且不会消失
- 支持读/写两种操作
- 在无数据或数据未就绪时会等待 (P 操作)
```c
typedef struct devops {
int (*init)(device_t *dev);
int (*read) (device_t *dev, int offset, void *buf, int count);
int (*write)(device_t *dev, int offset, void *buf, int count);
} devops_t;
```
I/O 设备看起来是个 “黑盒子”
- 写错任何代码就 simply “not work”
- 设备驱动:Linux 内核中最多也是质量最低的代码
=== 字节流/字节序列抽象的缺点
设备不仅仅是数据,还有控制
- 尤其是设备的附加功能和配置
- 所有额外功能全部依赖 ioctl
- “Arguments, returns, and semantics of ioctl() vary according to the device
driver in question”
- 无比复杂的 “hidden specifications”
例子
- 打印机的打印质量/进纸/双面控制、卡纸、清洁、自动装订……
- 一台几十万的打印机可不是那么简单 😂
- 键盘的跑马灯、重复速度、宏编程……
- 磁盘的健康状况、缓存控制……
=== 例子:终端
“字节流” 以内的功能
- ANSI Escape Code
- (还记得第一次课的那个数码管吗?)
“字节流” 以外的功能
- `stty -a`
- 终端大小怎么知道?
- 终端大小变化又怎么知道?
- isatty (3), termios (3)
- 大部分都是 `ioctl` 实现的
- 这才是水面下的冰山的一角
== Linux 设备驱动
=== Nuclear Launcher
如何在 Linux 中为我们的 “核弹发射器” 编写一个设备驱动程序?
内核模块:一段可以被内核动态加载执行的代码
- Everything is a file
- 设备驱动就是实现了 struct file_operations 的对象
- 把文件操作翻译成设备控制协议
- 调用到设备实现的 file_operations
=== 更多的 File Operations
```c
struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
int (*mmap) (struct file *, struct vm_area_struct *);
unsigned long mmap_supported_flags;
int (*open) (struct inode *, struct file *);
int (*release) (struct inode *, struct file *);
int (*flush) (struct file *, fl_owner_t id);
int (*fsync) (struct file *, loff_t, loff_t, int datasync);
int (*lock) (struct file *, int, struct file_lock *);
ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
int (*flock) (struct file *, int, struct file_lock *);
...
```
=== 为什么有两个 ioctl?
```c
long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
```
- `unlocked_ioctl`: BKL (Big Kernel Lock) 时代的遗产
- 单处理器时代只有 `ioctl`
- 之后引入了 BKL, `ioctl` 执行时默认持有 BKL
- (2.6.11) 高性能的驱动可以通过 `unlocked_ioctl` 避免锁
- (2.6.36) `ioctl` 从 struct file\*operations 中移除
- `compact_ioctl`: 机器字长的兼容性
- 32-bit 程序在 64-bit 系统上可以 `ioctl`
- 此时应用程序和操作系统对 ioctl 数据结构的解读可能不同 (tty)
- (调用此兼容模式)
=== 存储设备的抽象
磁盘 (存储设备) 的访问特性
- 以数据块 (block) 为单位访问
- 传输有 “最小单元”,不支持任意随机访问
- 最佳的传输模式与设备相关 (HDD v.s. SSD)
- 大吞吐量
- 使用 DMA 传送数据
- 应用程序不直接访问
- 访问者通常是文件系统 (维护磁盘上的数据结构)
- 大量并发的访问 (操作系统中的进程都要访问文件系统)
=== Linux Block I/O Layer
文件系统和磁盘设备之间的接口
- bread (读一块), bwrite (写一块), bflush (等待过往写入落盘)
#image("images/2024-02-27-10-14-34.png")
== 存储设备的虚拟化
=== 文件系统:实现设备在应用程序之间的共享
磁盘中存储的数据
- 程序数据
- 可执行文件和动态链接库
- 应用数据 (高清图片、过场动画、3D 模型……)
- 用户数据
- 文档、下载、截图
- 系统数据
- Manpages
- 配置文件 (/etc)
字节序列并不是磁盘的好抽象
- 让所有应用共享磁盘?一个程序 bug 操作系统就没了
=== 文件系统:磁盘的虚拟化
文件系统:设计目标
1. 提供合理的 API 使多个应用程序能共享数据
2. 提供一定的隔离,使恶意/出错程序的伤害不能任意扩大
“存储设备 (字节序列) 的虚拟化”
- 磁盘 (I/O 设备) = 一个可以读/写的字节序列
- 虚拟磁盘 (文件) = 一个可以读/写的动态字节序列
- 命名管理
- 虚拟磁盘的名称、检索和遍历
- 数据管理
- `std::vector<char>` (随机读写/resize)
=== 文件 = 虚拟磁盘
文件:虚拟的磁盘
- 磁盘是一个 “字节序列”
- 支持读/写操作
文件描述符:进程访问文件 (操作系统对象) 的 “指针”
- 通过 `open`/`pipe` 获得
- 通过 `close` 释放
- 通过 `dup`/`dup2` 复制
- `fork` 时继承
=== `mmap` 和文件
```c
void *mmap(
void *addr, size_t length, int prot, int flags,
int fd, off_t offset // 映射 fd 文件
); // offset 开始的 length 字节
```
文件是 “虚拟磁盘”
把磁盘的一部分映射到地址空间,再自然不过了
==== 小问题
- 映射的长度超过文件大小会发生什么?
- (RTFM, “Errors” section): `SIGBUS`...
- bus error 的常见来源 (M5)
- `ftruncate` 可以改变文件大小
=== 文件访问的游标 (偏移量)
文件的读写自带 “游标”,这样就不用每次都指定文件读/写到哪里了
- 方便了程序员顺序访问文件
例子
- `read(fd, buf, 512);` - 第一个 512 字节
- `read(fd, buf, 512);` - 第二个 512 字节
- `lseek(fd, -1, SEEK_END);` - 最后一个字节
- so far, so good
=== 偏移量管理:没那么简单 (1)
`mmap`, `lseek`, `ftruncate` 互相交互的情况
初始时文件大小为 0
- `mmap` (length = 2 MiB)
- `lseek` to 3 MiB (`SEEK_SET`)
- `ftruncate` to 1 MiB
在任何时刻,写入数据的行为是什么?
- blog posts 不会告诉你全部
- RTFM & 做实验!
> 文件描述符在 fork 时会被子进程继承。
父子进程应该共用偏移量,还是应该各自持有偏移量?
- 这决定了 offset 存储在哪里
考虑应用场景
- 父子进程同时写入文件
- 各自持有偏移量 → 父子进程需要协调偏移量的竞争
- (race condition)
- 共享偏移量 → 操作系统管理偏移量
- 虽然仍然共享,但操作系统保证 write 的原子性 ✅
=== 偏移量管理:行为
操作系统的每一个 API 都可能和其他 API 有交互 😂
- `open` 时,获得一个独立的 offset
- `dup` 时,两个文件描述符共享 offset
- `fork` 时,父子进程共享 offset
- `execve` 时文件描述符不变
- `O_APPEND` 方式打开的文件,偏移量永远在最后 (无论是否 fork)
- modification of the file offset and the write operation are performed as a
single atomic step
这也是 fork 被批评的一个原因
- (在当时) 好的设计可能成为系统演化过程中的包袱
- 今天的 fork 可谓是 “补丁满满”;[ A fork() in the road
](https://dl.acm.org/doi/10.1145/3317550.3321435)
== 目录树管理
=== 虚拟磁盘那么多,怎么找到想要的?
信息的局部性:将虚拟磁盘 (文件) 组织成层次结构
=== 利用信息的局部性组织虚拟磁盘
目录树
逻辑相关的数据存放在相近的目录
```
.
└── 学习资料
├── .学习资料(隐藏)
├── 问题求解1
├── 问题求解2
├── 问题求解3
├── 问题求解4
└── 操作系统
```
=== 文件系统的 “根”
树总得有个根结点
- Windows: 每个设备 (驱动器) 是一棵树
- `C:\` “C 盘根目录”
- `C:\Program Files\`, `C:\Windows`, `C:\Users`, ...
- 优盘分配给新的盘符
- 为什么没有 A:\, B:\?
- 简单、粗暴、方便,但 game.iso 一度非常麻烦……
- UNIX/Linux
- 只有一个根 `/`
- 第二个设备呢?
- 优盘呢???
=== 目录树的拼接
UNIX: 允许任意目录 “挂载 (mount)” 一个设备代表的目录树
- 非常灵活的设计
- 可以把设备挂载到任何想要的位置
- Linux 安装时的 “mount point”
- `/`, `/home`, `/var` 可以是独立的磁盘设备
mount 系统调用
```c
int mount(const char *source, const char *target,
const char *filesystemtype, unsigned long mountflags,
const void *data);
```
`mount /dev/sdb /mnt` (RTFM) Linux mount 工具能自动检测文件系统 (busybox 不能)
=== 真正的 Linux 启动流程
Linux-minimal 运行在 “initramfs” 模式
- Initial RAM file system
- 完整的文件系统
- 可以包含设备驱动等任何文件
- 但不具有 “持久化” 的能力
最小 “真正” Linux 的启动流程
```sh
export PATH=/bin
busybox mknod /dev/sda b 8 0
busybox mkdir -p /newroot
busybox mount -t ext2 /dev/sda /newroot
exec busybox switch_root /newroot/ /etc/init
```
通过 `pivot_root (2)` 实现根文件系统的切换
=== 文件的挂载
文件的挂载引入了一个微妙的循环
- 文件 = 磁盘上的虚拟磁盘
- 挂载文件 = 在虚拟磁盘上虚拟出的虚拟磁盘 🤔
Linux 的处理方式
- 创建一个 loopback (回环) 设备
- 设备驱动把设备的 `read`/`write` 翻译成文件的 `read`/`write`
- 观察 `disk-img.tar.gz` 的挂载
- `lsblk` 查看系统中的 block devices (strace)
- `strace` 观察挂载的流程
- `ioctl(3, LOOP_CTL_GET_FREE)`
- `ioctl(4, LOOP_SET_FD, 3)`
=== [ Filesystem Hierarchy Standard (FHS) ](http://refspecs.linuxfoundation.org/FHS_3.0/fhs/index.html)
FHS enables software and user to predict the location of installed files and
directories.
例子:macOS 是 UNIX 的内核 (BSD), 但不遵循 Linux FHS
#image("images/2024-02-27-10-47-11.png")
=== 目录管理:创建/删除/遍历
这个简单
- `mkdir`
- 创建一个目录
- 可以设置访问权限
- `rmdir`
- 删除一个空目录
- 没有 “递归删除” 的系统调用
- (应用层能实现的,就不要在操作系统层实现)
- rm -rf 会遍历目录,逐个删除 (试试 strace)
- getdents
- 返回 count 个目录项 (ls, find, tree 都使用这个)
- 以点开头的目录会被系统调用返回,只是 ls 没有显示
=== 更人类友好的目录访问方式
合适的 API + 合适的编程语言
- Globbing
```py
from pathlib import Path
for f in Path('/proc').glob('\*/status'):
print(f.parts[-2], \
(f.parent / 'cmdline').read_text() or '[kernel]')
```
=== 硬 (hard) 链接
需求:系统中可能有同一个运行库的多个版本
- `libc-2.27.so`, `libc-2.26.so`, ...
- 还需要一个 “当前版本的 libc”
- 程序需要链接 “libc.so.6”,能否避免文件的一份拷贝?
- 硬连接:允许一个文件被多个目录引用
- 目录中仅存储指向文件数据的指针
- 链接目录 ❌
- 跨文件系统 ❌
- 大部分 UNIX 文件系统所有文件都是硬连接 (ls -i 查看)
- 删除的系统调用称为 “unlink” (引用计数)
=== 软 (symbolic) 链接
软链接:在文件里存储一个 “跳转提示”
- 软链接也是一个文件
- 当引用这个文件时,去找另一个文件
- 另一个文件的绝对/相对路径以文本形式存储在文件里
- 可以跨文件系统、可以链接目录、……
- 类似 “快捷方式”
- 链接指向的位置当前不存在也没关系
- `~/usb` → `/media/jyy-usb`
- `~/Desktop` → `/mnt/c/Users/jyy/Desktop` (WSL)
`ln -s` 创建软链接
- symlink 系统调用
=== 软链接带来的麻烦
“任意链接” 允许创建任意有向图 😂
- 允许多次间接链接
- a → b → c (递归解析)
- 可以创建软连接的硬链接 (因为软链接也是文件)
- `ls -i` 可以看到
- 允许成环
- `find -L A | tr -d '/'`
- 可以做成一个 “迷宫游戏”
- ssh 进入游戏,进入名为 end 的目录胜利
- 只允许 `ls (-i)`, `cd`, `pwd`
- 所有处理符号链接的程序 (`tree`, `find`, ...) 都要考虑递归的情况
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-03.typ | typst | Other | // Error: 8-13 expected boolean, integer, float, ratio, or string, found function
#float(float)
|
https://github.com/RanolP/typlog | https://raw.githubusercontent.com/RanolP/typlog/main/series/make-a-pl/00-foreword.typ | typst | #import "../../_utils/_prelude.typ": *
#post(
0,
"시작에 앞서",
)[
사람들은 고수준의 아이디어를 펴내길 원하고, 기계들은 작은 명령 집합을 가지고 있습니다. 따라서, 두 집단 사이 소통에는 번역이 필요하죠.
이때, 프로그래밍 언어가 사람과 기계 사이를 이어주는 징검다리 역할을 합니다. 사람이 쓴 고수준 코드를 기계가 알아듣기 쉽게 번역해주죠.
여기서, 번역하기 전의 고수준 코드를 #word("원본 코드", "Source Code")라고 하며, 번역이 완료되어 기계라는 목표에 더
가까워진 저수준 코드를 #word("목표 코드", "Target Code")라고 부릅니다.
#figure(
rect(
width: 80%,
inset: (y: 32pt),
..engraved,
)[#fletcher.diagram(node((0, 0), [원본 코드]), edge("-|>"), node((0, 1), rect(
inset: 8pt,
fill: palette.blue-5,
..embossed(palette.blue-5),
)[#text(fill: white)[컴파일러]]), edge("-|>"), node((0, 2), [목표 코드]))
],
caption: [단순한 컴파일러],
)
=== 연습 문제
간단한 컴파일러를 만들어봅시다. 아래 스펙을 구현해보세요. 모든 명령은 무조건 줄 단위로(다시 말해, `\n` 문자로) 나뉘어 있으며, 올바르지
않은 프로그램 입력은 주어지지 않는다고 가정해도 좋습니다. 목표 코드는 어떤 언어이든 상관 없으나, 실행 가능한 프로그래밍 언어여야 합니다.
#table(
align: horizon + center,
columns: 2,
stroke: embossed(color.rgb("#d2d2d2")).stroke,
column-gutter: 8pt,
row-gutter: 8pt,
[*A* = *B* \ ```typlog_regexp /([a-zA-Z]+)\s*=\s*([0-9]+)/```],
[변수 이름 *A*에 정수형 값 *B*를 대입한다\ *B*의 범위는 $plus.minus 1000$을 넘지 않는다],
[putchar *A* \ ```typlog_regexp /putchar\s*([a-zA-Z]+)/```],
[변수 *A*에 담긴 값에 해당하는 ASCII 문자를 출력한다],
)
이 언어로 Hello를 출력하는 예제입니다.
```
H=72
e=101
l=108
o=111
putchar H
putchar e
putchar l
putchar l
putchar o
```
다음 페이지에 JavaScript/Python으로 작성한 예시 답안이 있습니다. 편의상 eval로 즉시 실행할 수 있게, 컴파일 대상 언어를 그
자신으로 해두었습니다.
#pagebreak()
==== 예시 답안
===== JavaScript
```js
function compile(source) {
let output = '';
for (const line of source.split("\n")) {
let match;
if (match = /([a-zA-Z]+)\s*=\s*([0-9]+)/.exec(line)) {
[, name, value] = match;
output += `${name} = ${value};\n`;
} else if (match = /putchar\s*([a-zA-Z]+)/.exec(line)) {
[, name] = match;
output += `process.stdout.write(String.fromCharCode(${name}));\n`
} else {
throw new Error(`Malformed Input: ${line}`);
}
}
return output;
}
```
===== Python
```py
import re
def compile(source):
output = ""
for line in source.split("\n"):
if match := re.match(r"([a-zA-Z]+)\s*=\s*([0-9]+)", line):
name, value = match.groups()
output += f"{name} = {value}\n"
elif match := re.match(r"putchar\s*([a-zA-Z]+)", line):
name = match.group(1)
output += f"print(chr({name}), end='')\n"
else:
raise Exception(f"Malformed Input: {line}")
return output
```
]
|
|
https://github.com/hongjr03/shiroa-page | https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DIP/chapters/6多分辨率处理.typ | typst | #import "../template.typ": *
#import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge
#import fletcher.shapes: house, hexagon, ellipse
#import "@preview/pinit:0.1.4": *
#import "@preview/cetz:0.2.2"
#import "/book.typ": book-page
#show: book-page.with(title: "数字图像处理基础 | DIP")
= 多分辨率处理 Multiresolution Processing
== 图像金字塔 Image Pyramids
构建过程:
#figure(
[
#let blob(pos, label, tint: white, ..args) = node(
pos,
align(center, label),
width: 28mm,
fill: tint.lighten(60%),
stroke: 1pt + tint.darken(20%),
corner-radius: 5pt,
..args,
)
#diagram(
spacing: 8pt,
cell-size: (8mm, 10mm),
edge-stroke: 1pt,
edge-corner-radius: 5pt,
mark-scale: 70%,
blob((0, 0), [第 $j$ 级\ 输入图像], width: auto, tint: red),
edge("-|>"),
edge("dddd,rrrrr", "-|>", $+$, label-pos: 0.97, label-side: center),
blob(
(2, 0),
[
近似滤波器\
如高斯滤波器
],
tint: orange,
),
edge("-|>"),
blob((4, 0), [2x下采样], tint: yellow, shape: hexagon),
edge("-|>"),
blob((6, 0), [第 $j+1$ 级\ 近似图像], width: auto, tint: red),
edge((5, 0), "dddd", "-|>", $-$, label-pos: 0.88, label-side: center),
blob((5, 1.25), [2x上采样], tint: yellow, shape: hexagon),
blob((5, 2.25), [插值滤波器], tint: orange),
blob((5, 4), [$+$], shape: circle, width: auto, tint: red),
edge("-|>"),
blob((6, 4), [第 $j$ 级\ 预测残差图像], width: auto, tint: red),
)
],
// caption: "高斯金字塔构建过程",
)
构建高斯金字塔的时候,先对图像进行高斯滤波,然后下采样。PPT上提到下采样也是通过高斯滤波来实现的,因为直接下采样(只拿奇数、偶数位置的像素点)会导致混叠、失真。
接着对每一步结果进行上采样(隔行、隔列补0),然后滤波(也是用的高斯滤波核,但是因为信息量只有$1/4$,所以核的权重$times 4$),再和上一步的结果相减,这样就得到了拉普拉斯金字塔。
#figure(image("../assets/2024-06-22-11-59-37.png", width: 78%))
== 小波变换 Wavelet Transform
#figure([
#let blob(
pos,
label,
tint: white,
..args,
) = node(
pos,
align(center, label),
width: auto,
inset: 6pt,
// fill: tint.lighten(60%),
// stroke: 1pt + tint.darken(20%),
// corner-radius: 5pt,
..args,
)
#diagram(
spacing: 8pt,
cell-size: (8mm, 10mm),
edge-stroke: 1pt,
edge-corner-radius: 5pt,
mark-scale: 70%,
blob((0, 0), $W_phi (j+1, n)$, width: auto),
blob((2, -.5), $h_psi (-n)$, shape: rect, stroke: 1pt + black),
edge("-|>"),
blob((3.5, -.5), $2↓$, shape: rect, stroke: 1pt + black),
edge("-|>"),
blob((5, -.5), $W_psi (j, n)$, width: auto),
blob((2, .5), $h_phi (-n)$, shape: rect, stroke: 1pt + black),
edge("-|>"),
blob((3.5, .5), $2↓$, shape: rect, stroke: 1pt + black),
edge("-|>"),
blob((5, .5), $W_phi (j, n)$, width: auto),
for y in (-.5, .5) {
edge((0, 0), "r", (1, y), "r", "-|>")
},
)])
|
|
https://github.com/augustebaum/petri | https://raw.githubusercontent.com/augustebaum/petri/main/tests/README.md | markdown | MIT License | # Tests
Tests of the library, which can be hacked on using `typst-test`.
Many of the tests are inspired by prior work in TikZ, including:
- <https://latexdraw.com/petri-nets-tikz/>
- <https://tikz.dev/library-petri>
## Example gallery
The following examples are obtained by rendering the individual tests.









|
https://github.com/zurgl/typst-resume | https://raw.githubusercontent.com/zurgl/typst-resume/main/resume/fr/professional.typ | typst | #import "../../templates/resume/section.typ": cvSection
#import "../../templates/resume/entry.typ": cvEntry
#import "@preview/fontawesome:0.1.0": *
#let innerList(str) = {
text(fill: rgb("#343a40"), {
v(-2pt)
str
})
}
#cvSection("Expérience Professionnelle")
#cvEntry(
title: [Freelance],
society: [YetAnotherSolution],
date: [Février 2021 - Présent],
location: [Troyes, France],
description: list(
[Conseil en ingénierie des S.I auprès d'entreprise nationale et internationale],
[Focus prioritaire sur les nouvelles technologies et leur intégration],
[Blockchain, IA générative, résilience et fiabilité des S.I.]
),
logo: "yas.png",
tags: ("Solana", "Typescript", "Rust", "PyTorch", "Linux", "Next.js", "Git", "IA Générative", "LLM" , "Stable Diffusion")
)
$/* ----------------------------- */$
#cvEntry(
title: [Solana Smart Contract Dev],
society: [Figment - Solana],
date: [Février 2022 - Septembre 2022],
location: [Remote, Canada],
description: list(
[ Développement d'un smart contract sur Solana pour la création d'une plateforme web de création de contenu, à la "Medium".],
[ Emission de deux tokens: un "Soul Bond Token" pour gérer les droits d'accès, un token utilitaire pour récompenser les membres.],
[ Les fonctions du contract permettent "on-chain": la gestion de la communauté (DAO-like), le sponsoring des créateurs, la proposition, la validation, la révision et la publication de nouveaux contenus.],
),
logo: "fig-sol.png",
tags: ("Solana", "SPL", "Rust", "linux", "DAO", "Soul bond token", "JIRA", "Scrum", "DAO", "Système d'économie de jetons"),
double: "yes",
)
$/* ----------------------------- */$
#cvEntry(
title: [Ethereum Smart Contract Dev],
society: [Figment - Ethereum],
date: [Novembre 2021 - Fevrier 2022],
location: [Remote, Canada],
description: list(
[ Création d'un smart contract sur Ethereum ciblant l'étape 0 du projet Ethereum 2.0: "Beacon Chain".],
[ L'objet du contract est la création de "batch de transaction" facilitant le stacking massif d'ETH (jusqu'à 100 x 32 ETH).],
[ Audit externe, validation et deploiement du contrat sur la "Beacon Chain" en production.],
),
logo: "fig-eth.png",
tags: ("Git", "Solidity", "Ethereum 2.0", "Smart contract Auditing", "Smart Contract Hardening", "Stacking"),
double: "yes",
)
$/* ----------------------------- */$
#cvEntry(
title: [Ingénieur logiciel - Content writer],
society: [Figment],
date: [Avril 2021 - Octobre 2021],
location: [Remote, Canada],
description: list(
[ Création de tutoriels pour diverses blockchains afin de diffuser les compétences de base en codage pour le web3.],
[ Depuis une application NextJS et en React: #innerList(list(
[ Connexion au wallet et soumission de transaction],
[ Récupération des donnée liées au wallet],
[ Intéraction avec des contracts "on-chain"],
[ Codage et déploiement de smart contract],
))],
[ Périmètre: Solana, CELO, TheGraph, APTOS, Tezos, Avalanche, Arweave, NEAR, Polygon, Polkadot, Ethereum],
),
logo: "figment.png",
tags: ("Typescript", "Next.js", "Github", "React", "Rust", "Solidity", "Move", "Markdown", "HTML/CSS")
)
$/* ----------------------------- */$
#cvEntry(
title: [Enseignant de Mathématiques],
society: [Cours Saint-François de Sales],
date: [Septembre 2017 - Août 2020],
location: [Paris, France],
description: list(
[Gestion de classes et transmission des savoirs.],
[Création de supports de cours et évaluation des élèves.],
),
logo: "sfds.png",
tags: ("Gestion de groupe", "Résolution des conflits", "Pédagogie", "Latex", "GeoGebra", "Scratch")
)
$/* ----------------------------- */$
#cvEntry(
title: [Ingénieur recherche et développement],
society: [Université Technologique de Troyes],
date: [Avril 2016 - Juin 2017],
location: [Paris, France],
description: list(
[Recours à théorie des graphes pour modéliser et résoudre des problèmes de planifications.],
[Implémentation de la solution sous la forme d'une bibilothèque C++.],
[Intégration de la solution sous la forme d'un service web interfaçant la lib C++ et les usagers du système d'information.],
),
logo: "utt.png",
tags: ("Théorie des graphes", "Recherche opérationnelle", "Planification", "C++", "Git", "Oracle", "PHP", "HTLM/CSS", "API", "FFI")
)
$/* ----------------------------- */$
#cvEntry(
title: [Enseignant de Mathématiques],
society: [Ministère de l'Éducation nationale],
date: [Janvier 2013 - Septembre 2015],
location: [Paris, France],
description: list(
[Répetiteur à domicile en sciences auprès d'élèves de tous niveaux, du collège jusque BAC+2.],
[Enseignant de sciences au CFA],
[Chargé de TD en mathématiques financière au sein de Y-Schools],
),
logo: "marie.png",
tags: ("Ecole de commerce", "CFA", "Enseignement", "Pédagogie")
)
$/* ----------------------------- */$
#cvEntry(
title: [Globetrotteur, Polymathe],
society: [Période de césure],
date: [Janvier 2012 - Décembre 2012],
location: [Troyes, France],
description: list(
[Année de césure dédiée aux voyages et à la veille scientifiques concernant les applications de la théories des catégories à la conception de nouveau langage de programmation.]
),
logo: "globe.png",
tags: ("Théorie des Topos", "Theorie des catégories", "Programmation fonctionnelle", "Lambda Calcul", "Haskell", "LISP", "Théorie des types")
)
$/* ----------------------------- */$
#cvEntry(
title: [Ingénieur logiciel],
society: [Cetelem],
date: [Juin 2011 - Décembre 2011],
location: [Paris, France],
description: list(
[En charge de l'évolution de l'application de calculs du risque de défaut des crédits à la consommation.],
[Mise en place d'un nouveau schéma de partitionnement des jeux de donnée à l'aide d'un algorithme de hachage.],
[Cette amélioration a permis la parallélisation des caculs offrant un gain de performance important dans la production des indicateurs.],
),
logo: "cetelem.png",
tags: ("SAS", "Langage C", "Bash scripting", "Linux", "Big Data")
)
$/* ----------------------------- */$
#cvEntry(
title: [Ingénieur recherche et développement, Data Analyste],
society: [BNP Arbitrage],
date: [Mars 2010 - Janvier 2011],
location: [Paris, France],
description: list(
[Collaboration avec les analystes quantitatifs à l'évolution applicative d'une solution intégrant tous les fournisseurs de données financières.],
[Normalisation et "cleaning" de 1 To de donnée journalière.],
[Création d'un nouveau pipeline dédié à l'indice VIX.],
[Consolidation du référentiel interne pour supprimer les données en double.],
),
logo: "bnp.png",
tags: ("Reuters", "Bloomberg", "Linux", "Python", "HDF5", "SQLite", "C++", "Linux", "Langage C")
)
$/* ----------------------------- */$
#cvEntry(
title: [Ingénieur logiciel, Gestion des risques],
society: [Société Générale],
date: [Février 2009 - Décembre 2009],
location: [Paris, France],
description: list(
[En charge de la maintenance et de l'évolution d'une application d'évaluation des risques financiers sur les fonds d'investissement.],
[Implémentation de la "Value At Risque" sur l'intégralité du périmètre.],
[Implémentation de 8 scénarios de "Stress Test", portant sur des variations importantes des: Taux, Devises, Actions, Bonds],
[Mise en place d'un reporting quotidien diffusant les indicateurs de risques aux équipes de gestion avant l'ouverture des marchés],
),
logo: "sg.png",
tags: ("Excel", "Java", "Visual Basic", "RiskData", "Control-M")
)
$/* ----------------------------- */$
#cvEntry(
title: [Ingénieur logiciel, Chef de Projet],
society: [State Street Corporation],
date: [Juin 2007 - Décembre 2008],
location: [Paris, France],
description: list(
[Reengineering d'une application chargée de l'attribution de performance de fonds financiers.],
[Leader de la migration (Outsourcing) du système d'information du middle office d'AXA IM au profit de SSC. Migration incluant la réecriture en Java de 40 applications chargées de l'inventaire, de la valorisation et du reporting des produits financiers d'AXA IM.],
),
logo: "ssc.png",
tags: ("MS Access", "Java", "VBA", "Excel", "SQL", "Gestion de projet")
)
$/* ----------------------------- */$
#cvEntry(
title: [Statisticien, Analyste de Donnée],
society: [EDF],
date: [Juin 2006 - Mai 2007],
location: [Noisy-le-Grand, France],
description: list(
[Analyse statistique portant sur l'optimisation des stocks des pièces de rechanges pour les sites de production nucléaire.],
[Fourniture d'indicateurs aux logisticiens pour gérer leur protefeuille de commande.]
),
logo: "edf.png",
tags: ("Excel", "SAS", "SQL", "ERP", "VBA")
)
#v(50pt) |
|
https://github.com/SkiFire13/master-thesis | https://raw.githubusercontent.com/SkiFire13/master-thesis/master/thesis.typ | typst | #import "template.typ": template
#show: template.with(
affiliation: (
university: "University of Padua",
department: [Department of Mathematics "Tullio Levi-Civita"],
degree: "Master Degree in Computer Science",
),
title: [Solving Systems of Fixpoint Equations \ via Strategy Iteration],
subtitle: "Master thesis",
supervisor: "Prof. <NAME>",
candidate: (
name: "<NAME>",
id: 2078263,
),
academic-year: "2023-2024",
keywords: ("fixpoint", "parity games", "strategy iteration"),
lang: "en",
)
#include "chapters/1-introduction.typ"
#include "chapters/2-background.typ"
#include "chapters/3-algorithm.typ"
#include "chapters/4-implementation.typ"
#include "chapters/5-conclusion.typ"
#bibliography("sources.bib", style: "bib-style.csl")
|
|
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/project_documentation/content/meeting_minutes/week_14.typ | typst | = Project Meeting 19.12.2023 08:15 - 08:45 (MS Teams)
== Participants
- Prof. Dr. <NAME>
- <NAME>
- <NAME>
== Agenda
- Clarification of some questions regarding submission:
- Is our current document structure (with separate document for project mgmt) ok: Yes.
- Could Prof. Dr. <NAME> execute the PoC application on his computer: Yes
- Is AVT the only place where we have to submit our files: AVT is for the department, make ZIP file with everything available to advisor
- Set date for Feedback meeting: 16.01.2024 15:00 |
|
https://github.com/loqusion/typix | https://raw.githubusercontent.com/loqusion/typix/main/docs/api/derivations/watch-typst-project.md | markdown | MIT License | # watchTypstProject
Returns a derivation for a script that watches an input file and recompiles on
changes.
## Parameters
**Note:** All parameters for
[`writeShellApplication`][nixpkgs-writeshellapplication] are also supported
(besides `text`).
### `fontPaths` (optional) { #fontpaths }
{{#include common/font-paths.md}}
#### Example { #fontpaths-example }
{{#include common/font-paths-example.md:watchtypstproject_example}}
### `forceVirtualPaths` (optional) { #forcevirtualpaths }
<!-- markdownlint-disable link-fragments -->
If there are any conflicts between [`virtualPaths`](#virtualpaths) and files in your
project directory, they will not be overwritten unless `forceVirtualPaths` is
`true`.
Default is `false`.
<!-- markdownlint-restore -->
### `scriptName` (optional) { #scriptname }
{{#include common/script-name.md}}
Default is `typst-watch`.
### `typstOpts` (optional) { #typstopts }
{{#include common/typst-opts.md:head}}
<!-- markdownlint-disable link-fragments -->
These are in addition to any options you manually pass in
[`typstWatchCommand`](#typstwatchcommand).
<!-- markdownlint-restore -->
{{#include common/typst-opts.md:tail}}
#### Example { #typstopts-example }
{{#include common/typst-opts-example.md:head}}
{{#include common/typst-opts-example.md:typstwatch}}
### `typstOutput` (optional) { #typstoutput }
{{#include common/typst-project-output.md:head}}
{{#include common/typst-project-output.md:watchtypstproject}}
### `typstSource` (optional) { #typstsource }
{{#include common/typst-project-source.md}}
Default is `main.typ`.
### `typstWatchCommand` (optional) { #typstwatchcommand }
Base Typst command to run to watch the project. Other arguments will be appended
based on the other parameters you supply.
Default is `typst watch`.
### `virtualPaths` (optional) { #virtualpaths }
{{#include common/virtual-paths.md}}
<!-- markdownlint-disable link-fragments -->
**NOTE:** Any paths specified here will not overwrite files in your project
directory, unless you set [`forceVirtualPaths`](#forcevirtualpaths) to `true`.
<!-- markdownlint-restore -->
#### Example { #virtualpaths-example }
{{#include common/virtual-paths-example.md:head}}
{{#include common/virtual-paths-example.md:watchtypstproject_example}}
{{#include common/virtual-paths-example.md:tail}}
## Source
- [`watchTypstProject`](https://github.com/loqusion/typix/blob/main/lib/watchTypstProject.nix)
[nixpkgs-writeshellapplication]: https://nixos.org/manual/nixpkgs/stable/#trivial-builder-writeShellApplication
|
https://github.com/freundTech/kit-slides-typst | https://raw.githubusercontent.com/freundTech/kit-slides-typst/main/README.md | markdown | Other | # KIT Slides Theme for Typst
A Karlsruhe Institute of Technology theme for typesetting slides in Typst.
This theme uses [polylux](https://github.com/andreasKroepelin/polylux) for creating slides in Typst.
You can find more information on available functions in the [polylux book](polylux.dev/book).
The simplest way to use this template in the Typst web app is to first add this [read-only shared project](https://typst.app/project/rMlNud7c83Ybf0R2B9BBTt) to your account, then create a copy of it from your dashboard.
## Usage
Clone this repository, then use `presentation.typ` as a starting point for your presentation.
The theme is imported and loaded using
```typst
#import "kit-slides.typ": *
#show: kit-theme.with(
title: [The title of your presentation],
subtitle: [
The subtitle of your presentation \
Can contain two lines
],
author: [Your name],
short-title: [A short title to display at the bottom of all slides. Default to your title],
group-logo: image("Path to the logo of your group"), // Optional
date: [The date of the presentation],
language: "de", // The language of the presentation. Supports "de" and "en".
institute: [Your institute],
)
```
Next insert the title slide using
```typst
#title-slide(banner: image("Path to your banner image"))
```
Now you can add more slides using
```typst
#slide(title: [Your slide title])[
Your slide content
]
```
## Compiling
We recommend using [pixi](https://pixi.sh) as a task and environment manager. You can however also use a regular typst installation.
### Using pixi
```bash
# compile once
pixi run compile
```
```bash
# watch for changes and recompile automatically
pixi run watch
```
Pixi also allows you to easily run different linters.
This template currently ships with `typos` to find typos and `typstyle` to format your typst code.
```bash
# run all linters
pixi run lint
```
### Using a local typst installation
```bash
# compile once
typst compile --font-path fonts/ thesis.typ
```
```bash
# watch for changes and recompile automatically
typst watch --font-path fonts/ thesis.typ
```
Make sure to not forget the `--font-path` argument as typst will otherwise silently use different fonts.
## Fonts
The KIT design guide requires using Arial (Windows) or Helvetica (MacOS) for office documents, including presentations. Because neither of those fonts is usually available on Linux machines this template ships with the free Roboto font to prevent typst from falling back to a serif font. Roboto is also approved by the KIT design guide, though only for web content, not office documents.
If you use this template in an official capacity it is recommended to install a copy of Arial on your system.
## Stability
This theme is still very new. I'll try to keep incompatible changes to a minimum, but can't promise that there won't be any incompatible changes.
## License
The source code of this theme, excluding files in the `kit/` and `fonts/Roboto/` directories, is licensed under the MIT license. See [LICENSE.txt](./LICENCE.txt) for details.
The "Karlsruhe Institute of Technology" logo in both German and English language is a protected word and figurative mark of the Karlsruhe Institute of Technology and must only be used in accordence with their usage policy.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/doc/examples.typ | typst | Apache License 2.0 | #import "example.typ": example
#let alu = example(```
element.alu(x: 0, y: 0, w: 1, h: 2, id: "alu")
wire.stub("alu-port-in1", "west")
wire.stub("alu-port-in2", "west")
wire.stub("alu-port-out", "east")
```)
#let block = example(```
element.block(
x: 0, y: 0, w: 2, h: 2, id: "block",
ports: (
north: ((id: "clk", clock: true),),
west: ((id: "in1", name: "A"),
(id: "in2", name: "B")),
east: ((id: "out", name: "C"),)
)
)
wire.stub("block-port-clk", "north")
wire.stub("block-port-in1", "west")
wire.stub("block-port-in2", "west")
wire.stub("block-port-out", "east")
```)
#let extender = example(```
element.extender(
x: 0, y: 0, w: 3, h: 1,
id: "extender"
)
wire.stub("extender-port-in", "west")
wire.stub("extender-port-out", "east")
```)
#let multiplexer = example(```
element.multiplexer(
x: 0, y: 0, w: 1, h: 3,
id: "multiplexer",
entries: 3
)
wire.stub("multiplexer.north", "north")
wire.stub("multiplexer-port-out", "east")
element.multiplexer(
x: 0, y: -4, w: 1, h: 3,
id: "multiplexer2",
entries: ("A", "B", "C")
)
wire.stub("multiplexer2.south", "south")
wire.stub("multiplexer2-port-out", "east")
for i in range(3) {
wire.stub("multiplexer-port-in" + str(i), "west")
wire.stub("multiplexer2-port-in" + str(i), "west")
}
```)
#let wires = example(```
for i in range(3) {
draw.circle((i * 3, 0), radius: .1, name: "p" + str(i * 2))
draw.circle((i * 3 + 2, 1), radius: .1, name: "p" + str(i * 2 + 1))
draw.content((i * 3 + 1, -1), raw(wire.wire-styles.at(i)))
}
wire.wire("w1", ("p0", "p1"), style: "direct")
wire.wire("w2", ("p2", "p3"), style: "zigzag")
wire.wire("w3", ("p4", "p5"), style: "dodge",
dodge-y: -0.5, dodge-margins: (0.5, 0.5))
```, vertical: true)
#let stub = example(```
draw.circle((0, 0), radius: .1, name: "p")
wire.stub("p", "north", name: "north", length: 1)
wire.stub("p", "east", name: "east", vertical: true)
wire.stub("p", "south", name: "south", length: 15pt)
wire.stub("p", "west", name: "west", length: 3em)
```)
#let gate-and = example(```
gates.gate-and(x: 0, y: 0, w: 1.5, h: 1.5)
gates.gate-and(x: 3, y: 0, w: 1.5, h: 1.5, inverted: "all")
```, vertical: true)
#let gate-nand = example(```
gates.gate-nand(x: 0, y: 0, w: 1.5, h: 1.5)
gates.gate-nand(x: 3, y: 0, w: 1.5, h: 1.5, inverted: "all")
```, vertical: true)
#let gate-buf = example(```
gates.gate-buf(x: 0, y: 0, w: 1.5, h: 1.5)
gates.gate-buf(x: 3, y: 0, w: 1.5, h: 1.5, inverted: "all")
```, vertical: true)
#let gate-not = example(```
gates.gate-not(x: 0, y: 0, w: 1.5, h: 1.5)
gates.gate-not(x: 3, y: 0, w: 1.5, h: 1.5, inverted: "all")
```, vertical: true)
#let gate-or = example(```
gates.gate-or(x: 0, y: 0, w: 1.5, h: 1.5)
gates.gate-or(x: 3, y: 0, w: 1.5, h: 1.5, inverted: "all")
```, vertical: true)
#let gate-nor = example(```
gates.gate-nor(x: 0, y: 0, w: 1.5, h: 1.5)
gates.gate-nor(x: 3, y: 0, w: 1.5, h: 1.5, inverted: "all")
```, vertical: true)
#let gate-xor = example(```
gates.gate-xor(x: 0, y: 0, w: 1.5, h: 1.5)
gates.gate-xor(x: 3, y: 0, w: 1.5, h: 1.5, inverted: "all")
```, vertical: true)
#let gate-xnor = example(```
gates.gate-xnor(x: 0, y: 0, w: 1.5, h: 1.5)
gates.gate-xnor(x: 3, y: 0, w: 1.5, h: 1.5, inverted: "all")
```, vertical: true)
#let group = example(```
element.group(
id: "g1", name: "Group 1", stroke: (dash: "dashed"),
{
element.block(id: "b1", w: 2, h: 2,
x: 0, y: 1.5,
ports: (east: ((id: "out"),)),
fill: util.colors.green
)
element.block(id: "b2", w: 2, h: 1,
x: 0, y: 0,
ports: (east: ((id: "out"),)),
fill: util.colors.orange
)
}
)
element.block(id: "b3", w: 2, h: 3,
x: (rel: 1, to: "g1.east"),
y: (from: "b1-port-out", to: "in1"),
ports: (west: ((id: "in1"), (id: "in2"))),
fill: util.colors.blue
)
wire.wire("w1", ("b1-port-out", "b3-port-in1"))
wire.wire("w2", ("b2-port-out", "b3-port-in2"),
style: "zigzag")
```)
#let intersection = example(```
wire.wire("w1", ((0, 0), (1, 1)), style: "zigzag")
wire.wire("w2", ((0, 0), (1, -.5)),
style: "zigzag", zigzag-ratio: 80%)
wire.intersection("w1.zig")
```) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/nth/0.2.0/nth.typ | typst | Apache License 2.0 | #let nth(ordinal-num) = {
let ordinal-str = str(ordinal-num)
let ordinal-suffix = if ordinal-str.ends-with(regex("1[0-9]")) {
"th"
}
else if ordinal-str.last() == "1" {
"st"
}
else if ordinal-str.last() == "2" {
"nd"
}
else if ordinal-str.last() == "3" {
"rd"
}
else {
"th"
}
ordinal-str + super(ordinal-suffix)
}
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/3d-cetz-attempt-3.typ | typst | // the file works ... but
// there are overlaps and these overlaps need to be removed
#import "@local/typkit:0.1.0": *
#import "@preview/cetz:0.2.2"
#import cetz.draw: *
// length: 1, width: 1, height: 1,
#let get-prism-segments(pos, dimensions: (1, 1, 1), styles: (:)) = {
let (x, y, z)=pos
let (length, width, height) = dimensions
let vertices = (
(x, y, z),
(x + length, y, z),
(x + length, y + width, z),
(x, y + width, z),
(x, y, z + height),
(x + length, y, z + height),
(x + length, y + width, z + height),
(x, y + width, z + height)
)
let faces = (
((0, 1, 2, 3), "front"),
((4, 5, 6, 7), "back"),
((0, 4, 7, 3), "left"),
((1, 5, 6, 2), "right"),
((0, 1, 5, 4), "bottom"),
((3, 2, 6, 7), "top")
)
return faces.map(face => {
let (indices, name) = face
let style = styles.at(name, default: (:))
let segments = indices.map(i => vertices.at(i))
return (segments, style)
})
}
#{
cetz.canvas({
let start = (0, 0, 0)
let attrs = (
dimensions: (1, 1, 1),
styles: (
front: (
fill: blue,
stroke: strokes.soft,
),
top: (
fill: green,
stroke: strokes.soft,
),
)
)
let lines = get-prism-segments(start, ..attrs)
for (vertices, style) in lines {
line(..vertices, close: true, ..style)
}
})
}
|
|
https://github.com/agarmu/typst-templates | https://raw.githubusercontent.com/agarmu/typst-templates/main/notes/symbols.typ | typst | MIT License | #let inv(x) = $#x^(-1)$
#let ll = $lambda$
#let span = $op("Span")$
#let arccot = $op("arccot")$
#let rank = $op("rank")$
#let null = $op("null")$
#let adj = $op("adj")$
#let col = $op("Col")$
#let row = $op("Row")$
#let inv(x) = $#x^(-1)$
#let comp = $" " circle.stroked.small " "$
#let qed = $square.stroked.small$
#let bg(x) = $lr((#x), size: #150%)$
#let pt(u) = $cal(P)_(#u)$
#let co(u) = $cal(C)_(#u)$
|
https://github.com/noahjutz/AD | https://raw.githubusercontent.com/noahjutz/AD/main/notizen/sortieralgorithmen/main.typ | typst | #import "/components/admonition.typ": admonition
#import "/config.typ": theme
= Sortieralgorithmen
== Insertion Sort <insertion-sort>
Der Algorithmus iteriert durch alle Elemente ab dem zweiten (rot markiert) und schiebt den Wert so lange nach vorne, bis keine kleineren Werte mehr vor ihm stehen.
```python
for j in range(1, n):
# a[j] nach vorne schieben
```
Zum Schluss von jeder Iteration ist die Liste bis zur jeweiligen Stelle sortiert (grün markiert).
Das "nach vorne schieben" erfolgt in drei Schritten:
1. Merke dir den Wert des Schlüssels (graue Spalte).
```python
key = a[j]
```
2. Iteriere von rechts nach links durch alle Elemente links des Schlüssels (blau markiert) und kopiere das Element jeweils um eine Position nach hinten, wenn es größer ist als das nächste.
```python
i = j-1
while (i >= 0 and a[i] > key):
a[i+1] = a[i]
i -= 1
```
3. Setze den Wert des Schlüssels ganz nach vorne.
```python
a[i+1] = key
```
=== Beispiel
Im folgenden Beispiel ist Insertion Sort für die Eingabeliste $(3, 2, 1)$ illustriert. Der Zähler (rot markiert) startet bei $i=1$ und endet bei $i=n-1=2$.
#import "insertion_sort/insertion_sort.typ": insertion_sort
#insertion_sort(3, 2, 1)
Längeres Beispiel: @ex-insertion-sort
=== Laufzeit
Für jedes Element `a[j]` werden zwischen $0$ und $j$ Verschiebeoperationen durchgeführt, um `a[j]` richtig in `a[:j+1]` einzusortieren.
#grid(columns: (1fr,)*2,
$
T^"WC" (n) = Theta(n^2) #h(16pt)
$,$
T^"BC" (n) = Theta(n)
$
)
Im Schnitt benötigt es $j slash 2$ Verschiebeoperationen, damit ist die AC-Laufzeit
$
T^"AC" (n) = sum_(j=1)^(n-1) j/2 = Theta(n^2)
$
=== Korrektheit
Behauptung: Nach jeden $j$-ten Schleifendurchlauf ist `a[:j+1]` sortiert.
==== Induktionsanfang (j = 1)
Ein Durchlauf der Schleife mit Zähler $j$ sieht so aus:
```python
key = a[j]
i = j-1
while i >= 0 and a[i] > key:
a[i+1] = a[i]
i -= 1
a[i+1] = key
```
Setzen wir den festen Wert $j=1$ in den Code ein, dann wird die while-Schleife höchstens einmal betreten. Vereinfacht kann man das als if-else-Block darstellen:
```python
key = a[1]
if a[0] > a[1]:
a[1] = a[0]
a[0] = key
else:
a[1] = key
```
Dieser Code vertauscht `a[0]` und `a[1]`, wenn `a[0]` größer ist. Das heißt, dass `a[0:2]` sortiert sind. #sym.checkmark
#include "insertion_sort/induction_0.typ"
==== Induktionsschritt (j - 1 #sym.arrow j)
Wir gehen davon aus, dass `a[:j]` nach Iteration $j-1$ sortiert ist.
#include "insertion_sort/induction_1.typ"
Wenn wir zeigen können, dass nach der nächsten Iteration $j$ das Subarray `a[:j+1]` sortiert ist, ist der Induktionsschritt erfüllt.
#admonition(
[Verschachtelte Induktion]
)[
Die innere Schleife startet mit $i=j-1$ und läuft ggf. nach unten bis $i=0$. Behauptung: Nach jedem $i$-ten Schleifendurchlauf gilt sind die Elemente in `a[i+1:j+1]` an der richtigen Stelle.
==== Induktionsanfang (i = j - 1)
Im ersten Durchlauf mit $i = j - 1$ werden folgende Anweisungen ausgeführt:
```python
if a[j-1] > a[j]:
a[j] = a[j-1]
```
Weil wir annehmen, dass `a[:j]` sortiert ist, ist `a[j-1]` der größte Wert in `a[:j]`. Nach der Ausführung des obigen Codes ist `a[j]` der größte Wert aus `a[:j+1]`. Damit ist `a[j:j+1]` sortiert. `a[:j-1]` bleibt unberührt. #sym.checkmark
#include "insertion_sort/induction_2.typ"
==== Induktionsschritt (i + 1 #sym.arrow i)
Nach Induktionsvoraussetzung gilt nach dem Durchlauf mit $i+1$:
`a[i+2:j+1]` ist korrekt
Wenn wir zeigen können, dass nach dem Durchlauf mit $i$ gilt:
`a[i+1:j+1]` ist korrekt
Dann ist der Induktionsschritt erfüllt.
Falls $i+1=0$ wird die while-Schleife verlassen, bevor sie für $i$ ausgeführt werden kann. Wir beweisen also für dieses $i$ nichts. #sym.checkmark
Falls `a[i]` $<=$ `key` wird die while-Schleife auch verlassen. #sym.checkmark
Sonst wird `a[i]` an den Anfang der rechten sortierten Teilliste `a[i+1:j+1]` gesetzt.
#include "insertion_sort/induction_3.typ"
Dort gehört dieser Wert auch hin, weil er durch die äußere IV (`a[:j]` ist sortiert) der größte noch nicht einsortierte Wert ist.
`a[:i]` $<=$ `a[i]` $<=$ `a[i+1:j+1]` #sym.checkmark
]
Nach dieser inneren Schleifeninvariante sind `a[:i]` und `a[i+1:j+1`] nach Beendigung der While-Schleife mit irgend einem $i$ sortiert. Ferner gilt folgendes:
`a[i-1]` $<=$ `key` $<=$ `a[i+1]`
Nachdem also der Schlüssel an Stelle `a[i]` setzt, ist `a[:j+1]` sortiert. #sym.square.filled
== Bubble Sort <bubble-sort>
In jedem Schleifendurchlauf wird die rechte Teilliste `a[i:]` betrachtet. Von rechts nach links werden die Elemente `a[j]` und `a[j+1]` paarweise vertauscht, um den minimalen Wert nach vorne zu bringen.
```python
for i in range(n):
for j in reversed(range(i, n-1)):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
```
Nach jedem Schleifendurchlauf ist die linke Teilliste bis zum Schlüssel sortiert (grün markiert).
=== Beispiel
Im Beispiel wird $(4, 3, 2, 1)$ sortiert. Der Zähler (rot markiert) wandert von $i=0$ nach $i=n-2=2$.
#import "bubble_sort.typ": bubble_sort
#bubble_sort(4, 3, 2, 1)
Längeres Beispiel: @ex-bubble-sort
=== Laufzeit
Es gibt zwei verschachtelte for-Schleifen in Abhängigkeit von $n$.
$
T^"WC" (n) = T^"BC" (n) = T^"AC" (n) = n^2
$
=== Korrektheit
Nach jedem $i$-ten Schleifendurchlauf ist `a[:i+2]` sortiert.
==== Induktionsanfang (i = 0)
#admonition("Verschachtelte Induktion")[
Nach jedem $j$-ten Schleifendurchlauf ist `min(a)` in `a[:j+1]` und `a[j]` $<=$ `a[j+1]`
==== Induktionsanfang (j = n - 2)
Die letzten beiden Elemente `a[n-1]` und `a[n-2]` werden ggf. vertauscht, um sie in die richtige Reihenfolge zu bringen. #sym.checkmark
==== Induktionsschritt (j + 1 #sym.arrow j)
Nach IV ist `min(a)` in `a[:j+2]`. Es werden `a[j]` und `a[j+1]` wieder ggf. vertauscht, um sie in die richtige Reihenfolge zu bringen. #sym.checkmark
]
==== Induktionsschritt (i - 1 #sym.arrow i)
#admonition("Verschachtelte Induktion")[
Nach jedem $j$-ten Schleifendurchlauf ist `min(a[i:])` in `a[i:j+1]`.
==== Induktionsanfang (j = n - 2)
Siehe obige verschachtelte Induktion. #sym.checkmark
==== Induktionsschritt (j + 1 #sym.arrow j)
Siehe obige verschachtelte Induktion. #sym.checkmark
]
==== Induktionsschluss
Nach dem $n-1$-ten Schleifendurchlauf ist `a[:n+1]` sortiert. #sym.square.filled
== Selection Sort <selection-sort>
In jedem Schleifendurchlauf ermitteln wir das Minimum in `a[i:]` und vertauschen es mit `a[i]`.
```python
for i in range(n):
x = a.index(min(a[i:]))
a[i], a[x] = a[x], a[i]
```
=== Beispiel
Im Beispiel ist der Zähler rot markiert und das rechte Minimum blau.
#import "selection_sort.typ": selection_sort
#selection_sort(4, 3, 2, 1)
Längeres Beispiel: @ex-selection-sort
=== Laufzeit
$
T^"WC" (n) = T^"BC" (n) = T^"AC" (n) = n^2
$
=== Korrektheit
Nach jedem $i$-ten Schleifendurchlauf ist `a[:i+1]` sortiert.
==== Induktionsanfang (i = 0)
`a[0]` und `min(a)` werden vertauscht. (Verschachtelte Induktion für die Berechnung des Minimums wird weggelassen) #sym.checkmark
==== Induktionsschritt (i - 1 #sym.arrow i)
`a[i]` und `min(a[i:])` werden vertauscht. `a[:i]` ist nach IV bereits sortiert. #sym.checkmark
==== Induktionsschluss
Nach dem $n$-ten Schleifendurchlauf ist die gesamte Liste `a[:n+1]` sortiert. #sym.square.filled
== Quicksort
Um eine Liste `a[f:l+1]` zu sortieren, wird in jedem Rekursionsschritt wird ein beliebiges sogenanntes Pivot-Element ausgewählt. In unserer Implementation wählen wir
```
pivot = a[f]
```
Die Partitionsfunktion sortiert das Pivotelement ein. Die Sublisten links und rechts des Pivots werden anschließend rekursiv sortiert.
=== Partition
Die Partitionsfunktion vertauscht die Liste so, dass alle kleineren Elemente vor dem Pivot und alle größeren hinter ihm stehen.
#include "quicksort/partition.typ"
Um von (a) auf (b) zu kommen, jede Zahl in `a[f+1:]` nach vorne vertauscht, falls sie kleiner als das Pivot ist.
```python
j = f+1
for i in range(f+1, l+1):
if a[i] <= key:
a[i], a[j] = a[j], a[i]
j += 1
```
Jetzt ist `a[1:j]` kleiner, und `a[j:n+1]` größer als das Pivot. Wenn wir also das Pivot bei `a[f]` mit `a[j-1]` vertauschen, ist es an der richtigen Stelle (c).
```python
a[f], a[j-1] = a[j-1], a[f]
```
=== Rekursion
Quicksort wird einmal für die Elemente links des Pivots und einmal für die rechts des Pivots aufgerufen. Falls es links oder rechts ein oder kein Element gibt, ist keine Aktion mehr erforderlich (base case).
```python
def quicksort(a, f, l):
if f >= l:
return # base case
m = partition(a, f, l)
quicksort(a, f, m-1)
quicksort(a, m+1, l)
```
#include "quicksort/recursion_tree.typ"
=== Laufzeit
Die Partition läuft die Eingabe einmal durch, hat also eine lineare Laufzeit $Theta(n)$.
==== Worst Case
Wenn die Eingabe aufsteigend oder absteigend sortiert ist, wird das Problem in jedem Rekursionsschritt um nur 1 kleiner.
#import "quicksort/quicksort.typ": quicksort
#quicksort(1, 2, 3, 4)
Ist sie aufsteigend sortiert, so wird nur der zweite rekursive Aufruf mit einer Eingabelänge von $n-1$ aufgerufen.
$
T(n) = cases(
Theta(1) "falls" n <= 1,
T(n-1) + Theta(n) "sonst"
)
$
Die Rekursionsgleichung ist in $Theta(n^2)$.
==== Best Case
Der Best-Case tritt auf, wenn das Pivot-Element in jedem Schritt die Eingabe halbiert.
#quicksort(4, 1, 3, 2, 6, 5, 7)
In diesem Fall wird das Problem in jedem Schritt halbiert.
$
T(n) = cases(
Theta(1) "falls" n <= 1,
2T(n/2) + Theta(n) "sonst"
)
$
Die Lösung dieser Rekursionsgleichung ist $Theta(n log n)$.
==== Average Case
Die Laufzeit hängt davon ab, an welcher Stelle $m$ das Pivotelement landet. Ist immer $m=f$ oder $m=l$, haben wir den Worst Case. Ist immer $m=floor((f+l) slash 2)$, haben wir den Best Case.
Im allgemeinen gilt für beliebige $m in {f,...,l}$:
$
T_m (n) =
underbrace(T(m-f), "links") +
underbrace(T(l-m), "rechts") +
underbrace(Theta(n), "partition")
$
Weil wir wissen, dass $l-f+1=n$, gilt für $i in {1,...,n}$:
$
T_i (n) = T(i-1) + T(n-i) + Theta(n)
$
== Merge Sort
Genauso wie Quicksort spaltet Merge Sort die Eingabe in jedem Rekursionsschritt in zwei Sublisten.
=== Merge
Die Merge-Prozedur nimmt als Eingabe zwei sortierte Listen `a1[f:m]` und `a2[m:l+1]`.
#include "mergesort/merge_input.typ"
Die beiden Listen werden gemischt, um eine sortierte Liste `anew[f:l+1]` zu produzieren.
#include "mergesort/merge_output.typ"
Um in Linearzeit zu mischen, nutzt quicksort, dass das Minimum zwei sortierter Listen `a1` und `a2` entweder `a1[0]` oder `a2[0]` sein muss.
#include "mergesort/merge_algorithm_0.typ"
Streichen wir den kleineren Wert, so bleiben zwei sortierte Listen übrig, für die wiederum das gleiche gilt.
#include "mergesort/merge_algorithm_1.typ"
In Code kann das folgendermaßen implementiert werden:
```python
if a[a1f] <= a[a2f]:
anew[i] = a[a1f]
a1f += 1
else:
anew[i] = a[a2f]
a2f += 1
```
Sobald die eine der beiden Listen durchgearbeitet wurde, wird der Rest der anderen Liste angehängt.
#include "mergesort/merge_algorithm_2.typ"
=== Rekursion
Die Eingabe wird rekursiv in 2 Teile gespalten, bis die Eingabe nur noch ein Element hat (base case). Die zwei Teile werden dann gemischt.
#import "mergesort/recursion.typ": mergesort_recursion
#align(
center,
mergesort_recursion((34, 45, 12, 34))
)
=== In Place
Um die Merge-Funktion ohne die hilfsliste `anew` zu implementieren, kann man Einträge der rechten Hälfte nach vorne verschieben, wenn sie kleiner sind. Weil in jedem Schritt entweder `a[a2f]` nach vorne gezogen wird oder `a[a1f]` stehen bleibt, wird `a1f` jedes mal inkrementiert, und `a2f` nur, wenn der Wert nach vorne gezogen wird.
#include "mergesort/merge_inplace.typ"
```python
while a1f < a2f and a2f < l+1:
if a[a2f] < a[a1f]:
a.insert(a1f, a.pop(a2f))
a2f += 1
a1f += 1
```
== Heap Sort
=== Linksvoller Baum
Ein Baum ist linksvoll, wenn alle Schichten bis auf die letzte voll besetzt sind, und die letzte von links nach rechts besetzt ist.
#grid(
columns: 2,
column-gutter: 12pt,
align: horizon,
include "heapsort/linksvoll.typ",
{
table(
columns: (1fr,)*6,
..range(6).map(i => {
box(baseline: -3pt)[$a_#i$]
})
)
table(
columns: (auto, 1fr),
align: horizon,
table.cell(
fill: theme.primary_light,
"Linker NF"
), $ 2i+1 $,
table.cell(
fill: theme.secondary_light,
"Rechter NF"
), $ 2i+2 $,
table.cell(
fill: theme.tertiary_light,
"Vorgänger"
), $ floor((i-1)/2) $
)
}
)
=== Heap
Ein Heap ist ein linksvoller Binärbaum, der für alle Knoten die Heap-Eigenschaft erfüllt:
#grid(
columns: 2,
column-gutter: 8pt,
row-gutter: 8pt,
"Minheap:",
[Vorgänger $<=$ Nachfolger],
"Maxheap:",
[Vorgänger $>=$ Nachfolger],
)
=== Heapify
Bevor wir ein beliebiges Array in einen Heap umwandeln, lösen wir ein einfacheres Problem: Ein Knoten $a_i$, dessen linker und rechter Teilbaum bereits Heaps sind, soll an die richtige Stelle vertauscht werden. Im folgenden implementieren wir Heapify für einen Maxheap. Betrachten wir als Beispiel
#align(
center,
include "heapsort/heapify.typ"
)
Zunächst vergleichen wir den Knoten mit seinen unmittelbaren Nachfolgern. Der maximale Wert muss nach oben, um die Heap-Eigenschaft zu erfüllen.
#align(
center,
grid(
columns: 3,
align: horizon,
column-gutter: 8pt,
include "heapsort/heapify_step_0.typ",
sym.arrow,
include "heapsort/heapify_step_1.typ"
)
)
Durch den Tausch könnte die Heap-Eigenschaft jetzt im linken Teilbaum verletzt sein, also rufen wir Heapify rekursiv auf.
#align(
center,
grid(
columns: 3,
align: horizon,
column-gutter: 8pt,
include "heapsort/heapify_step_2.typ",
sym.arrow,
include "heapsort/heapify_step_3.typ"
)
)
Die Rekursion ist dann beendet, wenn der Knoten größer als seine Nachfolger ist (oder keine Nachfolger hat), weil dann die Heap-Eigenschaft erfüllt ist.
Heapify hat eine Laufzeit von $O(log n)$, weil die Wurzel im schlimmsten Fall nach ganz unten wandern muss.
=== BuildHeap
Wie bringen wir einen beliebigen linksvollen Baum in Max-Heap-Form? Alle Blätter sind bereits korrekte Heaps, weil sie keine Nachfolger haben. Beispiel:
#align(
center,
include "heapsort/buildheap_step_0.typ"
)
Wenn wir von ganz unten bis zur Wurzel für alle nicht-Blätter Heapify aufrufen, dann wird der gesamte Baum schrittweise zu einem Heap. Die nicht-Blätter sind in `a[:n//2]`, weil der Vorgänger des letzten Blattes an Stelle $n-1$ ist:
$
floor((n-1-1)/2) = floor(n/2)-1
$
Wir iterieren von rechts nach links durch `a[:n//2]` und rufen für jeden Knoten Heapify auf.
#align(
center,
include "heapsort/buildheap_step_1.typ"
)
Da wir für $n slash 2$ Knoten Heapify aufrufen, ist die Laufzeit von BuildHeap durch $O(n log n)$ nach oben beschränkt. Tatsächlich ist BuildHeap noch schneller, weil die meisten Knoten, für die Heapify aufgerufen wird, weit unten sind.
$
T^"WC" (n) = sum_(h=0)^floor(log n)
underbrace(ceil(n slash 2^(h+1)), "Anz. Knoten\nauf Höhe h")
dot underbrace(O(h), "Heapify")
= O(n)
$
=== HeapSort
HeapSort nutzt die Eigenschaft des Max-Heaps, dass der größte Wert in der Wurzel `a[f]` steht.
Zuerst bauen wir einen Heap in $O(n)$ Zeit auf. Dann vertauschen wir `a[0]` und `a[n-1]`, was dazu führt, dass der größte Wert an der letzten Stelle steht. Im nächsten Schritt vernachlässigen wir `a[n-1]` und wiederholen das gleiche für die Subliste `a[:n-1]`. Um diese zu einem Heap zu machen, müssen wir nur Heapify aufrufen.
```python
build_heap(a)
for i in range(n-1, 1, -1):
a[0], a[n-1] = a[n-1], a[0]
heapify(n=n-1, root=i)
``` |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-01.typ | typst | Other | #test(calc.round(calc.e, digits: 2), 2.72)
#test(calc.round(calc.pi, digits: 2), 3.14)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/crates/conversion/vec2canvas/README.md | markdown | Apache License 2.0 | # reflexo-vec2canvas
Render vector items into canvas element, i.e. converting vector items into canvas items.
See [Typst.ts](https://github.com/Myriad-Dreamin/typst.ts)
|
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Code/angular.json.typ | typst | ```json
"configurations": {
"production": {
"fileReplacements": [{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}]
}
}
``` |
|
https://github.com/Champitoad/typst-slides | https://raw.githubusercontent.com/Champitoad/typst-slides/main/flower.typ | typst | Creative Commons Zero v1.0 Universal | #import "utils.typ": *
#let pistil_color = rgb("FFF344")
#let sheet(content) = rect(fill: pistil_color, inset: 5pt, content)
// Evaluate the bezier polynomial at t
#let beval(p1, c1, c2, p2, t) = {
t * t * t * p1 + 3 * (1 - t) * t * t * c1 + 3 * (1 - t) * (1 - t) * t * c2 + (1 - t) * (1 - t) * (1 - t) * p2
}
#let bbeval(p1, c1, c2, p2) = {
let a = 3 * p1 - 9 * c1 + 9 * c2 - 3 * p2
let b = 6 * c1 - 12 * c2 + 6 * p2
let c = 3 * c2 - 3 * p2
let local_candidates = if calc.abs(a) < 1e-9 {
if calc.abs(b) < 1e-9 {
()
} else {
(-c / b,)
}
} else {
let delta = b * b - 4 * a * c
let c1 = (-b - calc.sqrt(delta)) / (2 * a)
let c2 = (-b + calc.sqrt(delta)) / (2 * a)
(c1, c2)
}
let local = local_candidates.filter(x => 0 <= x and x <= 1)
let candidates = (0, 1) + local
let values = candidates.map(x => beval(p1, c1, c2, p2, x))
(min: calc.min(..values), max: calc.max(..values))
}
#let cubic_bounding(p1, c1, c2, p2) = {
let bounding_x = bbeval(p1.x.cm(), c1.x.cm(), c2.x.cm(), p2.x.cm())
let bounding_y = bbeval(p1.y.cm(), c1.y.cm(), c2.y.cm(), p2.y.cm())
(min: (x: cm(bounding_x.min), y: cm(bounding_y.min)),
max: (x: cm(bounding_x.max), y: cm(bounding_y.max)))
}
#let bounding_union(b1, b2) = {
(min: (x: calc.min(b1.min.x, b2.min.x), y: calc.min(b1.min.y, b2.min.y)),
max: (x: calc.max(b1.max.x, b2.max.x), y: calc.max(b1.max.y, b2.max.x)))
}
#let control_size(radius, a1, a2, l) = {
let x = calc.cos(a1) + calc.cos(a2)
let y = calc.sin(a1) + calc.sin(a2)
let norm = calc.sqrt(x * x + y * y)
let d = 8 * l / norm - 4 * radius
d / 3
}
#let one(f, stroke: black, text_size: 20pt) = {
let pistil = f.pistil
let flower = (
angle: mget(f, "angle", 0rad) + 180deg,
petal_size: mget(f, "petal_size", mget(pistil, "size", 1cm) * 3),
petal_color: mget(f, "petal_color", white.transparentize(100%)),
pistil: (
color: mget(pistil, "color", pistil_color),
content: mget(pistil, "content", block(width: 0cm, height: 0cm)),
size: mget(pistil, "size", 1cm)
),
petals: mget(f, "petals", ((:), (:), (:)))
)
if flower.petals.len() < 3 {
panic("Expected at least 3 petals, got " + str(flower.petals.len()))
}
let step = 2 * rad(calc.pi) / flower.petals.len()
let start = flower.angle + (rad(calc.pi) - step) / 2
let radius = flower.pistil.size
let petals_rendered = range(flower.petals.len()).map(i => {
let petal = flower.petals.at(i)
if petal.keys().contains("name") {
let a1 = start + i * step
let a2 = start + (i + 1) * step
let size = control_size(radius, a1, a2, flower.petal_size)
let p1 = (x: calc.cos(a1) * radius, y: calc.sin(a1) * radius)
let c1 = (x: p1.x + calc.cos(a1) * size, y: p1.y + calc.sin(a1) * size)
let p2 = (x: calc.cos(a2) * radius, y: calc.sin(a2) * radius)
let c2 = (x: p2.x + calc.cos(a2) * size, y: p2.y + calc.sin(a2) * size)
let top = (
x: beval(p1.x, c1.x, c2.x, p2.x, 0.5),
y: beval(p1.y, c1.y, c2.y, p2.y, 0.5),
)
let border = (
x: radius * calc.cos((a1 + a2) / 2),
y: radius * calc.sin((a1 + a2) / 2),
)
let shift = mget(petal, "shift", 1)
let center = (
x: border.x + shift * (top.x - border.x) * 0.5,
y: -(border.y + shift * (top.y - border.y) * 0.5),
)
let fill = mget(petal, "color", mget(f, "petal_color", none))
let color = mget(petal, "color", none)
let curve = path(stroke: stroke, fill: color,
((p1.x, p1.y), (p1.x - c1.x, p1.y - c1.y)),
((p2.x, p2.y), (c2.x - p2.x, c2.y - p2.y))
)
let bb = cubic_bounding(p1, c1, c2, p2)
(
curve: curve,
bounding: bb,
top: top,
center: center,
fill: fill,
name: petal.name,
content: mget(petal, "content", none)
)
} else {
(:)
}
}).filter(x => x.keys().contains("curve"))
let circle_bb = (min: (x: -flower.pistil.size, y: -flower.pistil.size),
max: (x: flower.pistil.size, y: flower.pistil.size))
let bounding = petals_rendered.fold(circle_bb, (acc, v) => bounding_union(acc, v.bounding))
let width = bounding.max.x - bounding.min.x
let height = bounding.max.y - bounding.min.y
let to_shift = (x: width/2, y: -height/2)
let content = box(width: width, height: height)[
#set text(size: text_size)
#for petal in petals_rendered {
place(dx: to_shift.x, dy: -to_shift.y, petal.curve)
context {
let content = petal.content
let content_size = measure(content)
let to_center = (x: -content_size.width / 2, y: content_size.height / 2)
let to_shift = shift(petal.center, shift(to_shift, to_center))
place(dx: to_shift.x, dy: -to_shift.y, content)
}
}
#let center = -flower.pistil.size
#place(dx: center + to_shift.x, dy: center + -to_shift.y, circle(
radius: flower.pistil.size,
fill: flower.pistil.color,
stroke: stroke,
))
#context {
let content_size = measure(flower.pistil.content)
let to_center = (x: -content_size.width / 2, y: content_size.height / 2)
let to_shift = shift(to_shift, to_center)
place(dx: to_shift.x, dy: -to_shift.y, flower.pistil.content)
}
]
let petals_coords = (:)
for petal in petals_rendered {
petals_coords.insert(petal.name,
(top: shift(petal.top, to_shift), center: shift(petal.center, to_shift)))
}
(content: content, center: to_shift, petals: petals_coords)
}
#let empty(n, pistil: (size: 1cm, color: pistil_color), petal_size: 3cm) = {
let petals = ()
for i in range(n) {
petals.push((name: "p" + str(i)))
}
one((
pistil: pistil,
petals: petals
))
}
#let f = one((
pistil: (color: yellow),
petal_size: 3cm,
petals: ((name: "p1"), (name: "p2"), (name: "p3"))
))
#f.content
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/代数学二/作业/hw10.typ | typst | #import "../../template.typ": *
#import "@preview/commute:0.2.0": node, arr, commutative-diagram
#show: note.with(
title: "作业9",
author: "YHTQ",
date: none,
logo: none,
withOutlined : false,
withTitle :false,
withHeadingNumbering: false
)
(应交时间为5月14日)
#let sect1(n) = $sect_(#n = 1)^infinity$
= p114
== 1
- 首先,注意到 $p A = 0$,因此由逆向极限定义的完备化当然有 $hat(A) = A$
- 其次,设 $B = directSum_(n >= 1) ZZ quo p^n ZZ$,则有:
$
(p^k) B = directSum_(n >= k + 1) ZZ quo p^n ZZ\
alpha(A) = directSum_(n >= 1) p^(n-1) ZZ quo p^n\
(p^k) B sect alpha(A) = directSum_(n >= k + 1) p^(n-1) ZZ quo p^n ZZ\
Inv(alpha)((p^k) B sect alpha(A)) = directSum_(n >= k + 1) ZZ quo p ZZ\
A quo Inv(alpha)((p^k) B sect alpha(A)) = directSum_(n <= k) ZZ quo p ZZ\
inverseLimit A quo Inv(alpha)((p^k) B sect alpha(A)) = product ZZ quo p ZZ\
$
- 最后,有正合列:
$
A ->^alpha B -> B quo alpha(A) -> 0
$
取 $p-$adic 完备化,习题证明了若 $A, B quo alpha(A)$ 都取 $B$ 的诱导拓扑,则仍然正合。然而此时 $B quo alpha(A)$ 的完备化确实来自于诱导拓扑,但 $A$ 的完备化与诱导拓扑的完备化不同,故完备化后的结果不可能正合。
== 2
前面计算的结果给出:
$
A_n = directSum_(k >= n + 1) ZZ quo p ZZ\
A quo A_n = directSum_(k <= n) ZZ quo p ZZ\
$
取逆向极限后变成:
$
0 -> 0 -> directSum_n ZZ quo p ZZ -> product_n ZZ quo p ZZ -> 0
$
然而 $directSum_n ZZ quo p ZZ -> product_n ZZ quo p ZZ$ 当然不是满射,故不正合,并有:
$
inverseLimit^1 A_n = (product_n ZZ quo p ZZ) quo (directSum_n ZZ quo p ZZ)
$
== 3
注意到:
$
sect1(n) alpha^n M = {x in M | exists y in I, (1 - y) x = 0 <=> x = y x}
$
而由前面的习题,$exists y, x = y x <=> A x = alpha x M$ 当且仅当对于每个极大理想 $m supset alpha$ 都有 $(A x)_m = 0 => x_m = 0$,进而结论正确
注意到 $hat(M) = 0$ 当且仅当 $sect1(n) alpha^n M = M$,也即:
$
forall m supset alpha, M_m = 0
$
这里任意极大理想当然可以换成任意素理想(只需在 $A quo alpha$ 上考虑,上式等价于 $M quo alpha M = 0$),继而就是结论
== 4
考虑正合列:
$
0 -> A ->^x (x)
$
取 $p-$adic完备化得正合列:
$
0 -> hat(A) ->^(hat(x)) (hat(x))
$
(这里的模当然都是有限生成的)\
表明 $hat(x)$ 不是零因子
第二个推导是不正确的,既然 $hat(A)$ 中还可能有其它元素。例如容易证明 $y^2 - x$ 是 $k[x, y]$ 中不可约多项式,$y^2 - x$ 是素理想,$k[x, y] quo (y^2 - x)$ 是诺特整环。再取 $I = (x - 1)$ 做完备化,泰勒公式给出 $sqrt(1 + (x- 1)) = sqrt(x)$ 存在,进而:
$
(y + sqrt(x))(y - sqrt(x)) = 0
$
注意到由构造 $sqrt(x)$ 是 $x - 1$ 的形式幂级数,不可能 $= plus.minus y$,故上式给出零因子
== 5
注意到:
$
(M^a)^b = (M tensorProduct A^a) tensorProduct A^b
$
因此只需证明 $A^a tensorProduct A^b = A^(a + b)$ 即可
#lemmaLinear[][
任取理想 $a$,有限生成模 $M$ 有:
$
inverseLimit (A quo a^m tensorProduct M) tilde.eq (inverseLimit A quo a^m) tensorProduct M
$
]
#proof[
根据熟知的定理,等价于证明:
$
inverseLimit (M quo a^m M) = M^a
$
这就是完备化的定义
]
注意到:
$
A^a tensorProduct A^b = (inverseLimit_m A quo a^m) tensorProduct (inverseLimit_n A quo b^n) = inverseLimit_(m, n) (A quo a^m tensorProduct A quo b^n) \
= inverseLimit_(m, n) A quo (a ^m + b^n)\
= inverseLimit_(n) A quo (a ^n + b^n)
$
再结合 $(a + b)^(2 n) subset a^n + b^n subset (a + b)^n$ 知上面的极限就是 $A^(a + b)$,证毕。
== 6
由定义,在 $alpha$ 拓扑下极大理想 $m$ 是闭集当且仅当 $m$ 包含 $alpha$,因此结论显然
== 7
$
hat(A) "忠实平坦" &<=> forall "有限生成模"M, M -> hat(M) "是单射" \
&<=> forall "有限生成模"M, sect a^n M = 0\
&<= alpha subset "Jacobson 根" \
&"(这是 Krull's 的推论)"\
$
此时,环当然是 Zariski 环
== 8
(容易验证本题中的 $A, B, C$ 都是整环)\
注意到若有收敛的 $n$ 元幂级数 $f$,只要 $f(0) != 0$ 一定有 $f$ 在 $0$ 的某个邻域内可逆,且其逆仍是幂级数,进而 $f$ 是 $B$ 中单位。同时,$f(0) = 0 <=> f in (z_1, z_2, ..., z_n)$,因此后者就是唯一的极大理想。
注意到 $CC[z_1, z_2, ..., z_n]$ 关于 $(z_1, z_2, ..., z_n)$ 的完备化是 $C$,而 $CC[z_1, z_2, ..., z_n] subset A subset B subset C$,因此 $A, B$ 关于对应极大理想的完备化应当也是 $C$
进一步,若 $B$ 诺特,$A$ 当然也诺特,由之前的习题及 $A, B$ 是局部环知 $C$ 在 $A, B$ 上忠实平坦,由第三章习题 $B$ 将在 $A$ 上平坦
== 9
递归构造 $g_k (x), h_k (x)$ 使得 $g_k h_k - f in m^k A[x]$ 且 $g_k, h_k$ 在 $A quo m^k [x]$ 中互素
- $k = 1$ 时取 $g_1, h_1$ 是 $overline(g), overline(h)$ 的任意一个原像即可
-
假设 $k$ 时已经构造完成,设:
$
g_k h_k - f = sum_(i=0)^n c_i x^i
$
其中 $c^i in m^k$\
由互素性,可设:
$
x^i + r_i (x) = a_i (x) h_k (x) + b_i (x) g_k (x)
$
其中 $deg a_i, b_i <= n-r, r$ 并且 $r_i (x) in m^(k) [x]$
不难发现将有:
$
c_n x^n = c_n a_n (x) h_k (x) + c_n b_i (x) g_k (x) - c_n r_n (x)\
sum_(i=0)^(n-1) c_i x^i = g_k (x) h_k (x) - f(x) - (c_n a_n (x) h_k (x) + c_n b_i (x) g_k (x) - c_n r_n (x))\
= (g_k (x) - c_n a_n (x))(h_k (x) - c_n b_n (x)) - f(x) + c_n r_n (x) - c_n^2 a_n (x) b_n (x)
$
其中 $c_n r_n (x) - c_n^2 a_n (x) b_n (x) in m^(k+1) [x]$,反复进行以上步骤,令
$
g' (x) = g_k (x) - sum_(k=0)^n c_k a_k (x)\
h' (x) = h_k (x) - sum_(k=0)^n c_k b_k (x)
$
,注意到:
$
1 + r_0 (x) = a_0 (x) h_k (x) + b_0 (x) g_k (x)
$
故:
$
a_0 (x) h' (x) + b_0 (x) g' (x) = 1 + r_0 (x) - sum_(k=0)^n c_k (a_0(x) a_k (x) + b_0(x) b_k (x)) := 1 + r' (x)\
r' a_0 h' + r' b_0 g' = r' + r'^2
$
两式相减:
$
(1-r')a_0 h' + (1-r') b_0 g' = 1 -r'^2
$
而当然有 $-r'^2 in m^(k+1) [x]$,进而 $h', g'$ 确实在 $A quo m^(k+1) [x]$ 中互素,完成了归纳的构造。
有了构造之后,只需取这些 $g_k, h_k$ 的极限为 $g, h$,则 $g h - f$ 在逆向极限中每一项都是零,当然在极限中是零。同时由 $A$ 的完备性极限就是本身,因此结论成立。
== 10
=== (i)
由条件,设 $overline(f(x)) = (overline(x) - alpha)overline(g(x))$,其中 $overline(g)(alpha) != 0$\
由 Hensel's Lemma,将乘积延拓到 $A[x]$,可设:
$
f(x) = (x - a)g(x)
$
其中 $a = alpha mod m$, g(a) != 0(既然 $overline(g(a)) = overline(g)(alpha) != 0$) 表明 $a$ 是单根
=== (ii)
注意到 $7-$adic 环 $ZZ_7$ 以 $(7)$ 为唯一极大理想,而 $ZZ_7 quo 7 ZZ_7 = ZZ quo 7 ZZ$\
考虑 $f(x) = x^2 - 2$,不难验证在 $ZZ quo 7 ZZ$ 中 $3$ 是其单根,这意味着它在 $ZZ_7$ 中也有单根,证毕
=== (iii)
设 $A = k[x], B = k[[x]]$,则 $B$ 是局部环,以 $(x)$ 为唯一极大理想。同时,$f(x, y)$ 关于是其上关于 $y$ 的多项式,并且在 $B quo (x) = k$ 中有单根 $a_0$(既然 $f(x, y) = f(0, y) in B quo (x)$)\
由第一问结论,$f(x, y)$ 将在 $B$ 中有单根 $y(x)$ 使得:
$
f(x, y(x)) = 0
$
这里 $y(x) in B$ 是 $x$ 的形式幂级数,证毕
== 12
设 $B = A[[x_1, x_2, ..., x_n]]$ ,首先熟知 $B$ 在 $A$ 上平坦,同时 $A -> B$ 的伴随映射 $Spec(B) -> Spec(A)$ 是满射(第一章习题),这足以说明 $B$ 在 $A$ 上忠实平坦。
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/typographix-polytechnique-reports/0.1.2/guide.typ | typst | Apache License 2.0 | #import "@preview/typographix-polytechnique-reports:0.1.2" as template
#show: template.apply
// Specific rules for the guide
#show link: set text(blue)
// Defining variables for the cover page and PDF metadata
#let title = [guide for typst #linebreak() polytechnique package]
#let subtitle = "A modern alternative to LaTeX"
#let short_title = "package guide"
#let authors = ("<NAME>")
#let date_start = datetime(year: 2024, month: 07, day: 05)
#let date_end = datetime(year: 2024, month: 08, day: 05)
#set text(lang: "en")
// Beginning of the content
#template.cover.cover(title, authors, date_start, date_end, subtitle: subtitle)
#pagebreak()
#outline(title: [Guide content], indent: 1em, depth: 2)
#pagebreak()
= Discovering Typst and the template
Typst is a user-friendlier alternative to LaTeX.
== Cover page
```typc
// Defining variables for the cover page and PDF metadata
#let title = [guide for typst #linebreak() polytechnique package]
#let subtitle = "A modern alternative to LaTeX"
#let short_title = "package guide"
#let authors = ("<NAME>")
#let date_start = datetime(year: 2024, month: 07, day: 05)
#let date_end = datetime(year: 2024, month: 08, day: 05)
#set text(lang: "en")
#polytechnique.cover.cover(title, authors, date_start, date_end, subtitle: subtitle)
```
Set text lang to `fr` if you want the months in French. \
You can also specify `short_month: true` in the call to cover to get month abbreviations.
== Doing some math
It is really easy to do some math, inline like $P V = n R T$ or if considering $f : x -> 1/18 x^4$, we have $forall x in RR, f(x) >= 0$. You can also do block content :
$ f(b) = sum_(k=0)^n (b-a)^k / k! f^((k))(a) + integral_a^b (b-t)^n / n! f^((n+1))(t) dif t $
== Table of contents
You can generate a table of contents using `#outline()`. Here are useful parameters you can specify :
- `indent`
- `depth`
- `title` (put the title inside brackets : [title])
For example, the previous table of contents was generated using :
```typc
#outline(title: [Guide content], indent: 1em, depth: 2)
```
== Cite an article
You can cite an article, a book or something like @example-turing (`@example-turing`). Just see the `#bibliography` command below - you need a `.bib` file containing the bibliography.
== Numbering pages
Useful commands to number pages (learn about #link("https://typst.app/docs/reference/model/numbering/")[numbering patterns]) :
```typc
#set page(numbering: none) // to disable page numbering
#set page(numbering: "1 / 1") // or another numbering pattern
#counter(page).update(1) // to reset the page counter to 1
```
*Warning* : put these instructions at the very beginning of a page, otherwise it will cause a pagebreak.
#heading(level: 2, numbering: none)[Heading without numbering]
#lorem(25)
== Dummy text with lorem
You can generate dummy text with the `#lorem(n)` command. For example : #lower(lorem(10))
=== Small heading
The small heading above won't appear in the table of contents (because depth is set to 2).
#pagebreak()
= Modify the template
== Contribute
Contributions are welcomed ! Check out the #link("https://github.com/remigerme/typst-polytechnique")[source repository].
You can also learn more about #link("https://github.com/typst/packages")[Typst packages] release pipeline.
#pagebreak()
#bibliography("assets/example.bib")
|
https://github.com/isaacholt100/isaacholt100.github.io | https://raw.githubusercontent.com/isaacholt100/isaacholt100.github.io/master/maths-notes/3-durham%3A-year-3/crypto/crypto.typ | typst | #import "../../template.typ": *
#show: doc => template(doc, hidden: ("proof",), slides: false)
// FIND: - \*(\w+)\*: ([\s\S]*?)(?=\n-|\n\n)\n
// REPLACE: #$1[\n $2\n]\n
#let modulo(n) = $thick mod #n$
#let lmodulo(n) = $quad mod #n$
#let PAI = $overline(O)$
#let vd(v) = $bold(#v)$
#let span = $op("span")$
#let ideal(..args) = $angle.l #args.pos().join(",") angle.r$
= Introduction
#definition[
Encryption process:
- Alice has a message (*plaintext*) which is *encrypted* using an *encryption key* to produce the *ciphertext*, which is sent to Bob.
- Bob uses a *decryption key* (which depends on the encryption key) to *decrypt* the ciphertext and recover the original plaintext.
- It should be computationally infeasible to determine the plaintext without knowing the decryption key.
]
#definition[
*Caesar cipher*:
- Add constant $k$ to each letter in plaintext to produce ciphertext: $ "ciphertext letter" = "plaintext letter" + k quad mod 26 $
- To decrypt, $ "plaintext letter" = "ciphertext letter" - k quad mod 26 $
- The key is $k thick mod 26$.
]
#note[
$Z$ is represented as $0 = 26 mod 26$, $A$ as $1 mod 26$.
]
#definition[
We define the following cryptosystem objectives:
- *Secrecy*: an intercepted message is not able to be decrypted
- *Integrity*: it is impossible to alter a message without the receiver knowing
- *Authenticity*: receiver is certain of identity of sender (they can tell if an impersonator sent the message)
- *Non-repudiation*: sender cannot claim they did not send a message; the receiver can prove they did.
]
#definition[
*Kerckhoff's principle*: a cryptographic system should be secure even if the details of the system are known to an attacker.
]
#definition[
There are 4 types of attack:
- *Ciphertext-only*: the plaintext is deduced from the ciphertext.
- *Known-plaintext*: intercepted ciphertext and associated stolen plaintext are used to determine the key.
- *Chosen-plaintext*: an attacker tricks a sender into encrypting various chosen plaintexts and observes the ciphertext, then uses this information to determine the key.
- *Chosen-ciphertext*: an attacker tricks the receiver into decrypting various chosen ciphertexts and observes the resulting plaintext, then uses this information to determine the key.
]
= Symmetric key ciphers
#note[
When converting letters to numbers, treat letters as integers modulo $26$, with $A = 1$, $Z = 0 equiv 26 thick (mod 26)$. Treat string of text as vector of integers modulo $26$.
]
#definition[
A *symmetric key cipher* is one in which encryption and decryption keys are equal.
]
#definition[
*Key size* is $log_2 ("number of possible keys")$.
]
#example[
Caesar cipher is a *substitution cipher*. A stronger substitution cipher is this: key is permutation of ${a, ..., z}$. But vulnerable to known-plaintext attacks and ciphertext-only attacks, since different letters (and letter pairs) occur with different frequencies in English.
]
#definition[
*One-time pad*: key is uniformly, independently random sequence of integers $mod 26$, $(k_1, k_2, ...)$, known to sender and receiver. If message is $(m_1, m_2, ..., m_r)$ then ciphertext is $(c_1, c_2, ..., c_r) = (k_1 + m_1, k_2 + m_2, ..., k_r + m_r)$. To decrypt the ciphertext, $m_i = c_i - k_i$. Once $(k_1, ..., k_r)$ have been used, they must never be used again.
- One-time pad is information-theoretically secure against ciphertext-only attack: $PP(M = m | C = c) = PP(M = m)$.
- Disadvantage is keys must never be reused, so must be as long as message.
- Keys must be truly random.
]
#theorem(name: "Chinese remainder theorem")[
Let $m, n in NN$ coprime, $a, b in ZZ$. Then exists unique solution $x modulo(m n)$ to the congruences $ x equiv a & lmodulo(m) \ x equiv b & lmodulo(n) $
]
#definition[
*Block cipher*: group characters in plaintext into blocks of $n$ (the *block length*) and encrypt each block with a key. So plaintext $p = (p_1, p_2, ...)$ is divided into blocks $P_1, P_2, ...$ where $P_1 = (p_1, ..., p_n)$, $P_2 = (p_(n + 1), ..., p_(2n)), ...$. Then ciphertext blocks are given by $C_i = f("key", P_i)$ for some encryption function $f$.
]
#definition[
*Hill cipher*:
- Plaintext divided into blocks $P_1, ..., P_r$ of length $n$.
- Each block represented as column vector $P_i in (ZZ \/ 26 ZZ)^n$
- Key is invertible $n times n$ matrix $M$ with elements in $ZZ \/ 26 ZZ$.
- Ciphertext for block $P_i$ is $ C_i = M P_i $ It can be decrypted with $P_i = M^(-1) C_i$.
- Let $P = (P_1, ..., P_r)$, $C = (C_1, ..., C_r)$, then $C = M P$.
]
#definition[
*Confusion* means each character of ciphertext depends on many characters of key.
]
#definition[
*Diffusion* means changing single character of plaintext changes many characters of ciphertext. Ideal diffusion is when changing single character of plaintext changes a proportion of $(S - 1)\/S$ of the characters of the ciphertext, where $S$ is the number of possible symbols.
]
#remark[
Confusion and diffusion make ciphertext-only attacks difficult.
]
#example[
For Hill cipher, $i$th character of ciphertext depends on $i$th row of key (so depends on $n$ characters of the key $M$) - this is medium confusion. If $j$th character of plaintext changes and $M_(i j) != 0$ then $i$th character of ciphertext changes. $M_(i j)$ is non-zero with probability roughly $25\/26$ so good diffusion.
]
#example[
Hill cipher is susceptible to known plaintext attack:
- If $P = (P_1, ..., P_n)$ are $n$ blocks of plaintext with length $n$ such that $P$ is invertible and we know $P$ and the corresponding $C$, then we can recover $M$, since $C = M P ==> M = C P^(-1)$.
- If enough blocks of ciphertext are intercepted, it is very likely that $n$ of them will produce an invertible matrix $P$.
]
= Public key encryption and RSA
#definition[
*Public key cryptosystem*:
- Bob produces encryption key, $k_E$, and decryption key, $k_D$. He publishes $k_E$ and keeps $k_D$ secret.
- To encrypt message $m$, Alice sends ciphertext $c = f(m, k_E)$ to Bob.
- To decrypt ciphertext $c$, Bob computes $g(c, k_D)$, where $g$ satisfies $ g(f(m, k_E), k_D) = m $ for all messages $m$ and all possible keys.
- Computing $m$ from $f(m, k_E)$ should be hard without knowing $k_D$.
]
#algorithm[
*Converting between messages and numbers*:
- To convert message $m_1 m_2 ... m_r$, $m_i in {0, ..., 25}$ to number, compute $ m = sum_(i = 1)^r m_i 26^(i - 1) $
- To convert number $m$ to message, append character $m mod 26$ to message. If $m < 26$, stop. Otherwise, floor divide $m$ by $26$ and repeat.
]
#theorem(name: "Fermat's little theorem")[
Let $p$ prime, $a in ZZ$ coprime to $p$, then $a^(p - 1) equiv 1 thick (mod p)$.
]
#definition[
*Euler $phi$ function* is $ phi: NN -> NN, quad phi(n) = |{1 <= a <= n: gcd(a, n) = 1}| = |(ZZ \/ n ZZ)^times| $
]
#proposition[
$phi(p^r) = p^r - p^(r - 1)$, $phi(m n) = phi(m) phi(n)$ for $gcd(m, n) = 1$.
]
#theorem(name: "Euler's theorem")[
If $gcd(a, n) = 1$, $a^(phi(n)) equiv 1 quad (mod n)$.
]
#algorithm(name: "RSA")[
- $k_E$ is pair $(n, e)$ where $n = p q$, the *RSA modulus*, is product of two distinct primes and $e in ZZ$, the *encryption exponent*, is coprime to $phi(n)$.
- $k_D$, the *decryption exponent*, is integer $d$ such that $d e equiv 1 quad (mod phi(n))$.
- $m$ is an integer modulo $n$, $m$ and $n$ are coprime.
- Encryption: $c = m^e quad (mod n)$.
- Decryption: $m = c^d quad (mod n)$.
- It is recommended that $n$ have at least $2048$ bits. A typical choice of $e$ is $2^16 + 1$.
]
#definition[
*RSA problem*: given $n = p q$ a product of two unknown primes, $e$ and $m^e quad (mod n)$, recover $m$. If $n$ can be factored, then RSA is solved.
]
#definition[
*Factorisation problem*: given $n = p q$ for large distinct primes $p$ and $q$, find $p$ and $q$.
]
#definition[
*RSA signatures*:
- Public key is $(n, e)$ and private key is $d$.
- When sending a message $m$, message is *signed* by also sending $s = m^d mod n$, the *signature*.
- $(m, s)$ is received, *verified* by checking if $m = s^e mod n$.
- Forging a signature on a message $m$ would require finding $s$ with $m = s^e mod n$. This is the RSA problem.
- However, choosing signature $s$ first then taking $m = s^e mod n$ produces valid pairs.
- To solve this, $(m, s)$ is sent where $s = h(m)^d$, $h$ is *hash function*. Then the message receiver verifies $h(m) = s^e mod n$.
- Now, for a signature to be forged, an attacker would have to find $m$ with $h(m) = s^e mod n$.
]
#definition[
*Hash function* is function $h: {"messages"} -> cal(H)$ that:
- Can be computed efficiently
- Is *preimage-resistant*: can't quickly find $m$ given $h(m)$.
- Is *collision-resistant*: can't quickly find $m, m'$ such that $h(m) = h(m')$.
]
#example(name: "Attacks on RSA")[
- If you can factor $n$, you can compute $d$, so can break RSA (as then you know $phi(n)$ so can compute $e^(-1) thick mod phi(n)$).
- If $phi(n)$ is known, then we have $p q = n$ and $(p - 1)(q - 1) = phi(n)$ so $p + q = n - phi(n) + 1$. Hence $p$ and $q$ are roots of $x^2 - (n - phi(n) + 1)x + n$.
- *Known $d$ attack*:
- $d e - 1$ is multiple of $phi(n)$ so $p, q | x^(d e - 1) - 1$.
- Look for factor $K$ of $d e - 1$ with $x^K - 1$ divisible by $p$ but not $q$ (or vice versa) (so likely that $(p - 1) | K$ but $(q - 1) divides.not K$).
- Let $d e - 1 = 2^r s$, $gcd(2, s) = 1$, choose random $x mod n$. Let $y = x^s$, then $y^(2^r) = x^(2^r s) = x^(d e - 1) equiv 1 thick mod n$.
- If $y equiv 1 thick mod n$, restart with new random $x$. Find first occurence of $1$ in $y, y^2, ..., y^(2^r)$: $y^(2^j) equiv.not 1 thick mod n$, $y^(2^(j + 1)) equiv 1 thick mod n$ for some $j >= 0$.
- Let $a := y^(2^j)$, then $a^2 equiv 1 thick mod n$, $a equiv.not 1 thick mod n$. If $a equiv -1 thick mod n$, restart with new random $x$.
- Now $n = p q | a^2 - 1 = (a + 1)(a - 1)$ but $n divides.not (a + 1), (a - 1)$. So $p$ divides one of $a + 1$, $a - 1$ and $q$ divides the other. So $gcd(a - 1, n)$, $gcd(a + 1, n)$ are prime factors of $n$.
]
#theorem[
it is no easier to find $phi(n)$ than to factorise $n$.
]
#theorem[
it is no easier to find $d$ than to factor $n$.
]
#algorithm(name: "Miller-Rabin")[
To probabilistically check whether $n$ is prime:
+ Let $n - 1 = 2^r s$, $gcd(2, s) = 1$.
+ Choose random $x mod n$, compute $y = x^s mod n$.
+ Compute $y, y^2, ..., y^(2^r) mod n$.
+ If $1$ isn't in this list, $n$ is *composite* (with witness $x$).
+ If $1$ is in list preceded by number other than $plus.minus 1$, $n$ is *composite* (with witness $x$).
+ Other, $n$ is *possible prime* (to base $x$).
]
#theorem[
- If $n$ prime then it is possible prime to every base.
- If $n$ composite then it is possible prime to $<= 1\/4$ of possible bases.
In particular, if $k$ random bases are chosen, probability of composite $n$ being possible prime for all $k$ bases is $<= 4^(-k)$.
]
== Factorisation
#algorithm(name: "Trial division factorisation")[
For $p = 2, 3, 5, ...$ up to $sqrt(n)$, test whether $p | n$.
]
#algorithm(name: "Fermat's method for factorisation")[
- If $x^2 equiv y^2 mod n$ but $x equiv.not plus.minus y mod n$, then $x - y$ is divisible by factor of $n$ but not by $n$ itself, so $gcd(x - y, n)$ gives proper factor of $n$ (or $1$).
- Let $a = ceil(sqrt(n))$. Compute $a^2 mod n$, $(a + 1)^2 mod n$ until a square $x^2 equiv (a + i)^2 mod n$ appears. Then compute $gcd(a + i - x, n)$.
- Works well under special conditions on the factors: if $|p - q| <= 2 sqrt(2) root(4, n)$ then Fermat's method takes one step: $x = ceil(sqrt(n))$ works.
]
#definition[
An integer is *$B$-smooth* if all its prime factors are $<= B$.
]
#algorithm(name: "Quadratic sieve")[
- Choose $B$ and let $m$ be number of primes $<= B$.
- Look at integers $x = ceil(sqrt(n)) + k$, $k = 1, 2, ...$ and check whether $y = x^2 - n$ is $B$-smooth.
- Once $y_1 = x_1^2 - n, ..., y_t = x_t^2 - n$ are all $B$-smooth with $t > m$, find some product of them that is a square.
- Deduce a congruence between the squares. Use difference of two squares and $gcd$ to factor $n$.
- Time complexity is $exp(sqrt(log n log log n))$.
]
= Diffie-Hellman key exchange
#theorem(name: "Primitive root theorem")[
Let $p$ prime, then there exists $g in FF_p^times$ such that $1, g, ..., g^(p - 2)$ is complete set of residues $mod p$.
]
#definition[
Let $p$ prime, $g in FF_p^times$. *Order* of $g$ is smallest $a in NN$ such that $g^a = 1$. $g$ is *primitive root* if its order is $p - 1$ (equivalently, $1, g, ..., g^(p - 2)$ is complete set of residues $mod p$).
]
#definition[
Let $p$ prime, $g in FF_p^times$ primitive root. If $x in FF_p^times$ then $x = g^L$ for some $0 <= L < p - 1$. Then $L$ is *discrete logarithm* of $x$ to base $g$. Write $L = L_g (x)$.
]
#proposition[
- $g^(L_g (x)) equiv x quad (mod p)$ and $g^a equiv x quad (mod p) <==> a equiv L_g (x) quad (mod p - 1)$.
- $L_g (1) = 0$, $L_g (g) = 1$.
- $L_g (x y) equiv L_g (x) + L_g (y) quad (mod p - 1)$.
- $L_g (x^(-1)) = -L_g (x) thick (mod p - 1)$.
- $L_g (g^a mod p) equiv a thick (mod p - 1)$.
- $h$ is primitive root mod $p$ iff $L_g (h)$ coprime to $p - 1$. So number of primitive roots mod $p$ is $phi(p - 1)$.
]
#definition[
*Discrete logarithm problem*: given $p, g, x$, compute $L_g (x)$.
]
#definition[
*Diffie-Hellman key exchange*:
- Alice and Bob publicly choose prime $p$ and primitive root $g mod p$.
- Alice chooses secret $alpha mod (p - 1)$ and sends $g^alpha mod p$ to Bob publicly.
- Bob chooses secret $beta mod (p - 1)$ and sends $g^beta mod p$ to Alice publicly.
- Alice and Bob both compute shared secret $kappa = g^(alpha beta) = (g^alpha)^beta) = (g^beta)^alpha mod p$.
]
#definition[
*Diffie-Hellman problem*: given $p, g, g^alpha, g^beta$, compute $g^(alpha beta)$.
]
#remark[
If discrete logarithm problem can be solved, so can Diffie-Hellman problem (since could compute $alpha = L_g (g^a)$ or $beta = L_g (g^beta)$).
]
#definition[
*Elgamal public key encryption*:
- Alice chooses prime $p$, primitive root $g$, private key $alpha med med mod (p - 1)$.
- Her public key is $y = g^alpha$.
- Bob chooses random $k mod (p - 1)$
- To send message $m$ (integer mod $p$), he sends the pair $(r, m') = (g^k, m y^k)$.
- To decrypt message, Alice computes $r^alpha = g^(alpha k) = y^k$ and then $m' r^(-alpha) = m' y^(-k) = m g^(alpha k) g^(-alpha k) = m$.
- If Diffie-Hellman problem is hard, then Elgamal encryption is secure against known plaintext attack.
- Key $k$ must be random and different each time.
]
#definition[
*Decision Diffie-Hellman problem*: given $g^a, g^b, c$ in $FF_p^times$, decide whether $c = g^(a b)$.
This problem is not always hard, as can tell if $g^(a b)$ is square or not. Can fix this by taking $g$ to have large prime order $q | (p - 1)$. $p = 2q + 1$ is a good choice.
]
#definition[
*Elgamal signatures*:
- Public key is $(p, g)$, $y = g^alpha$ for private key $alpha$.
- *Valid Elgamal signature* on $m in {0, ..., p - 2}$ is pair $(r, s)$, $0 <= r, s <= p - 1$ such that $ y^r r^s = g^m quad (mod p) $
- Alice computes $r = g^k$, $k in (ZZ\/(p - 1))^times$ random. $k$ should be different each time.
- Then $g^(alpha r) g^(k s) equiv g^m quad mod p$ so $alpha r + k s equiv m quad (mod p - 1)$ so $s = k^(-1) (m - alpha r) quad mod p - 1$.
]
#definition[
*Elgamal signature problem*: given $p, g, y, m$, find $r, s$ such that $y^r r^s = m$.
]
#algorithm(name: "Baby-step giant-step algorithm")[
To solve DLP:
- Let $N = ceil(sqrt(p - 1))$.
- Baby-steps: compute $g^j thick mod p$ for $0 <= j < N$.
- Giant-steps: compute $x g^(-N k) thick mod p$ for $0 <= k < N$.
- Look for a match between baby-steps and giant-steps lists: $g^j = x g^(-N k) ==> x = g^(j + N k)$.
- Always works since if $x = g^L$ for $0 <= L < p - 1 <= N^2$, $L$ can be written as $j + N k$ with $j, k in {0, ..., N - 1}$.
]
#algorithm(name: "Index calculus")[
To solve DLP:
- Fix smoothness bound $B$.
- Find many multiplicative relations between $B$-smooth numbers and powers of $g mod p$.
- Solve these relations to find discrete logarithms of primes $<= B$.
- For $i = 1, 2, ...$ compute $x g^i mod p$ until one is $B$-smooth, then use result from previous step.
]
#remark[
*Pohlig-Hellman algorithm* computes discrete logarithms $mod p$ with approximate complexity $log(p) sqrt(ell)$ where $ell$ is largest prime factor of $p - 1$, so is fast if $p - 1$ is $B$-smooth. Therefore $p$ is chosen so that $p - 1$ has large prime factor, e.g. choose *Germain prime* $p = 2q + 1$, with $q$ prime.
]
= Elliptic curves
#definition[
*abelian group* $(G, compose)$ satisfies:
- *Associativity*: $forall a, b, c, in G, a compose (b compose c) = (a compose b) compose c$.
- *Identity*: $exists e in G: forall g in G, e times g = g$.
- *Inverses*: $forall g in G, exists h in G: g compose h = h compose g = e$
- *Commutativity*: $forall a, b in G, a compose b = b compose a$.
]
#definition[
$H subset.eq G$ is *subgroup* of $G$ if $(H, compose)$ is group.
]
#remark[
To show $H$ is subgroup, sufficient to show $g, h in H => g compose h in H$ and $h^(-1) in H$.
]
#notation[
for $g in G$, write $[n] g$ for $g compose dots.h.c compose g$ $n$ times if $n > 0$, $e$ if $n = 0$, $[-n] g^(-1)$ if $n < 0$.
]
#definition[
*subgroup generated by $g$* is $ angle.l g angle.r = {[n]g: n in ZZ} $ If $angle.l g angle.r$ finite, it has *order $n$*, and $g$ has *order $n$*. If $G = angle.l g angle.r$ for some $g in G$, $G$ is *cyclic* and $g$ is *generator*.
]
#theorem(name: "Lagrange's theorem")[
Let $G$ finite group, $H$ subgroup of $G$, then $|H| | |G|$.
]
#corollary[
if $G$ finite, $g in G$ has order $n$, then $n | |G|$.
]
#definition[
*DLP for abelian groups*: given $G$ a cyclic abelian group, $g in G$ a generator of $G$, $x in G$, find $L$ such that $[L]g = x$. $L$ is well-defined modulo $|G|$.
]
#definition[
let $(G, compose)$, $(H, circle.filled.small)$ abelian groups, *homomorphism* between $G$ and $H$ is $f: G -> H$ with $ forall g, g' in G, quad f(g compose g') = f(g) circle.filled.small f(g') $ *Isomorphism* is bijective homomorphism. $G$ and $H$ are *isomorphic*, $G tilde.equiv H$, if there is isomorphism between them.
]
#theorem(name: "Fundamental theorem of finite abelian groups")[
Let $G$ finite abelian group, then there exist unique integers $2 <= n_1, ..., n_r$ with $n_i | n_(i + 1)$ for all $i$, such that $ G tilde.eq (ZZ \/ n_1) times dots.h.c times (ZZ \/ n_r) $ In particular, $G$ is isomorphic to product of cyclic groups.
]
#definition[
let $K$ field, $"char"(K) > 3$. An *elliptic curve* over $K$ is defined by the equation $ y^2 = x^3 + a x + b $ where $a, b in K$, $Delta_E := 4a^3 + 27b^2 != 0$.
]
#remark[
$Delta_E != 0$ is equivalent to $x^3 + a x + b$ having no repeated roots (i.e. $E$ is smooth).
]
#definition[
for elliptic curve $E$ defined over $K$, a *$K$-point* (*point*) on $E$ is either:
- A *normal point*: $(x, y) in K^2$ satisfying the equation defining $E$.
- The *point at infinity* $PAI$ which can be thought of as infinitely far along the $y$-axis (in either direction).
Denote set of all $K$-points on $E$ as $E(K)$.
]
#remark[
Any elliptic curve $E(K)$ is an abelian group, with group operation $plus.circle$ is defined as:
- We should have $P plus.circle Q plus.circle R = PAI$ iff $P, Q, R$ lie on straight line.
- In this case, $P plus.circle Q = -R$.
- To find line $ell$ passing through $P = (x_0, y_0)$ and $Q = (x_1, y_1)$:
- If $x_0 != x_1$, then equation of $ell$ is $y = lambda x + mu$, where $ lambda = (y_1 - y_0)/(x_1 - x_0), quad mu = y_0 - lambda x_0 $ Now $ y^2 & = x^3 + a x + b = (lambda x + mu)^2 \ ==> 0 & = x^3 - lambda^2 x^2 + (a - 2 lambda mu)x + (b - mu^2) $ Since sum of roots of monic polynomial is equal to minus the coefficient of the second highest power, and two roots are $x_0$ and $x_1$, the third root is $x_2 = lambda^2 - x_0 - x_1$. Then $y_2 = lambda x_2 + mu$ and $R = (x_2, y_2)$.
- If $x_0 = x_1$, then using implicit differentiation: $ & y^2 = x^3 + a x + b \ ==> & (dif y)/(dif x) = (3x^2 + a)/(2y) $ and the rest is as above, but instead with $lambda = (3x_0^2 + a)/(2y_0)$.
]
#definition[
*Group law* of elliptic curves: let $E: y^2 = x^3 + a x + b$. For all normal points $P = (x_0, y_0), Q = (x_1, y_1) in E(K)$, define
- $PAI$ is group identity: $P plus.circle PAI = PAI plus.circle P = P$.
- If $P = -Q =: (x_0, -y_0)$, $P plus.circle Q = PAI$.
- Otherwise, $P plus.circle Q = (x_2, -y_2)$, where $ x_2 & = lambda^2 - (x_0 + x_1), \ y_2 & = lambda x_2 + mu, \ lambda & = cases((y_1 - y_0)/(x_1 - x_0) & "if" x_0 != x_1, (3x_0^2 + a)/(2y_0) & "if" x_0 = x_1), \ mu & = y_0 - lambda x_0 $
]
#example[
- Let $E$ be given by $y^2 = x^3 + 17$ over $QQ$, $P = (-1, 4) in E(QQ)$, $Q = (2, 5) in E(QQ)$. To find $P plus.circle Q$, $ lambda = (5 - 4)/(2 - (-1)) = 1/3, quad mu = 4 - lambda(-1) = 13/3 $ So $x_2 = lambda^2 - (-1) -2 = -8/9$ and $y_2 = -(lambda x_2 + mu) = -109/27$ hence $ P plus.circle Q = (-8/9, -109/27) $ To find $[2]P$, $ lambda = (3(-1)^2 + 0)/(2 dot.op 4) = 3/8, quad mu = 4 - 3/8 dot.op (-1) = 35/8 $ so $x_3 = lambda^2 - 2 dot.op (-1) 137/64$, $y_3 = -(lambda x_3 + mu) = -2651/512$ hence $ [2]P = (x_3, y_3) = (137/64, -2651/512) $
]
#theorem(name: "Hasse's theorem")[
Let $|E(FF_p)| = N$, then $ |N - (p + 1)| <= 2 sqrt(p) $
]
#theorem[
$E(FF_p)$ is isomorphic to either $ZZ\/k$ or $ZZ\/m times ZZ\/n$ with $m | n$.
]
#definition[
*Elliptic curve Diffie-Hellman*:
- Alice and Bob publicly choose elliptic curve $E(FF_p)$ and $P in FF_p$ with order a large prime $n$.
- Alice chooses random $alpha in {0, ..., n - 1}$ and publishes $Q_A = [alpha]P$.
- Bob chooses random $beta in {0, ..., n - 1}$ and publishes $Q_B = [beta]P$.
- Alice computes $[alpha]Q_B = [alpha beta]P$, Bob computes $[beta]Q_A = [beta alpha]P$.
- Shared key is $K = [alpha beta] P$.
]
#definition[
*Elliptic curve Elgamal signatures*:
- Use agreed elliptic curve $E$ over $FF_p$, point $P in E(FF_p)$ of prime order $n$.
- Alice wants to sign message $m$, encoded as integer mod $n$.
- Alice generates private key $alpha in ZZ\/n$ and public key $Q = [alpha] P$.
- Valid signature is $(R, s)$ where $R = (x_R, y_R) in E(FF_p)$, $s in ZZ\/n$, $[tilde(x_R)] Q plus.circle [s] R = [m] P$.
- To generate a valid signature, Alice chooses random $0 != k in (ZZ\/n)^times$ and sets $R = [k] P$, $s = k^(-1) (m - tilde(x_R) alpha)$.
- $k$ must be randomly generated for each message.
]
#algorithm(name: "Elliptic curve DLP baby-step giant-step algorithm")[
Given $P$ and $Q = [alpha] P$, find $alpha$:
- Let $N = ceil(sqrt(n))$, $n$ is order of $P$.
- Compute $P, [2] P, ..., [N - 1]P$.
- Compute $Q plus.circle [-N]P, Q plus.circle [-2N]P, ..., Q plus.circle [-(N - 1)N]P$ and find a match between these two lists: $[i]P = Q plus.circle [-j N]P$, then $[i + j N]P = Q$ so $alpha = i + j N$.
]
#remark[
For well-chosen elliptic curves, the best algorithm for solving DLP is the baby-step giant-step algorithm, with run time $O(sqrt(n)) approx O(sqrt(p))$. This is much slower than the index-calculus method for the DLP in $FF_p^times$.
]
#algorithm(name: [Pollard's $p - 1$ algorithm])[
To factorise $n = p q$:
- Choose smoothness bound $B$.
- Choose random $2 <= a <= n - 2$. Set $a_1 = a$, $i = 2$.
- Compute $a_i = a_(i - 1)^i thick mod n$. Find $d = gcd(a_i - 1, n)$. If $1 < d < n$, we have found a nontrivial factor of $n$. If $d = n$, pick new $a$ and retry. If $d = 1$, increment $i$ by $1$ and repeat this step.
- A variant is instead of computing $a_i = a_(i - 1)^i$, compute $a_i = a_(i - 1)^(m_(i - 1))$ where $m_1, ..., m_r$ are the prime powers $<= B$ (each prime power is the maximal prime power $<= B$ for that prime).
- The algorithm works if $p - 1$ is *$B$-powersmooth* (all prime power factors are $<= B$), since if $b$ is order of $a mod p$, then $b | (p - 1)$ so $b | B!$ (also $b | m_1 dots.h.c m_r$). If the first $i$ for which $i!$ (or $m_1 dots.h.c m_i$) is divisible by $d$ and order of $a mod q$, then $a_i - 1 = a^(i!) - 1 mod n$ is divisible by both $p$ and $q$, so must retry with different $a$.
]
#remark[
Let $n = p q$, $p, q$ prime, $a, b in ZZ$, $gcd(4a^3 + 27b^2, n) = 1$. Then $E: y^2 = x^3 + a x + b$ defines elliptic curve over $FF_p$ and over $FF_q$. If $(x, y) in ZZ\/n$ is solution to $E mod n$ then can reduce coordinates $mod p$ to obtain non-infinite point of $E(FF_p)$ and $mod q$ to obtain non-infinite point of $E(FF_q)$.
]
#proposition[
let $P_1 = (x_1, y_1), P_2 = (x_2, y_2) in E mod n$, with $ (P_1 mod p) plus.circle (P_2 mod p) & = PAI \ (P_1 mod q) plus.circle (P_2 mod q) & != PAI $ Then $gcd(x_1 - x_2, n)$ (or $gcd(2x_1, n)$ if $P_1 = P_2$) is factor of $n$.
]
#algorithm(name: "Lenstra's algorithm")[
To factorise $n$:
- Choose smoothness bound $B$.
- Choose random elliptic curve $E$ over $ZZ\/n$ with $gcd(Delta_E, n) = 1$ and $P = (x, y)$ a point on $E$.
- Set $P_1 = P$, attempt to compute $P_i$, $2 <= i <= B$ by $P_i = [i] P_(i - 1)$. If one of these fails, a divisor of $n$ has been found (by failing to compute an inverse $mod n$). If this divisor is trivial, restart with new curve and point.
- If $i = B$ is reached, restart with new curve and point.
- Again, a variant is calculating $P_i = [m_i]P_(i - 1)$ instead of $[i]P_(i - 1)$ where $m_1, ..., m_r$ are the prime powers $<= B$
]
#remark[
Lenstra's algorithm works if $|E(ZZ\/p)|$ is $B$-powersmooth but $|E(ZZ\/q)|$ isn't. Since we can vary $E$, it is very likely to work eventually.
Running time depends on $p$ (the smaller prime factor): $ O(exp(sqrt(2 log(p) log log (p)))) $ Compare this to the general number field sieve running time: $ O(exp(C (log n)^(1\/3) (log log n)^(2\/3))) $
]
== Torsion points
#definition[
Let $G$ abelian group. $g in G$ is a *torsion* if it has finite order. If order divides $n$, then $[n]g = e$ and $g$ is *$n$-torsion*.
]
#definition[
*$n$-torsion subgroup* is $ G[n] := {g in G: [n]g = e} $
]
#definition[
*torsion subgroup* of $G$ is $ G_"tors" = {g in G: g "is torsion"} = union.big_(n in NN) G[n] $
]
#example[
- In $ZZ$, only $0$ is torsion.
- In $(ZZ\/10)^times$, by Lagrange's theorem, every point is $4$-torsion.
- For finite groups $G$, $G_"tors" = G = G[ |G| ]$ by Lagrange's theorem.
]
== Rational points
#note[
for elliptic curve $E: y^2 = x^3 + a x + b$ over $QQ$, can assume that $a, b in ZZ$. So assume $a, b in ZZ$ in this section.
]
#theorem(name: "Nagell-Lutz")[
Let $E$ elliptic curve, let $P = (x, y) in E(QQ)_"tors"$. Then $x, y in ZZ$, and either $y = 0$ (in which case $P$ is $2$-torsion) or $y^2 divides Delta_E$.
]
#corollary[
$E(QQ)_"tors"$ is finite.
]
#example[
can use Nagell-Lutz to show a point is not torsion.
- $P = (0, 1)$ lies on elliptic curve $y^2 = x^3 -x + 1$. $[2]P = (1/4, -7/8) in.not ZZ^2$. Then $[2]P$ is not torsion, hence $P$ is not torsion. So $E(QQ)$ contains distinct points $..., [-2]P, -P, PAI, P, [2]P, ...$, hence $E$ has infinitely many solutions in $QQ$.
]
#theorem(name: "Mazur")[
Let $E$ be elliptic curve over $QQ$. Then $E(QQ)_"tors"$ is either:
- cyclic of order $1 <= N <= 10$ or order $12$, or
- of the form $ZZ\/2 times ZZ\/2N$ for $1 <= N <= 4$.
]
#definition[
let $E: y^2 = x^3 + a x + b$ defined over $QQ$, $a, b in ZZ$. For odd prime $p$, taking reductions $overline(a)$, $overline(b) mod p$ gives curve over $FF_p$: $ overline(E): y^2 = x^3 + overline(a) x + overline(b) $ This is elliptic curve if $Delta_E equiv.not 0 mod p$, in which case $p$ is *prime of good reduction* for $E$.
]
#theorem[
let $E: y^2 = x^3 + a x + b$ defined over $QQ$, $a, b in ZZ$, $p$ be odd prime of good reduction for $E$. Then $f: E(QQ)_"tors" -> overline(E)(FF_p)$ defined by $ f(x, y) := (overline(x), overline(y)), quad f\(PAI\) := PAI $ is an injective homomorphism (note $x, y in ZZ$ by Nagell-Lutz).
]
#corollary[
$E(QQ)_"tors"$ can be thought of as subgroup of $E(FF_p)$ for any prime $p$ of good reduction, so by Lagrange's theorem, $|E(QQ)_"tors"|$ divides $|E(FF_p)|$.
]
#theorem(name: "Mordell")[
If $E$ is elliptic curve over $QQ$, then $ E(QQ) tilde.equiv E(QQ)_"tors" times ZZ^r $ for some $r >= 0$ the *rank* of $E$. So for some $P_1, ..., P_r in E(QQ)$, $ E(QQ) = \{n_1 P_1 + dots.h.c + n_r P_r + T: n_i in ZZ, T in E(QQ)_"tors"\} $ $P_1, ..., P_r$ (together with $T$) are *generators* for $E(QQ)$.
]
= Basic coding theory
== First definitions
#definition[
- *Alphabet* $A$ is finite set of symbols.
- $A^n$ is set of all lists of $n$ symbols from $A$ - these are *words of length $n$*.
- *Code of block length $n$ on $A$* is subset of $A^n$.
- *Codeword* is element of a code.
]
#definition[
If $|A| = 2$, codes on $A$ are *binary* codes. If $|A| = 3$, codes on $A$ are *ternary codes*. If $|A| = q$, codes on $A$ are *$q$-ary* codes. Generally, use $A = {0, 1, ..., q - 1}$.
]
#definition[
Let $x = x_1 ... x_n, y = y_1 ... y_n in A^n$. *Hamming distance* between $x$ and $y$ is number of indices where $x$ and $y$ differ: $ d: A^n times A^n -> {0, ..., n}, quad d(x, y) := |{i in [n]: x_i != y_i}| $ So $d(x, y)$ is minimum number of changes needed to change $x$ to $y$. If $x$ transmitted and $y$ received, then $d(x, y)$ *symbol-errors* have occurred.
]
#proposition[
Let $x, y$ words of length $n$.
- $0 <= d(x, y) <= n$.
- $d(x, y) = 0 <==> x = y$.
- $d(x, y) = d(y, x)$.
- $forall z in A^n, d(x, y) <= d(x, z) + d(z, y)$.
]
#definition[
*Minimum distance* of code $C$ is $ d(C) := min{d(x, y): x, y in C, x != y} in NN $
]
#notation[
Code of block length $n$ with $M$ codewords and minimum distance $d$ is called $(n, M, d)$ (or $(n, M)$) code. A $q$-ary code is called an $\(n, M, d\)_q$ code.
]
#definition[
Let $C subset.eq A^n$ code, $x$ word of length $n$. A *nearest neighbour* of $x$ is codeword $c in C$ such that $d(x, c) = min{d(x, y): y in C}$.
]
== Nearest-neighbour decoding
#definition[
*Nearest-neighbour decoding (NND)* means if word $x$ received, it is decoded to a nearest neighbour of $x$ in a code $C$.
]
#proposition[
Let $C$ be code with minimum distance $d$, let word $x$ be received with $t$ symbol errors. Then
- If $t <= d - 1$, then we can detect that $x$ has some errors.
- If $t <= floor((d - 1)/2)$, then NND will correct the errors.
]
== Probabilities
#definition[
*$q$-ary symmetric channel with symbol-error probability $p$* is channel for $q$-ary alphabet $A$ such that:
- For every $a in A$, probability that $a$ is changed in channel is $p$ (i.e. symbol-errors in different positions are independent events).
- For every $a != b in A$, probability that $a$ is changed to $b$ in channel is $ PP(b "received" | a "sent") = p/(q - 1) $
i.e. given that a symbol has changed, it is equally likely to change to any of the $q - 1$ other symbols.
]
#proposition[
Let $c$ codeword in $q$-ary code $C subset.eq A^n$ sent over $q$-ary symmetric channel with symbol-error probability $p$. Then $ PP(x "received" | c "sent") = (p/(q - 1))^t (1 - p)^(n - t), quad "where" t = d(c, x) $
]
#example[
Let $C = {000, 111} subset {0, 1}^3$.
#figure(table(
columns: (auto, auto, auto, auto, auto),
$x$, $t = d(000, x)$, [chance $000$ received as $x$], [chance if $p = 0.01$], [NND decodes correctly?],
$000$, $0$, $(1 - p)^3$, $0.970299$, "yes",
$100$, $1$, $p(1 - p)^2$, $0.009801$, "yes",
$010$, $1$, $p(1 - p)^2$, $0.009801$, "yes",
$001$, $1$, $p(1 - p)^2$, $0.009801$, "yes",
$110$, $2$, $p^2(1 - p)$, $0.000099$, "no",
$101$, $2$, $p^2(1 - p)$, $0.000099$, "no",
$011$, $2$, $p^2(1 - p)$, $0.000099$, "no",
$111$, $3$, $p^3$, $0.000001$, "no",
))
]
#corollary[
If $p < (q - 1)/q$ then $P(x "received" | c "sent")$ increases as $d(x, c)$ decreases.
]
#remark[
By Bayes' theorem, $ PP(c "sent" | x "received") = PP(c "sent and" x "received") / PP(x "received") = (PP(c "sent") PP(x "received" | c "sent"))/PP(x "received") $
]
#proposition[
Let $C$ be $q$-ary $(n, M, d)$ code used over $q$-ary symmetric channel with symbol-error probability $p < (q - 1)\/q$, and each codeword $c in C$ is equally likely to be sent. Then for any word $x$, $PP(c "sent" | x "received")$ increases as $d(x, c)$ decreases.
]
== Bounds on codes
#proposition(name: "Singleton bound")[
For $q$-ary code $(n, M, d)$ code, $M <= q^(n - d + 1)$.
]
#definition[
Code which saturates singleton bound is called *maximum distance separable (MDS)*.
]
#example[
Let $C_n$ be *binary repetition code* of block length $n$, $ C_n := \{underbrace(00...0, n), underbrace(11...1, n)\} subset {0, 1}^n $ $C_n$ is $(n, 2, n)_2$ code, and $2 = 2^(n - n + 1)$ so $C_n$ is MDS code.
]
#definition[
Let $A$ be alphabet, $|A| = q$. Let $n in NN$, $0 <= t <= n$, $t in NN$, $x in A^n$.
- *Ball of radius $t$ around $x$* is $ S(x, t) := {y in A^n: d(y, x) <= t} $
- Code $C subset.eq A^n$ is *perfect* if $ exists t in NN_0: A^n = product.co_(c in C) S(c, t) $ where $product.co$ is disjoint union.
]
#example[
For $C = {000, 111} subset {0, 1}^3$, $S(000, 1) = {000, 100, 010, 001}$ and $S(111, 1) = {111, 011, 101, 110}$. These are disjoint and $S(000, 1) union S(111, 1) = {0, 1}^3$, so $C$ is perfect.
]
#example[
Let $C = {111, 020, 202} subset {0, 1, 2}^3$. $forall c in C, d(c, 012) = 2$. So $012$ is not in any $S(c, 1)$ but is in every $S(c, 2)$, so $C$ is not perfect.
]
#lemma[
Let $|A| = q$, $x in A^n$, then $ |S(x, t)| = sum_(k = 0)^t binom(n, k) (q - 1)^k $
]
#example[
Let $C = {111, 020, 202} subset {0, 1, 2}^3$, so $q = 3$, $n = 3$. So $|S(x, 1)| = binom(3, 0) + binom(3, 1) (3 - 1) = 7$, $|S(x, 2)| = binom(3, 0) + binom(3, 1)(3 - 1) + binom(3, 2) (3 - 1)^2 = 19$. But $|{0, 1, 2}|^3 = 27$ and $7 divides.not 27$, $19 divides.not 27$, so ${0, 1, 2}^3$ can't be partioned by balls of either size. So $C$ can't be perfect. $|S(x, 3)| = 27$, but then $C$ must contain only one codeword to be perfect, and $|S(x, 0)| = 1$, but then $C = A^n$ to be perfect. These are trivial, useless codes.
]
#proposition(name: "Hamming/sphere-packing bound")[
$q$-ary $(n, M, d)$ code satisfies $ M sum_(k = 0)^t binom(n, k) (q - 1)^k <= q^n, quad "where" t = floor((d - 1)/2) $
]
#corollary[
Code saturates Hamming bound iff it is perfect.
]
= Linear codes
== Finite vector spaces
#definition[
*Linear code* of block length $n$ is subspace of $FF_q^n$.
]
#example[
Let $vd(x) = (0, 1, 2, 0)$, $vd(y) = (1, 1, 1, 1)$, $vd(z) = (0, 2, 1, 0) in FF_3^4$. $C_1 = {vd(x), vd(y), vd(0)}$ is not linear code since e.g. $vd(x) + vd(y) = (1, 2, 0, 1) in.not C_1$. $C_2 = {vd(x), vd(z), vd(0)}$ is linear code.
]
#notation[
Spanning set of $S$ is $ideal(S)$.
]
#proposition[
If linear code $C subset.eq FF_q^n$ has $dim(C) = k$, then $|C| = q^k$.
]
#definition[
A $q$-ary $[n, k, d]$ code is linear code: a subspace of $FF_q^n$ of dimension $k$ with minimum distance $d$. Note: a $q$-ary $[n, k, d]$ code is a $q$-ary $(n, q^k, d)$ code.
]
== Weight and minimum distance
#definition[
*Weight* of $vd(x) in FF_q^n$, $w(vd(x))$, is number of non-zero entries in $vd(x)$: $ w(vd(x)) = |{i in [n]: x_i != 0}| $
]
#lemma[
$forall vd(x), vd(y) in FF_q^n$, $d(vd(x), vd(y)) = w(vd(x) - vd(y))$. In particular, $w(vd(x)) = d(vd(x), vd(0))$.
]
#proposition[
Let $C subset.eq FF_q^n$ linear code, then $ d(C) = min{w(vd(c)): vd(c) in C, vd(c) != vd(0)} $
]<min-dist-as-weight>
#remark[
To find $d(C)$ for linear code with $q^k$ words, only need to consider $q^k$ weights instead of $binom(q^k, 2)$ distances.
]
= Codes as images
== Generator-matrices
#definition[
Let $C subset.eq FF_q^n$ be linear code. Let $G in M_(k, n)(FF_q)$, $f_G: FF_q^k -> FF_q^n$ be linear map defined by $f_G (vd(x)) = vd(x) G$. Then $G$ is *generator-matrix* for $C$ if
- $C = im(f) = \{vd(x) G: vd(x) in FF_q^k\} subset.eq FF_q^n$.
- The rows of $G$ are linearly independent.
i.e. $G$ is generator-matrix for $C$ iff rows of $G$ form basis for $C$ (note $vd(x) G = x_1 vd(g_1) + dots.h.c + x_k vd(g_k)$ where $vd(g_i)$ are rows of $G$).
]
#remark[
Given linear code $C = ideal(vd(a)_1, ..., vd(a)_m)$, a generator-matrix can be found for $C$ by constructing the matrix $A$ with rows $vd(a)_i$, then performing elementary row operations to bring $A$ into RREF. Once the $m - k$ bottom zero rows have been removed, the resulting matrix is a generator-matrix.
]
#example[
Let $C = ideal({(0, 0, 3, 1, 4), (2, 4, 1, 4, 0), (5, 3, 0, 1, 6)}) subset.eq FF_7^5$. $
A = mat(2, 4, 1, 4, 0; 5, 3, 0, 1, 6; 0, 0, 3, 1, 4) limits(->_(A_(12)(1))) mat(2, 4, 1, 4, 0; 0, 0, 1, 5, 6; 0, 0, 3, 1, 4) limits(->_(M_1 (4))) mat(1, 2, 4, 2, 0; 0, 0, 1, 5, 6; 0, 0, 3, 1, 4) limits(->_(A_(21)(3), A_(23)(4))) mat(1, 2, 0, 3, 4; 0, 0, 1, 5, 6; 0, 0, 0, 0, 0)
$ So $G = mat(1, 2, 0, 3, 4; 0, 0, 1, 5, 6)$ is generator matrix for $C$ and $dim(C) = 2$.
]
== Encoding and channel decoding
- Let $C$ be $q$-ary $[n, k]$ code with generator matrix $G in M_(k, n)(FF_q)$. To encode a message $x in FF_q^k$, multiply by $G$: codeword is $c = x G$.
- Note that rows of $G$ being linearly independent implies $f_G$ is injective, so no two messages are mapped to same codeword.
- If we want the code to correct (and detect) errors, we must have $k < n$.
- The received word $y in FF_q^n$ is decoded to the codeword $c' in C$.
- *Channel decoding* is finding the unique word $x'$ such that $x' G = c'$, i.e. $x' dot g_i = c'_i$ where $g_i$ is $i$th column of $G$. This gives $n$ equations in $k$ unknowns. Since $c'$ is a codeword, these equations are consistent, and since $f_G$ is injective, there is a unique solution.
- To solve $x' G = c'$, either use that $G^t (x')^t = (c')^t$ and row-reduce augmented matrix $(G^t | (c')^t)$, or pick generator-matrix in RREF, which then picks out each $x'_i$.
== Equivalence and standard form
#definition[
Codes $C_1, C_2$ of block length $n$ over alphabet $A$ are *equivalent* if we can transform one to the other by applying sequence of the following two kinds of changes to all the codewords (simultaneously):
- Permute the $n$ positions.
- In a particular position, permuting the $|A| = q$ symbols.
]
#proposition[
Equivalent codes have the same parameters $(n, M, d)$.
]
#definition[
Linear codes $C_1, C_2 subset.eq FF_q^n$ are *monomially equivalent* if we can obtain one from the other by applying sequence of the following two kinds of changes to all codewords (simultaneously):
- Permuting the $n$ positions.
- In particular position, multiply by $lambda in FF_q^times$.
If only the first change is used, the codes are *permutation equivalent*.
]
#definition[
$P in M_n (FF_q)$ is *permutation matrix* if it has a single $1$ in each row and column, and zeros elsewhere. Any permutation of $n$ positions of row vector in $FF_q^n$ can be described as right multiplication by permutation matrix.
]
#proposition[
Permutation matrices are orthogonal: $P^T = P^(-1)$.
]
#proposition[
Let $C_1, C_2 subset.eq FF_q^n$ linear codes with generator matrices $G_1, G_2$. Then if $G_1 = G_2 P$ for permutation matrix $P$, then $C_1$ and $C_2$ are permutation equivalent.
]
#definition[
$M in M_m (FF_q)$ is *monomial matrix* if it has exactly one non-zero element in each row and column.
]
#proposition[
Monomial matrix $M$ can always be written as $M = D P$ or $M = P D'$ where $P$ is permutation matrix and $D, D'$ are diagonal matrices. $P$ is *permutation part*, $D$ and $D'$ are *diagonal parts* of $M$.
]
#example[
$ mat(0, 2, 0; 0, 0, 3; 1, 0, 0) = mat(2, 0, 0; 0, 3, 0; 0, 0, 1) mat(0, 1, 0; 0, 0, 1; 1, 0, 0) = mat(0, 1, 0; 0, 0, 1; 1, 0, 0) mat(1, 0, 0; 0, 2, 0; 0, 0, 3) $
]
#proposition[
Let $C_1, C_2 subset.eq FF_q^n$ be linear codes with generator-matrices $G_1, G_2$. Then if $G_2 = G_1 M$ for some monomial matrix $M$, then $C_1$ and $C_2$ are monomially equivalent.
]
#definition[
Let $C subset.eq FF_q^n$ linear code. If $G = (I_k | A)$, with $A in M_(k, n - k)(FF_q)$, is generator-matrix for $C$, then $G$ is in *standard form*.
]
#note[
Not every linear code has generator-matrix in standard form.
]
#proposition[
Every linear code is permutation equivalent to a linear code with generator-matrix in standard form.
]
#example[
Let $C_1 subset.eq FF_7^5$ have generator matrix $G_1 = mat(1, 2, 0, 3, 4; 0, 0, 1, 5, 6)$. Then applying permutation matrix $ P = mat(1, 0, 0, 0, 0; 0, 0, 1, 0, 0; 0, 1, 0, 0, 0; 0, 0, 0, 1, 0; 0, 0, 0, 0, 1) ==> G_1 P = mat(1, 0, 2, 3, 4; 0, 1, 0, 5, 6) = (I_2 | A) $
]
= Codes as kernels
== Dual codes
#definition[
Let $C subset.eq FF_q^n$ linear code. *Dual* of $C$ is $ C^perp := {vd(v) in FF_q^n: forall vd(u) in C, vd(v) dot.op vd(u) = 0} $
]
#proposition[
If $G$ is generator matrix for linear code $C$ then $ C^perp = \{vd(v) in FF_q^n : vd(v) G^T = vd(0)\} = ker(f_(G^T)) $ where $f_(G^T): FF_q^n -> FF_q^k$, $f(x) = x G^T$ is linear map.
]<dual-as-kernel>
#proposition[
Let $C subset.eq FF_q^n$ linear code. Then $C^perp$ is also linear code and $dim(C) + dim(C^perp) = n$.
]
#proposition[
Let $C subset.eq FF_q^n$ linear code, then $(C^perp)^perp = C$.
]
#proof[
Show $dim((C^perp)^perp) = dim(C)$ and $C subset.eq (C^perp)^perp$.
]
#proposition[
Let $C subset.eq FF_q^n$ have generator-matrix in standard form, $G = (I_k | A)$, then $H = (-A^T | I_(n - k))$ is generator-matrix for $C^perp$.
]
#proof[
Show $forall y in FF_q^(n - k)$, $y H in C^perp$, let $f_H (y) = y H$ so $"im"(f_H) subset.eq C^perp$ and show $dim("im"(f_H)) = dim(C^perp)$.
]
#proposition[
Let $G$ be generator matrix of $C subset.eq FF_q^n$, let $P in M_n (FF_q)$ permutation matrix such that $G P = (I_k | A)$ for some $A in M_(k, n - k)(FF_q)$. Then $H = (-A^T | I_(n - k)) P^T$ is generator matrix for $C^perp$.
]
#proof[
Similar to previous proposition, use that $P^T = P^(-1)$.
]
#algorithm[
To find basis for dual code $C^perp$, given generator matrix $G = (g_(i j)) in M_(k, n)(FF_q)$ for $C$ in RREF:
+ Let $L = {1 <= j <= n: G "has leading" 1 "in column" j}$.
+ For each $1 <= j <= n$, $j in.not L$, construct $vd(v)_j$ as follows:
+ For $m in.not L$, $m$th entry of $vd(v)_j$ is $1$ if $m = j$ and $0$ otherwise.
+ Fill in the other entries of $vd(v)_j$ (left to right) as $-g_(1 j), ..., -g_(k j)$.
+ The $n - k$ vectors $vd(v)_j$ are basis for $C^perp$.
]
#example[
Let $C subset.eq FF_5^7$ be linear code with generator-matrix $ G = mat(1, 2, 0, 3, 4, 0, 0; 0, 0, 1, 1, 2, 0, 3; 0, 0, 0, 0, 0, 1, 4) $ Then $L = {1, 3, 6}$.
- $v_2 = (3, 1, 0, 0, 0, 0, 0)$
- $v_4 = (2, 0, 4, 1, 0, 0, 0)$
- $v_5 = (1, 0, 3, 0, 1, 0, 0)$
- $v_7 = (0, 0, 2, 0, 0, 1, 1)$
- So generator matrix for $C^perp$ is $ H = mat(3, 1, 0, 0, 0, 0, 0; 2, 0, 4, 1, 0, 0, 0; 1, 0, 3, 0, 1, 0, 0; 0, 0, 2, 0, 0, 1, 1) $
]
== Check-matrices
#definition[
Let $C$ be $[n, k]_q$ code, assume there exists $H in M_(n - k, n)(FF_q)$ with linearly independent rows, such that $ C = {vd(v) in FF_q^n: vd(v) H^t = vd(0)} $ Then $H$ is *check-matrix* for $C$.
]
#proposition[
If code $C$ has generator-matrix $G$ and check-matrix $H$, then $C^perp$ has check-matrix $G$ and generator-matrix $H$.
]
#proof[
Use @dual-as-kernel to show $G$ is check-matrix for $C^perp$. Show rows of $H$ form basis for $C^perp$.
]
#remark[
We can use above algorithm for the $G <--> H$ algorithm: obtain a generator-matrix for $C$ from a check-matrix for $C$, or vice versa.
]
== Minimum distance from a check-matrix
#lemma[
Let $C$ be $[n, k]_q$ code, $C = {vd(x) in FF_q^n: vd(x) A^T = vd(0)}$ for some $A in M_(m, n) (FF_q)$. The following are equivalent:
- There are $d$ linearly dependent columns of $A$.
- $exists vd(c) in C: 0 < w(vd(c)) <= d$.
]
#proof[
- $==>$: use definition of linear dependence, construct a _word_ $vd(c)$ with $d$ at most non-zero symbols, based on the definition. Show that $vd(c) in C$.
- $<==$: use non-zero entries of $vd(c)$ as coefficients for linear dependence between $d$ corresponding columns of $A$.
]
#example[
Let $C = {vd(x) in FF_7^5: vd(x) A^T = vd(0)}$ where $ A = mat(3, 1, 1, 4, 1; 2, 2, 5, 1, 4; 6, 3, 5, 0, 2) in M_(3, 5)(FF_7) $ We have $(0, 1, 2, 0, 4) A^T = vd(0)$. So $(0, 1, 2, 0, 4) in C$, so $C$ has codeword of weight $3$. Also, $1 (1, 2, 3) + 2 (1, 5, 5) + 4 (1, 2, 4) = (0, 0, 0)$ so $A$ has $3$ linearly dependent columns.
]
#theorem[
Let $C = {vd(x) in FF_q^n: vd(x) A^T = vd(0)}$ for some $A in M_(m, n)(FF_q)$. Then there is a linearly dependent set of $d(C)$ columns of $A$, but any set of $d(C) - 1$ columns of $A$ is linearly independent.
So $d(C)$ is the smallest possible size of a set of linearly dependent columns of $A$.
]
#proof[
Use @min-dist-as-weight and above lemma.
]
= Polynomials and cyclic codes
== Non-prime finite fields
#theorem[
Let $f(x) in FF_q [x]$, then $FF_q [x] \/ ideal(f(x))$ is ring. $FF_q [x] \/ ideal(f(x))$ is field iff $f(x)$ irreducible in $FF_q [x]$.
]
#proposition[
If $f(x) = lambda m(x) in FF_q [x]$, with $0 != lambda in FF_q$, then $ FF_q [x] \/ ideal(f(x)) = FF_q [x] \/ ideal(m(x)) $ In particular, we only need to consider monic polynomials.
]
#definition[
$alpha in FF_q$ is *primitive* if $ FF_q^times = {alpha^j: j in {0, ..., q - 2}} $ Every finite field has a primitive element.
]
#definition[
Let $f(x) in FF_q [x]$ irreducible. If $x$ is primitive in $FF_q [x] \/ ideal(f(x))$, then $f(x)$ is *primitive polynomial* over $FF_q$.
]
#theorem[
Let $q = p^r$, $p$ prime, $r >= 2$ integer. Then there exists monic, irreducible $f(x) in FF_p [x]$ with $deg(f) = r$. In particular, $FF_q = FF_p [x] \/ ideal(f(x))$ is field with $q = p^r$ elements. Moreover, we can choose $f(x)$ to be primitive.
]
== Cyclic codes
#definition[
Code $C$ is *cyclic* if it is linear and $ (a_0, ..., a_(n - 1)) in C <==> (a_(n - 1), a_0, ..., a_(n - 2)) in C $ i.e. any cyclic shift of a codeword is also a codeword.
]
#notation[
Let $R_n = FF_q [x] \/ (x^n - 1)$. Note $R_n$ is not field. There is correspondence between elements in $R_n$ and vectors in $FF_q^n$: $ a(x) = a_0 + dots.h.c + a_(n - 1) x^(n - 1) <--> vd(a) = (a_0, ..., a_(n - 1)) $
]
#lemma[
If $a(x) <--> vd(a)$, then $x a(x) <--> (a_(n - 1), a_0, ..., a_(n - 2))$.
]<lem:cyclic-shift-polynomial>
#proposition[
$C subset.eq R_n$ is cyclic iff $C$ is ideal in $R_n$, i.e. $a(x), b(x) in C ==> a(x) + b(x) in C$ and $a(x) in C, r(x) in R_n ==> r(x) a(x) in C$.
]
#proof[
- $==>$: use linearity of $C$ and @lem:cyclic-shift-polynomial.
- $<==$: for linearity, use $r(x) = r_0$ constant. For cyclicity, use @lem:cyclic-shift-polynomial with $r(x) = x^m$.
]
#definition[
For $f(x) in R_n$, the *code generated by $f(x)$* is $ ideal(f(x)) := {r(x) f(x): r(x) in R_n} $
]
#proposition[
For any $f(x) in R_n$, $ideal(f(x))$ is cyclic code.
]
#example[
Let $R_3 = FF_2 [x] \/ (x^3 - 1)$, $f(x) = x^2 + 1 in R_3$. Then $ ideal(f(x)) = & {0, 1 + x, 1 + x^2, x + x^2} subset.eq R_3 \ <--> & {(0, 0, 0), (1, 1, 0), (1, 0, 1), (0, 1, 1)} subset.eq FF_2^3 $
]
#theorem[
Let $C$ cyclic code in $R_n$ over $FF_q$, $C != {0}$. Then
- There is unique monic polynomial $g(x)$ of smallest degree in $C$.
- $C = ideal(g(x))$.
- $g(x) | x^n - 1$.
]
#remark[
Converse of above theorem holds: every monic factor $g(x)$ of $x^n - 1$ is the unique generator polynomial of $ideal(g(x))$, so distinct factors generate distinct codes. So to find all cyclic codes in $R_n$, find each monic divisor $g(x)$ of $x^n - 1$ to give cyclic code $ideal(g(x))$.
]
#proof[
- First assume there are two such $g(x)$ which are different, obtain contradiction.
- Use division algorithm to show $C subset.eq ideal(g(x))$ and that $g(x) | x^n - 1$.
]
#remark[
If $C = {0}$, then setting $g(x) = x^n - 1$, we have $C = ideal(g(x))$.
]
#definition[
In cyclic code $C$, monic polynomial of minimal degree is the *generator-polynomial* of $C$.
]
#example[
To find all binary cyclic codes of block-length $3$, consider $R_3 = FF_2 [x]\/ideal(x^3 - 1)$. In $FF_2 [x]$, $x^3 - 1 = (x + 1)(x^2 + x + 1)$ and $x^2 + x + 1$ is irreducible. So the possible candidates for the generator-polynomial are
#figure(table(
columns: (auto, auto, auto),
"generator", [code in $R_3$], [code in $FF_2^3$],
$1$, $R_3$, $FF_2^3$,
$x + 1$, ${0, 1 + x, 1 + x^2, x + x^2}$, ${(0, 0, 0), (1, 1, 0), (1, 0, 1), (0, 1, 1)}$,
$x^2 + x + 1$, ${0, 1 + x + x^2}$, ${(0, 0, 0), (1, 1, 1)}$,
$x^3 - 1$, ${0}$, ${(0, 0, 0)}$
))
]
== Matrices for cyclic codes
#proposition[
If $C$ is cyclic code with generator-polynomial $g(x) = g_0 + dots.h.c + g_r x^r$, then $dim(C) = n - r$ and $C$ has generator-matrix $ G = mat(g_0, g_1, dots.h.c, g_r,0, dots.h.c, dots.h.c, 0; 0, g_0, g_1, dots.h.c, g_r, 0, dots.h.c, 0; 0, 0, g_0, g_1, dots.h.c, g_r, 0, dots.h.c; 0, dots.h.c, 0, dots.down, dots.down, dots.down, dots.down, dots.down; 0, dots.h.c, dots.h.c, 0, g_0, g_1, dots.h.c, g_r) in M_(n - r, n)(FF_q) $
]
#proof[
- Show $g_0 != 0$, use this to show rows are linearly independent.
- Show rows of $G$ span $C$ by using polynomial representation of $C$.
]
#example[
Let $C = {(0, 0, 0), (1, 1, 0), (0, 1, 1), (1, 0, 1)} in FF_2^3$. $C = ideal(1 + x)$ so $dim(C) = 3 - 1 = 2$, $ G = mat(1, 1, 0; 0, 1, 1) $
]
#definition[
Let $C subset.eq R_n$ be $[n, k]$ cyclic code with generator polynomial $g(x)$, let $g(x) h(x) = x^n - 1 in FF_q [x]$. Then $h(x)$ is the *check-polynomial* of $C$.
]
#lemma[
Check-polynomial of cyclic $[n, k]$ code is monic of degree $k$.
]
#proposition[
Let $C$ be cyclic code in $R_n$ with check-polynomial $h(x)$. Then $c(x) in C$ iff $c(x) h(x) = 0$ in $R_n$.
]<check-polynomial-for-containment>
#proof[
- $==>$: use that $C = ideal(g(x))$.
- $<==$: use division algorithm.
]
#definition[
The *reciprocal polynomial* of $h(x) = h_0 + h_1 x + dots.h.c + h_k x^k$ is $ overline(h)(x) = h_k + h_(k - 1) x + dots.h.c + h_0 x^k = x^k h(x^(-1)) $
]
#proposition[
Let $C$ cyclic $[n, k]$ code with check-polynomial $h(x) = h_0 + dots.h.c + h_k x^k$. Then
- $C$ has check-matrix $ H = mat(h_k, h_(k - 1), dots.h.c, h_0, 0, dots.h.c, dots.h.c, 0; 0, h_k, h_(k - 1), dots.h.c, h_0, 0, dots.h.c, 0; 0, 0, h_k, h_(k - 1), dots.h.c, h_0, 0, dots.h.c; 0, dots.h.c, 0, dots.down, dots.down, dots.down, dots.down, dots.down; 0, dots.h.c, dots.h.c, 0, h_k, h_(k - 1), dots.h.c, h_0) $
- $C^perp$ is cyclic and generated by $overline(h)(x)$ (i.e. $h_0^(-1) overline(h)(x)$ is generator-polynomial for $C^perp$).
]
#proof[
- Show that $H$ is generator matrix for $C^perp$:
- Show rows of $H$ are linearly independent.
- Show rows of $H$ are in $C^perp$:
- Let $c(x) in C$, use @check-polynomial-for-containment to show $c(x) h(x) = b(x) x^n - b(x)$ for some $b(x) in FF_q [x]$, $deg(b) <= k - 1$.
- Show that $overline(h)(x) | x^n - 1$ (hint: write $x^n = x^k x^(n - k)$).
- Show that if $overline(h)(x)$ monic, then $ideal(overline(h)(x))$ and $C^perp$ have a common generator-matrix.
- If $overline(h)(x)$ not monic, show that multiplying by $h_0$ is row operation, and so $ideal(overline(h)(x))$ and $C^perp$ have a common generator matrix.
]
= MDS and perfect codes
== Reed-Solomon codes
#notation[
Let $bold(P)_k = FF_q [z]_(<k)$ be vector space of polynomials of degree $< k$ in $FF_q$: $ FF_q [z]_(<k) = {a_0 + dots.h.c + a_(k - 1) z^(k - 1): a_i in FF_q} $ Dimension of $FF_q [z]_(< k)$ is $k$.
]
#definition[
Let $0 <= k <= n <= q$, $vd(a) = (a_1, ..., a_n)$, $vd(b) = (b_1, ..., b_n) in FF_q^n$ with all $a_j$ distinct and all $b_j$ non-zero. Define the linear map $ phi_(vd(a), vd(b)): bold(P)_k -> FF_q^n, quad phi_(vd(a), vd(b)) (f(z)) := (b_1 f(a_1), ..., b_n f(a_n)) in FF_q^n $ The *$q$-ary Reed-Solomon code* $"RS"_k (vd(a), vd(b))$ is the image of $phi_(vd(a), vd(b))$: $ "RS"_k (vd(a), vd(b)) = phi_(vd(a), vd(b))(bold(P)_k) subset.eq FF_q^n $
]
#proposition[
- $"RS"_k (vd(a), vd(b))$ is a $q$-ary $[n, k, n - k + 1]$ code. In particular, it is an MDS code.
- A generator-matrix for $"RS"_k (vd(a), vd(b))$ is $ G = \(b_j a_j^(i - 1)\)_(i, j) = mat(phi_(vd(a), vd(b))(1); dots.v; phi_(vd(a), vd(b))(z^(k - 1))) in M_(k, n)(FF_q) $ where $1 <= i <= k$, $1 <= j <= n$.
]
#proof[
- To show dimension is $k$, show that $phi_(vd(a), vd(b))$ is injective, by showing it has trivial kernel.
- To show minimum distance is $n - k + 1$, show for $f(z) != 0$ that $w(phi_(vd(a), vd(b))(z)) >= n - (k - 1)$.
- Use linearity and injectivity of $phi_(vd(a), vd(b))$ and fact that ${1, ..., z^(k - 1)}$ is basis for $bold(P)_k$ to show $G$ is generator-matrix for $"RS"_k (vd(a), vd(b))$.
]
#remark[
We have $ {0} = "RS"_0 (vd(a), vd(b)) subset "RS"_1 (vd(a), vd(b)) subset dots.c subset "RS"_n (vd(a), vd(b)) = FF_q^n $ (since a row is added to the generator matrix each time).
]
#example[
Let $q = 7$, $n = 5$, $k = 3$, $vd(a) = (0, 1, 6, 2, 3)$, $vd(b) = (5, 4, 3, 2, 1)$. Then $ phi_(vd(a), vd(b)): bold(P)_3 & -> FF_7^5, \ f(z) & |-> (5 f(0), 4 f(1), 3 f(6), 2 f(2), 1 f(3)) $ So a generator matrix for $"RS"_3 (vd(a), vd(b))$ is $ G = mat(5, 4, 3, 2, 1; 0, 4, 4, 4, 3; 0, 4, 3, 1, 2) $
]
#definition[
$alpha in FF_q$ is *primitive $n$-th root of unity* if $alpha^n = 1$ and $forall 0 < j < n$, $ alpha^j != 1$.
]
#proposition[
Let $alpha in FF_q$ primitive $n$-th root of unity, $m in ZZ$, define $ vd(a)^((m)) = ((alpha^0)^m, ..., (alpha^(n - 1))^m) in FF_q^n $ Then for $0 <= k <= n$, $"RS"_k (vd(alpha)^((1)), vd(alpha)^((m)))$ is cyclic.
]
#proof[
- Show cyclic permutation of $vd(alpha)^((m))$ is equivalent to multiplying by $alpha^(-m) in FF_q$.
- Show rows of generator matrix of $"RS"_k (vd(alpha)^((1)), vd(alpha)^((m)))$ has rows $vd(alpha)^((m + i - 1))$ for $1 <= i <= k$.
- Use linearity of a permutation to conclude result.
]
#example[
In $FF_5$, $2^1 = 2$, $2^2 = 4$, $2^3 = 3$, $2^4 = 1$ so $2$ is primitive $4$th root of unity in $FF_5$ so $vd(alpha)^m = (1^m, 2^m, 4^m, 3^m)$. We have $vd(alpha)^((1)) = (1, 2, 4, 3)$, $vd(alpha)^((2)) = (1, 4, 1, 4)$, so a generator matrix for $"RS"_2 (vd(alpha)^((1)), vd(alpha)^((2)))$ is $ G = mat(1, 4, 1, 4; 1, 3, 4, 2) $ By performing ERO's, we obtain another generator matrix $ G' = mat(3, 1, 1, 0; 0, 3, 1, 1) $ This is generator matrix for the cyclic code with generator polynomial $g(x) = (x - 1)(x - 3) = x^2 + x + 3$. So $"RS"_2 (vd(alpha)^((1)), vd(alpha)^((2)))$ is cyclic with generator polynomial $g(x)$. Note $x^4 - 1 = (x - 1)(x - 2)(x - 3)(x - 4)$ so $g(x) | x^4 - 1$.
]
#proposition[
For $vd(a), vd(b)in FF_q^n$ with $a_j$ all distinct and $b_j$ all non-zero,
- There exists $vd(c)$ with all $c_j != 0$ such that for $1 <= k <= n - 1$, $ ("RS"_k (vd(a), vd(b)))^perp = "RS"_(n - k)(vd(a), vd(c)) $
- $vd(c)$ is given by the $1 times n$ check-matrix for $"RS"_(n - 1)(vd(a), vd(b))$.
]
#proof[
- First consider $k = n - 1$. Let $vd(c)$ be the $1 times n$ check-matrix for $"RS"_(n - 1)(vd(a), vd(b))$.
- Use that $"RS"_(n - 1)(vd(a), vd(b))$ saturates singleton bound to show all $c_j != 0$, and so that $"RS"_1 (vd(a), vd(c))$ and $("RS"_(n - 1)(vd(a), vd(b)))^perp$ share a generator matrix (so are the same code).
- $forall f(z) in bold(P)_(n - 1)$, since $phi_(vd(a), vd(b)) (f(z)) in "RS"_(n - 1)(vd(a), vd(b))$, and $vd(c)$ is check-matrix for $"RS"_(n - 1)(vd(a), vd(b))$, $ phi_(vd(a), vd(b)) (f(z)) dot vd(c) = 0 $
- Since $dim("RS"_(n - k)(vd(a), vd(c))) = n - k = dim\(("RS"_k (vd(a), vd(b)))^perp\)$, enough to show $"RS"_(n - k)(vd(a), vd(c)) subset.eq ("RS"_k (vd(a), vd(b)))^perp$:
- By considering degrees, show that for $g(z) in bold(P)_k$ and $g(z) in bold(P)_(n - k)$, $(f g)(z) in bold(P)_(n - 1)$. Deduce that $phi_(vd(a), vd(c))(g(z)) dot phi_(vd(a), vd(b))(f(z)) = 0$.
]
== Hamming codes
#definition[
Let $r >= 2$, $n = 2^r - 1$, let $H in M_(r, n)(FF_2)$ have columns corresponding to all non-zero vectors in $FF_2^r$. The *binary Hamming code of redundancy $r$* is $ "Ham"_2 (r) = {vd(x) in FF_2^n: vd(x) H^t = vd(0)} $ Note the order of columns is not specified, so we have a collection of permutation-equivalent codes.
]
#example[
For $r = 2, 3$, we can take $ H_2 = mat(0, 1, 1; 1, 0, 1), quad H_3 = mat(0, 0, 0, 1, 1, 1, 1; 0, 1, 1, 0, 0, 1, 1; 1, 0, 1, 0, 1, 0, 1) $
]
#proposition[
For $r >= 2$, $"Ham"_2 (r)$ is perfect $[2^r - 1, 2^r - r - 1, 3]$ code with check-matrix $H$.
]
#proof[
- $n = 2^r - 1$: count rows in $H^t$.
- To show $H$ is check-matrix, verify its rows are linearly independent by considering its column rank.
- $k = 2^r - r - 1$: $k = n - "number of rows of" H$.
- $d = 3$: use criterion of minimum distance from linearly (in)dependent columns. No column is multiple of another, but columns $vd(e_1), vd(e_2)$ and $vd(e_1) + vd(e_2)$ are linearly dependent.
- $"Ham"_2 (r)$ is perfect: we have $|"Ham"_2 (r)| = 2^k = 2^(2^r - r - 1)$, $t = floor((d - 1)/2) = 1$. $|S(c, 1)| = 1 + n = 2^r$ and the $S(c, 1)$ are disjoint, so $|union_(c in C) S(c, 1)| = 2^(2^r - r - 1) dot 2^r = 2^n$.
]
#definition[
Can define Hamming codes for $q > 2$. Consider $FF_q^r$ for $r >= 2$. $vd(v), vd(w) in FF_q^r - {0}$ are *equivalent* if $vd(v) = lambda dot vd(w)$ for some $lambda in FF_q^times$. For $vd(v) in FF_q^r - {0}$, set $ L_(vd(v)) = {vd(w) in FF_q^r: vd(w) "equivalent to" vd(v)} = {lambda vd(v): lambda in FF_q^times} $ Note $|L_(vd(v))| = q - 1$ and $w in L_(vd(v))$ iff $L_(vd(w)) = L_(vd(v))$. Also, if $L_(vd(v)) != L_(vd(w))$ then $L_(vd(v)) sect L_(vd(w)) = emptyset$. Hence the $L_(vd(v))$ partition $FF_q^r - {0}$ and there are $(q^r - 1)\/(q - 1)$ of them.
]
#example[
For $q = 3$, $r = 2$ there are $(3^2 - 1)\/(3 - 1) = 4$ sets: $ L_((0, 1)) & = {(0, 1), (0, 2)}, quad L_((1, 0)) & = {(1, 0), (2, 0)}, \ L_((1, 1)) & = {(1, 1), (2, 2)}, quad L_((1, 2)) & = {(1, 2), (2, 1)} $
]
#definition[
For $r >= 2$, $n = (q^r - 1)\/(q - 1)$, construct $H in M_(r, n)(FF_q)$ by taking one column from each of the $n$ different $L_v$. The *Hamming code of redundancy $r$* is $ "Ham"_q (r) = {vd(x) in FF_q^n: vd(x) H^t = vd(0)} $ Note that different choices of $H$ give monomially equivalent codes.
]
#example[
For $"Ham"_3 (2)$, we can choose e.g. $ H = mat(0, 2, 2, 2; 1, 2, 0, 1) quad "or" quad H = mat(2, 1, 2, 0; 1, 1, 0, 1) $
]
#proposition[
For $r >= 2$, $"Ham"_q (r)$ is perfect $[n, n - r, 3]$ code, with check-matrix $H$.
] |
|
https://github.com/El-Naizin/cv | https://raw.githubusercontent.com/El-Naizin/cv/main/modules_zh/certificates.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("证书")
#cvHonor(
date: [2022],
title: [AWS 安全认证],
issuer: [亚马逊网络服务 (AWS)],
)
#cvHonor(
date: [2017],
title: [应用数据科学与 Python],
issuer: [Coursera]
)
#cvHonor(
date: [],
title: [SQL 基础课程],
issuer: [Datacamp]
)
|
https://github.com/qujihan/toydb-book | https://raw.githubusercontent.com/qujihan/toydb-book/main/README.md | markdown | <div align="center">
<strong>
<samp>
</samp>
</strong>
</div>
# WIP. 从零开始的分布式数据库生活
[](https://github.com/qujihan/toydb-book/actions/workflows/build.yml)
[](https://nightly.link/qujihan/toydb-book/workflows/build/main/from_zero_to_distributed_database.pdf.zip)
# 编译本书
所需组件
- python(tqdm, requests)
- [typst](https://typst.app/)
- [typstyle]()
```shell
git clone https://github.com/qujihan/toydb-book.git
# 下载依赖
cd toydb-book && git submodule update --init --recursive
pip install requests # 下载字体使用
pip install tqdm # 为了下载界面好看一点
# 下载所需字体
# 与 python3 ./typst-book-template/fonts/download.py --proxy 相同
make font
# 编译
# 与 python3 ./typst-book-template/op.py c 相同
make c
```
## TODO
正在把理解理成书中....
- 存储引擎
- [√] Bitcask存储引擎
- [√] MVCC
- 共识算法 Raft
- [☓] Message
- [☓] Node
- [☓] Log
- SQL引擎
- [√] Type
- [☓] Engine
- [☓] Parse
- [☓] Planner
- [☓] Execution
- [☓] 编码
# 一些推广
- [typst](https://typst.app/): 全新的排版工具
- [typst-book-template](https://github.com/qujihan/typst-book-template): typst生成书籍的模板, 本书使用的模板(为了本书专门写的, 后来改造成了一个模板) |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/if-05.typ | typst | Other | // Make sure that we don't complain twice.
// Error: 5-12 cannot add integer and string
#if 1 + "2" {}
|
https://github.com/hnlinzhi19/typst_tpm | https://raw.githubusercontent.com/hnlinzhi19/typst_tpm/main/project.typ | typst | #import "tpl.typ": *
#show: project.with(
title: "项目管理笔记",
authors: (
"木木",
),
abstract: "学习笔记",
)
#pagebreak()
= 项目一般知识
- 项目
- 组织
- 生命周期
#pagebreak()
== 项目
#cannotes(
question: [
什么是项目?
项目有什么特点?
项目目标有什么?
],
notes: [
项目第三方
地方撒的
],
summarize: [
项目是一系列的活动的集合
项目管理是一系列的活动
]
)
#pagebreak()
= 模版简介
SimplePaper 是 Typst 的模版,用于生成简单的论文。
= 使用说明
模版默认使用的字体包括 "FZShuSong-Z01", "FZXiaoBiaoSong-B05", "FZHei-B01", "FZKai-Z03", "DejaVu Sans Mono",如果你在本地编译,需要在方正官网安装这些字体。
如果你的系统没有安装这些字体或想更换其他字体,你需要在模版中修改字体。
我们提供了一个 Typst 的#link("https://typst.app/project/rTNVUul26WZq12qs3kbD25")[在线模板],你可以复制这个模板到你的工作区后在线编辑。*注意:由于模版包括了上述的字体文件,模板的大小可能较大。*
= 使用示例 <example>
== 特殊标记 <bug1>
你可以 Typst 的语法对文本进行特殊标记,我们为如下标记设定了样式:
+ *突出*
+ _强调_
+ 引用 @example
+ `raw text`
=== 注意事项
由于 Typst 的语法, 如果你使用 `*本文*` 来标记突出,那么你需要在 `*` 前面加上一个空格,但这会导致你 *突出的文本* 前后附带一个空格,如果你#strong("不想要这个空格"),你可以使用 `#strong("本文")` 来代替。
在列表中使用 raw text 可能会导致不正确的显示,如 @bug1 中的列表。
raw text 中的中文字体可能较小,这是因为 Typst 无法为不同的中英文字体设置不同的字号,所以我们将中英文的字体设置为了相同的字号,这对于英文来说是合适的,但对于中文来说可能不合适。如`raw text: English 中文`。
== 图片
我们为图片标题默认设置了 "FZKai-Z03" 字体,效果如@img 如果你想要使用其他字体,你可以自行修改模版。
#figure(image("sample.svg"),
caption: [
示例图片
],
)<img>
== 表格
#figure(
table(
columns: (auto, 1fr, 1fr, 1fr),
inset: 10pt,
align: start + top,
[过程], [输入], [工具与技术],[输出],
[
测试
],
[
dsafd \
dsafd \
],
[
dd \
],
[
ds
],
),
caption: "过程"
)
#figure(
table(
columns: (auto, 1fr, 1fr, 1fr, 1fr, 1fr),
inset: 10pt,
align: horizon,
[], [周一], [周二],[周三],[周四],[周五],
"早上", "编译原理", "操作系统", "计算机网络", "操作系统", "计算机网络",
"下午", "数据挖掘", "计算机网络", "操作系统", "计算机网络", "分布式系统"
),
caption: "示例表格"
)
== 代码
我们为代码添加了如下简单的样式。
```c
#include <stdio.h>
int main()
{
// printf() 中字符串需要引号
printf("Hello, World!");
return 0;
}
```
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.0.1/path-util.typ | typst | Apache License 2.0 | // This file contains utility functions for path calculation
#import "util.typ"
#import "vector.typ"
#let default-samples = 25
#let ctx-samples(ctx) = ctx.at("samples", default: default-samples)
/// Get first position vector of a path segment
///
/// - s (segment): Path segment
/// -> vector
#let segment-begin(s) = {
return s.at(1)
}
/// Get last position vector of a path segment
///
/// - s (segment): Path segment
/// -> vector
#let segment-end(s) = {
if s.at(0) == "line" {
return s.last()
}
return s.at(2)
}
/// Calculate bounding points for a list of path segments
///
/// - segments (array): List of path segments
/// -> array: List of vectors
#let bounds(segments) = {
let samples = default-samples
let bounds = ()
for s in segments {
let type = s.at(0)
if type == "line" {
bounds += s.slice(1)
} else if type == "quadratic" {
let (a, b, c) = s.slice(1)
bounds.push(a)
bounds.push(b)
bounds += range(1, samples).map(x =>
util.bezier-quadratic-pt(a, b, c, x / samples))
} else if type == "cubic" {
let (a, b, c, d) = s.slice(1)
bounds.push(a)
bounds.push(b)
bounds += range(1, samples).map(x =>
util.bezier-cubic-pt(a, b, c, d, x / samples))
}
}
return bounds
}
/// Calculate length of a single path segment
///
/// - s (array): Path segment
/// -> float: Length of the segment in canvas units
#let segment-length(s) = {
let samples = default-samples
let type = s.at(0)
let pts = ()
if type == "line" {
pts = s.slice(1)
} else if type == "quadratic" {
let (a, b, c) = s.slice(1)
pts.push(a)
pts = range(1, samples).map(t =>
util.bezier-quadratic-pt(a, b, c, t / samples))
pts.push(b)
} else if type == "cubic" {
let (a, b, c, d) = s.slice(1)
pts.push(a)
pts = range(1, samples).map(t =>
util.bezier-cubic-pt(a, b, c, d, t / samples))
pts.push(b)
} else {
panic("Not implemented")
}
let l = 0
let pt = pts.at(0)
for i in range(1, pts.len()) {
l += vector.len(vector.sub(pts.at(i), pt))
pt = pts.at(i)
}
return l
}
/// Find point at position on polyline segment
///
/// - s (array): Polyline path segment
/// - t (float): Position (0 to 1)
/// -> vector: Position on the polyline
#let point-on-polyline(s, t) = {
if t == 0 {
return s.at(1)
} else if t == 1 {
return s.last()
}
let l = segment-length(s)
if l == 0 {
return s.at(1)
}
let dist = (a, b) => {
vector.len(vector.sub(b, a))
}
let traveled-length = 0
for i in range(2, s.len()) {
let part-length = dist(s.at(i - 1), s.at(i))
if traveled-length / l <= t and (traveled-length + part-length) / l >= t {
let f = (t - traveled-length / l) / (part-length / l)
return vector.add(
s.at(i - 1),
vector.scale(vector.sub(s.at(i), s.at(i - 1)), f))
}
traveled-length += part-length
}
return s.at(1)
}
/// Get position on path segment
///
/// - s (segment): Path segment
/// - t (float): Position (from 0 to 1)
/// -> vector: Position on segment
#let point-on-segment(s, t) = {
let type = s.at(0)
if type == "line" {
return point-on-polyline(s, t)
} else if type == "quadratic" {
let (a, b, c) = s.slice(1)
return util.bezier-quadratic-pt(a, b, c, t)
} else if type == "cubic" {
let (a, b, c, d) = s.slice(1)
return util.bezier-cubic-pt(a, b, c, d, t)
}
}
/// Get the length of a path
///
/// - segments (array): List of path segments
/// -> float: Total length of the path
#let length(segments) = {
return segments.map(segment-length).sum()
}
/// Get position on path
///
/// - segments (array): List of path segments
/// - t (float): Poisition (from 0 to 1)
/// -> vector: Position on path
#let point-on-path(segments, t) = {
if segments.len() == 1 {
return point-on-segment(segments.first(), t)
}
let l = length(segments)
let traveled-length = 0
for s in segments {
let part-length = segment-length(s)
if traveled-length / l <= t and (traveled-length + part-length) / l >= t {
let f = (t - traveled-length / l) / (part-length / l)
return point-on-segment(s, f)
}
traveled-length += part-length
}
}
/// Get position and direction on path
///
/// - segments (array): List of path segments
/// - t (float): Position (from 0 to 1)
/// - scale (float): Scaling factor
/// -> tuple: Tuple of the point at t and the scaled direction
#let direction(segments, t, scale: 1) = {
let scale = scale
let (pt, dir) = (t, t + .001)
// if at end, use something < 1
if t >= 1 {
dir = t - .001
} else {
scale *= -1
}
let (a, b) = (
point-on-path(segments, pt),
point-on-path(segments, dir)
)
return (a, vector.scale(vector.norm(vector.sub(b, a)), scale))
}
|
https://github.com/darioglasl/Arbeiten-Vorlage-Typst | https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/Anhang/03_Projektplan/02_risikomanagement.typ | typst | === Risiko Management
Für das Projekt werden verschiedene Risiken identifiziert, die in der folgenden Matrix kategorisiert werden. Links ist die Eintrittswahrscheinlichkeit und oben die Auswirkung aufgeführt. Anschliessend werden die einzelnen Risiken beschrieben, sowie die Massnahmen, die ergriffen werden, um das Risiko zu minimieren. Nach jedem Sprint wird ausgewertet, ob die Risiken eingetreten sind und sie sich in der Matrix verschoben haben.
#figure(
table(
columns: (auto, auto, auto, auto, auto, auto),
fill: (col, row) => {
if col == 0 or row == 0 {white}
else if (col == 1 and row >= 1 and row <= 3) or (col == 2 and (row == 1 or row == 2)) or (col == 3 and row == 1) {rgb(52, 173, 12)}
else if (col == 1 and row == 4) or (col == 2 and row == 3) or (col == 3 and row == 2) or (col == 4 and row == 1) {rgb(134, 217, 67)}
else if (col == 1 and row == 5) or (col == 2 and row == 4) or (col == 3 and row == 3) or (col == 4 and row == 2) or (col == 5 and row == 1) {yellow}
else if (col == 2 and row == 5) or (col == 3 and row == 4) or (col == 4 and row == 3) or (col == 5 and row == 2) {rgb(245, 148, 12)}
else if (col == 3 and row == 5) or (col == 4 and row == 4) or (col == 5 and row == 3) or (col == 4 and row == 5) or (col == 5 and row == 4) or (col == 5 and row == 5) {rgb(224, 29, 29)}
else {white}
},
[], [*Niedrig*], [*Mittel*], [*Hoch*], [*Sehr hoch*], [*Kritisch*],
[*Unmöglich*], [], [], [], [], [],
[*Unwahrscheinlich*], [R1], [], [], [], [],
[*Möglich*], [], [], [], [], [],
[*Wahrscheinlich*], [], [], [], [], [],
[*Sehr wahrscheinlich*], [], [], [], [], [],
),
caption: "Risikomatrix zu Beginn des Projektes",
)
#figure(
table(
columns: (auto, auto),
align: left,
[*Nummer*], [R1],
[*Risiko*], [Panzerknacker überfallen Tresor],
[*Auswirkung*], [Ganzes Geld ist weg],
[*Massnahmen*], [Gute Fallen und Verteidigung aufstellen],
),
caption: "Risiko 1: Tresor wird von Panzerknacker überfallen",
)
==== Update nach Sprint 1
|
|
https://github.com/piepert/philodidaktik-hro-phf-ifp | https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/grundpositionen/thesen.typ | typst | Other | #import "/src/template.typ": *
== #ix("Abbilddidaktik"), #ix("Konstitutionsthese") und #ix("Transformationsthese")
#table(columns: (33.33%, 33.33%, 33.33%),
stroke: none,
strong(ix("Abbilddidaktik")),
strong(ix("Konstitutionsthese")),
strong(ix("Transformationsthese")),
[
Die Philosophie ist ein #ix("akademisches Fach", "Fach, akademisch"), Philosophieunterricht versucht dieses Fach in der Schule abzubilden. Daher braucht die Philosophie keine Didaktik und wird durch sie verfälscht. Ein #ix("Vermittlungsproblem") gibt es nicht, denn die Philosophie muss nicht vermittelt werden.
], [
Die Didaktik wird als konstitutiv#en[konstitutiv: für einen Sachverhalt grundlegend oder notwendig anzusehen] für Philosohie angesehen. Ohne Didaktik ist Philosophie nicht möglich, didaktische Konzepte sind notwendig für das Philosophieren, wie z.B. das Konzept des #ix("Dialogs", "Dialog") bei Platon. Philosophiedidaktik muss selbst philosophisch sein.
], [
Philosophie und Didaktik sind verschieden. Philosophie soll durch die Didaktik nicht reduziert werden, sondern die Methoden, mit denen philosophiert wird, soll zu den Methoden des Philosophieunterrichts werden. Es soll kein #ix("P4C")#en[P4C: philosophy for children, auch "#ix("PfK")"#en-note("pfk-en")]#en-content("pfk-en")[#ix("PwC"): auch #ix("PmK"), philosophy with children] stattfinden, sondern ein #ix("PwC")#en[PwC: philosophy with children, auch "PmK"#en-note("pmk-en")]#en-content("pmk-en")[PmK: Philosophieren mit Kindern].
],
[
#set par(justify: false)
#text(fill: color-orange, [$=>$ Didaktik ist irrelevant für Philosophie])
], [
#set par(justify: false)
#text(fill: color-orange, [$=>$ Didaktik ist notwendig für Philosophie])
], [
#set par(justify: false)
#text(fill: color-orange, [$=>$ Didaktik und Philosophie ergänzen sich])
])
// Die Methoden, die im KÜK vorgestellt werden, machen sich also der #strong(ix("Transformationsthese")) zu Nutze. So ist z.B. das #ix("Gedankenexperiment") eine philosophische Methode und wird auch im Unterricht benutzt, um den Kindern nicht _Philosophie_ (#ix("P4C")) beizubringen, sondern sie zum _Philosophieren_ (#ix("PwC")) zu bringen. Im Gegensatz zur #strong(ix("Konstitutionsthese")) stellt sie jedoch nicht die Didaktik über die Philosophie, aber auch in ihr werden die Methoden der Philosophie zu den Methoden des Philosophieunterrichts, da beide überhaupt nicht getrennt werden können.#todo[Ist die Konstitutionsthese eine extreme Form der Transformationsthese? Lässt sich das "die Methoden der Philosophie werden zu den Methoden des Philosophieunterrichts" tatsächlich auch auf die Konstitutionsthese anwendbar?] |
https://github.com/QQKdeGit/bupt-typst | https://raw.githubusercontent.com/QQKdeGit/bupt-typst/master/main.typ | typst | MIT License | #import "template.typ": *
#show: BUPTBachelorThesis.with(
titleZH: "这是一个本科毕业设计的中文标题",
abstractZH: [
中文摘要。
那只敏捷的棕毛 fox 跳过那只懒狗,消失得无影无踪。
那只敏捷的棕毛狐狸 jumps over 那只懒狗,消失得无影无踪。
思源宋体也和它的兄弟字体思源黑体一样针对屏幕显示进行了优化,但前者具有截然不同的风格,适合用于文学性较强的文本或优雅、时尚的标题。它的打印效果也非常优美。
],
keywordsZH: ("北京邮电大学", "本科生", "毕业设计", "模板", "示例"),
titleEN: "This is English Title",
abstractEN: [
English Abstract.
The quick brown fox jumps over the lazy dog and runs away. The quick brown fox jumps over the lazy dog and runs away. The quick brown fox jumps over the lazy dog and runs away.
],
keywordsEN: ("BUPT", "undergraduate", "thesis", "template", "example"),
)
// 正文
= 基础模块
我认为 Typst 介于 LaTeX 和 Markdown 之间。在你开始使用这个模板之前,你可以对 LaTeX 不那么熟悉,但确保你对 Markdown 有一定了解,并且我建议学习一下如何使用 Typst 。
== 段落示例
二级标题和三级标题的段前和段后都增加了 0.5 行间距。如果二级标题和三级标题之间没有内容,两者的间距会直接叠加,而不是像 Word 那样自动设置。
=== 三级标题
=== 另一个三级标题
我是标题下的第一个段落。我前面没有缩进。
我上面的段落没有 2 个全角空格的缩进,但是我有。我也不知道为什么。
=== 最后一个三级标题
#h(2em)
我也是标题下的第一个段落,但是我前面有缩进,因为我的上一行有一个函数。
== 图示例
这是一幅图。
#Figure(
"images/Apple-Shenzhen.jpg",
[Apple 深圳万象城零售店],
80%
)
== 表格示例
#Table(
"北京邮电大学历年录取分数线",
(auto, auto, auto, auto, auto),
horizon,
(
[*年份*], [*录取批次*], [*招生类型*], [*最低分/最低位次*], [*省控线*],
[2018], [本科一批], [普通类], [649/2469], [532],
[2017], [本科一批], [普通类], [635/2548], [537],
[2016], [本科一批], [宏福校区], [621/--], [548],
[2015], [本科一批], [普通类], [646/2499], [548],
[2014], [本科一批], [普通类], [--/--], [548],
)
)
这是一张表。注意到了吗?这里并没有自动段首空格,因为我们还在上一段里。要想在后面开启新的一段,需要自己手动输入换行符“\\”。后面没有空格的原理是一样的。
== 公式示例
下方是一个简单的求圆的面积的公式:
$ S = pi r^2 $
语法跟 Markdown 很像,比较容易上手。
== 引用示例
这是一个参考文献 @cn_ref 的引用 @webster_social_media 。
== 代码示例
这是一段用示例代码。
```cpp
void setFib(void)
{
fib(1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 | 89, 10);
}
```
Typst 还支持书写行内的代码,就像 Markdown 一样,比如 `return n * f(n - 1)` 。
// 附页
#show: Appendix.with(
bibliographyFile: "reference.yml"
)
#pagebreak()
#primary_heading([= 致#h(2em)谢])
谢谢你北邮,因为有你,温暖了四季。
#pagebreak()
#primary_heading([= 附#h(2em)录])
#set heading(outlined: false)
== 附录 1
这是一个附录内容,学校规定附录的二级标题得是“附录”二字后接阿拉伯数字。
但是 Typst 的中文与英文和数字之间的空格并没有像 LaTeX 那样自动空出,所以就需要自己手打了。
#set page(footer: none)
#pagebreak()
#primary_heading([= 外#h(1em)文#h(1em)资#h(1em)料])
#pagebreak()
#primary_heading([= 外#h(1em)文#h(1em)译#h(1em)文])
|
https://github.com/chendaohan/bevy_tutorials_typ | https://raw.githubusercontent.com/chendaohan/bevy_tutorials_typ/main/11_transform/transform.typ | typst | #set page(fill: rgb(35, 35, 38, 255), height: auto, paper: "a3")
#set text(fill: color.hsv(0deg, 0%, 90%, 100%), size: 22pt, font: "Microsoft YaHei")
#set raw(theme: "themes/Material-Theme.tmTheme")
= 1. Transform 变换
Transform 允许你将对象放置到游戏世界中。它是对象的“平移”(位置/坐标)、“旋转”和“缩放”的组合。
你可以通过修改 translation 来移动对象,通过修改 rotation 来旋转对象,通过修改 scale 来缩放对象。
```Rust
fn transform_red_rectangle(
mut right: Local<bool>,
mut rectangle: Query<&mut Transform, With<RedRectangle>>,
time: Res<Time>,
) {
let Ok(mut transform) = rectangle.get_single_mut() else {
return;
};
// 平移方向
if transform.translation.x < -300. {
*right = false;
} else if transform.translation.x > 300. {
*right = true;
}
// 平移和缩放
let velocity = Dir3::X * 200. * time.delta_seconds();
let scale = time.delta_seconds() / 3.;
if *right {
transform.translation -= velocity;
transform.scale -= scale;
} else {
transform.translation += velocity;
transform.scale += scale;
}
// 旋转
transform.rotate_z(time.delta_seconds());
}
```
= 2. Transform 组件
在 Bevy 中,变换由两个组件表示:Transform 和 GlobalTransform。
任何代表游戏世界中对象的实体都需要有这两个组件。如果你要创建自定义实体,可以使用 TransformBundle 来同时添加这两个组件,当然你也可以分别添加 Transform 和 GlobalTransform。
```Rust
commands.spawn((
Mesh2dHandle(meshes.add(Capsule2d::new(40., 100.))),
materials.add(Color::Srgba(css::BLUE)),
TransformBundle {
local: Transform::from_xyz(0., -120., 0.),
global: GlobalTransform::default(),
},
VisibilityBundle::default(),
Name::new("Blue Capsule 2d"),
));
```
== 2.1 Transform
Transform 是你经常使用的内容。它是一个包含平移、旋转和缩放的 struct 。要读取或操作这些值,请使用查询从你的系统访问它。
如果实体有父级,则 Transform 组件是相对于父级的。这意味着子对象将与父对象一起移动/旋转/缩放。
```Rust
let circle = commands
.spawn((
MaterialMesh2dBundle {
mesh: Mesh2dHandle(meshes.add(Circle::new(50.))),
material: materials.add(Color::Srgba(css::ORANGE)),
transform: Transform::from_xyz(220., 0., 0.),
..default()
},
OrangeCircle,
Name::new("Orange Circle"),
))
.id();
commands
.spawn((
MaterialMesh2dBundle {
mesh: Mesh2dHandle(meshes.add(Rectangle::new(300., 150.))),
material: materials.add(Color::Srgba(css::RED)),
transform: Transform::from_xyz(0., 185., 0.),
..default()
},
RedRectangle,
Name::new("Red Rectangle"),
))
.add_child(circle);
```
== 2.2 GlobalTransform
GlobalTransform 是相对于全局空间的,如果实体没有父级,Transform 与 GlobalTransform 相等。
GlobalTransform 的值由 Bevy (“变换传播”)在内部计算/管理的。
与 Transform 不同,平移/旋转/缩放不能直接访问。数据以优化的方式存储(使用 Affine3A),并且可以在层次结构中进行无法表示为简单变换的复杂变换。
如果你想尝试将 GlobalTransform 转换回可用的平移/旋转/缩放表示,你可以尝试以下方法:
- .translation()
- .to_scale_rotation_translation()
- .compute_transform()
= 3. Transform 传播
这两个组件由一组内部系统(“变换传播系统”)同步,该系统在 PostUpdate Schedule 中运行。
注意:当你改变 Transform 时,GlobalTransform 不会立即更新。在变化传播系统运行之前,它们将不会同步。
如果你需要直接使用 GlobalTransform。你应该将你的系统添加到 PostUpdate Schedule 中,并在 TransformSystem::TransformPropagate 之后进行排序。
```Rust
.add_systems(
PostUpdate,
circle_global_transform_info
.after(TransformSystem::TransformPropagate),
)
``` |
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Maths_Devoir_Maison_4.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Maths Devoir Maison 4",
authors: (
"<NAME>",
),
date: "4 Décembre, 2023",
)
#set heading(numbering: "1.1.")
== Rédacteur <NAME>
<rédacteur-lucas-duchet-annez>
== Exercice 1
<exercice-1>
=== Partie A
<partie-a>
On sait que $lr((C f))$ admet deux asymptotes d’équations $x eq 1$ et
$x eq minus 1$ cela veut dire que $f$ n’est pas définie quand $x eq 1$
ou $x eq minus 1$ or f est une fonction rationnelle définie tant que son
dénominateur est différent de 0 soit quand $x^2 minus c eq.not 0$ Donc
$c eq lr((1))^2$ ou $c eq lr((minus 1))^2$ soit $c eq 1$.
$ f lr((x)) minus lr((x plus 2)) eq frac(a x^3 plus b x^2, x^2 minus 1) minus x minus 2 $
$ eq frac(lr((a minus 1)) x^3 plus lr((b minus 2)) x^2 plus x plus 2, x^2 minus 1) $
$ eq frac(x^3 lr((a minus 1 plus frac(b minus 2, x) plus 1 / x^2 plus 2 / x^3)), x^2 lr((1 minus 1 / x^2))) $
$ eq x frac(a minus 1 plus frac(b minus 2, x) plus 1 / x^2 plus 2 / x^3, 1 minus 1 / x^2) $
On sait que $l i m_(x arrow.r plus oo) 1 / x^k eq 0$ donc
$l i m_(x arrow.r plus oo) a minus 1 plus frac(b minus 2, x) plus 1 / x^2 plus 2 / x^3 eq a minus 1$
et $l i m_(x arrow.r plus oo) 1 minus 1 / x^2 eq 1$ De plus
$l i m_(x arrow.r plus oo) x eq plus oo$ Donc
$l i m_(x arrow.r plus oo) f lr((x)) minus lr((x plus 2)) eq l i m_(x arrow.r plus oo) x lr((a minus 1)) eq 0$
Pour que la limite soit 0 il faut que $a minus 1 eq 0$ soit $a eq 1$
Finalement On peut noter
$ f lr((x)) minus lr((x plus 2)) eq x frac(1 minus 1 plus frac(b minus 2, x) plus 1 / x^2 plus 2 / x^3, 1 minus 1 / x^2) $
$ eq frac(frac(b minus 2, plus) 1 / x plus 2 / x^2, 1 minus 1 / x^2) $
A nouveau $1 / x$ et $1 / x^2$ tendent vers $0$ lorsque $x$ tend vers
$plus oo$. Par conséquent on obtient
$l i m_(x arrow.r plus oo) f lr((x)) minus lr((x plus 2)) eq l i m_(x arrow.r plus oo) b minus 2 eq 0$
Donc $b eq 2$
=== Partie B
<partie-b>
+ Pour étudier les variations de $g$ on analyse le signe de sa dérivée.
$g prime lr((x)) eq 3 x^2 minus 3$ $g prime lr((x)) gt 0$
$3 x^2 minus 3 gt 0$ $x^2 gt 3 / 3$ $x^2 gt 1$ $x gt 1$ ou
$x lt minus 1$
Pour calculer les limites de $g$ on factorise par le terme prépondérant.
$g lr((x)) eq x^3 lr((1 minus 3 / x^2 minus 4 / x^3))$ On sait que
$lim_(x arrow.r plus oo) 1 / x^k eq 0$ donc
$lim_(x arrow.r plus oo) 1 minus 3 / x^2 minus 4 / x^3 eq 1$ et
$lim_(x arrow.r plus oo) x^3 eq plus oo$. Par conséquent
$lim_(x arrow.r plus oo) g lr((x)) eq plus oo$ et de manière analogue
$lim_(x arrow.r minus oo) g lr((x)) eq minus oo$ On en déduit
#align(center)[#table(
columns: 8,
align: (col, row) => (auto,auto,auto,auto,auto,auto,auto,auto,).at(col),
inset: 6pt,
[x], [-∞], [], [-1], [], [1], [], [+∞],
[signe de g’(x)],
[],
[+],
[0],
[-],
[0],
[+],
[],
[var de g],
[-∞],
[➚],
[g(-1)\=-2],
[➘],
[g(1)\=-6],
[➚],
[+∞],
)
]
#block[
#set enum(numbering: "1.", start: 2)
+ #block[
#set enum(numbering: "a.", start: 1)
+ On peut étudier chaque intervalle à l’aide du théorème des valeurs
intermédiaires. Premièrement g est une fonction polynomiale donc
définie et dérivable sur $bb(R)$, par conséquent g est une fonction
continue sur $bb(R)$. Sur l’intervalle
$bracket.r minus oo semi minus 1 bracket.r$ g est croissante et
$lim_(x arrow.r minus oo) g lr((x)) eq minus oo$,
$g lr((minus 1)) eq minus 2$ donc $lr((C g))$ ne coupe pas l’axe des
abscisses et l’équation $g lr((a)) eq 0 lr((E))$ n’as pas de
solution de manière analogue sur $lr([minus 1 semi 1])$ g est
décroissante et comme $g lr((minus 1)) lt 0$ $lr((E))$ n’as pas non
plus de solution. Finalement sur
$bracket.l 1 semi plus oo bracket.l$ g est croissante et
$lim_(x arrow.r plus oo) g lr((x)) eq plus oo gt 0$,
$g lr((1)) eq minus 6 lt 0$ Donc d’après le théorème des valeurs
intermédiares $lr((E))$ a une unique solution sur l’intervalle
$bracket.l 1 semi plus oo bracket.l$
+ $g lr((2.19)) eq minus 0.066541$ et $g lr((2.20)) eq 0.048$ ce qui
veut dire que $g lr((2.19)) lt a lt g lr((2.20))$ soit d’après le
théorème des valeurs intermédiares $2.19 lt a lt 2.20$
]
+ $g lr((x)) gt 0$ $x^3 minus 3 x minus 4 gt 0$ $x gt a$ On en déduit le
tableau suivant
#align(center)[#table(
columns: 6,
align: (col, row) => (auto,auto,auto,auto,auto,auto,).at(col),
inset: 6pt,
[x], [-∞], [], [a], [], [+∞],
[signe de g(x)],
[],
[-],
[0],
[+],
[],
)
]
]
=== Partie C
<partie-c>
+ $f$ est définie quand son dénominateur est différent de $0$ soit quand
$x^2 minus 1 eq.not 0$ donc quand $x eq.not 1$ et $x eq.not minus 1$
donc $D_f eq bb(R) backslash brace.l minus 1 semi 1 brace.r$ De plus
$f lr((x)) eq frac(u lr((x)), v lr((x)))$ avec
$u lr((x)) eq x^3 plus 2 x^2$ et $v lr((x)) eq x^2 minus 1$ donc son
ensemble de dérivabilité est
$D_(f prime) eq bb(R) backslash brace.l minus 1 semi 1 brace.r$ car
$v$ n’est pas définie quand $x eq 1$ et $x eq minus 1$
+ f satisfait les conditions de la partie A car
$f lr((0)) eq frac(0^3 plus 2 lr((0^2)), 0^2 minus 1) eq 0$ donc f
passe par l’origine. De plus $f$ n’est pas définie en $minus 1$ et $1$
comme dans la partie A et la limite de
$f lr((x)) minus lr((x plus 2)) eq frac(x^3 plus 2 x^2 minus x^3 plus x minus 2 x^2 plus 2, x^2 minus 1) eq frac(1 plus 2 / x^2, x lr((1 minus 1 / x^2)))$
Or $lim_(x arrow.r plus oo) 1 / x^k eq 0$ donc
$lim_(x arrow.r plus oo) f lr((x)) minus lr((x plus 2)) eq 0$ et de
manière analogue
$lim_(x arrow.r minus oo) f lr((x)) minus lr((x plus 2)) eq 0$
+ #block[
#set enum(numbering: "a.", start: 1)
+ $f prime lr((x)) eq frac(lr((x^2 minus 1)) lr((3 x^2 plus 4 x)) minus 2 x lr((x^3 plus 2 x^2)), lr((x^2 minus 1))^2) eq frac(x^4 minus 3 x^2 minus 4 x, lr((x^2 minus 1))^2) eq frac(x g lr((x)), lr((x^2 minus 1))^2)$
+
]
$lim_(x arrow.r lr((minus 1))^minus) f lr((x)) eq plus oo$ car
$x lt minus 1$ $x^2 gt 1$ car $x^2$ est décroissante sur $bb(R)^minus$
$x^2 minus 1 gt 0$
et de manière analogue
$lim_(x arrow.r lr((minus 1))^plus) f lr((x)) eq minus oo$ car
$x gt minus 1$ $x^2 lt 1$ car $x^2$ est décroissante sur $bb(R)^minus$
$x^2 minus 1 lt 0$
De plus $lim_(x arrow.r 1^plus) f lr((x)) eq plus oo$ car $x gt 1$
$x^2 gt 1$ car $x^2$ est croissante sur $bb(R)^plus$ $x^2 minus 1 gt 0$
Finalement $lim_(x arrow.r 1^minus) f lr((x)) eq minus oo$ car $x lt 1$
$x^2 lt 1$ car $x^2$ est croissante sur $bb(R)^plus$ $x^2 minus 1 lt 0$
#align(center)[#table(
columns: 10,
align: (col, row) => (auto,auto,auto,auto,auto,auto,auto,auto,auto,auto,).at(col),
inset: 6pt,
[x], [-∞], [], [-1], [], [0], [], [1], [], [+∞],
[signe de xg(x)],
[],
[+],
[],
[+],
[0],
[-],
[],
[-],
[],
[var de f],
[x+2],
[➚],
[||],
[➚],
[0],
[➘],
[||],
[➘],
[x+2],
)
]
#block[
#set enum(numbering: "1.", start: 4)
+ #block[
#set enum(numbering: "a.", start: 1)
+ $x plus 2 plus frac(x plus 2, x^2 minus 1) eq frac(x plus 2 plus lr((x plus 2)) lr((x^2 minus 1)), x^2 minus 1) eq frac(x plus 2 minus 2 minus x plus x^3 plus 2 x^2, x^2 minus 1) eq f lr((x))$
+ Par conséquent
$f lr((x)) minus lr((x plus 2)) eq frac(x plus 2, x^2 minus 1)$ Donc
quand x tend vers $minus oo$ $lr((C f))$ sera légèrement en dessous
de $Delta$ et inversement quand x tend vers $plus oo$
]
+ #figure([#image("DM4_1.png")],
caption: [
Graphique
]
)
]
=== Partie D
<partie-d>
#figure([#image("DM4_2.png")],
caption: [
h(x) en pointillé
]
)
= Brouillon
<brouillon>
== Exercice 2
<exercice-2>
+ #figure([#image("DM4_3.png")],
caption: [
Arbre de probabilités
]
)
+ #block[
#set enum(numbering: "a.", start: 1)
+ $a_2 eq P lr((A_2 sect B_1)) plus P lr((A_2 sect A_1)) eq P_(B_1) lr((A_2)) P lr((B_1)) plus P_(A_2) lr((A_1)) P lr((A_2))$
donc $a_2 eq 0.5 times 0.24 plus 0.5 times 0.84 eq 0.54$
+ $P_(A_2) lr((B_1)) eq frac(P paren.l A_2 sect B_1, P lr((A_2))) eq frac(0.24 times 0.5, 0.54) eq 2 / 9$
]
+ ```
a.
```
#image("DM4_4.png") \
b.
$a_n plus 1 eq lr((0.24)) lr((1 minus a_n)) plus 0.84 a_n eq 0.24 minus 0.24 a_n plus 0.84 a_n eq 0.6 a_n plus 0.24$
+ Soit à démonter:
$P lr((n)) upright(": \"") a_n eq 0.6 minus 0.1 times 0.6^(n minus 1) upright("\"")$
\
Initialisation: au rang $n eq 1$ on a d’une part $a_1 eq 0.5$ et
$0.6 minus 0.1 times 0.6^0 eq 0.5$ Donc $P lr((1))$ est vraie
c’est-à-dire la propriété est initialisée. \
Hérédité: On suppose qu’il existe un entier naturel $k$ tel que
$P lr((k))$ soit vraie c’est-à-dire
$a_k eq 0.6 minus 0.1 times 0.6^(k minus 1)$ \
On veut démontrer que la propriété est vraie au rang $k plus 1$ \
$a_(k plus 1) eq 0.6 lr((a_k)) plus 0.24 eq 0.6 lr((0.6 minus 0.1 times 0.6^(k minus 1))) plus 0.24$
~
$a_(k plus 1) eq 0.36 minus 0.1 times 0.6^(k plus 1 minus 1) plus 0.24 eq 0.6 minus 0.1 times 0.6^(k plus 1 minus 1)$
\
Donc $P lr((k plus 1))$ est vraie c’est-à-dire $P lr((n))$ est
héréditaire. \
Conclusion: La propriété est initialisée et héréditaire donc d’après
le principe de récurrence
$forall n in bb(N)^ast.basic upright(", on a :") a_n eq 0.6 minus 0.1 times 0.6^(n minus 1)$
+ $lim_(n arrow.r plus oo) 0.6^n eq 0$ car $minus 1 lt 0.6 lt 1$ Donc
$lim_(n arrow.r plus oo) a_n eq 0.6$ Ce qui veut dire qu’après un
grand nombre de jour la probabilité de trouver le vélo au point A au
matin suivant est de 0.6
+ On peut utiliser un programme de seuil
```python
def seuil(A):
u=0.5
n=1
while u < A:
n+=1
u=0.6*u+0.24
return n
print(seuil(0.599))
```
On obtient n\=11 ce qui veut dire qu’après 11 matin la probabilité
d’obtenir le vélo au point A le matin suivant sera supérieur à 0.599
== Exercice 3
<exercice-3>
D’après le théorème de Pythagore on a $R^2 eq r^2 plus lr((h / 2))^2$
soit $r^2 eq R^2 minus lr((h / 2))^2$ Or le volume d’un cylindre
d’hauteur variable est $V lr((h)) eq pi r^2 h$ Donc
$V lr((h)) eq pi lr((R^2 minus lr((h / 2))^2)) h eq pi h lr((R^2 minus h^2 / 4))$
On peut maintenant étudier les variations de $V$ sur
$bracket.r 0 semi 2 R bracket.l$
$V prime lr((h)) eq pi lr((R^2 minus h^2 / 4)) plus frac(minus 1, 2) h lr((pi h)) eq pi R^2 minus frac(3 pi h^2, 4)$
$ V prime lr((h)) eq 0 $ $ pi R^2 minus frac(3 pi h^2, 4) eq 0 $
$ pi R^2 eq frac(3 pi h^2, 4) $ $ 4 pi R^2 eq 3 pi h^2 $
$ frac(4 pi R^2, 3 pi) eq h^2 $ $ frac(4 R^2, 3) eq h^2 $ Donc
$h eq frac(2 R, sqrt(3))$ \
car $R gt 0$ et $h gt 0$ en tant que longeur.
Donc $h eq frac(2 R, sqrt(3))$ quand $V lr((h))$ est maximal et
$r^2 eq R^2 minus h^2 / 4$ \
$ r^2 eq frac(2 R^2, 3) $
$ r eq frac(R sqrt(2), sqrt(3)) eq sqrt(2 / 3) R $ car $R gt 0$ et
$r gt 0$ en tant que longeur.
|
|
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/ffa14c-numerical_algebra/main.typ | typst | #set text(
font: "Source Han Serif SC",
size: 10pt,
)
#set math.equation(numbering: "(1)")
#align(
center,
text(20pt)[
2023秋 数值代数
],
)
#align(
center,
text(12pt)[
马天开 PB21000030
],
)
#align(
center,
text(12pt)[
上次修改:#datetime.today().display("[year]-[month]-[day]")
],
)
#outline(depth: 1)
#pagebreak()
= 第一次书面作业
== 1.1
给出求下三角阵的逆矩阵的详细算法。
#text(fill: blue)[
*解答*
设下三角阵 $L$ 的逆矩阵为 $T$,对 $T$ 进行分块:
$
T = [T_1, T_2, dots.c, T_n]
$
注意到:
$
L T = [L T_1, L T_2, dots.c, L T_n] = [e_1, e_2, dots.c, e_n] = I
$
对每个 $L T_i = e_i$,$L$ 是下三角阵,利用算法1.1.1,分别计算出 $T_1, T_2, dots.c, T_n$。
]
#text(fill: red)[
*算法*
```txt
for j=1:n
for k=1:n-1
T(k,j)=T(k,j)/L(k,k);
T(k+1:n,j)=T(j+1:n,j)-T(k,j)L(k+1:n,k);
end
T(n,j)=T(n,j)/L(n,n);
end
```
]
== 1.2
设 $S, T in RR^(n times n)$ 为两个上三角阵,而且线性方程组 $(S T - lambda I)x=b$ 是非奇异的。给出一种运算量为 $O(n^2)$ 的算法来求解该方程组。
#text(fill: blue)[
*解答*
- $O(n^2)$ 计算$hat(S) = (S T - lambda I)$,注意到$S$与$T$都是上三角阵,所以$hat(S)$也是上三角阵
- $O(n^2)$ 回代法求解$hat(S) x = b$,线性方程组非奇异
]
== 1.3
证明:如果 $L_k=I-l_k e_k^T$ 是一个Gauss变换,那么 $L_k^{-1}=I+l_k e_k^T$ 也是一个Gauss变换。
#text(fill: blue)[
*解答*
根据定义,容易说明 $L^prime = I+l_k e_k^T$ 是Gauss变换,只需证明 $L^prime L_k = I$ 即可。
注意到:
$
(I-l_k e_k^T)(I+l_k e_k^T) = I - l_k e_k^T + l_k e_k^T - l_k e_k^T l_k e_k^T = I- l_k e_k^T l_k e_k^T
$
而 $ l_k = (0,dots.c,0,l_(k+1,k),dots.c,l_(n,k))^T $
显然得到$e_k^T l_k &= 0$,因此
$
L^(-1)= I+l_k e_k^T
$
]
== 1.4
确定一个 $3 times 3$ Gauss变换 $L$,使得:
$
L mat(delim:"[",2;3;4) = mat(delim:"[",2;7;8)
$
#text(fill: blue)[
*解答*
显然如下变换满足要求:
$
L = mat(delim:"[",
1;
2,1;
2,0,1;
)
$
]
== 1.5
证明:如果 $A in RR^(n times n)$ 有三角分解,并且是非奇异的,那么 $A = L U$ 的分解中 $L$ 和 $U$ 都是唯一的。
#text(fill: blue)[
*解答*
设 $A = L_1 U_1 = L_2 U_2$,其中 $L_1, L_2$ 是单位下三角阵,$U_1, U_2$ 是上三角阵。
于是成立:
$
L_2^(-1) L_1 = U_2 U_1^(-1)
$
容易说明 $L_2^(-1)$ 也是单位下三角阵,$U_1^(-1)$ 也是上三角阵。同时,$L_2^(-1) L_1$ 是单位下三角阵,$U_2 U_1^(-1)$ 是上三角阵。
在两侧相等的情况下,只可能均等于对角矩阵,同时左侧又是单位下三角阵,因此只能是单位对角阵,即 $ L_2^(-1) L_1 = U_2 U_1^(-1) = I $
从而$ L_1 = L_2, U_1 = U_2 $
]
== 1.6
设$A = (a_(i j)) in RR^(n times n)$ 的定义如下:
$
a_(i j) = cases(
1 quad& i = j or j = n,
-1 quad& i > j,
0 quad& "else"
)
$
证明 $A$ 有满足 $abs(l_(i j)) <=1$ 和 $u_(n n) = 2^(n-1)$ 的三角分解
#text(fill: blue)[
*解答*
设 $L = (l_(i j)) in RR^(n times n)$ 是单位下三角阵,$U = (u_(i j)) in RR^(n times n)$ 是上三角阵,满足 $A = L U$。
其中
$
l_(i j) = cases(
0 quad& i < j,
1 quad& i = j,
-1 quad& i > j,
)
$
$
u(i j) = cases(
2^(i-1) quad& j=n,
1 quad& i = j,
0 quad& "else"
)
$
容易证明 $A = L U$,同时 $abs(l_(i j)) <=1$ 和 $u_(n n) = 2^(n-1)$ju
] |
|
https://github.com/i-am-wololo/cours | https://raw.githubusercontent.com/i-am-wololo/cours/master/main/parties_i23/groupes.typ | typst | #import "../templates.typ": *
|
|
https://github.com/p-will/thesis_typst_template | https://raw.githubusercontent.com/p-will/thesis_typst_template/main/README.md | markdown | # thesis_typst_template
A typst template for a thesis at HTWD Dresden
|
|
https://github.com/long-paddy-field/typst_template | https://raw.githubusercontent.com/long-paddy-field/typst_template/main/seminor/seminor_temp.typ | typst | #import "@preview/physica:0.9.3":*
#import "@preview/unify:0.5.0":*
#import "@preview/metro:0.2.0":*
#let seminor_article(
fontsize: 11pt,
title: none,
subtitle: none,
header_text: none,
autors: (),
abstruct: [],
date: none,
doc,
)={
let serif = "Noto Serif CJK JP"
let sans = "Noto Sans CJK JP"
// let math_font = "Noto Sans Math"
// ヘッダーの設定
set page(paper:"a4",
header:align(right,text(font: serif, size: fontsize, header_text)))
set page(numbering: "(1)")
align(center,text(font: sans, size: 1.5*fontsize, strong(title)))
align(center)[
#box()[
#align(left,text(font: sans, size: 1.2*fontsize,subtitle))
]
]
if abstruct !=[]{
par(align(left,text(font: sans)[
*概要*\
#block(width: 99%)[#align(left,abstruct)]
]))
}
// set font
set text(lang: "ja", font: serif, fontsize)
// 行間の調整
set par(
leading: 1.2em,
justify: true,
first-line-indent: 1.1em,
)
show par: set block(spacing: 1.2em)
show heading: set block(above: 1.6em, below: 0.6em)
set heading(numbering: "1.1. ")
// 見出しの下の段落を字下げするため
show heading: it =>{
it
par(text(size: 0pt, ""))
}
// 様々な場所でのフォント
show heading: set text(font: sans)
// show math.equation: set text(font: math_font)
// 数式のナンバリング
set math.equation(numbering: "(1)",number-align: bottom)
doc
}
#let appendix(app)=[
#counter(heading).update(0)
#set heading(numbering: "A.1. ")
#app
]
#let introbox(title: none, body)={
align(right)[
#rect(width: 98%, stroke: (left: 1pt))[
#align(left)[
#text(font: "Noto Sans CJK JP", size: 12pt)[#sym.star.stroked#emph(title)]\
#body
]
]
]
}
#let quizbox(title: none, body)={
rect(width: 100%, stroke:(rest: 1pt),radius: 5pt)[
#text(font: "Noto Sans CJK JP", size: 14pt, )[#emph(title)]\
#body
]
}
#let colMath(x, color)= text(fill: color)[$#x$]
#let voidbox(width:4em, text:none)={
box(width:width, height: 1.2em, baseline: 0.2em,stroke:(rest: 1pt), inset: 0.2em)[#align(center)[#text]]
} |
|
https://github.com/matteopolak/resume | https://raw.githubusercontent.com/matteopolak/resume/main/README.md | markdown | MIT License | # My Resume
[](.github/workflows/build.yml)
My resume, built with [Typst](https://github.com/typst/typst).
|
https://github.com/lucafluri/typst-templates | https://raw.githubusercontent.com/lucafluri/typst-templates/master/Project_Report_FHNW_MSE/template.typ | typst | #import "appendix.typ"
#let buildMainHeader(mainHeadingContent) = {
[
#align(center, smallcaps(mainHeadingContent))
#line(length: 100%)
]
}
#let buildSecondaryHeader(mainHeadingContent, secondaryHeadingContent) = {
[
#smallcaps(mainHeadingContent) #h(1fr) #emph(secondaryHeadingContent)
#line(length: 100%)
]
}
// To know if the secondary heading appears after the main heading
#let isAfter(secondaryHeading, mainHeading) = {
let secHeadPos = secondaryHeading.location().position()
let mainHeadPos = mainHeading.location().position()
if (secHeadPos.at("page") > mainHeadPos.at("page")) {
return true
}
if (secHeadPos.at("page") == mainHeadPos.at("page")) {
return secHeadPos.at("y") > mainHeadPos.at("y")
}
return false
}
#let getHeader() = {
locate(loc => {
// Find if there is a level 1 heading on the current page
let nextMainHeading = query(selector(heading).after(loc), loc).find(headIt => {
headIt.location().page() == loc.page() and headIt.level == 1
})
if (nextMainHeading != none) {
return buildMainHeader(nextMainHeading.body)
}
// Find the last previous level 1 heading -- at this point surely there's one :-)
let lastMainHeading = query(selector(heading).before(loc), loc).filter(headIt => {
headIt.level == 1
}).last()
// Find if the last level > 1 heading in previous pages
let previousSecondaryHeadingArray = query(selector(heading).before(loc), loc).filter(headIt => {
headIt.level > 1
})
let lastSecondaryHeading = if (previousSecondaryHeadingArray.len() != 0) {previousSecondaryHeadingArray.last()} else {none}
// Find if the last secondary heading exists and if it's after the last main heading
if (lastSecondaryHeading != none and isAfter(lastSecondaryHeading, lastMainHeading)) {
return buildSecondaryHeader(lastMainHeading.body, lastSecondaryHeading.body)
}
return buildMainHeader(lastMainHeading.body)
})
}
// 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: "",
abstract: [],
authors: (),
date: none,
body,
) = {
// Set the document's basic properties.
set document(author: authors.map(a => a.name), title: title)
// set page(numbering: "I", number-align: center, margin: (x: 15%, y: 10%))
set text(font: "STIX Two Text", lang: "en", size: 12pt)
// Set paragraph spacing.
show par: set block(above: 2em, below: 2em)
set heading(numbering: "1.1")
set par(leading: 0.75em)
set align(center)
image("figures/fhnwLogo.jpg", width: 80%)
v(10%)
// linebreak()
// Title row.
align(center)[
#block(text(weight: 700, 3em, title))
#v(10%, weak: true)
]
// Author information.
pad(
top: 0.8em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center)[
_*#author.role*_ \
*#author.name* \
#link("mailto:" + author.email) \
]),
),
)
v(10%)
align(center)[
#block(text(weight: "semibold", 1.5em, "P8 Project"))
#v(5%)
#block(text(1.3em, "MSc in Engineering with Specialisation in Computer Science"))
#v(10%)
#block(text(1.3em, "Institute for Interactive Technologies"))
#v(2.5%)
#"Brugg-Windisch"\
#date
#v(2.5%)
#image("figures/mse.svg", width: 60%)
]
pagebreak()
set page(numbering: "I", number-align: center, margin: (x: 15%, y: 10%))
// Abstract.
pad(
x: 2em,
top: 1em,
bottom: 1.5em,
align(left)[
#heading(
outlined: false,
numbering: none,
text(0.85em, smallcaps[Abstract]),
)
#abstract
#v(5%)
*Keywords*: #linebreak()
Point Clouds • Data Selection • Exploratory Data Analysis • XR • Hand Tracking
],
)
pagebreak()
let outline(title: "Contents", depth: none, indent: true) = {
heading(title, numbering: none)
locate(it => {
// let elements = query(heading, after: it)
let elements = query(selector(heading).after(it), it)
for el in elements {
if depth != none and el.level > depth { continue }
if(el.outlined == false) { continue }
let maybe_number = if el.numbering != none {
numbering(el.numbering, ..counter(heading).at(el.location()))
" "
}
let line = {
if indent {
h(1em * (el.level - 1 ))
}
if el.level == 1 {
v(weak: true, 0.5em)
set text(weight: "bold")
maybe_number
el.body
} else {
maybe_number
el.body
}
// Filler dots
box(width: 1fr, h(3pt) + box(width: 1fr, repeat[.]) + h(3pt))
// Page number
str(counter(page).at(el.location()).first())
linebreak()
}
link(el.location(), line)
}
})
}
align(left)[
#outline(indent: true, title: "Table of Contents")
]
set page(numbering: "1", number-align: center, header: getHeader())
// counter(page).update(1)
// set par(first-line-indent: 20pt)
// set page(header: getHeader())
// Main body.
set par(justify: true)
align(left)[
#body
#bibliography("references.bib")
#appendix
////
// SOA
// #pagebreak()
// #set heading(outlined: false, numbering: none)
// = Statement of Authenticity
// I confirm that this P8 project was written autonomously by me using only the sources, aids, and assistance stated in the report, and that any work adopted from other sources, which was written as part of this thesis, is duly cited and referenced as such.
// Brugg-Windisch, #date
// #v(2em)
// #image("figures/signature_cropped.jpeg", width: 30%)
// <NAME>
]
} |
|
https://github.com/adeshkadambi/ut-thesis-typst | https://raw.githubusercontent.com/adeshkadambi/ut-thesis-typst/main/template.typ | typst | MIT License | #let ut-thesis(
title,
author,
degree,
department,
year,
abstract,
ack,
abbrev,
body
) = {
// constants
let rest-margin = 0.75in
let left-margin = 1.25in
let font-size = 12pt
let font = "New Computer Modern"
// Set the document's basic properties
set document(author: author, title: title)
set page(
paper: "us-letter",
margin: (left: left-margin, rest: rest-margin),
numbering: "i",
number-align: center,
)
set text(font: font, size: font-size, lang: "en")
set par(leading: 1.5em, justify: true, first-line-indent: 2em)
// Table captions go above the table
show figure.where(
kind: table
): set figure.caption(position: top)
// Title page (no page number shown)
page(numbering: none)[
#set par(leading: 0.65em)
#align(center)[
#v(2in-rest-margin)
#smallcaps(text(weight: "regular", 1.25em, title))
#v(1.5in)
by
#v(1.5in)
#author
#v(1.5in)
A thesis submitted in conformity with the requirements\
for the degree of #degree
#v(0.5em)
#department\
University of Toronto
#v(3cm)
© Copyright by #author #year
#v(1.25in-rest-margin)
]
]
// Abstract page (starts with page number ii)
page(numbering: "i")[
#set par(leading: 0.65em)
#block(width: 100%)[
#align(center)[
#title \
#author \
#degree \
#department \
University of Toronto \
#year \
]
]
#set align(center)
#heading(
outlined: false,
numbering: none,
"Abstract"
)
#v(1em)
#set align(left)
#set par(leading: 2em)
#abstract
]
// Acknowledgments
page[
#set align(center)
#heading(outlined: false, numbering: none, "Acknowledgments")
#v(1em)
#set align(left)
#ack
]
// Table of contents
page[
#heading(outlined: false, numbering: none, "Table of Contents")
#outline(depth: 3, indent: true, title: "")
]
// List of Tables
page[
#heading(outlined: false, numbering: none, "List of Tables")
#outline(
title: "",
target: figure.where(kind: table),
)
]
// List of Figures
page[
#heading(outlined: false, numbering: none, "List of Figures")
#outline(
title: "",
target: figure.where(kind: image),
)
]
// List of Abbreviations
page[
#heading(outlined: false, numbering: none, "List of Abbreviations")
#v(2.5em)
#abbrev
]
// Main body (switch to Arabic numerals)
set page(numbering: "1")
counter(page).update(1)
// Heading Configuration
set heading(numbering: "1.")
show heading.where(level: 1): it => [
// we layout rather large Chapter Headings, e.g:
//
// Chapter 1.
// Introduction
//
#pagebreak()
#v(2in-rest-margin)
#block[
#if it.numbering != none [
#set text(size: 24pt)
Chapter #counter(heading).display() \
#set text(size: 32pt)
#it.body
]
#if it.numbering == none [
#set text(size: 32pt)
#it.body
]
#v(1cm)
]
#v(1cm, weak: true)
]
show heading.where(level: 2): it => [
#set text(size: 20pt)
#block[
#v(0.5cm)
#counter(heading).display()
#it.body
]
// some space after the heading 2 (before text)
#v(0.5em)
]
show heading.where(level: 3): it => [
#set text(size: 16pt)
#block[
#v(0.5cm)
#counter(heading).display()
#it.body
]
// some space after the heading 3 (before text)
#v(0.5em)
]
show heading.where(level: 4): it => [
#set text(size: 12pt)
#block[
#v(0.5cm)
#counter(heading).display()
#it.body
]
// some space after the heading 4 (before text)
#v(0.5em)
]
// Main body content
body
}
#let appendix(body) = {
set heading(numbering: "A.1.", supplement: [Appendix])
counter(heading).update(0)
show heading.where(level: 1): it => [
#pagebreak()
#v(2in-0.75in)
#block[
#if it.numbering != none [
#set text(size: 24pt)
Appendix #counter(heading).display() \
#set text(size: 32pt)
#it.body
]
#if it.numbering == none [
#set text(size: 32pt)
#it.body
]
#v(1cm)
]
#v(1cm, weak: true)
]
body
}
|
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/auton-routes/program.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#import "/utils.typ"
#show: create-body-entry.with(
title: "Program: Offensive Size Auton",
type: "program",
date: datetime(year: 2024, month: 1, day: 20),
author: "<NAME>",
witness: "<NAME>",
)
#grid(
columns: (1fr, 1fr),
gutter: 20pt,
[
After the Capital Belt Challenge we discovered that most of our alliance
partners were incapable of performing AWP with us. This lead us to prioritize
scoring triballs over scoring AWP. We came up with this route that will score 4
triballs into the goal.
+ We drop our preloaded triball off in front of the goal
+ We pick up the triball to the robot's left
+ We drop that triball next to the first one
+ We pick up the triball touching the barrier on the auton line
+ We drop the triball next to the first two
+ We extend our wings, and push all 4 triballs into the goal
],
figure(image("./4-ball.png"), caption: "Our new offensive side auton route"),
)
// typstfmt::off
#grid(
columns: (2fr, 1fr),
gutter: 20pt,
[
```cpp
chassis.moveToPoint(0, 32, 2000); // Move forward 32"
chassis.waitUntilDone(); // Wait until the movement is complete
chassis.turnTo(20, 45, 1000); // Turn to face the goal
intake.set_state(lib::IntakeState::Reversed); // Outake the triball
pros::delay(1000); // Wait a second for the triball to leave the intake
```
],
image("./1.png"),
[
```cpp
chassis.moveToPose(-30, 28, -22, 2000); // Move to middle bar
chassis.waitUntilDone();
intake.set_state(lib::IntakeState::Running); // Intake Triball
```
],
image("./2.png"),
[
```cpp
chassis.moveToPose(0, 46, 100, 2000); // Move and face goal
pros::delay(1000);
intake.set_state(lib::IntakeState::Reversed); // Outake Triball
```
],
image("./3.png"),
[
```cpp
pros::delay(1000);
intake.set_state(lib::IntakeState::Idle); // Set intake to idle
chassis.moveToPose(-40, 52, -90, 1000); // Move to middle bar
intake.set_state(lib::IntakeState::Running); // Intake Triball
pros::delay(1500);
```
],
image("./4.png"),
[
```cpp
chassis.turnTo(30, 45, 1000); // Turn to face goal
intake.set_state(lib::IntakeState::Reversed); // Outake triball
pros::delay(500);
flaps.set_state(lib::FlapState::Expanded); // Expand flaps
chassis.moveToPoint(20, 45, 3000); // Use flaps to move towards goal and push in all four triballs into goal
```
],
image("./5.png"),
)
// typstfmt::on
|
https://github.com/katamyra/Notes | https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS3001/Sections/MakeupSection.typ | typst | #import "../../../template.typ": *
= Social Epistemology
#definition[
*Internal Realism* is a point of view in the middle of scientific realism (which is the idea that scientific theories provide true descriptions of our world) and anti-realism (which is the idea that )
] |
|
https://github.com/abenson/report | https://raw.githubusercontent.com/abenson/report/master/README.md | markdown | # A Report template for Use with Typst
SPDX-License Identifier: Unlicense
These files are meant to be used with Typst `v0.7.0`. They can be made to work
with older versions, though. I believe the only thing I'm using from `v0.7.0`
currently is `float:true`.
## Status
All of the old templates and plans are being retired. There will be a single
type called `report`.
- [x] `work` => `report`
- [x] `simple` => `report`
To enable the features of the old long-form template, such as the title page and
table of contents, pass `title_page: true` to the `report.with()`.
## Why Typst?
I used to have a workflow based around [Pandoc](https://pandoc.org/). It allowed
me to write in Markdown and generate pretty PDFs using Pandoc's [template
system](https://github.com/abenson/custom-pandoc-templates/).
It's major drawback, for me, was an intermediary step that involved LaTeX.
TeXLive is huge, cumbersome, and on some of my smaller systems, such as my
Chromebook or ancient PowerBook, disk space is a limited commodity.
I began looking for a replacement, settling on reStructuredText and
[Rinoh](https://www.mos6581.org/rinohtype/) for a very short period of time,
until I found Typst.
[Typst](https://typst.app) is a typesetting framework similar to TeX and LaTeX,
but much smaller and with a newly designed language. Also, it borrows a lot of
inline formatting from other frameworks, such as `_italics_` and `*bold*`, which
make it easy to work with quickly.
|
|
https://github.com/marcantoinem/CV | https://raw.githubusercontent.com/marcantoinem/CV/main/fr/education.typ | typst | #import "../src/style.typ": experience
#let polytechnique = {
experience(
"Polytechnique Montréal",
[GPA: 3,71/4.00 $diamond.stroked.small$ 64/120 crédits],
"Août 2022 - Présent",
"Génie informatique",
"",
)
}
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/meta/cite-footnote.typ | typst | Apache License 2.0 | Hello @netwok
And again: @netwok
#pagebreak()
#bibliography("/files/works.bib", style: "chicago-notes")
|
https://github.com/cbr9/CV | https://raw.githubusercontent.com/cbr9/CV/main/modules/certificates.typ | typst | Apache License 2.0 | #import "../template/template.typ": *
#cvSection("Certificates")
#cvHonor(
date: "April 2022",
title: "PyTorch for Deep Learning",
issuer: "Udemy",
url: "https://www.udemy.com/certificate/UC-c8142260-a945-4f41-91f5-d213671b8493"
)
#cvHonor(
date: "March 2022",
title: "Mathematics for Machine Learning",
issuer: "Coursera",
url: "https://www.coursera.org/account/accomplishments/specialization/certificate/DJPXWT9X9KVS"
)
#cvHonor(
date: "December 2021",
title: "Neural Networks and Deep Learning",
issuer: "Coursera",
url: "https://www.coursera.org/account/accomplishments/certificate/JXLQNFEH3H9S"
)
#cvHonor(
date: "March 2020",
title: "Linear Algebra",
issuer: "Udemy",
url: "https://www.udemy.com/certificate/UC-0d00a3f9-2a0c-4881-a50e-4341fa30b055/"
)
#cvHonor(
date: "March 2020",
title: "Probability & Statistics",
issuer: "Udemy",
url: "https://www.udemy.com/certificate/UC-BHG909SJ/",
)
|
https://github.com/Treeniks/bachelor-thesis-isabelle-vscode | https://raw.githubusercontent.com/Treeniks/bachelor-thesis-isabelle-vscode/master/presentation.typ | typst | #import "/utils/isabelle.typ": *
#import "@preview/cetz:0.2.2"
#import "@preview/polylux:0.3.1": *
#import themes.clean: *
#import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge
#import "@preview/codly:1.0.0": *
#set page(paper: "presentation-16-9")
#let tum-blue = rgb(0, 101, 189)
#let date = datetime(year: 2024, month: 08, day: 26)
#show: clean-theme.with(
footer: [<NAME>],
short-title: [Improving Isabelle/VSCode],
logo: image("/resources/tum-logo.svg"),
color: tum-blue,
)
#set text(font: "STIX Two Text", size: 22pt)
#show math.equation: set text(font: "STIX Two Math")
#show raw: set text(font: "JetBrains Mono", size: 1em)
#show: codly-init.with()
#codly(
zebra-fill: luma(245),
stroke: 2pt + luma(230),
lang-stroke: none,
)
#title-slide(
title: [Improving Isabelle/VSCode],
subtitle: [Towards Better Prover IDE Integration\ via Language Server],
authors: "<NAME>",
date: date.display(),
)
#slide(title: [Language Server Protocol])[
#align(horizon + center)[
#diagram(
edge-stroke: 2pt,
node((0, 0), [Code Editor], height: 10em, width: 4em, stroke: 2pt),
node((1, 0), [Client], height: 10em, width: 4em, stroke: 2pt),
node((5, 0), [Server], height: 10em, width: 4em, stroke: 2pt),
edge((0, 0), (1, 0)),
edge((1, 0), (5, 0), "<{-}>", [jsonrpc]),
)
#v(1fr) // so that align horizon actually works for some reason...
]
]
#new-section-slide("State and Output Panels")
#slide(title: [Comparison State Panels])[
#table(
columns: (1fr, 1fr),
stroke: none,
align: center,
table.header([#jedit], [#only(1, vscode)#only(2)[#vscode (new)]]),
box(stroke: 2pt + luma(150), image("/resources-presentation/jedit-state-panel.png")),
[
#only(1, box(stroke: 2pt + luma(150), image("/resources-presentation/vscode-state-panel.png")))
#only(2, box(stroke: 2pt + luma(150), image("/resources-presentation/vscode-state-panel2.png")))
]
)
]
#slide(title: [Disabling HTML])[
#only(2, align(horizon + center, box(stroke: 2pt + luma(150), image(height: 85%, "/resources-presentation/neovim-html.png"))))
#only(3, align(horizon + center, box(stroke: 2pt + luma(150), image(height: 85%, "/resources/neovim-no-decs-light.png"))))
#only(4, align(horizon + center, box(stroke: 2pt + luma(150), image(height: 85%, "/resources/neovim-with-decs-light.png"))))
]
#new-section-slide("Decorations on File Switch")
#slide(title: [])[
#grid(
columns: (1fr, 1fr),
rows: (auto, 1fr),
gutter: 15pt,
align: horizon + center,
uncover(2, text(size: 1.5em)[*Client*]),
uncover(2, text(size: 1.5em)[*Server*]),
{
only(1, [Caching])
only(2, rect(width: 50%, height: 100%)[Caching])
},
{
only(1)[Request]
only(2, rect(width: 50%, height: 100%)[Request])
},
)
]
// #slide(title: [])[
// #align(horizon + center)[
// #cetz.canvas({
// import cetz.draw: *
// line((0, 0), (20, 0), name: "line")
// content(
// ("line.start", 5%, "line.end"), anchor: "south", padding: .4, [Client]
// )
// content(
// ("line.start", 95%, "line.end"), anchor: "south", padding: .4, [Server]
// )
// })
// #v(1fr)
// ]
// ]
#slide(title: [Decorations on File Switch])[
#only(1)[
```typescript
/* decoration for document node */
type Content = Range[] | DecorationOptions[]
const document_decorations = new Map<Uri, Map<string, Content>>()
```
]
#only((2, 3))[
#codly(highlights: (
(line: 3, start: 38, end: 38, fill: green),
))
```typescript
/* decoration for document node */
type Content = Range[] | DecorationOptions[]
const document_decorations = new Map<Uri , Map<string, Content>>()
```
]
#only(3)[
#codly(highlights: (
(line: 3, start: 38, end: 38, fill: green),
))
```typescript
/* decoration for document node */
type Content = Range[] | DecorationOptions[]
const document_decorations = new Map<string , Map<string, Content>>()
```
]
]
#new-section-slide("Further Improvements")
#slide(title: [Further Improvements])[
#uncover((beginning: 1))[- #only(1)[*Fixed File Content Desyncs*]#only((beginning: 2))[Fixed File Content Desyncs]]
#uncover((beginning: 2))[- #only(2)[*Improved Handling of State Panel IDs*]#only((beginning: 3))[Improved Handling of State Panel IDs]]
#uncover((beginning: 3))[- #only(3)[*Completions for Abbreviations*]#only((beginning: 4))[Completions for Abbreviations]]
#uncover((beginning: 4))[- #only(4)[*More Granular Symbol Options*]#only((beginning: 5))[More Granular Symbol Options]]
#uncover((beginning: 5))[- #only(5)[*Code Actions for Active Markup*]#only((beginning: 6))[Code Actions for Active Markup]]
#uncover((beginning: 6))[- *Isabelle System Options\ as VSCode Settings*]
#only(3)[
#place(
horizon + center,
dy: 50pt,
box(stroke: 2pt, image(width: 80%, "/resources-presentation/completions.png")))
]
#only(4)[
#place(
horizon + right,
dy: 25pt,
box(stroke: 2pt, image(width: 50%, "/resources-presentation/symbol-handling.png")))
]
#only(5)[
#place(
horizon + right,
dy: 25pt,
box(stroke: 2pt, image(width: 50%, "/resources/vscode-action-active-sledgehammer-light-before.png"))
)
]
#only(6)[
#place(
horizon + right,
dy: 25pt,
box(stroke: 2pt, image(width: 50%, "/resources-presentation/vscode-settings.png"))
)
]
]
#focus-slide(background: tum-blue)[
*Questions?*
]
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/visualize/gradient-math.typ | typst | Apache License 2.0 | // Test that gradients are applied correctly on equations.
---
// Test on cancel
#show math.equation: set text(fill: gradient.linear(..color.map.rainbow))
#show math.equation: box
$ a dot cancel(5) = cancel(25) 5 x + cancel(5) 1 $
---
// Test on frac
#show math.equation: set text(fill: gradient.linear(..color.map.rainbow))
#show math.equation: box
$ nabla dot bold(E) = frac(rho, epsilon_0) $
---
// Test on root
#show math.equation: set text(fill: gradient.linear(..color.map.rainbow))
#show math.equation: box
$ x_"1,2" = frac(-b +- sqrt(b^2 - 4 a c), 2 a) $
---
// Test on matrix
#show math.equation: set text(fill: gradient.linear(..color.map.rainbow))
#show math.equation: box
$ A = mat(
1, 2, 3;
4, 5, 6;
7, 8, 9
) $
---
// Test on underover
#show math.equation: set text(fill: gradient.linear(..color.map.rainbow))
#show math.equation: box
$ underline(X^2) $
$ overline("hello, world!") $
---
// Test a different direction
#show math.equation: set text(fill: gradient.linear(..color.map.rainbow, dir: ttb))
#show math.equation: box
$ A = mat(
1, 2, 3;
4, 5, 6;
7, 8, 9
) $
$ x_"1,2" = frac(-b +- sqrt(b^2 - 4 a c), 2 a) $
---
// Test miscelaneous
#show math.equation: set text(fill: gradient.linear(..color.map.rainbow))
#show math.equation: box
$ hat(x) = bar x bar = vec(x, y, z) = tilde(x) = dot(x) $
$ x prime = vec(1, 2, delim: "[") $
$ sum_(i in NN) 1 + i $
$ attach(
Pi, t: alpha, b: beta,
tl: 1, tr: 2+3, bl: 4+5, br: 6,
) $
---
// Test radial gradient
#show math.equation: set text(fill: gradient.radial(..color.map.rainbow, center: (30%, 30%)))
#show math.equation: box
$ A = mat(
1, 2, 3;
4, 5, 6;
7, 8, 9
) $
---
// Test conic gradient
#show math.equation: set text(fill: gradient.conic(red, blue, angle: 45deg))
#show math.equation: box
$ A = mat(
1, 2, 3;
4, 5, 6;
7, 8, 9
) $
|
https://github.com/rabotaem-incorporated/calculus-notes-2course | https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/03-lebesgue-integral/05-var-substitution.typ | typst | #import "../../utils/core.typ": *
== Замена переменной в интеграле Лебега
#def(label: "def-diffeomorphism")[
Пусть $Omega_1$ и $Omega_2 subset RR^m$ открытые. $Phi: Omega_1 --> Omega_2$ называется _диффеоморфизмом_, если
1. $Phi$ --- биекция,
2. $Phi$ --- непрерывно дифференцируема на $Omega_1$,
3. $Phi^(-1)$ --- непрерывно дифференцируема на $Omega_2$.
]
#th(name: "замена переменной в интеграле по мере Лебега", label: "substitution")[
$Omega subset RR^m$ открытое. $Phi: Omega --> tilde(Omega)$ диффеоморфизм. $f: tilde(Omega) --> overline(RR)$, $f >= 0$ измерима (или суммируема). Тогда $ integral_tilde(Omega) f dif lambda_m (x) = integral_Omega f(Phi(x)) abs(Jj_Phi (x)) dif lambda_m (x), $
где $Jj_Phi(x) = det Phi' (x)$ --- якобиан.
]
#example(name: "авторский, не бейте если не нравится", label: "substitution-example")[
Давайте попробуем изуродовать нормальный интеграл, сделав в него подстановку.
$
integral_([0;1]times [0;1] times[0;1]) f(p) dif lambda_3 (p),
space f(x, y, z) = 1 - y.
$
Это интеграл линейной функции в кубе. Что-то вроде общей массы снега в кубе $1 times 1 times 1$ метр, где плотность снега убывает линейно с нуля до единицы, чем дальше от земли и чем ближе к поверхности.
Подстановка такая:
$
Phi vec(x, y, z) =
vec(y/2, 1 - z^2, x/3) =
mat(0, 1/2, 0; 0, 0, -1; 1/3, 0, 0) dot vec(x, y, z^2) + vec(0, 1, 0).
$
Она сжимает параллелепипед $[0;3] times [0;2] times [0;1]$ в куб, переворачивает ее, и меняет местами координатные оси ($x ~~> y$, $y ~~> z$ и $z ~~> x$). Производная равна
$
Phi' vec(x, y, z) = mat(0, 1/2, 0; 0, 0, -1; 1/3, 0, 0) dot mat(1, 0, 0; 0, 1, 0; 0, 0, 2z) = mat(0, 1/2, 0; 0, 0, -2z; 1/3, 0, 0).
$
Тогда якобиан --- $-1/3 z$.
Тогда
$
integral_([0;1]^3) f dif lambda_3 = integral_[0;3] integral_[0;2] integral_[0;1] z^2 dot abs(-1/3z) dif z dif y dif x.
$
Нетрудно увидеть, что оба интеграла равны $1/2$.
Кажется, это довольно неплохой пример, поэтому я буду использовать его дальше.
]
#make_theorem("Частные случаи", color: proof_color)()[
1. Сдвиг. Прибавляем к каждому $x$ какой-то вектор. Тогда якобиан равен единице, так как матрица производной --- единичная.
$ integral_(RR^m) f dif lambda_m = integral_(RR^m) f(x + a) dif lambda_m $
Здесь мы подвинули $x$ на вектор $a$. Интегрируя функцию по $RR^m$, множество не меняется.
2. Линейное отображение $Phi(x) = T x$. Тогда $Jj_Phi = det T$. Тогда
$ integral_(RR^m) f dif lambda_m = abs(det T) integral_(RR^m) f(T_x) dif lambda_m (x) $
3. Сжатие/растяжение: $Phi(x) = c x$. Тогда получается диагональная матрица с определителем $c^m$:
$ integral_(RR^m) f dif lambda_m = abs(c)^m integral_(RR^m) f(c x) dif lambda_m (x) $
]
#lemma(label: "diffeomorphism-decomposition")[
$Phi: Omega -> tilde(Omega)$ диффеоморфизм, $Omega$, $tilde(Omega) subset RR^m$, $a in Omega$, $0 < k < m$. Тогда существует окрестность $U_a$ такая, что $Phi bar_(U_a) = Phi_1 compose Phi_2$, где $Phi_1$, $Phi_2$ --- диффеоморфизмы. $Phi_1$ не меняет какие-то (не обязательно любые) $k$ координат (и возможно их переставляет), а $Phi_2$ --- остальные $m - k$ координат.
]
#proof[
Пусть $x, u in RR^k$, $y, v in RR^(m - k)$. Порежем координаты: $Phi(x, y) = (phi(x, y), psi(x, y))$, где $phi$ действует в $RR^k$, а $psi$ в $RR^(m - k)$. Пусть $Phi_1(u, v) = (u, f(u, v))$ и $Phi_2(u, v) = (g(u, v), v)$. Тогда $ (phi(x, y), psi(x, y)) = Phi(x, y) = Phi_1 compose Phi_2 = Phi_1(g(u, v), v) = (g(u, v), f(g(u, v), v)). $
Отсюда можно однозначно определить $g$: $g(u, v) = phi(u, v)$. Теперь $Phi_2$ определяется однозначно: $Phi_2(u, v) = (phi(u, v), v)$. Отсюда $psi(u, v) = f compose Phi_2(u, v)$. Получится формула для $f$: $f(x, y) = psi compose Phi_2^(-1)(x, y)$. Для того, чтобы это получилось, необходима обратимость $Phi_2$ в некоторой окрестности $U_a$.
Воспользуемся теоремой об обратной функции#rf("inverse-fn"). Непрерывную дифференцируемость легко увидеть: посмотрим на определитель $Phi'_2$:
$ Phi'_2 = mat(phi'_u, phi'_v; 0, E) ==> det Phi'_2 = det phi'_u. $
$phi'_u$ --- минор $k times k$ матрицы $Phi'$, так как это производные каких-то $k$ координат функции $Phi$. Так как $Phi$ непрерывно дифференцируемая биекция, то $det Phi' != 0$.
Действительно, если продифференцировать $Phi^(-1) (Phi (x)) = id$ получится $Phi' dot (Phi^(-1))' (Phi) = E$, значит $det Phi' != 0$ так как иначе произведение тоже имело бы определитель $0$. Отмечу, что производная композиции существует, так как по определению диффеоморфизма#rf("def-diffeomorphism") $Phi^(-1)$ --- непрерывно дифференцируема.
Это неверно для произвольной непрерывной биекции ($x^3$, например).
Раз $det Phi' != $, у $Phi$ найдется какой-то ненулевой минор размера $k times k$.
Это не обязательно угловой минор: может быть какой-то другой, поэтому переменные, возможно, придется переставить, чтобы такой угловой минор получить. Если мы переставим переменные с помощью какой-то перестановки $Phi_0$ в $Phi$, получив какой-то новый диффеоморфизм, то можно применить обратную перестановку к $Phi_1$, и так как $Phi_1 compose Phi_2 = Phi_0 compose Phi$, то $(Phi_0^(-1) compose Phi_1) compose Phi_2 = Phi$.
]
#example(name: "все еще авторский, чтобы вам понимать было сложнее")[
Это очень сложная лемма для понимания. Даже сложнее самого доказательства теоремы, я бы сказал. Поэтому давайте посмотрим на ее особенно внимательно.
Рассмотим диффеоморфизм из моего примера#rf("substitution-example"), и декомпозируем его на два: первый оставит одну координату, а второй --- две.
$ Phi vec(x, y, z) = vec(y/2, 1 - z^2, x/3). $
Будем следовать ходу доказательства. Разрежем координаты.
$ Phi(x, y, z) = (y/2, (1 - z^2, x / 3)) $
Рассмотрим $Phi_1 (x, y, z) = (x, f(x, y, z))$ и $Phi_2 (x, y, z) = (g(x, y, z), y, z)$. Мы хотим, чтобы $Phi_1 compose Phi_2 = Phi$:
$ Phi_1 compose Phi_2 = (g(x, y, z), f(g(x, y, z), y, z)) = (y/2, (1 - z^2, x / 3)) = Phi. $
Отсюда находится $g(x, y, z) = y/2$. Тогда мы хотим, чтобы $f(y/2, y, z) = (1-z^2, x/3)$. Только вот, что-то не получается. $f$, фактически --- функция от двух аргументов --- $y$ и $z$, а в результате мы хотим что-то, зависимое от $x$??
Почему у нас не получилось? Давайте посмотрим на $Phi_2$:
$ Phi_2 (x, y, z) = (y/2, y, z). $
Это необратимая функция, а нам необходима обратимость, чтобы $f compose Phi_2 = (1 - z^2, x/3)$ решалось для $f$. Но как же так? Разве нам не обещали обратимость в доказательстве?
Обещали, но не говорили, по каким конкретно координатам. Чтобы была обратимость, требуется, чтобы определитель $Phi'_2$ был не равен нулю:
$
Phi'_2 = mat(0, 1/2, 0; 0, 1, 0; 0, 0, 1),
$ а для этого требуется, чтобы определитель $phi'_u$ из доказательства был ненулевым. А что такое в нашем случае $phi$? Это $phi(x, y, z) = y/2$ --- первая одна координата, а $phi'_x = 0$. Получается, что обратимости $phi_x$ нет, значит нет обратимости $Phi_2$.
Ок, а как тогда нормально декомпозировать? Давайте для начала посмотрим на $Phi'$:
$
Phi' = mat(0, 1/2, 0; 0, 0, -2z; 1/3, 0, 0).
$
Проблемы начались, как только мы попыталсь обратить $Phi_2$. Так давайте выберем $Phi_2$ как-то по-другому. Этот диффеоморфизм обязан сохранять $2$ координаты, быть обратимым, и посчитать что-то, чтобы следующий диффеоморфизм ($Phi_1$) мог сохранить одну. Попробуем просто угадать.
Например, скажем, что $y$ и $z$ мы обязательно сохраним. Тогда у нас должен иметься способ вывести $x$. $Phi(x, y, z) = (y/2, 1 - z^2, x/3)$. Например, попробуем $Phi_2 (x, y, z) = (x/3, y, z)$. Так мы посчитали $x/3$, и $Phi_1$ не придется его пересчитывать. Тогда $Phi_1 (x, y, z) = (y/2, 1 - z^2, x)$. Их композиция и правда $Phi$.
Хорошо, а как без угадывания? В построении из леммы, мы хотели, чтобы $phi'_u$ --- уголовой минор матрицы $Phi'$, был ненулевым. Тогда $Phi_2$ будет обратимым автоматически. Давайте заставим этот минор быть ненулевым. Для этого мы добавим третий диффеоморфизм $Phi_0^(-1)$ в конец, который будет переставлять переменные как мы хотим. То есть теперь
$
Phi = Phi_0^(-1) compose Phi_1 compose Phi_2,
$
и $Phi_0$ --- просто перестановка переменных. В нашем примере подойдет перестановка
$
Phi_0 (x, y, z) = (z, x, y), space Phi_0^(-1) (x, y, z) = (y, z, x).
$
Тогда
$
Phi_1 compose Phi_2 = Phi_0 compose Phi = (x/2, y/3, 1-z^2)
$
и
$
Phi_1 compose Phi_2 = mat(
1/2, 0, 0; 0, 1/3, 0; 0, 0, -2z
)
$
А вот у этой штуки уже угловой минор имеет определитель $1/2$.
Давайте доделаем, для честности.
$
Phi_1 (x, y, z) &= (x, f_y (x, y, z), f_z (x, y, z)), \
Phi_2 (x, y, z) &= (g(x, y, z), y, z).
$
$
Phi_1 compose Phi_2 = (g(x, y, z), f_y (g(x, y, z), y, z), f_z (g(x, y, z), y, z)) = (x/3, y/2, 1-z^2).
$
Отсюда $g(x, y, z) = x/3$, $f(x, y, z) = (y/2, 1 - z^2)$, и
$
Phi_1 (x, y, z) = (x, y/2, 1-z^2),\
Phi_2 (x, y, z) = (x/3, y, z).
$
Только пока что $Phi_1 compose Phi_2 != Phi$, надо еще сделать что-то с $Phi_0$. Приделаем $Phi_0^(-1)$ к $Phi_1$, получим $Phi'_1$:
$
Phi'_1 (x, y, z) = Phi_0^(-1) compose Phi_1 = (y/2, 1 - z^2, x)
$
И вот теперь $Phi'_1 compose Phi_2 = Phi$.
/*
Сохранить $y$ и $z$ не получиться --- мы уже пробовали. Попробуем сохранить $x$ и $z$:
$ Phi_2 (x, y, z) = (x, g(x, y, z), z). $
Тогда $Phi_1$ обязан сохранить $y$:
$ Phi_1 (x, y, z) = (f_x (x, y, z), y, f_z (x, y, z)). $
И требуется, чтобы
$
Phi_1 compose Phi_2 = Phi ==>
(f_x (x, g(x, y, z), z), g(x, y, z), f_z (x, g(x, y, z), z)) = (y/2, 1 - z^2, x / 3).
$
Отсюда легко найти $g(x, y, z) = 1 - z^2$. Тогда
$ f(x, 1 - z^2, z) = (y/2, x/3)$. Снова не повезло.
К этому моменту становиться понятно, что чтобы получить обратимость $Phi_2$, нужно сохранить в $Phi_2$ такие координаты, чтобы по остальным можно было вывести $phi$. В нашем случае $phi = z/2$, а значит сохранить нужно $x$ и $y$. Попытка номер 3:
$
Phi_1 (x, y, z) &= (f_x (x, y, z), f_y (x, y, z), z),\
Phi_2 (x, y, z) &= (x, y, g(x, y, z)).
$
И мы хотим, чтобы композиция была правильной:
$
Phi_1 compose Phi_2 = (f_x (x, y, g(x, y, z)), f_y (x, y, g(x, y, z)), g(x, y, z)) = (y/2, 1 - z^2, x / 3).
$
Отсюда, $g(x, y, z) = x/3$, и
$
f(x, y, x/3) =
$
В доказательстве мы претворялись, что $Phi$ разбивается как $(phi, psi)$, но ничего не мешает нам разбить $Phi$, например, как $(psi_x, phi_y, psi_z)$. Давайте так и сделаем: $Phi = (#text(red, $y/2$), #text(blue, $1-z^2$), #text(red, $x/3$))$. Тогда $Phi_1$ будет оставлять на месте вторую координату, а $Phi_2$ --- первую и третью, то есть:
$
Phi_1 compose Phi_2 = (f_x (x, y, z), ) compose
$
*/
]
#follow(label: "diffeomorphism-decomposition+")[
Эту лемму#rf("diffeomorphism-decomposition") можно применить много раз.
$Phi: Omega -> tilde(Omega)$ диффеоморфизм, $Omega, tilde(Omega) in RR^m$, $a in Omega$. Тогда найдется окрестность $U_a$ такая, что $Phi bar_(U_a) = Phi_1 compose Phi_2 compose ... compose Phi_m$, где каждая функция $Phi_i$ диффеоморфизм, который оставляет на месте все координаты, кроме одной.
]
#example(name: "да, все еще от меня, и все еще непонятный")[
Можно просто расширить рассужение из леммы с двух функций на $n$. Доказательство получиться аналогично, просто будет больше букв и индексов. Но давайте сделаем по другому. Я покажу на примере, не строго, как получить это по индукции.
Давайте снова посмотрим на наш пример, и декомпозируем $Phi$ полностью. Мы знаем, что
$
Phi'_1 = (y/2, 1-z^2, x), Phi_2 = (x/3, y, z) ==> Phi'_1 compose Phi_2 = Phi.
$
$Phi_2$ уже оставляет все координаты кроме одной ($x$).
Разложим $Phi'_1$ на $Phi_3$ и $Phi_4$ (да, нумерация совсем сбилась, ну и ладно). И $Phi_3$, и $Phi_4$ должны сохранять на месте 2 координаты... Только лемма такого не умеет: она суммарно может сохранить 3 координаты, а мы хотим 4. С другой стороны, у нас уже одна координата стоит на месте: $x$. Давайте рассмотрим диффеоморфизм $Psi: RR^2 --> RR^2$ такой, что $Phi'_1(x, y, z) = (Psi (y, z), x)$. Тогда про $x$ не нужно думать вообще. Применим рассуждения из леммы к $Psi$ и разложим его как $Psi_1 compose Psi_2$. Абсолютно аналогичными рассуждениями,
$
Psi_1 (y, z) = (y, 1 - z^2), space Psi_2 (y, z) = (y/2, z).
$
Нетрудно убедиться, что и правда, $Psi_1 compose Psi_2 = Psi$.
Теперь восстановим $Phi_3$ и $Phi_4$:
$
(Phi_3 compose Phi_4) (x, y, z) = ((Psi_1 compose Psi_2)(y, z), x).
$
Подойдут, например
$
Phi_4 (x, y, z) &= (x, Psi_2 (y, z)) = (x, y/2, z),\
Phi_3 (x, y, z) &= (Psi_1 (y, z), x) = (y, 1-z^2, x).
$
]
#th(name: "Линделёфа", label: "lindelof")[
Из любого покрытия $Omega subset RR^m$ открытыми множествами можно выбрать не более чем счетное подпокрытие.
]
#proof[
Пусть $Omega subset Union_(alpha in I) G_alpha$, где $G_alpha$ открытые. Возьмем $a in Omega$. Найдется $beta in I$ такое, что $a in G_beta$. Оно открытое, поэтому $B_r (a) subset G_beta$. Пошевелим точку так, чтобы радиус и координаты точки стали рациональными, в нем все еще лежала точка $a$, то есть сделаем шар такой, что $a in B_tilde(r) (b) subset B_r (a) subset G_beta.$ Но таких шариков не более чем счетно. Для каждого шарика оставляем один элемент покрытия, который его содержит, получаем что хотели.
]
#th(label: "measure-diffeomorphism")[
Пусть $Phi: Omega -> tilde(Omega)$ --- диффеоморфизм, $Omega, tilde(Omega) in RR^m$. $A subset tilde(Omega)$ измеримо. Тогда $ lambda_m A = integral_(Phi^(-1) (A)) abs(Jj_Phi) dif lambda_m. $
]
Сейчас мы докажем, что из этой теоремы будет следовать формула замены переменной#rf("substitution"), причем не просто целиком из теоремы, а для любого частного случая $Phi$ получается, что можно подставлять в интеграл $Phi$. То есть чтобы доказать формулу замены переменной, нужно доказать эту формулу для произвольного диффеоморфизма. Однако это сложно сделать сразу, поэтому мы будем доказывать формулу по шагам, каждый раз доказывая ее для каких-то $Phi$ (через это доказывая теорему о замене переменной), и затем пользоваться заменой переменной для доказанных частных случаев чтобы доказать теорему для новых $Phi$.
#pr(label: "substitution-temp")[
Если теорема#rf("measure-diffeomorphism") верна для конкретного $Phi$, то для того же $Phi$ верна формула замены переменной#rf("substitution").
]
#proof[
1. $f = bb(1)_A$. Из теоремы#rf("measure-diffeomorphism"),
$
integral_tilde(Omega) bb(1)_A dif lambda_m =
lambda_m A =^rf("measure-diffeomorphism")
integral_(Phi^(-1) (A)) abs(Jj_Phi) dif lambda_m =
integral_Omega underbrace(bb(1)_(Phi^(-1) (A)), bb(1)_A compose Phi) abs(Jj_Phi) dif lambda_m =
integral_Omega (bb(1)_A compose Phi) dot abs(Jj_Phi) dif lambda_m.
$
2. $f$ --- простая: верно по линейности.
3. $f >= 0$ измеримая: записываем#rf("simple-approx") последовательность простых $0 <= phi_1 <= phi_2 <= ...$, $phi_n --> f$ поточечно. По теореме Леви#rf("levy") получаем что хотим. Не буду писать, все уже поняли.
4. $f$ суммируема: ну там поделили на плюс минус и вычли.
]
#line(length: 100%)
#let Omegat = $tilde(Omega)$
#let Omegatt = $tilde(Omegat)$
#proof(name: "теоремы")[
Запасайтесь попкорном.
*Шаг 1: Пусть $Omega = Union U_n$ --- не более чем счетное объединение открытых множеств. Если теорема верна для каждого $U_n$, то она верна и для $Omega$*. Пусть $A = usb A_n$, $A_n subset U_n$. Тогда $Phi^(-1) (A_n)$ дизъюнктны, так как $Phi$ --- биекция. Тогда
$
lambda A =
sum lambda A_n =^rf("measure-diffeomorphism")
sum integral_(Phi^(-1) (A_n)) abs(Jj_Phi) dif lambda =^rf("mfn-props''", "set-additive")
integral_(Phi^(-1) (A)) abs(Jj_Phi) dif lambda.
$
*Шаг 2: Если теорема верна для диффеоморфизмов $Phi$ и $Psi$, то она верна и для $Phi compose Psi$*. Пусть $ Omega -->^Phi Omegat -->^Psi Omegatt, A subset Omegatt. $
Тогда
$
lambda A =^rf("measure-diffeomorphism")
integral_(Psi^(-1)(A)) abs(Jj_psi (x)) dif lambda(x) =^((*))
integral_(Phi^(-1)(Psi^(-1)(A))) abs(Jj_Psi (Phi (x))) dot abs(Jj_Phi (x)) dif lambda(x) newline(=)
integral_(Phi^(-1)(Psi^(-1)(A))) abs(det (Psi'(Phi (x)))) dot abs(det Phi' (x)) dif lambda(x) =
integral_(Phi^(-1)(Psi^(-1)(A))) abs(det (Psi'(Phi) Phi')) dif lambda newline(=)
integral_(Phi^(-1)(Psi^(-1)(A))) abs(det (Psi compose Phi)') dif lambda =
integral_(Phi^(-1)(Psi^(-1)(A))) abs(Jj_(Phi compose Psi)) dif lambda.
$
Переход $(*)$ верен по теореме о замене переменной#rf("substitution"), которой, как мы выяснили#rf("substitution-temp"), здесь можно пользоватся.
*Шаг 3: $m = 1$*. $ integral_(a, b] abs(phi') dif lambda_1 = abs(phi(a) - phi(b)) = lambda_1 (phi(a), phi(b)]. $ Это формула Ньютона-Лейбница.
Определим $nu A = integral_(phi^(-1)(A)) abs(phi') dif lambda_1$ --- мера, которая на ячейках совпадает с $lambda_1$. Значит $nu = lambda_1$ по единственности продолжения#rf("standard-continuation-unique"). Значит и для всех остальных измеримых множеств формула работает.
*Шаг 4: Теорема верна для диффеоморфизмов, которые оставляют все координаты кроме одной*.
$Phi: Omega --> Omegat$ диффеоморфизм, не изменяющий $m - 1$ координаты. Диффеоморфизм может их переставлять, но нам и не важно, то теореме Тонелли#rf("tonelli") или Фубини#rf("fubini"), перестановка не меняет значение интеграла. Более того, потребуем, чтобы диффеоморфизм не трогал именно первые $m - 1$ координаты. Пусть $(y, t)$, где $y in RR^(m - 1)$, $t in RR$ --- аргументы $Phi$. Тогда $Phi(y, t) = (y, phi(y, t))$.
$ lambda_m Phi(A) =_"Кавальери"^rf("cavalieri") integral_(RR^(m - 1)) lambda_1 (Phi (A))_y dif lambda_(m - 1) (y). $
Посмотрим на сечения поближе:
$
(Phi(A))_y =
{s in RR: exists a in A space Phi(a) = (y, s)} =
{s in RR: exists x in A_y space Phi(y, x) = (y, s)} newline(=)
{s in RR: exists x in A_y space phi(y, x) = s} =
phi(y, A_y).
$
Значит
$
integral_(RR^(m - 1)) lambda_1 (Phi (A))_y dif lambda_(m - 1) (y) = integral_(RR^(m - 1)) lambda_1 (phi(y, A_y)) dif lambda_(m - 1) (y) = \ integral_(RR^(m - 1)) integral_(A_y) abs(phi'_t (y, t)) dif lambda_1 (t) dif lambda_(m - 1) (y).
$
В последнем переходе мы воспользовались предыдущим шагом: мера $lambda_1$ равняется внутреннему интегралу, так как для одномерного случая мы уже это знаем. Посмотрим на $Phi'$:
$
Phi' = mat(E, 0; phi'_(y_1) ... phi'_(y_(m - 1)), phi'_t).
$
Якобиан $Phi$ тогда равен $phi'_t$. Значит
$
integral_(RR^(m - 1)) integral_(A_y) abs(phi'_t (y, t)) dif lambda_1 (t) dif lambda_(m - 1) (y) =
integral_(RR^(m - 1)) integral_(A_y) abs(Jj_Phi) dif lambda_1 (t) dif lambda_(m - 1) (y)
=^(rf("tonelli") rf("fubini"))_"Тонелли\nФубини"
integral_A abs(Jj_Phi) dif lambda_m.
$
#line(length: 100%)
Теперь собираем доказательство из кусочков.
Рассматрим каждую точку $a in Omega$. Применим к каждой точке лемму#rf("diffeomorphism-decomposition+"). $U_a$ --- окрестность из леммы, $Phi bar_(U_a) = Phi_1 compose Phi_2 compose ... compose Phi_m$, где $Phi_i$ оставляют $m - 1$ координату.
По теореме Линделёфа#rf("lindelof") оставляем не более чем счетное количество окрестностей.
Шаг 1 говорит, что достаточно проверить теорему только для этих $U_a$, и для всего $Omega$ она будет верна. Шаг 2 говорит, что достаточно проверить утверждение для произвольного $Phi_j$, и для композиции всех теорема тоже будет верна. Шаг 4 осуществляет проверку для $Phi_j$, опираясь на шаг 3.
Теорема доказана.
Значит формула замены переменной тоже доказана#rf("substitution-temp").
]
#notice[
Можно записать формулу по-другому:
$ integral_(Phi(A)) f dif lambda_m = integral_A (f compose Phi) abs(Jj_Phi) dif lambda_m. $
Здесь $Phi: Omega --> Omegat$ диффеоморфизм, $A subset Omega$.
]
#proof[
$
integral_(Phi(A)) f dif lambda_m =
integral_(Omegat) bb(1)_(Phi(A)) dot f dif lambda_m =^rf("substitution")
integral_Omega f compose Phi dot bb(1)_A dot abs(Jj_Phi) dif lambda =
integral_A (f compose Phi) abs(Jj_Phi) dif lambda_m.
$
]
#notice[
$Phi: Omega --> Omegat$ такое, что $exists e in Omega$ и $tilde(e) in Omegat$, такое, что $lambda e = lambda tilde(e) = 0$, и $Phi bar_(Omega without e): Omega without e --> tilde(Omega) without tilde(e)$ --- диффеоморфизм, и то формула все равно верна.
]
#proof[
Выкинем из интегралов слева и справа эти множества нулевой меры. Интегралы не изменятся.
]
#example(label: "gaussian-integral")[
Полярные координаты: $(r, t) ~~> (r cos t, r sin t)$, преобразовывающие "полосу" в плоскость без прямой.
Тогда $ vec(r, t) -->^Phi vec(r cos t, r sin t), Phi' = mat(cos t, -r sin t; sin t, r cos t) ==> Jj_Phi = det Phi' = r cos^2 t + r sin^2 t = r. $
Записываем формулу замены переменной#rf("substitution") (теорема Фубини#rf("fubini") позволяет записать интеграл по двумерному множеству как двойной):
$
integral_(RR^2) f dif lambda_2 = integral_([0, +oo)) integral_([0, 2pi]) r f (r cos t, r sin t) dif lambda_1 (t) dif lambda_1 (r).
$
Подставим $f(x, y) = e^(-x^2 - y^2)$, $f(r cos t, r sin t) = e^(-r^2)$:
$
integral_(RR^2) e^(-x^2 - y^2) dif x dif y = integral_0^(+oo) integral_0^(2pi) r e^(-r^2) dif t dif r = 2pi integral_0^(+oo) r e^(-r^2) dif r = (- pi e^(-r^2)) bar_0^(+oo) = pi.
$
Кстати,
$
integral_(RR^2) e^(-x^2 - y^2) dif x dif y = integral_RR e^(-x^2) dif x dot integral_RR e^(-y^2) dif y = (integral_RR e^(-x^2) dif x)^2 ==> integral_RR e^(-x^2) dif x = sqrt(pi).
$
Этот интеграл иногда оказывается полезен.
]
|
|
https://github.com/Simgnt/report-typst-template | https://raw.githubusercontent.com/Simgnt/report-typst-template/main/README.md | markdown | # Report Format
Template typst pour quarto correspondant au format du rapport de stage ENSAE. Il suffit de télécharger le dossier _extensions dans son environnement et de remplir le header de la même façon que dans le template.
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/delimited_08.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test colored delimiters
$ lr(
text("(", fill: #green) a/b
text(")", fill: #blue)
) $
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/matrix_06.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
$ mat(B, A B) $
$ mat(B, A B, dots) $
$ mat(B, A B, dots;) $
$ mat(#1, #(foo: "bar")) $
|
https://github.com/hash-roar/typst-math-template | https://raw.githubusercontent.com/hash-roar/typst-math-template/main/two_clolumn_thesis/main.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "math",
authors: (
(name: "<NAME>", email: "<EMAIL>"),
),
abstract: [#lorem(30)],
date: "April 18, 2023",
keywords: ("word1", "word2", "word3"),
)
#set heading(numbering: "1.1")
// We generated the example code below so you can see how
// your document will look. Go ahead and replace it with
// your own content!
= Introduction
#lorem(10)
$
T_1 = (sqrt(N)(O_(11)O_(22)-O_(12)O_(21))) / sqrt(n_1n_2C_1C_2 )
$
== In this paper
#lorem(20)
#figure(
caption: "Figure 1: A figure caption.",
image("cell.png")
)
=== Contributions
#lorem(40)
= Related Work
#lorem(500)
|
|
https://github.com/qujihan/typst-beamer | https://raw.githubusercontent.com/qujihan/typst-beamer/main/example/example.typ | typst | MIT License | #import "../beamer.typ": beamer
#show: beamer.with(
title: "Write a Beamer Template in Typst",
author: "<EMAIL>",
date: "2023-04-03",
)
= Show Time
== Offical Example Code (Fibonacci sequence)
#lorem(20)
$ F_n = round(1/sqrt(5) phi.alt^n), quad phi.alt = (1 + sqrt(5))/2 $
#let count = 8
#let nums = range(1, count+1)
#let fib(n) = (
if n <= 2{
1
} else {
fib(n - 1) + fib(n - 2)
}
)
#align(center+horizon, box(width: 60%,lorem(20)))
#align(center+horizon, table(
columns: count,
..nums.map(n => $F_#n$),
..nums.map(n => str(fib(n)))
))
== Pic Example
#align(center + horizon,
figure(
image(width: 50%, "seda.jpg"),
caption:[My friend photographed Seda in western Sichuan]
)
)
== Code Example
#columns(2,gutter: 5%)[
```golang
func bubbleSort(arr[] int) []int {
length := len(arr)
if length <=1 {
return arr
}
for i :=0;i < length - 1;i++ {
for j :=0;j < length - i -1;j++ {
if arr[j+1] > arr[j] {
arr[j],arr[j+1] = arr[j+1],arr[j]
}
}
}
return arr
}
```
#colbreak()
Bubble sort is a simple sorting algorithm that repeatedly compares adjacent elements in a sequence and swaps them if they are in the wrong order (ascending or descending). The larger (or smaller) elements gradually "bubble" to the end of the sequence.
]
= Todo
== Footer
#box(width: 90%,text([
There's no support for footer because I can't use it yet, but I'll add it as soon as I can.
]))
== Catalogs
#box(width: 80%,text([
The part about the implementation of the catalog is too ugly, but the official hasn't provided too many ways to modify the catalog, so I'll leave it like this for now, and wait for future modifications
])) |
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/mgmt_summary.typ | typst | = Management Summary
== Initial Situation
Many teachers use tools like Scratch or LEGO Mindstorms when introducing
children and young adults to the programming world. Such visual, block-based
tools eliminate the hurdle of code syntax, allowing beginners to concentrate on
the program they want to write.
However, almost all visual tools for teaching programming are made for the imperative
programming paradigm. Visual tools exist for functional programming, but either lack
a good user experience or hide essential concepts required to understand functional
programming.
== Objective
With VisualFP, a visual, block-based tool should be designed that can be used to
teach functional programming. At the center of this project is a design concept
for visual function composition, describing how the visual editor of such a tool
would work. A proof of concept application with a visual function editor should
be created to prove the concept is feasible.
A potent type inference engine is necessary for such an editor to work,
which shall be implemented using a unification algorithm as proposed by Simon
<NAME> @spj-ghc-inference. An overview of a unification-based engine
is shown in @management-summary-inference-engine.
#figure(
image("./static/inference-engine.svg", width: 65%),
caption: [Type-inference engine components]) <management-summary-inference-engine>
Additionally, the application should run on the user's machine so that it can
be used in classrooms without server infrastructure.
== Results
The developed concept uses nested blocks to represent function definitions. Type
holes guide the development flow as typed placeholders for missing pieces of a value definition. Users can drop value blocks into a type hole to
fill it with that value. Value blocks are provided by the editor or are defined
by the user.
The concept was implemented in a proof of concept application written using
Haskell and Electron.js. A component-level view of the application is provided
in @management-summary-component-diagram.
#figure(
image("./static/component_diagram.svg", width: 100%),
caption: "C4 Component Diagram for VisualFP PoC"
) <management-summary-component-diagram>
The application includes a small selection of
pre-defined values that can be used to build a user-defined function. A
screenshot of the application is provided in @managmenet-summary-screenshot.
#figure(
box(stroke: 2pt, image("./static/management-summary-screenshot.png", width: 80%)),
caption: "Screenshot of the mapAdd5 function definition in VisualFP"
) <managmenet-summary-screenshot>
The implemented application proves that the developed design concept works as
envisioned. However, the application is not yet ready to be used in classrooms
as additional design and development is required to bring the idea to its full
potential.
#pagebreak() |
|
https://github.com/MALossov/YunMo_Doc | https://raw.githubusercontent.com/MALossov/YunMo_Doc/main/thesis.typ | typst | Apache License 2.0 | #import "./template/template.typ": *
#show: Thesis()
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/04-opentype/schemtic.typ | typst | Other | #import "/template/theme.typ": theme
#import "/lib/glossary.typ": tr
#let stroke = 1pt + theme.main;
#set grid.vline(stroke: stroke)
#set grid.hline(stroke: stroke)
#let graph-cell = (it, no-stroke: false) => block(
spacing: 0pt,
inset: 0.5em,
outset: 0pt,
stroke: if no-stroke { none } else { stroke },
it,
)
#let graph = align(center, grid(
columns: 4,
inset: 0.5em,
stroke: none,
grid.hline(),
grid.vline(),
grid.vline(x: 4),
grid.cell(align: left, colspan: 4)[OpenType 字体格式],
graph-cell(no-stroke: true)[
#graph-cell[全局元数据]
],
graph-cell[
#graph-cell[#tr[outline]]
A
B
...
],
graph-cell[
#graph-cell[#tr[metrics]]
全局#linebreak()#tr[metrics]
A
B
...
],
graph-cell[
#graph-cell[高级#tr[typography]特性]
#tr[ligature]
#tr[kern]
...
],
grid.hline(),
))
#block(breakable: false, graph)
|
https://github.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024 | https://raw.githubusercontent.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024/master/expt01/report.typ | typst | #set page(margin: (left: 1.6cm, right: 1.6cm, top: 2.4cm, bottom: 2.4cm), numbering: "1")
#set text(font:("STIX Two Text", "Noto Serif CJK SC"), size: 1.07em, lang: "zh", cjk-latin-spacing: auto)
#set par(leading: 0.96em, justify: true)
#show par: set block(spacing: 1.25em)
#set heading(bookmarked: true)
#show heading: set text(size: 1.1em)
#show figure.caption: set text(font: "<NAME> (technical preview)", size: 1.1em, fill: rgb(55, 55, 55))
#set math.equation(numbering: "(1)")
#show link: underline
#show link: set text(fill: rgb(32, 120, 150))
// #set page(paper: "iso-b5")
#import "blockcode.typ": bc
#let em = (body) => {
set text(font:("<NAME> (Technical Preview)"), size: 1.1em)
[#body]
}
= 数字图像处理$quad$实验一
#include "./private.typ"
#stack(dir: rtl, spacing: 2em,
[
#figure(caption: "绕在支架上的钨丝的
扫描电子显微镜图像", image("images/Fig0327(a)(tungsten_original).png", width: 25%))<orig>
], block(width: 11.8cm)[
== 实验目的
+ #em[完成图像统计算法]:计算给定图像@orig 的直方图、均值和方差;
+ #em[实现图像增强算法]:根据教材提供的方案,完成选择性局部图像增强功能;
+ #em[探究参数选择方法]:通过实验分析增强关键参数对图像质量的影响规律,寻找合适的参数.
== 实验准备
压缩包中提供了源代码和编译后的单个网页文件,后者可以直接运行在浏览器中.
=== 使用编译后的代码
])
用浏览器打开压缩包中提供的 `第一次实验.html` 即可.打开后界面如@ui 所示.
#figure(caption: "UI 使用示例")[
#image("images/ui.png")
]<ui>
=== 开发环境配置
源代码需要编译后运行.如果需要修改源码,需要安装 #link("https://nodejs.org/")[Node.js] 并使用 npm 安装依赖,命令如下.
```sh
npm i -g pnpm
pnpm i
pnpm dev
```
然后,按照终端输出提示,打开 http://localhost:8080.
=== 开发环境介绍
为了方便查看效果,我采用了 Web 相关技术进行开发,编译后可以运行在任意操作系统的浏览器环境中.可以方便地选择本地的任意图片(受浏览器限制,仅限 `png` 和 `jpg` 格式),并且可以通过 UI 调整各个参数并实时查看结果.
同时,由于没有使用相关的图像处理库,所以在自行实现的过程中能够深入了解底层原理.
=== 图片的读取和显示
本实验中,代码允许用户选择本地图片作为输入.首先,用户通过 HTML 的文件选择器选择一张图片.接着,我们将图片绘制到 canvas 画布上,此时图片数据可以读取为 RGBA 形式的数组,即每个像素包含红、绿、蓝和透明度四个通道的值,范围皆为 0 $~$ 255.
由于我们假定实验处理的是灰度图像,因此我们定义了 ```ts toSingleChannel()``` 函数,将RGBA形式的数组转换为单通道的灰度值数组,以便后续处理.#em[灰度图像的红、绿、蓝三个通道的值相等],因此我们可以以任意三个通道中任意一个通道的值作为灰度值.
由于canvas的数据返回的是 ```ts Uint8ClampedArray``` 类型,即一个 8 位无符号整数数组.数据的排列为 $[r_0, g_0, b_0,a_0, r_1, g_1, b_1, a_1, dots, r_(n-1), g_(n-1), b_(n-1), a_(n-1)]$,我们需要将其转换为 $[r_0, r_1, dots, r_(n-1)]$ 的形式.
#bc(filename: "src/imageUtils.ts")[
```ts
function toSingleChannel(imgData: ImageData): SingleChannelImageData {
const length = imgData.width * imgData.height;
const data = new Uint8ClampedArray(length);
for (let i = 0; i < imgData.data.length; i++) {
// 灰度图像 r == g == b,alpha == 255,取 r 通道即可
data[i] = imgData.data[i * 4];
}
return {
data,
width: imgData.width,
height: imgData.height,
length,
};
}
```
]
处理图像完成后,我们又需要将处理后的单通道灰度值数组转换为 RGBA 形式的数组,才能绘制到canvas画布上显示或者转换成图片下载.因此我们定义了 ```ts toRGBA()``` 函数,将 $[h_0, h_1, dots, h_(n-1)]$ 转换为 $[h_0, h_0, h_0, 255, h_1, h_1, h_1, 255, dots, h_(n-1), h_(n-1), h_(n-1), 255]$ 的形式.
#bc(filename: "src/imageUtils.ts")[
```ts
function toRGBA(imageData: SingleChannelImageData): ImageData {
const rgba = new Uint8ClampedArray(imageData.length * 4);
for (let i = 0; i < imageData.length; i++) {
rgba[i * 4] = imageData.data[i];
rgba[i * 4 + 1] = imageData.data[i];
rgba[i * 4 + 2] = imageData.data[i];
rgba[i * 4 + 3] = 255;
}
return new ImageData(rgba, imageData.width, imageData.height);
}
```
]
== 图像统计特征
=== 计算全局直方图
首先创建一个长度为 256 的数组,并将所有元素初始化为 0.然后,遍历图像数据中的每个像素,并#em[将其灰度值作为索引],将对应灰度级的计数加 1.最后,返回计算得到的直方图数组.
#bc(filename: "src/histogram.ts")[
```ts
function histogram(imgData: SingleChannelImageData): number[] {
const hist = new Array(256).fill(0);
for (let i = 0; i < imgData.data.length; i++) {
const gray = imgData.data[i];
hist[gray]++;
}
return hist;
}
```
]
=== 显示直方图
为显示直方图,我采用了#link("https://echarts.apache.org/zh/index.html")[Apache ECharts],是最初由百度开发的一个基于 JavaScript 的开源可视化图表库.我们只需传入 $x$ 轴(0 ~ 255的一个递增数组)和 $y$ 轴(```ts data``` 或 ```ts normalizedDate```)两部分数据,后者需要设置 ```ts type: "bar"``` 指定为直方图.点击右上角的下载图标可以保存图片到本地.
#figure(caption: "直方图")[
#image("images/直方图.png", width: 91%)
]
将所有灰度的分量除以 $M times N$,即可得到如@normalized 所示的归一化的直方图:
#figure(caption: [规一化的直方图])[
#image("images/规一化的直方图.png", width: 88%)
]<normalized>
=== 计算全局均值
首先初始化一个累加变量 `sum` 为 0.然后,遍历图像数据中的每个像素,将其灰度值累加到 `sum` 中.最后,将 `sum` 除以图像数据长度,得到图像的全局均值并返回.
#bc(filename: "src/histogram.ts")[
```ts
function calculateMean(imgData: SingleChannelImageData) {
let sum = 0;
for (let i = 0; i < imgData.data.length; i++) {
sum += imgData.data[i];
}
return sum / imgData.data.length;
}
```
]
=== 计算全局方差
首先初始化一个变量 `sum` 为 0.然后,遍历图像数据中的每个像素,计算其灰度值与均值的差的平方,并累加到 `sum` 中.最后,将 `sum` 除以图像数据长度,得到图像的全局方差并返回.
#bc(filename: "src/histogram.ts")[
```ts
function calculateSigma2(imgData: SingleChannelImageData, m: number) {
let sum = 0;
for (let i = 0; i < imgData.length; i++) {
sum += Math.pow(imgData.data[i] - m, 2);
}
return sum / imgData.data.length;
}
```
]
== 选择性局部图像增强
=== 计算局部直方图
计算局部直方图的算法与全局直方图类似,只是对于只是对于每个像素,都需取邻域(一个子图像)进行计算.我们可以像@sub 这样设置,来查看一个 $5 times 5$ 子图像的直方图.
#figure(caption: "查看子图像的直方图", image("images/5x5.png"))<sub>
要计算一个局部直方图,为了性能考虑,我们不应复制一份子图像出来,而是根据坐标遍历局部.先封装一个计算给定的子图像的直方图的函数.我们在函数输入中用 $x$ 和 $y$ 表示子图像的左上角坐标(包含),$x_"end"$ 和 $y_"end"$ 表示右下角坐标(包含).
#bc(filename: "src/histogram.ts")[
```ts
/**
* 计算图像的局部直方图
* @param imgData 单通道图像数据
* @param x 邻域左上角 x 坐标
* @param y 邻域左上角 y 坐标
* @param x_end 邻域右下角 x 坐标
* @param y_end 邻域右下角 y 坐标
* @returns 邻域内的直方图,长度为 256
*/
function localHistogram(
imgData: SingleChannelImageData,
x: number,
y: number,
x_end: number,
y_end: number
): number[] {
const hist = new Uint8Array(256).fill(0);
// 如果超出图像边界,将其限制在图像边界内
const y_start = Math.max(y, 0);
y_end = Math.min(y_end, imgData.height - 1);
const x_start = Math.max(x, 0);
x_end = Math.min(x_end, imgData.width - 1);
/** 局部区域面积,在边界处会小于邻域面积 */
const area = (y_end - y_start + 1) * (x_end - x_start + 1);
for (let j = y_start; j <= y_end; j++) {
const base = j * imgData.width;
for (let i = x_start; i <= x_end; i++) {
// 由于图像数据是一维数组,我们需要将二维坐标转换为一维坐标
const idx = base + i;
// 取灰度值作为索引
const gray = imgData.data[idx];
hist[gray]++;
}
}
// 将 Uint8Array 转换为浮点数数组再对每个值除以面积,否则精度会丢失
return Array.from(hist).map((x) => x / area);
}
```
]
书中并没有提到在边界处对邻域的处理.原先的计算方法是将未归一化的直方图除以邻域的大小的平方,但这样实质上相当于在图像的行和列的首末填充0值,导致边界处出现全黑边框.
#bc(filename: "src/histogram.ts", type: "wrong")[
```ts
const area = neighborhood * neighborhood;
```
]
正确的计算方法是计算邻域的面积,即 $(y_"end" - y_"start" + 1) times (x_"end" - x_"start" + 1)$,其中 $x, y, x_"end", y_"end"$ 都应限制在图像边界内.
/*
#figure(caption: [错误(左)和正确(右)的计算方法结果])[
#stack(
dir: ltr, spacing: 2mm,
image("images/Fig0327(a)(tungsten_original).png-E 4-K0 0.37-K1 0.02-K2 0.4 N7.png", width: 12em),
image("images/correct-neighbor.png", width: 12em),
)
]
]
*/
=== 计算局部均值和方差
计算局部直方图的目的是计算局部均值和方差.
对于给定图像中任意像素的坐标,$S_(x y)$ 表示规定大小的以 $(x," "y)$ 为中心的邻域(子图像),记 $p_S_(x y)$ 为区域 $S_(x y)$ 中像素的规一化直方图,$r_i$ 为灰度,规定的邻域的边长为 $l$,则对于 $x=l,#h(.5em)l+1,#h(.5em)l+2,#h(.25em)dots.c,M-l-2,#h(.5em)M-l-1,quad y=l,#h(.5em)l+1,#h(.5em)l+2,#h(.25em)dots.c,N-l-2,#h(.5em)N-l-1$,像素的均值和方差分别如@mS 和@mSigma 所示.
$ m_S_(x y) = sum^(L-1)_(i=0) r_i p_S_(x y) (r_i) $<mS>
$ sigma_S_(x y) = sum^(L-1)_(i=0) (r_i - m_S_(x y))^2 p_S_(x y)(r_i) $<mSigma>
我们将每个像素邻域的均值和方差分别储存在两个数组中返回.
#bc(filename: "src/histogram.ts")[
```ts
function calcLocal(imgData: SingleChannelImageData, neighborhood: number) {
if (neighborhood % 2 === 0) throw new Error("邻域必须为奇数");
/** 邻域半径,例如 3x3 邻域半径为 1 */
const half = Math.floor(neighborhood / 2);
/** 存储每个像素根据邻域计算的均值 */
console.log(imgData.length);
const ms = new Array(imgData.length).fill(0);
/** 存储每个像素根据邻域计算的标准差 */
const sigmas = new Array(imgData.length).fill(0);
for (let j = 0; j < imgData.height; j++) {
for (let i = 0; i < imgData.width; i++) {
/** p 是邻域 $S_(x y)$ 的未规一化直方图,需要除以面积得到规一化直方图 */
const p = localHistogram(imgData, i - half, j - half, i + half, j + half);
let m = 0;
let sigma2 = 0;
for (let r = 0; r < 256; r++) {
m += r * p[r];
}
for (let r = 0; r < 256; r++) {
sigma2 += Math.pow(r - m, 2) * p[r];
}
const idx = j * imgData.width + i;
ms[idx] = m;
sigmas[idx] = Math.sqrt(sigma2);
}
}
return { ms, sigmas };
}
```
]
=== 逐像素处理
我们在之前计算了全局的均值 $m_G$ 和标准差 $sigma_G$,以及每个像素邻域的局部均值 $m_S$ 和标准差 $sigma_S$.这些统计特征将用于判断每个像素是否满足选择性增强的条件.接下来,我们遍历图像的每个像素.
$
g(x,y) = cases(
E dot.c f(x","y)","quad &m_S_(x y) <= k_0 m_G " 且 " k_1 sigma_G <= sigma_S_(x y) <= k_2 sigma_G,
f(x,y)"," quad &"其他"
)
$<enhance>
根据@enhance,对于每个像素,我们判断其局部均值 $m_S$ 和局部标准差 $sigma_S$ 是否满足以下条件:
- $m_S <= k_0 m_G$,即局部均值小于等于全局均值的 $k_0$ 倍;
- $k_1 sigma_G <= sigma_S <= k_2 sigma_G$,即局部标准差在全局标准差的 $k_1$ 倍和 $k_2$ 倍之间.
其中,$k_0$、$k_1$ 和 $k_2$ 是预设的常数,用于控制选择性增强的范围.
如果某个像素满足上述两个条件,我们就对其进行增强处理,将该像素的灰度值 $f(x,y)$ 乘以一个增强因子 $E$,即 $g(x,y) = E dot f(x,y)$,以提高满足条件的像素的对比度;如果像素不满足条件,我们就保持其灰度值不变,即 $g(x,y) = f(x,y)$.
我们还需要确保增强后的像素值仍然在 $0~255$ 的范围内.如果计算得到的像素值小于 0,我们将其设为 0;如果大于 255,我们将其设为 255.最后,将处理后的像素值存储到新的图像数据中,并将其转换为 RGBA 格式,绘制到 canvas 上显示.
#bc(filename: "src/App.svelte")[
```ts
function enhanceImage(origImage: SingleChannelImageData, neighborhood: number) {
/** 全局均值 */
const m_G = calculateMean(origImage);
/** 全局标准差 */
const sigma_G = Math.sqrt(calculateSigma2(origImage, m));
/** 局部均值和方差 */
const { ms, sigmas } = localHistogram(origImage, neighborhood);
const enhanced = new Uint8ClampedArray(origImage.data); // 复制原图像数据
for (let idx = 0; idx < origImage.length; idx++) {
const m_S = ms[idx];
const sigma_S = sigmas[idx];
if (m_S <= k0 * m_G && k1 * sigma_G <= sigma_S && sigma_S <= k2 * sigma_G) {
let px = Math.round(E * origImage.data[idx]);
if (px < 0)
px = 0;
else if (px > 255)
px = 255; // 确保像素值在 0~255 内
enhanced[idx] = px; // 更新增强后的像素值
}
}
... // 转换为 RGBA 图像数据并绘制到 canvas 上的代码省略
}
```]
通过这样的逐像素处理,我们实现了选择性局部图像增强.满足条件的像素得到增强,其他像素保持不变,从而提高了图像的整体质量.
== 增强关键参数选择
#set image(width: 25%)
#set stack(spacing: 2mm)
#let optimal = image("images/Fig0327(a)(tungsten_original).png-E 4-K0 0.4-K1 0.02-K2 0.4.png")
/ $E$ 参数: 增大 $E$ 会增强图像整体对比度,但可能导致细节丢失和噪声放大,如@E 所示.
- $E=3$ 时,暗区域的对比度偏小;
- $E=5$ 时,我们可以明显看出黑色和白色的噪点;
- 增强效果最好的是 $E=4$.
/ $K_0$ 参数: 控制了图像增强的整体阈值,如@K0 所示.
- $k_0 = 0.16$ 时,图像对比度略有提升,但整体效果不明显;
- $k_0 = 0.3$ 时,图像对比度进一步增强,但背景细节有部分失真;
- $k_0 = 0.4$ 时,图像对比度显著提高,失真较少.
- $k_0 = 0.5$ 时,图像对比度并未进一步增强,并且明亮区域的钨丝上出现了全白像素,过饱和导致出现了细节丢失的现象.
#figure(
placement: bottom,
stack(
dir: ltr, // left-to-right
image("images/Fig0327(a)(tungsten_original).png-E 3-K0 0.4-K1 0.02-K2 0.4.png"),
optimal,
image("images/Fig0327(a)(tungsten_original).png-E 5-K0 0.4-K1 0.02-K2 0.4.png"),
),
caption: [从左至右 $E = 3$,$E = 4$,$E = 5$ 时的增强效果]
)<E>
// / $K_0, K_1, K_2$: 调整阈值参数可以控制增强区域的选择性,从而突出特定特征.
#figure(
caption: [从左至右 $K_0=0.16$,$K_0 = 0.3$,$K_0 = 0.4$,$K_0 = 0.5$ 时的增强效果],
placement: bottom,
stack(
dir: ltr,
image("images/k0=.16.png"),
image("images/k0=.3.png"),
optimal,
image("images/k0=.5.png")
)
)<K0>
#figure(
caption: [从左至右 $K_1=0.008$,$K_1 = 0.020$,$K_1 = 0.048$ 时的增强效果],
placement: bottom,
stack(
dir: ltr,
image("images/Fig0327(a)(tungsten_original).png-E 4-K0 0.4-K1 0.008-K2 0.4.png"),
optimal,
image("images/Fig0327(a)(tungsten_original).png-E 4-K0 0.4-K1 0.048-K2 0.4.png"),
)
)<K1>
/ $K_1$ 参数: 控制了图像的对比度,如@K1 所示.
1. $K_1 = 0.008$ 是三张中增强最少的,纹理和细节较不明显,图像比其他两幅更平滑、细节较少;
2. $K_1 = 0.020$ 时,与 $K_1 = 0.008$ 相比,清晰度和对比度有明显提高,钨丝的层次更加分明,表面特征也更清楚;
3. $K_1 = 0.048$ 时,虽然支架上的白色噪点消失了,但暗处的细节出现了失真.
/ $K_2$ 参数: 控制了细节的提升幅度,如@K2 所示.
- $K_2 = 0.05$ 及 $K_2 = 0.1$ 时,增强效果较弱,图像暗处细节提升有限,背景细节大幅度失真;
- $K_2 = 0.2$ 时,增强效果显著;
- $K_2 = 0.4$ 时,锐利边缘处出现伪影,而暗处细节并未进一步提升.
#figure(
placement: top,
stack(
dir: ltr, // left-to-right
spacing: 2mm, // space between contents
image("images/Fig0327(a)(tungsten_original).png-E 4-K0 0.4-K1 0.02-K2 0.4.png", width: 25%),
image("images/Fig0327(a)(tungsten_original).png-E 4-K0 0.4-K1 0.02-K2 0.2.png", width: 25%),
image("images/Fig0327(a)(tungsten_original).png-E 4-K0 0.4-K1 0.02-K2 0.1.png", width: 25%),
image("images/Fig0327(a)(tungsten_original).png-E 4-K0 0.4-K1 0.02-K2 0.05.png", width: 25%),
),
caption: [从左至右 $K_2 = 0.4$,$K_2 = 0.2$,$K_2 = 0.1$,$K_2 = 0.05$ 时的增强效果]
)<K2>
/ $S_(x y)$ 参数: 增大局部区域大小可以平滑图像,但可能导致边缘模糊,并且在对比度较大的边缘处出现伪影,如@S 所示.
#figure(
stack(
dir: ltr, // left-to-right
spacing: 2mm, // space between contents
image("images/Fig0327(a)(tungsten_original).png-E 4-K0 0.37-K1 0.02-K2 0.4 N3.png"),
image("images/Fig0327(a)(tungsten_original).png-E 4-K0 0.37-K1 0.02-K2 0.4 N5.png"),
image("images/Fig0327(a)(tungsten_original).png-E 4-K0 0.37-K1 0.02-K2 0.4 N7.png", width: 25%),
),
caption: [从左至右邻域大小为 $3$,$5$,$7$ px 时的增强效果]
)<S>
|
|
https://github.com/thornoar/lambda-calculus-course | https://raw.githubusercontent.com/thornoar/lambda-calculus-course/master/main-lectures/problems-all.typ | typst | #import "template.lib.typ": *
#import "@local/common:0.0.0": *
#show: formatting
#let Mult = combinator([Mult])
#let Fac = combinator([Fac])
#set heading(numbering: none)
#head([ Задачи ])
= Конверсия и редукция
+
- Перепишите в формальной нотации: $y(@x..x y (@z%w..y z))$
- Перепишите в упрощённом виде: $(@v'(@v''((((@v v)v')v'')((v''(@v'''(v'v''')))v''))))$
+ Положим $X == #S#I$. Покажите, что $X X X X = X(X(X X))$. Правда ли, что $X^n X = X X^(~~ n)$ справедливо для всех $n in NN_0$?
+ Покажите, что выражение имеет нормальную форму:\
[a]#hs $(@y.. y y y)((@a%b.. a)#I (#S#S))$, #h(1fr)
[b]#hs $#S#S#S#S$, #h(1fr)
[c]\*#hs $#S (#S#S)(#S#S)#S$. #h(1fr)
+ Найдите л-выражение $M$, такое, что $forall N in #L: hs M N = M M$.
+ Докажите, что *не* существует такого $F in #L$, что $forall M, N in #L: hs F (M N) = M$.
+ Пусть $A == #S#K#K#K$. Постройте такое л-выражение $M$, чтобы выполнялась конверсия $#S#I M #K A = #S M #S #K A$.
+ Докажите, что правило эт-конверсии ($@x.. M x = M, hs forall M,x: x in.not TV(M)$) эквивалентно тому, что "функции равны, если равны их значения":
#v(-5pt)
$
M x = N x ==> M = N, #h(15pt) forall M, N, x : x in.not TV(M N).
$
#v(-5pt)
+
- Докажите, что: #h(1fr)
[a]#hs $#I inc #K$, #h(1fr)
[b]#hs $#I inc #S$, #h(1fr)
[c]\*#hs $x y inc x x$. #h(5fr)
- Постройте последовательность $M_0, M_1, ...$, такую, что $M_i inc M_j$, если $i eq.not j$.
+ Докажите, что $P inc Q hs <==> hs (#l + (P = Q)) tack.r #K = #KK$
+ Постройте последовательность л-выражений $M_0, M_1, ...$ так, чтобы $M_0 = v$ и для любого\ $n in NN_0$ выполнялось $M_(n+1) &= M_(n+2) M_n.$
+ Докажите, что $forall M in #L: hs exists N in #L: hs N #I ->>_beta M$, причём $N$ в б-нормальной форме.
+ Обозначим через $M arrow.t N$ условие $exists L: hs (L ->> M) and (L ->> N)$. Покажите, что:\
[a]#hs $(@x.. a x)b arrow.t (@y.. y b)a$, #h(1fr)
[b]#hs $(@x.. x c)c arrow.t (@x.. x x)c$, #h(1fr)
[c]#hs $(@x.. b x)c arrow.t (@x..x)b c$ #h(1fr)
+ Постройте л-выражения со следующими редукционными графами:\
#v(.3cm)
#grid(
columns: (4.5cm, 3.5cm, 5.5cm),
align: (center, center, center),
gutter: 1.6cm,
lambda-diagram(
spacing: 0.7cm,
{
let (A,B,C) = ((-1.5,0),(1.5,0),(0,-3))
lnode(A)
lnode(B)
lnode(C)
ledge(A,B, bend: 30deg)
ledge(B,A, bend: 30deg)
ledge(B,C, bend: 10deg)
ledge(A,C, bend: -10deg)
}
),
grid.cell(
rowspan: 2,
lambda-diagram(
spacing: 1.8cm,
{
import calc: *
let (A,B,C) = (
(cos(180deg), sin(180deg)),
(cos(60deg), sin(60deg)),
(cos(-60deg), sin(-60deg))
)
lnode(A); self(A, angle: 180deg)
lnode(B); self(B, angle: 60deg)
lnode(C); self(C, angle: -60deg)
ledge(A,B)
ledge(B,C)
ledge(C,A)
}
)
),
grid.cell(
rowspan: 2,
lambda-diagram(
spacing: 1.3cm,
{
let (A,B,C,D) = ((0,0),(0,-1),(0,-2),(0,-3))
let L = (1,0)
lnode(A)
lnode(B)
lnode(C)
lnode(L)
node(D, move($dots.v$, dy: 0.15cm), radius: 0.06cm, inset: 0cm, outset: 0cm)
ledge(A,B, bend: 20deg)
ledge(B,C, bend: 20deg)
ledge(C,D, bend: 20deg)
ledge(A,L, bend: 10deg)
ledge(B,L, bend: -10deg)
ledge(C,L, bend: -40deg)
self(A, angle: 180deg)
self(B, angle: 180deg)
self(C, angle: 180deg)
self(L, angle: 40deg)
}
)
),
lambda-diagram(
spacing: 1.1cm,
{
let (A,B,C) = ((-2,0),(0,0),(2,0))
lnode(A)
lnode(B)
ledge(A,B, bend: 40deg)
ledge(B,A, bend: 40deg)
self(A, angle: 180deg)
self(B, angle: 0deg)
}
),
)
#v(.5cm)
+ Нарисуйте редукционные графы следующих л-выражений:\
[a]#hs $(@x.. #I x x)(@x.. #I x x)$, #h(1fr)
[b]#hs $(@x.. #I (x x))(@x.. #I (x x))$ #h(1fr)
+ Пусть $M == A A x$, где $A == @a%x%z.. z (a a x)$. Докажите, что редукционный граф $Gr(M)$ содержит $n$-мерный куб при всех $n in NN_0$.
+ Покажите, что концептуально существует только одно л-выражение (а именно $#O$), имеющее следующий редукционный граф:
#align(center, lambda-diagram(
spacing: 1cm,
{
lnode((0,0))
self((0,0), angle: 0deg)
}
))
+ Расширим множество л-выражений двумя константами $delta, epsilon$. Также добавим новое правило редукции: $delta M M -> epsilon$ для любого $M in #L union {delta, epsilon}$. Докажите, что в получившейся системе *не* выполняется теорема Чёрча-Россера.
#box(
stroke: 0.5pt,
width: 100%,
inset: 0.25cm,
radius: 0.2cm,
[
Подсказка: найдите выражения $C$. $D$ такие, что
$
C x ->> delta x (C x),\
D ->> C D.
$
Докажите, что $D ->> epsilon$ и $D ->> C epsilon$, но у $epsilon$ и $C epsilon$ нет общего редукта.
]
)
+ Пусть $rel1$ и $rel2$ --- коммутирующие отношения на множестве $X$. Покажите, что $Trans(rel1)$ и $Trans(rel2)$ также коммутируют.
+ л-выражение $M$ _сильно нормализуется_ #h(2pt) (нотация $SN(M)$), если *не* существует бесконечного редукционного пути, начинающегося в $M$. Докажите, что:\
[a]#hs $SN(M) ==> M$ имеет нормальную форму;\
[b]#hs $SN(M) ==> Gr(M)$ конечен. Верно ли обратное?
+ Рассмотрим
$
"SN"_0 &:= { M in #L | SN(M) },\
"SN"_(n+1) &:= { M in #L | forall N_1, N_2, ..., N_k in "SN"_n: hs M N_1 N_2 ... N_k in "SN"_n }.
$
Докажите, что\
[a]#hs $"SN"_1 subset "SN"_0$, но $"SN"_1 eq.not "SN"_0$.\
[b]#hs $"SN"_1 = "SN"_2 = "SN"_3 = ...$
+ Нарисуйте редукционные графы выражений:\
[a]#hs $H #I H$, где $H == @x%y.. x(\z.. y z y)x$;\
[b]#hs $L L #I$, где $L == @x%y.. x(y y)x$;\
[c]#hs $P Q$, где $P == @u.. u #I u$, $Q == @x%y.. x y #I (x y)$.
+ Постройте л-выражения с редукционными графами:
#v(.7cm)
#grid(
columns: (6.5cm, 6.5cm),
align: (center, center),
gutter: 1.9cm,
lambda-diagram(
spacing: 2cm,
{
let (A,B,C) = ((0,0),(1,0),(2,0))
lnode(A)
lnode(B)
lnode(C)
ledge(A,B, bend: 15deg)
ledge(B,C, bend: 15deg)
self(A, angle: -90deg)
self(B, angle: -90deg)
}
),
lambda-diagram(
spacing: 2cm,
{
let (A,B,C) = ((0,0),(1,0),(2,0))
lnode(A)
lnode(B)
lnode(C)
ledge(A,B, bend: 15deg)
ledge(B,C, bend: 15deg)
self(B, angle: -90deg)
self(C, angle: -90deg)
}
),
grid.cell(
colspan: 2,
lambda-diagram(
spacing: 1cm,
{
let (A1,B1,C1) = ((0,1),(1,0),(0,-1))
let (A2,B2,C2) = ((4,1),(5,0),(4,-1))
let (A3,B3,C3) = ((8,1),(9,0),(8,-1))
let (A4,B4,C4) = ((9,1),(10,0),(9,-1))
lnode(A1)
lnode(B1)
lnode(C1)
lnode(A2)
lnode(B2)
lnode(C2)
lnode(A3)
lnode(B3)
lnode(C3)
ledge(A1, A2)
ledge(B1, B2)
ledge(C1, C2)
ledge(A2, A3)
ledge(B2, B3)
ledge(C2, C3)
ledge(A1, B1)
ledge(B1, C1)
ledge(C1, A1)
ledge(A2, B2)
ledge(B2, C2)
ledge(C2, A2)
ledge(A3, B3)
ledge(B3, C3)
ledge(C3, A3)
ledge(A3, A4)
ledge(B3, B4)
ledge(C3, C4)
}
)
)
)
#v(.7cm)
+ Покажите, что *ни одно* л-выражение не имеет редукционный граф
#align(center, lambda-diagram(
spacing: 1.8cm,
{
let (A,B1,B2,B3,C) = ((0,1),(-1,0),(0,0),(1,0),(0,-1))
lnode(A)
lnode(B1)
lnode(B2)
lnode(B3)
lnode(C)
ledge(A,B1)
ledge(A,B2)
ledge(A,B3)
ledge(B1,C)
ledge(B2,C)
ledge(B3,C)
}
))
+ Найдите л-выражение $M_0$ с редукционным путём
$
M_0 ->>_beta M_1 ->_eta M_2 ->>_beta M_3 ->_eta M_4 ->>_beta dots.h.c
$
+ Пусть $M_1 == (@x.. b x (b c))c$, $M_2 == (@x.. x x)(b c)$. Докажите, что *не* существует такого выражения $M$, что $M ->> M_1$ и $M ->> M_2$.
= л-представимость
+ Пусть $M_1, M_2, ..., M_k$ и $N_1, N_2, ..., N_k$ --- два набора л-выражений. Покажите, что
$
<< M_1, M_2, ..., M_k >> = << N_1, N_2, ..., N_k >> hs <==> hs M_1 = N_1, M_2 = N_2, ..., M_k = N_k
$
+ Постройте л-выражения $A, B in #L$ таким образом, чтобы $A x = A$ и $B x = x B$.
+ Постройте выражения $F, pi in #L^0$, такие, что:
- $forall n in NN: hs F nums(n) x y = x y^(~~ n)$
- $forall n in NN, hs forall i <= n: hs pi nums(n) num(i) = pi^n_i $
+
- Постройте л-выражение $Mult$, такое, что $Mult num(n) #h(3pt) num(m) = num(m n)$ для любых $m,n in NN_0$.
- Постройте л-выражение $Fac$, такое, что $Fac num(n) = num(n!)$ для любого $n in NN_0$.
+ _Элементарная функция Аккермана_ $phi$ определяется следующими соотношениями:
$
phi(0, n) &= n+1,\
phi(m+1, 0) &= phi(m, 1),\
phi(m+1, n+1) &= phi(m, phi(m+1, n)).
$
Покажите, что $phi$ рекурсивна, и найдите л-выражение, которое её л-представляет.
+ Постройте функцию предшествующего элемента для чисел Чёрча: $#P _c^-$ такое, что $#P _c^- c_(n+1) = c_n$ при всех $n in NN_0$.
+ Допустим, что каждый символ в упрощённой записи л-выражения (переменная, скобка, точка, запятая, лямбда) занимает 0.5см пространства на бумаге. Найдите л-выражение длиной менее 25см, имеющее нормальную форму длиной не менее $10^10^150$ световых лет (скорость света составляет $3 dot 10^10$ см/сек.)
#let p = math.pound
+ Пусть
$
pound &= @a%b%c%d%e%f%g%h%i%j%k%l%m%n%o%p%q%s%t%u%v%w%x%y%z%r.. r(t h i s i s a f i x e d p o i n t c o m b i n a t o r),\
dollar &= #p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p.
$
Покажите, что $dollar$ --- комбинатор неподвижной точки.
+ Докажите, что $M in #L$ --- комбинатор неподвижной точки $<==>$ $M = (#S #I) M$.
+ Пусть $f$, $g$ --- л-выражения. Положим $X == #Th (f circ g)$. Докажите, что $g(X)$ --- неподвижная точка выражения $g circ f$.
+ Положим $#Y _M == @f.. W W M$, где $W == @x%z.. f(x x z)$. Докажите, что $#Y _M$ --- комбинатор неподвижной точки для любого $M in #L$.
+ Докажите, что $#Y _M = #Y _N ==> M = N$. ($#Y _M$ и $#Y _N$ определены как в предыдущей задаче)
+
- Пусть $f : NN_0^2 -> NN_0$ --- рекурсивная функция. Постройте последовательность $X_0, X_1, ...$ л-выражений, такую, что при всех $n in NN_0$ выполняется $X_n X_m = X_(f(n,m))$.
- Пусть $X = { x_1, x_2, ..., x_n }$, и пусть $times$ --- бинарная операция на $X$. Постройте л-выражения $X_1, X_2, ..., X_n$ таким образом, чтобы выполнялось $X_i X_j = X_k hs <==> hs x_i times x_j = x_k$ при всех $i, j, k$.
+ Пусть $d$ --- числовая система. Докажите, что $d$ адекватна тогда и только тогда, когда
$
exists F, F^(-1) in #L: hs hs forall n in NN_0: hs hs (F nums(n) = d_n) and (F^(-1) d_n = num(n)).
$
#let C = combinator([C])
+ Пусть $d_0, d_1, ...$ --- адекватная числовая система. Положим $d'_n == #Y#C d_n$, где $#C == @x%y%z.. x(z y)$. Покажите, что все рекурсивные функции одного аргумента $phi : NN_0 -> NN_0$ л-представляются с помощью $d'$.\ (подсказка: рассмотрите $F' == @x..x F$)
+ Пусть $f_0 == @x%y%z.. y$ и $#S^+_f == @x.. <<x>>$. Покажите, что функции $#P^-_f == <<I>>$ и $Zero _f == @x%y%z.. x (@x'%y'%z'.. z')y z$ превращают $(f_0, #S^+_f)$ в адекватную числовую систему.
+ Рассмотрим последовательность $a_n == #K^n #I$. Покажите, что $a$ --- *не* числовая система.
+ Покажите, что множество ${ M in #L | M = #I }$ --- *не* рекурсивное.
+ Докажите, что существует л-выражение $M$, такое, что $M = num(M)$.\ (подсказка: обратите внимание на доказательство теоремы Скотта-Карри о неразрешимости)
+ Докажите _вторую теорему о неподвижной точке:_ $forall F in #L: hs exists X in #L: hs F nums(X) = X$.
|
|
https://github.com/tingerrr/anti-matter | https://raw.githubusercontent.com/tingerrr/anti-matter/main/src/util.typ | typst | MIT License | #import "@preview/oxifmt:0.2.0"
/// Run `func` in locate to get a location, skip locate if a location is already given.
///
/// - loc (location, none): a `location` which may not be set
/// - func (function): a function which receives a `location`
/// -> any
#let maybe-locate(loc, func) = {
if loc != none {
func(loc)
} else {
locate(func)
}
}
/// Returns the cardinality of a numbering pattern, i.e. the number of counting symbols it contains.
///
/// - pattern (str): the numbering pattern to get the cardinality for
/// -> integer
#let cardinality(pattern) = {
// this naiive check is fine because numbering patterns currently don't support escaping
let symbols = ("1", "a", "A", "i", "I", "い", "イ", "א", "가", "ㄱ", "\\*")
pattern.matches(regex(symbols.join("|"))).len()
}
/// Panics with an error message if the given pattern is not valid.
///
/// - pattern (any): a value that may or may not be a valid pattern
/// -> none
#let assert-pattern(pattern) = {
if type(pattern) not in (str, function, type(none)) {
panic(oxifmt.strfmt("Expected `str`, `function` or `none`, got `{}`", type(pattern)))
}
if type(pattern) == str {
let card = cardinality(pattern)
if card not in (1, 2) {
panic(oxifmt.strfmt(
"Pattern can only contain 1 or 2 counting symbols, had {} (`\"{}\"`)", card, pattern
))
}
}
}
|
https://github.com/lurbano/typstTemplates | https://raw.githubusercontent.com/lurbano/typstTemplates/main/article/Article%20Template%20(Spring%20Experiment)/main.typ | typst | MIT License | #import "template.typ": *
#show: u_ieee.with(
title: "Determining the Spring Constant of a Small, Green, Spring Scale",
abstract: [
We determined that the relationship between force and the displacement (stretching) of a spring was linear. Using linear regression with multiple small masses, the spring constant (proportinaliaty constant) for the small green spring scales was found to be 0.01 kg$dot$s #super[-2].
],
authors: (
(
name: "<NAME>",
department: [Dept of Makerspacetronautics],
organization: [The Fulton School],
location: [Chesterfield, MO],
email: "<EMAIL>"
),
),
//index-terms: ("spring constant", "force"),
bibliography-file: "refs.bib",
)
#let nonum(eq) = math.equation(block: true, numbering: none, eq)
// #let uFig(fig, capt) = {
// set par(leading:1em)
// rect(
// figure( image(fig), caption: capt)
// )
// }
= Introduction
When a force is applied along the axis of a spring, the spring stretches or compresses (@displacementDiagram). Our assignment was to determine if the relationship between the force applied and the amount of stretching (displacement) was linear, and if it was linear, what was the coeffecient of proportionality.
A linear relationship between force (F) and displacement ($Delta x$) can be represented by the proportionality relationship:
$ F prop Delta x $ <prop>
where:
#nonum(
$ F &= "force" [M L T^(-2)] \
Delta x &= "displacement" [L]
$)
// #uFig("Spring-elongation-applied-force2b.svg", [Force applied to spring results in displacement. Image adapted from @springImage.])
#figure(
rect(image("Spring-elongation-applied-force2b.svg", width: 80%)),
caption: [
Force applied to spring results in displacement. Image adapted from @springImage.
],
) <displacementDiagram>
The proportionality relationship from equation @prop yields the equation:
$ F = k dot Delta x $
where:
#nonum($ k = "proportionality constant" [M T^(-2)] $)
= Procedure
A green spring scale was suspended from a rod. Three different masses were attached to the hook at the end of the spring scale and the displacement of the spring measured.
= Results
#figure(
table(
columns: (auto, auto),
inset: 6pt,
align: center,
[*Mass (kg)*], [*Displacement (m)*],
"1",
"3",
"5",
"2"
),
caption: "Mass/displacement data."
) <displacementTable>
= Analysis and Discussion
The graph clearly indicates a linear relationship between the applied force and displacement, with a very high regression coefficient ($r^2$).
In terms of experimental design, while conducting this experiment, we learned that:
- more data is better, as it tends to average out errors from individual measurements,
- larger values relative to the absolute error results in smaller percent errors,
- data should be spread out as much as possible to be able to see trends
= Conclusion
The relationship between force applied to a spring and the spring's displacement is linear.
|
https://github.com/Myriad-Dreamin/shiroa | https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/packages/shiroa/utils.typ | typst | Apache License 2.0 |
#import "supports-text.typ": plain-text
#let _labeled-meta(label) = (
context {
let res = query(label)
if res.len() <= 0 {
none
} else if res.len() == 1 {
res.at(0).value
} else {
res.map(it => it.value)
}
}
)
#let _store-content(ct) = (
kind: "plain-text",
content: plain-text(ct),
)
/// helper function to get (and print/use) the final book metadata
#let get-book-meta() = _labeled-meta(<shiroa-book-meta>)
/// helper function to get (and print/use) the final build metadata
#let get-build-meta() = _labeled-meta(<shiroa-build-meta>)
|
https://github.com/crdevio/Livres | https://raw.githubusercontent.com/crdevio/Livres/main/Avant%20la%20MP2I/main.typ | typst | #import "template.typ": *
#import "tablex.typ" : *
#document(title: "Avant la MP2I - Informatique (2024)")[
#imp[Licence] Avant La MP2I is licensed under CC BY-NC-SA 4.0
#imp[Document encore en écriture !] Rejoignez le discord (https://discord.gg/wrAx8B96Jy)pour signaler les fautes d'orthographe (elles doivent être nombreuses), les fautes dans les exercices, etc. Si vous n'avez pas discord, un formulaire est disponible sur le site de ce document.
#imp[Objectifs] Ce document a été rédigé par un élève de classe MPI (désormais à Ulm) et non un professeur, il ne contient pas un "must-have" avant de rentrer en prépa. Il est en fait une compilation de points de cours et d'exercices classiques que j'aurais voulu avoir vu avant de rentrer en classe préparatoire. Le meilleur moyen d'utiliser ce document est de lire un chapitre par jour, de bien comprendre les points de cours et les notions présentées et ensuite d'attaquer les exercices. Si vous ne trouvez pas la solution à certains exercices, pas de panique : c'est normal. C'est la principale différence avec la terminale, le but n'est pas de trouver mais de chercher. En cherchant un exercice vous mobilisez des connaissances (tiens ça ressemble à tel théorème / telle propriété, oh et si j'essayais de faire ça ...) et peut-être que ça ne suffira pas pour résoudre l'exercice, mais vous aurez appris bien plus qu'en ayant trivialisé #ita[ (vous entendrez souvent ce mot)] un exercice d'application simple.
#imp[Sources] La plupart des exercices présentés sont des exercices auxquels j'ai pensé en écrivant le cours ou que l'on m'a envoyé (je remercie Wyrdix pour certains exercices dans la partie `Exercices sans thèmes précis`). Certains peuvent aussi venir de mon parcours en classe préparatoire, je n'ai pas forcément leur source précise mais les exercices viendront souvent de :
- Algorithms (<NAME>)
- Leetcode (site de programmation compétitive)
#imp[Les différents thèmes abordés] Ce document est volontairement léger en cours pour ne pas vous noyer pendant les vacances, il faut principalement vous reposer. Cependant, quelques exercices ne peuvent pas faire de mal et quelques définitions non plus (juste pour s'habituer aux notations de prépa). Voici la liste des points abordés dans l'ordre:
+ Qu'est-ce qu'un algorithme
+ Récursivité
+ Tableaux ou listes ?
+ Représentation des réels
+ Raisonner inductivement
+ Retour sur trace
+ Introduction aux graphes
+ Travailler avec des mots
+ Comment débuguer
+ Exercices sans thème précis
+ Corrections de certains exercices
#imp[Gardez ce polycopié à jour] en téléchargeant régulièrement la dernière version sur le site https://avantlampii.cr-dev.io/ ou directement depuis le github (https://github.com/crdevio/Livres)
#imp[Contribuez] vous pouvez utiliser le repo GitHub pour proposer vos Pull Requests (exercices, corrections, typos, etc).
#imp[Nouveautés de la version 2024]
- Ajouter de certaines corrections
- Ajout d'exercices
- Plus de margin-notes pour centrer le texte
- Ajout du cours sur le retour sur trace
- Changements mineurs de style
= Qu'est-ce qu'un algorithme ?
== Définition
Vous avez sans doute souvent entendu parler d'algorithme, que ce soit en NSI ou lors de vos cours de mathématiques au lycée, mais qu'est-ce que c'est exactement ? On serait tenté de dire qu'un programme Python est un algorithme... Mais non ! Ce serait plutôt une implémentation d'un algorithme. Pour le comprendre, voici la définition formelle d'un algorithme :
#def(title: "Algorithme")[Un algorithme est une suite d'instructions précises réalisant une tâche.]
#rem[] Instruction "précise" signifie qu'on ne doit pas douter, elle doit être claire ! Un ordinateur exécute le code de manière séquentielle #ita[en général], il ne doit pas y avoir d'ambiguïté sur la tâche à exécuter.
Cette définition peut surprendre si on ne l'a jamais vue : pas de notion de programmation et pas de notion d'ordinateur (trier votre main au Uno est un algorithme selon cette définition). C'est tout à fait normal puisqu'à l'époque où ce mot a été prononcé pour la première fois (IXème siècle) il n'y avait pas d'ordinateur pour implémenter les algorithmes, cependant on possède désormais cette définition :
#def(title :"Implémentation d'un algorithme")[On appelle implémentation d'un algorithme son écriture dans un langage de programmation.]
Cette définition correspond donc à ce que l'on vous a probablement qualifié d'algorithme au lycée. Vous pouvez maintenant comprendre, par exemple, que l'*algorithme du tri fusion* est une suite d'instructions permettant de trier une liste et que votre fichier `tri.py` est son *implémentation en python*.
== Exemple d'algorithme
Pour le premier exemple d'algorithme, on va considérer le plus classique (que vous avez probablement vu en Maths Exp.) : l'algorithme d'Euclide. Voici un rappel du principe #ita[c'est volontairement confus pour introduire l'intérêt d'avoir des instructions claires] :
Pour deux nombres `a` $>=$ `b`, si `b` est nul on renvoie `a` sinon on rappelle l'algorithme avec `a % b` et `b`.
La preuve mathématiques est sans intérêt ici (vous la ferez sûrement en début de première année) donc on va admettre que l'algorithme fonctionne. Je pense que vous avez pu le remarquer : cette notation pour l'algorithme n'est pas très pratique, si vous ne voyez pas où est le problème, voici une version plus propre (plus proche d'une suite d'instructions) de cet algortihme :
```
PGCD:
Entrée : a >= b
Si b>a alors renvoyer PGCD(b,a)
Sinon Si b=0 renvoyer a
Sinon renvoyer pgcd(a % b, b)
```
#rem[] Cet algorithme s'appelle lui-même, si vous l'avez déjà vu en NSI vous pouvez continuer à lire cette section, sinon je vous conseille de passer à l'introduction à la récursivité.
Maintenant que vous avez vu les deux versions, je suppose que si je vous demandais de me coder en python l'algorithme du PGCD, vous préféreriez avoir la deuxième version plutôt que la première comme indication : elle est plus claire. Cette définition est *informatiquement correcte mais elle n'a aucun lien avec votre ordinateur*, en fait je peux écrire le même genre de programme pour mon réveil et ça restera de l'informatique :
```
Reveil:
Entrée : cours1
Si cours1 != SI alors se_lever()
Sinon dormir()
```
Pour en revenir à l'aglorithme d'Euclide, la suite d'instructions définie est donc bien un *algorithme*, en revanche, le code suivant en est une implémentation en OCaml (*n'apprenez pas le OCaml pour le moment* ! Si vous souhaitez vous initier au OCaml, ce document contient dans les dernières pages un lien vers une super série de vidéos).
#cb(title : "Euclide en OCaml")[
```ocaml
let rec pgcd a b =
if b>a then pgcd b a
else begin
if b=0 then a
else pgcd (a mod b) b
end;;
```
]
#exo_nd(title: "Maximum", etoile: 1)[
1. Ecrire un algorithme qui prend en entrée un ensemble fini de valeurs (un objet similaire à une liste python) et qui permet d'en obtenir le plus grand élément.
2. L'implémenter dans le langage de votre choix.
]
#exo_nd(title: "Croissance")[
1. Ecrire un algorithme qui prend en entrée une suite finie de nombres (un objet similaire à une liste python) et qui vérifie si elle est de nature croissante.
2. Modifier votre algorithme pour qu'il permette de dire si la suite est croissante, décroissante, constante ou qu'elle ne possède aucune de ces propriétés.
]
#exo_nd(title: "Euclide borné", etoile: 2)[
1. Ecrire un algorithme (séquence d'instructions) qui prend en entrée trois entiers `a`, `b` et `t` et renvoie Vrai si l'algorithme d'Euclide termine en moins de `t` appels à l'algorithme (en accord avec l'algorithme récursif ci-dessus) et Faux sinon.
#rem[Il n'est pas possible de juste réaliser des appels à l'algorithme précédemment écrit, il faut le redéfinir et modifier son comportement]
]
#exo_nd(title: "Chevaux", etoile: 4, source: "ENS ULM")[
Vous avez 25 chevaux et vous voulez les 3 plus rapides, mais vous n'avez le droit qu'à 7 courses d'au plus 5 chevaux : comment faire ?
#rem[(INDICATION) Il faut des courses d'exactement 5 chevaux.]
]
== Comparer les algortihmes
Pour comparer deux algorithmes, on peut envisager plusieurs pistes. Une méthode naïve serait de lancer les deux algorithmes sur une même machine et comparer le temps de calcul. Cette méthode pose plusieurs problèmes :
- Qui nous dit qu'un l'algorithme n'est pas plus rapide qu'un autre à cause d'une spécificité du système ?
- On ne teste ici le programme que sur une seule entrée: rien ne nous assure que le résultat serait toujours valable pour d’autres entrées.
Il y a encore d'autres problèmes qui peuvent intervenir mais les deux cités suffisent à comprendre que ce n'est pas la piste à suivre.
Avant d'analyser un algorithme (en donner la #imp[complexité]), il faut savoir en fonction de quoi l'analyser. Par exemple, pour un algorthime de tri, l'analyser en fonction du plus grand élément passé en entrée n'a pas réellement de sens (puisqu'on suppose que la comparaison entre deux entiers est, à une constante près, la même indépendamment de la taille). En revanche, l'étudier selon la taille de la liste passée en entrée semble plus intéressant. On note désormais $n$ la taille de l'entrée.
Maintenant que l'on sait selon quel paramètre nous voulons étudier notre algorithme, il faut savoir ce que l'on veut mesurer. Notre but est d'obtenir une #imp[approximation asymptotique], ce qui (dans un langage plus raisonnable) revient à expliquer à quel point la complexité croît en fonction de l'entrée. Par exemple, pour une fonction qui parcourt deux fois une liste, on aura une croissance linéaire ($2 times n$). Ainsi, on notera $theta (n)$, ne vous tracassez pas pour la notation $theta$, il s'agit d'une des #imp[notations de Landau], elles sont au programme de NSI mais vous seront clairement rappellés en prépa. Retenez simplement que pour exprimer que #imp[la croissance de l'algorithme, notée $C_n$,est "à une constante près", une fonction $g(n)$], on note $C_n = theta(g(n))$.
Vous vous dîtes sûrement que cette notation n'a pas d'intérêt car écrire $2n$ est bien plus précis. Vous auriez raison si il n'y avait pas de constantes ignorés dans ce calcul. Pour comprendre ce que je viens de dire, voici un exemple :
#cb(
title: "NbJoursDeNoel"
)[
NbJoursDeNoel(`cadeaux[2...n]`):
```python
for i=1 to n:
Chanter “ Pour le i ème jour de Noël, j'ai reçu ”
for j=i downto 2
Chanter "j cadeaux[j]"
if i>1
Chanter "et"
Chanter "un oréo"
```
]
L'algorithme prend pour entrée une liste de $n-1$ cadeaux dans un tableau. On va donc exprimer la complexité selon cette taille $n$. On peut se rendre compte qu'on a une complexité $theta (n^2)$ à la main:
On fait une boucle principale de 1 à $n$ et à chaque appel on a une boucle de taille $i$.
On pourraît se dire qu'un calcul mathématiques nous permettrait de connaître la complexité précise de la fonction. Mais pour l'obtenir, il faudrait connaître la complexité de `Chanter`, or on sait juste qu'elle est constante, ce qu'on peut noter $theta(1)$. Il y a dès ce moment une approximation, aussi précis que l'on veuille être, cette approximation sera toujours la, il faut donc uniquement chercher un autre de grandeur car le $theta (1)$ de `Chanter` ne dépend pas de $n$ et n'affectera donc que par des constantes l'évolution de la complexité en fonction de la valeur $n$ passée en entrée.
=== À quel ordre regarder ?
Avant toute chose, on s'intéresse aux *pires cas* des algorithmes, c'est-à-dire les entrées les plus défavorables, ce qui permet de dire "je suis sûr que pour toute entrée, la complexité ne peut pas dépasser cet ordre de grandeur". Si on prend le meilleur cas, l'algorithme consistant à prendre une liste en entrée et attendre (boucle `while` ne faisant rien dans le cas non trié) qu'elle se trie toute seule est un algorithme de tri linéaire puisque le meilleur cas (liste triée) est de complexité linéaire (pour savoir si elle est triée). Il n'y a donc aucun intérêt à prendre le meilleur cas.
Voici deux algortihmes :
```
Algo1:
Entrée : une matrice de taille n*n symétrique
Pour i allant de 0 à (n-1)
Pour j allant de i à (n-1)
faire_truc(i,j)
```
```
Algo2:
Entrée : une matrice de taille n*n symétrique
Pour i allant de 0 à (n-1)
Pour j allant de 0 à (n-1)
faire_truc(i,j)
```
On pourraît se dire que le premier est plus optimisé car il va parcourir moins de cases, il ne va parcourir que la partie supérieure de la matrice. Or, si on fait une analyse fine, on aura une complexité (on suppose que `faire_truc` a un coût de 1) $1 + 2 + 3+ ... + n$ et cette somme vaut $n(n+1)/2$ (au programme de première spé maths), on a donc quelque chose "de l'ordre de $n^2$", c'est-à-dire qu'à un terme négligeable (tracer les fonctions $x -> x^2$ et $x -> x$ sur votre calculatrice ou sur géogebra) près, on a un algorithme de l'ordre de $n^2$. C'est le même ordre que pour l'algorithme 2 qui lui va pourtant parcourir toutes les cases.
En classe prépa (et souvent ailleurs, sauf si on est vraiment sur de l'optimisation à une ligne près, ce qui est rare) on ne cherche qu'à avoir des complexités "à un ordre près" (ce sera défini plus précisemment en maths, le but ici est juste d'avoir une idée) donc ce qui va compter va être une approximation. On ne va pas s'amuser à dire qu'une boucle qui effectue 6 opérations pour chacune des $n$ entrées est en complexité $6n$, on va dire qu'elle est de l'ordre de $n$ (noté $theta(n)$, le $theta$ aspire les constantes multiplicatives).
Depuis le début on utilise des $theta$ car on prend des exemples simples et qu'on peut à la fois minorer et majorer par des constantes multiplicatives les termes asymptotiques qui nous intéressent. En prépa (de mon expérience personnel), vous manipulerez beaucoup plus les $O$ qui sont uniquement des majorations (ie "cet algorithme ne peut pas être pire que celui-ci"), on va donc utiliser des $O$ à partir de maintenant en retenant qu'il suffit de majorer (ie écrire que $C_n <= k times g(n)$ avec $k$ une constante)
C'est en réalité très pratique, il devient beaucoup plus simple de donner des complexités à l'oeil nu :
```
Additionner_matrice:
Entrée : M une matrice de taille n*n
resultat <- 0
pour i allant de 0 à (n-1)
pour j allant de 0 à (n-1)
resultat <- résultat + M[i][j]
renvoyer resultat
```
On a deux boucles `for` (pour) imbriqués, chacune a $n$ éléments et la deuxième boucle exécute une opération $O(1)$ (une somme, un accès à `résultat` et une affectation), donc $O(n^2)$. Et *c'est tout* ! Si vous avez compris ça, vous savez donner la complexité de 50% des algorithmes que vous verrez durant vos années en prépa (évidemment il y aura des subtilités, notamment avec la récursivité, mais ceci est l'idée principale à avoir en tête).
#exo_nd(title: "Complexité du produit matriciel", etoile: 2)[
1. Ecrire un algorithme qui fait le produit de deux matrices. (on supposera les conditions nécessaires remplies)
2. Donnez-en la complexité.
]
#exo_nd(title: "Mais qui a inventé ça ?")[
1. Soit l'algorithme suivant :
```
CoffeeSearch:
Entrée: L une liste d'entiers de taille n, x un entier
Pour e dans L:
Si e == x, alors renvoyer Vrai
Sinon faire_un_cafe()
renvoyer Faux
```
Sachant que l'opération `faire_un_cafe` prend environ $100 000$ étapes, quelle est la complexité (à un ordre près) de l'algorithme `CoffeeSearch` ?
]
#pl(title: "Autres notions de complexité")[
Retiré après relecture.
]
#exo_nd(title: "Complexité du tri par insertion")[
1. Donner un algorithme pour le tri par insertion.
2. L'implémenter dans le langage de votre choix.
3. Donnez un ordre de grandeur de la complexité
]
#exo_nd(title: "Carmin-sur-mer", etoile: 2)[
#image("images/carmin.png",width:40%)
Voici l'arène de Carmin-sur-mer. Il y a $3$ rangées de $5$ poubelles devant vous. Deux d'entre elles contiennent un interrupteur, on sait qu'elles sont adjacentes.
Tant qu'aucun interrupteur n'a été trouvé, ils ne changent pas de position. Dès qu'un d'entre eux est trouvé, vous avez un essai. Si vous trouvez les deux interrupteurs, vous gagnez, sinon les interrupteurs changent aléatoirement de place et il faut recommencer.
1. Proposez un algorithme naïf pour trouver une solution à l'arène (celle qu'un enfant de 8 ans ferait).
2. Proposez une optimisation à l'aide d'un tableau de poubelles "déjà vus".
3. Sachant que si vous vous ratez plus de 100 fois, vous êtes assurés d'avoir bon à la 101ème tentative, quelle est la complexité de votre premier algorithme ? De la version optimisée ?
]
#exo_nd(title: "Inverser un tableau")[
1. Soit un tableau $T$ de taille $n$, proposez un algorithme permettant d'obtenir $T'$ le tableau inverse de $T$ (le premier élément de $T'$ est le dernier de $T$ etc).
#rem[Cet exercice est simple car on manipule un tableau, ie vous pouvez faire $T[i]$ pour récupérer le $i$-ème élément, dans la section sur la récursivité on verra que pour une liste, c'est une autre histoire]
]
#exo_nd(title: "Nombres premiers", etoile: 3)[
1. Donnez un algorithme qui permet de trouver les nombres premiers $<= n$ (si vous ne l'avez pas vu, cherchez sur internet : Crible d'Ératosthène)
2. Quelle est la complexité de cet algorithme ?
3. Est-il possible, de manière simple, de savoir si un nombre est premier ou non en complexité linéaire (c'est-à-dire en $O(n)$).
#rem[AKS n'est pas considéré simple !]
]
#exo_nd(title: "Sudoku, première rencontre", etoile: 2)[
Soit une grille de Sudoku qui possède des carrés de $n$ cases (sous forme de matrice, si vous ne savez pas comment ça marche, pas de panique, regardez la section sur les tableaux et les listes)
1. Donnez un algorithme qui étant donné une configuration (la grille est remplie avec certaines valeurs) renvoie Vrai si la partie est finie (indépendamment de si la solution est correcte ou non) et Faux sinon
2. Donnez un algorithme qui étant donné une configuration renvoie Vrai si la grille est correcte (si elle ne viole aucune règle du Sudoku) et Faux sinon
3. Donnez la complexité de chacun de vos algorithmes.
]
#exo_nd(title: "Bruteforcing pour les nuls")[
Vous venez de voler un PC à un inconnu dans un bus (ce n'est pas très gentil), vous courrez vous enfermer chez vous et vous l'allumez : il y a un mot de passe !
1. Si il s'agit des codes PIN de windows Hello (4 chiffres), combien d'essais vous faudrait-il pour bruteforce le mot de passe ? Ecrire l'algorithme.
2. Par manque de chance, vous avez bloqué Windows Hello : pas grave, il vous reste son mot de passe classique. Heureusement pour vous, il a laissé une note "longueur = 14". Sachant que son mot de passe n'utilise que des lettres de l'alphabet, combien de mot de passe faut-il tester ? Quelle serait la complexité d'un algorithme de bruteforce ?
3. Si vous savez que son mot de passe commence par un $P$, de combien pouvez-vous réduire la complexité ?
]
#exo_nd(title: "L'unique", etoile: 4)[
Ecrire un algorithme qui, étant donné une liste d'entiers telle que chacun des éléments dans la liste y soit exactement 2 fois sauf un unique élément, renvoie l'unique élément n'apparaissant qu'une seule fois. #ita[Vous ne devrez parcourir votre liste qu'une seule fois, interdit de revenir en arrière, interdit d'utiliser une mémoire externe autre que $O(1)$, cf le paragraphe Complexité Spatiale dans le chapitre récursivité si vous ne l'avez pas vu en NSI]
]
= Récursivité
== Définition
Commençons par définir une fonction récursive, nous rentrerons dans les détails juste après :
#def(title : "Fonction récursive")[
Une fonction est dite récursive si elle s'appelle elle-même dans son corps d'instructions
]
Par exemple, la fonction suivante est récursive :
```python
def fact(n): #on suppose n>=0
if n==0: 1
return n * fact(n-1)
```
Elle est strictement équivalente à cette fonction :
```python
def fact(n): #on suppose n>=0
res = 1
for i in range(1,n+1):
res*= i
return res
```
mais elle est plus simple à lire. La récursivité n'est évidemment pas qu'une simplification du code et a d'autres intérêts, mais pour commencer il est bien de comprendre qu'une fonction récursive peut en partie servir à avoir un code plus lisible.
#exo_nd(title: "Une première mise sous forme récursive")[
Soit la fonction suivante :
```python
def mystere(n):
res = 1
for i in range(2,n+1,2):
res*=i
return res
```
1. Que fait cette fonction ?
2. L'écrire sous forme récursive
3. Soit `mystere2` la fonction où le `range` est de la forme `range(1,n+1,2)`. Comment calculer `mystere` à partir de `fact` et `mystere2` ?
4. Quelle est la complexité de vos fonctions
]
#exo_nd(title: "Un produit")[
Proposez une fonction qui prend en entrée deux entiers `a` et `b` et qui calcule le produit `a` $times$ `b` sans avoir le droit d'utiliser l'opération $times$. Le réécrire en récursif si ce n'était pas déjà fait.
]
== Précautions
Dans le code de `fact`, il y a le cas `if n==0` qui est mis en première ligne, on appelle ce genre de cas les #imp[cas de base]. Ils sont primordiaux car sans eux votre programme tournerait à l'infini. Par exemple, si on passe `n=-1` à la fonction `fact`, elle produira une erreur. Les cas de base changent d'un problème à l'autre, il faut toujours faire attention à ne pas les oublier. De même, il faut faire attention à pouvoir garantir un #imp[variant] sur votre fonction récursive qui permet de garantir qu'elle atteindra un cas de base. Par exemple, dans la fonction `fact`, on peut garantir que `n` est strictement décroissant à chaque appel et donc atteindra 0, ie le cas de base. Voici quelques exercices :
#exo_nd(title: "Identifier un variant")[
1. Ecrire un algorithme récursif calculant la suite de Fibonacci
2. Donner les cas de base d'un algorithme calculant la suite de Fibonacci
($star$)3. Quel est le variant associé ?
]
#exo_nd(title: "Un peu de proba... ", etoile: 3)[
Soit l'algorithme suivant :
```
Proba:
Entrée: n et k deux entiers
if n==0:
renvoyer k
res<- lancer_piece()
if res == Pile:
renvoyer proba(n-1,k+1)
else:
renvoyer proba(n,k+1)
```
Exemple d'utilisation : `proba(n,0)`
1. Que fait cet algorithme ?
2. Est-ce une loi de Bernoulli ? Binomiale ?
3. Quelle est la probabilité qu'un appel baisse la valeur de $n$ ?
4. Avec quelle probabilité la valeur de $n$ ne décroît pas en $p$ appels ?
5. Proposez une estimation de la complexité
6. Proposez une application à cet algorithme.
]
== Comment fonctionne la récursivité $star$
À chaque appel, un "bloc d'activation" est ajouté dans votre ordinateur, plus il y en a, plus ils s'#imp[empilent]. Le terme d'empiler est important : Une pile est une structure de données où vous n'avez accès qu'à l'élément le plus au-dessus de la pile (comme une pile d'assiette) ie le dernier élément inséré. En fait c'est logique de n'avoir accès qu'au dernier appel : quand une fonction s'appelle elle-même de manière récursive, on ne pourra y accéder qu'une fois tous les appels postérieurs effectués. Ainsi quand votre ordinateur lit :
```
def f(n):
if n==0: return
f(n-1)
truc(n)
```
Il fait :
```
f(5) empilé
f(4) empilé
f(3) empilé
f(2) empilé
f(1) empilé
f(0) dépilé
truc(1)
f(1) dépilé
truc(2)
f(2) dépilé
...
```
#exo_nd(title: "Blocs d'activation")[
1. Donnez l'enchaînement décrivant `fact(5)`.
2. On propose l'algorithme suivant pour la suite de fibonacci :
```
fibo:
Entrée: n
Si n==0 renvoyer 0
Sinon Si n==1 renvoyer 1
Sinon renvoyer fibo(n-1)+fibo(n-2)
```
Donnez l'enchaînement décrivant `fibo(5)`
3. Pouvez-vous le faire pour `fibo(10)` ?
4. Codez cette fonction dans le langage de votre choix, pour quelle valeur de $n$ le temps d'attente devient trop long ?
]
== Complexité
=== Temporelle
Je ne vais pas rentrer dans les détails pour la complexité des fonctions récursives, vous le verrez dans le début de votre première année, le but ici est simplement de vous faire comprendre, avec les mains, quel algorithme sera infaisable et lequel sera faisable.
Si vous avez fait l'exercice 2-5, vous avez remarqué que pour une valeur de `n` assez faible, le programme devient impossible à lancer, mais pourquoi ? Si on note `C(n)` la complexité pour un appel avec la taille `n`, on peut voir la relation de récurrence suivante : `C(n) = C(n-1) + C(n-2) + 1` (le 1 est à peu près le coût de l'addition en tant qu'opération élémentaire). Ainsi, on peut voir que la fonction va calculer plein de fois les mêmes valeurs, sans rentrer dans les détails de la résolution, on trouve que la complexité vaut $C(n) = phi^n$ avec $phi$ un nombre $> 1$, ainsi la complexité $C(n)$ va exploser, ce qu'on appelle une complexité #imp[exponentielle].
À l'inverse, si on considère la fonction `fact`, on a une formule de la forme `C(n) = C(n-1) +1` et la, vous connaissez ! Si on réécrit ceci $u_n = u_(n-1) +1$ c'est une suite arithmétique, on trouve trivialement que $u_n = n$ donc $C(n) = n$, c'est une complexité linéaire donc tout à fait acceptable.
Pour aller un peu plus loin, on peut voir à la main que `fibo` va être bien plus lourde que `fact` en imaginant l'arbre des appels, on se rend compte que `fibo` va avoir, pour chaque appels, deux sous-branches (l'appel à $n-1$ et celui à $n-2$). Chaque sous-branche va elle-même en avoir deux et ainsi de suite, on appelle ceci un arbre binaire, vous le verrez en première année, visuellement cet arbre est bien plus lourd que les appels de `fact` qui ne font qu'une simple ligne.
=== Spatiale
Une autre notion importante est la complexité spatiale. En réalité, avec nos ordinateurs modernes, elle n'a la plupart du temps peu d'importance. Cependant elle peut-être utile dans des contextes précis (faire décoller une fusée entre autres) et peut aussi nous provoquer quelques erreurs embêtants, dont les fameux StackOverflow, qui sont un dépassement de l'espace alloué aux fonctions récursives (la pile où on stocke les blocs d'activation).
Comment évaluer la complexité spatiale ? Avec des langages comme Python, ce n'est pas toujours très facile : est-ce qu'un tableau a une taille bien adaptée, ou est-ce qu'il a été sur-évalué ? sous-évalué ? Bref, le fait que Python veuille nous simplifier la vie a des contre-parties, dont celui d'avoir plus de mal à identifier la complexité spatiale. On préfère alors les #imp[langages typés], ça tombe bien C et OCaml le sont ! C'est-à-dire que quand vous déclarez une variable, il faut en préciser le type. Ainsi, vous ne pouvez pas déclarer un tableau d'entiers et y stocker Harry Potter volume 1 (en Python, vous pouvez).
On va travailler en C dans la suite, pas de panique vous n'avez pas à savoir le manipuler pour le moment, c'est simplement pour être précis.
Prenons un premier exemple : on veut stocker `n` entiers. La commande C correspondante est :
```c
int* tableau = (int*)(malloc(sizeof(int)*n));
```
Ce n'est pas la syntaxe la plus simple, mais c'est la plus parlante. Sans rentrer dans les détails, on a `sizeof(int)` qui renvoie la taille d'un entier dans le système qu'on utilise et la multiplication par `n` qui permet d'être sûr qu'on a un `O(n)` comme complexité en espace.
On se rend donc compte que le C est certes un peu plus lourd en syntaxe, mais est mille fois plus précis que les instructions Python `tab = []` et `tab.append(truc)`.
Pour les fonctions récursives, si vous n'êtes pas en récursivité terminale (je ne rentre pas dans ces détails, vous verrez ceci en cours de OCaml), vous pouvez considérer que `n` appels récursifs à une fonction qui a une complexité spatiale $O(l)$ est en complexité spatiale $O(l times n)$. C'est logique : les blocs d'activations sont ajoutés à la pile d'exécution donc dans le pire cas, on a ajouté tous les blocs sans en retirer on a donc une pile de $n$ blocs de hauteur de $O(l)$ donc bien du $O(l times n)$. Ainsi, quand on demande des fonctions récursives en complexité spatiale $O(1)$, c'est que chaque appel doit être en $O(1)$ et que vous n'avez pas le droit de faire des opérations mémoires avant d'appeller la fonction (ie pas de tableau déclaré avant l'appel)
#exo_nd(title: "Rendre fibonacci linéaire" + $star$)[
1. Proposez une manière de rendre l'algorithme de fibonacci en complexité linéaire (toujours en récursif !) à l'aide de la "mémoïsation" (si vous n'avez pas eu NSI, la correction de cette question est disponible juste en-dessous)
($star star star$)2. Faîtes de meme, mais en complexité spatiale $O(1)$ (donc $O(k)$ pour $k$ appels récursifs)
]
#imp[Correction de la question 1 (exemple de mémoïsation)]
```python
def fibo(n):
tableau = [-1 for i in range(n)]
tableau[0] = 0
tableau[1] = 1
def aux(k):
if tableau[k] != -1: return tableau[k]
a1,a2 = aux(k-1),aux(k-2)
tableau[k] = a1+a2
return a2
aux(n)
```
#exo_nd(title: "Complexité spatiale")[
Donnez la complexité spatiale des fonctions suivantes :
1.
```python
def coucou(n):
print("coucou")
if n != 0 : return coucou(n-1)
```
#rem[Si vous connaissez déjà la récursivité terminale, n'en tenez pas compte dans votre réponse]
2.
```python
def useless(n):
t = []
while(True):
t.append(1)
```
3.
```python
def doublon(n,tab):
k = chercher_val_max(n) #on suppose O(1) espace
stockage = [false for i in range(k+1)]
for i in range(k):
if stockage[tab[i]]: return True
stockage[tab[i]] = True
return False
```
($star$)4.
```c
char* cc = (char*)(malloc(sizeof(char)*2));
cc[0] = 'c';
cc[1] = 'c';
```
($star$) 5.
```ocaml
let init n =
Array.make_array n False;;
```
]
#exo_nd(title: "Un tri", etoile: 2)[
Voici un algorithme de tri:
```
Tri:
Entrée: T tableau d'entiers de taille n
Si n==1: renvoyer ()
Sinon:
Tri(T[0:n/2],n/2)
Tri(T[n/2:n],n/2)
Fusionner(0,n,n/2)
```
En admettant que `Fusionner` est de complexité à peu près $n$, donnez une relation de récurrence décrivant la complexité de `Tri`. On admettra qu'elle se résoud en $n log(n)$.
]
#exo_nd(title: "Un beau sapin")[
1. Décrire un algorithme récursif qui affiche un sapin de Noël, ie quelque chose de cette forme :
```
*
***
*****
*******
*
```
($star$)2. Essayez d'en afficher 2 côte à côte
]
#exo_nd(title: "Palindrome")[
On suppose que l'on possède un type `parchemin` tel que on ait accès à trois informations :
la première lettre du parchemin (`p.premiere`), la dernière lettre du parchemin (`p.derniere`) et le parchemin correspondant au mot entre les deux. Si le parchemin ne contient qu'une seule lettre, `p.derniere` prend une valeur spéciale appellée `NULL`.
#ita[Par exemple, abc est codé a:(b:NULL):c]
1. Faites un dessin montrant comment les mots `coucou` et `bobob` sont encodés par ce parchemin.
2. Ecrire un algorithme qui prend en entrée un parchemin et renvoie `True` s'il code un palindrome et `False` sinon
]
#exo_nd(title: "Somme des chiffres", etoile: 2)[
1. Ecrire un programme qui prend en entrée un entier $n in NN$ et renvoie la somme de ses chiffres, par exemple `somme(1234)` $= 1+2+3+4 = 10$.
2. Ecrire un programme qui prend en entrée un entier $n$ et renvoie la somme des chiffres des nombres $<= 10000$ dont la somme des chiffres est inférieure ou égale à $n$
]
#exo_nd(title: "Compte à rebours", etoile: 2)[
Ecrire un programme qui, étant donné un entier $n in NN$, affiche `0 1 ... n (n-1) ... 0 1 .......` une infinité de fois
]
#exo_nd(title: "Maximum d'une matrice", etoile: 2)[
Ecrire un programme qui, étant donné une matrice de dimension $(n,p) in NN^2$, renvoie la liste des plus grands éléments sur chaque ligne. (de manière récursive)
]
#exo_nd(title: "Permutations", etoile: 3)[
(Tombé à ULM mais franchement c'était du vol)
Ecrire un programme qui, étant donné un entier $n in NN$, renvoie toutes les permutations de $[|1;n|]$.
#rem[On procédera récursivement. On peut le voir de deux manières, une méthode "simple" et une jolie méthode avec un arbre d'arité $n$]
]
#exo_nd(title: "Recherche dichotomique", etoile: 3)[
On se donne un tableau trié par ordre croissant, ie pour tout $i <j$, `tab[i]` $<=$ `tab[j]`.
1. Donnez un algorithme naïf (en complexité linéaire) pour trouver un élément $x$ dans un tel tableau
2. Proposez un algorithme qui exploite le côté croissant
3. Complexité ?
]
#exo_nd(title: "Jeu d'élimination", etoile: 2)[
On vous donne une #imp[liste] qui contient $[|1;n|]$
On applique l'algorithme suivant :
- On retire le premier élément à gauche puis tous les éléments qui sont sur des indices accessibles en faisant des pas de 2 depuis l'élément retiré (par exemple si on a `1 2 3 4`, on retire `1 3` et il reste `2 4`).
- On retire le dernier élément (donc le plus à droite) et on fait de même (avec le même exemple il resterait `1 3`)
- On répète en alternant tant qu'il ne reste pas qu'un seul élément
1. Donnez la réponse pour $n=9$
2. Codez un algorithme qui prend un entier $n$ et renvoie le dernier élément restant.
]
#exo_nd(title: "Puissance", etoile: 2)[
Ecrire un algorithme récursif qui renvoie $x^n$ pour $x in RR$ et $n in ZZ$.
]
#exo_nd(title: "ATOI", etoile: 3)[
En C, il y a une fonction très pratique qui prend en entrée une chaîne de caractère et renvoie le nombre associé, par exemple `atoi("125") = 125`.
Implémentez `atoi` dans le langage de votre choix.
]
== Note de fin
Actuellement vous pouvez encore vous demander "mais pourquoi on utilise la récursivité alors qu'un algorithme itératif suffit", la réponse sera immédiate quand vous aurez lu la partie sur les raisonnements inductifs. En attendant, essayez avant de passer à la section suivante d'avoir bien compris comment "penser récursif" : cas de base, relation de récurrence, variant, programmation.
= Tableaux ou listes ?
Depuis le début de ce document, je varie entre liste et tableau sans vraiment faire de différence : c'est fini. Un tableau et une liste sont deux structures totalement différentes en informatique.
== Tableau
#def(title: "Tableau")[
Un tableau est une structure de donnée qui peut stocker un nombre fini, précisé au préalable, d'éléments d'un type (souvent précisé au préalable aussi, mais ça dépend de l'implémentation)
]
Ainsi, on peut voir un tableau comme une structure à deux paramètres : `t.n` sa taille (`len` en Python) et `t.content` son contenu. Par exemple, `t[i]` signifie la `i`ème case de `t.content`. Le fait que la taille soit précisée au préalable peut être perturbant au début, surtout quand on vient de Python qui permet de faire `t.append(elt)` indépendamment d'une limite de taille; en fait c'est parce qu'en python ce ne sont pas vraiment des tableaux mais plutôt un mélange. À chaque fois que vous dépassez la limite de taille du tableau, sans vous le dire, Python augmente sa taille (elle croît selon la suite de Fibonacci) pour éviter un dépassement mémoire. L'avantage de cet objet est que quand on connaît par avance la taille de ce que l'on va manipuler, le tableau permet de récupérer un élément en complexité optimale ($O(1)$). En revanche, sa taille sera limitée, et si on veut l'améliorer, il faudra en payer le prix ($O(n)$ à chaque fois qu'on augmente la taille).
#exo_nd(title: "Tableau ?")[
Dire dans chacun des cas si un tableau est adapté ou non.
1. Stocker $n$ fixé entiers en mémoire et y accéder rapidement
2. Stocker les connexions à un site web sur une période d'1 heure sachant qu'il y a au plus 10 connexions par minute.
3. Stocker les connexions à un site web sur une période de 5 minutes
($star$)4. Implémenter une mémoire d'ordinateur
5. Faire des mesures de température toutes les 5ms pendant 10 secondes dans le cadre d'une expérience physique
]
#exo_nd(title: "Tableaux dynamiques")[
Un tableau dynamique est un tableau qui met à jour sa taille automatiquement quand il dépasse sa capacité. Voici quelques stratégies pour augmenter la taille d'un tableau à chaque fois qu'on la dépasse, sans justification et uniquement par votre intuition, dire les quelles sont intéressantes et pourquoi :
1. Dès qu'on dépasse $n$, on créé un nouveau tableau de taille $n+1$
2. Dès qu'on dépasse $n$, on double la capacité pour avoir $2n$
3. Dès qu'on dépasse $n$, on on prend le terme suivant dans la suite de Fibonacci.
]
== Listes
Une liste est une structure de donnée dans laquelle on a accès qu'au premier élément et à la suite. C'est-à-dire que pour représenter `1,2,3` sous forme de liste, on peut le voir comme ceci : `1:(2:(3))`. L'avantage principale est qu'il n'y a pas de taille pré-définie pour une liste, on peut à tout moment définir une nouvelle liste `4:l` par exemple avec `l = 1:(2:(3))`. Cependant, il y a un inconvénient, essayez de faire ce mini-exercice avant de lire la suite :
#exo_nd(title : "Inconvénient d'une liste")[
Selon vous, qu'elle va être la propriété utile d'un tableau qui ne sera plus vraie pour une liste ?
]
#imp[Cherchez l'exercice précédent avant de lire ceci] : Une liste ne permet plus d'accéder à un élément en $O(1)$, puisqu'on a accès qu'au premier élément et à la suite, si on veut accéder au dernier élément, on doit tous les regarder 1 à 1 et attendre de tomber sur celui qui n'a rien après lui, puisque la complexité étudiée est celle dans le pire cas, on a bien du $O(n)$ pour la recherche.
Mais alors pourquoi utiliser une liste ? Elle permet non seulement de manipuler des données dont on a aucune idée de la taille, mais hormis cet aspect, dans certaines applications on n'a pas besoin de chercher un élément précis et on veut tous les parcourir, dans ce cas la liste comme le tableau sont en $O(n)$ et l'avantage de la liste est qu'elle est naturellement pensée pour être récursive, en effet en voici la définition :
#def(title: "Liste")[
Une liste est soit la liste vide, soit un élément suivi d'une liste.
]
Ainsi on peut facilement donner des algorithmes sur les listes :
#exo_nd(title: "Plus grand élément d'une liste")[
Donnez un algorithme pour trouver le plus grand élément d'une liste : pensez récursif !
]
#exo_nd(title: "Liste ou tableau ?")[
Pour chacune des fonctions suivantes, dire si elle correspond à une liste ou tableau, justifier.
1. `append`
2. `pop`
3. `truc[i]`
]
#exo_nd(title: "Implémentation d'une fonctionnalité Python")[
Essayez de faire `tableau[::-1]` en python.
1. Quelle est cette opération ?
2 ($star$). Proposez une implémentation avec des listes.
3. Quelle est sa complexité ?
4. Faire de même avec des tableaux.
]
#exo_nd(title: "Concaténation")[
Proposez un algorithme qui prend en entrée deux listes et les concatènent, ie renvoie la liste des éléments de la première suivant des éléments de la deuxième.
]
#exo_nd(title: "Choix de structure")[
Supposons que vous vouliez stocker des données triées par ordre croissant et que vous souhaitiez avoir une structure qui permette d'optimiser certains algorithmes grâce à cette propriété, quelle structure allez-vous choisir : liste ou tableau ?
]
== Pourquoi le OCaml ?
Si vous avez déjà regardé un petit peu le programme, vous savez qu'il contient deux langages : C et OCaml. Le C est un choix logique, mais pour le OCaml cela peut vous sembler étrange. L'avantage du OCaml est qu'il fait partie des langages dans lequel il est simple d'écrire en récursif (il est pensé pour). Ainsi (et ce n'est qu'un exemple parmis de nombreux autres), on peut facilement manipuler des types qui sont définis inductivement. Cette facilité provient de l'outil `match` majoritairement, il permet de raisonner *par cas*, voici un exemple simple (je ne vous demande pas de comprendre la syntaxe, mais plutôt l'idée derrière):
```ocaml
let rec parcours l =
match l with
| [] -> print_string "Il ne reste plus rien\n"
| [e] -> print_string "Il ne reste qu'un élément\n"
| e::t -> (
print_string "Je viens de trouver l'élément: " ^ e ^ "\n";
parcours t
);;
```
Si on met de côté la syntaxe, on remarque qu'on peut distinguer différents cas en précisant "la forme attendue", on a par exemple `[e]` qui signifie une liste d'un seul élément. \
#rem[On aurait pu retirer le cas `[e]` car la liste vide reste une liste donc ce cas est englobé dans `e::t`, ici je l'ai juste mis pour bien comprendre les possibilités]
Implémenter ces algorithmes sera possible en C, mais beaucoup plus encombrant car C ne possède pas ce match (une méthode souvent utilisée consiste à ajouter un entier qui va indiquer le type, par
exemple liste vide codée par 0, une autre par 1)
== Note de fin
Je ne pense pas que ce chapitre soit un chapitre où les exercices soient utiles. Le but est uniquement de bien comprendre la différence et quand utiliser l'un / l'autre. Vérifiez donc bien (en dressant un petit tableau comparatif par exemple) que vous avez compris cette différence.
= Représentation des réels
== Représenter un entier
Pour représenter un entier dans un ordinateur, on utilise la base 2, ie une écriture #imp[en binaire]. Puisque nos ordinateurs permetttent de stocker tout un tas de 0 et de 1, autant s'en servir !
On admet pour cela pour un théorème que vous verrez en début de première année (en maths):
#th(title: "Représentation en base " + $k$)[
Pour $k >=1$, pour tout $n in NN$, il existe une unique manière d'écrire $n$ en base $k$, c'est-à-dire d'écrire $n = sum_(i=0)^(p) alpha_i k^i$ avec $forall i, alpha_i in [|0;k-1|]$.
]
Si on applique ce résultat pour $k=2$, on obtient que tout entier peut s'écrire de manière unique comme une somme de puissance de 2. Par exemple, $5 = 2^2 + 2^0$ et l'unicité permet d'assurer qu'il n'y a pas d'autres écritures.
#exo_nd(title: "Une première propriété")[
Comment, à partir de son écriture binaire, dire si un entier est pair ou impair ?
]
Ainsi, on représente un entier dans un ordinateur comme cette somme. Par exemple, $31 = 1 + 2 + 4 + 8 + 16 = 2^0 + 2^1 + 2^2 + 2^3 + 2^4$, donc on écrit $11111$ pour représenter $31$. Attention, on écrit dans l'ordre "inverse", c'est-à-dire que le 1 le plus à gauche correspond à $1 times 16$ et non $1 times 2^0$. Pour un autre exemple, $14 = 8 + 4 + 2 = 1110$.
#pl(title: [Entier maximum sur $n$ bits])[
Si on veut obtenir le plus grand nombre possible, il faut que tous les bits soient à 1. Dans ce cas on a $sum_(k=0)^(n) 2^k = 2^(n+1)-1$.
#exo_nd(title: "Autre justification")[
Proposez un autre argument que "pour maximiser il faut que les bits soient à 1" pour justifier qu'on ne peut pas faire mieux que $2^(n+1) - 1$.
#rem[(INDICATION) utiliser l'unicité]
]
]
#exo_nd(title: "Ecriture binaire")[
Donnez l'écriture binaire des nombres suivants :
1. 72
2. 89
3. 1
4. 0
5. 987
A la main, on peut faire des petites valeurs sans trop de souci, cependant, vous allez devoir écrire un algorithme pour celui-ci :
($star star$)6. 2946654722
]
== Sommer des entiers
Il s'agit du même algorithme que pour l'addition "à mains nues", on utilise une retenue.
Par exemple :
#exo_nd(title: "Somme en binaire")[
Calculez $11001 + 00011$ à la main, comme en CE2.
]
Et voilà, vous savez sommer des nombres en binaires !
== Soustraire des entiers
Pour faire $n-p$ en binaire, on fait $n + (-p)$. On procède ainsi car calculer $-p$ est simple si on prend la convention que le premier bit (celui de poids fort) est le bit de signe. Ainsi, si il vaut 0, on a un nombre positif, si il vaut 1, c'est un négatif.
#rem[On peut voir le nombre binaire $gamma 110$ comme étant $(-1)^gamma 110$ par exemple]
Pour obtenir $-p$ voici la procédure :
#imp[On inverse tous les bits et on ajoute 1 au nombre].
#exo_nd(title: "Pourquoi ?")[
Pourquoi ajoute-t-on 1?
]
#exo_nd(title: "Calcul binaire négatif")[
On se place dans une convention où le bit de poids fort est le bit de signe. Calculez les nombres suivants :
1. $10011 + 01010$
2. $1000 + 0001$
3. $1111 - 1111$
4. $1111 - 1110$
($star$)5. $1001 - 111000$ #ita[L'étoile est par rapport aux nombres de bits différents]
]
== Représenter des réels
Pour représenter un réel, on va l'écrire en écriture ingénieur, c'est-à-dire $(-1)^gamma 1,t r u c times 10^(e x p o s a n t)$. Le "truc" correspond à ce qu'on appelle la #imp[mantisse]. Il faut donc trouvrer un moyen d'encoder cette forme. Pour cela on a la #imp[norme IEEE-754], on encode en binaire les différentes parties en les écrivant à la suite. Ainsi, le premier bit (de poids fort) est celui de signe, puis on a $k$ bits pour l'exposant, le reste est réservé à la mantisse.
Par exemple, $1001111$ avec 3 bits de d'exposant peut se réécrire $1$ $001$ $111$. #imp[Il y a une subtilité sur l'exposant], $001$ n'est pas le code de l'exposant, c'est celui de l'exposant additionné à une valeur qui permet de ne coder que des entiers positifs, cette valeur est $2^(k-1) -1$. Ainsi, $001$ représente 1 en base 10 et ici $k=3$ donc le décalage est $1$, donc on a encodé $1-1 = 0$. Ainsi, l'exposant est nul. Puis on a le bit de signe qui est sur 1, donc on a un négatif. Enfin la mantisse est $111$ donc $0.5+0.25+0.125 = 0.875$, le réel encodé est donc $-1,875$.
#exo_nd(title: "Représentation des réels")[
Donner les réels correspondant aux écritures suivantes :
1. $11001001$ avec $k=3$
2. $00000001$ avec $k=4$
3. $101010101$ avec $k=3$
]
#imp[Les 3 exercices suivants sont à traiter dans l'ordre, ils vont vous apprendre à générer un nombre pseudo-aléatoire avec des opérations binaires].
#exo_nd(title: "Left et Right shift")[
On se donne les opérateurs de Left Shift (`<<`) et Right Shift (`>>`) qui permettent de "décaler" un nombre binaire. Par exemple, `5<<2 = 20` car `5 = 101` et décaler de 2 revient à ajouter 2 zéros, ie `10100` donc `4+16 = 20`.
Le Right Shift s'utilise de la même manière et sert à réduire le nombre binaire en "oubliant" son bit de poids faible.
1. Expliquez pourquoi `5>>1 = 2`
($star$)2. Soit $n in NN$, proposez un algorithme qui prend en entrée un entier $x in NN$ et renvoie $x mod 2^n$ en utilisant les bit-shifts.
]
#exo_nd(title: "Xor")[
On définie sur des nombres binaires l'operation de XOR comme étant (bit par bit) 0 si les deux bits sont identiques et 1 sinon.
Par exemple, `11011 ^ 01101 = 10110`.
1. Calculez le résultat de `1010 ^ 0110`.
2. Ecrivez une fonction qui prend entrée deux nombres entiers positifs `a` et `b`, et renvoie #imp[la distance de Hamming de ces deux nombres], à savoir le nombre de bits différents entre `a` et `b`. On pensera évidemment à utiliser le XOR...
($star star$)3. Ecrivez un algorithme qui #imp[échange le contenu de deux variables `a` et `b` (des entiers) sans utiliser de variable intermédiaire].
($star$)4. Ecrivez un algorithme qui prend entrée un entier $n in NN$ et renvoie la partié de ce nombre *en utilisant le XOR*.
]
#exo_nd(title: "Le XORShift", etoile: 2)[
C'est un exercice qui peut être vu comme une application de fin de partie avec les deux précédents exercices. Il ne faut pas avoir traité intégralement les exercies précédents mais seulement avoir compris les concepts.
1. Remémorez-vous tout ce que vous savez sur les générateurs pseudo-aléatoires.
En python, on peut utiliser `>>` et `<<` pour les shifts, ainsi que `^` pour le XOR.
On propose l'algorithme suivant:
#cb(title: "XORShift 32 bits")[
```python
def xorshift(seed):
x = seed
x = x ^ (x << 13)
x = x ^ (x >> 17)
x = x ^ (x << 5)
return x
```
]
2. Codez-le en python et appellez-le un grand nombre de fois en l'appellant à chaque fois avec le résultat de l'appel précédent.
3. En analysant le titre du code proposé, trouvez la période de ce générateur (après combien d'appels sommes-nous certains de retomber sur une valeur déjà générée) ? Est-elle atteinte pour toute graine ?
4. On admet qu'en remplaçant `13,17,5` par `13,7,17` on arrive à avoir un générateur sur 64 bits. Que devient la période trouvée précédemment ? Est-elle atteinte pour toute graine ?
]
#exo_nd(title: "Une introduction aux circuits booléens")[
Une porte XOR est un opérateur qui prend en entrée deux bits et renvoie 1 si ils sont différents, 0 sinon. Une porte NOT inverse son entrée (1 donne 0, 0 donne 1)
1. Expliquez comment obtenir une porte OR avec ces deux portes (OR vaut 1 si au moins une des deux entrées est vraie)
2. Expliquez comment obtenir une porte AND avec des deux portes.
3. On suppose avoir une porte qui décompose un nombre sur $n$ bits en ses $n$ bits (on a une entrée par bit), expliquez comment faire un XOR entre des nombres encodés sur $n$ bits grace à cette porte.
]
= Raisonner inductivement $star$
C'est l'un des chapitre les plus importants de tout ce document. Lisez-le plusieurs fois et essayez de comprendre un maximum de notions.
== Introduction
En Informatique, vous aurez souvent besoin de décrire des #imp[structures de données], que ce soit des listes, des arbres, des UnionFind, etc. La plupart de ces structures sont #imp[construites inductivement]. C'est-à-dire qu'on a des cas de base, (la liste vide pour les listes par exemple) et des cas qui vont faire le lien entre eux. Par exemple on peut définir une liste de la sorte :
- Soit la liste est vide
- Soit la liste est un élément suivie d'une liste `e::l`
Ainsi, on peut dire que `[1;2;3]` est `1::(2::(3::(Vide)))`. Le gros avantage de cette définition va être sur les preuves.
#exo_nd(title: "Identifier la structure")[
Reprenez la définition d'une liste ci-dessus, identifiez le cas de base et le constructeur.
]
#rem[CORRECTION DE L'EXERCICE : Le constructeur est `::` qui sert à concaténer, ie ajouter un élément à une liste. Le cas de base est la liste vide. On comprend donc qu'on ajoute des éléments un à un à une liste vide, ce qui est intuitif.]
#exo_nd(title: "Les arbres", etoile: 2)[
La définition d'un arbre binaire est disponible en #imp[IV-2] (#ita[si vous voulez la lire, ne lisez rien d'autre que la définition, sautez le théorème #imp[4-1] et sa démonstration pour le moment])
1. Identifiez le ou les cas de base d'un arbre binaire. Identifiez le ou les connecteurs d'un arbre binaire.
($star star$)2. Essayez de donner un type équivalent pour des arbres d'arité `n` (l'arité d'un arbre est le nombre maximal de fils d'un noeud). Identifiez les connecteurs et les cas de base.
]
#th(title: "Raisonnement inductif")[
Si une propriété est vraie pour les cas de base et qu'elle est préservée par l'application d'un constructeur, alors elle est vraie pour tout élément du type considéré.
]
#dem[
#rem[La démonstration est fondamentale pour le raisonnement inductif]
Soit une propriété $P$ vraie pour les cas de base et pour les autres constructeurs d'un type $tau$. On va #imp[montrer par récurrence finie sur la taille de la construction de tout élément de type $tau$ que la propriété est vraie dessus].
On pose $H_(n in NN^*)$ : "$P$ est vraie pour tous les éléments de type $tau$ qui sont construits en moins de $n$ constructeurs".
- $H_1$ est vraie car $P$ est vraie pour les cas de base.
- Supposons $H_n$ et montrons $H_(n+1)$ : On note $(c_1,...,c_(n+1))$ la suite finie de constructeurs menant à $t in tau$. Par hypothèse de récurrence, l'objet $t'$ construit en suivant les constructeurs $(c_1,...,c_n)$ est bien de type $tau$ et respecte la propriété $P$. Or, $c_(n+1)$ est un constructeur et la propriété est maintenue par passage à un constructeur par hypothèse, donc appliquer $c_(n+1)$ à $t'$ donne un objet qui vérifie bien $tau$. Cet objet est par définition $t$, donc $t$ vérifie $P$.
D'où $H_n$ vraie pour tout $n in NN^*$ par principe de récurrence.
]
Ainsi on peut voir que savoir que la propriété tient pour les cas de base et que composer par un constructeur la préserve permet d'affirer qu'elle sera vraie pour tout objet du type considéré.
#exo_nd(title: "Encore et encore")[
Refaîtes la démonstration du théorème #imp[4-1] pour voir si vous l'avez bien comprise.
]
== Les arbres
Maintenant que vous avez une vague idée des raisonnements inductifs, voyons un cas concret (que vous reverrez en MP2I, mais le voir avant pour en comprendre les idées peut-être bénéfique je pense) : #imp[les arbres]
#def(title: "Arbre binaire")[
Un arbre binaire est #imp[définie inductivement] #ita[(j'avais dis que c'était important comme terme)] de la sorte :
- L'arbre vide est un arbre
- Un arbre à un seul noeud est un arbre, qu'on nomme une #imp[feuille]
- Un noeud avec 1 ou 2 fils qui sont eux-même des arbres binaires est un arbre.
]
Voici un exemple d'arbre pour vous faire une idée :
#figure(
image("images/arbre.png", width: 50%),
caption: [
Exemple d'arbre (source: Wikipédia)
],
)
#pl(title: "Le OCaml, ce sauveur" + $star star$)[
Plus haut, j'avais dis que le OCaml était très pratique pour les types définies par induction, voyons voir pourquoi. On définit la hauteur d'un arbre binaire de la sorte :
- L'arbre vide est de hauter $-1$ (#ita[Pour permettre d'avoir la même hauteur pour un arbre qu'on le représente comme ayant des feuilles sans fils ou des feuilles qui ont pour fils l'arbre vide])
- Un noeud $x$ qui a pour fils $a_1$ et $a_2$ a pour hauteur $1 + max(a_1,a_2)$.
À première vue, cette définition est compliquée à coder en C ou en Python, en revanche en OCaml, par le mot-clé `match`, on a le code magique suivant :
#cb(title: "hauteur")[
```ocaml
let rec hauteur a =
match a with
| Vide -> -1
| Feuille -> 0
| Noeud(a1,a2) -> 1 + max (hauteur a1) (hauteur a2);;
```
]
On voit alors la puissance du OCaml qui permet de raisonner inductivement directement dans son code.
#rem[Pourquoi cette partie est $star star$ ? Elle est très utile mais demande d'être capable d'avoir une intuition sur ce que fait un code sans connaître le langage, ce n'est pas une compétence simple et ce n'est pas un attendu de la CPGE puisque vous connaîtrez le OCaml, elle est donc juste ici pour les curieux ou ceux qui ont déjà des petites notions de OCaml. Pour ne pas effrayer les autres, j'ai donc mis $star star$.]
]
== Faire de l'inductif quand le langage n'est pas fait pour
Voyons une astuce très simple pour raisonner de manière inductive quand le langage de programmation utilisé n'a pas été pensé pour. Pour cela, on va partir du python et on va chercher à représenter un arbre.
L'idée est d'ajouter une variable qui va permettre de savoir dans quel "type" on se trouve. Ainsi, on prendra le type suivant :
#cb(title: "type arbre")[
```python
class Arbre:
def __init__(self):
self.type = 0 #0 = Vide, 1 = Feuille, 2 = Noeud
self.f1 = None
self.f2 = None
```
]
Ainsi, on peut facilement faire un "match" en Python, par exemple voici une fonction qui donne la hauteur en Python #ita[définition de la hauteur d'un arbre binaire disponible dans la section Aller Plus Loin ci-dessus]:
#cb(title: "Hauteur d'un arbre en Python")[
```python
def hauteur(a):
if a == None : return -1 # cas à gérer car on a mis les fils à None par défaut
else if a.type == 0 : return -1
else if a.type == 1 : return 0
else : return 1 + hauteur(a.f1) + hauteur(a.f2)
```
]
#rem[Certains exercices de cette section peuvent-être délicats (vraiment), c'est normal si vous bloquez dessus : vous les reverrez probablement en cours et le fait de les avoir cherché vous donnera un énorme avantage au niveau de l'intuition sur ce genre d'exercices. Le but n'est encore une fois pas de chercher, mais de comprendre.]
#exo_nd(title: "Noeuds d'un arbre en fonction de sa hauteur", etoile: 2)[
($star star$)1. Trouvez un encadrement du nombre de noeud d'un arbre selon sa hauteur.
2. Montrez cet encadrement par un raisonnement inductif.
]
#rem[Cet exercice étant fondamentale, en voici la correction.]
#dem[
1. Obtenons une minoration et une majoration séparémment :
- Si on a une hauteur $h$, on a $h$ "couches" de noeuds. Le cas où il y a le moins de noeuds est celui où les couches sont le moins remplies. Pour cela, on considère le cas où il n'y a qu'un seul noeud par couche (ce genre d'arbre s'appelle arbre #imp[en peigne]). On a alors $n = h+1$ (essayez de bien comprendre le +1 via un dessin).
- De même, le pire cas est celui où chaque noeud a 2 fils, dans ce cas, chaque couche de hauteur $k$ a $2^h$ noeuds. On obtient donc $sum_(k=0)^(h) 2^k = 2^(h+1) -1$. Cette somme est une somme géométrique, qui est au programmde terminale et vous en aurez souvent besoin.
2. #imp[Question capitale pour vérifier si le raisonnement inductif est compris].
- Si l'arbre est vide, on a sa hauteur qui vaut -1 et son nombre de noeud qui vaut 0, donc $0 <= 0 <= 0$.
- Si l'arbre est une feuille, il a 1 noeud et est de hauteur 0. Donc $1 <= 1 <= 1$.
On a les cas de base qui sont vrais. Soit un arbre $A = (g,d)$ (on note $g$ le fils gauche et $d$ le fils droit) tel que $g$ et $d$ vérifient l'encadrement proposé.
Alors, $h_A = 1 + max(h_g,h_d)$ et $n_A = 1 + n_g + n_d$. Donc, en sommant les inégalités :
$
h_1 + 1 + h_2 + 1 + 1 <= 1 + n_1 + n_2 <= 2^(h_1 + 1) + 2^(h_2 + 1) -1 <= 2 times 2^h - 1
$
Or, $(h_1 +1 ) + (h_2 + 1) >= h$ car $h = h_1 + 1$ ou $h = h_2 +1$ et l'autre valeur est $>=0$. Donc : $h +1<= h_1 + h_2 + 1 <= 1 + n_g + n_d <= 2^(h+1) -1$
]
#exo_nd(title: "Parchemin, le retour")[
On considère le type parchemin définie dans l'exercice Palindrome du chapitre 2.
Montrez que n'importe quel mot peut être encodé par ce type.
]
#exo_nd(title: "Array to List")[
1. Ecrire une fonction qui prend en entrée un tableau et renvoie la liste correspondante.
2. Ecrire une fonction qui prend en entrée une liste et renvoie le tableau correspondant.
]
#exo_nd(title: "Parcours d'un arbre")[
On définie le parcours #imp[préfixe] d'un arbre de la sorte :
- Quand on arrive à un noeud qui a pour enfant $(g,d)$, on fait une action sur le noeud (on le parcourt, ça peut être l'afficher par exemple), puis on rappelle le parcours sur $g$ et après sur $d$.
1. Dessinez un arbre de hauteur 2, donnez-en le parcours préfixe. #ita[De manière générale, c'est important en prépa de toujours prendre des exemples simples et appliquer les algorithmes qu'on nous donne, même si ce n'est pas demandé.]
2. Montrez que tous les noeuds de l'arbre sont ainsi parcourues.
3. Est-ce que parcourir le noeud avant ses fils, entre ses fils, ou après ess fils change quelque chose à la propriété de la question 2?
]
#exo_nd(title: "Arbre binaire de recherche ", etoile: 3)[
On définie un arbre binaire étiquetté comme un arbre binaire où les noeuds ont une valeur (un entier par exemple).
Un arbre binaire est dit de recherche si il a la propriété suivante :
Pour tous noeuds $n = (x,g,d)$ #ita[(valeur $x$, fils gauche $g$ et fils droit $d$)], on a que si $y$ est une valeur dans $g$, alors $y<=x$ et si $y$ est une valeur dans $d$, alors $y>x$.
1. Est-ce grave si on modifie $y>x$ par $y<=x$ ?
2. Où se trouve le maximum d'un arbre binaire de recherche ? Le minimum ?
3. Est-ce que, étant donné un arbre binaire quelconque, on peut permutter ses valeurs de manière à avoir un arbre binaire de recherche ?
4. Pourquoi, selon vous, appelle-t-on ces arbres "de recherche" ?
5. Proposez un algorithme de recherche dans ce type d'arbre.
($star star star$)6. Donnez la complexité de votre algorithme de la question 5
7. Est-ce qu'inverser $y<=x$ et $y>x$ est gênant ?
8. Quelle forme voudrions-nous que l'arbre est pour que la recherche soit efficace ?
]
#exo_nd(title: "Tri par tas")[
On appelle #imp[tas max] un arbre binaire tel que tout élément est inférieur à son père #ita[(on peut définir de même les tas min)] et qui est complet sauf éventuellement sur la dernière ligne, et cette dernière ligne est remplie de gauche à droite. Un arbre binaire est dit complet si chaque hauteur possède $2^h$ noeuds.
La définition d'un tas permet de le voir comme un tableau, en effet, on met le premier élément à la racine, les éléments 2 et 3 sont ses fils, les élément 4 et 5 les fils du deuxième, les éléments 6 et 7 les fils du 3, ainsi de suite (on parle de #imp[parcours en largeur] d'un arbre).
1. Donnez une relation qui donne pour un noeud $i$ l'indice de ses fils dans le tableau et l'indice de son père.
2.a) Dans un tax max, où se trouve le maximum ? Dans un tas min, où se trouve le minimum ?
($star star$) 2.b) Comment élimineriez-vous la racine d'un tas ? #rem[(INDICATION) il faudrait l'inverser avec un certain élément puis faire quelque chose sur cet élément désormais à la racine]
($star$)3. Supposons qu'on ait une fonction `heapify` qui fait un tas à partir d'une liste d'entiers, proposez un algorithme, à l'aide de la question 2, qui permet de trier la liste.
($star star star$)4. Codez la fonction `heapify`.
]
#exo_nd(title: "Artihmétique", etoile: 3)[
On définie le type `Calcul` de cette façon :
```
Calcul est un de ces éléments:
- Entier(n)
- Addition(Calcul c1, Calcul c2)
- Produit(Calcul c2, Calcul c2)
- Moins(Calcul)
```
1. A-t-on besoin de parenthèses ?
2. Codez de cette manière $1+(2*3)*4 - 7$
3. Si vous deviez représenter ce calcul sous forme d'arbre, comment étiqueriez-vous les noeuds ? Les feuilles ?
4. Montrez que tout calcul admet un arbre de calcul.
($star star star$)5. Montrez l'#imp[unicité] ce cet arbre de calcul, à permutation des arguments d'une opération près #ita[(ie $1+2 = 2+1$)]
]
#exo_nd(title: "Combinatoire des arbres", etoile: 4)[
#ita[Tombé plusieurs fois à l'écrit de l'ENS, en début de sujet]
Combien existe-t'-il d'arbres binaires à $n$ noeuds ?
]
#exo_nd(title: "Interpréteur", etoile: 4)[
Ecrire un programme qui prend en entrée une chaîne de caractères représentant un calcul valide (par exemple `"(1+2)*3 - (4 / 5)"`) et l'évaluant.
#rem[On pensera à d'abord faire l'exercice disponible dans la section Récursivité qui vous fait coder la fonction `atoi` (qui prend en entrée une chaîne de caractères contenant uniquement des entiers et renvoie le nombre associé)]
]
#exo_nd(title: "Fusion croissante", etoile: 3)[
1. Ecrire un algortihme qui prend en entrée 2 listes triées par ordre croissant et qui renvoie une liste triée correspondant à la concaténation de ces deux listes.
2. En donner la complexité (si elle n'est pas linéaire, vous pouvez essayer d'améliorer votre algorithme)
3. Ecrire un algorithme qui prend en entrée $k$ listes triées par ordre croissant et qui renvoie une liste triée correspondant à la concaténation de ces $k$ listes.
($star star star$)4. Quelle en est la complexité ? (on peut trouver en $O(n log(k))$ avec $n$ le nombre total d'éléments si on utilise une file de priorité)
]
= Raisonnement dynamique
== Introduction
C'est au programme de N.S.I. mais ce n'est visiblement pas ce que retiennent le mieux les élèves, il est donc important de refaire un point dessus, ce n'est pas compliqué mais il faut avoir compris l'objectif derrière. Commençons par poser la définition d'un raisonnement dynamique :
#def(title: "Raisonnement dynamique")[
On #imp[raisonne dynamiquement] quand on utilise des sous-solutions optimales pour générer des solutions optimales à des problèmes.
]
Bon, bon, bon... Cette définition est peut-être un peu floue, non ? Pas de panique, je vais maintenant donner l'intuition.
Le principe d'un raisonnement dynamique est le suivant :
- On a un gros problème à résoudre, un problème compliqué.
- On trouve une manière de le #imp[découper] en différents intervalles tel que, si on souhaite résoudre le problème sur un intervalle plus gros, on ait juste à l'avoir résolue sur des intervalles plus petits.
- On calcule récursivement les valeurs dont on a besoin, puis on s'en sert pour résoudre le gros problème.
Et c'est tout !
== Le sac à dos
Voyons un exemple d'application à travers le problème dynamique le plus célèbre : #imp[le sac à dos].
On a un sac à dos qui permet de porter un poids maximal $P_(m a x)$. On a devant nous $n$ objets, de valeurs $v_1,...,v_n$ et de poids $p_1,...,p_n$. On cherche à prendre des objets tel qu'on ne dépasse pas le poids $P_(m a x)$ et on cherche en même temps à maximiser la somme des valeurs des objets pris.
#exo_nd(title: "Premier découpage", etoile: 2)[
Essayez de trouver vous-même comment découper ce problème.
]
On va dynamiser ce problème en le découpant en intervalle de sous-problèmes. On pose $S_(i,p)$ le problème du sac-à-dos où on ne considère que les $i$ premiers objets et un poids maximal $p$.
#imp[Quand on dynamise un problème, on doit s'assurer d'avoir des cases triviales], c'est l'équivalent de l'initialisation d'une récurrence ou d'un raisonnement inductif. Ici, si on a un poids maximal de 0 (sous réserve que chaque objet ait un poids non nul, ce qu'on supposera ici), on a un cas trivial et la valeur maximale est 0. De même, si on considère un seul objet, on peut très facilement résoudre la ligne correspondante ($0$ si $p <= p_1$ et $v_1$ sinon).
Un fois que le découpage a été effectué et que nous avons trouvé les cases triviales, il faut réfléchir à une #imp[relation permettant de remplir les autres cases]. Il faut s'assurer que ce soit un ordre remplissable, ie qu'on ne tombe pas sur un raisonnement qui se mord la queue (pour avoir $(i,p)$ on a besoin de $(i',p')$ qui a lui-même besoin de $(i,p)$). Ici, on peut en trouver un.
#exo_nd(title: "Relation")[
Essayez de trouver par vous-même une relation permettant de remplir le tableau (et par conséquent un ordre de remplissage).
]
Voyons quelle relation nous pouvons trouver :
On a deux possibilités pour chaque objet : soit on le prend, soit on ne le prend pas. Si on le prend, on se trouve dans un poids $p_(n e w)$ tel que $0 <= p_(n e w) = p_(a c t) - p_i < p_i$. Si on ne le prend pas, on est simplement dans le même cas qu'à l'objet précédent. Ainsi :
$p_(i,p) = m a x(v_i + p_(i-1,p-p_i), p_(i-1,p))$ si $p -p_i >= 0$ et $p_(i,p) = p_(i-1,p)$ sinon.
On a une relation de récurrence, qui permet effectivement un remplissage puique pour remplir une case $(i,p)$ on n'a besoin que de cases strictement avant.
Ainsi, ce problème est résolue dynamiquement !
#rem[Si ça vous semble trop compliqué, pas de panique, vous trouverez dans la section exercice des exercices beaucoup plus abordables sur la programmation dynamique.]
== Plus long facteur commun
Voici un deuxième exemple, beaucoup plus compliqué, réservez-le en deuxième lecture !
Etant donné deux mots $a$ et $b$, on appelle #imp[plus long facteur commun] de $a$ et $b$ le plus long mot $w$ tel que $w$ apparaisse dans $a$ et apparaisse dans $b$ (pas forcément à la suite, mais avec des indices strictement croissants) . Par exemple, si on prend `ABRICOTS` et `ABRIBUS`,le plus grand facteur sera `ABRIS` #imp[avec un S]. Voyons comment résoudre ce problème grâce à un raisonnement dynamique :
On note $n$ la taille de $a$ et $p$ la taille de $b$. On va découper notre problème selon le préfixe de $u$ et $v$ que l'on regarde (un préfixe est un mot de la forme $u_1 ... u_i$). On a alors un tableau de cette forme :
TODO
Maintenant, il apparaît quelque chose de classique en programmation dynamique : #imp[les cas de base].
Ici, si on regarde le moment où on a un mot vide (noté $epsilon$), on est sûr que le plus grand facteur commun sera de taille 0 (puisque $epsilon$ n'a pour facteur que $epsilon$). Ainsi, la première ligne et la première colonne peuvent déjà être remplies de 0 :
TODO
Désormais, réfléchissons à une formule pour, connaissant certains cas, donner $(i,j)$. Le but est de trouver #imp[un ordre de remplissage]. Pour cela on va chercher à donner une formule de récurrence, ie à écrire $p f c (u,v)_(i,j)$ #ita[(le plus long facteur commun entre $u$ et $v$ en considérant les $i$ premières lettres de $u$ et les $j$ premières de $v$)] en fonction de certains $p f c (u,v)_(i',j')$.
#exo_nd(title: "Formule de récurrence", etoile: 2)[
Pouvez-vous essayer de trouver la formule avant de lire la suite ?
]
L'idée est la suivante : Quand on veut le plus grand facteur entre $u$ et $v$ avec les $i$ et $j$ premières lettres de $u$ et $v$, il y a deux cas :
- Si $u_i = v_j$, on peut tenter de trouver un facteur qui tient compte de cette égalité : $1 + p f c(u,v)_(i-1,j-1)$
- Sinon, on renvoie simplement $max (p f c(u,v)_(i,j-1), p f c(u,v)_(i-1,j))$
Enfin, on fait attention dans le premier cas à tout de même proposer l'autre solution (on peut possiblement proposer des cas pathologiques où c'est plus optimale de ne pas compter une lettre commune). Ainsi, on peut remplir le tableau ligne par ligne, ou colonne par colonne, et on aura bien que quand on calcule $(i,j)$, on aura déjà calculé toutes les valeurs dont on a besoin (grace aux cas de base).
== Exercices
#exo_nd(title: "Montrer un escalier peut-être mathématiques...")[
Vous avez devant vous un escalier de $n$ marches. (On peut supposer $n <= 10 000$ car de toute façon, vous n'aurez pas le courage de monter plus de 10 000 marches).
À chaque marches, vous pouvez soit en monter 2 d'un coup, soit une seule. Combien de manières différentes avez-vous de monter l'esaclier ?
Par exmeple, pour $n=2$ on attend une réponse de 2 : 1 marchep puis 1 marche ou 2 marches.
Quelle est la complexité de votre algorithme ?
]
#exo_nd(title: "Escalier à coûts", etoile: 2)[
On se place dans le même contexte que l'exercice précédent, sauf que chaque marche a un coût. Par exemple, au lieu d'avoir $n=4$, on peut prendre `[2,1,10,1]` et dans ce cas, on préfèrera faire `[2,1,1]` (1 marche puis 2 marches) plutôt que de commencer par prendre les deux marches.
Ecrier un programme qui prend en entrée un tableau correspondant aux prix des marches et qui renvoie le coût minimal.
]
#exo_nd(title: "Triangle de Pascal")[
Si vous ne savez pas ce qu'est un triangle de Pascal, je vous invite à regarder sur Google ou dans ovter cours de Maths de terminale.
Ecrire un algorithme qui prend en entrée un entier $n$ et renvoie un tableau qui correpond aux $n$ premières étages du triangle de Pascal. Par exemple, pour $n=3$, on renverra `[[1],[1,1],[1,2,1]]`.
]
#exo_nd(title: "Théorie des jeux par la programmation dynamique", etoile: 3)[
On considère deux joueurs qui s'affrontent dans le jeu suivant :
Il y a en face d'eux un tableau de `n` éléments. À chaque tour, le joueur $i$ peut choisir de prendre le premier ou le dernier élément du tableau et ajouter le score de cet élément à son score. Le jeu se termine quand il n'y a plus de nombre dans le tableau.
Le joueur 1 (qui commence à jouer) gagne si son score est supérieur ou égal à celui du joueur 2. Sinon, il perd.
Ecrire une fonction `peut_gagner(tab)` qui prend en entrée un tableau de jeu et renvoie `True` si le joueur 1 a un moyen de gagner et `False` sinon.
]
#pl(title: "Intuition sur la théorie des jeux")[
Ici, on demande à ce que le joueur 1 ait "au moins un" moyen de gagner. En fait, c'est parce que #imp[indépendamment] ce que fait son adversaire, il pourra toujours jouer #imp[au moins un coup] qui lui permet d'être sûr de gagner. Ainsi, quand vous ferez de la théorie des jeux en deuxième année, la condition de victoire pour un joueur est la suivant :
Pour tous choix du joueur 2, il existe une série de coups du joueur 1 qui lui permet de gagner.
On ne demande en particulier pas à ce que tous les coups du joueur 1 lui permettent de gagner.
]
#exo_nd(title: "((()))((()))", etoile: 3)[
Ecrire une fonction qui prend un entier $n$ et renvoie le nombre de manières que l'on a de disposer $n$ parenthèses (donc $2n$ si on compte ouvrantes et fermantes) en respectant un parenthésage correct (quand on ferme une parenthèse, il y en avait au moins une qui était ouverte)
]
#exo_nd(title: "Distance d'édition (de Levenshtein)", etoile: 4)[
On appelle distance d'édition entre deux mots la distance minimale d'une série d'opérations qui permettent de passer de $u$ à $v$. Les opérations sont les suivantes (applicables uniquement à $u$, $v$ reste fixe) :
- Ajouter une lettre dans $u$ pour un coût de 1
- Supprimer un lettre de $u$ pour un coût de 1
- Remplacer une lettre de $u$ par une autre pour un coût de 1.
Par exemple la distance d'édition de `MP2I` à `MPI` est 1 en supprimant `2` dans `MP2I`. Cependant, on aurait aussi pu s'amuser à remplacer le `I` par un `2` et supprimer le `2` initialement présent, on aurait eu une distance de 2 : on fera attention à bien renvoyer la distance minimale.
Etant donné deux mots $u$ et $v$, donnez la distance d'édition entre $u$ et $v$ à l'aide d'un algorithme dynamique.
]
#exo_nd(title: "Piège à eau", etoile: 4)[
On vous donne un $n in NN$ représentant des niveaux d'élévations du sol. Par exemple, si on prend le tableau `[2;1;2]`, on a un mur de taille 2, un mur de taille 1 puis un mur de taille 2 (dans l'ordre, posé horizontalement, ils sont tous de largeur 1)
Etant donné un entier $n$ et un tableau correspondant, combien de case d'eau peut-on emprisonner ? (Imaginez qu'il pleut, combien de cases peuvent contenir de l'eau en ayant un mur à gauche et à droite)
]
= Retour sur trace $star$
#rem[Cette section est en cours d'écriture / relecture, elle n'est pas terminée.]
== Forcebrute
Jusqu'à présent on considérait des problèmes dans lesquels on pouvait trouver la réponse avec quelques parcours sans pouvoir se tromper, par exemple pour calculer la hauteur d'un arbre il faut parcourir l'arbre mais on est sûrs qu'un parcours va suffire. Si désormais je vous donne un PC avec un mot-de-passe et que je vous demande de le dévérouiller, vous ne pouvez pas en un parcours (en un mot de passe) être sûr de trouver le bon (ou alors vous êtes un oracle), il parait donc compliquer de donner un algorithme "intelligent" pour le faire. C'est justement le but de la force brute:
#def(title: "Bruteforce")[
Un algorithme bruteforce est un algorithme qui, étant donné un problème et un ensemble possible de solutions, essaye toutes les solutions jusqu'à en trouver une ou toutes dans le domaine voulu.
]
Par exemple si vous savez que le mot-de-passe est de taille 12, vous allez générer tous les mots de passe possibles de 12 caractères jusqu'à trouver le bon.
#exo_nd(title: "Bruteforce",etoile:1)[
1. Ecrire un algorithme python qui prend en entrée un mot de taille 8 et qui essaye tous les mots de taille 8 jusqu'à trouver celui passé en entrée
2. Ecrire un algorithme python qui prend en entrée un mot de taille $<= 8$ et qui essaye tous les mots nécessaires jusqu'à trouver celui passé en entrée (on n'utilisera pas `len` sur l'entrée).
]
== Retour sur trace
Pour certains problèmes, tester #imp[toutes] les solutions est une perte de temps, par exemple si on prend une grille de sudoku déjà remplie et qu'il nous reste les cases $c_1,...,c_k$ à remplir, l'algorithme bruteforce va tester toutes les valeurs de $[|1;9|]$ dans chaque $c_i$ (ça fait beaucoup de possibilités). Pourtant si on a déjà remplies $c_1,...,c_(p < k)$ et que la solution actuelle a deux lignes (ou colonnes, ou carrés) qui ont la même valeur, toutes les solutions $c_1,...,c_p,...,c_k$ seront fausses. On a donc envie de #imp[s'arrêter dès qu'on a fait une erreur].
#def(title: "Retour sur trace")[
On considére la solution vide (qui est valide si l'entrée l'est, si elle ne l'est pas le problème n'a pas de solution). Ensuite, pour chaque position on essaye toutes les valeurs possibles et dès qu'on arrive à une solution partielle fausse (fausse selon une fonction qu'on se donne en entrée qui vérifie qu'une solution partielle reste une solution partielle si on modifie $c$ pour la valeur $v$) on #imp[passe à la valeur suivante pour la case actuelle si possible, et sinon on renvoie faux].
]
Faisons un exemple concret: On va écrire un algorithme qui créé des couples de personnes selon des contraintes (soit $A$ et $B$ veulent absolument être ensemble, soit ils s'en moquent, soit ils ne veulent pas du tout être ensemble).
Entrée: ```(Alice veut être avec Bob), (Bob veut être avec Alice), (Charlie ne veut pas être avec Bob), (Charlie se moque de Eve), (Eve se moque de Charlie)```
Algorithme à la main:
```
- Alice
- Coupleé avec Alice
- Impossible car on ne peut pas lier une personne à elle-même
- Couplée avec Bob
- Respecte les contraintes, on continue
- Bob est déjà couplé avec Alice donc on génère pour la personne suivante
- Charlie est couplé avec Alice
- Impossible car Alice est déjà couplé
- Charlie est couplé avec Bob
- Impossible car Bob est déjà couplé
- Charlie est couplé avec Charlie
- Impossible car on ne peut pas lié une personne à elle-même
- Charlie est couplé avec Eve
- Ok
- Eve est déjà couplé donc c'est bon
```
Dans cet exemple on a réussi, montrons un exemple qui se passe moins bien, avec 2 personnes:
Entrée: ```(Alice veut être avec Bob),(Bob ne veut pas être Alice)```
Algorithme à la main:
```
- Alice couplée avec Alice
- Impossible car on ne peut pas lier une personne à elle-même
- Alice couplée avec Bob
- Impossible car Bob ne veut pas d'Alice
- Il n'y a plus de possibilités, Alice ne peut pas être couplé
- On n'a plus personne à modifier: c'est perdu.
```
Donnons un dernier exemple, qui cette fois-ci réussie mais après un essai infrucuteux. Vous #imp[noterez bien l'effacement des choix à chaque erreur]
Entrée: ```(A moque B), (B moque A), (C veut A), (D se moque de tout le monde)```
Algorithme à la main:
```
- A couplée avec A
- Impossible
- A couplée avec B
- B déjà couplé
- C couplé avec A
- Impossible car A déjà couplé
- C couplé avec B
- Impossible car B déjà couplé
- C couplé avec C
- Impossible
- C couplé avec D
- Impossible car C veut A
- Plus de solution possible, renvoie faux
- A n'est plus couplé à B. A couplé à C
- B couplé avec A
- Impossible car A déjà couplé
- B couplé avec B
- Impossible
- B couplé avec C
- Impossible car C déjà couplé
- B couplé avec D
- C déjà couplé
- D déjà couplé
- Solution trouvée
```
Il faut faire attention à quelques points:
- Il faut bien faire reculer la solution partielle de 1 quand on a une erreur. Dans notre exemple des couples, si A est couplée à B et qu'on veut coupler A à C, il faut penser à découpler B de à A.
- Quand on renvoie faux ce n'est pas la fin, sauf si c'est le premier choix qui renvoie faux. De manière générale, `faux` = retour en arrière de 1.
- La fonction de test de solutions partielles est souvent le point le plus compliqué.
== Exercices de fin de partie
Les exercices sont durs et cette notion sera intégralement revue en MP2I donc je vous mets qu'un seul exercice, à traiter seulement si le cours vous en dit.
#exo_nd(title: "Sudoku", etoile: 3)[
1. Reprendre l'exercice "Sudoku, première rencontre"
2. On va vouloir résoudre le sudoku par retour sur trace avec pour fonction de vérification la fonction qui vous dit si la grille viole une règle du sudoku. L'idée est de se donner un ordre arbitraire sur les cases et de combler les trous 1 à 1 avec toutes les valeurs possibles (de 0 à 9). Coder cet algorithme en python.
]
= Introduction aux graphes
Les graphes font partie des points-clés du programme de MP2I et MPI, vous reprendrez de 0 en cours, mais il peut-être avantageux d'avoir déjà quelques notions en tête pour gagner du temps.
== Qu'est-ce qu'un graphe
#def(title: "Graphe non-orienté")[
Un graphe non-orienté est la donné d'un ensemble $S$ de sommets et d'un ensemble $A subset P(S times S)$ d'arêtes.
]
C'est-à-dire qu'un graphe, c'est des sommets ($1$, $2$,... par exemple) et des relations entre les sommets qu'on appelle arête. On peut passer d'un sommet $i$ à un sommet $j$ sur un graphe si $\{i,j\} in A$ ($P(S times S)$ désigne les parties de $S times S$ ie un ensemble de couples de sommets).
#pl(title: "Notation ensembliste")[
Les plus attentifs auront remarqués qu'on note une arête $\{i,j\}$ et non $(i,j)$. C'est car on est sur un graphe non-orienté, ie on peut aller de $i$ à $j$ par une arête si et seulement si on peut aller de $j$ à $i$ en une arête. Un ensemble n'a pas de notion d'ordre, par exemple $\{1,2\} = \{2,1\}$. Par contre, quand on parle de graphe orienté, on utilise bien la notation $(i,j)$.
]
Pour avoir les idées fixes, donnons un premier exemple de graphe. Modélisons le groupe d'ami d'Alice par un graphe tel que deux personnes soient reliées si elles se suivent mutuellement sur instagram.
#figure(
image("graph/premier_ex.jpg", width: 50%),
caption: [
Exemple de graphe
],
)
On peut alors lire que `Eve` est amie avec `Wole` et `Adam` mais qu'elle n'est pas directement amie avec `Alice`.
== Notion de chemin
#def(title: "Chemin dans un graphe non-orienté")[
On appelle chemin une suite finie de sommets $(s_1,...,s_n)$ telle que $forall i in [|1;n-1|], \{s_i, s_(i+1)\} in A$. La taille d'un chemin est son nombre d'arêtes, donc $n-1$ selon cette définition.
]
Par exemple, si on considère le graphe de la figure 1, on a le chemin `Jack,Wole,Eve,Adam`, mais `Eve,Alice,Adam` n'est pas un chemin car il n'y a pas d'arête de `Eve` à `Alice`.
Il existe différents types de chemins pouvant nous intéresser.
#def(title: "Chemin élémentaire")[
Un chemin est dit #imp[élémentaire] si il ne passe pas deux fois par le même sommet.
]
On a alors notre première démonstration importante sur les graphes :
#th(title: "Lemme de König")[
Si il existe, dans un graphe $G = (S,A)$ un chemin de $a$ à $b$, alors il exist un chemin élémentaire de $a$ à $b$.
]
#dem[
L'idée est simple : si on passe par un sommet $x$ deux fois, on peut retirer une boucle au chemin :
Si on a un chemin de $a$ à $b$ qui passe deux fois par $x$, on a un chemin de la forme $(s_1,...,s_i,x,s_(i+2),...,s_j,x,s_(j+2)...,b)$. Par définition d'un chemin, il y a une arête de $x$ à $j+2$, on peut donc couper pour avoir un chemin de cette forme : $(s_1,...,s_i,x,s_(j+2),...,b)$. On peut ainsi couper toutes les boucles et on obtient bien un chemin simple.
]
#exo_nd(title: "Chemin simple")[
Un chemin est dit #imp[simple] si il ne passe pas deux fois par une même arête. Peut-on établir un résultat similaire au Lemme de König pour les chemins simples ?
]
== Composante connexe
#def(title: "Composante connexe")[
On dit qu'un ensemble $C$ de sommets forme une composante connexe si $forall (i,j) in C^2,$ il existe un chemin de $i$ à $j$. (il en existe donc un de $j$ à $i$ en suivant le même chemin "à l'envers")
]
Par exemple, dans le graphe des amis d'Alice, il n'y a qu'une seule composante connexe qui est simplement tous ses amis.
Voici un deuxième exemple :
#exo_nd(title: "Composante connexe")[
#figure(
image("graph/cc.jpg", width: 50%),
caption: [
Composante connexe
],
)
Identifiez les composantes connexes du graphe de la figure 2.
]
== Cycle
#def(title: "Cycle")[
Un cycle est un #imp[chemin simple] $(s_1,...,s_n)$ tel que $s_1 = s_n$.
]
#exo_nd(title: "Est un cycle ?")[
Est-ce que, dans un graphe non-orienté, pour tout arête $\{i,j\} in A$, $(i,j,i)$ est un cycle ?
]
#exo_nd(title: "Est un cycle ?")[
#figure(
image("graph/ex_cycle.jpg", width: 30%),
caption: [
Graphe de l'exercice
],
)
Quel est le plus grand cycle de ce graphe ?
]
== Représenter un graphe
Il y a deux manières "usuelles" de représenter un graphe :
- Par matrice d'adjacence
- Par liste d'adjacence
Dans le premier cas, on représente les arêtes par un tableau 2-dimension tel que `tab[i][j]` soit à `True` si et seulement si l'arête reliant `i` à `j` est dans le graphe (et donc à `False` sinon). Dans le second, on a une liste par sommets et la liste du sommet `i` contient `j` si et seulemen,t si l'arête reliant `i` à `j` existe.
#exo_nd(title: "Représentation d'un graphe")[
1. Représentez le graphe de la figure 3 sous forme de matrice d'adjacence
($star$)2. Que peut-on dire de la matrice ainsi obtenue (quelle propriété a-t-elle) ? Est-ce que sur cet exemple ou est-ce propre aux graphes non-orientés ?
3. Représentez le graphe des amis d'Alice sous forme de liste d'adjacence.
]
== Parcours d'un graphe
On va maintenant passer à un algorithme qui est à la base de 80% des exercices de graphe : le parcours en profondeur.
L'idée est de parcourir les sommets en regardant le voisinage à chaque fois. On part d'un sommet `i`, qu'on marque comme étant "visité" puis pour chacun de ses voisins, si il n'est pas déjà visité, on appelle le parcours dessus.
#exo_nd(title: "Pourquoi s'embêter ?")[
Pourquoi ajoute-t-on cette idée de marquer les sommets visités ?
]
Voici un code du parcours en profondeur :
#cb(title: "Parcours en profondeur")[
```python
visite = [False for i in range(g.taille)]
def auxiliaire(g,i):
if visite[i]: return #déjà visité
visite[i] = True
for v in g.adjacence[i]:
auxiliaire(g,v)
def parcours_prof(g):
for i in range(g.taille):
auxiliaire(g,i)
```
]
#exo_nd(title: "Autour du parcours en profondeur")[
1. Executez le parcours en profondeur sur le graphe des amis d'Alice.
2. Executez le parcours en profondeur sur le graphe de la figure 2.
($star$)3. Quel lien peut-on faire en parcours en profondeur et composante connexe ?
($star star star$)4. Prouvez-le.
]
#exo_nd(title: "Réflexion sur la représentation")[
1. Quelle représentation est utilisé dans le code proposé ?
2. Réécrivez le parcours en profondeur avec une autre représentation.
($star star$)3. Quels sont les avantages et les désavantages de chacune des représentations en terme d'espace et de temps ?
]
== Graphes orientés
Il existe aussi des graphes qui sont #imp[orientés], c'est-à-dire qu'on ne prend plus les notations ensemblistes pour les arêtes. Voici la définition :
#def(title: "Graphe orienté")[
Un graphe orienté est la donné d'un ensemble $S$ de sommets et d'un ensemble de couple, de sommets que l'on note $A$.
]
#rem[Ainsi, un graphe orienté peut avoir une arête d'un sommet à lui-même, ce n'est pas interdit.]
Voici un exemple de graphe orienté, on met une arête de $i$ à $j$ si $i$ suit $j$ sur instagram. Puisqu'il se peut que $i$ suive $j$ sans que $j$ suive $i$, un graphe orienté est plus adapté :
#figure(
image("graph/ex_graph_oriente.png", width: 30%),
caption: [
Graphe orienté
],
)
#rem[On remarque qu'on a une arête dans les deux sens entre Adam et Bob.]
Puisque vous repartirez de zéro sur les graphes orientés en prépa, je vous propose de voir la suite du cours comme un exercice (ce qui est d'ailleurs le cas, tout est sous forme d'exercice).
#exo_nd(title: "Circuit")[
Dans un graphe orienté, on ne parle plus de cycle mais de circuit, la définition reste sinon presque la même. "Presque" à un détail près, qui est la question de cet exercice :
Est-ce que dans un graphe orienté, un circuit à 2 sommets est effectivement un circuit ? (on a vu que pour un cycle il en fallait au moins 3)
(Faîtes un dessin)
]
#exo_nd(title: "Parcours en profondeur")[
Ecrire un parcours en profondeur pour les graphes orientés.
]
#exo_nd(title: "Détection de cycle", etoile: 3)[
1. Proposez, à partir du parcours en profondeur, un algorithme détectant les cycles dans un graphe non-orienté. #ita[On fera attention à respecter la règle interdisant les cycles de 2 sommets]
2. Proposez, à partir du parcours en profondeur, un algorithme détectant les cycles dans un graphe orienté. #ita[On fera attention à bien avoir traité l'exercice #imp[6-9] avant.]
]
#exo_nd(title: "Composante fortement connexe", etoile: 2)[
Dans un graphe non-orienté, la définition de composante connexe était "simple" car avoir un chemin de $i$ à $j$ implique d'en avoir un de $j$ à $i$, ici c'est différent.
1. Pourquoi est-ce différent ? Proposez un exemple.
On définie alors une composante #imp[fortement connexe] comme un ensemble de sommets #imp[maximal au sens de l'inclusion] (ie on a oublié personne) tel que pour tout couple de sommets dedans, on est un chemin reliant le premier au deuxième et un reliant le deuxième au premier.
($star$) 2. Proposez un algorithme naïf pour donner les composantes fortement connexes.
($star$)3. Proposez un algorithme pour trouver les composantes fortement connexes sans limite de complexité
4. ($star star star star$) Pouvez-vous trouver en $O(n log(n))$ ?
#rem[Si vous bloquez sur la question 4, c'est tout à fait normal, le but est que vous cherchiez sans trouver, pour bien comprendre les raisonnements erronés que vous pourriez avoir sur les graphes. Pour les plus curieux, vous pouvez chercher #ita[l'Algorithme de Kosaraju] sur Google, mais il sera vu en début de deuxième année, donc pas trop de panique.]
]
#exo_nd(title: "Arbre de parcours en profondeur")[
Soit $G$ un graphe non-orienté, on dit que c'est un #imp[arbre s'il est acyclique et connexe.]
1. Représenter les graphes de quelques parcours en profondeurs (mettre une arête entre $i$ et $j$ si et seulement si $i$ découvre $j$). Quelle propriété à ce graphe ? On admet que c'est un résultat correct (ou alors vous pouvez essayer de le prouver)
On appelle #imp[racine] d'une composante connexe le sommet de la composante connexe visitée par un parcours en profondeur qui a pour père un sommet qui n'est pas dans la composante connexe (le père est le sommet qui l'a découvert).
2. Est-ce que la racine d'une composante connexe dépend du sommet duquel on commence le parcours ?
3. Prouvez l'unicité de la racine pour un sommet de départ fixé.
]
== Exercices
#exo_nd(title: "Autour de la connexité", source: "ENS ULM")[
On se donne dans cet exercice un graphe $G$ non-orienté. On définie $c(G)$ comme le coefficient correspondant au nombre minimum de sommets à retirer de $G$ pour obtenir un graphe non-connexe.
1. Que dire si $G$ n'est pas connexe ?
Dans la suite, on supposera $G$ connexe.
2. Que vaut $c(G)$ si $G$ est le graphe complet ? (tous les sommets sont reliés entre eux)
3. Que vaut $c(G)$ si $G$ est un anneau auquel on a ajouté une arête ? (composé d'un seul grand cycle en forme de cercle et d'une arête qui relie deux sommets sur le cercle)
4. Donner un graphe qui a $c(G) = 1$. Si vous avez pris de l'avance sur le programme (je n'invite pas à le faire, au contraire) : quelle grande famille de graphe vérifie cette propriété ?
]
#exo_nd(title: "Graphes biparties")[
Un graphe non-orienté est dit bipartie si il existe deux ensembles $A$ et $B$ de sommets tel que tout arêtes $e$ du graphe connecte un sommet de $A$ et un sommet de $B$, ie il n'y a jamais d'arêtes au sein d'une même composante.
1. Est-ce que tout graphe peut se mettre sous une forme bipartie ?
2. Dessinez un graphe bipartie à 5 noeuds. Pouvez-vous en proposer un à $n$ sommets pour $n in NN$ ? (#ita[ne cherchez pas trop loin])
($star star star$)3. Ecrire un algorithme qui prend en entrée un graphe et renvoie Vrai si il est bipartie et Faux sinon.
]
#exo_nd(title: "Au moins deux solitaires", source: "<NAME>", etoile: 2)[
Prouvez que tout graphe connexe acyclique à $n >= 2$ sommets a au moins 2 sommets de degré 1 (interdit de parler d'arbre ou de feuille)
]
= Travailler avec des mots
== Définitions
On se donne un alphabet, noté $Sigma$ usuellement. Par exemple, en binaire on a $Sigma = \{ 0;1\}$, sur notre ordinateur on a $Sigma = $ la table ascii, et pour mon chien on a $Sigma = \{W,O,U,F\}$. Si vous voulez une définition "formelle":
#def(title: "Alphabet")[
Un alphabet $Sigma$ est un ensemble #imp[fini] de symboles (appellés lettres)
]
On définie ensuite les mots sur un alphabet :
#def(title: "Mot")[
Un #imp[mot] sur l'alphabet $Sigma$ est une suite finie de lettres.
]
Par exemple, $(a,b,r,a,c,a,d,a,b,r,a)$ est un mot sur l'alphabet $Sigma$ des lettres de la langue française. Cependant, ce n'est pas une notation très pratique donc on notera ce mot `abracadabra`.
== Programmation
En Python, vous n'avez pas de distinction entre lettre et mot, vous pouvez par exemple écrire en Python :
```python
a = 'a'
b = "b"
mot = "mot"
mot2 = 'mot2'
```
Il n'y a pas de distinction entre `''` et `""`. Heureusement pour vous, #imp[en OCaml et en C il y a une distinction] !
Pour coder une lettre d'un alphabet $Sigma$, on utile `''`, et on appelle les objets de ce type des #imp[caractères].
Pour coder un ensemble de lettres, un #imp[mot] (qu'on appelle le type `string`), on utilise `""`.
== Recherche
Le problème le plus classique quand on parle de mots est sans doute le problème de recherche : est-ce qu'un texte `t` contient au moins une itération du mot `w` (qui peut aussi être un texte) ?
L'idée naïve est de tester à chaque indice (un indice est la position d'un "curseur" qui lit le texte, on commence en $0$) si le texte qui commence à l'indice est celui qui nous intéresse suivie d'autre chose.
Par exemple, si on cherche `GAIA` dans `TAGAGAIA` :
`TAGAGAIA`
`GAIA`
On a `T` $!=$ `G`, donc on décale d'un indice :
`TAGAGAIA`
` GAIA`
On a `G` $!=$ `A`. On continue et on finit par trouver le motif `GAIA` à la fin du texte.
C'est l'algorithme le plus naïf et il suffit pour des petits tetes.
#exo_nd(title: "Quelques applications")[
1. Codez cet algorithme en Python
2. Donnez sa complexité en fonction de paramètres importants.
3. Modifiez-le pour qu'il compte le nombre d'itérations du motif
4. Donnez le nombre d'itérations du motif `Harry` dans le tome 1 d'Harry Potter.
]
On va désormais chercher à faire mieux : on va utiliser l'algorithme de Boyer-Moore-Horsepool.
== Boyer-Moore-Horsepool
Cet algorithme sert à optimiser le décalage : on ne va plus décaler 1 à 1 à chaque fois, mais on va essayer de faire mieux.
La première idée non intuitive de cet algorithme est de #imp[lire de droite à gauche et non de gauche à droite]. Vous pourrez réfléchir à la raison de ce choix en exercice de la section.
On va #imp[pré-calculer] un tableau uni-dimensionnel où on stockera les différents décalages que l'on obtient. Pour cela, on se sert de la lecture de droite à gauche, si on veut chercher `ababb` dans `abbaababbab` :
```
abbaababbab
ababb
```
La première erreur est au premier test (`b` $!=$ `a`), on cherche alors le derneier `a` du mot et on vient le coller sur le `a` qui a fait l'erreur. En cherchant le dernier, on s'assure de ne rater aucune possibilité (toutes les autres auraient échoués, au moins une fois sur ce caractère). Ainsi on cherche de la sorte :
```
abbaababbab
ababb
```
Le décalage doit donc permettre de faire correspondre le caractère qui a fait échouer la tentative précédente et la dernière itération dans le motif à chercher de ce caractère. Pour obtenir ce décalage, on va stocker #imp[le plus grand indice $i$ tel que `motif[i] = c` pour tout caractère `c`].
#exo_nd(title: "Pré-calcul")[
Donnez un code qui prend en entrée un motif et renvoie la table à pré-calculer.
#rem[On pourra utilsier les 256 premiers éléments de la table ASCII pour le tableau et utiliser $-1$ comme valeur indiquant qu'il n'y a aucune itération.]
]
Maintenant, il faudrait savoir utiliser ce tableau pré-calculé. On se place dans une recherche quelconque. On est actuellement à l'indice $j$ dans le motif et on a commencé la recherche sur un indice $i$. On arrive à deux caractères différents, $x$ pour le motif et $y$ pour le texte. Par exemple, si on est dans la situation suivante :
```
GGATATTAGCCAGCA
ATGGG
^
```
On a $i = 4$, $j = 3$ (on est à la 5ème lettre du texte et on est à la 4ème du motif), $x=G$ et $y=T$. On a alors 3 cas à distinguer :
- Si $t a b l e[y] = -1$, on n'a pas de $y$ dans le motif, donc on ne peut pas réussir notre recherche, ainsi on décale après l'indice actuel, qui est $i+j$. Donc on se place en $i+j+1$.
- Si $t a b l e[y] < j$, la dernière occurence de $y$ dans le motif est avant la lettre considérée, on veut alors la faire correspondre, pour cela on relance une recherche en $i + j - t a b l e[y]$
- Si $t a b l e [y] > j$ on ne peut pas décaler (ça reviendrait à revenir en erreur), donc on fait simplement $+1$ pour être sur de ne rater aucune possibilité.
#exo_nd(title : "Justification")[
1. Que dire si $t a b l e [y] = j$ ?
2. Justifiez, par un dessin et un exemple, les 3 cas.
]
#exo_nd(title: "Avec les mains")[
Dans chacun des cas, recherchez à la main en précisant les cas considérés :
1. `Harry` dans `Hermione dit à Harry de rentrer dans la voiture`
2. `Python` dans `Java << Python`
3. `OCAML` dans `OOCCAAMMLOCAML`
4. `Bary` dans `Barycentre de Bary.`
]
#exo_nd(title: "Reconnaissance de motif Boyer-Moore-Horspool")[
Implémentez l'algorithme en Python.
]
= Débuguer un programme
Vous avez désormais vu la totalité des points de cours importants pour aborder sereinement votre MP2I et pouvoir commencer à écrire du code en TP/TD/DM, cependant #imp[vous aurez des erreurs], beaucoup d'erreurs. C'est #imp[normal] et je pense que c'est en les corrigeant que vous apprendrez le plus. Ce chapitre se décompose en deux parties, la deuxième étant pour les MP2I qui viennent de rentrer et qui découvrent l'enfer du Seg Fault. Les exercices de fin de partie sont traitables par les terminales tant qu'il n'y a pas de C ou de OCaml dedans.
== Les erreurs de logique
#imp[Le cas le plus simple] Avant d'attaquer le débuguage, il y a certains cas dans lesquels vous n'avez presque rien à faire: quand votre IDE (ou compilateur, ou interpréteur) le fait pour vous. Par exemple si on donne ```python a = "a" + 2``` à Python, on obtient `TypeError: unsupported operand type(s) for +: 'int' and 'str'
` et on peut facilement comprendre notre erreur. C'est le cas le plus gentil et on peut ainsi facilement modifier notre code, cependant ce genre d'erreur n'arrivera très vite plus et vous aurez à la place des #imp[erreurs de logique] (nom non-officiel) à savoir des erreurs dans le principe même de votre code, dans l'implémentation de votre algorithme, dans les arguments d'un appel de fonctions, etc.
=== Introduction à Coin Coin
#imp[Les autres] 90% du temps (statistique personnelle) les erreurs ne se jouent qu'à un +1, qu'à un -1, qu'à un $<=$ qui devait être un $>=$ ou qu'à un $i$ qui était en fait un $j$. Le reste du temps, il faut reprendre précisemment le #imp[cheminement de votre code] pour trouver l'endroit qui le fait buguer. Le meilleur moyen pour le trouver est d'expliquer votre code dans votre tête, de la manière la plus précise possible. C'est un peu comme la maïeutique de Socrate sauf qu'ici c'est vous-même qui vous interrogez. Vous pouvez évidemment expliquer votre code à un ami, mais il ne servira que de figuration et il perdra juste son temps, le mieux est d'investir dans cet outil révolutionnaire :
#figure(
image("images/canard.jpg", width: 50%),
caption: [
Le meilleur logiciel de débuguage
],
)
Dès que vous avez un problème, parlez-en à Coin Coin (Coin pour les intimes) et en lui expliquant votre problème #imp[très précisemment], il vous soufflera la solution. Cependant, pour que ça marche il faut parler correctement à Coin Coin. Voici donc les règles à suivre quand vous parlez à Coin Coin :
1. Ligne par ligne tu expliqueras.
Il n'est pas question de laisser passer une ligne "triviale" sous-prétexte qu'elle est évidente ou qu'elle ne sert à rien, Coin Coin a besoin de #imp[tous les détails] pour vous aider.
2. Les liens tu expliciteras
Coin Coin a une mémoire très limitée, ainsi vous devez toujours lui #imp[expliciter dans quel contexte la ligne est exécutée]. Par exemple la ligne ```python for i in range(100):``` n'aura pas le même contexte d'exécution selon qu'elle est la première boucle `for` ou quelle est imbriquée dans d'autres (on pourraît avoir une erreur avec les indices qui se recouvrent). Ne soyez #imp[jamais vague dans les liens], car sinon en lisant trop vite vous passerez à côté de l'erreur
1. Les bornes tu donneras
Coin Coin est également très mauvais en maths, ainsi vous devrez lui préciser chacun de vos bornes, que ce soit pour les boucles #imp[ou pour les fonctions récursives] (ainsi vous n'aurez plus d'erreurs de + ou - 1)
4. Le résultat attendu tu compareras
#imp[Coin Coin adore les histoires imagées], ainsi quand vous lui parlez d'une fonction, vous lui donnerez un exemple d'exécution pour des valeurs recouvrant toutes les possibilités, afin de tester tous les cas de votre code à la main
5. #imp[Rien] tu ne supposeras
Enfin, vous ne devrez supposer aucun résultat sur des fonctions de vos anciennes questions traitées : l'erreur peut venir de n'importe où. Il se peut que vous ayez oublié un cas dans vos anciennes questions.
Discuter avec Coin Coin de cette manière permet en général de trouver votre problème. Même si dans certains cas vous #imp[pouvez court-circuiter le processus].
=== Court-ciruiter au bon endroit
Quand votre code est long, ou que vous n'avez envie de tester qu'une partie précise, vous pouvez #imp[déterminer où est votre problème] sans raconter toute l'histoire à Coin Coin. Pour trouver ce qui fait planter votre programme vous pouvez utiliser des #imp[print] pour trouver la bonne ligne à étudier (ou la bonne fonction). L'idée est la suivante : Quand votre programme plante, il aura exécuté toutes les lignes avant celle qui a mis fin à l'exécution (du moins en Python) et donc le dernier print affiché sera le dernier avant le bug. Vous pouvez #imp[procéder par bloc] pour le trouver. Par exemple si on considère ce code :
```python
def f1():
exec_1()
exec_2()
exec_3()
def f2():
exec_4()
exec_5()
exec_6()
i = input("Entrez un choix")
if i=="0": f1()
else: f2()
```
Il va falloir mettre un `print` après le `i =`, ce qui permet d'être sûr que la fonction `input` marche bien (ici c'est immédiat mais si c'est votre propre fonction, il vaut mieux tester), si il s'affiche on en met un entre chaque exécution de `f1` et un entre chaque exécution de `f2` et on voit lesquelles font buguer directement dans le terminal en mettant une première fois 0 comme en entrée et une deuxième fois autre chose. Il ne vous reste plus qu'à faire pareil dans les exécutions qui font buguer, ou à parler à Coin Coin selon le contexte.
== Segmentation Fault
Votre pire ennemi en prépa, de loin. En OCaml les erreurs sont assez précises en général, vous avez toujours au moins la ligne qui cause problème. En C c'est assez rare d'avoir la ligne, et il y a pire : quand le compileur ne marche pas et vous dit juste #imp[Segmentation Fault]. Cette erreur apparaît quand vous accédez à une partie de la mémoire qui ne vous est pas alloué, ainsi elle est compliquée à corriger car elle peut avoir des centaines de raisons d'apparaître (malloc avec les mauvaises bornes, accès à une zone mémoire que vous avez free, ...). Vous pouvez alors, et c'est ce qui va vous faire apprendre le plus (car vous rentrerez plus en détails dans le fonctionnement de `malloc`, des pointeurs etc en général) parler à Coin Coin pour trouver votre erreur (attention aux prints, `C` ne les affichera pas forcément en fonction des optimisations du compilateur).
Cependant, vous n'aurez peut-être pas le temps de faire ce travail à chaque fois (encore plus si vous avez bien assimilé les différentes notions). Il y a un outil qui existe : #imp[gdb]. Une fois vos fichiers compilés, vous pouvez lancer `gdb votre_fichier.extension_des_exec` (l'extension dépendant de l'os) et vous obtiendrez un terminal dont les lignes commencent par `(gdb)`. Une fois dedans, l'instruction `run` permet d'avancer dans le programme jusqu'à l'erreur, vous aurez alors le #imp[nom de la fonction qui vous a fait planter] et mieux, vous aurez accès à la mémoire actuelle du programme pour pouvoir voir l'état dans lequel vous êtes. (je vous laisse regarder la documentation de `gdb` à ce sujet, elle l'expliquera mieux que moi, en particulier vous pourrez y voir comment placer des #imp[breakpoints])
== Exercies de fin de partie
#exo_nd(title: "Débuguage de boucles",etoile :1)[
```python
tab = [[0 for i in range(10)] for j in range(20)]
for i in range(10):
for j in range(20):
print(tab[i][j])
```
1. Débuguez le code avec la technique de Coin Coin (explicitez bien les liens)
]
#exo_nd(title: "Débuguage de Fibonacci", etoile: 1)[
```python
def fibo(n):
return fibo(n-1)+fibo(n-2)
```
1. Parlez à Coin Coin de votre exécution de `fibo(3)`, rendez-vous compte alors de l'erreur.
]
#exo_nd(title: "Tri par pile", etoile:2)[
```python
class Pile:
def __init__(self):
self.elements = []
def est_vide(self):
return len(self.elements) == 0
def empiler(self, element):
self.elements.append(element)
def depiler(self):
if not self.est_vide():
return self.elements.pop()
else:
raise IndexError("La pile est vide")
def sommet(self):
if not self.est_vide():
return self.elements[-1]
else:
raise IndexError("La pile est vide")
def taille(self):
return len(self.elements)
def tri_par_pile(liste):
pile = Pile()
for element in liste:
pile.empiler(element)
liste_triee = []
while not pile.est_vide():
element = pile.depiler()
if not liste_triee or element > liste_triee[-1]:
liste_triee.append(element)
else:
while liste_triee and element < liste_triee[-1]:
pile.empiler(liste_triee.pop())
liste_triee.append(element)
return liste_triee
```
1. Débuguer ce programme en parlant à Coin Coin sur des exemples d'exécution
]
#exo_nd(title: "Liste doublement chaînée",etoile: 2)[
```c
struct node{
int val;
struct node* left;
struct node* right;
};
typedef struct node node;
typedef node* liste;
liste creer_liste_vide(){ return NULL; }
liste insert(liste l, int x){
liste new = malloc(sizeof(node));
new->val = x;
new->left = l;
if(l == NULL){
return new;
}
l->right = new;
new->right = l->right;
return new;
}
void free_liste(liste l){
if(l->left != NULL){
return free_liste(l->left);
}
if(l==NULL){
return;
}
free_liste(l->left);
free_liste(l->right);
free(l);
l = NULL;
}
```
1. Débuguer cette structure (il y a peut-être une chose qui ne marche pas, ou deux, ou trois, ou dix)
]
#exo_nd(title: "Les pointeurs", etoile: 1)[
```c
int main()
{
int* ptr;
int* nptr = NULL;
printf("%d %d", *ptr, *nptr);
return 0;
}
int main() {
int arr[5];
for (int i = 0; i <= 5; ++i) {
arr[i] = i;
}
for (int i = 0; i <= 5; ++i) {
printf("%d ", arr[i]);
}
return 0;
}
int main() {
int *ptr;
int value = 42;
if (value == 42) {
printf("%d", *ptr); // Utilisation d'un pointeur non alloué conditionnellement
}
return 0;
}
```
1. Corrigez les SegFault.
]
Des exercices plus compliqué sont à venir.
= Exercices sans thèmes précis
#exo_nd(title: "Borne inférieure des tris à comparaison", etoile: 4)[
Montrez qu'un tri à comparaison a besoin de au moins $n log(n)$ opérations.
]
#exo_nd(title: "Inspiré du Duc de Densmore", etoile: 4)[
Au cours d'une journée, un nombre $N$ de personnes se sont rendues à la mairie. Chaque personne, exceptée une, y est allée exactement une fois.
Personne ne se souvient quand il y est allé, mais tout le monde se souvient de qui il a croisé.
Comment déterminer la personne qui est allée 2 fois à la mairie ?
#rem[À traiter une fois le chapitre sur les graphes lus.
Indice 1 : Raisonner sur un exemple
Indice 2 : Essayer de représenter sur une frise le moment où les personnes sont à la Mairie.
]
]
#exo_nd(title: "Le meilleur pâtissier", etoile: 3)[
Un concours national a lieu pour déterminer le meilleur pâtissier. Chaque personne a une note dans $[|0;100|]$.
Problème, le concours a eu lieu dans $M$ lieux différents, chaque lieu possède une liste de candidat-note non triée.
Par exemple si il y a le candidat 1 qui a 80 points et le candidat 2 qui en a 0 (il ne faut pas le juger), on aura la liste `"(1-80)::(2-0)"` (il faut donc formatter les chaînes de caractères)
Chaque lieu a accueilli $N$ candidats.
1. Comment obtenir la liste globale des candidats classés par ordre décroissant des notes (le meilleur est donc le premier) ?
($star star star$)2. Comment obtenir la liste globale des notes classées par ordre décroissant ? On attend une complexité $O(M times N)$.
]
#exo_nd(title: "Selection aléatoire", etoile: 4)[
Etant donné un fil de données que vous ne pouvez parcourir qu'une seule fois, comment obtenir un élément de de manière uniforme ?
#rem[Indice : $1/2 times ... times (N-1)/N = 1/N$]
]
#exo_nd(title: "k-ème minimum", etoile: 4)[
Etant donné une liste ou un tableau de $N$ valeurs, comment déterminer le $k$-ème minimum ?
On pourra fournir une solution en $O(k N)$ pour débuter, mais il existe (et on invite à chercher) une solution en $O(N times l o g (N))$.
]
#exo_nd(title: "exo oxe eox oex ..." + $star star$)[
Etant donné un mot (une chaîne de caractères), afficher toutes les permutations de ce mot (attention, pour le mot `bob`, `bob` doit être affiché deux fois).
#rem[(Indication) Commencer par générer les permutations de $[|1;n|]$]
]
= Corrections
== Chapitre 1
#corr(num:"1-1")[Garder en mémoire le maximum qui vaut intialement le premier élément. A chaque élément du tableau, le comparer au maximum en mémoire.]
#corr(num:"1-2")[
1. Toujours garder en mémoire l'élément précédent (au début le premier élément) et pour chaque élément, vérifier qu'il est $>=$ à celui en mémoire, puis le mettre en mémoire.
2. Faire de même avec $<=$ et $=$ et vérifier l'un des 3]
#corr(num:"1-3")[Lui ajouter un paramètre qu'on décroît de 1 à chaque fois, si il est nul alors on renvoie faux. Si l'algorithme termine avant on renvoie vrai]
#corr(num:"1-6")[$O(|L|)$ ! Le 100000 est une constante]
#corr(num:"1-12")[1. $10^4$ 2. $(26*2)^14$ 3. On peut diviser par $26*2$]
#corr(num:"1-13")[
On fait un XOR. Ou si vous ne connaissez pas le XOR, on met 1 en mémoire, puis pour tout élément, si l'élément divise le nombre en mémoire on divise, sinon on multiplie par cet élément.
]
== Chapitre 2
#corr(num:"2-1")[
1. Elle calcule le produit des nombres pairs entre $2$ et $n$
2. ```python
def fact_pair(n):
if n==0: return 1
if n%2==1: return fact_pair(n-1)
return n * fact(n-2)
```
3. On peut faire `fact(n)/mystere2(n)`
4. $O(n)$
]
#corr(num:"2-3")[
1. ```python
def fib(n):
if n<=1: return n
return fib(n-1)+fib(n-2)
```
2. Ce sont les cas $n <= 1$. On le voit car il n'y a plus d'appel récursif.
3. $n$ décroît strictement à chaque appel, ce qui garantit la terminaison.
]
#corr(num:"2-6")[
1. On créé un tableau de taillt `n` et pour chaque `fib(k)`, si la case $k$ a déjà été remplie on renvoit sa valeur, sinon on calcule `fib(k)` avec `fib(k-1)` et `fib(k-2)` et on ajoute la valeur dans le tableau. Comme ça on calcule une seule fois chaque valeur de fibonacci et on a une complexité linéaire.
2. L'idée est de faire `fib` qui renvoie le couple $(u_(n-1),u_n)$. Je vous laisse chercher avec cette indication.
]
#corr(num:"2-7")[
1. $O(n)$
2. ça ne termine pas, on ne parle pas de complexité.
3. $O(max(t a b))$
4. $O(1)$
5. $O(n)$
]
#corr(num:"2-12")[
```python
def rebours_aux2(n):
print(n)
if n!=1: rebours_aux2(n-1)
def rebours_aux1(k,n):
print(k)
if k==n:
rebours_aux2(n)
else:
rebours_aux1(k+1)
def infinite(n):
while True:
rebours_aux1(0,n)
```
]
#corr(num:"2-14")[Obtenir par appel récursif les permutations de $[|1;n-1|]$ puis ajouter $n$ à toutes les positions dans toutes les permutations.]
== Chapitre 3
#corr(num:"3-1")[
1. Les tableaux sont optimaux car accès $O(1)$ et on connaît déjà la taille au début.
2. De même car on peut borner la taille et que c'est pas trop grand, donc un tableau est suffisant.
3. Les deux sont possibles, si c'est un très gros site c'est un peu compliqué de borner donc préférer des listes (mais en pratique ce sera une base de donnée)
4. Je sais pas pourquoi j'ai mis cette question, surtout que les deux sont utiles.
5. On peut borner la taille et c'est acceptable donc tableau.
]
#corr(num:"3-3")[Accès $O(1)$]
#corr(num:"3-4")[
```
def maxi(a,b):
if a>=b:
return a
return b
def max(l):
if un_seul_element(l): return seul_element(l)
if vide(l): ERREUR
return maxi(element_act(l),max(suite(l)))
```
]
== Chapitre 4
== Chapitre 5
#corr(num:"5-1")[
Cas de base: Liste vide. Constructeur: $::$
]
#corr(num:"5-2")[
Cas de base: Arbre vide, Feuille. Constructeur: Noeud
]
#corr(num:"5-4")[
1. $h+1 <= n <= 2^(h+1) - 1 $. Pour cela considérer le pire cas et le meilleur cas (que 1 fils / que 2 fils)
2. ça sera fait en prépa.
]
#corr(num:"5-11")[
J'ai dérapé, ne pas traiter.
]
== Chapitre 6
#corr(num:"6-1")[
On fait deux cas: Celui dans lequel on prend l'objet et celui dans lequel on ne le prend pas. Et on fait un appel récursif dessus (toujours en considérant l'objet $k$, pour permettre de le prendre plusieurs fois. De toute façon vu qu'on a une limite de poids on ne va jamais tourner à l'infini tant que l'objet n'a pas de poids 0 et si il a un poids 0 il n'y a pas de solutions car la solution c'est $infinity$)
]
== Chapitre 7
== Chapitre 8
#corr(num:"8-1")[
Si un chemin de $u$ à $v$ passe deux fois par une même arête, on peut simplement retirer tous qu'il fait enter les deux passages dans l'arête et on aura toujours un chemin de $u$ à $v$
]
#corr(num:"8-2")[
`7,8` et `6,5,4,1,2,3`
]
#corr(num:"8-3")[
Non ! Un cycle est un chemin #imp[simple] et la l'arête $\{i,j\}$ est utilisée deux fois.
]
#corr(num:"8-4")[
$(5,4,1,2,3)$ (ou tout cycle équivalent)
]
#corr(num:"8-5")[Todo, elle est importante celle-là]
#corr(num:"8-9")[
Oui ! Car l'arête $(i,j)$ est cette-fois différente de celle $(j,i)$ (différence ensemble / couple, au programme de terminale et première)
]
== Chapitre 9
== Chapitre 10
#corr(num:"10-1")[
L'erreur à débuguer est le fait que ce soit `tab[j][i]`, je laisse Coin-Coin vous expliquer pourquoi.
]
#corr(num:"10-2")[
L'erreur à débuguer est l'oubli de cas de basen je laisse Coin-Coin vous expliquer pourquoi.
]
= Crédits
Auteur : <NAME> (https://www.cr-dev.io/)
Merci à Wyrdix, Grégoire, et aux terminales qui ont proposé des exercices supplémentaires pour le polycopié et des retouches sur le cours.
Merci aux terminales qui ont relu le polycopié et permis de mieux calibrer les exercices / le nombre d'étoiles.
Merci à tous ceux qui m'enverront des exercices à mettre dans les versions prochaines.
#imp[Licence] Avant la MP2I © 2023 by cr-dev.io is licensed under CC BY-NC 4.0
] |
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%20591%20-%20Mathematical%20Logic/Assignments/Assignment%202.typ | typst | #import "/Templates/generic.typ": latex, header
#import "@preview/ctheorems:1.1.0": *
#import "/Templates/math.typ": *
#import "/Templates/assignment.typ": *
#let head(doc) = header(doc, title: "Assignment 2")
#show: head
#show: latex
#show: NumberingAfter
#show: thmrules
#show: symbol_replacing
#set page(margin: (x: 1.6cm, top: 2.5cm, bottom: 2cm))
#show math.equation: it => {
if it.has("label"){
return math.equation(block: true, numbering: "(1)", it)
}
else {
it
}
}
#show ref: it => {
let el = it.element
if el != none and el.func() == math.equation {
link(el.location(),numbering(
"(1)",
counter(math.equation).at(el.location()).at(0)+1
))
} else {
it
}
}
#let lemma = lemma.with(numbering: none)
= Question
== Statement
Show that two countable structures are isomorphic if and only if the Duplicator/Prover has a winning strategy in $G_omega (mM,mN)$
== Solution
Assume $mM tilde.eq mN$, then the Prover wins trivially by just following the isomorphism.
On the other hand assume Prover has a winning strategy, then we can play the role of the Spoiler to force Prover to construct an isomorphism. First enumerate the models
$
|mM| = { m_0, m_1, ... }, quad
|mN| = { n_0, n_1, ... }
$
on the first turn we pick $m_0$ and let Prover map it to some element of $|mN|$. On the second turn we pick the smallest index element of $|mN|$ that has not been picked before and force Prover to map it. We continue this, on odd turns we pick the smallest index element of $|mM|$ that has not been picked before, and on even turns we pick the smallest index element of $|mN|$ that has not been picked before. This essentially forces Prover to use the back-and-forth method. Since every element of both models will eventually be mapped and since Prover has to win this game, the resulting map $union.big_i f_i$ will be an isomorphism between $mM$ and $mN$.
#pagebreak(weak: true)
= Question
== Statement
We say that a theory is axiomatized by a set $A$ of sentences if $T = Cn(A)$ where $Cn$ denotes the conclusions of a set of sentences. A universal sentence $phi$ is a sentence of the form $phi = forall overline(x) thin psi(overline(x))$ where $psi$ is atomic.
Let $T$ be an $L$-theory and $T_forall$ be the set of all universal sentences $sigma$ such that $T proves sigma$. Show that $mM sat T_forall$ if and only if there is an $mN sat T$ such that $mM seq mN$. Conclude that $T$ is axiomatizable by a set of universal sentences if and only if the set of models of $T$ is closed under taking substructures.
== Solution
// #remark[
// I am pretty sure the statement as written above could be false, for example if $T = { exists x : x != x }$, then $T_forall$ is satisfied by all models but no supermodel of it satisfies $T$. I thus modified the intermediate lemma so that I can still reach the correct conclusion.
// ]
#lemma[
$mM sat T_forall$ iff we have a model $mN$ with $mM seq mN$ and $mN sat T$.
]
#proof[
One direction is easy, assume that $mM seq mN$ with $mN sat T$, let $phi = forall overline(x) thin psi(overline(x))$ with $phi in T$ and $psi$ atomic. Then by unwrapping the definition of satisfaction we know that
$
mN sat phi => forall overline(a) in |mN| (mN sat psi(overline(a))) => forall overline(a) in |mM| (mM sat psi(overline(a))) => mM sat phi.
$
Now assume that $mM sat T_forall$, then first note that $T$ must be consistent since otherwise all the atomic contradictions in $T$ would also be in $T_forall$. Let $S$ denote the set of all atomic sentences in $L(mM)$ that are true in $mM$. We now show that $T union S$ is consistent by contradiction. Assume it is not, then by compactness it would have an inconsistent finite subcollection, denote that subcollection $T' union S'$, where $S'$ is non empty by consistency of $T$. Now for some $overline(c) in |mM|$ we have $phi_i = psi_i (overline(c))$ for all $phi_i in S'$. Then consider the sentence
$
Phi = exists overline(x) (and.big_(phi in S') psi (overline(x))),
$
if this sentence is true in some model $mM'$ of $T'$ then $mM' sat T' union S'$ since we can just interpret the constants in $S'$ to be the witnesses of the above sentence.
On the other hand if this sentence is false in all models of $T'$ then by completeness theorem $T' proves not Phi$, but notice that
$
not Phi = forall overline(x) (or.big_(phi in S') not psi(overline(x)))
$
and so $not Phi$ is a universal sentence and thus in $T_forall$ and so $mM sat not Phi$. But now $Phi(overline(c))$ must be true in $mM$ by construction of $S$ and so we have a contradiction.
By completeness, $T union S$ has a model $mN$, that model is then a superstructure of $mM$ since it satisfies all the atomic $L(mM)$-sentences of $mM$, this proves the lemma.
]
Now using this lemma, assume $T_forall$ axiomatizes $T$, then if $mN$ is a model of $T$ then for any substructure $mM$ we have by the above lemma $mM sat T_forall$ and thus $mM sat T$. On the other hand if the models of $T$ are closed under taking substructures then if $mM sat T_forall$ we have that there exists $mN$ with $mM seq mN$ and $mN sat T$ so then $mM sat T$ also. Since this is true for every model, by completeness, $T_forall proves T$.
#pagebreak(weak: true)
= Question
<question-3>
== Statement
An $forall exists$-sentence $phi$ is one of the form $phi = forall overline(x)thin exists overline(y) thin psi(overline(x),overline(y))$ where $psi$ is quantifier free.
Show that $T$ is axiomatizable by $forall exists$-sentences if and only if the class of models of $T$ is closed under taking unions of increasing chains (linearly ordered by inclusion) of models.
== Solution
#remark[
I unfortunately stumbled upon the solution of questions 2 and 3 in the textbook by <NAME> while trying to look up what a universal statement means. Both solutions are largely inspired by whats in that book.
]
We will try to emulate the solution for question 2, we set $T_(forall exists)$ to be the set of $forall exists$-sentences in $T$. Assume that $mM_i sat T$ for all $i in I$, set $mM = union.big_i mM_i$, then let $phi in T$ be of the form $phi = forall overline(x) thin exists overline(y) thin psi(overline(x),overline(y))$, we have
$
mM sat phi <=> forall overline(a) in |mM|, exists overline(b) in |mM|, mM sat psi(overline(a),overline(b))
$<eqn-union_satisfy>
now fix some $overline(a)$, since it is a finite tuple of elements, there exists some $i$ with $overline(a) in |mM_i|$. Since $phi$ holds in $mM_i$ there is some vector of elements $overline(b) in |mM_i|$ with $mM_i sat psi(overline(a), overline(b))$. Since $psi$ is atomic then $mM sat psi(overline(a), overline(b))$ as well and so by @eqn-union_satisfy we have $mM sat phi$.
For the other direction we have a lot more work to do. Assume that models of $T$ are closed under taking unions of chains and that $mM sat T_(forall exists)$.
#lemma[
For any model $mM' sat T_(forall exists)$ with $mM elm mM'$ we have a model $mN sat T union S$ with $mM' seq mN$ and where
$
S = { phi med exists forall med L"-sentence" | mM sat phi }
$
]
#proof[
To construct such a model we will use completeness, to do this set $Gamma = T union C union S$ where
$
C = { phi "atomic" L(mM')"-sentence" | mM' sat phi }.
$
Now assume that $Gamma$ is inconsistent, then by compactness let $T' union C' union S'$ be a finite subset that achieves a contradiction. As before we can show that $T$ is consistent, and $C union S$ is consistent since $mM' sat C union S$. Then construct the sentences
$
phi =
exists overline(x)
(and.big_(phi in C') phi (overline(x)))
quad
"and"
quad
phi' = and.big_(psi in S) psi
$
then if $T' union { phi, phi' }$ is consistent then by interpreting the $overline(x)$ given to us by $phi$ as the constants in $C'$ we get that $T' union C' union S'$ is consistent. On the other hand if $T union {phi, phi' }$ is inconsistent then $T' proves not (phi and phi')$, but one can easily check that $not (phi and phi')$ is an $forall exists$-sentence and thus is in $T_(forall exists)$. But then $mM sat not (phi and phi')$, which contradicts the construction of $C$ and $S$. It is then clear that a model $mN$ of $Gamma$ is a superstructure of $mM'$ with $mN sat T union S$
]
#lemma[
For a model $mN sat T union S$ with $mM seq mN$ we have that there exists a model $mM'$ with $mM elm mM'$ and $mN seq mM$.
]
#proof[
To construct such a superstructure we need to check that $S(mM) union C(mN)$ is consistent, where
$
S(mM) = { phi "an" thin L(mM)"-sentence" | mM sat phi}
"and"
C(mN) = { phi "atomic" L(mN)"-sentence" | mN sat phi }
$
Assume that this set is inconsistent, then by compactness let $S' union C'$ be an inconsistent finite subset, both $S$ and $C$ are consistent on their own so neither $S'$ nor $C'$ are empty. Hence define the sentence
$
phi = exists overline(x)
(and.big_(phi in C') phi (overline(x))),
$
by the exact same argument as above either $S(mM) union { phi }$ cannot be consistent and so $S(mM) proves not phi$. However, $not phi$ is an $exists forall$-sentence implying $not phi in S$, but then we know that $mN sat not phi$ which contradicts the construction of $phi$ from statements in $C(mN)$. This proves that $S(mM) union C(mN)$ is consistent and any model of $S(mM) union C(mN)$ is then a candidate for $mN$.
]
By iterating the use of the two lemmas above we can get a chain
$
mM =: mM_0 seq mN_0 seq mM_1 seq mN_1 seq ...
$
so consider
$
cal(M)' := union.big_i mM_i = union.big_i mN_i
$
Since it is a union of $mM_i$ which are all elementary superstructures of $mM$ they are all elementarily equivalent, thus $cal(M)' equiv mM$. But now each $mN_i$ is a model of $T$ and so since $T$ is closed under taking unions of chains we have that $cal(M)'$ is a model of $T$. But then $mM$ is also a model of $T$. We have thus proved that every model of $T_(forall exists)$ is also a model of $T$ and thus $T = Cn(T_(forall exists))$.
#pagebreak(weak: true)
= Question
<question-4>
== Statement
A model $mM$ of a theory $T$ is existentially closed if whenever $sigma$ is an existential $L(mM)$-sentence satisfied in a model $mN sat T$ containing $mM$, then $mM sat sigma$.
Show that if $T$ is axiomatizable by $forall exists$-sentences, then it has an existentially closed model.
== Solution
I'm gonna assume that $T$ is consistent as otherwise I think this is false.
Let $mM$ be a model of $T$, set $kappa = ||mM||+|L| + aleph_0$, define $frak(X)$ the collection of superstructures $mN sat T$ with $|mN| seq |mM| union.sq kappa$, note that this collection is a set.
#lemma[
Let $mN in frak(X)$ be a model which fails to be existentially closed for some sentence $sigma$, then $mN$ has a superstructure $mN' in frak(X)$ with $mN' sat sigma$.
]
#proof[
By definition $mN$ has some superstructure $mN^*$ with $mN^* sat T$ and $mN^* sat sigma$. By Lowenheim-Skolem downwards Theorem we have that there exists a model $mN'$ with $mN seq mN' lt.curly mN^*$ and
$
||mN'|| <= ||mN|| + |L(mN)| + aleph_0 = ||mN|| + |L| + ||mN|| = ||mN|| + |L| <= ||mM|| + |L|.
$
By $mN' lt.curly mN^*$ we have that $mN' sat T$ and $mN' sat sigma$, also by enumerating $|mN'| backslash |mN|$ we can map all those elements to elements of $kappa$ to get that $mN'$ is isomorphic to some model in $frak(X)$.
]
Now $frak(X)$ is partially ordered by inclusion, and for every chain $mM_i$ in $frak(X)$ we have that $|mM_i| seq |mM| union kappa$ and so $|union.big_i mM_i| seq |mM| union kappa$. But also since $T$ is axiomatizable by $forall exists$-sentences, then by @question-3 we have that $union.big_i mM_i sat T$ and so $union.big_i mM_i in frak(X)$ and thus is an upper bound for the chain. Now by Zorn's lemma we have that since chains contain upper bounds then there exists a maximal element of $frak(X)$. But by the lemma above a maximal element cannot fail to be existentially closed for any sentence $sigma$, so it must be existentially closed.
#pagebreak(weak: true)
= Question
== Statement
Suppose $T$ has only infinite models. Show that if $T$ is $kappa$-categorical for some $kappa >= |L|$ and axiomatizable by $forall exists$-sentences, then all models of $T$ are existentially closed. Conclude that every algebraically closed field is existentially closed.
== Solution
#lemma[
If there exists model $mM$ of cardinality $kappa$, then there exists a non-existentially closed model $mM$ of any cardinality $gamma >= |L|$.
]
#proof[
Assume that $mM$ fails to be existentially closed for some existential $L(mM)$-sentence $sigma$, then let $mN sat T$ be a supermodel with $mN sat sigma$.
If $gamma > kappa$, then essentially by the same argument as upward Lowenheim-Skolem theorem we have that there exists models $mM',mN'$ with $mM' seq mN'$, $mM elm mM'$, $mN elm mN'$ and $||mM'|| = gamma$. Now by definition of an elementary submodel we have that
$
mM sat sigma <=> mM' sat sigma
"and"
mN sat sigma <=> mN' sat sigma
$
and so $mM' satn sigma, mN' sat sigma$ so $mM'$ is not existentially closed.
On the other hand, if $|L| <= gamma < kappa$ then let $C = {c_1,...,c_n}$ be the set of $L(mM)$ elements that appear in sigma, by downward Lowenheim-Skolem theorem we have that there exists a model $mM'$ containing $C$ with $mM' elm mM seq mN$ and $||mM'|| = gamma$. Then again, by definition of elementary submodel we have that since $overline(c) in |mM'|$,
$
mM' sat sigma <=> mM sat sigma
$
and so $mM' satn sigma$ and so $mM'$ is not elementary closed.
]
Now using this lemma we can use @question-4 to find a model of size $kappa$ which is existentially closed. But now since it is $kappa$-categorical all models of size $kappa$ are existentially closed. But then by the lemma above this shows all models of it are existentially closed.
Next we recall that algebraically closed fields are defined over the language $(+,dot,0,1)$ and satisfy the following axioms
- $forall x (x + 0 = 0)$
- $forall x forall y forall z (x + (y + z)) = ((x + y) + z)$
- $forall x forall y (x + y = y + x)$
- $forall x exists y (x + y = e)$
- $forall x (x dot 0 = 0)$
- $forall x forall y forall z (x dot (y dot z) = (x dot y) dot z)$
- $forall x (x dot 1 = x)$
- $forall x (x dot y = y dot x)$
- $forall x forall y forall z (x dot (y + z) = (x dot y) + (x dot z))$
- $forall x exists y (x != 0 -> x dot y = 1)$
And then we add axioms of the form $1 + 1 = 0, 1 + 1 + 1 = 0,...$ to fix a characteristic $p$, as well as the axioms
$forall a_0 ... forall a_(n-1) exists x (x^n + sum_(i=0)^(n-1) a_i x^i = 0)$ for all $i$.
All of these axioms are $forall exists$-sentences, and we know that $|L| <= aleph_0$ and all the theories are $aleph_1$ categorical and so all algebraically closed fields are existentially closed.
#pagebreak(weak: true)
= Question
== Statement
Let $mM$ be a model. An _Ultrapower_ of $mM$ is a model of the form $product_i mM_i slash cal(U)$ where all $mM_i = mM$.
Let $mM^*$ be an ultrapower of $mM$. Show that the diagonal map $iota$ mapping $a$ to the equivalence class of the constant sequence with value $a$ is an elementary embedding of $mM$ into $mM^*$. Show that if $mM^*$ is obtained from a nonprincipal ultrafilter on $NN$, then $iota$ surjective if and only if $mM$ is finite.
== Solution
Let $a$ be a vector of elements in $mM$ and $tilde(a)$ is the image of that vector of elements under $iota$, then let $phi(overline(x))$ be a formula, we have that ${ i in I : mM_i sat phi(tilde(a)_i) }$
is either equal to $I$ or the empty set.
Then by Łoś's Theorem we have that
$
mM sat phi(a) <=> { i in I : mM_i sat phi(tilde(a)_i) } = I <=> { i in I : mM_i sat phi(tilde(a)_i) } in cal(U)
<=> mM^* sat phi(tilde(a)).
$
and so $mM sat phi(a) <=> mM^* sat phi(tilde(a))$ which is precisely the definition of an elementary embedding.
Before we prove the next statement we need a small lemma.
#lemma[
If $cal(U)$ is an ultrafilter and $A union.sq B in cal(U)$ then exactly one of the following is true
- $A in cal(U)$
- $B in cal(U)$
]
#proof[
We know that either $A in cal(U)$ or $I backslash A in cal(U)$, if $I backslash A in cal(U)$ then
$
(I backslash A) sect (A union B) = B in cal(U)
$
]
Now assume that $I = NN$, we want to show that if $mM$ is finite then $iota$ is surjective.
Assume that $mM$ is finite and enumerate its elements ${x_1,...,x_n} = |mM|$. Let $(a_i)_(i in NN)$ be a fixed element of $mM^*$, then consider the set
$
S_j = { i in NN : a_i = x_j }
$
that is, the set of indices where the element of the sequence with that index is equal to $x_j$.
Now we have that $NN = union.sq.big_(j) S_j$ and so since $NN in cal(U)$, by repeatedly applying the lemma exactly one of the $S_j$ are in $cal(U)$ (we are allowed to do this since the union is finite). Let $S_k$ be that distinguished subset, then
$
{ i in NN : a_i = iota(x_k)} = S_k in cal(U)
$
and so $a_i tilde_(cal(U)) iota(x_k)$ and so we found $a_i$ as the image of an element in $a_i$.
On the other hand assume that $mM$ is not finite, then let ${x_1,x_2,...}$ be an enumeration of some countably infinite subset of it. Consider the element $(x_i)_(i in NN) in mM^*$, we have that for any element $x in mM$ the set ${ i in NN : x_i = x}$
is either a singleton or the empty set. But any nonprincipal filter contains no finite subsets thus $iota(x) tilde.not_(cal(U)) x_i$ for all $x in mM$ and so the map $iota$ is not surjective.
#pagebreak(weak: true)
= Question
== Statement
Let $mM$ and $mN$ be elementarily equivalent models, show that $mM$ embeds into some ultrapower of $mN$.
== Solution
First we will need a lemma.
#lemma[
Fix some finite $Delta seq Th_(L(mM))(mM)$, let $C = {c_1,...,c_n}$ be the set of additional constants that appear in $Delta$ but are not in $L$. There is an interpretation $mN_Delta$ of $mN$ as a model of $L(C)$ with $mN_Delta sat Delta$.
]
#proof[
Let $Delta = {phi_1 (ov(c)),...,phi_k (ov(c))}$, then $mM$ satisfies the $L$-sentence
$
psi = exists ov(x) (and.big_(i=1)^k phi_i (ov(x)))
$
then by elementary equivalence $mN$ also satisfies $psi$, so by interpreting $ov(x) = (x_1,...,x_n)$ as the constants $c_1,...,c_n$ we get that $mN_Delta$ is a model of $L(C)$ with $mN_Delta sat Delta$.
]
Now set $I = { Delta seq Th_(L(mM))(mM) : Delta "is finite"}$, then define the basic sets $[Delta] = { Delta' in I : Delta seq Delta' }$ and then $D = { Y seq I : [Delta] seq Y "for some" Delta }$. $D$ is a filter since if $[Delta_1] seq Y_1, [Delta_2] seq Y_2$ then
$
[Delta_1 union Delta_2] = [Delta_1] sect [Delta_2] seq Y_1 sect Y_2
$
Now let $cal(U)$ be any ultrafilter containing $D$, we prove that $mN^* = product_(Delta in I) mN_Delta slash cal(U)$ is a model of $L(mM)$ that satisfies $Th_(L(mM))(mM)$.
First for any element $c in mM$ consider the sentence $phi = exists x (x = c)$, then ${phi} in I$. Now $[{phi}] in cal(U)$ and for any $Delta in [{phi}]$ we have
$
mM_Delta sat phi
$
so set $x_(Delta,c)$ to be a witness of $x$ in $phi$ in $mM_Delta$.
Then all sequences $(a_Delta)_(Delta in I)$ in $mN^*$ with $a_Delta = x_(Delta,c)$ for all $Delta in [{phi}]$ are equivalent and so we can define the interpretation
$
c^(mN^*) = (a_Delta)_(Delta in I)
$
Now for any $phi in Th_(L(mM))(mM)$ we can write $phi = psi(ov(c))$ then for any $Delta in [{phi, exists x (x = ov(c))}]$ we have
$
mN_Delta sat psi(x_(Delta,ov(c)))
$
so
$
{ Delta in I : mN_Delta sat phi(ov(c)_Delta) } supset.eq { Delta in I : mN_Delta sat phi(x_(Delta, ov(c))) } supset.eq [{phi, exists x (x = ov(c))}] in cal(U)
$
and thus $mN^* sat Th_(L(mM))(mM)$ and so $mM lt.curly mN^*$.
|
|
https://github.com/voxell-tech/velyst | https://raw.githubusercontent.com/voxell-tech/velyst/main/assets/typst/styles/monokai_pro.typ | typst | Apache License 2.0 | #let red = rgb("#FF6188")
#let orange = rgb("#FC9867")
#let yellow = rgb("#FFD866")
#let green = rgb("#A9DC76")
#let blue = rgb("#78DCE8")
#let purple = rgb("#AB9DF2")
#let base0 = rgb("#19181A")
#let base1 = rgb("#221F22")
#let base2 = rgb("#2D2A2E")
#let base3 = rgb("#403E41")
#let base4 = rgb("#5B595C")
#let base5 = rgb("#727072")
#let base6 = rgb("#939293")
#let base7 = rgb("#C1C0C0")
#let base8 = rgb("#FCFCFA")
|
https://github.com/Complex2-Liu/macmo | https://raw.githubusercontent.com/Complex2-Liu/macmo/main/contests/2023/content/problem-04.typ | typst | #import "../lib/math.typ": problem, solution, note, ans
#import "../lib/utils.typ": hphantom
#problem[
记 $phi(k)$ 为欧拉函数在正整数 $k$ 的取值. 求: $sum_(k = 1)^n phi(k) floor(n / k)
= underline(hphantom("ANSWER"))$.
]
#solution[
表达式是一个依赖于 $n$ 的函数, 记为 $S_n$. 显然 $S_1 = 1, S_2 = 3$,
下面我们递归的来求 $S_n$. 设 $S_n - S_(n - 1) = sum_(k = 1)^n phi(k) a_k$,
这里 $a_k = floor(n / k) - floor((n - 1) / k)$.
注意到 $0 <= a_k <= 1$, 并且 $a_k = 1$ 当且仅当 $k$ 是 $n$ 的因子, 所以
$S_n - S_(n - 1) = sum_(d divides n) phi(d) = n$, 于是
$S_n = 1 + 2 + dots.h.c + n = ans((n (n + 1)) / 2.)$
]
#note[
这里考了一个必须熟悉的公式 $sum_(d divides n) phi(d) = n$.
]
/* vim: set ft=typst: */
|
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/states/locate.md | markdown | MIT License | # Locate
<div class="warning">This section is outdated. It may be still useful, but it is strongly recommended to study new context system (using the reference).</div>
> Link to [reference](https://typst.app/docs/reference/meta/locate/)
Many things should be recompiled depending on some external things.
To understand, what those external things are, it should be a content that
_is put into a document_. It works roughly the same way as `state.update`.
Locate takes a function that, when that `locate` is put in the document
and given a _location in the document_, returns some content instead of that `locate`.
## Location
> Link to [reference](https://typst.app/docs/reference/meta/location/)
```typ
#locate(loc => [
My location: \
#loc.position()!
])
```
## `state.at(loc)`
Given a location, returns _value of state in that location_.
That allows kind of _time travel_, you can get location at _any place of document_.
`state.display` is roughly equivalent to
```typ
#let display(state) = locate(location => {
state.at(location)
})
#let x = state("x", 0)
#x.display() \
#x.update(n => n + 3)
#display(x)
```
## Final
Calculates the _final value_ of state.
The location there is needed to restrict what content will change within recompilations.
That greatly increases speed and better resolves "conflicts".
```typ
#let x = state("x", 5)
x = #x.display() \
#locate(loc => [
The final x value is #x.final(loc)
])
#x.update(-3)
x = #x.display()
#x.update(n => n + 1)
x = #x.display()
```
## Convergence
Sometimes layout _will not converge_. For example, imagine this:
```typ
#let x = state("x", 5)
x = #x.display() \
#locate(loc => [
// let's set x to final x + 1
// and see what will go on?
#x.update(x.final(loc) + 1)
#x.display()
])
```
**WARNING**: layout did not converge within 5 attempts
It is impossible to resolve that layout, so Typst gives up and gives you a warning.
That means you _should be careful_ with states!
This is a _dark, **dark magic**_ that requires large sacrifices!
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/string-00.typ | typst | Other | // Test the `len` method.
#test("Hello World!".len(), 12)
|
https://github.com/Joshuah143/himmens-resume | https://raw.githubusercontent.com/Joshuah143/himmens-resume/main/himmens_resume_en.typ | typst | // Imported from Overleaf version
#let ubcblue = rgb("#002145")
#show link: underline
#set text(fallback: false)
#set text(font: "Open Sans", size: 11pt)
#show text.where(weight: "bold"): set text(fill: ubcblue)
#show text.where(weight: "regular"): set text(fill: rgb("#333333"))
#set grid.cell(align: top + left)
#show heading: it => [
#text(fill: ubcblue)[#it.body] #box(width: 1fr, line(length: 100%, stroke: ubcblue + 0.5pt))
]
#let cv-mode = false
#let use_footer = true
#let job = (title: "",
company: "",
description: "",
date: "",
actions: [],
site: "",
visible: true) => {
if (visible or cv-mode) [
#text(weight: "bold")[#title] \
#company | #date
#if site != "" [
| #site
]\
#if description != "" [
#description \
]
#for action in actions [
- #action \
]
]
}
#let split_job = (title: "",
company: "",
description: "",
date: "",
actions: [],
site: "",
visible: true) => {
if (visible or cv-mode) {
grid(columns: (1fr, 3fr), column-gutter: 10pt, row-gutter: 0pt,
[ #text(weight: "bold")[#title] \
#company \
#date \
#if site != "" [
#link(site) \
] ],
[#if description != "" [
#description \
]
#for action in actions [
- #action \
]]
)
}
}
#let award = (title: "",
organization: "",
date: "",
description: [],
visible: true) => {
if (visible or cv-mode) [
#text(weight:"bold")[#title] | #date \
#description
]
}
#let skill = (title: "",
description: "",
visible: true) => {
if (visible or cv-mode) [
#text(weight:"bold")[#title] | #description \
]
}
#let achievement = (focus: "",
description: "",
visible: true) => {
if (visible or cv-mode) [
- #text(weight:"bold")[#focus] #description \
]
}
#set page(paper: "us-letter", footer: grid(columns: (50%, 50%), image("assets/cooplogo.png"), grid.cell(align: right+horizon)[#text(font: "Open Sans", weight: "bold")[<EMAIL> | 604-822-9677]]), header: locate(loc => {
if counter(page).at(loc).first() > 1 {
return {text(weight: "bold")[<NAME> - Resume]; box(width: 1fr, align(right)[*<EMAIL> | 587-434-0118*])}
}}))
// Begin actual resume
#align(center)[
#text(size: 17pt, font: "Open Sans", weight: "bold")[Joshua Himmens] \
#if cv-mode [
#text(size: 10pt, font: "Open Sans", weight: "bold")[Curriculum Vitae \ ]
]
#link("mailto:<EMAIL>")[<EMAIL>] | 587-434-0118 | #link("https://himmens.com")[himmens.com] \
#text(weight: "bold")[Undergraduate Engineering Physics Student] at The University of British Columbia\
#text(weight: "bold")[92% (A+)] Average | #text(weight: "bold")[English], #text(weight: "bold")[French] (Working Knowledge) | #link("https://github.com/Joshuah143")[Github/Joshuah143]
]
= Technical Skills
#skill(
title: "Machine Learning",
description: "TensorFlow, Keras, PointNet, Weights and Biases (wandb), ONNX",
visible: true
)
#skill(
title: "Embedded Programming",
description: "Experienced with FreeRTOS on TMS570, RP2040, and STM32",
visible: true,
)
#skill(
title: "Software Development",
description: "C, C++, Python, Java, MATLAB, Bash, Git",
visible: true,
)
#skill(
title: "Quantum Computing",
description: "Used Qiskit to simulate quantum algorithms.",
visible: false,
)
#skill(
title: "Particle Physics",
description: "Root, CERN grid compute, Athena",
visible: true,
)
= Technical/Research Experience
#job(
title: "ATLAS Deep Learning Research Student",
company: "TRIUMF",
description: "ATLAS detects particles from the Large Hadron Collider colliding at 99.999999% the speed of light to explore the bounds of physics.",
date: "05/2024 - Present (part time from 09/2024)",
site: "himmens.com/triumf",
actions: (
"Developed panoptic segmentation models for the ATLAS detector using the PointNet ML framework with Wandb, TensorFlow, Keras.",
"Used ONNX to implement models in C++ for deployment on the ATLAS Athena system.",
"Used CERN's grid computing to parallelize compute across thousands of nodes.",
"Worked independently to develop models using cutting edge transfer learning approaches."),
visible: true
)
#job(
title: "Command and Data Handling (CDH) Lead and Firmware Developer",
company: "UBC Orbit Satellite Team",
description: "ALEASAT is an earth observation cubesat supported by the European Space Agency and UBC.",
date: "10/2023 - Present",
site: "himmens.com/orbit",
actions: (
"Led the CDH team to develop software to meet mission and testing objectives from ESA (European Space Agency) for the ALEASAT project.",
"Managed a team of 10 firmware developers, with over 40 tasked, 1300 CI builds, 2000 lines of code completed/written.",
"Developed mission testing, function testing, and acceptance testing procedures to meet ESA and ECSS standards.",
"Programmed device drivers and electrical ground support equipment (EGSE).",
"Developed the ALEASAT Avionics Test Bench (FlatSat).",
),
visible: true
)
#job(
title: "Embedded Firmware Developer",
company: "UBC Orbit Satellite Team",
date: "2023 - Present",
actions: (
"Programmed device drivers, electrical ground support equipment (EGSE).",
"Developed the ALEASAT Avionics Test Bench (FlatSat).",
"Worked on the ALEASAT onboard computer for launch in Q1 2026."),
visible: false
)
#job(
title: "Open Source Contributor",
company: "NumPy",
date: "2021",
actions: (
"Contributed to the open-source numerical analysis tool with 86 million monthly downloads.",),
visible: false
)
#job(
title: "Elections Officer",
company: "Elections Alberta",
date: "2023",
actions: (
"Integrated as part of a team to run a safe and fair provincial election",
"Managed public interactions and vote counting."),
visible: false
)
#job(
title: "International Baccalaureate Student",
company: "Western Canada High School",
date: "2020 - 2023",
actions: (
"Took the IB diploma program with higher-level Math, Physics, and Chemistry",
"Completed an Extended Essay on simulations of the brachistochrone problem in physics."),
visible: false
)
#job(
title: "National Youth Spokesperson",
company: "Scouts Canada",
date: "2017 - 2022",
actions: (
"Hosted events",
"Authored articles",
"Managed social media",
"Engaged with media outlets."),
visible: false
)
#job(
title: "Committee Member",
company: "Scouts Canada Sustainable Development Goals Program",
date: "2019 - 2020",
actions: (
"Assisted in creating programs for Sustainable Development Goals education and outreach.",),
visible: false
)
= Publications and Presentations
Presented #text(weight: "bold")[Developing Machine Learning Techniques for Particle Flow in the ATLAS Experiment] at the Canadian Astroparticle Physics Summer Student Talks Competition (CASST 2024), where I #text(weight: "bold")[placed 2nd] of 44 presentations.
Presenter of #text(weight:
"bold")[JetPointnet: A Machine Learning Approach to Cell-to-Track Attribution in the ATLAS Experiment] to be presented at the Canadian Undergraduate Physics Conference in October 2024.
#pagebreak()
Presented #text(weight: "bold")[3D Particle Flow in the ATLAS Calorimeter: How to Train Your Model], a speed-talk, at the 2024 TRIUMF Science Week
Presented #text(weight: "bold")[ALEASAT ESA "Fly Your Satellite!" Training Week Presentation] at the European Space Agency's ESEC-GALAXIA (Transinne Belgium) in 2024 as part of the "Fly Your Satellite 4!" program.
= Awards
#award(
title: "<NAME> First Year Summer Research Experience (FYSRE) Award",
date: "2024",
description: ("Awarded to promising students in physics for a 4 month research placement."),
visible: true)
#award(
title: "Alberta Centennial Award and Alberta Premier's Citizenship Award",
date: "2023",
description: ("Awarded for outstanding community service. Value: $2000"),
visible: true)
#award(
title: "Calgary Flames Foundation Community Involvement Scholarship",
date: "2023",
description: ("Awarded for community involvement. Value: $2005"),
visible: true)
#award(
title: "<NAME> Leadership Award for exceptional community service",
date: "2023",
description: ("Awarded for exceptional community service. Value: $1000"),
visible: true)
#award(
title: "<NAME> Entrance Scholarship",
date: "2023",
description: ("Awarded for academic achievement. Value: $2000"),
visible: true)
#award(
title: "<NAME> award for embodying the spirit of Canadian debate",
date: "2023",
description: ("Required a vote of the student delegates at the Canadian National Debate Seminar."),
visible: false)
#award(
title: "10 Scouts Canada commendations",
date: "2017 - 2022",
description: ("Awarded for various achievements."),
visible: false)
= Advocacy and Leadership
#split_job(
title: "Curriculum and Advocacy Director",
company: "UBC Engineering Undergraduate Society",
date: "2024 - Present",
actions: (
"Worked with the faculty and the undergraduate society to develop multi-year plans for coop-related advocacy.",
"Advocated for transparency in coop fee use in line with standards at other institutions."),
visible: true
)
#split_job(
title: "<NAME>",
company: "Child Rights Connect",
date: "2021 - 2023",
actions: (
"Provided guidance to UN delegations on communication strategies for high-level rights goals.",
"Presented to governments and consulted on international initiatives to support the UN Convention on the Rights of the Child."),
visible: true
)
#split_job(
title: "Correspondent",
company: "Organization of American States",
date: "2019 - 2020",
actions: (
"Created and edited content on human and child rights in the Americas.",
"Attended the 3rd Pan American Child and Youth Forum in Cartagena, Colombia with the Government of Canada."),
visible: false
)
= Experiences
#achievement(
focus: "\"Quantum School for Young Students\"",
description: "participant at the University of Waterloo and Institute for Quantum Computing.",
visible: true
)
#achievement(
focus: "\"Introduction to Quantum Computing\"",
description: "participant, an 8-month course on quantum computing using IBM's quantum infrastructure.",
visible: true
)
#achievement(
focus: "\"GoPhysics!\"",
description: "participant, a physics enrichment program at the Perimeter Institute.",
visible: false
)
#achievement(
focus: "B2 French proficiency",
description: "(B1 DELF certified).",
visible: false
)
#achievement(
focus: "Public speaker",
description: "on children's rights and youth engagement, with audiences ranging from 100-1000 people.",
visible: false
)
#achievement(
focus: "Placed 4th nationally",
description: "in Canadian National style debate in 2023.",
visible: false
)
#achievement(
focus: "Scientific Computing with Python certification",
description: "(300 hours).",
visible: true
)
#achievement(
focus: "National Debate Semi-Finalist",
description: "Canadian National Style, 2023.",
visible: false
)
|
|
https://github.com/tingerrr/subpar | https://raw.githubusercontent.com/tingerrr/subpar/main/test/kind/test.typ | typst | MIT License | // Synopsis:
// - default kind is figure and is not inferred from content
// - the super supplement is propagated down by default
// - same kind correctly usese same counter
#import "/test/util.typ": *
#import "/src/lib.typ" as subpar
// figure by default regardless of inner content
#subpar.grid(
figure(```typst = Hello World```, caption: [Inner Caption]), <1a>,
figure(```typst = Hello World```, caption: [Inner Caption]), <1b>,
columns: (1fr, 1fr),
caption: [Super],
label: <1>,
)
// setting it propagates the inferred supplement down
#subpar.grid(
figure(```typst = Hello World```, caption: [Inner Caption]), <2a>,
figure(```typst = Hello World```, caption: [Inner Caption]), <2b>,
columns: (1fr, 1fr),
caption: [Super],
kind: raw,
label: <2>,
)
// turning off propagation causes different supplements for super and sub figures
#subpar.grid(
figure(table[A], caption: [Inner Caption]), <3a>,
figure(table[A], caption: [Inner Caption]), <3b>,
columns: (1fr, 1fr),
caption: [Super],
propagate-supplement: false,
label: <3>,
)
@1, @1a, @1b
@2, @2a, @2b
@3, @3a, @3b
|
https://github.com/TheLukeGuy/backtrack | https://raw.githubusercontent.com/TheLukeGuy/backtrack/main/tests/sample.typ | typst | Apache License 2.0 | // Copyright © 2023 <NAME>
// This file is part of Backtrack.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at <http://www.apache.org/licenses/LICENSE-2.0>.
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#import "/src/lib.typ"
#import lib: versions
#let version = lib.current-version
#let cmp-to(other) = [
This is
#if version.cmpable < other.cmpable [
less than
] else if version.cmpable == other.cmpable [
equal to
] else [
greater than
]
Typst #other.displayable.
]
#let body = [
You are using Typst v#version.displayable!
#cmp-to(versions.v0-3-0)
#cmp-to(versions.v0-8-0)
#cmp-to(versions.v2023-01-30)
#cmp-to(versions.v2023-02-25)
#cmp-to(versions.post-v0-8-0(0, 9, 0))
#cmp-to(versions.post-v0-8-0((1, 2), 3))
The minor version is
#if calc.even(version.observable.at(1)) [
even.
] else [
odd.
]
]
#if version.cmpable >= versions.v2023-03-21.cmpable {
set text(font: "Libertinus Serif")
show raw: set text(font: "Libertinus Mono")
show math.equation: set text(font: "Libertinus Math")
body
} else {
set text(family: "Libertinus Serif")
show raw: set text(family: "Libertinus Mono")
show math.formula: set text(family: "Libertinus Math")
body
}
|
https://github.com/SillyFreak/tu-wien-software-engineering-notes | https://raw.githubusercontent.com/SillyFreak/tu-wien-software-engineering-notes/main/formal-methods/notes.typ | typst | #import "@preview/cetz:0.1.2": canvas, draw, tree
#import "@preview/commute:0.2.0": node, arr, commutative-diagram
#import "../template/template.typ": notes
#show: notes.with(
title: "Formal Methods Notes",
authors: (
"<NAME>, 01126573",
),
)
#[
#set heading(numbering: none)
= License
This work ©2023 by <NAME> is licensed under CC BY-SA 4.0. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/4.0/
= Revision history
- no "published" version yet.
= About this document
This document is based on the Formal Methods in Informatics lecture at Vienna University of Technology; particularly from taking it in the 2023/24 winter term. Corrections and additions are welcome as pull requests at
https://github.com/SillyFreak/tu-wien-software-engineering-notes
This document leaves out several details and was written primarily for me, but I hope it is useful for other people as well. Among the things one reading it should keep in mind:
- This is not a replacement to the course slides or the lectures/recordings in any way. Much of the information may require context and/or preliminaries found in the slides or in the lecture.
- In general, I skip formal definitions where they were basic enough for me; for example, I do not repeat syntax and semantic definitions for SIMPLE, FOL, etc.
- The document is in general still incomplete.
- I am fallible and make errors or overlook some points' importance.
If you have questions, feel free to reach out on Github. I may at least occasionally be motivated enough to answer questions, extend the document with explanations based on your question, or help you with adding it yourself.
#pagebreak()
]
= Tseitin translation
The Tseitin translation's purpose is to transform an arbitrary propositional formula into a conjunction of disjunctions (clauses), which can then be fed to a typical SAT solver. In contrast to the CNF, the resulting formula is linear in the input formula's length.
Following, we will translate the example formula from the lecture slides:
$ phi: (p and q -> r) -> (q -> r) $
== Labelling of subformula occurrences (SFOs)
In the tree representation of the formula, every subformula receives a new atom. That new atom is set equivalent to the subformula; if the subformula is not itself atomic, the branches of the subformula are themselves replaced by new atoms.
#grid(
columns: (1fr,)*2,
rows: auto,
gutter: 3pt,
{
set align(center)
let data = (
$->$,
($->$, ($and$, $p$, $q$), $r$),
($->$, $q$, $r$),
)
let add-labels(data, accum: 0) = {
if type(data) != array {
accum += 1
((data: data, label: accum), accum)
} else {
let (root, ..branches) = data
// iterate over branches
for i in range(1, data.len()) {
let branch = data.at(i)
let (branch, new-accum) = add-labels(branch, accum: accum)
accum = new-accum
data.at(i) = branch
}
// transform root
accum += 1
data.at(0) = (data: data.at(0), label: accum)
(data, accum)
}
}
let data = add-labels(data).at(0)
canvas({
import draw: *
set-style(stroke: 0.45pt)
tree.tree(
data,
padding: 0.8,
spread: 0.8,
grow: 1.2,
draw-node: (node, _) => {
let (data, label) = node.content
let label = text(blue, 0.8em)[$ell_#label$]
let label = move(dx: -14pt, dy: -8pt)[#label]
let label = box(width: 0pt)[#label]
content((), [#data#label])
},
draw-edge: (from, to, _) => {
line((a: from, number: .5, abs: true, b: to),
(a: to, number: .5, abs: true, b: from))
},
name: "tree",
)
})
},
[
#show math.attach: it => {
if it.base.text == $ell$.body.text {
text(blue, it)
} else {
it
}
}
$
ell_1 &<-> p \
ell_2 &<-> q \
ell_3 &<-> ell_1 and ell_2 \
ell_4 &<-> r \
ell_5 &<-> ell_3 -> ell_4 \
ell_6 &<-> q \
ell_7 &<-> r \
ell_8 &<-> ell_6 -> ell_7 \
ell_9 &<-> ell_7 -> ell_8 \
$
],
)
We can easily see that subformula $p$ is satisfiable iff $(ell_1 <-> p) and ell_1$ is satisfiable: substituting the left clause into the right one, we are left with exactly $p$. This conjunction of the new atom and the corresponding equivalence clause thus captures the satisfiability of the original subformula. Likewise, for a more complex subformula like $p and q$, we can take $(ell_1 <-> p) and (ell_2 <-> q) and (ell_3 &<-> ell_1 and ell_2) and ell_3$ and get the same result. Applying this to the whole formula $phi$, we get
$
(ell_1 <-> p) and dots and (ell_9 &<-> ell_7 -> ell_8) and ell_9
$
This formula has three crucial properties:
- as stated above, it is satisfiable iff $phi$ is satisfiable (although not logically equivalent because it contains new atoms),
- its length is linear in terms of the length of $phi$, and
- it is essentially _flattened_, which means that the linearity in length will be preserved when transforming it to CNF.
== Generating clauses for the CNF
SAT solvers by convention accept formulas as a set of clauses over a set of atoms. To make the above result usable by such a tool, we need to convert it into this form. Since we have constructed a flat set of equivalence clauses, we can enumerate all possible forms of clauses and how they are translated into CNF. For example:
$
&ell_i <-> x &&equiv (ell_i -> x) &&and (ell_i <- x) &&equiv (not ell_i or x) and (ell_i or not x) \
&ell_i <-> (x and y) &&equiv (ell_i -> (x and y)) &&and (ell_i <- (x and y)) &&equiv (not ell_i or x) and (not ell_i or y) and (ell_i or not x or not y) \
&ell_i <-> (x -> y) &&equiv (ell_i -> (x -> y)) &&and (ell_i <- (x -> y)) &&equiv (not ell_i or not x or y) and (ell_i or x) and (ell_i or not y) \
$
Another approach to getting these clauses' CNFs is directly via the truth table. Recall: from the true (false) entries in a truth table, one can read the DNF (CNF) of the function represented by the truth table:
#[
#let xx = $#hide($not$) x$
#let nx = $not x$
#let yy = $#hide($not$) y$
#let ny = $not y$
#set align(center)
#table(
columns: 5,
align: (x, y) => if y == 0 {
center
} else {
((center,)*3 + (right,)*2).at(x)
},
$x$, $y$, $x xor y$, [DNF], [CNF],
$0$, $0$, $0$, $$, $xx or yy$,
$0$, $1$, $1$, $nx and yy$, $$,
$1$, $0$, $1$, $xx and ny$, $$,
$1$, $1$, $0$, $$, $nx or ny$,
)
]
Each CNF clause is formed from one row where the formula is not satisfied. The first line can be read like this: "if $x |-> 0, y |-> 0$, the formula is not fulfilled, so at least one of the varibales must be opposite from that assignment." Then, if all clauses (that each negate one of the conditions under which the formula is false) are satisfied, the assignment belongs to one of the other rows, i.e. the ones that _do_ satisfy the formula.
Thus, we can enumerate for each subformula in our translation the false assignments and read the CNF from that; for example ("`x`" stands for "don't care"):
#[
#let assign3(a, b, c) = {
[#a #hide($and$) #b #hide($<->$) #c]
}
#set align(center)
#table(
columns: 2,
align: (x, y) => if y == 0 {
center
} else {
(center, left).at(x)
},
$x and y <-> ell$, [CNF],
assign3($0$, `x`, $1$), $x or not ell$,
assign3(`x`, $0$, $1$), $y or not ell$,
assign3($1$, $1$, $0$), $not x or not y or ell$,
)
]
We can now finally translate our formula into a _definitional form_ that is in CNF:
$
(not ell_1 or p) and (ell_1 or not p) and dots and (not ell_9 or not ell_7 or ell_8) and (ell_9 or ell_7) and (ell_9 or not ell_8) and ell_9
$
Or, as a set of clauses instead of a formula:
$
delta(phi) = hat(delta)(phi) union {ell_9} = {not ell_1 or p, ell_1 or not p, dots, not ell_9 or not ell_7 or ell_8, ell_9 or ell_7, ell_9 or not ell_8, ell_9}
$
= Implication Graphs
Implication graphs capture aspects of the logical structure of a set of clauses that are useful for efficiently computing satisfiability of that set of clauses. We will first define some preliminaries, then implication graphs themselves, and then look at some examples.
== Clause states
A clause can have one of four states:
- _satisfied:_ at least one of its literals is assigned true
- _unsatisfied:_ all its literals is assigned false
- _unit:_ all but one literals is assigned false (i.e. the last needs to be assigned true to be satisfied, the decision is forced)
- _unresolved:_ none of the above
== Decisions
Decisions add variable assignments to a partial variable assignment. Depending on when in the process a variable is assigned, a decision has a _decision level_. By deciding one variable per level, decision levels (for regular decisions) range from 1 at most to the number of variables - usually, it will be less, because decisions on unit clauses are forced.
We write $x = v@d$ to say that variable $x$ has been assigned value $v$ at decision level $d$. As a shorthand for $x = 1@d$/$x = 0@d$, we write $x@d$/$not x@d$ (or $ell@d$: deciding a literal at depth $d$, where the literal is a negated or non-negated variable). The _dual_ $ell^d$ (or $ell^d@d$) means the opposite decision of $ell$ (or $ell@d$), e.g. the dual of $x@d$ is $not x@d$ and vice-versa.
== Antecedents
Under a partial variable assignment $sigma$, a clause $C$ may simplify to a unit clause $ell$, which we write $C sigma = ell$. For example, under the partial variable assignment $sigma = { x_1 |-> 1, x_4 |-> 0}$, the clause $C: not x_1 or x_4 or not x_3$ simplifies to $not x_3$.
The clause that, under some $sigma$, forces a decision of $ell$ is called its _antecedent_: $"Antecedent"(ell) = C$. Here, $C$ is treated as a set of literals (i.e. ${not x_1, x_4, not x_3}$). Although it should not matter for the construction of implication graphs, when a literal is not forced under some partial assignment, we can simply take the antecedent to be an empty set.
== The implication graph
An implication graph (IG) is a DAG $G = (V, E)$ that satisfies:
- Each vertex has a label of the form $ell@d$, where $ell$ is some literal and $d$ is a decision level.
- For each vertex $v_j$, take the set of dual literals of its antecedent: ${v_i | v_i^d in "Antecedent"(v_j)}$. For all $v_i$ that are vertices of the graph, there is an edge from $v_i$ to $v_j$, or: $E = {(v_i, v_j) | v_i, v_j in V, v_i^d in "Antecedent"(v_j)}$. All these edges are labelled with $"Antecedent"(v_j)$.
- The way IGs are constructed, all but one $v_i$ _will_ label a vertex in the graph, or equally: the clause $"Antecedent"(v_j)$ is unit and the edges completely decribe why $v_j$ was forced; unforced literals don't have incoming edges. The only $v_i$ that thus didn't label a vertex is $v_j^d$. If that existed, this leads to the other option:
Conflict graphs are also implication graphs, and they contain additionally
- one vertex labelled $kappa$ called the conflict node, and
- edges ${(v, kappa) | v^d in c}$ for some clause $c$.
- Note that there's no "filter" $v in V$ in this definition, so all of $c$'s literals' duals need to actually be vertices, which makes the clause actually unsatisfied and $kappa$'s predecessor nodes conflicting.
Implication graphs are created incrementally by deciding one variable, resolving any unit clauses resulting from that assignment (by boolean constraint propagation or BCP), and repeating that until either all variables are assigned or a conflict is found.
== Example 1
Let's take the single clause $c: not x_1 or x_4 or not x_3$ again and start from zero.
- Arbitrarily we begin by assigning $x_1 |-> 1$, or with the decision $x_1@1$.
- After this decision, we have no unit clause and continue with $x_4 |-> 0$ or $not x_4@2$. At this point, $c$ can be simplified to $not x_3$, meaning we have $"Antecedent"(not x_3) = {not x_1, x_4, not x_3}$.
- We thus add a vertex $not x_3@2$ (at the same depth as the decision that made the clause unit) and two edges $(x_1@1, not x_3@2)$, $(not x_4@2, not x_3@2)$ to the graph.
- All variables have been assigned without conflict; we're done.
#grid(
columns: (auto,)*3,
rows: auto,
gutter: 1fr,
[
#set align(center)
#commutative-diagram(
node-padding: (32pt, 16pt),
node((0, 0), [$x_1@1$]),
// node((2, 0), [$not x_4@2$]),
// node((1, 1), [$not x_3@2$]),
// arr((0, 0), (1, 1), [$C$]),
// arr((2, 0), (1, 1), [$C$]),
)
],
[
#set align(center)
#commutative-diagram(
node-padding: (32pt, 16pt),
node((0, 0), [$x_1@1$]),
node((2, 0), [$not x_4@2$]),
// node((1, 1), [$not x_3@2$]),
// arr((0, 0), (1, 1), [$C$]),
// arr((2, 0), (1, 1), [$C$]),
)
],
[
#set align(center)
#commutative-diagram(
node-padding: (32pt, 16pt),
node((0, 0), [$x_1@1$]),
node((2, 0), [$not x_4@2$]),
node((1, 1), [$not x_3@2$]),
arr((0, 0), (1, 1), [$c$]),
arr((2, 0), (1, 1), [$c$]),
)
],
)
== Example 2
Let's assume that we had not made decisions one after the other (and thus resolved $c$ that became a unit clause) but came up instantly with the assignment ${x_1@1, not x_4@1, x_3@1}$. This would make $c$ unsatisfied and lead to a conflict graph:
#[
#set align(center)
#commutative-diagram(
node-padding: (48pt, 24pt),
node((0, 0), [$x_1@1$]),
node((1, 0), [$not x_4@1$]),
node((2, 0), [$x_3@1$]),
node((1, 1), [$kappa$]),
arr((0, 0), (1, 1), [$c$]),
arr((1, 0), (1, 1), [$c$]),
arr((2, 0), (1, 1), [$c$]),
)
]
== Example 3
To arrive at a conflict organically, we need a set of clauses that can be refuted such as $c_1: x or y$, $c_2: x or z$, $c_3: not y or not z$. We start by assigning $x |-> 0$ and are forced from there:
#grid(
columns: (auto,)*4,
rows: auto,
gutter: 1fr,
[
#set align(center)
#commutative-diagram(
node-padding: (40pt, 20pt),
node((1, 0), [$not x@1$]),
// node((0, 1), [$y@1$]),
// arr((1, 0), (0, 1), [$c_1$]),
// node((2, 1), [$z@1$]),
// arr((1, 0), (2, 1), [$c_2$]),
// node((1, 2), [$kappa$]),
// arr((0, 1), (1, 2), [$c_3$]),
// arr((2, 1), (1, 2), [$c_3$]),
)
],
[
#set align(center)
#commutative-diagram(
node-padding: (40pt, 20pt),
node((1, 0), [$not x@1$]),
node((0, 1), [$y@1$]),
arr((1, 0), (0, 1), [$c_1$]),
// node((2, 1), [$z@1$]),
// arr((1, 0), (2, 1), [$c_2$]),
// node((1, 2), [$kappa$]),
// arr((0, 1), (1, 2), [$c_3$]),
// arr((2, 1), (1, 2), [$c_3$]),
)
],
[
#set align(center)
#commutative-diagram(
node-padding: (40pt, 20pt),
node((1, 0), [$not x@1$]),
node((0, 1), [$y@1$]),
arr((1, 0), (0, 1), [$c_1$]),
node((2, 1), [$z@1$]),
arr((1, 0), (2, 1), [$c_2$]),
// node((1, 2), [$kappa$]),
// arr((0, 1), (1, 2), [$c_3$]),
// arr((2, 1), (1, 2), [$c_3$]),
)
],
[
#set align(center)
#commutative-diagram(
node-padding: (40pt, 20pt),
node((1, 0), [$not x@1$]),
node((0, 1), [$y@1$]),
arr((1, 0), (0, 1), [$c_1$]),
node((2, 1), [$z@1$]),
arr((1, 0), (2, 1), [$c_2$]),
node((1, 2), [$kappa$]),
arr((0, 1), (1, 2), [$c_3$]),
arr((2, 1), (1, 2), [$c_3$]),
)
],
)
_Sneak peek into CDCL:_ our decision of $not x@1$ led to a conflict here (in general, there could be multiple unforced decisions, but here it's just one), so we know that that is a decision we _must not_ make. We thus need to backtrack to before that decision (in this case: before _any_ decision) and prevent ourselves from making that mistake again.
The way this is done is by adding a clause that captures the wrong decision, i.e. $c_4: x$. Because here, we only had one unforced decision, this is already a unit clause, and we're forced to decide $x@0$ (i.e. before the first regular decision).
After that, no clause is unit ($c_1$, $c_2$, $c_4$ are satisfied, $c_3$ is unresolved) so we can make a decision such as $y@1$, which forces a decision on $z$:
#grid(
columns: (auto,)*3,
rows: auto,
gutter: 1fr,
[
#set align(center)
#commutative-diagram(
node-padding: (40pt, 20pt),
node((0, 0), [$x@0$]),
// node((1, 0), [$y@1$]),
// node((1, 1), [$not z@1$]),
// arr((1, 0), (1, 1), [$c_3$]),
)
],
[
#set align(center)
#commutative-diagram(
node-padding: (40pt, 20pt),
node((0, 0), [$x@0$]),
node((1, 0), [$y@1$]),
// node((1, 1), [$not z@1$]),
// arr((1, 0), (1, 1), [$c_3$]),
)
],
[
#set align(center)
#commutative-diagram(
node-padding: (40pt, 20pt),
node((0, 0), [$x@0$]),
node((1, 0), [$y@1$]),
node((1, 1), [$not z@1$]),
arr((1, 0), (1, 1), [$c_3$]),
)
],
)
The core of conflict-driven clause learning (CDCL) is then to define algorithms for finding conflict clauses and backtracking strategies.
|
|
https://github.com/tlsnotary/docs-mdbook | https://raw.githubusercontent.com/tlsnotary/docs-mdbook/main/research/ole-flavors.typ | typst | #set page(paper: "a4")
#set par(justify: true)
#set text(size: 12pt)
= Oblivious Linear Evaluation (OLE) flavors from random OT
Here we sum up different OLE flavors, where some of them are needed for
subprotocols of TLSNotary. All mentioned OLE protocol flavors are
implementations with errors, i.e. in the presence of a malicious adversary, he
can introduce additive errors to the result. This means correctness is not
guaranteed, but privacy is.
== Functionality $cal(F)_"ROT"$
*Note*: In the literature there are different flavors of random OT, depending on
if the receiver can choose his input or not. Here we that assume the receiver
has a choice.
Define the functionality $cal(F)_"ROT"$:
- The sender $P_A$ receives the random tuple $(t_0, t_1)$, where $t_0, t_1$ are
$kappa$-bit messages.
- The receiver $P_B$ inputs a bit $x$ and receives the corresponding $t_x$.
== Random OLE
=== Functionality $cal(F)_"ROLE"$
Define the functionality $cal(F)_"ROLE"$ where
- $P_A$ receives $(a, x)$
- $P_B$ receives $(b, y)$
such that $ y = a dot b + x$
=== Protocol $Pi_"ROLE"$
+ $P_B$ randomly samples $d arrow.l bb(F)$ and $f arrow.l bb(F)$.
+ $P_A$ randomly samples $c arrow.l bb(F)$ and $e arrow.l bb(F)$.
+ For each $i = 1, ... , l$ where $l = |f|$: Both parties call
$cal(F)_"ROT" (f)$, so $P_A$ knows $t_0^i, t_1^i$ and $P_B$ knows $t_(f_i)$.
+ $P_A$ sends $e$ and $u_i = t_(i,0) - t_(i,1) + c$ to $P_B$.
+ $P_B$ defines $b = e + f$ and sends $d$ to $P_A$.
+ $P_A$ defines $a = c + d$ and outputs
$x = sum 2^i t_(i,0) - a dot e$
+ $P_B$ computes $ y_i
&= f_i (u_i + d) + t_(i,f_i) \
&= f_i (t_(i,0) - t_(i,1) + c + d) + t_(i,f_i) \
&= f_i dot a + t_(i,0) $
and outputs $y = 2^i y_i$
+ Now it holds that $y = a dot b + x$.
== Vector OLE
=== Functionality $cal(F)_"VOLE"$
Define the functionality $cal(F)_"VOLE"$ which maintains a counter $k$ and
which allows to call an $"Extend"_k$ command multiple times.
- When calling $"Initialize"$, $P_B$ inputs a field element $b$. This sets up the
functionality for subsequent calls to $"Extend"_k$.
- When calling $"Extend"_k$: $P_A$ receives $(a_k, x_k)$ and $P_B$ receives
$y_k$.
such that $ y_k = a_k dot b + x_k$
=== Protocol $Pi_"VOLE"$
*Note*: This is the $Pi_"COPEe"$ construction from KOS16.
+ Initialization:
- $P_B$ chooses some field element $b$.
- Both parties call $cal(F)_"ROT" (b)$, so $P_A$ knows
$t_0^i, t_1^i$ and $P_B$ knows $t_(b_i)$.
- With some PRF define: $s_(i,0)^k := "PRF"(t^i_0, k)$, $s_(i,1)^k :=
"PRF"(t^i_1, k)$
+ $"Extend"_k$: This can be batched or/and repeated several times.
- $P_A$ chooses some field element $a_k$ and sends
$u_i^k = s_(i,0)^k - s_(i,1)^k + a_k$ to $P_B$.
- $P_A$ outputs $x_k = sum 2^i s_(i,0)^k$
- $P_B$ computes $ y^k_i
&= b_i dot u^k_i + s_(i,f_i)^k \
&= b_i (s_(i,0)^k - s_(i,1)^k + a_k) + s_(i,f_i)^k \
&= b_i dot a_k + s_(i,0)^k $
and outputs $y_k = 2^i y^k_i$
+ Now it holds that $y_k = a_k dot b + x_k$.
== Random Vector OLE
=== Functionality $cal(F)_"RVOLE"$
Define the functionality $cal(F)_"RVOLE"$ which maintains a counter $k$ and
which allows to call an $"Extend"_k$ command multiple times.
- When calling $"Initialize"$, $P_B$ receives a field element $b$. This sets up
the functionality for subsequent calls to $"Extend"_k$.
- When calling $"Extend"_k$: $P_A$ receives $(a_k, x_k)$ and $P_B$ receives
$y_k$.
such that $ y_k = a_k dot b + x_k$
=== Protocol $Pi_"RVOLE"$
+ Initialization:
- $P_B$ chooses some field element $f$.
- Both parties call $cal(F)_"ROT" (f)$, so $P_A$ knows
$t_0^i, t_1^i$ and $P_B$ knows $t_(f_i)$.
- $P_A$ sends $e$ to $P_B$ and $P_B$ defines $b = e + f$.
- With some PRF define: $s_(i,0)^k := "PRF"(t^i_0, k)$, $s_(i,1)^k :=
"PRF"(t^i_1, k)$
+ $"Extend"_k$: This can be batched or/and repeated several times.
- $P_A$ samples randomly $c_k arrow.l bb(F)$ and
$P_B$ samples randomly $d_k arrow.l bb(F)$.
- $P_A$ sends $u_i^k = s_(i,0)^k - s_(i,1)^k + c_k$ to $P_B$.
- $P_B$ sends $d_k$ to $P_A$.
- $P_A$ defines $a_k = c_k + d_k$ and outputs
$x_k = sum 2^i s_(i,0)^k - a_k dot e$
- $P_B$ computes $ y^k_i
&= f_i (u^k_i + d_k) + s_(i,f_i)^k \
&= f_i (s_(i,0)^k - s_(i,1)^k + c_k + d_k) + s_(i,f_i)^k \
&= f_i dot a_k + s_(i,0)^k $
and outputs $y_k = 2^i y^k_i$
+ Now it holds that $y_k = a_k dot b + x_k$.
== OLE from random OLE
=== Functionality $cal(F)_"OLE"$
Define the functionality $cal(F)_"OLE"$. After getting input $a$ from $P_A$ and $b$
from $P_B$ return $x$ to $P_A$ and $y$ to $P_B$ such that $y = a dot b + x$.
=== Protocol $Pi_"OLE"$
Both parties have access to a functionality $cal(F)_"ROLE"$, and call
$"Extend"_k$, so $P_A$ receives $(a'_k, x'_k)$ and $P_B$ receives $(b'_k, y'_k)$.
Then they perform the following derandomization:
- $P_A$ sends $u_k = a_k + a'_k$ to $P_B$.
- $P_B$ sends $v_k = b_k + b'_k$ to $P_A$.
- $P_A$ outputs $x_k = x'_k + a'_k dot v_k$.
- $P_B$ outputs $y_k = y'_k + b_k dot u_k$.
Now it holds that $ y_k - x_k
&= (y'_k + b_k dot u_k) - (x'_k + a'_k dot v_k) \
&= (y'_k + b_k dot (a_k + a'_k)) - (x'_k + a'_k dot (b_k + b'_k)) \
&= a_k dot b_k
$
|
|
https://github.com/0xPARC/0xparc-intro-book | https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/summer-notes-evan/0xparc-summer-2024-notes.typ | typst | #import "@local/evan:1.0.0":*
#show: evan.with(
title: [Evan's notes],
subtitle: [0xPARC Summer 2024],
author: "<NAME>",
date: datetime.today(),
)
#toc
#include "src/0801-symposium.typ"
#include "src/0803-research-workshop.typ"
#include "src/0812-math-seminar.typ"
#include "src/0813-math-seminar.typ"
#include "src/0813-evan-talk.typ"
#include "src/0821-multilinear.typ"
|
|
https://github.com/catarinacps/typst-abnt | https://raw.githubusercontent.com/catarinacps/typst-abnt/main/presets.typ | typst | MIT License | #let bachelors(title, course) = [
Monograph presented as a partial requirement
for the degree of #title in #course
]
#let inf-ufrgs = (
name: [Instituto de Informática],
department-ina: [Departamento de Informática Aplicada],
department-int: [Departamento de Informática Teórica],
director: ([Diretora do Instituto de Informática], [Prof#super[a]. <NAME>]),
librarian: ([Bibliotecário-Chefe do Instituto de Informática], [<NAME>]),
cic-coord: ([Coordenador do Curso de Ciência de Computação], [Prof. <NAME>]),
)
#let ufrgs = (
name: [Universidade Federal do Rio Grande do Sul],
location: [Porto Alegre, RS],
nominata: (
([Reitor], [Prof. <NAME>]),
([Vice-Reitora], [Prof#super[a]. <NAME>]),
([Pró-Reitor de Graduação], [Prof. <NAME>])
),
courses: (
cic: (
name: [Computer Science],
program: [Bachelor of Science in Computer Science],
title: [Bachelor],
department: inf-ufrgs.name,
nominata: (
inf-ufrgs.director,
inf-ufrgs.cic-coord,
inf-ufrgs.librarian
)
)
)
)
|
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/common-tools/jointer.typ | typst |
#import "/meta-environments/env-features.typ": *
= Jointer
The _jointer_ (or in some countries a _surface planer_) can flatten the face of a board. The newly flattened face can then be presented to the fence to create a board with an edge square to the face.
== Notes
=== Safety
- Keep hands six inches from the cutter.
- Never push on the workpiece above the cutter.
=== Care
- *Do not adjust the outfeed table.* \
_The machine will bind and kick back if it is not correctly adjusted to the height of the cutter._
- Watch for excessive chip ejection around the cutter and machine base. If a lot of chips are getting ejected, check the dust collection boot for build up, and clean the chute when needed.
- Do not cut engineered materials, splintered wood, or wood with knots on the jointer.\
_These materials are prone to chipping, causing kickback and projectiles. Engineered materials are also particularly damaging to the cutters due to the staggered grain orientation._
== Parts of the Jointer
=== Full View
#figure(
image("images/jointer-front_quarter-annotated.png", width: 100%),
caption: [
An annotated full view of the jointer.
],
)
=== Fence Releases
#figure(
image("images/jointer-fence_controls-annotated.png", width: 100%),
caption: [
Handles on the back of the jointer to release the fence.
],
)
=== On/Off/Emergency Buttons
Use the *green button* to turn on the machine.
Use the *red button* to turn off the machine.
The large red *emergency stop* button is designed to be easy to hit if you need to power off the machine quickly. If you use the emergency stop button, you must twist the emergency stop button to release it (the button is spring loaded, and will pop out when released). The machine will not run until the emergency stop button is released.
During normal usage it is better to use the stop button instead of the emergency stop button.
=== Cutter
The cutter is a helical cutter head with many carbide inserts.
Always maintain a safe distance from the cutter. Never push down on a workpiece over the cutter head; the workpiece may be kicked out of the machine, exposing the cutter heads to your hands.
=== Blade Guard
The blade guard covers the cutting head when there is no workpiece moving through the jointer. This style of guard is sometimes called a "pork chop" style guard due to its shape.
The guard should easily swing out of the way with the workpiece. If the guard does not easily move, *STOP*. Do not try to force the guard. Turn off the machine and alert a shop tech.
Do not try to prop the guard open or open the guard manually while the cutter is moving.
=== Infeed Table
The infeed table holds the workpiece before it contacts the cutting head. Push the workpiece along the infeed table toward the cutting head to begin the cut.
The depth of cut is determined by how far the infeed table sits below the apex of the cutting head.
=== Infeed Height Adjustment Crank
The infeed hight adjustment crank raises and lowers the infeed table to adjust how much material is taken off on each pass. Taking multiple light cuts is recommended for better control and quality of cut.
In general, a cut depth greater than 1/8" is not recommended.
=== Fence
The fence can be moved laterally to expose more or less of the cutting head, and angled with repsect to the outfeed table.
Normally, the fence is set to be perpendicular to the plane of the outfeed table. Always check your desired angle with a quality square or gauge.
The fence does not need to be perpendicular to the rotational axis of the cutter, only to the plane of the outfeed table.
=== Fence Position Lock
The fence position lock secures the fence's lateral position with respect to the cutting head.
*Do not move the fence without first unlocking it.* Always lock the fence after moving it to a new position.
=== Fence Angle Lock
Secures the fence angle with respect to the tables.
=== Fence Perpendicular Stop
Use this stop to quickly index the fence to the perpendicular.
=== Outfeed Table
The outfeed table supports the workpiece after it has passed over the cutter. The height of the outfeed table should always match the apex of the cutting head.
=== Outfeed Height Adjustment Crank
*Do not use the outfeed hight adjustment crank.* This setting should _never_ be used unless the jointer is out of calibration and you are trained and have permission to do so.
== Basic Operation
=== Workholding
When face jointing, use pads to apply pressure straight down to keep the board in good contact with the table.
When edge jointing, use pads to apply pressure at a 45° angle to that the board is in good contact with both the table and the fence.
=== Setting Up
+ Turn on the dust collection.
+ Open the blast gate.
+ Adjust the depth of cut. \
_Maximum cut of 1/16" for faces and 1/8" for edges._
+ Place the workpiece on the infeed table, with the widest, most stable surface facing the table.\
_If the workpiece is cupped, place the cupped (concave) side facing down._
+ Turn on the motor.
=== Joint the Workpiece
+ Using a push block to gently keep the workpiece in contact with the infeed table and fence, begin pushing the workpiece across the cutter. \
_Move the workpiece as smoothly as possible._
+ *Do not push down on the workpiece over the cutter.*\
_Pushing down on the workpiece over the cutter will flex the warped wood flat during cutting, preventing the workpiece from becoming flat when released._
+ Once all of the workpiece is on the outfeed table, use a push pad to gently keep the workpiece in contact with the outfeed table and the fence. Use a push block on the tail end to gently push the work piece past the cutter with only light downward pressure.\
_Keep your fingers free of the cutter._
+ Repeat until the surface is flat.\
_Check for flat by checking for light when placing the workpiece on a known flat surface, or checking with a rule. If multiple passes does not seem to make progress toward flatness, this indicates that the outfeed table is misadjusted._
Flip the workpiece on its side so that the flat edge is against the fence, and repeat the jointing procedure to flatten the second edge. Test the corner with a square to make sure the corner is true. When edge jointing the fence is the most important reference surface.
=== Cleaning Up
+ Turn off the motor.
+ Sweep up any dust and/or shavings.\
_There is a floor intake for the dust collection system on the wall behind the resaw bandsaw._
+ Close the blast gate.
+ Turn off the dust collection.\
_If other members are still using the dust collector, leave it on._ |
|
https://github.com/m-pluta/bias-in-ai-report | https://raw.githubusercontent.com/m-pluta/bias-in-ai-report/main/report/recommend.typ | typst | = Value Conflict Analysis <S_VCA>
// #highlight([
// - How human values were identified
// - Describe potential value conflicts
// - Data Collection vs. Privacy
// - How these may be resolved, which group's interests should be prioritised - always prioritise individuals freedoms
// ])
Individuals and corporations intrinsically value different things.
Individuals often value autonomy, privacy, and security, seeking to protect their personal information and maintain control over their personal lives and decisions. Corporations, on the other hand, typically value profitability and efficiency, seeking to analyse all available data to improve performance.
This divergence in values is identified in @F_stakeholder_table and cases such as the Cambridge Analytica scandal and the 2017 Equifax breach, underline the importance of resolving this conflict.
In this particular use case, the key conflict lies between the agency wanting consumers' facial and emotional data and the individuals wanting a degree of privacy and assurance that their data is adequately protected.
In order to resolve this conflict it is necessary to conduct empirical investigations to gather qualitative data on how each stakeholder feels towards the technology as well as quantitative data investigating suitable methods for:
- obtaining informed consent
- ensuring transparency through data collection and use
- implementing robust data protection measures
Importantly, there are two more existing conflicts between stakeholders:
+ Developers are likely to prioritise the safety and quality of the model, while the advertising agency may aim for rapid deployment at the expense of thorough testing and safeguarding. Here, prioritising the developer's value for safety is crucial, and suitable protocols should be established to never allow an unsafe model to be deployed for public use.
+ The government has a responsibility to protect public welfare and environmental sustainability, both of which the advertising agency may sacrifice in order to advance development. In this case, the government's values must be prioritised to ensure irreversible damage is not done by the agency and that all actions are heavily regulated.
= Recommendations <S_Recommendations>
Based on the insights uncovered by the EIA in @S_EIA and @S_VCA, it is clear that many empirical investigations have to be undertaken before designing can begin.
Additionally, in order to create a model that is deemed 'fair' and 'unbiased', it is important to first contextually define these notions. Currently, there are at least 20 admissible definitions for AI fairness @P_Verma_fairness_definitions including both statistical and causal definitions "with no clear agreement on which definition to apply in each scenario" @P_Verma_fairness_definitions.
We suggest that these notions should first be formally defined and guided by further empirical investigations into stakeholders' perceptions of 'fairness' and 'bias'.
== Choice of Dataset <S_Dataset>
As outlined in @S_Intro, the dataset should consist of human faces labelled with the corresponding emotion.
When selecting such a dataset, there are four key factors to consider:
+ _Accuracy_ - Are faces labelled correctly?
+ _Completeness_ - Do there exist unlabelled faces? If so, are the remaining faces still representative of the population? Are all demographics equally represented?
+ _Consistency_ - Is the labelling consistent?
+ _Relevance_ - Are there too many distinct labels? Are all the faces human?
Among the presently available datasets, AffectNet @D_AffectNet stands out by being the largest collection of images and often being used as a benchmark. Despite this, it is ultimately extremely biased @P_affectnet_white_bias through its over-representation of the white race.
Although diversity considerations were made during its inception, the images lack crucial demographic annotations @P_affectnet_bias which makes it difficult to monitor technical bias during the training process. Furthermore, a recent study of AffectNet's underlying bias revealed that a given model's bias is unlikely to be caused by the dataset's bias. This is due to the mitigation strategy of balancing the dataset being unsuccessful as a result of pre-existing bias in the images.
This has led to the creation of face-attributed datasets like FairFace @D_fairface which are labelled by gender, race, and age. Notably, FairFace is comparable in size to AffectNet (n$approx$100000), and is also race-balanced, meaning all 7 races identified have an equal representation @P_fairface_paper. However, a potential limitation of this dataset is the distribution is unlikely to align with the population the algorithm is being applied to, leading to lower accuracy.
== Risk and bias mitigation measures
- *Interpretability and Explainability* -
In machine learning, models are often tasked with optimising an objective function, and while the model may be perfectly capable of doing this, it is often difficult for humans to gain insight @W_interpretability_def_useful. This is the key benefit of interpretable models that allows humans to understand what caused the model to make a particular decision @W_interpretability_definition and explainable models which involve creating a second model capable of explaining the choices made by the ML system @P_bias_mitigation_in_medicine_explainability.
By incorporating these measures into the design process, it promotes responsible development as the effects of changes made to the model can be verified by examining the decision process. This helps avoid unintentional addition of bias to the system. @W_interpretability_benefit
- *Continuous monitoring* -
This mitigation measure is a long-term strategy that involves continuously monitoring the model's evaluation metrics, which can include accuracy, precision, recall, and f1-score for each demographic indicator (race, gender, age).
The continuous monitoring of the model's behaviour means that model drift and degradation in performance can be identified and corrected @W_continuous_monitoring_explained. This allows developers to quickly address the issue (or shut down the entire model) before the model can generate unfair or harmful outputs.
- *Diversity and inclusion* -
By encouraging diversity within the development team and involving indirect stakeholders in discussions, the likelihood of identifying and challenging assumptions that could result in biased outcomes increases. This approach not only helps reduce bias and potential harm to end users, but also increases the system's fairness and equity.
== Critical Assessment and Limitations
While these mitigation strategies are theoretically plausible, in practice they offer a multitude of limitations.
Interpretability for example offers a serious trade-off. Often, highly interpretable models may struggle with capturing complex relationships within data @P_interpretability_limitations (particularly applicable to image data due to its complexity), which can reduce the model's overall accuracy making it more susceptible to producing wrong outputs and harming users.
Moreover, while VSD is a well-studied framework, it is a theoretically grounded approach @P_2_value_sensitive_design which does not provide a clear way of embedding values into the design @P_VSD_in_AI_critiques. |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10B60.typ | typst | Apache License 2.0 | #let data = (
("INSCRIPTIONAL PAHLAVI LETTER ALEPH", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER BETH", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER GIMEL", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER DALETH", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER HE", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER WAW-AYIN-RESH", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER ZAYIN", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER HETH", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER TETH", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER YODH", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER KAPH", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER LAMEDH", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER MEM-QOPH", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER NUN", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER SAMEKH", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER PE", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER SADHE", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER SHIN", "Lo", 0),
("INSCRIPTIONAL PAHLAVI LETTER TAW", "Lo", 0),
(),
(),
(),
(),
(),
("INSCRIPTIONAL PAHLAVI NUMBER ONE", "No", 0),
("INSCRIPTIONAL PAHLAVI NUMBER TWO", "No", 0),
("INSCRIPTIONAL PAHLAVI NUMBER THREE", "No", 0),
("INSCRIPTIONAL PAHLAVI NUMBER FOUR", "No", 0),
("INSCRIPTIONAL PAHLAVI NUMBER TEN", "No", 0),
("INSCRIPTIONAL PAHLAVI NUMBER TWENTY", "No", 0),
("INSCRIPTIONAL PAHLAVI NUMBER ONE HUNDRED", "No", 0),
("INSCRIPTIONAL PAHLAVI NUMBER ONE THOUSAND", "No", 0),
)
|
https://github.com/EpicEricEE/typst-plugins | https://raw.githubusercontent.com/EpicEricEE/typst-plugins/master/united/src/united.typ | typst | #import "number.typ": format-number, format-range
#import "unit.typ": format-unit
// Convert the argument to a string.
//
// The argument can be of type `int`, `float`, `symbol`, `str`, or `content`.
//
// If the argument is of type `content`, it can be an `attach`, `frac`, `lr`,
// `smartquote` or `text` element, or a sequence of these.
#let to-string(body) = {
if type(body) == str {
// Strings
return body.replace("\u{2212}", "-")
} else if type(body) in (int, float, symbol) {
// Numbers and symbols
return to-string(str(body))
} else if type(body) == content {
if body.func() == math.attach {
// Exponents
let base = to-string(body.base)
let exponent = to-string(body.t)
return base + "^" + exponent
} else if body.func() == math.frac {
// Fractions
let num = to-string(body.num)
let denom = to-string(body.denom)
return num + "/" + denom
} else if body.func() == math.lr {
// Left/right
return to-string(body.body)
} else if body.func() == smartquote {
// Quotation marks
return "'"
} else if body.has("children") {
// Sequences
return body.children.map(to-string).join("")
} else if body.has("text") {
// Text
return to-string(body.text)
} else if body == [ ] or repr(body.func()) == "space" {
// Space
return " "
}
}
panic("cannot convert argument to string")
}
// Format a number.
//
// Parameters:
// - value: The number.
// - product: The symbol to use for the exponent product.
// - uncertainty: How to display uncertainties.
// - decimal-sep: The decimal separator.
// - group-sep: The separator between digit groups.
#let num(
value,
product: math.dot,
uncertainty: "plusminus",
decimal-sep: ".",
group-sep: math.thin
) = {
let result = format-number(
to-string(value),
product: product,
uncertainty: uncertainty,
decimal-sep: decimal-sep,
group-sep: group-sep
)
$result$
}
// Format a unit.
//
// Parameters:
// - unit: The unit.
// - unit-sep: The separator between units.
// - per: How to format fractions.
#let unit(
unit,
unit-sep: math.thin,
per: "reciprocal"
) = {
let result = format-unit(
to-string(unit),
unit-sep: unit-sep,
per: per
)
$result$
}
// Format a quantity (i.e. number with a unit).
//
// Parameters:
// - value: The number.
// - unit: The unit.
// - product: The symbol to use for the exponent product.
// - uncertainty: How to display uncertainties.
// - decimal-sep: The decimal separator.
// - group-sep: The separator between digit groups.
// - unit-sep: The separator between units.
// - per: How to format fractions.
#let qty(
value,
unit,
product: math.dot,
uncertainty: "plusminus",
decimal-sep: ".",
group-sep: math.thin,
unit-sep: math.thin,
per: "reciprocal"
) = {
let result = format-number(
to-string(value),
product: product,
uncertainty: uncertainty,
decimal-sep: decimal-sep,
group-sep: group-sep,
follows-unit: true,
)
result += format-unit(
to-string(unit),
unit-sep: unit-sep,
per: per,
prefix-space: true
)
$result$
}
// Format a range.
//
// Parameters:
// - lower: The lower bound.
// - upper: The upper bound.
// - product: The symbol to use for the exponent product.
// - uncertainty: How to display uncertainties.
// - decimal-sep: The decimal separator.
// - group-sep: The separator between digit groups.
// - delim: Symbol between the numbers.
// - delim-space: Space between the numbers and the delimiter.
#let numrange(
lower,
upper,
product: math.dot,
uncertainty: "plusminus",
decimal-sep: ".",
group-sep: math.thin,
delim: "to",
delim-space: sym.space,
) = {
let result = format-range(
to-string(lower),
to-string(upper),
product: product,
uncertainty: uncertainty,
decimal-sep: decimal-sep,
group-sep: group-sep,
delim: delim,
delim-space: delim-space
)
$result$
}
// Format a range with a unit.
//
// Parameters:
// - lower: The lower bound.
// - upper: The upper bound.
// - unit: The unit.
// - product: The symbol to use for the exponent product.
// - uncertainty: How to display uncertainties.
// - decimal-sep: The decimal separator.
// - group-sep: The separator between digit groups.
// - delim: Symbol between the numbers.
// - delim-space: Space between the numbers and the delimiter.
// - unit-sep: The separator between units.
// - per: How to format fractions.
#let qtyrange(
lower,
upper,
unit,
product: math.dot,
uncertainty: "plusminus",
decimal-sep: ".",
group-sep: math.thin,
delim: "to",
delim-space: math.space,
unit-sep: math.thin,
per: "reciprocal"
) = {
let result = format-range(
to-string(lower),
to-string(upper),
product: product,
uncertainty: uncertainty,
decimal-sep: decimal-sep,
group-sep: group-sep,
delim: delim,
delim-space: delim-space,
follows-unit: true,
)
result += format-unit(
to-string(unit),
unit-sep: unit-sep,
per: per,
prefix-space: true
)
$result$
}
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/out-of-flow-in-block_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Mix-and-match all the previous ones.
#set page(height: 5cm, margin: 1cm)
Mix-and-match all the previous tests.
#block(breakable: true, above: 1cm, stroke: 1pt, inset: 0.5cm)[
#counter("dummy").step()
#place(dx: -0.5cm, dy: -0.75cm, box(width: 200%)[OOF])
#line(length: 100%)
#place(dy: -0.8em)[OOF]
#rect(height: 2cm, fill: gray)
]
|
https://github.com/Turkeymanc/notebook | https://raw.githubusercontent.com/Turkeymanc/notebook/main/entries/entries.typ | typst | #include "./example-entry.typ"
// TODO: add more entries here
// entries will appear in included order
|
|
https://github.com/dainbow/MatGos | https://raw.githubusercontent.com/dainbow/MatGos/master/themes/11.typ | typst | #import "../conf.typ": *
= Свойства интеграла с переменным верхним пределом (непрерывность, дифференцируемость). Формула Ньютона-Лейбница.
== Свойства интеграла с переменным верхним пределом
#definition[
*Разбиением* $P$ отрезка $[a, b]$ называется конечное множество точек отрезка $[a, b]$:
#eq[
$P: a = x_0 < x_1 < ... < x_n = b; quad Delta x_k := x_k - x_(k - 1); k = overline("1, n")$
]
]
#definition[
*Диаметром разбиения* $P$ называется
#eq[
$Delta(P) = max_(1 <= i <= n) Delta x_i$
]
]
#definition[
*Верхней суммой Дарбу* разбиения $P$ функции $f$ называется
#eq[
$U(P, f) = sum_(k = 1)^n sup_(x in [x_(k - 1), x_k]) f(x) dot Delta x_k$
]
]
#definition[
*Нижней суммой Дарбу* разбиения $P$ функции $f$ называется
#eq[
$U(P, f) = sum_(k = 1)^n inf_(x in [x_(k - 1), x_k]) f(x) dot Delta x_k$
]
]
#definition[
Функция $f$ называется *интегрируемой по Риману* на $[a, b]$ ($f in cal(R)[a, b]$),
если
#eq[
$forall epsilon > 0 : exists P : space U(P, f) - L(P, f) < epsilon$
]
]
#definition[
*Интегралом Римана* интегрируемой по Риману на $[a, b]$ функции $f$ называется
#eq[
$integral_a^b f(x) dif x = inf_P U(P, f) = sup_P L(P, f)$
]
]
#theorem(
"Основные свойства интеграла Римана",
)[
+ (Линейность) Если $f_1, f_2 in cal(R)[a, b]$, то $f_1 + f_2 in cal(R)[a, b]$,
причём
#eq[
$integral_a^b (f_1 + f_2)(x) dif x = integral f_1(x) dif x + integral f_2(x) dif x$
]
Кроме того, $forall c in RR$ выполняется, что $c f_1 in cal(R)[a, b]$, причём
#eq[
$integral_a^b c f_1(x) dif x = c integral_a^b f_1(x) dif x$
]
+ (Монотонность) Если $f_1, f_2 in cal(R)[a, b]$ и $forall x in [a, b]: space f_1(x) <= f_2(x)$,
то
#eq[
$integral_a^b f_1(x) dif x <= integral_a^b f_2(x) dif x$
]
+ (Аддитивность):
#eq[
$f in cal(R)[a, b] <=> forall c in (a, b): space f in cal(R)[a, c] and f in cal(R)[c, b]$
]
Причём $integral_a^b f(x) dif x = integral_a^c f(x) dif x + integral_c^b f(x) dif x$
+ (Оценка) Если $f in cal(R)[a, b]$ и $forall x in [a, b]: space abs(f(x)) <= M$,
то
#eq[
$abs(integral_a^b f(x) dif x) <= M (b - a)$
]
]
#theorem(
"<NAME>",
)[
Функция интегрируема по Риману на отрезке $[a, b]$, тогда и только тогда, когда на этом отрезке она ограничена,
и множество точек, где она разрывна, имеет нулевую меру Лебега.
]
#theorem(
"Достаточные условия интегрируемости по Риману",
)[
+ Непрерывная на отрезке функция интегрируема на нем;
+ Ограниченная на отрезке функция, разрывная в конечном числе его точек, интегрируема на этом отрезке;
+ Монотонная на отрезке функция, интегрируема на нем;
+ Произведение интегрируемой функции на число интегрируемо;
+ Сумма интегрируемых функций интегрируема;
+ Произведение интегрируемых функций интегрируемо;
+ Если отношение двух интегрируемых функций ограничено, то оно интегрируемо.
Частный случай -- если множество значений знаменателя не имеет $0$ предельной точкой;
+ Модуль интегрируемой функции интегрируем.;
]
#definition[
Пусть $forall b' in (a, b) : space f in cal(R)[a, b']$. Тогда $F(b') = integral_a^b' f(x) dif x$ называется
*интегралом с переменным верхним пределом*.
Будем считать, что $F(a) = 0$, а для $alpha > beta$:
#eq[
$integral_alpha^beta f(x) dif x = -integral_beta^alpha f(x) dif x$
]
]
#theorem(
"Основные свойства интеграла с переменным верхним пределом",
)[
Если $f in cal(R)[a, b]$, то интеграл с перменным верхним пределом $F(x)$ непрерывен
на $[a, b]$.
Если, кроме того, $f$ непрерывна в $x_0 in [a, b]$, то $F(x)$ дифференцируема в $x_0$,
причём $F'(x_0) = f(x_0)$.
]
#proof[
Непрерывность следует из комбинирования свойств аддитивности и оценки:
#eq[
$forall x_1, x_2 in [a, b] : x_1 < x_2 and x_2 - x_1 < epsilon / M : space abs(F(x_2) - F(x_1)) &= abs(integral_(x_1)^(x_2) f(x) dif x) <=\ integral_(x_1)^(x_2) abs(f(x)) dif x &<= M(x_2 - x_1) < epsilon$
]
В условиях непрерывности $f$, докажем, что производная интеграла действительно
равна $f(x_0)$:
#eq[
$abs((F(x) - F(x_0)) / (x - x_0) - f(x_0)) = abs(1 / (x - x_0) integral_(x_0)^x (f(t) - f(x_0)) dif t) <= sup_(t in [x_0, x]) abs(f(t) - f(x_0))$
]
Благодаря непрерывности $f$ мы знаем, что при $x -> x_0$ сможем оценить итоговый
супремум сверху $epsilon$.
]
== Формула Ньютона-Лейбница
#definition[
*Первообразной* функции $f$ на $[a, b]$ называется такая дифференцируемая на $[a, b]$ функция $F$,
что
#eq[
$forall t in [a, b] : space F'(t) = f(t)$
]
]
#definition[
*Интегральной суммой* $S(P, f, seq(idx: i, end: n, t))$ называется
#eq[
$sum_(i = 1)^n f(t_i) Delta x_i$
]
где $P : a = x_0 < ... < x_n = b, forall i = overline("1, n"): t_i in [x_(i - 1), x_i]$.
]
#theorem(
"Интеграл как предел интегральных сумм",
)[
#eq[
$f in cal(R)[a, b] <=> exists lim_(Delta(P) -> 0) S(P, f, seq(idx: i, end: n, t))$
]
При этом $integral_a^b f(x) dif x = lim_(Delta(P) -> 0) S(P, f, seq(idx: i, end: n, t))$
]
#theorem("Основная теорема интегрального исчисления")[
Если $f in cal(R)[a, b]$ имеет первообразную $F$ на $[a, b]$, то
#eq[
$integral_a^b f(x) dif x = F(b) - F(a) = F(x)|_a^b$
]
]
#proof[
Для любого разбиения $P$:
#eq[
$F(b) - F(a) attach(=, t: "телескопическая сумма") sum_(k = 1)^n (F(x_k) - F(x_(k - 1))) attach(=, t: "теорема Лагранжа") \
sum_(k = 1)^n F'(xi_k) Delta x_k = sum_(k = 1)^n f(xi_k) Delta x_k$
]
Устремляя $Delta(P) -> 0$ получим, что $F(b) - F(a)$ равно требуемому интегралу
по эквивалентному определению.
]
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/009%20-%20Born%20of%20the%20Gods/003_Emonberry%20Red.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Emonberry Red",
set_name: "Born of the Gods",
story_date: datetime(day: 05, month: 02, year: 2014),
author: "<NAME>",
doc
)
#emph[There was no need to trouble the Agent for this; it simply required Adrasteia's shears. Such a shame, she thought, and sighed aloud. Her two sisters, one at the far end of the enormous and ancient oak table, the other at the side midway between the two, paused their work on a great tapestry spread out between them to look up.]
#emph[Two threads, one blue, the other gold, which had begun their journey through the tapestry in parallel, had now become intertwined. This happened all the time, and each time it was a new entanglement, sometimes beautiful, sometimes tragic, sometimes both. Such beauty could be found in tragedy; however, Adrasteia did not allow herself to be influenced by what she witnessed among the threads of the tapestry. She must consider the welfare of the whole. These two particular threads had, indeed, created a beautiful pattern as they wound about one another, bordered on all sides by darker-hued threads in patterns that seemed intent upon pulling the blue and gold apart.]
#emph[The weavework of these two was unconventional, so singular in its expression that even Adrasteia, whose detachment and efficiency were renowned, indulged a longer moment of appreciation. The moment passed, and it was time for her to get to work with her shears on the snarl that had developed in the threads.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Pavios lay awake in his dark room. Heliod had long since ridden below the horizon. Despite an exhausting day walking what surely must have been every avenue and alley of the polis of Akros in tow behind his father—who insisted on introducing Pavios to an endless list of government officials and diplomats, bankers and business people—Pavios could not sleep. He thought only of Thanasis, who lay just on the other side of the wall behind his head. He wondered if Thanasis had read the note Pavios had left for him, and found the gift he had hidden earlier, behind their adjoining houses, beneath the pile of coal Thanasis's father used in his smithing.
#figure(image("003_Emonberry Red/01.jpg", width: 100%), caption: [Temple of Enlightenment | Art by <NAME>ov], supplement: none, numbering: none)
A knot clenched in Pavios's throat the more he thought about not seeing Thanasis again. Just two days hence, Pavios's father planned to send him back to Meletis to marry the daughter of a prominent official—a sweet but uninteresting girl whose soft face shone perpetually clean and rosy, as if she scrubbed it every hour. The girl's father had presented a fine short sword to Pavios to seal the contract between the two families. Pavios had stood motionless, unable to move to take the sword. His arms felt too heavy. The sword might as well have been manacles binding him to this girl and the political designs of their fathers. His father stepped forward quickly and accepted the gift on Pavios's behalf. It was done.
In two days, he would never see Thanasis again, and the thought made sleep seem like a waste of precious time.
It had become very difficult to communicate with Thanasis, and letting him know where to look for the gift had not been easy. Although they lived next to one another, separated by that simple masonry wall, their parents were not friends, and they may as well have lived on opposite sides of Akros. The fathers of the two families avoided any interaction with one another. Pavios's father was an ambassador from Meletis, and the two of them had relocated to Akros six months before. It was not an assignment Pavios's father desired, and uprooting to take a post in Akros was to him a demotion that cast him into a perpetual brood. It was not long after taking up this residence in the small home next to the blacksmith that the fathers quarreled, and Pavios was forbidden from associating with the blacksmith's quiet and handsome son.
As Pavios tossed in the dark, it occurred to him that he did not know if Thanasis could read. He had assumed it when, early that morning, he had stolen a piece of parchment, a pot of ink, and a quill from his father's office before his father took them on their political traipse around the polis. Their course brought them close enough to their new home to justify a stop there for a midday repast. Pavios had slipped into his room and quickly written a note, telling Thanasis to search the coal pile. He had stuffed the note into his shirt and rejoined his father at the table. He ate a biscuit quickly, but kept watch through the window on the smithy across the street.
Thanasis was apprenticed to his father, training as a blacksmith. Pavios could see both father and son at work. Soot smudged Thanasis's face. His face was always smudged with soot, which made him appear hard and serious, until he smiled or spoke. When he worked with his father, he did neither, his heat-flushed face like the glowing metal he plunged into water, hardened and glistening.
Thanasis's father disappeared from view. Pavios excused himself from the table and stepped outside before his father could ask where he was going.
It only took a moment for their eyes to meet. Thanasis had apparently seen him return home with his father and had been watching for him to re-emerge from the house. The frown on Thanasis's face melted into an acknowledging smile. Pavios pulled the note from his shirt so Thanasis saw it. Pavios rolled up the note and placed it beneath a stone near the door to Thanasis's house. When he turned back around, Thanasis was no longer watching. His frown had returned, along with Thanasis's father. Had he seen where Pavios had hidden the note? Pavios had no way to check, as his own father stepped from the house, walking stick in hand, and bade him to come along.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Thanasis was unhappy, Pavios learned, much like he was. He did not want to be a blacksmith.
"I want to be a Lukos," Thanasis had told him the first time they met, in those wonderful days before their fathers' quarrel, when they were not restricted from seeing one another. Thanasis had shown him a secret spot just outside Akros, a broad but secluded outcropping just off the narrow switchback that led down through the mountains outside the polis walls. Although not far from Akros, they could neither see the polis's battlements nor hear the noise of its streets from the outcropping. A single emonberry tree grew near the edge of the outcropping, its low branches weighed down with its tart, white fruit. Rabbits from a nearby warren frequented the place, nibbling at the occasional green shoots and grasses growing in patches around the tree's base.
#figure(image("003_Emonberry Red/02.jpg", width: 100%), caption: [Mountain | Art by Raoul Vitale], supplement: none, numbering: none)
"A Lukos?"
"A wolf of the Akroan army," Thanasis replied. "They are the toughest warriors in all of #emph[Theros] ."
Thanasis told Pavios the epic stories of Akros. They sat next to each other, their backs against an enormous sun-warmed boulder, legs outstretched, their dusty sandals kicked off. Thanasis was animated as he told the tales, and his foot brushed against Pavios's. Pavios could not help but be swept into the powerful current of Thanasis's enthusiasm as he spoke of the Army. He allowed it to carry him, his heart borne like a floating leaf.
Pavios knew very little about his new home and the warrior culture of the Akroan people. At first, he had resented them, blaming them for the move from his home in the beautiful city of Meletis out into these isolated mountains. Leaving Meletis, he had been forced to abandon his studies at the Dekatia—there were no Thaumaturges in Akros with whom he could continue his magic tutelage and magic was one of the few things Pavios enjoyed. It promised a path away from his father's ambitions for him. In Akros, his father's oppressive expectations and command over his life were inescapable. It was all the fault of these rude and aggressive Akroans.
However, Pavios could not stoke that resentment for long after meeting Thanasis. Pavios never heard Thanasis speak against anyone harshly, not even his own father, who stood athwart his hopes of training as a warrior at the great Kolophon, the unbreachable stone heart of the Akroan polis. Instead, Thanasis had been pressed into apprenticeship to his father. He seemed to bear this disappointment well, far better than Pavios felt he could. Thanasis seemed built to endure anything, tall and tanned, his shoulders broad and solid, like the quadrant arches that strengthened the massive walls of some of the magnificent stone buildings in Meletis. He kept his black hair cropped short in the way of new recruits in the Army. Thanasis would make a great warrior, he was certain.
During the first two months they had known one another, they met as often as possible on the outcropping. Pavios began to share some of his own stories, and entertained Thanasis with riddles and simple cantrips he'd learned during his time at the Dekatia. He was slow to open up with more personal stories, though, and did not share his betrothal to the girl in Meletis.
The days grew shorter and the air cooler in the mountains, but still the two met to tell each other stories. On one particularly chill day, Pavios, in his haste to escape his father's incessant planning of what they would do once they were back in Meletis and Pavios was married, left his house without his cloak. The mistake didn't occur to him until he had stepped outside the protective walls of Akros and the cold mountain breeze nipped him. Fetching his cloak would make him late to meet Thanasis and might invite questions from his father, so he continued on.
The two sat together as usual, although the great boulder was cold pressing into Pavios's back and the sun dipped often behind clouds, causing him to shiver. In the midst of telling a story about One-Eye Pass and the heroics of the Akroans who fought the cyclopes who lived there, Thanasis removed his own cloak and wrapped it around Pavios without missing a beat in the climax of his narrative. The simple cloak was lined with rabbit fur, and the leather was soft from many years of use. It carried the scent of smoke and hammered bronze, and of Thanasis himself. When Pavios pulled the cloak about him and the fur collar closed around his neck, he breathed the intimate, comforting scent of his friend.
#figure(image("003_Emonberry Red/03.jpg", width: 100%), caption: [Cyclops of One-Eyed Pass | Art by Kev Walker], supplement: none, numbering: none)
When Heliod touched the horizon, they rose to walk back to the polis. Pavios began to untie the cloak, but Thanasis placed a hand on his shoulder. "You may keep it," he said. Pavios wore the cloak every day from then on during that cold season.
Thanasis had shared painful stories as well. He stared at the ground as he told the story of his mother, and how she had died just three months before Pavios arrived in Akros. Although she was a fiercely independent artisan who traveled often to sell the pottery and jewelry she made, she always kept a reliable schedule with her family of when she would return home from her trips. One day, she did not return. Thanasis and his father searched for her until they came across her satchel in the mountains far from the road, torn and bloodstained, her craft jewelry spilling out of it. She had been taken by a beast, it was clear, although they never found her remains. Not long after, his father's reticence over Thanasis joining the Akroan army hardened into unwavering prohibition.
When Thanasis finished the story, he looked up. His eyes were rimmed with red. There were no tears in them, but a resilience that struggled to hold in a swollen tide of sadness and loss. Pavios saw something else there, too, he thought: a reaching out from aloneness, and a growing love for his friend. Or, was he seeing merely a reflection of himself? No, it was there, he was certain.
Pavios pulled him close, embracing him, and kissed his cheek. Thanasis tightened suddenly, as if surprised by Pavios's forwardness, his shoulders setting like a wall between them. He did not embrace Pavios in return. The moment ended abruptly and Pavios released him. They put on their sandals and walked the switchback home to Akros in silence.
The following day, the disagreement between their fathers erupted and there were no more meetings on the outcropping. Then, three days before Pavios left the note for Thanasis, Pavios's father announced he would leave for Meletis at the end of the week in order to prepare for his son's upcoming wedding.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Pavios drifted into sleep, but awoke when something tapped him on his forehead. He brushed a hand across his face and found a pebble in his hair. He sat up and rolled it between his fingers in the dark. As he considered getting up to light a candle and examine it, another pebble landed on his head. He heard a whisper. It sounded like his name.
"Pavios." It came from above him. Pavios stood on the bed and was still, listening.
"Pavios, it's me, Thanasis."
The sound was coming from the wall, but it sounded as if Thanasis was in the room with him. Pavios ran his hand along the wall and discovered a small crack. He peered into the crack but could see nothing in the darkness. He leaned in close. "Thanasis?"
"Pavios!" Thanasis's voice rose. "You sleep like you are dead."
Pavios's heard pounded. "I'm so happy to hear your voice," he said. In that moment just how much he had missed his friend overwhelmed him. "I'm so happy to hear your voice," he repeated, loudly, feeling suddenly foolish.
"Shhh! You'll wake our fathers."
"My father won't let me see you. He drags me all over the polis every day now while he works."
"Mine will also not let me see you," Thanasis replied. There was a long pause. "Pavios?"
"Yes," Pavios answered quietly. "I am here."
"I want to see you."
Pavios felt that if he opened his mouth to speak, he would not be able to keep himself from shouting with excitement. Or worse, he might awaken and this would be nothing more than a dream. He wanted to respond, "Yes! I want to see you, too!" and pound the wall between them until it fell into rubble, but he could not seem to even exhale at the moment, much less lift his arms to such a task.
#figure(image("003_Emonberry Red/04.jpg", width: 100%), caption: [Fated Infatuation | Art by <NAME>], supplement: none, numbering: none)
"Can we meet again?" Thanasis's voice was quieter.
Pavios found his breath and leaned against the wall. "I wasn't sure—" he started, hesitating, "—after the last time. I mean—" he stammered. "Yes," he said, finally.
"Can you meet tomorrow at midday?"
"I will find a way."
"I will wait for you," Thanasis said. "Goodnight, Pavios."
"Goodnight, Thanasis." Pavios crawled back beneath his covers.
"And thank you for the gift, Pavios."
Pavios smiled and could not wait to fall asleep. He pulled the rabbit fur cloak that lay spread across his bed up to his chin, breathed deeply, and drifted into sleep.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[The snarl of thread was proving difficult. Adrasteia massaged it between her soft and wrinkled fingers, teasing at it with a hook in an attempt to separate the threads. Perhaps one could be saved to continue its winding journey? Alas, the clever technique her sister had employed in weaving these two together bound their destinies so closely that attempts to end just one was unwise. One was the warp, the other the weft, and one without the other could weaken the tapestry, leaving it prone to irreparable tears. Although she and her sisters controlled many things in the destinies of all in ] Theros#emph[ —even at times the gods themselves—there were rules that should not be bent, and a few that must never, ever be broken.]
#figure(image("003_Emonberry Red/05.jpg", width: 100%), caption: [Fate Unraveler | Art by <NAME>], supplement: none, numbering: none)
#emph[From beneath the table she withdrew a roughly hewn, darkly stained box made from the ancient, knotty wood of a tree that never grew in the world. The box's silver hinges made no sound as she opened it. Velvet the color of ripened plums lined the interior, and three implements lay neatly at the bottom: a sliver thimble; a long, delicate bone bodkin; and a pair of crooked ebony shears. Adrasteia took the shears and replaced the box beneath the table.]
#emph[The shears were as black as an empty night sky, reflecting none of the amber candlelight or the ubiquitous realm of Nyx. The blades began at their handles, straight and sharp, sliding together precisely, but as they closed each became noticeably misaligned, bending slightly and then impossibly into and then past the other until the scissoring ceased. The shears could never be fully closed. Purphoros had offered to forge her a new set long ago, an offer she and her sisters had cackled continuously over for a good thirty-three years afterward.]
#emph[Adrasteia returned to the snarl of the threads. One can view too critically the state of individual threads, she thought, to the exclusion of the artistic value of what mortals or gods would call flaws. A flaw implies judgment, which requires criteria based around a set of exclusions, and these are expected to remain consistent from one moment to the next. Such things are illusions in this room. Fate has no flaws, nor an enduring aesthetic. The only true beauty is a dispassionate completeness.]
#emph[Still, in fleeting moments, Adrasteia experienced beauty in the threads, knew appreciation, and, at times, felt admiration. But those moments passed, and the work always remained, awaiting completion.]
#emph[There. She tied off the snarl from the back. It was ready. Adrasteia pinched it between her thumb and forefinger, each calloused and hardened from an eternity of pinpricks and the abrading slide of endless threads. She opened her crooked shears wide and positioned the vertex of the blades at the throat of the snarl.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Pavios arrived at the outcropping first. Clouds overcast the sky and it was quite cold. Beneath the cloak, slung across his back, he carried a pack with food, clothing, his knife, the training manual the master Thaumaturge had given him when he had left the Dekatia in Meletis, flint and steel, and various other items necessary to a long trip. Upon awakening early in the morning, before his father, he had made a decision. He would not return to Meletis. The thought of leaving Thanasis and marrying another knotted his stomach, causing a panic to seize him. He didn't know where they'd go, but if Thanasis accepted, they would figure it out.
He hoped Thanasis would bring the gift Pavios had given him, the very short sword given to him in Meletis to finalize the marriage arrangement. If he and Thanasis were destined to be together, the sword would be essential in their fate.
If Thanasis refused, Pavios resolved that he would go on alone. Perhaps he would die; to live without Thanasis would be a life he could not bear. The thought made him nervous. Thanasis could refuse—was he being too presumptuous once again, just as he had that day when last they were together here? He began to sweat. He removed the cloak and his pack, and set the two on the ground. The cold hit him, and he sipped from his wineskin to warm himself.
Pavios heard a growl, deeper and more terrifying than any he had heard from any animal he had ever encountered. Across the broad outcropping and a short way down the switchback he saw a blur of motion. A beast with a thick fleece mane the color of snow tore into a rabbit. Pavios did not move, but watched as the rabbit was killed, torn apart, and consumed in a few quick bites. Blood and fur dripped from the killer's jaws.
#figure(image("003_Emonberry Red/06.jpg", width: 100%), caption: [Fleecemane Lion | Art by <NAME>], supplement: none, numbering: none)
It looked up, sniffed the air, and then saw Pavios.
Panicked, Pavios bolted in the opposite direction, passing the emonberry tree and scrambling down the narrow switchback. In all the times he had come here with Thanasis, he had never explored beyond the outcropping and the path they followed to reach it. He did not know where the switchback led beyond their meeting spot, but he had no time to ponder it.
He did not look back. The switchback became narrower and more treacherous, and he couldn't risk losing his footing. And if the beast was behind him, if it was about to spring and take him down, he did not want to know. Better that it happen quickly, as it had for the rabbit.
Pavios reached the bottom of the gorge, but still did not stop or look back. Ahead, he saw a small opening in the rock wall, a small cave. He reached it and clambered inside. He tried to quiet his breathing, tried not to gasp and give away his hiding place.
Pavios did not know for how long or how far he had run. His panting subsided, but he shook with fear and cold. He remained still for a long time, watching for the beast. It never appeared.
A new fear gripped him then. Thanasis would be coming to meet him. He would be walking right into jaws of the beast.
Pavios climbed out of his hiding spot. The beast was nowhere to be seen. He hurried back up the switchback, but it was slow going up the steep gorge wall.
Night was falling as he approached the outcropping, but he could see that the creature had been into his pack. It had scattered his supplies. The pack lay at the end of the outcropping, torn. Blood stained it. Pavios hoped it was blood from the beast's rabbit meal.
Pavios climbed up and onto the outcropping. "Thanasis?" he called. "Are you hiding?"
He heard a ragged breath. Pavios scanned about in the failing light. There, leaning against the emonberry tree, was Thanasis. Blood drenched his tunic. In his chest was thrust the short sword Pavios had given him. Across Thanasis's lap lay the cloak he had given Pavios. It was rent and bloodied; the rabbit fur lining was shredded.
Pavios cried out and rushed to his friend. "What—what has happened?" He reached out to help him, but stopped. What could he do? Should he pull the sword free? Could Thanasis be moved? Was there time to run for help in Akros? His mind filled with crashing thoughts. He took Thanasis's head in his hands, pushed the hair out of his face. Thanasis's eyes drifted open slightly. His skin was pale and cold in Pavios's hands.
"Pavios," Thanasis mouthed the name, but no sound accompanied it. With a great effort, he drew a shallow breath and forced his voice. "I thought it killed you..." His voice trailed off.
"No," Pavios said. His eyes swam with tears. It was becoming terribly clear to him what had happened. "I'm alive. I'm safe." He took the ripped and bloodied cloak and attempted to place it around Thanasis for warmth. Bits of rabbit fur dangled from it and hairs came free, matting in the blood trickling from Thanasis's lips. Thanasis must have discovered the cloak and pack and mistaken the blood for his in a scene horribly reminiscent of his mother's death. In that moment of despair, had Thanasis taken his own life by plunging the sword into his heart?
Thanasis's weak breaths ceased. Night was upon them. Pavios could barely see his friend's face in the darkness and through his tears. He touched his forehead to Thanasis's. "Don't go," he said softly.
Pavios did not pray often. He knew the gods, but there was little time or purpose for prayer. Now, though, he called out to Erebos, the god of the dead. "<NAME>," he entreated, "I love him. Don't..." Pavios swallowed. Although he was not accustomed to praying, he was sure that when one did, it was wise to not make demands of the gods. "Please, Erebos... I cannot live without him."
#figure(image("003_Emonberry Red/07.jpg", width: 100%), caption: [Erebos, God of the Dead | Art by <NAME>], supplement: none, numbering: none)
The sword.
It was not a voice, but he heard it nonetheless.
You may be with him again, but only in my realm. Use the sword before the warmth of his life leaves his body, and I will permit you to join him.
Erebos had answered him. "Erebos," Pavios said. "I am afraid."
I will ease your passage. There will be no pain.
Pavios took hold of the hilt of the sword and slid it gently from his friend's chest. The metal was warm from Thanasis's body. He stood, turned the blade upon his own heart. He did not believe he had the strength to push it between his ribs, so he turned toward Thanasis and allowed himself to fall forward. The hilt struck the ground, and the blade drove into Pavios's heart. He felt a shock, but it was not pain. In fact, for an instant he felt happiness, and as the blade pushed its way through his body, he laughed aloud. The sensation passed quickly, though, and he closed his eyes, his head at rest in Thanasis's lap.
Beneath them, their blood seeped into the roots of the emonberry tree.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[Perhaps it was a momentary distraction as she closed the shears around the threads that caused her to misjudge the snip by a hair's breadth. The shears took the snarl, and along with it the very tip of her thumb. Adrasteia drew a quick breath through her teeth.She sucked at the wound, tasting copper, flat and heavy. Sentimental old fool, she chastised herself, let that be a lesson to you and your silly heart for why you should not be seduced into the travails of mortals.She leaned over the tapestry, squinting, and saw that a tiny drop of blood had stained it.]
#emph[Adrasteia placed her crooked shears and the snarl of thread in the box and closed the lid.]
|
|
https://github.com/Sematre/typst-letter-pro | https://raw.githubusercontent.com/Sematre/typst-letter-pro/main/src/lib.typ | typst | MIT License | // ####################
// # typst-letter-pro #
// ####################
//
// Project page:
// https://github.com/Sematre/typst-letter-pro
//
// References:
// https://de.wikipedia.org/wiki/DIN_5008
// https://www.deutschepost.de/de/b/briefvorlagen/normbrief-din-5008-vorlage.html
// https://www.deutschepost.de/content/dam/dpag/images/P_p/printmailing/downloads/automationsfaehige-briefsendungen-2023.pdf
// https://www.edv-lehrgang.de/din-5008/
// https://www.edv-lehrgang.de/anschriftfeld-im-din-5008-geschaeftsbrief/
// ##################
// # Letter formats #
// ##################
#let letter-formats = (
"DIN-5008-A": (
folding-mark-1-pos: 87mm,
folding-mark-2-pos: 87mm + 105mm,
header-size: 27mm,
),
"DIN-5008-B": (
folding-mark-1-pos: 105mm,
folding-mark-2-pos: 105mm + 105mm,
header-size: 45mm,
),
)
// ##################
// # Generic letter #
// ##################
/// This function takes your whole document as its `body` and formats it as a simple letter.
///
/// - format (string): The format of the letter, which decides the position of the folding marks and the size of the header.
/// #table(
/// columns: (1fr, 1fr, 1fr),
/// stroke: 0.5pt + gray,
///
/// text(weight: "semibold")[Format],
/// text(weight: "semibold")[Folding marks],
/// text(weight: "semibold")[Header size],
///
/// [DIN-5008-A], [87mm, 192mm], [27mm],
/// [DIN-5008-B], [105mm, 210mm], [45mm],
/// )
///
/// - header (content, none): The header that will be displayed at the top of the first page.
/// - footer (content, none): The footer that will be displayed at the bottom of the first page. It automatically grows upwords depending on its body. Make sure to leave enough space in the page margins.
///
/// - folding-marks (boolean): The folding marks that will be displayed at the left margin.
/// - hole-mark (boolean): The hole mark that will be displayed at the left margin.
///
/// - address-box (content, none): The address box that will be displayed below the header on the left.
///
/// - information-box (content, none): The information box that will be displayed below below the header on the right.
/// - reference-signs (array, none): The reference signs that will be displayed below below the the address box. The array has to be a collection of tuples with 2 content elements.
///
/// Example:
/// ```typ
/// (
/// ([Foo], [bar]),
/// ([Hello], [World]),
/// )
/// ```
///
/// - page-numbering (string, function, none): Defines the format of the page numbers.
/// #table(
/// columns: (auto, 1fr),
/// stroke: 0.5pt + gray,
///
/// text(weight: "semibold")[Type], text(weight: "semibold")[Description],
/// [string], [A numbering pattern as specified by the official documentation of the #link("https://typst.app/docs/reference/model/numbering/", text(blue)[_numbering_]) function.],
/// [function], [
/// A function that returns the page number for each page.\
/// Parameters:
/// - current-page (integer)
/// - page-count (integer)
/// Return type: _content_
/// ],
/// [none], [Disable page numbering.],
/// )
///
/// - margin (dictionary): The margin of the letter.
///
/// The dictionary can contain the following fields: _left_, _right_, _top_, _bottom_.\
/// Missing fields will be set to the default.
/// Note: There is no _rest_ field.
///
/// - body (content, none): The content of the letter
/// -> content
#let letter-generic(
format: "DIN-5008-B",
header: none,
footer: none,
folding-marks: true,
hole-mark: true,
address-box: none,
information-box: none,
reference-signs: none,
page-numbering: (current-page, page-count) => {
"Page " + str(current-page) + " of " + str(page-count)
},
margin: (
left: 25mm,
right: 20mm,
top: 20mm,
bottom: 20mm,
),
body,
) = {
if not letter-formats.keys().contains(format) {
panic("Invalid letter format! Options: " + letter-formats.keys().join(", "))
}
margin = (
left: margin.at("left", default: 25mm),
right: margin.at("right", default: 20mm),
top: margin.at("top", default: 20mm),
bottom: margin.at("bottom", default: 20mm),
)
set page(
paper: "a4",
flipped: false,
margin: margin,
background: {
if folding-marks {
// folding mark 1
place(top + left, dx: 5mm, dy: letter-formats.at(format).folding-mark-1-pos, line(
length: 2.5mm,
stroke: 0.25pt + black
))
// folding mark 2
place(top + left, dx: 5mm, dy: letter-formats.at(format).folding-mark-2-pos, line(
length: 2.5mm,
stroke: 0.25pt + black
))
}
if hole-mark {
// hole mark
place(left + top, dx: 5mm, dy: 148.5mm, line(
length: 4mm,
stroke: 0.25pt + black
))
}
},
footer-descent: 0%,
footer: context {
show: pad.with(top: 12pt, bottom: 12pt)
let current-page = here().page()
let page-count = counter(page).final().first()
grid(
columns: 1fr,
rows: (0.65em, 1fr),
row-gutter: 12pt,
if page-count > 1 {
if type(page-numbering) == str {
align(right, numbering(page-numbering, current-page, page-count))
} else if type(page-numbering) == function {
align(right, page-numbering(current-page, page-count))
} else if page-numbering != none {
panic("Unsupported option type!")
}
},
if current-page == 1 {
footer
}
)
},
)
// Reverse the margin for the header, the address box and the information box
pad(top: -margin.top, left: -margin.left, right: -margin.right, {
grid(
columns: 100%,
rows: (letter-formats.at(format).header-size, 45mm),
// Header box
header,
// Address / Information box
pad(left: 20mm, right: 10mm, {
grid(
columns: (85mm, 75mm),
rows: 45mm,
column-gutter: 20mm,
// Address box
address-box,
// Information box
pad(top: 5mm, information-box)
)
}),
)
})
v(12pt)
// Reference signs
if (reference-signs != none) and (reference-signs.len() > 0) {
grid(
// Total width: 175mm
// Delimiter: 4.23mm
// Cell width: 50mm - 4.23mm = 45.77mm
columns: (45.77mm, 45.77mm, 45.77mm, 25mm),
rows: 12pt * 2,
gutter: 12pt,
..reference-signs.map(sign => {
let (key, value) = sign
text(size: 8pt, key)
linebreak()
text(size: 10pt, value)
})
)
}
// Add body.
body
}
// ####################
// # Helper functions #
// ####################
/// Creates a simple header with a name, an address and extra information.
///
/// - name (content, none): Name of the sender
/// - address (content, none): Address of the sender
/// - extra (content, none): Extra information about the sender
#let header-simple(name, address, extra: none) = {
set text(size: 10pt)
if name != none {
strong(name)
linebreak()
}
if address != none {
address
linebreak()
}
if extra != none {
extra
}
}
/// Creates a simple sender box with a name and an address.
///
/// - name (content, none): Name of the sender
/// - address (content, none): Address of the sender
#let sender-box(name: none, address) = rect(width: 85mm, height: 5mm, stroke: none, inset: 0pt, {
set text(size: 7pt)
set align(horizon)
pad(left: 5mm, underline(offset: 2pt, {
if name != none {
name
}
if (name != none) and (address != none) {
", "
}
if address != none {
address
}
}))
})
/// Creates a simple annotations box.
///
/// - content (content, none): The content
#let annotations-box(content) = {
set text(size: 7pt)
set align(bottom)
pad(left: 5mm, bottom: 2mm, content)
}
/// Creates a simple recipient box.
///
/// - content (content, none): The content
#let recipient-box(content) = {
set text(size: 10pt)
set align(top)
pad(left: 5mm, content)
}
/// Creates a simple address box with 2 fields.
///
/// The width is is determined automatically. Row heights:
/// #table(
/// columns: 3cm,
/// rows: (17.7mm, 27.3mm),
/// stroke: 0.5pt + gray,
/// align: center + horizon,
///
/// [sender\ 17.7mm],
/// [recipient\ 27.3mm],
/// )
///
/// See also: _address-tribox_
///
/// - sender (content, none): The sender box
/// - recipient (content, none): The recipient box
#let address-duobox(sender, recipient) = {
grid(
columns: 1,
rows: (17.7mm, 27.3mm),
sender,
recipient,
)
}
/// Creates a simple address box with 3 fields and optional repartitioning for a stamp.
///
/// The width is is determined automatically. Row heights:
/// #table(
/// columns: 2,
/// stroke: none,
/// align: center + horizon,
///
/// text(weight: "semibold")[Without _stamp_],
/// text(weight: "semibold")[With _stamp_],
///
/// table(
/// columns: 3cm,
/// rows: (5mm, 12.7mm, 27.3mm),
/// stroke: 0.5pt + gray,
/// align: center + horizon,
///
/// [_sender_ 5mm],
/// [_annotations_\ 12.7mm],
/// [_recipient_\ 27.3mm],
/// ),
///
/// table(
/// columns: 3cm,
/// rows: (5mm, 21.16mm, 18.84mm),
/// stroke: 0.5pt + gray,
/// align: center + horizon,
///
/// [_sender_ 5mm],
/// [_stamp_ +\ _annotations_\ 21.16mm],
/// [_recipient_\ 18.84mm],
/// )
/// )
///
/// See also: _address-duobox_
///
/// - sender (content, none): The sender box
/// - annotations (content, none): The annotations box
/// - recipient (content, none): The recipient box
/// - stamp (boolean): Enable stamp repartitioning. If enabled, the annotations box and the recipient box divider is moved 8.46mm (about 2 lines) down.
#let address-tribox(sender, annotations, recipient, stamp: false) = {
if stamp {
grid(
columns: 1,
rows: (5mm, 12.7mm + (4.23mm * 2), 27.3mm - (4.23mm * 2)),
sender,
annotations,
recipient,
)
} else {
grid(
columns: 1,
rows: (5mm, 12.7mm, 27.3mm),
sender,
annotations,
recipient,
)
}
}
// #################
// # Simple letter #
// #################
/// This function takes your whole document as its `body` and formats it as a simple letter.
///
/// The default font is set to _Source Sans Pro_ without hyphenation. The body text will be justified.
///
/// - format (string): The format of the letter, which decides the position of the folding marks and the size of the header.
/// #table(
/// columns: (1fr, 1fr, 1fr),
/// stroke: 0.5pt + gray,
///
/// text(weight: "semibold")[Format],
/// text(weight: "semibold")[Folding marks],
/// text(weight: "semibold")[Header size],
///
/// [DIN-5008-A], [87mm, 192mm], [27mm],
/// [DIN-5008-B], [105mm, 210mm], [45mm],
/// )
///
/// - header (content, none): The header that will be displayed at the top of the first page. If header is set to _none_, a default header will be generaded instead.
/// - footer (content, none): The footer that will be displayed at the bottom of the first page. It automatically grows upwords depending on its body. Make sure to leave enough space in the page margins.
///
/// - folding-marks (boolean): The folding marks that will be displayed at the left margin.
/// - hole-mark (boolean): The hole mark that will be displayed at the left margin.
///
/// - sender (dictionary): The sender that will be displayed below the header on the left.
///
/// The name and address fields must be strings (or none).
///
/// - recipient (content, none): The recipient that will be displayed below the annotations.
///
/// - stamp (boolean): This will increase the annotations box size is by two lines in order to provide more room for the postage stamp that will be displayed below the sender.
/// - annotations (content, none): The annotations box that will be displayed below the sender (or the stamp if enabled).
///
/// - information-box (content, none): The information box that will be displayed below below the header on the right.
/// - reference-signs (array, none): The reference signs that will be displayed below below the the address box. The array has to be a collection of tuples with 2 content elements.
///
/// Example:
/// ```typ
/// (
/// ([Foo], [bar]),
/// ([Hello], [World]),
/// )
/// ```
///
/// - date (content, none): The date that will be displayed on the right below the subject.
/// - subject (string, none): The subject line and the document title.
///
/// - page-numbering (string, function, none): Defines the format of the page numbers.
/// #table(
/// columns: (auto, 1fr),
/// stroke: 0.5pt + gray,
///
/// text(weight: "semibold")[Type], text(weight: "semibold")[Description],
/// [string], [A numbering pattern as specified by the official documentation of the #link("https://typst.app/docs/reference/meta/numbering/", text(blue)[_numbering_]) function.],
/// [function], [
/// A function that returns the page number for each page.\
/// Parameters:
/// - current-page (integer)
/// - page-count (integer)
/// Return type: _content_
/// ],
/// [none], [Disable page numbering.],
/// )
///
/// - margin (dictionary): The margin of the letter.
///
/// The dictionary can contain the following fields: _left_, _right_, _top_, _bottom_.\
/// Missing fields will be set to the default.
/// Note: There is no _rest_ field.
///
/// - font (string, array): Font used throughout the letter.
///
/// Keep in mind that some fonts may not be ideal for automated letter processing software
/// and #link("https://en.wikipedia.org/wiki/Optical_character_recognition", text(blue)[OCR]) may fail.
///
/// - body (content, none): The content of the letter
/// -> content
#let letter-simple(
format: "DIN-5008-B",
header: none,
footer: none,
folding-marks: true,
hole-mark: true,
sender: (
name: none,
address: none,
extra: none,
),
recipient: none,
stamp: false,
annotations: none,
information-box: none,
reference-signs: none,
date: none,
subject: none,
page-numbering: (current-page, page-count) => {
"Page " + str(current-page) + " of " + str(page-count)
},
margin: (
left: 25mm,
right: 20mm,
top: 20mm,
bottom: 20mm,
),
font: "Source Sans Pro",
body,
) = {
margin = (
left: margin.at("left", default: 25mm),
right: margin.at("right", default: 20mm),
top: margin.at("top", default: 20mm),
bottom: margin.at("bottom", default: 20mm),
)
// Configure page and text properties.
set document(
title: subject,
author: sender.name,
)
set text(font: font, hyphenate: false)
// Create a simple header if there is none
if header == none {
header = pad(
left: margin.left,
right: margin.right,
top: margin.top,
bottom: 5mm,
align(bottom + right, header-simple(
sender.name,
if sender.address != none {
sender.address.split(", ").join(linebreak())
} else {
"lul?"
},
extra: sender.at("extra", default: none),
))
)
}
let sender-box = sender-box(name: sender.name, sender.address)
let annotations-box = annotations-box(annotations)
let recipient-box = recipient-box(recipient)
let address-box = address-tribox(sender-box, annotations-box, recipient-box, stamp: stamp)
if annotations == none and stamp == false {
address-box = address-duobox(align(bottom, pad(bottom: 0.65em, sender-box)), recipient-box)
}
letter-generic(
format: format,
header: header,
footer: footer,
folding-marks: folding-marks,
hole-mark: hole-mark,
address-box: address-box,
information-box: information-box,
reference-signs: reference-signs,
page-numbering: page-numbering,
{
// Add the date line, if any.
if date != none {
align(right, date)
v(0.65em)
}
// Add the subject line, if any.
if subject != none {
pad(right: 10%, strong(subject))
v(0.65em)
}
set par(justify: true)
body
},
margin: margin,
)
}
|
https://github.com/HiiGHoVuTi/requin | https://raw.githubusercontent.com/HiiGHoVuTi/requin/main/log/sat-types.typ | typst |
#import "../lib.typ": *
#show heading: heading_fct
=== SAT -- des preuves !
Soit $k in NN$. On appelle _type fini borné par $k$_ un élément de $"Fin"_k := frak(P)[|1, k|]$.
Dans cette partie, tous les types seront finis bornés par $k$.
#question(0)[Mettre en bijection les valuations des formules à $k$ variables et $[|1, 2^k|]$.]
On identifie maintenant les entiers aux valuations.
#question(1)[Soit $a in T in "Fin"_k$. Donner une formule propositionnelle satisfaite par $b in T$ si et seulement si $a = b$.]
#question(0)[Soit $P : [|1, k|] -> 2$ un prédicat sur les types. Montrer que $P^(-1) (top) in "Fin"_k$.]
#question(1)[Soit $Y in "Fin"_k$. Donner une formule propositionnelle satisfaite par $a in T$ si et seulement si $a in Y$.]
Soit $T in "Fin"_k$ puis $P$ un prédicat sur $T$.
#question(1)[En déduire un algorithme déterminant la véracité de $forall x in T, P(x)$.]
=== Typer c'est prouver
On s'intéresse à un langage de programmation autorisant l'assignation et l'appel à des fonctions.
Une _fonction_ est un identifiant unique muni d'un $n+1$-uplet de $"Fin"_k$ : les $n$ premières valeurs sont les types des arguments et la dernière est
Un _programme_ est donc une liste d'éléments de la forme $x_(n+1) := overline(f)(x_1...x_n)$ avec $overline(f)$ un arbre étiqueté par des fonctions et dont les feuilles sont dans ${x_1...x_n}$.
#question(1)[Quel doit être le type de $x_n$ ?]
On propose d'utiliser la concaténation des valuations de $x_1...x_n$ comme valuation associée à $x_1...x_n$.
#question(1)[Donner une formule propositionnelle satisfaite par $x_1 ... x_n$ si et seulement si $f (x_1 ... x_n)$ est bien typé.]
#question(1)[En déduire une formule propositionnelle satisfaite par $x_1 ... x_n$ si et seulement si un programme est bien typé.]
Une _déclaration de fonction_ est la donnée d'un type souhaité $T$ et $overline(f)(x_1 ... x_n)$ un arbre.
#question(2)[Proposer une extension du langage permettant de définir ses propres fonctions.]
On souhaite désormais se munir de polymorphisme. On autorise désormais les fonctions à quantifier universellement sur des types. Ainsi $f$ est un $n+1$-uplet de $"Fin"_k union.sq {alpha_1 ... alpha_q}$.
#question(2)[Donner une formule vraie si et seulement si la déclaration d'une fonction $f$ est bien typée.]
=== Et c'est pas fini...
Mais _quid_ des types infinis ?
Soit $G = (T, S)$ un graphe orienté. On supposera $NN in T$ par exemple.
#question(1)[Donner une formule propositionnelle satisfaite par une valuation $nu$ sur $T$ si et seulement si $G[nu^(-1) (top)]$ est acyclique.]
#question(1)[Proposer un graphe sur $"Fin"_k$ dont la formule associée est satisfaite par les ensembles de types compatibles.]
Un _type raffiné par un prédicat_ est un type $T$ muni d'un prédicat $p : T -> 2$. On notera \ ${t in T | p(t)}$ ce type résultant.
On impose de plus une condition sur les prédicats : si $T$ est raffiné par un ensemble de prédicats, on peut calculer si le type résultant est vide.
#question(1)[Donner l'ensemble des sommets accessibles depuis ${3}$. Est-il raisonnable de réaliser $G$ en mémoire ?]
#question(1)[Peut-on systématiquement typer $x := f(y)$ où $f : Y -> X$ comme \ $x in {z in X | f(y) = z}$ ?]
On suppose disposer d'un ensemble raisonnable de raffinements de la forme $f(x)=y$ avec $f$ une fonction pré-existante, on ignorera le reste des informations calculées.
#question(2)[Reprendre l'algorithme de la partie précédente avec les types infinis, le polymorphisme et les types raffinés.]
=== Réalisation efficace
// ptdr info C
|
|
https://github.com/qujihan/typst-book-template | https://raw.githubusercontent.com/qujihan/typst-book-template/main/README_zh.md | markdown | <div align="center">
<strong>
<samp>
[English](./README.md)
</samp>
</strong>
</div>
# 一个Typst书籍模板
> [!IMPORTANT]
> 需要提前安装:
> 1. [typst](https://github.com/typst/typst): *0.12.0* 或者更高版本
> 2. [typstyle](https://github.com/Enter-tainer/typstyle)
> 3. [字体](./fonts.json)
> - 中文字体: [Source Han Serif SC](https://github.com/adobe-fonts/source-han-serif)
> - 西文字体: [Lora](https://github.com/cyrealtype/Lora-Cyrillic)
> - 代码字体: [CaskaydiaCove Nerd Font](https://github.com/ryanoasis/nerd-fonts/releases/download/v3.2.1/CascadiaCode.zip)
> - 如果想一键安装, 可以运行 fonts 下的 download.py (`python typst-book-template/fonts/download.py`)
> - 中国大陆地区可是使用 `python typst-book-template/fonts/download.py --proxy` 提高下载速度
# Quick Start
> [!Tip]
> 默认从 typst-book-template 的父目录的 main.typ 作为项目入口开始编译, 输出结果为 output_file.pdf
>
> 如果想要修改可以参照 typst-book-template/metadata.json, 在项目根目录下(与typst-book-template同级)创建 metadata.json
metadata.json
// output_file_name 需要以.pdf或者.svg结尾
```json
{
"root_file_name": "main.typ",
"output_file_name": "typst-book-template-demo.pdf"
}
```
main.typ
```typ
#import "typst-book-template/book.typ": *
#show: book.with(info: (
name: "author",
title: "typst-book-template demo",
))
#include "src/chapter1.typ"
```
src/chapter1.typ
```typ
#import "../typst-book-template/book.typ": *
// `path-prefix`如何使用, 可以参考 expample下的例子
#let path-prefix = figure-root-path + "src/pics/"
= chapter 1
== section 1
```
```shell
# 将本项目作为 git submodule
git init
git submodule add https://github.com/qujihan/typst-book-template.git typst-book-template
git submodule update --init --recursive
# 推荐按照 tqdm
# pip install tqdm
python typst-book-template/fonts/download.py
# 实时预览
python typst-book-template/op.py w
# 编译
python typst-book-template/op.py c
# 格式化typst代码
python typst-book-template/op.py f
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.