repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/chendaohan/bevy_tutorials_typ | https://raw.githubusercontent.com/chendaohan/bevy_tutorials_typ/main/30_bloom/bloom.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. 辉光
“Bloom”效果会在亮光周围产生光晕。虽然这不是一种物理上准确的效果,但它受到了通过脏或不完美镜头看光线的启发。
Bloom在帮助感知非常亮的光线方面表现出色,尤其是在显示硬件不支持HDR输出时。你的显示器只能显示一定的最大亮度,因此Bloom是一种常见的艺术选择,用于传达比显示器能显示的亮度更高的光强。
Bloom在使用去饱和非常亮颜色的色调映射算法时效果最佳。Bevy的默认设置是一个不错的选择。
Bloom需要在你的相机上启用HDR模式。添加BloomSettings组件到相机以启用Bloom并配置效果。
```rust
commands.spawn((
Camera3dBundle {
camera: Camera {
hdr: true,
..default()
},
..default()
},
BloomSettings::NATURAL,
));
```
= 2. Bloom设置
Bevy提供了许多参数来调整Bloom效果的外观。
默认模式是“节能模式”,更接近真实光物理的行为。它试图模仿光散射的效果,而不人为地增加图像亮度。效果更加微妙和“自然”。
还有一种“加法模式”,它会使所有东西变亮,让人感觉亮光在“发光”不自然。这种效果在许多游戏中很常见,尤其是2000年代的老游戏。
Bevy提供了三种Bloom“预设”:
- NATURAL:节能模式,微妙,自然的外观。
- OLD_SCHOOL:“发光”效果,类似于老游戏的外观。
- SCREEN_BLUR:非常强烈的Bloom,使所有东西看起来模糊。
你也可以通过调整BloomSettings中的所有参数来创建完全自定义的配置。使用预设作为灵感。
以下是Bevy预设的设置:
```rs
fn toggle_bloom_presets(
mut bloom_settings: Query<&mut BloomSettings>,
keys: Res<ButtonInput<KeyCode>>,
) {
let Ok(mut bloom_settings) = bloom_settings.get_single_mut() else {
return;
};
if keys.just_pressed(KeyCode::Digit1) {
*bloom_settings = BloomSettings::NATURAL;
} else if keys.just_pressed(KeyCode::Digit2) {
*bloom_settings = BloomSettings::OLD_SCHOOL;
} else if keys.just_pressed(KeyCode::Digit3) {
*bloom_settings = BloomSettings::SCREEN_BLUR;
}
}
``` |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/CHANGELOG.md | markdown | Other | # Revision history for typst-hs
## 0.6
* Recognize figure.caption function (#52).
* Allow defined identifiers to override math defaults (#51).
Previously we evaluated all math in a special environment that
shadowed any user-defined functions with the same-named functions
from the math or sym modules. This change gives user-defined identifiers
priority over the math defaults, allowing things like `bb` to be
overridden.
* Typst.Types: EvalState now has two new fields, `evalMathIdentifiers` and
`evalStandardIdentifiers`. `evalIdentifiers` is now just for user-defined
identifiers. [API change]
* Don't implicitly load sys module for math.
## 0.5.0.5
* Allow numbers like `1.` in math mode (#50).
## 0.5.0.4
* Add built-in identifiers for standard types (#21):
array, bool, content, int, float, regex, length,
alignment, color, symbol, string.
* Adjust emphasis parser for CJK characters (#49).
Typst documentation says that `*` strong emphasis
"only works at word boundaries." However, in typst/typst#2648
this was changed for CJK.
## 0.5.0.3
* Support grid.(cell,header,footer,hline,vline) (#44).
* Support table.(cell,vline,hline,header,footer) (#44).
* Allow space after equation in code (#43).
* Treat unicode whitespace characters as whitespace (#43).
* Allow raw (backticked) content as code expression (#43).
* Allow colon in label (#43).
* Allow line comments at end of file (#43).
* Depend on typst-symbols 0.1.6.
* Add Haddock docs to parts of the public API (<NAME>,
<NAME>).
* Avoid backtracking in `pDictExpr` (<NAME>).
* Allow colon in dict literal (<NAME>) (#43, #45).
## 0.5.0.2
* Fix parsing of field access in math (#41). `$plus.circle_2$`
should give you a subscript 2 on the symbol `plus.circle`.
Underscores are not allowed in field access in math.
* Support toml-parser-2.0.0.0 (<NAME>).
## 0.5.0.1
* Set `evalPackageRoot` to working dir to start, even if the file to be
converted is somewhere else. This seems to be what the test suite expects.
* Make file loading relative to package root if present (#39).
* Parser: remove `pBindExpr` from `pBaseExpr`. It does not seem
to be necessary, and it causes problems with things like `$#x = $y$` (#34).
* Fix assignment of module name in package imports (#30).
* Don't allow `container.at` to insert new values (#26).
* Handle `dict.at(variable) = expression` (#25).
* Remove dependency on the unmaintained digits library (#24).
We just copy the code for the function we need (with
attribution): it is BSD3-licensed.
## 0.5
* Support "as" keyword in imports (#21).
[API change] In Typst.Syntax, the Imports type now contains
fields for an optional "as" identifier.
* Support version type (#21).
[API change] Add VVersion constructor to Val, TVersion to ValType.
Support the `version` constructor function and the `at` method (#21).
* Parser: Ensure that `set` rule doesn't pick up `if` on next line (#23).
* Parser: Allow multiline strings (#20).
* Allow function applications in dictionary key construction (#19).
[API change]: in Typst.Syntax, the Dict constructor for Expr
now takes type `[Spreadable (Expr, Expr)]` instead of
`[Spreadable (Identifier, Expr)]`. This is because the key
identifiers sometimes are not known at parse time and must
be computed in Evaluate.
## 0.4
* `evaluateTypst` now returns a single Content instead of a sequence
(breaking API change). The Content is a "document" element that wraps
the other contents. (This is added automatically in typst:
https://typst.app/docs/reference/model/document/#parameters-title.)
* Improve math parser.
* Add `sys` module and `sys.version`.
* Math: add `sech` and `csch` operators, `math.mid`.
* `math.op` is no longer limited to string argument.
* Remove automatic matching for `|..|` in math (typst 0.8 breaking change).
* Fix `in` so it works with a type.
* `repr` label with angle brackets.
* `cite` now just takes one positional element, a label
instead of strings (typst 0.9 breaing change).
* Add `quote` element.
* Add first-class types. `type()` function now returns a
ValType instead of a string. Allow ValTypes to == strings
for compatibility, as in typst.
* `highlight` element for text.
* Allow array `zip` method to take any number of arguments.
* Add `calc.tau`.
* Add array `intersperse` method.
* Add string `rev` method.
* Fix search path for typst packages, from
`cache/typst/packages/preview/packagename-major.minor.patch` to
`cache/typst/packages/preview/packagename-major/minor.patch` (#18).
* Add support of 'wide' spacing character.
* Fix precedence for numerical attachments (#17).
Typst makes a subtle distinction between `$a_1(x)$`, in which
the `_` groups more tightly than the `(..)`, and $`a_f(x)$`,
in which the `(..)` groups more tightly than the `_`.
This patch implements the distinction. This fixes conversion of,
e.g., `$n(a)^(b)$`.
* Use typst-symbols 0.1.5.
## 0.3.2.1
* Fix resolution of symbols (#15). Symbols like `dot`, which only have
variants, were not being properly resolved: we were getting the
last matching variant rather than the first.
* Avoid text's `readFile` in cli app (#13). Instead read as bytestring and
force interpretation as UTF-8.
* Fix some parser edge cases involving emphasis after `'` (#12).
## 0.3.2.0
* Add metadata element.
* Add dedup method for vector.
* Add math.class
* Make MAttach on symbols include limits if symbol is relation.
This is a 0.7 change: "Changed relations to show attachments as limits
by default (e.g. in $a ->^x b$)."
* Add Typst.MathClass.
* Add im, id, tr text operators.
* Parse math symbol shorthands as identifiers.
* Use typst-symbols 0.1.4 so we get all of the defined shorthands.
* Fix tests because of breaking symbol change ident -> equiv.
* Depend on dev texmath.
## 0.3.1.0
* Allow multiplying a ratio by a length.
* Use `symModule` and `mathModule` directly when evaluating
Equation instead of looking up `sym` and `math`.
* Fix parsing of escapes in string literals. Symbols in general
can't be escaped. There is just a small list of valid escapes.
* Fix bugs in converting typst regexes to TDFA's format.
* Allow Symbol to be regex replacement text.
* Allow VString and VSymbol to be +'d.
* Update for toml-parser-1.2.0.0 API changes (#9, <NAME>).
* Derive the decoder for typst.toml (#7, <NAME>)
* Implement typst's `toml()` function (#8, <NAME>ens).
## 0.3.0.0
* We now target typst 0.6.
* `joinVals` - fall back on repr when as a fallback in joining values.
* Fix a spacing issue in parsing code inside equations (#6).
* Fix `#include`. It wasn't including content!
* Fix issue with math parsing of factorial (#5).
* Handle "style" by evaluating it immediately, rather than passing it through
as an element in content (#4).
* Add `outline.entry`.
* Allow identifiers to start with `_`.
* Fix bug in parsing consecutive '#' expressions in math function (#2).
* Fix bugs in makeLiteralRE.
* Give namedArg an argument for a default value.
This avoids spurious parse error messages.
* Change return value of dictionary insert method to none.
* Improve #panic output.
* [API change]: Add Spreadable type in Typst.Syntax.
Use this for Dict and Array values.
* Handle package lookup, assuming packages are either local or cached.
* API change: combine IO operations into Operations structure.
`evaluateTypst` now takes a single Operations dictionary instead
of separate `loadBytes` and `currentUTCTime` functions. And
Operations now also includes functions to query environment
variables and check directories. This will be needed for
package lookup.
* Depend on typst-symbols 0.1.2.
* Make factorial take priority over fraction.
## 0.2.0.0
* We now target typst 0.5.
* Implement methods for datetime.
* Implement `base` parameter on str.
* Add `datetime` constructor.
* Implement `datetime.today`.
* Add VDateTime type.
* Implement `fields` method on content.
* Add `display`, `inline`, `script`, `sscript` to math module.
* Add `str.to-unicode`, `str.from-unicode`.
* Add `calc.ln` and `calc.exp`.
* Remove deprecated `calc.mod`.
* Depend on typst-symbols 0.1.1.
## 0.1.0.0
* First version. Released on an unsuspecting world.
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/mathtools/index.typ | typst |
#import "create-fractions-from-ratios.typ": create-fractions-from-ratios
|
|
https://github.com/Shuenhoy/modern-zju-thesis | https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/pages/undergraduate-eval.typ | typst | MIT License | #import "../utils/fonts.typ": 字号, 字体
#import "../utils/datetime-display.typ": datetime-display
#import "./template-individual.typ": template-individual
#import "../utils/twoside.typ": *
#let undergraduate-eval(scores: none, comment) = {
template-individual("本科生毕业论文(设计)考核", outlined: true)[
#set text(size: 字号.小四)
#strong[一、指导教师对毕业论文(设计)的评语:<mzt:no-header-footer>]
#comment
#v(0.8fr)
#strong(
align(right)[
指导教师(签名)#box(width: 5em, stroke: (bottom: 0.5pt))\
年#h(2em)月#h(2em)日
],
)
#v(1em)
#strong[#h(-2em)二、答辩小组对毕业论文(设计)的答辩评语及总评成绩:]
#v(1fr)
#strong[#table(
columns: 6,
align: center,
[成绩比例],
[文献综述#linebreak() (10%)],
[开题报告#linebreak()(15%)],
[外文翻译#linebreak()(5%)],
[毕业论文质量及答辩#linebreak()(70%)],
[总评成绩],
[分值], ..(
if scores == none {
()
} else {
(
[#scores.at(0)],
[#scores.at(1)],
[#scores.at(2)],
[#scores.at(3)],
[#scores.sum()],
)
}
)
)
#align(right)[
负责人(签名)#box(width: 5em, stroke: (bottom: 0.5pt))\
年#h(2em)月#h(2em)日
]]
]
twoside-emptypage
} |
https://github.com/saecki/zig-grep | https://raw.githubusercontent.com/saecki/zig-grep/main/paper/template.typ | typst | #import "@preview/codelst:1.0.0": sourcecode, code-frame
#let project(title: str, author: str, body) = {
// Set the document's basic properties.
set document(author: author, title: title)
set page(
paper: "a4",
margin: (x: 2.5cm, y: 2.5cm),
numbering: "1",
number-align: center,
)
set text(
font: "Linux Libertine",
lang: "en",
)
set heading(numbering: "1.")
// superscript citations
// show cite.where(supplement: none, form: "normal"): c => {
// super(cite(form: "prose", c.key))
// }
// Prettier raw text
show raw.where(lang: none, block: false): r => {
// -- blue highlighted --
let words = r.text.split(" ")
for (idx, word) in words.enumerate() {
let w-radius = if words.len() == 1 {
3pt
} else if idx == 0 {
(left: 3pt)
} else if idx == words.len() - 1 {
(right: 3pt)
} else {
0pt
}
box(
fill: rgb("#f4f6fa"),
outset: (y: 3pt),
inset: (x: 2pt),
radius: w-radius,
text(fill: rgb("#4050d0"), word),
)
}
// -- bold --
// text(weight: "bold", r.text)
// -- quoted --
// quote(r.text)
}
body
}
#let output(content) = {
sourcecode(
numbering: none,
frame: code-frame.with(
fill: luma(240),
stroke: none,
inset: (left: 1.8em, right: .45em, y: .65em)
),
content,
)
}
|
|
https://github.com/nvarner/typst-lsp | https://raw.githubusercontent.com/nvarner/typst-lsp/master/editors/lapce/README.md | markdown | MIT License | # Typst LSP Lapce Extension
A language server for Typst.
## Features
- Limited syntax highlighting, error reporting, code completion
- Compiles to PDF on save (configurable to as-you-type, or can be disabled)
## Technical
The extension uses [Typst LSP](https://github.com/nvarner/typst-lsp) on the
backend.
|
https://github.com/Treeniks/bachelor-thesis-isabelle-vscode | https://raw.githubusercontent.com/Treeniks/bachelor-thesis-isabelle-vscode/master/chapters/04-main-refinements.typ | typst | #import "/utils/todo.typ": TODO
#import "/utils/isabelle.typ": *
= Refinements to Existing Functionality
The work presented in this thesis on #vscode can be roughly categorized into two areas: The refinement of existing features and the introduction of new ones. This chapter focuses on the former. In both categories, #jedit serves as the primary reference implementation. Whether addressing a problem or filling a gap in functionality, the aim has been to replicate the behavior of #jedit closely. While it could be argued that certain features in #jedit also warrant improvements, this thesis does not engage with those considerations.
#include "/chapters/04-main-refinements/desyncs.typ"
#include "/chapters/04-main-refinements/state-ids.typ"
#include "/chapters/04-main-refinements/state-and-output-panels.typ"
#include "/chapters/04-main-refinements/completions.typ"
// == Decoration Notification Send All Decorations
// #TODO[
// - currently only send some decorations, now send all
// ]
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.1.2/src/lib.typ | typst | Apache License 2.0 | #let version = (0,1,2)
#import "canvas.typ": canvas
#import "draw.typ"
#import "coordinate.typ"
#import "styles.typ"
// Libraries
#import "lib/axes.typ"
#import "lib/plot.typ"
#import "lib/chart.typ"
#import "lib/palette.typ"
#import "lib/angle.typ"
#import "lib/tree.typ"
#import "lib/decorations.typ"
// Utility
#import "vector.typ"
#import "matrix.typ"
#import "bezier.typ"
|
https://github.com/MDLC01/board-n-pieces | https://raw.githubusercontent.com/MDLC01/board-n-pieces/main/tests/symbols.typ | typst | MIT License | #import sys.inputs.lib as bnp
#set text(font: "Noto Sans Symbols 2")
#bnp.chess-sym.pawn.filled
#bnp.chess-sym.pawn.filled.r
#bnp.chess-sym.pawn.filled.b
#bnp.chess-sym.pawn.filled.l
#bnp.chess-sym.pawn.stroked
#bnp.chess-sym.pawn.stroked.r
#bnp.chess-sym.pawn.stroked.b
#bnp.chess-sym.pawn.stroked.l
#bnp.chess-sym.pawn.white
#bnp.chess-sym.pawn.white.r
#bnp.chess-sym.pawn.white.b
#bnp.chess-sym.pawn.white.l
#bnp.chess-sym.pawn.black
#bnp.chess-sym.pawn.black.r
#bnp.chess-sym.pawn.black.b
#bnp.chess-sym.pawn.black.l
#bnp.chess-sym.pawn.neutral
#bnp.chess-sym.pawn.neutral.r
#bnp.chess-sym.pawn.neutral.b
#bnp.chess-sym.pawn.neutral.l
#bnp.chess-sym.knight.filled
#bnp.chess-sym.knight.filled.r
#bnp.chess-sym.knight.filled.b
#bnp.chess-sym.knight.filled.l
#bnp.chess-sym.knight.stroked
#bnp.chess-sym.knight.stroked.r
#bnp.chess-sym.knight.stroked.b
#bnp.chess-sym.knight.stroked.l
#bnp.chess-sym.knight.white
#bnp.chess-sym.knight.white.r
#bnp.chess-sym.knight.white.b
#bnp.chess-sym.knight.white.l
#bnp.chess-sym.knight.black
#bnp.chess-sym.knight.black.r
#bnp.chess-sym.knight.black.b
#bnp.chess-sym.knight.black.l
#bnp.chess-sym.knight.neutral
#bnp.chess-sym.knight.neutral.r
#bnp.chess-sym.knight.neutral.b
#bnp.chess-sym.knight.neutral.l
#bnp.chess-sym.bishop.filled
#bnp.chess-sym.bishop.filled.r
#bnp.chess-sym.bishop.filled.b
#bnp.chess-sym.bishop.filled.l
#bnp.chess-sym.bishop.stroked
#bnp.chess-sym.bishop.stroked.r
#bnp.chess-sym.bishop.stroked.b
#bnp.chess-sym.bishop.stroked.l
#bnp.chess-sym.bishop.white
#bnp.chess-sym.bishop.white.r
#bnp.chess-sym.bishop.white.b
#bnp.chess-sym.bishop.white.l
#bnp.chess-sym.bishop.black
#bnp.chess-sym.bishop.black.r
#bnp.chess-sym.bishop.black.b
#bnp.chess-sym.bishop.black.l
#bnp.chess-sym.bishop.neutral
#bnp.chess-sym.bishop.neutral.r
#bnp.chess-sym.bishop.neutral.b
#bnp.chess-sym.bishop.neutral.l
#bnp.chess-sym.rook.filled
#bnp.chess-sym.rook.filled.r
#bnp.chess-sym.rook.filled.b
#bnp.chess-sym.rook.filled.l
#bnp.chess-sym.rook.stroked
#bnp.chess-sym.rook.stroked.r
#bnp.chess-sym.rook.stroked.b
#bnp.chess-sym.rook.stroked.l
#bnp.chess-sym.rook.white
#bnp.chess-sym.rook.white.r
#bnp.chess-sym.rook.white.b
#bnp.chess-sym.rook.white.l
#bnp.chess-sym.rook.black
#bnp.chess-sym.rook.black.r
#bnp.chess-sym.rook.black.b
#bnp.chess-sym.rook.black.l
#bnp.chess-sym.rook.neutral
#bnp.chess-sym.rook.neutral.r
#bnp.chess-sym.rook.neutral.b
#bnp.chess-sym.rook.neutral.l
#bnp.chess-sym.queen.filled
#bnp.chess-sym.queen.filled.r
#bnp.chess-sym.queen.filled.b
#bnp.chess-sym.queen.filled.l
#bnp.chess-sym.queen.stroked
#bnp.chess-sym.queen.stroked.r
#bnp.chess-sym.queen.stroked.b
#bnp.chess-sym.queen.stroked.l
#bnp.chess-sym.queen.white
#bnp.chess-sym.queen.white.r
#bnp.chess-sym.queen.white.b
#bnp.chess-sym.queen.white.l
#bnp.chess-sym.queen.black
#bnp.chess-sym.queen.black.r
#bnp.chess-sym.queen.black.b
#bnp.chess-sym.queen.black.l
#bnp.chess-sym.queen.neutral
#bnp.chess-sym.queen.neutral.r
#bnp.chess-sym.queen.neutral.b
#bnp.chess-sym.queen.neutral.l
#bnp.chess-sym.king.filled
#bnp.chess-sym.king.filled.r
#bnp.chess-sym.king.filled.b
#bnp.chess-sym.king.filled.l
#bnp.chess-sym.king.stroked
#bnp.chess-sym.king.stroked.r
#bnp.chess-sym.king.stroked.b
#bnp.chess-sym.king.stroked.l
#bnp.chess-sym.king.white
#bnp.chess-sym.king.white.r
#bnp.chess-sym.king.white.b
#bnp.chess-sym.king.white.l
#bnp.chess-sym.king.black
#bnp.chess-sym.king.black.r
#bnp.chess-sym.king.black.b
#bnp.chess-sym.king.black.l
#bnp.chess-sym.king.neutral
#bnp.chess-sym.king.neutral.r
#bnp.chess-sym.king.neutral.b
#bnp.chess-sym.king.neutral.l
#bnp.chess-sym.knight.filled.tr
#bnp.chess-sym.knight.filled.br
#bnp.chess-sym.knight.filled.bl
#bnp.chess-sym.knight.filled.tl
#bnp.chess-sym.knight.stroked.tr
#bnp.chess-sym.knight.stroked.br
#bnp.chess-sym.knight.stroked.bl
#bnp.chess-sym.knight.stroked.tl
#bnp.chess-sym.knight.white.tr
#bnp.chess-sym.knight.white.br
#bnp.chess-sym.knight.white.bl
#bnp.chess-sym.knight.white.tl
#bnp.chess-sym.knight.black.tr
#bnp.chess-sym.knight.black.br
#bnp.chess-sym.knight.black.bl
#bnp.chess-sym.knight.black.tl
#bnp.chess-sym.knight.neutral.tr
#bnp.chess-sym.knight.neutral.br
#bnp.chess-sym.knight.neutral.bl
#bnp.chess-sym.knight.neutral.tl
#bnp.chess-sym.knight.bishop.filled
#bnp.chess-sym.knight.bishop.stroked
#bnp.chess-sym.knight.bishop.white
#bnp.chess-sym.knight.bishop.black
#bnp.chess-sym.knight.rook.filled
#bnp.chess-sym.knight.rook.stroked
#bnp.chess-sym.knight.rook.white
#bnp.chess-sym.knight.rook.black
#bnp.chess-sym.knight.queen.filled
#bnp.chess-sym.knight.queen.stroked
#bnp.chess-sym.knight.queen.white
#bnp.chess-sym.knight.queen.black
#bnp.chess-sym.equihopper.filled
#bnp.chess-sym.equihopper.filled.rot
#bnp.chess-sym.equihopper.stroked
#bnp.chess-sym.equihopper.stroked.rot
#bnp.chess-sym.equihopper.white
#bnp.chess-sym.equihopper.white.rot
#bnp.chess-sym.equihopper.black
#bnp.chess-sym.equihopper.black.rot
#bnp.chess-sym.equihopper.neutral
#bnp.chess-sym.equihopper.neutral.rot
#bnp.chess-sym.soldier.filled
#bnp.chess-sym.soldier.stroked
#bnp.chess-sym.soldier.red
#bnp.chess-sym.soldier.black
#bnp.chess-sym.cannon.filled
#bnp.chess-sym.cannon.stroked
#bnp.chess-sym.cannon.red
#bnp.chess-sym.cannon.black
#bnp.chess-sym.chariot.filled
#bnp.chess-sym.chariot.stroked
#bnp.chess-sym.chariot.red
#bnp.chess-sym.chariot.black
#bnp.chess-sym.horse.filled
#bnp.chess-sym.horse.stroked
#bnp.chess-sym.horse.red
#bnp.chess-sym.horse.black
#bnp.chess-sym.elephant.filled
#bnp.chess-sym.elephant.stroked
#bnp.chess-sym.elephant.red
#bnp.chess-sym.elephant.black
#bnp.chess-sym.mandarin.filled
#bnp.chess-sym.mandarin.stroked
#bnp.chess-sym.mandarin.red
#bnp.chess-sym.mandarin.black
#bnp.chess-sym.general.filled
#bnp.chess-sym.general.stroked
#bnp.chess-sym.general.red
#bnp.chess-sym.general.black
|
https://github.com/drupol/ipc2023 | https://raw.githubusercontent.com/drupol/ipc2023/main/src/ipc2023/outro.typ | typst | #import "imports/preamble.typ": *
#focus-slide[
#set text(size:2em, fill: white, font: "Virgil 3 YOFF")
#set align(center + horizon)
Thanks...
#set text(size:.5em)
#uncover(2)[and reproduce this at home!]
#pdfpc.speaker-note(```md
Phewwww it's done! The stress is almost gone! It's time for questions now !
Feel also free to catch me in the venue at any moment if you'd like a demo
or simply more explanation on a specific concept, I'll be definitely glad
to share.
```)
]
|
|
https://github.com/Ngan-Ngoc-Dang-Nguyen/thesis | https://raw.githubusercontent.com/Ngan-Ngoc-Dang-Nguyen/thesis/main/README.md | markdown | A Typst implementation of https://www.latextemplates.com/template/legrand-orange-book
See the example pdf in the Release section of this project
To compile the example:
typst watch ./example/example.typ --root . --font-path fonts
This template was realized with the help of:
https://github.com/sahasatvik/typst-theorems
https://github.com/RolfBremer/in-dexter
Shield: [![CC BY-NC-SA 4.0][cc-by-nc-sa-shield]][cc-by-nc-sa]
This work is licensed under a
[Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License][cc-by-nc-sa].
[![CC BY-NC-SA 4.0][cc-by-nc-sa-image]][cc-by-nc-sa]
[cc-by-nc-sa]: http://creativecommons.org/licenses/by-nc-sa/4.0/
[cc-by-nc-sa-image]: https://licensebuttons.net/l/by-nc-sa/4.0/88x31.png
[cc-by-nc-sa-shield]: https://img.shields.io/badge/License-CC%20BY--NC--SA%204.0-lightgrey.svg
|
|
https://github.com/LDemetrios/Conspects-4sem | https://raw.githubusercontent.com/LDemetrios/Conspects-4sem/master/typst/lib/externation.typ | typst |
#let labeled-try-catch(unique-label, first, on-error) = {
locate(loc => {
let lbl = label(unique-label)
let first-time = query(locate(_ => {}).func(), loc).len() == 0
if first-time or query(lbl, loc).len() > 0 {
[#first() #lbl]
} else {
on-error()
}
})
}
#let try-catch-counter = state("try-catch-counter", 0)
#let try-catch(a, b) = {
try-catch-counter.display(cnt => {
labeled-try-catch("try-catch-lbl-" + str(cnt), a, b)
})
try-catch-counter.update(cnt => { cnt + 1 })
}
#let externation-data = state("externation-data", (
do-show-result: false,
exec-call-counter: 0,
exec-results-file: none,
reader: none,
))
#let exec(
files, /* dict<filename, string> */
commands, /* array<command : array<args>> */
displayer, /* function (result) => content */
stub: () => text(fill: blue, `Evaluation results aren't displayed`), /* function () => replacement */
) = {
externation-data.display(
data => {
let cnt = data.exec-call-counter
[
#metadata((files: files, commands: commands))#label("exec-call-" + str(cnt))
]
if data.do-show-result {
let eval-res = eval((data.reader)(data.exec-results-file))
if (eval-res.len() > cnt) {
displayer(eval-res.at(cnt))
} else {
`Not yet evaluated`
}
} else {
stub()
}
},
)
externation-data.update(it =>
(
do-show-result: it.do-show-result,
exec-call-counter: it.exec-call-counter + 1,
exec-results-file: it.exec-results-file,
reader: it.reader,
))
}
#let setup-exec(results-file, reader) = {
try-catch(() => {
let _ = reader(results-file)
externation-data.update(it =>
(
do-show-result: true,
exec-call-counter: 0,
exec-results-file: results-file,
reader: reader,
))
}, () => {
externation-data.update(it =>
(
do-show-result: false,
exec-call-counter: 0,
exec-results-file: results-file,
reader: reader,
))
})
}
#let close-exec() = {
externation-data.display(it => [
#metadata(it.exec-call-counter)#label("exec-calls-number")
])
}
#let remove-fragment-markers(rgx: regex("/\* *#ext:[a-zA-Z0-9.:\-]* *\*/"), body) = {
body.replace(rgx, "");
}
#let search-fragments(marker, begin-format: (it) => regex("/\* *#ext:begin:" + it + " *\*/"), end-format: (it) => regex("/\* *#ext:end:" + it + " *\*/"), fragment-markers-regex:regex("/\* *#ext:[a-zA-Z0-9.:\-]* *\*/"), code) = {
let begin-marker = begin-format(marker)
let end-marker = end-format(marker)
code.split(begin-marker).slice(1).map(
it => it.split(end-marker)
).filter(
it => it.len() > 1
).map(
it => it.at(0).trim(regex("[\r\n]*"))
)
}
#let do-not-render() = {
[
#metadata(true)<do-not-render>
]
}
#do-not-render()
#let colored-output(entry, out, err) = {
//let output = entry.at("output", default:())
for line in entry {
let clr = if line.color == "output" { out } else { err }
text(fill:clr, raw(line.line))
[\ ]
}
} |
|
https://github.com/bigskysoftware/hypermedia-systems-book | https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/lib/indexing.typ | typst | Other | // Based on in-dexter by <NAME>, <NAME>
#let index(..content) = locate(loc =>
[#metadata((content: content.pos(), location: loc))<jkrb_index>])
#let indexed(content) = [#index(content)#content]
#let make-index() = {
let content-to-string(content) = {
if content.has("text") {
content.text
} else {
let ct = ""
for cc in content.children {
if cc.has("text") {
ct += cc.text
}
}
ct
}
}
locate(
loc => {
let index-terms = query(<jkrb_index>, loc)
let terms-dict = (:)
for el in index-terms {
let ct = el.value.content.map(content-to-string)
let key = ct.join(", ")
if terms-dict.keys().contains(key) != true {
terms-dict.insert(key, (term: ct, locations: ()))
}
// Add the new page entry to the list.
// let ent = el.value.location.page
if (
terms-dict.at(key).locations.len() == 0 or terms-dict.at(key).locations.last().page() != el.value.location.page()
) {
terms-dict.at(key).locations.push(el.value.location)
}
}
// Sort the entries.
let sorted-keys = terms-dict.keys().sorted()
// Output.
set par(justify: false, hanging-indent: 2em)
let last-term = ("",)
for key in sorted-keys {
let entry = terms-dict.at(key)
show grid: set block(inset: 0pt, spacing: 0pt)
let term = none
if entry.term.len() > 1 {
if last-term.at(0) != entry.term.at(0) {
grid(entry.term.at(0))
v(5pt)
}
term = {
h(1em)
entry.term.slice(1).join(", ")
}
} else {
term = entry.term.at(0)
}
grid(
columns:(1fr, auto),
term,
box(
entry.locations.map(location =>
link(location.position(),
text(
number-width: "tabular",
str(counter(page).at(location).last())
)
)
).join(", "),
)
)
v(5pt)
(last-term = entry.term)
}
},
)
}
|
https://github.com/Toniolo-Marco/git-for-dummies | https://raw.githubusercontent.com/Toniolo-Marco/git-for-dummies/main/slides/theory/remote-repo.typ | typst | #import "@preview/touying:0.5.2": *
#import themes.university: *
#import "@preview/numbly:0.1.0": numbly
#import "@preview/fletcher:0.5.1" as fletcher: node, edge
#let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide)
#import "../components/gh-button.typ": gh_button
#import "../components/git-graph.typ": branch_indicator, commit_node, connect_nodes, branch
Everything we have seen so far is about the *local repository*, that is, the *repository present on our machine*. To collaborate with other developers, it is necessary to have a remote repository, generally it is hosted on services such as GitHub, GitLab or self-hosted.
#grid(columns: (4fr,5fr),[
The *remote repository* is a repository that *the whole team can access*; its branches can be *synchronized*, through pull and push operations, with local repositories. In this way, team members can *work on a common project* while maintaining a history of changes and versions.
],[
#align(center)[#scale(100%)[
#set text(13pt)
#fletcher-diagram(
node-stroke: 1pt,
edge-stroke: 1pt,
spacing: 10em,
node((1,0), [Remote Repository\ on GitHub], corner-radius: 2pt, label:"origin"),
edge((1,0),(0.25,1),"-|>",bend: 10deg),
edge((0.25,1),(1,0),"-|>",label:"git push", bend: 25deg),
node((0.25,1), align(center)[Developer 1 \ Machine], shape: rect),
edge((1,0),(1,1),"-|>", bend: 10deg),
edge((1,1),(1,0),"-|>", bend: 10deg),
node((1,1), [Developer 2 \ Machine], shape: rect),
edge((1,0),(1.75,1),"-|>",label:"git pull", bend: 10deg),
edge((1.75,1),(1,0),"-|>", bend: 25deg),
node((1.75,1), [Developer 3 \ Machine], shape: rect),
)
]]
]
)
The *remote repository* is generally called _origin_. For more complex projects, multiple _remote_ can be added. |
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/研讨.typ | typst | #import "touying/lib.typ": *
#import "template.typ": *
#import "todo.typ": *
#import "@preview/algorithmic:0.1.0"
#import algorithmic: algorithm
#import "notes.typ"
#let s = themes.simple.register(s, aspect-ratio: "16-9", footer: [Harbin Engineering University])
#let s = (s.methods.enable-transparent-cover)(self: s)
#let (init, slide, slides, title-slide, centered-slide, focus-slide,touying-outline) = utils.methods(s)
#show: init
#let codeblock(raw, caption: none, outline: false) = {
figure(
if outline {
rect(width: 100%)[
#set align(left)
#raw
]
} else {
set align(left)
raw
},
caption: caption, kind: "code", supplement: ""
)
}
#let themeColor = rgb(46, 49, 124)
#let head_main=info(
color: black,
(
icon: "1024px-Buckminsterfullerene-3D-balls.png",
content:"M 大作业研讨",
content1:"研讨"
)
)
// #align(left+top,image("icon/校标.png",width: 15em))
#slide[
#v(-1.3em)
// #h(1em)
#align(top+right,image("icon/校标.png",width: 10em))
#align(center+horizon, text(size: 35pt)[
#head_main
])
#v(0.5em)
#align(center,[
#for c in data.成员 [
#text(font: "FangSong",size: 0.75em)[#c
#h(0.6em)
]
]
#v(-0.7em)
// #h(-6.8em)
#for c in data.成员1 [
// #h(3.4em)
#text(font: "FangSong",size: 0.75em)[#c
#h(0.6em)
]
]
]
)
]
#set heading(numbering: "1.")
#set text(font:("Times New Roman","Source Han Serif"),size: 0.76em,spacing: 0.3em,weight: "extralight")
#show heading.where(level: 2):set text(themeColor, 0.9em,font: "Microsoft YaHei")
#show heading.where(level: 3):set text(themeColor, 0.8em,font: "Microsoft YaHei")
// #show strong:set text(font: "HYCuFangSongJ")
// #show footnote:set text(themeColor, 0.9em,font: "Microsoft YaHei")
// 小标题样式
#show heading.where(level: 1):set text(themeColor, 1.5em,font:("Times New Roman","Microsoft YaHei"))
#set par(justify: true,first-line-indent: 2em) // 两端对齐,段前缩进2字符
// #set footnote(numbering: "*")
// 二级标题下加一条横线
#show heading.where(level: 2): it => stack(
v(-1.1em),
align(top+right,image("icon/校标.png",width: 8em)),
// v(-1.1em),
// str(type( locate(loc => query(heading.where(level: 1), loc)))),
// str(type((1,2,3,4,5))),
// align(center,
// rect(fill: themeColor)[
// #for c in ("背景及意义","项目概述") [
// #text(fill:white,font: "Microsoft YaHei")[#c]
// ]
// ]
// )
// ,
// header_rect(),
align(center,[]),
v(-1em),
v(0.1em),
it,
v(0.6em),
// line(length: 100%, stroke: 0.05em + themeColor),
line(length: 100%,stroke: (paint: themeColor, thickness: 0.06em)),
v(0.8em),
)
// #set heading.where(level: 3)(numbering: "1.");
// #show heading.where(level: 3):set heading(numbering: "1.")
#show heading.where(level: 3): it => stack(
v(-0.0em),
it,
v(0.6em),
// line(length: 100%, stroke: 0.05em + themeColor),
line(length: it.body.text.len()*0.25em+2.8em,stroke: (paint: themeColor, thickness: 0.06em, dash: "dashed")),
v(0.1em),
)
// #centered-slide()
// = 111
#show heading: it => {
it
v(-0.8cm)
par()[#text()[#h(0.0em)]]
}
// #show centered-slide : it=>{
// it
// }
#centered-slide(section: [第一题],[])
// #set
// #show footnote.entry: it => {
// let loc = it.note.location()
// numbering(
// "1: ",
// ..counter(footnote).at(loc),
// )
// it.note.body
// }
#let 字体 = (
仿宋: ("Times New Roman", "FangSong"),
宋体: ("Times New Roman", "Source Han Serif"),
黑体: ("Times New Roman", "SimHei"),
楷体: ("Times New Roman", "KaiTi"),
代码: ("New Computer Modern Mono", "Times New Roman", "SimSun"),
)
// 设置代码字体
#show raw: set text(font: 字体.代码)
#let codeblock(raw, caption: none, outline: false) = {
figure(
if outline {
rect(width: 100%)[
#set align(left)
#raw
]
} else {
set align(left)
raw
},
caption: caption, kind: "code", supplement: ""
)
}
#slide[
#let text1 = read("./code/use1.m")
#raw(text1, lang: "matlab")
]
#slide[
#figure(
align(center,
image("./img/1.svg",width: 120%)
)
, caption: [第一题结果示意图]
)
]
#centered-slide(section: [第二题],[])
#import "@preview/mitex:0.2.3": *
#slide[
== 艾里斑
#v(-2em)
#image("./img/7.png",width: 70%)
#h(2em)艾里斑是点光源通过理想透镜成像时,由于衍射而在焦点处形成的光斑。中央是明亮的圆斑,周围有一组较弱的明暗相间的同心环状条纹,把其中以第一暗环为界限的中央亮斑称作艾里斑。这个光斑的大小可以用下面的公式来估计:
#mitex(`
r=d/2=1.22\frac{\lambda f}{D}
`)
在数学上,艾里斑的光强分布可以通过以下的公式来描述:
#mitex(`
I(r)=\left(\frac{2J_1(kr)}{kr}\right)^2
`)
]
#slide[
#figure(
align(center,
image("./img/8.png",width: 80%)
)
, caption: [艾里斑]
)
]
#slide[
#let text1 = read("./code/use2.m")
#raw(text1, lang: "matlab")
]
#centered-slide(section: [第三题],[])
#slide[
只做了均匀光栅反射和透射谱
中心波长$lambda_B$有
#mitex(`
\lambda_B=2n_{eff}\Lambda
`)
#mitex(`
\begin{aligned}&R=\frac{P_B(0)}{P_A(0)}=\frac{|B(0)|^2}{|A(0)|^2}=\frac{\kappa\kappa^*\sin^2(sL)}{s^2\cos^2(sL)+\delta^2\sin^2(sL)}\\\\\\&T=\frac{P_A(L)}{P_A(0)}=\frac{|A(L)|^2}{|A(0)|^2}=\frac{s^2}{s^2\cos^2(sL)+\delta^2\sin^2(sL)}\end{aligned}
`)
其中 $ Delta k=k-pi /lambda,s^2=Omega^2-Delta k^2$, 其中 $Omega$ 为耦合系数;
$ Omega= (pi Delta n )/lambda M_p $
近似为 $1 — V^2$
]
#slide[
#let text1 = read("./code/use3.m")
#raw(text1, lang: "matlab")
]
#slide[
#figure(
align(center,
image("./code/3.svg",width: 70%)
)
)
] |
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/covers/LiturgiaBV.typ | typst | #set text(font: "Monomakh Unicode", lang: "cu")
#import "../style.typ": *
#rect(width: 100%, height: 100%, outset: 7%,
stroke: (paint: red, thickness: 4pt),
rect(width: 100%, height: 100%, outset: 6%,
stroke: (paint: red, thickness: 4pt),
[
#align(center)[#text(100pt)[#redText[☦]]]
#align(center)[#redText[
#text(50pt)[Боже́ственнаѧ]\ \ \
#text(90pt)[ЛЇТꙊРГІ́Ꙗ]\ \ \
#text(20pt, black)[и҆́же во ст҃ы́хь ѻ҆тца̀ на́шегѡ]\ \
#text(50pt)[Васі́лїа Вели́кагѡ]\
]]\ \ \ \ \ \ \ \ \
#align(center)[#text(20pt)[#redText[Editio Ruthenia]]]\
#align(center)[#text(20pt)[Prešov\ <NAME>\ 2023]]
]
)
) |
|
https://github.com/Quaternijkon/Typst_FLOW | https://raw.githubusercontent.com/Quaternijkon/Typst_FLOW/main/src/components.typ | typst | #import "utils.typ"
#let _typst-builtin-numbering = numbering
#let cell = block.with(width: 100%, height: 100%, above: 0pt, below: 0pt, outset: 0pt, breakable: false)
/// SIDE BY SIDE
///
/// A simple wrapper around `grid` that creates a grid with a single row.
/// It is useful for creating side-by-side slide.
///
/// It is also the default function for composer in the slide function.
///
/// Example: `side-by-side[a][b][c]` will display `a`, `b`, and `c` side by side.
///
/// - `columns` is the number of columns. Default is `auto`, which means the number of columns is equal to the number of bodies.
///
/// - `gutter` is the space between columns. Default is `1em`.
///
/// - `..bodies` is the contents to display side by side.
#let side-by-side(columns: auto, gutter: 1em, ..bodies) = {
let bodies = bodies.pos()
if bodies.len() == 1 {
return bodies.first()
}
let columns = if columns == auto {
(1fr,) * bodies.len()
} else {
columns
}
grid(columns: columns, gutter: gutter, ..bodies)
}
/// Adaptive columns layout
///
/// Example: `components.adaptive-columns(outline())`
///
/// - `gutter` is the space between columns.
///
/// - `max-count` is the maximum number of columns.
///
/// - `start` is the content to place before the columns.
///
/// - `end` is the content to place after the columns.
///
/// - `body` is the content to place in the columns.
#let adaptive-columns(gutter: 4%, max-count: 3, start: none, end: none, body) = layout(size => {
let n = calc.min(
calc.ceil(measure(body).height / (size.height - measure(start).height - measure(end).height)),
max-count,
)
if n < 1 {
n = 1
}
start
if n == 1 {
body
} else {
columns(n, body)
}
end
})
/// Touying progress bar.
///
/// - `primary` is the color of the progress bar.
///
/// - `secondary` is the color of the background of the progress bar.
///
/// - `height` is the height of the progress bar, optional. Default is `2pt`.
#let progress-bar(height: 2pt, primary, secondary) = utils.touying-progress(ratio => {
grid(
columns: (ratio * 100%, 1fr),
rows: height,
cell(fill: primary), cell(fill: secondary),
)
})
/// Left and right.
///
/// - `left` is the content of the left part.
///
/// - `right` is the content of the right part.
#let left-and-right(left, right) = grid(
columns: (auto, 1fr, auto),
left, none, right,
)
// Create a slide where the provided content blocks are displayed in a grid and coloured in a checkerboard pattern without further decoration. You can configure the grid using the rows and `columns` keyword arguments (both default to none). It is determined in the following way:
///
/// - If `columns` is an integer, create that many columns of width `1fr`.
/// - If `columns` is `none`, create as many columns of width `1fr` as there are content blocks.
/// - Otherwise assume that `columns` is an array of widths already, use that.
/// - If `rows` is an integer, create that many rows of height `1fr`.
/// - If `rows` is `none`, create that many rows of height `1fr` as are needed given the number of co/ -ntent blocks and columns.
/// - Otherwise assume that `rows` is an array of heights already, use that.
/// - Check that there are enough rows and columns to fit in all the content blocks.
///
/// That means that `#checkerboard[...][...]` stacks horizontally and `#checkerboard(columns: 1)[...][...]` stacks vertically.
#let checkerboard(columns: none, rows: none, ..bodies) = {
let bodies = bodies.pos()
let columns = if type(columns) == int {
(1fr,) * columns
} else if columns == none {
(1fr,) * bodies.len()
} else {
columns
}
let num-cols = columns.len()
let rows = if type(rows) == int {
(1fr,) * rows
} else if rows == none {
let quotient = calc.quo(bodies.len(), num-cols)
let correction = if calc.rem(bodies.len(), num-cols) == 0 {
0
} else {
1
}
(1fr,) * (quotient + correction)
} else {
rows
}
let num-rows = rows.len()
if num-rows * num-cols < bodies.len() {
panic("number of rows (" + str(num-rows) + ") * number of columns (" + str(num-cols) + ") must at least be number of content arguments (" + str(
bodies.len(),
) + ")")
}
let cart-idx(i) = (calc.quo(i, num-cols), calc.rem(i, num-cols))
let color-body(idx-body) = {
let (idx, body) = idx-body
let (row, col) = cart-idx(idx)
let color = if calc.even(row + col) {
white
} else {
silver
}
set align(center + horizon)
rect(inset: .5em, width: 100%, height: 100%, fill: color, body)
}
let body = grid(
columns: columns, rows: rows,
gutter: 0pt,
..bodies.enumerate().map(color-body)
)
body
}
/// Show progressive outline. It will make other sections except the current section to be semi-transparent.
///
/// - `alpha` is the transparency of the other sections. Default is `60%`.
///
/// - `level` is the level of the outline. Default is `1`.
///
/// - `transform` is the transformation applied to the text of the outline. It should take the following arguments:
///
/// - `cover` is a boolean indicating whether the current entry should be covered.
///
/// - `..args` are the other arguments passed to the `progressive-outline`.
#let progressive-outline(
alpha: 10%, // 将透明度从60%降低到30%
level: 1,
transform: (cover: false, alpha: 10%, ..args, it) => {
// 根据标题级别设置字号
let fontSize = if it.element.level == 1 {
if cover { 0.8em } else { 1.1em } // 一级标题
} else if it.element.level == 2 {
if cover { 0.7em } else { 0.8em } // 二级标题
} else {
0.8em // 其他级别标题
}
let weight = if it.element.level == 1 {
if cover { "regular" } else { "bold" }
} else {
"regular"
}
text(
fill: if cover {
utils.update-alpha(text.fill, alpha)
} else {
text.fill
},
size: fontSize,
weight: weight,
it
)
},
..args,
) = (
context {
// 起始页和结束页
let start-page = 1
let end-page = calc.inf
if level != none {
let current-heading = utils.current-heading(level: level)
if current-heading != none {
start-page = current-heading.location().page()
if level != auto {
let next-headings = query(
selector(heading.where(level: level)).after(inclusive: false, current-heading.location()),
)
if next-headings != () {
end-page = next-headings.at(0).location().page()
}
} else {
end-page = start-page + 1
}
}
}
show outline.entry: it => transform(
cover: it.element.location().page() < start-page or it.element.location().page() >= end-page,
level: level,
alpha: alpha,
..args,
it,
)
outline(..args)
}
)
/// Show a custom progressive outline.
///
/// - `self` is the self context.
///
/// - `alpha` is the transparency of the other headings. Default is `60%`.
///
/// - `level` is the level of the outline. Default is `auto`.
///
/// - `numbered` is a boolean array indicating whether the headings should be numbered. Default is `false`.
///
/// - `filled` is a boolean array indicating whether the headings should be filled. Default is `false`.
///
/// - `paged` is a boolean array indicating whether the headings should be paged. Default is `false`.
///
/// - `numbering` is an array of numbering strings for the headings. Default is `()`.
///
/// - `text-fill` is an array of colors for the text fill of the headings. Default is `none`.
///
/// - `text-size` is an array of sizes for the text of the headings. Default is `none`.
///
/// - `text-weight` is an array of weights for the text of the headings. Default is `none`.
///
/// - `vspace` is an array of vertical spaces above the headings. Default is `none`.
///
/// - `title` is the title of the outline. Default is `none`.
///
/// - `indent` is an array of indentations for the headings. Default is `(0em, )`.
///
/// - `fill` is an array of fills for the headings. Default is `repeat[.]`.
///
/// - `short-heading` is a boolean indicating whether the headings should be shortened. Default is `true`.
///
/// - `uncover-fn` is a function that takes the body of the heading and returns the body of the heading when it is uncovered. Default is the identity function.
///
/// - `..args` are the other arguments passed to the `progressive-outline` and `transform`.
#let custom-progressive-outline(
self: none,
alpha: 60%,
level: auto,
numbered: (false,),
filled: (false,),
paged: (false,),
numbering: (),
text-fill: none,
text-size: none,
text-weight: none,
vspace: none,
title: none,
indent: (0em,),
fill: (repeat[.],),
short-heading: true,
uncover-fn: body => body,
..args,
) = progressive-outline(
alpha: alpha,
level: level,
transform: (cover: false, alpha: alpha, ..args, it) => {
let array-at(arr, idx) = arr.at(idx, default: arr.last())
let set-text(level, body) = {
set text(fill: {
let text-color = if type(text-fill) == array and text-fill.len() > 0 {
array-at(text-fill, level - 1)
} else {
text.fill
}
if cover {
utils.update-alpha(text-color, alpha)
} else {
text-color
}
})
set text(
size: array-at(text-size, level - 1),
) if type(text-size) == array and text-size.len() > 0
set text(
weight: array-at(text-weight, level - 1),
) if type(text-weight) == array and text-weight.len() > 0
body
}
let body = {
if type(vspace) == array and vspace.len() > it.level - 1 {
v(vspace.at(it.level - 1))
}
h(range(1, it.level + 1).map(level => array-at(indent, level - 1)).sum())
set-text(
it.level,
{
if array-at(numbered, it.level - 1) {
let current-numbering = numbering.at(it.level - 1, default: it.element.numbering)
if current-numbering != none {
_typst-builtin-numbering(
current-numbering,
..counter(heading).at(it.element.location()),
)
h(.3em)
}
}
link(
it.element.location(),
{
if short-heading {
utils.short-heading(self: self, it.element)
} else {
it.element.body
}
box(
width: 1fr,
inset: (x: .2em),
if array-at(filled, it.level - 1) {
array-at(fill, level - 1)
},
)
if array-at(paged, it.level - 1) {
_typst-builtin-numbering(
if page.numbering != none {
page.numbering
} else {
"1"
},
..counter(page).at(it.element.location()),
)
}
},
)
},
)
}
if cover {
body
} else {
uncover-fn(body)
}
},
title: title,
..args,
)
/// Show mini slides. It is usually used to show the navigation of the presentation in header.
///
/// - `self` is the self context, which is used to get the short heading of the headings.
///
/// - `fill` is the fill color of the headings. Default is `rgb("000000")`.
///
/// - `alpha` is the transparency of the headings. Default is `60%`.
///
/// - `display-section` is a boolean indicating whether the sections should be displayed. Default is `false`.
///
/// - `display-subsection` is a boolean indicating whether the subsections should be displayed. Default is `true`.
///
/// - `short-heading` is a boolean indicating whether the headings should be shortened. Default is `true`.
#let mini-slides(
self: none,
fill: rgb("000000"), // 填充颜色,默认为黑色
alpha: 60%, // 非当前章节的透明度
display-section: false, // 是否显示章节的幻灯片链接
display-subsection: true, // 是否显示子章节的幻灯片链接
short-heading: true, // 是否使用简短的标题
) = (
context {
// 查询所有一级和二级标题
let headings = query(heading.where(level: 1).or(heading.where(level: 2)))
// 过滤出一级标题(章节)
let sections = headings.filter(it => it.level == 1)
// 如果没有章节,直接返回
if sections == () {
return
}
// 获取第一个章节所在的页面编号
let first-page = sections.at(0).location().page()
// 过滤掉第一个章节之前的标题
headings = headings.filter(it => it.location().page() >= first-page)
// 查询幻灯片元数据,过滤出有效的幻灯片
let slides = query(<touying-metadata>).filter(it => (
utils.is-kind(it, "touying-new-slide") and it.location().page() >= first-page
))
// 获取当前页面编号
let current-page = here().page()
// 计算当前章节的索引
let current-index = sections.filter(it => it.location().page() <= current-page).len() - 1
// 初始化用于存储列的数组
let cols = ()
let col = ()
// 遍历标题,构建目录结构
for (hd, next-hd) in headings.zip(headings.slice(1) + (none,)) {
// 获取下一个标题的页面编号,如果没有则设为正无穷
let next-page = if next-hd != none {
next-hd.location().page()
} else {
calc.inf
}
// 如果是一级标题(章节)
if hd.level == 1 {
// 如果当前列不为空,将其添加到列数组中并重置
if col != () {
cols.push(align(left, col.sum()))
col = ()
}
// 构建章节内容
col.push({
// 获取标题内容,可能是简短形式
let body = if short-heading {
utils.short-heading(self: self, hd)
} else {
hd.body
}
// 创建指向该章节的链接
[#link(hd.location(), body)<touying-link>]
linebreak()
// 处理该章节下的幻灯片
while slides.len() > 0 and slides.at(0).location().page() < next-page {
let slide = slides.remove(0)
if display-section {
// 获取下一个幻灯片的页面编号
let next-slide-page = if slides.len() > 0 {
slides.at(0).location().page()
} else {
calc.inf
}
// 判断幻灯片是否为当前页面,并显示相应的圆形符号
if slide.location().page() <= current-page and current-page < next-slide-page {
[#link(slide.location(), sym.circle.filled)<touying-link>]
} else {
[#link(slide.location(), sym.circle)<touying-link>]
}
}
}
// 如果需要显示章节和子章节,添加换行
if display-section and display-subsection {
linebreak()
}
})
} else {
// 如果是二级标题(子章节)
col.push({
// 处理该子章节下的幻灯片
while slides.len() > 0 and slides.at(0).location().page() < next-page {
let slide = slides.remove(0)
if display-subsection {
// 获取下一个幻灯片的页面编号
let next-slide-page = if slides.len() > 0 {
slides.at(0).location().page()
} else {
calc.inf
}
// 判断幻灯片是否为当前页面,并显示相应的圆形符号
if slide.location().page() <= current-page and current-page < next-slide-page {
[#link(slide.location(), sym.circle.filled)<touying-link>]
} else {
[#link(slide.location(), sym.circle)<touying-link>]
}
}
}
// 如果需要显示子章节,添加换行
if display-subsection {
linebreak()
}
})
}
}
// 将最后一个列添加到列数组中
if col != () {
cols.push(align(left, col.sum()))
col = ()
}
// 自适应字号计算
let num_sections = sections.len() // 章节数量
let max_size = .5em // 最大字号
let min_size = .3em // 最小字号
let size_range = max_size - min_size // 字号范围
let max_sections = 3 // 章节数量小于等于3时使用最大字号
// 计算非当前章节的字号
let computed_size = if num_sections <= max_sections {
max_size
} else {
let size = max_size - (num_sections - max_sections) * (size_range / (num_sections - 1))
// 确保字号不小于最小字号
if size < min_size {
min_size
} else {
size
}
}
let small-size = computed_size // 非当前章节的字号
// 计算当前章节的字号,比非当前章节大一些
let large-size = small-size + .1em // 当前章节的字号
// 设置各章节的显示样式
if current-index < 0 or current-index >= cols.len() {
// 如果当前索引无效,所有章节都使用非当前章节的样式
cols = cols.map(body => text(fill: fill, size: small-size, body))
} else {
// 遍历所有章节
cols = cols.enumerate().map(pair => {
let (idx, body) = pair
if idx == current-index {
// 当前章节,使用较大字号和正常颜色
text(fill: fill, size: large-size, body)
} else {
// 非当前章节,使用较小字号和透明度处理的颜色
text(fill: utils.update-alpha(fill, alpha), size: small-size, body)
}
})
}
// 设置对齐方式为顶部对齐
set align(top)
// 设置显示块的内边距
show: block.with(inset: (top: .5em, x: 2em))
// 调整换行符的垂直偏移,减少行间距
show linebreak: it => it + v(-1em)
// 创建网格布局,排列各章节列
grid(columns: cols.map(_ => auto).intersperse(1fr), ..cols.intersperse([]))
}
)
#let simple-navigation(
self: none,
short-heading: true,
primary: white,
secondary: gray,
background: black,
logo: none,
) = (
context {
let body() = {
let sections = query(heading.where(level: 1))
if sections.len() == 0 {
return
}
let current-page = here().page()
set text(size: 0.5em)
for (section, next-section) in sections.zip(sections.slice(1) + (none,)) {
set text(fill: if section.location().page() <= current-page and (
next-section == none or current-page < next-section.location().page()
) {
primary
} else {
secondary
})
box(inset: 0.5em)[#link(
section.location(),
if short-heading {
utils.short-heading(self: self, section)
} else {
section.body
},
)<touying-link>]
}
}
block(
fill: background,
inset: 0pt,
outset: 0pt,
grid(
align: center + horizon,
columns: (1fr, auto),
rows: 1.8em,
gutter: 0em,
cell(
fill: background,
body(),
),
block(fill: background, inset: 4pt, height: 100%, text(fill: primary, logo)),
),
)
}
)
/// LaTeX-like knob marker for list
///
/// Example: `#set list(marker: components.knob-marker(primary: rgb("005bac")))`
#let knob-marker(primary: rgb("#005bac")) = box(
width: 0.5em,
place(
dy: 0.1em,
circle(
fill: gradient.radial(
primary.lighten(100%),
primary.darken(40%),
focal-center: (30%, 30%),
),
radius: 0.25em,
),
),
) |
|
https://github.com/drupol/master-thesis | https://raw.githubusercontent.com/drupol/master-thesis/main/src/thesis/main.typ | typst | Other | #import "imports/preamble.typ": *
#import "theme/template.typ": *
#set document(
title: title,
author: author,
date: none,
keywords: (
"university",
"umons",
"june 2024",
"master thesis",
"reproducibility",
"r13y",
"compilation",
"docker",
"nix",
"guix",
),
)
#show: project.with(
title: title,
university: university,
faculty: faculty,
degree: degree,
program: program,
supervisor: supervisor,
advisors: advisors,
author: author,
startDate: startDate,
submissionDate: submissionDate,
doi: doi,
disclaimer: include "disclaimer.typ",
acknowledgement: include "acknowledgement.typ",
abstract: include "abstract.typ",
accessibility: include "accessibility.typ",
extra: include "extra.typ",
terms: (
(
key: "CC BY 4.0",
short: "CC BY 4.0",
long: "Creative Commons Attribution 4.0 International",
description: [The Creative Commons Attribution 4.0 International License #cite(<CCBy40>,form:"normal") is a widely used license that allows others to distribute, remix, adapt, and build upon your work, even commercially, as long as they credit you for the original creation. This is the most flexible of the CC licenses.],
),
(
key: "CDN",
short: "CDN",
long: "Content Delivery Network",
description: [A content delivery network is a system of distributed servers that deliver web content to a user based on the geographic locations of the user, the origin of the webpage and a content delivery server, making the delivery of content more efficient.],
),
(
key: "CICD",
short: "CI/CD",
long: "Continuous Integration/Continuous Deployment",
description: [Continuous Integration (CI) is a software development practice where developers regularly merge their code changes into a central repository, after which automated builds and tests are run. Continuous Deployment (CD) is a software release process that uses automated testing to validate that changes are safe to deploy to production.],
),
(
key: "CPU",
short: "CPU",
long: "Central Processing Unit",
description: [The CPU is the primary component of a computer that processes instructions. It runs the operating system and applications, constantly receiving input from the user or active software programs. It processes the data and produces outputs. ARM and X86 are two common CPU architectures.],
),
(
key: "CRA",
short: "CRA",
long: "Cyber Resilience Act",
description: [The Cyber Resilience Act #cite(<CRA>,form:"normal") is a proposed European Union regulation that aims to improve the cybersecurity of digital products and services. It includes provisions for #link(<ch2-supply-chain>)[software supply chain] security, incident reporting, and security certification.],
),
(
key: "CS",
short: "CS",
long: "Computer Science",
description: [The discipline of Computer Science includes the study of algorithms and data structures, computer and network design, modelling data and information processes, and artificial intelligence. Computer Science draws some of its foundations from mathematics and engineering and therefore incorporates techniques from areas such as queueing theory, probability and statistics, and electronic circuit design.],
),
(
key: "CycloneDX",
short: "CycloneDX",
description: [@cyclonedx is an open-format standard baked by the OWASP foundation and Ecma Technical Committee designed to provide comprehensive and interoperable information about the components used within software projects like software bill of materials and advanced supply chain capabilities for cyber risk reduction.],
),
(
key: "DevOps",
short: "DevOps",
description: [DevOps is a set of practices that combines software development (Dev) and IT operations (Ops). It aims to shorten the systems development life cycle and provide #gls("CICD").],
),
(
key: "DevSecOps",
short: "DevSecOps",
description: [
DevSecOps is an extension of #gls("DevOps") practices that integrates security (Sec) measures at every stage of the software development lifecycle, ensuring that security is a fundamental aspect of development and operations processes.
],
),
(
key: "DSL",
short: "DSL",
long: "Domain Specific Language",
description: [A domain-specific language is a computer language specialised to a particular application domain. This is in contrast to a general-purpose language, which is broadly applicable across various domains.],
),
(
key: "FHS",
short: "FHS",
long: "Filesystem Hierarchy Standard",
description: [The Filesystem Hierarchy Standard is a reference document that describe the conventions used for the layout of Unix-like operating systems. This includes names, locations, and permissions of many file and directories.],
),
(
key: "HL3",
short: "HL3",
long: "Hippocratic Licence 3.0",
description: [The Hippocratic Licence 3.0 #cite(<HypocraticLicence>,form:"normal") is a software license that ensures that software is not used to contribute to human rights abuses or other unethical practices. It is designed to protect users and communities from the potential misuse of software.],
),
(
key: "IDE",
short: "IDE",
long: "Integrated Development Environment",
plural: "IDEs",
longplural: "Integrated Development Environments",
desc: [An integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development.],
),
(
key: "IEEE",
short: "IEEE",
long: "Institute of Electrical and Electronics Engineers",
description: [The Institute of Electrical and Electronics Engineers #cite(<ITripleE>, form:"normal"), established in 1963, is the world's largest technical professional organisation dedicated to advancing technology for the benefit of humanity. It serves as a professional association for electronic engineering, electrical engineering, and related disciplines.],
),
(
key: "MD5",
short: "MD5",
long: "Message Digest 5",
description: [The MD5 message-digest algorithm is a widely used hash function producing a 128-bit hash value. MD5 was designed by <NAME> in 1991 to replace an earlier hash function MD4, and was specified in 1992 as RFC 1321.],
),
(
key: "OCI",
short: "OCI",
long: "Open Container Initiative",
description: [OCI stands for @opencontainerinitiative, an open governance project for the purpose of creating open industry standards around container formats and runtime. An "OCI image" is a container image that conforms to the OCI image format specification.],
),
(
key: "OS",
short: "OS",
long: "Operating System",
plural: "OSes",
longplural: "Operating Systems",
description: [An operating system is system software that manages computer hardware and software resources, and provides common services for computer programs.],
),
(
key: "PDF",
short: "PDF",
long: "Portable Document Format",
description: [A file format developed by Adobe in the 1990s to present documents, including text formatting and images, in a manner independent of application software, hardware, and operating systems.],
),
(
key: "POSIX",
short: "POSIX",
long: "Portable Operating System Interface",
description: [POSIX is a family of standards specified by the #gls("IEEE") for maintaining compatibility between operating systems.],
),
(
key: "PURL",
short: "PURL",
plural: "PURLs",
long: "Package URL",
description: [A PURL #cite(<purl>,form:"normal") is a #gls("URL") string used to identify and locate a software package in a mostly universal and uniform way across programing languages, package managers, packaging conventions, tools, APIs and databases.],
),
(
key: "REPL",
short: "REPL",
long: "Read-Eval-Print Loop",
description: [A read-eval-print loop is an interactive computer programming environment that takes single user inputs, evaluates them, and returns the result to the user.],
),
(
key: "SBOM",
short: "SBOM",
plural: "SBOMs",
long: "Software Bill of Materials",
description: [The software bill of materials is a comprehensive inventory of all components, including libraries, dependencies and versions, that constitute a software product, used for tracking and managing software supply chain security.],
),
(
key: "SPDX",
short: "SPDX",
long: "Software Package Data Exchange",
description: [The @spdx format, created and maintained by the
Linux Foundation, is a standardised way of documenting and communicating the
components, licenses, and copyrights of software packages. It provides a
consistent method for tracking and sharing information about software contents,
particularly in open-source and collaborative environments.],
),
(
key: "SHA1",
short: "SHA-1",
long: "Secure Hash Algorithm 1",
description: [SHA-1 is a hash function which takes an input and produces a 160-bit (20-byte) hash value known as a message digest – typically rendered as 40 hexadecimal digits. It was designed by the United States National Security Agency (NSA), and is a U.S. Federal Information Processing Standard.],
),
(
key: "SHA2",
short: "SHA-2",
long: "Secure Hash Algorithm 2",
description: [SHA-2 is a set of cryptographic hash functions designed by the United States National Security Agency (NSA). It consists of six hash functions with digests (hash values) that are 224, 256, 384 or 512 bits: SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, SHA-512/256.],
),
(
key: "SE",
short: "SE",
long: "Software Engineering",
description: [Software Engineering is a computing discipline. It is the systematic application of engineering approaches to the development of software.],
),
(
key: "SemVer",
short: "SemVer",
long: "Semantic Versioning",
description: [Semantic Versioning #cite(<preston2013semantic>, form: "normal") is a versioning scheme for software that uses a three-part version number: `MAJOR.MINOR.PATCH`.],
),
(
key: "SRI",
short: "SRI",
long: "Subresource Integrity",
description: [Subresource Integrity #cite(<sri>, form: "normal") is a security feature that allows web developers to ensure that resources they fetch are delivered without unexpected manipulation.],
),
(
key: "SVG",
short: "SVG",
long: "Scalable Vector Graphics",
description: [SVG is an XML-based vector image format.],
),
(
key: "SWHID",
short: "SWHID",
long: "Software Heritage Identifier",
description: [The Software Heritage Identifier #cite(<hal-01865790>,form:"normal") is a unique identifier for software artifacts, such as source code, that is used to track and reference software across different platforms and systems.],
),
(
key: "URL",
short: "URL",
long: "Uniform Resource Locator",
description: [A URL is a reference to a web resource that specifies its location on a computer network and a mechanism for retrieving it.],
),
),
)
#include "1-introduction.typ"
#include "2-reproducibility.typ"
#leftblank(weak: false)
#include "3-tools.typ"
#include "4-conclusion.typ"
|
https://github.com/almarzn/portfolio | https://raw.githubusercontent.com/almarzn/portfolio/main/templates/typst/.template/styles.typ | typst | #import "./page.typ": *
#import "./shared/sizes.typ": scale
#import "@preview/splash:0.3.0": tailwind
#let margin-small = block.with(inset: (x: 8pt));
#let margin-medium = block.with(inset: (x: 16pt));
#let margin-large = block.with(inset: (x: 32pt));
#let margin-xlarge = block.with(inset: (x: 48pt));
#let default(body) = {
let footer-size = 64pt
let base-margin = 24pt
// set block(stroke: (paint: blue, thickness: 1pt, dash: "dashed"))
// set grid(st: (paint: yellow, thickness: 1pt, dash: "dashed"))
set page(
background: page-background(color: tailwind.orange-400),
footer-descent: 0%,
footer: page-footer(
height: footer-size,
background: tailwind.slate-200,
content: (
header: "Max Digital Services Lyon",
sub: [SIRET -- 56789876511],
contact1: (
name: [<NAME>],
phone: [01 02 03 04 05]
),
contact2: (
name: [<NAME>],
phone: [07 93 10 02 30]
)
)
),
margin: (x: 0pt, top: 0pt, bottom: footer-size)
)
set text(font: "Lexend")
set text(size: scale.p)
set heading(numbering: none)
show heading.where(level: 1): set text(size: scale.h1)
show heading.where(level: 1): set block(below: 20pt)
// show heading.where(level: 1): it => {
// upper(it)
// }
show heading.where(level: 2): set text(size: scale.h2, fill: tailwind.orange-500)
show heading.where(level: 2): set block(spacing: 0pt)
show heading.where(level: 3): set text(weight: "extrabold", size: scale.h3)
// show heading.where(level: 3): set block(spacing: 20pt)
show heading.where(level: 4): set text(weight: "semibold", size: scale.h4)
// show heading.where(level: 4): set block(spacing: 20pt)
show heading.where(level: 5): set text(weight: "light", size: scale.h5)
// show heading.where(level: 5): set block(spacing: 10pt)
// show heading.where(level: 4): it => {
// upper(it)
// }
body
}
#let section-heading(
icon,
text
) = [
== #grid(
columns: (32pt, auto, 1fr),
column-gutter: 12pt,
align(center + horizon, block(icon)),
align(horizon, text),
align(horizon, line(length: 100%, stroke: (paint: tailwind.orange-400, thickness: 3pt, cap: "round"))),
)
]
// #let section-heading(
// icon,
// content
// ) = block(inset: 8pt, radius: 4pt, fill: tailwind.orange-400)[
// == #text(fill: white, [#box(width: 32pt, align(center + horizon, icon)) #content])
// ] |
|
https://github.com/Myriad-Dreamin/shiroa | https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/packages/shiroa/lib.typ | typst | Apache License 2.0 | //! The `shiroa` package has three parts.
//!
//! 1. Metadata variables and functions.
//! - `target`
//! - `page-width`
//! - `is-web-target`
//! - `is-pdf-target`
//! - `book-sys`
//!
//! 2. Components to read or write book.typ
//! - `book`
//! - `book-meta`
//! - `build-meta`
//! - `chapter`
//! - `prefix-chapter`
//! - `suffix-chapter`
//! - `divider`
//! - `external-book`
//!
//! 3. Typst Supports
//! - `cross-link`
//! - `plain-text`
//! - `media`
// Part I: Metadata variables and functions
#import "meta-and-state.typ": *
// Part II: Components to read or write book.typ
#import "summary.typ": *
// Part III: Supports
#import "supports-link.typ" as link-support: cross-link
#import "supports-text.typ" as text-support: plain-text
#import "media.typ"
#import "utils.typ": get-book-meta, get-build-meta
// Part IV: Templates, todo: move me to a new package
#import "templates.typ"
|
https://github.com/rabotaem-incorporated/calculus-notes-2course | https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/03-lebesgue-integral/04-measure-product.typ | typst | #import "../../utils/core.typ": *
== Произведение мер
#def(label: "def-measurable-rect")[
$(X, Aa, mu)$ и $(Y, Bb, nu)$ --- пространства с $sigma$-конечной#rf("def-sfinite") мерой. Пусть $ P := {A times B: A in Aa, B in Bb, mu A < +oo, nu B < +oo}. $
Такие множества $A times B$ назовем _измеримыми прямоугольниками_. Введем $m_0 (A times B) := mu A dot nu B$.
]
#th[
$Pp$ --- полукольцо#rf("def-semiring"), а $m_0$ --- $sigma$-конечная#rf("def-sfinite") мера на $Pp$.
]
#proof[
${A in Aa: mu A < +oo}$ и ${B in Bb : nu B < +oo}$ --- полукольца (и даже просто кольца). Декартово произведение полуколец --- полукольцо#rf("cartesian-semiring-prod"), поэтому $Pp$ --- полукольцо.
Так как можно сказать, что $X = usb X_n$ и $Y = usb Y_k$, $mu X_n < +oo, nu Y_k < +oo$, то $X times Y = usb X_n times Y_k$, и $m_0 (X_n times Y_k) < +oo$. Отсюда следует $sigma$-конечность. Осталось проверить, что $m_0$ --- мера. Проверим, что если $A times B = P = usb_(k = 1)^oo P_k = usb_(k = 1)^oo A_k times B_k $, то $m_0 P = sum_(k = 1)^oo m_0 P_k.$
Мы знаем, что $ bb(1)_A dot bb(1)_B = bb(1)_P = sum_(k = 1)^oo bb(1)_(P_k) = sum_(k = 1)^oo bb(1)_(A_k) dot bb(1)_(B_k)$. Проинтегрируем по мере $mu$
$
integral_X bb(1)_A (x) dot bb(1)_B (y) dif mu(x) =^rf("def-integral-simple") mu A dot bb(1)_B (y)
$
Также
$
integral_X bb(1)_A (x) dot bb(1)_B (y) dif mu(x) =
integral_X sum_(k = 1)^oo bb(1)_(A_k) (x) dot bb(1)_(B_k) (y) dif mu (x)
newline(=^rf("integral-sum-perm-mfn"))
sum_(k = 1)^oo integral_X bb(1)_(A_k) (x) dot bb(1)_(B_k) (y) dif mu(x) =
sum_(k = 1)^oo mu A_k dot bb(1)_(B_k) (y).
$
Теперь проинтегрируем по мере $nu$ оба результата
$
integral_Y mu A dot bb(1)_B (y) dif nu(y) =^rf("def-integral-simple")
mu A dot nu B = m_0 P
\
integral_Y sum_(k = 1)^oo mu A_k bb(1)_(B_k) (y) dif nu(y) =^rf("integral-sum-perm-mfn")
sum_(k = 1)^oo mu A_k dot nu B_k =
sum_(k = 1)^oo m_0 P_k.
$
]
#def(label: "def-measure-prod")[
Стандартное продолжение#rf("def-standard-continuation") меры $m_0$ с полукольца $Pp$ называется _произведением мер_ $mu$ и $nu$. Обозначается $mu times nu$ (обычно $m$). $Aa times.circle Bb$ --- $sigma$-алгебра, на которой определена $mu times nu$.
]
#props(label: "measure-prod-props")[
1. #sublabel("cartesian-prod") Декартово произведение измеримых множеств --- измеримое.
2. #sublabel("zero") Если $mu e = 0$, то $m (e times Y) = 0$, где $m = mu times nu$.
]
#proof[
1. $A = usb_(k = 1)^oo A_k$, $mu A_k < +oo$, $B = usb_(n = 1)^oo B_n$, $nu B_n < +oo$. $A times B = usb_(n, k = 1)^oo A_k times B_n$, $mu A_k dot nu B_n < +oo$, $A_k times B_n in Pp$.
2. $Y = usb_(n = 1)^oo Y_n$, $nu Y_n < +oo$. $m(e times Y_k) = 0$. $e times Y = usb_(k = 1)^oo e times Y_k ==> m(e times Y) = 0$.
]
#denote(label: "def-sect")[
$C subset X times Y$. Обозначим
$
C_x &= {y in Y: (x, y) in C},\
C^y &= {x in X: (x, y) in C}.
$
Это _сечения_ множества $C$.
]
#props[
1. $(Union_(alpha in I) C_alpha)_x = Union_(alpha in I) (C_alpha)_x$.
2. $(Sect_(alpha in I) C_alpha)_x = Sect_(alpha in I) (C_alpha)_x$.
]
#def(label: "def-mfn+")[
$f$ определенная почти везде на $E$, _измерима в широком смысле_, если найдется $e subset E$ ($mu e = 0$), такое, что $f bar_(E without e)$ измерима.
Вскоре все функции, измеримые в широком смысле мы начнем называть измеримыми.
]
#def(label: "def-monotonous-class")[
Пусть $Ee$ --- семейство подмножеств в $X$. $Ee$ --- _монотонный класс_, если
1. $E_j in Ee. space E_1 subset E_2 subset E_3 subset ... ==> Union_(j = 1)^oo E_j in Ee$.
2. $E_j in Ee. space E_1 supset E_2 supset E_3 supset ... ==> Sect_(j = 1)^oo E_j in Ee$
]
#th(label: "monotonous-class-contains-borel")[
Если монотонный класс содержит алгебру $Aa$, то он содержит и ее Бореллевскую оболочку $Bb(Aa)$.
]
#proof[
Без доказательства. Это делается чистой алгеброй, забьем делать аккуратно. Но основная мысль такая: надо рассмотреть минимум по включению мотононных классов, содержащих $Aa$, и показать, что он является $sigma$-алгеброй. Достаточно будет доказать, что это алгебра, так как есть свойство про объединение башни. Там возня с использованием минимальности, пофиг.
]
#th(name: "принцип Кавальери", label: "cavalieri")[
$(X, Aa, mu)$ и $(Y, Bb, nu)$ --- пространства с $sigma$-конечными#rf("def-sfinite") мерами, $nu$ --- полная#rf("def-complete-measure") мера. $m = mu times nu$, $C in Aa times.circle Bb$#rf("def-measure-prod"). Тогда
1. $C_x in Bb$ при почти всех $x in X$.
2. $phi(x) := nu C_x$ измерима в широком смысле#rf("def-mfn+").
3. $m C = integral_X nu C_x dif mu(x)$.
]
#proof[
*Шаг 1.* Пусть $X$ и $Y$ конечной меры, $Pp = {A times B : A in Aa, B in Bb}$, $Ee$ --- система подмножеств в $X times Y$ такая что $E in Ee <==> forall x in X space E_x in Bb$ и $phi(x) = nu E_x$ --- измеримая.
Тогда
1. $Ee$ --- симметричная система#rf("def-symm-system").
$ ((X times Y) without E)_x = Y without E_x in Bb. \
nu((X times Y) without E)_x = underbrace(nu Y, < +oo) - nu E_x space #[--- измерима как функция от $x$].
$
Значит $X times Y without E in Ee$.
2. $E_j in Ee. space E_1 subset E_2 subset ... ==> Union_(j = 1)^oo E_j in Ee$
$
(Union_(j = 1)^oo E_j)_x = Union_(j = 1)^oo (E_j)_x in Bb. \
(E_1)_x subset (E_2)_x subset ... ==> nu(Union_(j = 1)^oo (E_j)_x) = lim nu(E_j)_x,
$
по непрерывности меры снизу#rf("bottom-up-continious"), предел измерим.
3. $E_j in Ee. space E_1 supset E_2 supset ... ==> Sect_(j = 1)^oo E_j in Ee$.
Аналогично#rf("top-down-continious").
4. Значит $Ee$ --- монотонный класс#rf("def-monotonous-class").
5. $A sect B = nothing, A, B in Ee ==> A union.sq B in Ee$.
$(A union.sq B)_x = A_x union.sq B_x in Bb$. $nu (A union.sq B)_x = nu (A_x union.sq B_x) = nu A_x + nu B_x$. Это сумма измеримых функций, она измерима.
6. $Ee supset Pp$, а $Pp$ --- полукольцо (измеримых прямоугольников), поэтому по предыдущему пункту, $Ee supset$ конечное дизъюнктное объединение элементов в $Pp$. Это кольцо#rf("def-ring")!
7. $Ee$ --- симметричное и содержит кольцо, поэтому $Ee$ содержит алгебру. По теореме о монотонном классе#rf("monotonous-class-contains-borel"), $Ee supset sigma"-алгебра"$, натянутая на $Pp$, то есть $Ee supset Bb(Pp)$.
То есть мы поняли, что для любого $C in Bb(Pp)$, $C_x in Bb$ и $phi(x) = nu C_x$ измерима.
*Шаг 2: Рассмотрим $C in Bb(Pp)$*. Докажем, что $m C = integral_X phi dif mu$. Рассмотрим на $Bb(Pp)$ функцию множеств $E maps integral_X nu E_x dif mu(x)$. Докажем, что это --- мера на $Bb(Pp)$:
$
usb_(j = 1)^oo E_j maps
integral_X nu (usb_(j = 1)^oo E_j)_x dif mu(x) =
integral_X sum_(j = 1)^oo nu(E_j)_x dif mu(x) =^rf("integral-sum-perm-mfn")
sum_(j = 1)^oo integral_X nu(E_j)_x dif mu(x).
$
Эта мера и $m$ совпадают на $Pp$. По теореме о единственности продолжения меры#rf("standard-continuation-unique"), они совпадают на $Bb(Pp)$.
*Шаг 3: $C in Aa times.circle Bb$#rf("def-measure-prod"), $m C = 0$*.
Тогда существует $tilde(C) in Bb(Pp)$ такое, что $m tilde(C) = 0$ и
$tilde(C) supset C$
(у нас была теорема#rf("external-measure-through-semiring") в главе про продолжение меры, которая говорит, что такое множество всегда найдется).
Значит
$0 = m tilde(C) = integral_X nu tilde(C)_x dif mu(x) ==> nu tilde(C)_x = 0$
при почти всех $x in X$.
У нас есть включение $tilde(C)_x supset C_x$,
поэтому из-за полноты#rf("def-complete-measure") $nu$,
$C_x in Bb$ при почти всех $x in X$ и $nu C_x = 0$ почти везде.
Значит $m C = 0 = integral_X nu C_x dif mu(x)$ и $phi(x) = nu C_x$
измерима в широком смысле#rf("def-mfn+").
*Шаг 4: $C$ произвольное из $Aa times.circle Bb$*. $exists tilde(C) in Bb(Pp)$ такое, что $C = tilde(C) union.sq e$, где $m e = 0$ (следствие#rf("measurable-is-borel-plus-zero") из той самой теоремы, упомянутой на прошлом шаге). $C_x = tilde(C)_x union.sq e_x in Bb$ при почти всех $x in X$. $nu C_x = nu tilde(C)_x + nu e_x = nu tilde(C)_x$ почти везде. Значит $nu C_x$ измерима в широком смысле.
$
m C = m tilde(C) = integral_X nu tilde(C)_x dif mu(x) = integral_X nu C_x dif mu(x),
$
так как $nu C_x = nu tilde(C)_x$ при почти всех $x$.
*Шаг 5: Отказываемся от конечности мер, пользуясь тем, что $mu$ и $nu$ $sigma$-конечные*. Нарезаем на кусочки: $X = usb_(k = 1)^oo X_k$, $Y = usb_(n = 1)^oo Y_n$, $mu X_k < +oo$ и $nu Y_n < +oo$. $C = usb_(k, n = 1)^oo C_(k,n)$, где $C_(k,n) = C sect (X_k times Y_n)$. Знаем, что $(C_(k,n))_x in Bb$ при почти всех $x$, $phi_(k,n) := nu(C_(k,n))_x$ измерима в широком смысле, $m C_(k,n) = integral_X nu(C_(k,n))_x dif mu(x)$. Поймем, что если просуммировать по всем кускам, все будет хорошо:
$
C_x = usb_(k, n = 1)^oo (C_(k,n))_x in Bb "при почти всех" x
$
$
phi = sum_(k, n) phi_(k, n) - "измерима в широком смысле"
$
$
m C = sum_(k, n) m C_(k, n) = sum_(k, n) integral_X nu(C_(k, n))_x dif mu(x) =^rf("integral-sum-perm-mfn") integral_X sum_(k, n) nu(C_(k, n))_x dif mu = integral_X nu C_x dif mu(x)
$
]
#notice[
- Принцип берет имя от Бонавентуры Кавальери, который, вообще говоря, придумал "метод неделимых" --- эмпирический метод вычисления площади. Это --- его невероятно сильное обобщение с формализацией.
- $Pp(C) := {x in X: C_x != nothing}$ не всегда измеримо.
- $tilde(Pp)(C) := {x in X: nu C_x > 0}$ всегда измеримо. Поэтому вместо $X$ в интеграле можно написать множество $tilde(Pp)(С)$.
]
#def(label: "def-graph")[
$(X, Aa, mu)$ --- пространство с $sigma$-конечной мерой. $f: E --> overline(RR)$ неотрицательна.
_Подграфиком $f$ над множеством $E$_ называется множество $ Pp_f (E) := {(x, y) in E times RR: 0 <= y <= f(x)}. $
_Графиком $f$ над множеством $E$_ называется
$
Gamma_f (E) := {(x, y) in E times RR : y = f(x)}.
$
Отметим, что если функция принимает значение $plus.minus oo$, то соответствующая точка не принадлежит графику.
]
#lemma(label: "graph-measure-zero")[
Будем рассматривать меру $m := mu times lambda_1$#rf("def-measure-prod"). Если $f$ измерима, то $m Gamma_f (E) = 0$.
]
#proof[
Пусть $mu E < +oo$, $eps > 0$. $E_k := E{k eps <= f < (k + 1) eps}$. Тогда $Gamma_f (E_k) subset E_k times [k eps, (k + 1) eps)$, значит
$
Gamma_f (E) subset Union_(k in ZZ) Gamma_f (E_k) subset Union_(k in ZZ) E_k times [k eps, (k + 1) eps),\
m (Union_(k in ZZ)E_k times [k eps, (k + 1) eps)) = sum_(k in ZZ) mu E_k eps = mu E eps ==> Gamma_f (E) --> 0.
$
Если $mu E = +oo$, Порежем#rf("def-sfinite") $E = Union_(n = 1)^oo F_n$, $mu F_n < +oo$. Напомню, что произведение мер требует $sigma$-конечности каждой меры по определению#rf("def-measure-prod"). Тогда
$
Gamma_f (E) = Union_(n = 1)^oo underbrace(Gamma_f (F_n), "мера 0") = 0.
$
]
#notice[
Если $f$ не измерима, ни о чем говорить нельзя. Например, $f(x + y) = f(x) + f(y)$ имеет ужасные ненепрерывные решения, которые всюду плотны на плоскости.
]
#lemma(label: "subgraph-measurable")[
Если $f$ измерима в широком смысле#rf("def-mfn+"), то $Pp_f (E)$ измерим#rf("def-graph").
]
#proof[
Берем#rf("simple-approx") $phi_n >= 0$ --- простые. $phi_n arrow.tr f$. $Pp_(phi_n) (E)$ измерим (как конечное объединение измеримых прямоугольников#rf("def-measurable-rect")).
Попробуем зажать $Pp_f (E)$ между двумя множествами равной меры. Во-первых, для любой точки ниже графика, найдется простая, которая ее покрывает (так как $phi_n (x) arrow.tr f(x)$, то $Union_n phi_n (x) = [0, f(x)) "или" [0, f(x)]$), то есть
$
Pp_f (E) without Gamma_f (E) subset Union_(n = 1)^oo Pp_(phi_n) (E).
$
При этом, ни для какой точки выше графика, точки под $phi_n$ не найдется, поэтому
$
Union_(n = 1)^oo Pp_(phi_n) (E) subset Pp_f (E).
$
Если добавить к первому включению график слева и справа, получится
$
Pp_f (E) subset Union_(n = 1)^oo Pp_(phi_n) (E) union Gamma_f.
$
Объединив все вместе,
$
Pp_f (E) without Gamma_f (E) subset
Union_(n = 1)^oo Pp_(phi_n) (E) subset
Pp_f (E) subset
Union_(n = 1)^oo Pp_(phi_n) (E) union Gamma_f.
$
Мера второго и четвертого множества равны, так как мера графика нуль#rf("graph-measure-zero"). Значит $Pp_f (E)$ зажат между двумя множествами равной меры, а значит измерим#rf("def-complete-measure"), так как произведение мер --- стандартное продолжение#rf("def-standard-continuation"), а оно полное.
]
#th(name: "о мере подграфика", label: "subgraph-measure")[
$(X, Aa, mu)$ --- пространство с $sigma$-конечной мерой.
$f: X --> overline(RR)$, $f >= 0$, $m = mu times lambda_1$.
Тогда $f$ --- измерима в широком смысле тогда и только тогда#rf("def-mfn+"), когда $Pp_f$#rf("def-graph") измерим, и в этом случае $m Pp_f = integral_X f dif mu$.
]
#proof[
- "$==>$": лемма#rf("subgraph-measurable").
- "$<==$": Применим принцип Кавальери#rf("cavalieri") для $Pp_f$.
$
(Pp_f)_x = cases(delim: "[", [0, +oo]\, & "если" f(x) = +oo, [0, f(x)]\, & "если" f(x) < +oo).
$
Согласно принципу Кавальери, $lambda_1 (Pp_f)_x = f(x)$ измерима в широком смысле и $ m Pp_f = integral_X lambda_1 (P_f)_x dif mu(x) = integral_X f dif mu. $
]
#th(name: "Тонелли", label: "tonelli")[
$(X, Aa, mu)$, $(Y, Bb, nu)$ --- два пространства с полными $sigma$-конечными мерами, $m = mu times nu$, $f: X times Y --> [0, +oo]$ --- измерима. Тогда
1. $f_x (y) := f(x, y)$ при почти всех $x in X$ измерима как функция от $y$.
2. $phi(x) := integral_Y f(x, y) dif nu$ измерима в широком смысле.
3. $ integral_(X times Y) f dif m = integral_X phi dif mu = integral_X (integral_Y f(x, y) dif nu(y)) dif mu (x) = integral_Y (integral_X f(x, y) dif mu(x)) dif nu(x). $
]
#proof[
Тут вроде уже не так плохо...
*Шаг 1*.
Пусть $f = bb(1)_C$, где $C in A times.circle B$#rf("def-measure-prod"). Тогда $f_x (y) = bb(1)_(C_x) (y)$. По Кавальери#rf("cavalieri"),
1. при почти всех $x in X$, $C_x$ измерима относительно $nu$, значит и $f_x$ измерима как функция от $y$ относительно $nu$.
2. $phi(x) = integral_Y f_x dif nu = integral_Y bb(1)_(C_x) dif nu = nu C_x$ --- измерима в широком смысле.
3. $ integral_(X times Y) f dif m = m C = integral_X phi dif mu. $
*Шаг 2*. Если $f >= 0$ простая, то $f = sum_(k = 1)^n c_k bb(1)_(C_k)$, $C_k$ дизъюнктны:
$ integral_(X times Y) f dif mu = sum_(k = 1)^n c_k m C_k = sum_(k = 1)^n c_k integral_X (integral_Y bb(1)_(C_k) (x, y) dif nu(y)) dif mu(x) = integral_X (integral_Y f(x, y) dif nu(y)) dif mu(x) $
*Шаг 3*.
1. Если $f >= 0$ измеримая. Рассмотрим#rf("simple-approx") $psi_n --> f$ поточечно, $0 <= psi_1 <= psi_2 <= ...$. Можно записать неравенство для сечений: $0 <= (psi_1)_x <= (psi_2)_x <= ...$, значит $(psi_n)_x --> f_x$ поточечно. А поточечный предел измеримых функций измерим#rf("inf-sup-lim-mfn").
2. $phi_n (x) := integral_Y (psi_n)_x dif nu$ измерима в широком смысле и по теореме Леви#rf("levy") сходится к $integral_Y f_x dif nu$.
3. По монотонности интеграла#rf("mfn-props", "inequality") $integral_Y (psi_n)_x dif nu <= integral_Y (psi_(n + 1))_x dif nu$. Так как $integral_(X times Y) psi_n dif m = integral_(X) phi_n dif mu$ по предыдущему пункту, по теореме Леви#rf("levy"), левая часть стремится к $integral_(X times Y) f dif m$, а правая к $integral_X phi dif mu$. Получили равенство.
Разумеется, здесь мы рассмотрели сечения по $x$, но аналогично можно рассмотреть сечения $y$, и получить равенство последнему интегралу.
]
#th(name: "Фубини", label: "fubini")[
_(Везде вместо измеримости пишем суммируемость)_
$(X, Aa, mu)$, $(Y, Bb, nu)$ --- два пространства с полными $sigma$-конечными мерами, $m = mu times nu$, $f: X times Y --> overline(RR)$ --- суммируема. Тогда
1. $f_x (y) := f(x, y)$ при почти всех $x in X$ суммируема как функция от $y$.
2. $phi(x) := integral_Y f(x, y) dif nu(y)$ суммируема на $X$.
3. $ integral_(X times Y) f dif m = integral_X phi dif mu = integral_X (integral_Y f(x, y) dif nu(y)) dif mu (x) = integral_Y (integral_X f(x, y) dif mu(x)) dif nu(y). $
]
#proof[
1. $f = f_+ - f_-$, $f_x = (f_+)_x - (f_-)_x$ суммируема при почти всех $x$, так как#rf("sfn-props", "abs-bound"):
$
+oo > integral_(X times Y) abs(f) dif m =^rf("tonelli")
integral_X integral_Y abs(f(x, y)) dif nu(y) dif mu(x) ==>
integral_Y abs(f(x, y)) dif nu(y) =
integral_Y abs(f_x) dif nu < +oo
$
при почти всех $x in X$.
2. $ integral_X abs(phi) dif mu = integral_X abs(integral_Y f(x, y) dif nu(y)) dif mu (x) <= integral_X integral_Y abs(f(x, y)) dif nu(y) dif mu(x) < +oo. $
3. $ integral_(X times Y) f_(plus.minus) dif m = integral_X integral_Y f_(plus.minus) (x, y) dif nu(y) dif mu(x). $ (и вычтем)
]
#follow(label: "independent-2d-prod")[
$(X, Aa, mu)$, $(Y, Bb, nu)$ --- два пространства с полными $sigma$-конечными мерами, $m = mu times nu$. $f: X --> overline(RR)$ и $g: Y --> overline(RR)$ суммируемы. Пусть $h(x, y) = f(x) g(y)$. Тогда $h$ суммируема на $X times Y$ и $ integral_(X times Y) h dif m = integral_X f dif mu dot integral_Y g dif nu. $
]
#proof[
Если $f$ рассмотреть как функцию двух переменных, то она измерима. Тоже самое с $g$. Значит произведение измеримых функций $h$ тоже измеримо. Докажем суммируемость#rf("sfn-props", "abs-bound"):
$
integral_(X times Y) abs(h) dif mu =^"Тонелли"_rf("tonelli")
integral_X integral_Y underbrace(abs(f(x)), "не зависит от y") abs(g(y)) dif nu(y) dif mu(x)
newline(=)
integral_X abs(f(x)) underbrace(integral_Y abs(g(y)) dif nu(y), "константа от" x) dif mu(x) =
integral_X abs(f) dif mu dot integral_Y abs(g) dif nu < +oo.
$
Дальше можно записать тоже самое без модулей по теореме Фубини#rf("fubini"), получим равенство.
]
#notice[
Для справедливости формулы
$
integral_X integral_Y f(x, y) dif nu(y) dif mu(x) = integral_Y integral_X f(x, y) dif mu(x) dif nu(y)
$
не достаточно суммируемости функций $f_x (y) := f(x, y)$, $f_y (x) := f(x, y)$, $phi(x) := integral_Y f_x dif nu(y)$ и $psi(y) := integral_X f_y dif mu(x)$. Обязательна суммируемость $f(x, y)$ на $X times Y$.
]
#example[
$mu = nu = lambda_1$, $X = Y = [-1, 1]$, $f(x, y) = (x^2 - y^2)/(x^2 + y^2)^2$. Тогда $ phi(x) = integral_[-1, 1] (x^2 - y^2)/(x^2 + y^2)^2 dif y = lr(y / (x^2 + y^2) bar)_(y=-1)^(y=1) = 2 / (x^2 + 1). $
Это суммируемая функция.
$
integral_[-1, 1] phi(x) dif x = integral_(-1)^1 2 / (x^2 + 1) dif x = lr( 2 arctan x bar)_(-1)^1 = pi.
$
С другой стороны,
$
integral_[-1, 1] integral_[-1, 1] (x^2 - y^2)/(x^2 + y^2)^2 dif x dif y = -pi.
$
(тут аналогично, опустим подробности).
]
#notice[
Формула
$
integral_X integral_Y f(x, y) dif nu(y) dif mu(x) = integral_Y integral_X f(x, y) dif mu(x) dif nu(y)
$
может быть верной, и без суммируемости $f$ на $X times Y$.
]
#example[
$mu = nu = lambda_1$, $X = Y = [-1, 1]$, и $f(x, y) = (x y) / (x^2 + y^2)^2$. Равенство интегралов, очевидно есть, из-за симметричности функции. Почему суммируемости нет остается читателю в качестве упражнения.
]
#th(label: "integral-through-lebesgue-set-measure")[
$(X, Aa, mu)$ --- пространство с $sigma$-конечной мерой. Тогда $integral_E abs(f) dif mu = integral_0^(+oo) mu X{abs(f) >= t} dif t$.
]
#notice[
$mu E{abs(f) >= t}$ убывает, значит у нее более чем счетное число точек разрыва. Почему? Возьмем какую-то точку разрыва. У нее есть предел слева и предел справа, то есть это скачок. В каждом скачке рациональное число, а их не более чем счетно.
]
#proof[
Рассмотрим $m = mu times lambda_1$,
$
integral_X abs(f) dif mu =
m Pp_abs(f) =
integral_(X times [0, +oo)) bb(1)_(Pp_abs(f)) dif m =_"Тонелли"^rf("tonelli")
integral_[0, +oo) integral_X underbrace(bb(1)_(Pp_abs(f)) (x, t), = bb(1)_(X{abs(f) >= t})) dif mu(x) dif lambda_1 (t)
newline(=)
integral_[0, +oo] underbrace(integral_X bb(1)_{abs(f) >= t} dif mu, = mu X{abs(f) >= t}) dif lambda_1 (t) = integral_0^(+oo) mu X{abs(f) >= t} dif t. $
]
#follow(label: "integral-through-lebesgue-set-measure'")[
В условии теоремы можно записать строгий знак.
$(X, Aa, mu)$ --- пространство с $sigma$-конечной мерой. Тогда $integral_E abs(f) dif mu = integral_0^(+oo) mu E{abs(f) > t} dif t$.
]
#proof[
$g(t) := mu E {abs(f) >= t}$ монотонна, значит у нее не более чем счетное число точек разрыва. Пусть $t_0$ --- точка непрерывности. Тогда $t_n arrow.br t_0$ и $ E{abs(f) > t_0} = Union_(n = 1)^oo E{abs(f) >= t_n}. $
$ mu E{abs(f) > t_0} =^rf("bottom-up-continious") lim_(n -> oo) mu E{abs(f) >= t_n} = lim_(n -> oo) g(t_n) = g(t_0). $
]
#follow(label: "power-integral-through-lebesgue-set-measure")[
$ integral_E abs(f)^p dif mu = integral_0^(+oo) p t^(p - 1) mu E{abs(f) >= t} dif t. $
]
#proof[
Пусть $g(t) := mu E{abs(f) >= t}$.
$ integral_E abs(f)^p dif mu = integral_0^(+oo) underbrace(mu E{abs(f)^p >= t}, =g(t^(1/p))) dif t = integral_0^(+oo) g(t^(1/p)) dif t. $
Сделаем замену переменной в римановом интеграле: $s := t^(1/p)$:
$
integral_0^(+oo) g(t^(1/p)) dif t = integral_0^(+oo) p s^(p - 1) g(s) dif s.
$
Формально говоря, мы ее не доказывали для ненепрерывных функций, ну и ладно. Скоро появится более общая теорема#rf("substitution"), которая покроет и этот случай.
]
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-aspect_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test alignment in automatically sized square and circle.
#set text(8pt)
#box(square(inset: 4pt)[
Hey there, #align(center + bottom, rotate(180deg, [you!]))
])
#box(circle(align(center + horizon, [Hey.])))
|
https://github.com/voXrey/cours-informatique | https://raw.githubusercontent.com/voXrey/cours-informatique/main/typst/01-correction.typ | typst | #import "@preview/codly:0.2.1": *
#show: codly-init.with()
#codly()
#set text(font: "Roboto Serif")
= Part II : Analyse de Programmes <part-ii-analyse-de-programmes>
== Introduction <introduction>
Correction : Mon code produit-il le résultat attendu ?
Terminaison : Mon code répond-il un jour ?
Complexité : A quelle vitesse mon programme répond-il ?
Solution 1 : Batteries de Tests. Limitation : On ne peut pas être exhaustif, il peut toujours se produire en situation réelle une configuration non testée.
Solution 2 : Analyse mathématique
= Chapitre 1 : Correction <chapitre-1-correction>
== I - Introduction <i---introduction>
```c
void swap(a,i,j) // échange les cases i et j de a
void mystery(int len, int* a) {
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (a[i] < a[j]) swap(a,i,j);
}
}
}
```
Ce programme est-il correct ?
- Correct : fait-il ce qu’on attend de lui ?
- Ici : qu’est ce qu’on attend de lui ?
Problème : Il faut préciser ce qu’on attend d’un programme, c’est sa #strong[spécification].
Entraînement : Écrivons la spécification d’un algorithme de tri.
- On demande que le tableau :
- soit trié
- soit une permutation du tableau initial
== II - Vocabulaire <ii---vocabulaire>
Pour préciser ce qu’un programme doit faire, on donne sa #strong[spécification]. Elle est composée de :
- La #strong[précondition] : ce sont les hypothèses que l’on fait sur les arguments.
- La #strong[postcondition] : c’est ce que vérifie le résultat ou éventuellement les modifications effectuées en mémoire.
Un programme est alors #strong[correct] pour une spécification donnée si pour toute entrée du programme qui vérifie la précondition alors la sortie vérifie la postcondition.
```c
int incr(int n) {
return n+1;
}
```
Ce programme vérifie la spécification suivante :
- Précondition : `n` est pair
- Postcondition : `f(n)` est impair
```c
// Function to check if an array is sorted
bool is_sorted(int *a, int n) {
while (--n >= 1) {
if (a[n] < a[n - 1])
return false;
}
return true;
}
// Function to shuffle the elements of an array
void shuffle(int *a, int n) {
int i, t, r;
for (i = 0; i < n; i++) {
t = a[i];
r = rand() % n;
a[i] = a[r];
a[r] = t;
}
}
// BogoSort function to sort an array
void bogosort(int *a, int n) {
while (!is_sorted(a, n))
shuffle(a, n);
}
```
Le `bogosort` tire aléatoirement des permutations d’une liste (ou tableau) jusqu’à l’avoir trié.
#quote(
block: true,
)[
Remarque : On parle ici de #strong[correction partielle]. Cela consiste à démontrer que le programme est correct en supposant qu’il termine (même si cette supposition est fausse).
]
On dit qu’un programme est #strong[correct] lorsque l’on a #strong[correction partielle] + #strong[terminaison].
== III - Correction de programmes impératifs <iii---correction-de-programmes-impératifs>
```c
int max_arr(int len, int* a) {
assert(len > 0);
int m = a[0];
for (int i = 1; i < len; i++) {
m = max(a[i],m);
}
return m;
}
```
Spécification de `max_arr` :
- Précondition : `len > 0` (le tableau a est non vide)
- Postcondition : Renvoie la valeur maximale de a, c’est-à-dire $"max"_(i in \[0, "len"\[) a[i]$.
Pour cela on utilise la notion #strong[d’invariant de boucle].
Un invariant de boucle est une propriété mathématique sur les variables du programme qui :
- Est vrai avant la boucle
- Est préservée par une itération de la boucle
Cette propriété sera donc vraie à la fin de l’exécution de la boucle.
#quote(block: true)[
Remarque : Cette propriété doit impliquer la postcondition.
]
Sur l’exemple de `max_arr` : prenons comme invariant :
$ m = max_(j in \[0, i\[) a[i] $
Vérifions que c’est un bon invariant.
Avant la boucle :
$m = a lr([0])$ et $i = 1$
Or $m a x_(j in \[ 0 , i \[) a lr([j]) = a lr([0]) = m$
Donc l’invariant est vrai
Hérédité :
Si l’invariant est vrai #strong[en début de boucle] montrons qu’il sera vrai en début de boucle suivante. En effet en début de boucle on a $m a x_(j in \[ 0 , i \[) a lr([j])$.
#quote(
block: true,
)[
Notation : Par convention on note m’ et i’ les valeurs des variables m et i après une itération de boucle.
]
On a $m prime = m a x lr((a lr([i]) , m))$ et $i prime = i + 1$
Donc $m prime = m a x lr((a lr([i]) , m a x_(j in \[ 0 , i \[) a lr([j]))) = m a x_(j in lr([0 , i])) a lr([j])$
Et donc comme $i prime = i + 1$ : $m prime = m a x_(j in lr([0 , i prime - 1])) a lr([j])$
Puis on a $m prime = m a x_(j in \[ 0 , i prime \[) a lr([j])$
Donc $m = m a x_(j in \[ 0 , l e n \[) a lr([j])$
Finalement $m = m a x_(j in \[ 0 , l e n \[) a lr([j])$
C’est exactement la postcondition.
== IV - Correction de programmes Récursifs <iv---correction-de-programmes-récursifs>
```c
int fibo(int n) {
if (n == 0 || n == 1) {
return 1;
}
return fibo(n-1) + fibo(n-2);
}
```
Spécification
- Précondition : $n gt.eq 0$
- Postcondition : renvoie $u_n$ ou $u$ est définie par $u_0 = u_1 = 1$ et $u_(n + 2) = u_(n + 1) + u_n$
La correction de programme récursifs se démontre par récurrence.
Prenons l’exemple du programme ci-dessus.
Pour tout \$n \\in \\N\$ on pose $H lr((n)) : f i b o lr((n)) = u_n$
Initialisation
- Si $n = 0 , f i b o lr((0)) = 1 = u_0$
- Si $n = 1 , f i b o lr((1)) = 1 = u_1$
Hérédité
On suppose $n > 1$
$f i b o lr((n))$ renvoie $f i b o lr((n - 1)) + f i b o lr((n - 2))$
Par hypothèse de récurrence, comme $n - 1 < n$ et $n - 2 < n$ et $n - 1 gt.eq 0$, $n - 2 gt.eq 0$.
On a $f i b o lr((n - 1)) = u_(n - 1)$
Et $f i b o lr((n - 2)) = u_(n - 2)$
Or $u_n = u_(n - 1) + u_(n - 2)$
Donc $f i b o lr((n)) = u_n$
Le programme est donc correct.
Procédons à un autre exemple :
```c
int sum_arr(int len, int* a) {
if (len == 0) return 0;
return sum_arr(len-1, a) + a[len-1];
}
```
Postcondition : renvoie $sum_(j = 0)^(l e n - 1) a lr([j])$
On montre par récurrence sur `len` que la fonction est correcte c’est-à-dire elle vérifie la postcondition.
Si len \= 0 : la fonction renvoie 0. Or $s u m_(j = 0)^(l e n - 1) a lr([j]) = 0$.
Si len \> 0 : Par hypothèse de récurrence, `sum_arr(len-1, a)` renvoie $sum_(j = 0)^(l e n - 1) a lr([j])$.
Donc `sum_arr(len, a)` renvoie $a lr([l e n - 1]) + sum_(j = 0)^(l e n - 1) a lr([j]) = sum_(j = 0)^(l e n - 1) a lr([j])$.
L’invariant de boucle de la version impérative serait $S = sum_(j = 0)^(i - 1) a lr([j])$
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/table_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 14-19 expected color, gradient, pattern, none, array, or function, found string
// #table(fill: "hey") |
https://github.com/GYPpro/Java-coures-report | https://raw.githubusercontent.com/GYPpro/Java-coures-report/main/Report/1.typ | typst | #set text(font:("Times New Roman","Source Han Serif SC"))
#show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Display block code in a larger block
// with more padding.
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
#set math.equation(numbering: "(1)")
#set text(
font:("Times New Roman","Source Han Serif SC"),
style:"normal",
weight: "regular",
size: 13pt,
)
#set page(
paper:"a4",
number-align: right,
margin: (x:2.54cm,y:4cm),
header: [
#set text(
size: 25pt,
font: "KaiTi",
)
#align(
bottom + center,
[ #strong[暨南大学本科实验报告专用纸(附页)] ]
)
#line(start: (0pt,-5pt),end:(453pt,-5pt))
]
)
= 命令行编译运行
\
#text("*") 实验项目类型:设计性\
#text("*")此表由学生按顺序填写\
#text(
font:"KaiTi",
size: 15pt
)[
课程名称#underline[#text(" 面向对象程序设计/JAVA语言 ")]成绩评定#underline[#text(" ")]\
实验项目名称#underline[#text(" 命令行编译运行 ")]指导老师#underline[#text(" 干晓聪 ")]\
实验项目编号#underline[#text(" 1 ")]实验项目类型#underline[#text(" 设计性 ")]实验地点#underline[#text(" 数学系机房 ")]\
学生姓名#underline[#text(" 郭彦培 ")]学号#underline[#text(" 2022101149 ")]\
学院#underline[#text(" 信息科学技术学院 ")]系#underline[#text(" 数学系 ")]专业#underline[#text(" 信息管理与信息系统 ")]\
实验时间#underline[#text(" 2023年10月13日上午 ")]#text("~")#underline[#text(" 2023年10月13日中午 ")]\
]
#set heading(
numbering: "一、"
)
#set par( first-line-indent: 1.8em)
= 实验目的
\
#h(1.8em)学习安装、手工使用编译器
= 实验环境
\
#h(1.8em)计算机:PC X64
操作系统:Windows
编程语言:Java
IDE:Visual Studio Code
= 程序原理
\
+ 下载OPEN JDK21并加入PATH
+ 利用`javac`和`java`指令编译运行代码
#pagebreak()
= 程序代码
```java
package sis0;
class Main{
public static void main( String[] args ) throws Exception {
System.out.printf( "Hello World!\n" );
}
}
```
= 出现的问题、原因与解决方法
\
#h(1.8em)未出现问题
= 测试数据与运行结果
\
#h(1.8em)无输入数据
输出:`Hello World!` |
|
https://github.com/PgBiel/glypst | https://raw.githubusercontent.com/PgBiel/glypst/main/test/samples/warn_ok.typ | typst | MIT License | = W
**Hello world!
__Bye world!
|
https://github.com/imatpot/typst-ascii-ipa | https://raw.githubusercontent.com/imatpot/typst-ascii-ipa/main/CHANGELOG.md | markdown | MIT License | # Changelog of `ascii-ipa`
follows [semantic versioning](https://semver.org)
## 2.0.0
> [!CAUTION]
> This release contains breaking changes
- General
- **BREAKING:** Dropped support for `override-font` to avoid [`str`](https://typst.app/docs/reference/foundations/str/)/[`content`](https://typst.app/docs/reference/foundations/content/) ambiguity
- Added bracket & braces support for [precise, morphophonemic, indistinguishable, obscured, and transliterated](https://en.wikipedia.org/wiki/International_Phonetic_Alphabet#Brackets_and_transcription_delimiters) notations
- Added support for converting [`raw`](https://typst.app/docs/reference/text/raw/)
- Branner
- **BREAKING:** Infixed `))` (e.g. `t))s`) is no longer supported and must now be used as a postfix (e.g. `ts))`) as per the official specification
- Added support for more IPA characters and diacritics according to official specification
- Praat
- Added support for more IPA characters and diacritics according to official specification
- SIL
- Added support for more IPA characters and diacritics according to official specification
- Added support for subscripts
- Added support for right-bar tone glides
- Added support for left-bar tones
- Added Unicode support for hooks (palatal, retroflex)
- Added Unicode support for middle tildes (velar, pharyngeal)
- Added Unicode support for superscripts
- X-SAMPA
- Added support for more IPA characters and diacritics according to official specification
## 1.1.1
- Fixed a bug in X-SAMPA where ``` ` ``` falsely took precedence over ``` @` ``` (https://github.com/imatpot/typst-packages/issues/1)
## 1.1.0
- Translations will now return a [`str`](https://typst.app/docs/reference/foundations/str/) if the font is not overridden
- The library now explicitly exposes functions via a "gateway" entrypoint
- Update internal project structure
- Update package metadata
- Update documentation
## 1.0.0
- Initial release
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1000.typ | typst | Apache License 2.0 | #let data = (
("MYANMAR LETTER KA", "Lo", 0),
("MYANMAR LETTER KHA", "Lo", 0),
("MYANMAR LETTER GA", "Lo", 0),
("MYANMAR LETTER GHA", "Lo", 0),
("MYANMAR LETTER NGA", "Lo", 0),
("MYANMAR LETTER CA", "Lo", 0),
("MYANMAR LETTER CHA", "Lo", 0),
("MYANMAR LETTER JA", "Lo", 0),
("MYANMAR LETTER JHA", "Lo", 0),
("MYANMAR LETTER NYA", "Lo", 0),
("MYANMAR LETTER NNYA", "Lo", 0),
("MYANMAR LETTER TTA", "Lo", 0),
("MYANMAR LETTER TTHA", "Lo", 0),
("MYANMAR LETTER DDA", "Lo", 0),
("MYANMAR LETTER DDHA", "Lo", 0),
("MYANMAR LETTER NNA", "Lo", 0),
("MYANMAR LETTER TA", "Lo", 0),
("MYANMAR LETTER THA", "Lo", 0),
("MYANMAR LETTER DA", "Lo", 0),
("MYANMAR LETTER DHA", "Lo", 0),
("MYANMAR LETTER NA", "Lo", 0),
("MYANMAR LETTER PA", "Lo", 0),
("MYANMAR LETTER PHA", "Lo", 0),
("MYANMAR LETTER BA", "Lo", 0),
("MYANMAR LETTER BHA", "Lo", 0),
("MYANMAR LETTER MA", "Lo", 0),
("MYANMAR LETTER YA", "Lo", 0),
("MYANMAR LETTER RA", "Lo", 0),
("MYANMAR LETTER LA", "Lo", 0),
("MYANMAR LETTER WA", "Lo", 0),
("MYANMAR LETTER SA", "Lo", 0),
("MYANMAR LETTER HA", "Lo", 0),
("MYANMAR LETTER LLA", "Lo", 0),
("MYANMAR LETTER A", "Lo", 0),
("MYANMAR LETTER SHAN A", "Lo", 0),
("MYANMAR LETTER I", "Lo", 0),
("MYANMAR LETTER II", "Lo", 0),
("MYANMAR LETTER U", "Lo", 0),
("MYANMAR LETTER UU", "Lo", 0),
("MYANMAR LETTER E", "Lo", 0),
("MYANMAR LETTER MON E", "Lo", 0),
("MYANMAR LETTER O", "Lo", 0),
("MYANMAR LETTER AU", "Lo", 0),
("MYANMAR VOWEL SIGN TALL AA", "Mc", 0),
("MYANMAR VOWEL SIGN AA", "Mc", 0),
("MYANMAR VOWEL SIGN I", "Mn", 0),
("MYANMAR VOWEL SIGN II", "Mn", 0),
("MYANMAR VOWEL SIGN U", "Mn", 0),
("MYANMAR VOWEL SIGN UU", "Mn", 0),
("MYANMAR VOWEL SIGN E", "Mc", 0),
("MYANMAR VOWEL SIGN AI", "Mn", 0),
("MYANMAR VOWEL SIGN MON II", "Mn", 0),
("MYANMAR VOWEL SIGN MON O", "Mn", 0),
("MYANMAR VOWEL SIGN E ABOVE", "Mn", 0),
("MYANMAR SIGN ANUSVARA", "Mn", 0),
("MYANMAR SIGN DOT BELOW", "Mn", 7),
("MYANMAR SIGN VISARGA", "Mc", 0),
("MYANMAR SIGN VIRAMA", "Mn", 9),
("MYANMAR SIGN ASAT", "Mn", 9),
("MYANMAR CONSONANT SIGN MEDIAL YA", "Mc", 0),
("MYANMAR CONSONANT SIGN MEDIAL RA", "Mc", 0),
("MYANMAR CONSONANT SIGN MEDIAL WA", "Mn", 0),
("MYANMAR CONSONANT SIGN MEDIAL HA", "Mn", 0),
("MYANMAR LETTER GREAT SA", "Lo", 0),
("MYANMAR DIGIT ZERO", "Nd", 0),
("MYANMAR DIGIT ONE", "Nd", 0),
("MYANMAR DIGIT TWO", "Nd", 0),
("MYANMAR DIGIT THREE", "Nd", 0),
("MYANMAR DIGIT FOUR", "Nd", 0),
("MYANMAR DIGIT FIVE", "Nd", 0),
("MYANMAR DIGIT SIX", "Nd", 0),
("MYANMAR DIGIT SEVEN", "Nd", 0),
("MYANMAR DIGIT EIGHT", "Nd", 0),
("MYANMAR DIGIT NINE", "Nd", 0),
("MYANMAR SIGN LITTLE SECTION", "Po", 0),
("MYANMAR SIGN SECTION", "Po", 0),
("MYANMAR SYMBOL LOCATIVE", "Po", 0),
("MYANMAR SYMBOL COMPLETED", "Po", 0),
("MYANMAR SYMBOL AFOREMENTIONED", "Po", 0),
("MYANMAR SYMBOL GENITIVE", "Po", 0),
("MYANMAR LETTER SHA", "Lo", 0),
("MYANMAR LETTER SSA", "Lo", 0),
("MYANMAR LETTER VOCALIC R", "Lo", 0),
("MYANMAR LETTER VOCALIC RR", "Lo", 0),
("MYANMAR LETTER VOCALIC L", "Lo", 0),
("MYANMAR LETTER VOCALIC LL", "Lo", 0),
("MYANMAR VOWEL SIGN VOCALIC R", "Mc", 0),
("MYANMAR VOWEL SIGN VOCALIC RR", "Mc", 0),
("MYANMAR VOWEL SIGN VOCALIC L", "Mn", 0),
("MYANMAR VOWEL SIGN VOCALIC LL", "Mn", 0),
("MYANMAR LETTER MON NGA", "Lo", 0),
("MYANMAR LETTER MON JHA", "Lo", 0),
("MYANMAR LETTER MON BBA", "Lo", 0),
("MYANMAR LETTER MON BBE", "Lo", 0),
("MYANMAR CONSONANT SIGN MON MEDIAL NA", "Mn", 0),
("MYANMAR CONSONANT SIGN MON MEDIAL MA", "Mn", 0),
("MYANMAR CONSONANT SIGN MON MEDIAL LA", "Mn", 0),
("MYANMAR LETTER SGAW KAREN SHA", "Lo", 0),
("MYANMAR VOWEL SIGN SGAW KAREN EU", "Mc", 0),
("MYANMAR TONE MARK SGAW KAREN HATHI", "Mc", 0),
("MYANMAR TONE MARK SGAW KAREN KE PHO", "Mc", 0),
("MYANMAR LETTER WESTERN PWO KAREN THA", "Lo", 0),
("MYANMAR LETTER WESTERN PWO KAREN PWA", "Lo", 0),
("MYANMAR VOWEL SIGN WESTERN PWO KAREN EU", "Mc", 0),
("MYANMAR VOWEL SIGN WESTERN PWO KAREN UE", "Mc", 0),
("MYANMAR SIGN WESTERN PWO KAREN TONE-1", "Mc", 0),
("MYANMAR SIGN WESTERN PWO KAREN TONE-2", "Mc", 0),
("MYANMAR SIGN WESTERN PWO KAREN TONE-3", "Mc", 0),
("MYANMAR SIGN WESTERN PWO KAREN TONE-4", "Mc", 0),
("MYANMAR SIGN WESTERN PWO KAREN TONE-5", "Mc", 0),
("MYANMAR LETTER EASTERN PWO KAREN NNA", "Lo", 0),
("MYANMAR LETTER EASTERN PWO KAREN YWA", "Lo", 0),
("MYANMAR LETTER EASTERN PWO KAREN GHWA", "Lo", 0),
("MYANMAR VOWEL SIGN GEBA KAREN I", "Mn", 0),
("MYANMAR VOWEL SIGN KAYAH OE", "Mn", 0),
("MYANMAR VOWEL SIGN KAYAH U", "Mn", 0),
("MYANMAR VOWEL SIGN KAYAH EE", "Mn", 0),
("MYANMAR LETTER SHAN KA", "Lo", 0),
("MYANMAR LETTER SHAN KHA", "Lo", 0),
("MYANMAR LETTER SHAN GA", "Lo", 0),
("MYANMAR LETTER SHAN CA", "Lo", 0),
("MYANMAR LETTER SHAN ZA", "Lo", 0),
("MYANMAR LETTER SHAN NYA", "Lo", 0),
("MYANMAR LETTER SHAN DA", "Lo", 0),
("MYANMAR LETTER SHAN NA", "Lo", 0),
("MYANMAR LETTER SHAN PHA", "Lo", 0),
("MYANMAR LETTER SHAN FA", "Lo", 0),
("MYANMAR LETTER SHAN BA", "Lo", 0),
("MYANMAR LETTER SHAN THA", "Lo", 0),
("MYANMAR LETTER SHAN HA", "Lo", 0),
("MYANMAR CONSONANT SIGN SHAN MEDIAL WA", "Mn", 0),
("MYANMAR VOWEL SIGN SHAN AA", "Mc", 0),
("MYANMAR VOWEL SIGN SHAN E", "Mc", 0),
("MYANMAR VOWEL SIGN SHAN E ABOVE", "Mn", 0),
("MYANMAR VOWEL SIGN SHAN FINAL Y", "Mn", 0),
("MYANMAR SIGN SHAN TONE-2", "Mc", 0),
("MYANMAR SIGN SHAN TONE-3", "Mc", 0),
("MYANMAR SIGN SHAN TONE-5", "Mc", 0),
("MYANMAR SIGN SHAN TONE-6", "Mc", 0),
("MYANMAR SIGN SHAN COUNCIL TONE-2", "Mc", 0),
("MYANMAR SIGN SHAN COUNCIL TONE-3", "Mc", 0),
("MYANMAR SIGN SHAN COUNCIL EMPHATIC TONE", "Mn", 220),
("MYANMAR LETTER RUMAI PALAUNG FA", "Lo", 0),
("MYANMAR SIGN RUMAI PALAUNG TONE-5", "Mc", 0),
("MYANMAR SHAN DIGIT ZERO", "Nd", 0),
("MYANMAR SHAN DIGIT ONE", "Nd", 0),
("MYANMAR SHAN DIGIT TWO", "Nd", 0),
("MYANMAR SHAN DIGIT THREE", "Nd", 0),
("MYANMAR SHAN DIGIT FOUR", "Nd", 0),
("MYANMAR SHAN DIGIT FIVE", "Nd", 0),
("MYANMAR SHAN DIGIT SIX", "Nd", 0),
("MYANMAR SHAN DIGIT SEVEN", "Nd", 0),
("MYANMAR SHAN DIGIT EIGHT", "Nd", 0),
("MYANMAR SHAN DIGIT NINE", "Nd", 0),
("MYANMAR SIGN KHAMTI TONE-1", "Mc", 0),
("MYANMAR SIGN KHAMTI TONE-3", "Mc", 0),
("MYANMAR VOWEL SIGN AITON A", "Mc", 0),
("MYANMAR VOWEL SIGN AITON AI", "Mn", 0),
("MYANMAR SYMBOL SHAN ONE", "So", 0),
("MYANMAR SYMBOL SHAN EXCLAMATION", "So", 0),
)
|
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Code/compareFields2.typ | typst | #import("../Template/customFunctions.typ"): *
#codly(annotations:(
(
start: 12,
end: 26,
label: <compareArrayField>
),
(
start: 28,
end: 37,
label: <comparePrimitiveField>
),
),
highlights:(
(line:2, label: <compareTranslations>),
)
)
```ts
const compareTranslations = (unchangedObject: any, newObject: any, baseFieldName: string) => {
unchangedObject.translations.forEach((oldTranslationObject: any, index: any) => {
const newTranslationObject = newObject.translations.find((newTranslation: any) => newTranslation.languageId === oldTranslationObject.languageId);
const languageAbbreviation = languages.find(l => l.id === oldTranslationObject.languageId)?.abbreviation;
if (newTranslationObject && languageAbbreviation) {
compareTranslationFields(oldTranslationObject, newTranslationObject, baseFieldName, languageAbbreviation);
}
});
};
...
const compareArrayField = (unchangedObject: any, newObject: any, baseFieldName: string, field: string) => {
const unchangedObjectIds = unchangedObject[field].map((obj: any) => obj.id);
const newObjectIds = newObject[field].map((obj: any) => obj.id);
// Check if the arrays contain the same elements, ignore the order
if (JSON.stringify(unchangedObjectIds.sort()) !== JSON.stringify(newObjectIds.sort())) {
changes.push({
field: `${baseFieldName}.${String(field)}`,
oldValue: unchangedObjectIds,
newValue: newObjectIds
});
}
};
const comparePrimitiveField = (unchangedObject: any, newObject: any, baseFieldName: string, field: string) => {
if (unchangedObject[field] !== newObject[field]) {
changes.push({
field: `${baseFieldName}.${String(field)}`,
oldValue: unchangedObject[field],
newValue: newObject[field]
});
}
};
``` |
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/casoslov/postne_casy/cas6.typ | typst | #import "/style.typ": *
#import "/SK/texts.typ": *
#import "../styleCasoslov.typ": *
= Šiesty pôstny čas
#show: rest => columns(2, rest)
#nacaloBezKnaza
#zalm(53)
#zalm(54)
#zalm(90)
#si
#lettrine("Aleluja, aleluja, aleluja, sláva tebe, Bože.") #note[(3x)]
#lettrine("Pane, zmiluj sa.") #note[(3x)]
== Katizma
#note("Berieme katizmu podľa predpisu.")
== Tropáre
#centerNote("2. hlas")
#lettrine("Ty si v šiesty deň a o šiestej hodine * na kríž pribil trúfalý Adamov hriech v raji spáchaný. * Roztrhaj tiež dlžobný úpis našich prehrešení, * Kriste, Bože, a zachráň nás.")
#vers("Čuj, Bože, moju modlitbu, * pred mojou úpenlivou prosbou sa neskrývaj.")
#lettrine("Ty si v šiesty deň a o šiestej hodine...")
#vers("Ja však budem volať k Bohu * a Pán ma zachráni.")
#lettrine("Ty si v šiesty deň a o šiestej hodine...")
#primText[I teraz: (Bohorodičník)]
#lettrine("Keďže nemáme dostatok odvahy pre množstvo našich hriechov, * ty, Bohorodička Panna, pros toho, ktorý sa z teba narodil, * veď mnoho zmôže modlitba Matky k Vládcovej dobrosrdečnosti. * Neprehliadni modlitby hriešnych, Prečistá, * lebo ten, ktorý sa rozhodol aj trpieť za nás, * je milosrdný a má moc zachrániť.")
== Tropár proroctva
#centerNote("3. hlas")
#lettrine("Pretože naše neprávosti sa proti nám postavili, * ty Pane povstaň a príď nám na pomoc. ** Veď ty si náš otec a okrem teba iného nepoznáme.")
#si
#lettrine("Pretože naše neprávosti...")
== Čítanie
#prokimen(4, "Tvoje oltáre, Pane mocností, Kráľu môj a Bože môj.", "Aké milé sú tvoje príbytky, Pane mocností.")
#note("Berieme čítanie z pôstnej triódy.")
#prokimen(8, "Pane, ukáž nám svoje milosrdenstvo a daruj nám svoju spásu.", "Pane, preukázal si milosť svojej krajine, Jakuba si zbavil poroby.")
#zoznam((
"Pane, príď nám čím skôr v ústrety so svojím milosrdenstvom, * lebo sme veľmi úbohí. * Pre slávu svojho mena nám pomôž, Bože, naša spása, * a vysloboď nás; * a pre svoje meno odpusť nám hriechy.",
))
#trojsvatePoOtcenas
== Tropáre
#centerNote("2. hlas")
#lettrine("Vykonal si spásu uprostred zeme, Kriste Bože, * keď si rozpäl svoje prečisté ruky na kríži, * a tak si zhromaždil všetky národy, * ktoré ti volajú: Pane, sláva tebe.")
#secText[Sláva:]
#lettrine("Klaniame sa tvojmu prečistému obrazu, Dobrotivý, * prosiac odpustenie našich prehrešení, <NAME>. * Veď ty si dobrovoľne dovolil pribiť svoje telo na kríž, * aby si vyslobodil svoje stvorenie z otroctva nepriateľa. * Preto ti vďačne spievame: * „Spasiteľ náš, všetko si naplnil radosťou, keď si prišiel spasiť svet.“")
#secText[I teraz:]
#centerNote[Ak je pondelok, utorok alebo štvrtok:] #lettrine("Bohorodička, ty si prameň milosrdenstva, * urob nás hodnými tvojho súcitu, * pozri na hriešny ľud, a tak ako vždy, prejav svoju silu, veď v teba dúfame. * Raduj sa, spievame, ako kedysi Gabriel, veľvojvodca beztelesných síl.")
#centerNote[Ak je streda alebo piatok:] #lettrine("Preslávna si, panenská Bohorodička, preto ťa ospevujeme, * veď kríž tvojho Syna premohol peklo a smrť navždy zničil, * nás mŕtvych vzkriesil a život nám daroval, * znova nás uviedol do strateného raja. * Preto dobrorečíme Kristovi a chválospevom ho oslavujeme * ako všemohúceho Boha, plného milosrdenstva.")
#lettrine("Pane, zmiluj sa.") #primText([40x])
#vKazdomCase
#ektenia(3)
#lettrine("Čestnejšia si ako cherubíni * a neporovnateľne slávnejšia ako serafíni, * bez porušenia si porodila Boha Slovo, * opravdivá Bohorodička, velebíme ťa.")
Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami.
#efrem
#trojsvatePoOtcenas
#lettrine("Pane, zmiluj sa.") #note[(12x)]
#lettrine("Bože a Pane mocností, Tvorca celého sveta, pre milosrdenstvo tvojej nenapodobiteľnej veľkodušnosti si zoslal svojho jednorodeného Syna, nášho Pána Ježiša Krista, aby zachránil náš rod. Úctyhodným Krížom si roztrhal dlžobný úpis našich hriechov, a tak si zvíťazil nad kniežatstvami a mocnosťami temnoty. Ty sám, Vládca, milujúci človeka, prijmi aj tieto ďakovné a prosebné modlitby nás hriešnych, osloboď nás od každého zhubného a temného prehrešenia a od všetkých viditeľných i neviditeľných nepriateľov, ktorí sa nám usilujú ublížiť. Prikovaj naše telá k bázni pred tebou a neodkloň naše srdcia k zlým slovám alebo myšlienkam, ale tvojou láskou zraň naše duše. Nech k tebe ustavične vzhliadame a nech nás vedie tvoje svetlo, aby sme pozerali na teba, neprístupné a večné svetlo a vzdávali tak neprestajnú chválu a vďaku tebe, Otcovi, ktorý nemá počiatku, spolu s tvojím jednorodeným Synom i s tvojím presvätým, dobrým a životodarným Duchom, teraz i vždycky i na veky vekov. Amen.")
#prepustenieMaleBezKnaza |
|
https://github.com/jamesrswift/typst-chem-par | https://raw.githubusercontent.com/jamesrswift/typst-chem-par/main/src/rules/isomers.typ | typst | MIT License | #import "../stateful.typ": *
#let isomers(body) = {
show regex("(((iso)|(sec)|(tert)|(cis)|(trans)|(syn)|(anti)|(endo)|(exo)|[iompnNO])-)|([N][,′'’])"): (it) => context {
if-state-enabled( it , {
show "-": "–"
emph(it)
})
}
body
}
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-3040.typ | typst | Apache License 2.0 | #let data = (
(),
("HIRAGANA LETTER SMALL A", "Lo", 0),
("HIRAGANA LETTER A", "Lo", 0),
("HIRAGANA LETTER SMALL I", "Lo", 0),
("HIRAGANA LETTER I", "Lo", 0),
("HIRAGANA LETTER SMALL U", "Lo", 0),
("HIRAGANA LETTER U", "Lo", 0),
("HIRAGANA LETTER SMALL E", "Lo", 0),
("HIRAGANA LETTER E", "Lo", 0),
("HIRAGANA LETTER SMALL O", "Lo", 0),
("HIRAGANA LETTER O", "Lo", 0),
("HIRAGANA LETTER KA", "Lo", 0),
("HIRAGANA LETTER GA", "Lo", 0),
("HIRAGANA LETTER KI", "Lo", 0),
("HIRAGANA LETTER GI", "Lo", 0),
("HIRAGANA LETTER KU", "Lo", 0),
("HIRAGANA LETTER GU", "Lo", 0),
("HIRAGANA LETTER KE", "Lo", 0),
("HIRAGANA LETTER GE", "Lo", 0),
("HIRAGANA LETTER KO", "Lo", 0),
("HIRAGANA LETTER GO", "Lo", 0),
("HIRAGANA LETTER SA", "Lo", 0),
("HIRAGANA LETTER ZA", "Lo", 0),
("HIRAGANA LETTER SI", "Lo", 0),
("HIRAGANA LETTER ZI", "Lo", 0),
("HIRAGANA LETTER SU", "Lo", 0),
("HIRAGANA LETTER ZU", "Lo", 0),
("HIRAGANA LETTER SE", "Lo", 0),
("HIRAGANA LETTER ZE", "Lo", 0),
("HIRAGANA LETTER SO", "Lo", 0),
("HIRAGANA LETTER ZO", "Lo", 0),
("HIRAGANA LETTER TA", "Lo", 0),
("HIRAGANA LETTER DA", "Lo", 0),
("HIRAGANA LETTER TI", "Lo", 0),
("HIRAGANA LETTER DI", "Lo", 0),
("HIRAGANA LETTER SMALL TU", "Lo", 0),
("HIRAGANA LETTER TU", "Lo", 0),
("HIRAGANA LETTER DU", "Lo", 0),
("HIRAGANA LETTER TE", "Lo", 0),
("HIRAGANA LETTER DE", "Lo", 0),
("HIRAGANA LETTER TO", "Lo", 0),
("HIRAGANA LETTER DO", "Lo", 0),
("HIRAGANA LETTER NA", "Lo", 0),
("HIRAGANA LETTER NI", "Lo", 0),
("HIRAGANA LETTER NU", "Lo", 0),
("HIRAGANA LETTER NE", "Lo", 0),
("HIRAGANA LETTER NO", "Lo", 0),
("HIRAGANA LETTER HA", "Lo", 0),
("HIRAGANA LETTER BA", "Lo", 0),
("HIRAGANA LETTER PA", "Lo", 0),
("HIRAGANA LETTER HI", "Lo", 0),
("HIRAGANA LETTER BI", "Lo", 0),
("HIRAGANA LETTER PI", "Lo", 0),
("HIRAGANA LETTER HU", "Lo", 0),
("HIRAGANA LETTER BU", "Lo", 0),
("HIRAGANA LETTER PU", "Lo", 0),
("HIRAGANA LETTER HE", "Lo", 0),
("HIRAGANA LETTER BE", "Lo", 0),
("HIRAGANA LETTER PE", "Lo", 0),
("HIRAGANA LETTER HO", "Lo", 0),
("HIRAGANA LETTER BO", "Lo", 0),
("HIRAGANA LETTER PO", "Lo", 0),
("HIRAGANA LETTER MA", "Lo", 0),
("HIRAGANA LETTER MI", "Lo", 0),
("HIRAGANA LETTER MU", "Lo", 0),
("HIRAGANA LETTER ME", "Lo", 0),
("HIRAGANA LETTER MO", "Lo", 0),
("HIRAGANA LETTER SMALL YA", "Lo", 0),
("HIRAGANA LETTER YA", "Lo", 0),
("HIRAGANA LETTER SMALL YU", "Lo", 0),
("HIRAGANA LETTER YU", "Lo", 0),
("HIRAGANA LETTER SMALL YO", "Lo", 0),
("HIRAGANA LETTER YO", "Lo", 0),
("HIRAGANA LETTER RA", "Lo", 0),
("HIRAGANA LETTER RI", "Lo", 0),
("HIRAGANA LETTER RU", "Lo", 0),
("HIRAGANA LETTER RE", "Lo", 0),
("HIRAGANA LETTER RO", "Lo", 0),
("HIRAGANA LETTER SMALL WA", "Lo", 0),
("HIRAGANA LETTER WA", "Lo", 0),
("HIRAGANA LETTER WI", "Lo", 0),
("HIRAGANA LETTER WE", "Lo", 0),
("HIRAGANA LETTER WO", "Lo", 0),
("HIRAGANA LETTER N", "Lo", 0),
("HIRAGANA LETTER VU", "Lo", 0),
("HIRAGANA LETTER SMALL KA", "Lo", 0),
("HIRAGANA LETTER SMALL KE", "Lo", 0),
(),
(),
("COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK", "Mn", 8),
("COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK", "Mn", 8),
("KATAKANA-HIRAGANA VOICED SOUND MARK", "Sk", 0),
("KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK", "Sk", 0),
("HIRAGANA ITERATION MARK", "Lm", 0),
("HIRAGANA VOICED ITERATION MARK", "Lm", 0),
("HIRAGANA DIGRAPH YORI", "Lo", 0),
)
|
https://github.com/ShapeLayer/ucpc-solutions__typst | https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/lib/presets/presets.typ | typst | Other | #import "./difficulties.typ": difficulties
|
https://github.com/wade-cheng/typst-mla | https://raw.githubusercontent.com/wade-cheng/typst-mla/main/README.md | markdown | MIT License | # Typst MLA
`mla.typ` is a custom [typst](https://typst.app/) template to format documents in MLA. See example document at `main.pdf`.
https://github.com/wychwitch/typst-mla9-template is more feature-complete. However, because of https://github.com/typst/typst/issues/311, the first paragraph after a heading is not indented. This issue is not fixed as of 17 April, 2024. This template fixes this issue via a hacky workaround, but again, is less feature complete than wychwitch's. |
https://github.com/MrToWy/Bachelorarbeit | https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Chapters/4-Implementierung.typ | typst | #import "../abbreviations.typ": *
#import "../Template/customFunctions.typ": *
= Implementierung <implementierung>
Nachdem in @entwurf das System geplant wurde, soll nun in diesem Kapitel das System erstellt werden. Zunächst wird das Backend vorbereitet. Hierzu wird in @schema als erstes die Datenbank an das neue Schema angepasst, um im Anschluss die geplanten Endpunkte implementieren zu können. Sobald das Backend vollständig ist, kann das Frontend die benötigten Daten abrufen. Deshalb wird erst im zweiten Schritt dann in @createFrontend das Frontend erstellt. In @createDocumentation ist beschrieben, wie das System dokumentiert wurde. Abschließend wurde das System für ein Deployment mit Podman vorbereitet (@podman).
== Backend <createBackend>
Das Backend wird im Folgenden auch als API bezeichnet und greift auf verschiedene andere Komponenten zu. Es gibt eine Datenbank, in der die Informationen zu den Modulen, Usern und die Änderungshistorie gespeichert werden. Außerdem gibt es die API selbst, die Daten aus der Datenbank lädt und mithilfe von HTTP-Endpunkten an das Frontend weitergibt. Zuletzt gibt es ein Python-Skript und einen Docker-Container, welche für die einzelnen Studiengänge die Modulhandbücher als PDF generieren. In den folgenden Unterabschnitten ist die Implementierung der genannten Komponenten beschrieben.
//#imageFigure(<architectureDiagram>, "Architektur.png", "Komponenten des Systems")
#block(breakable: false)[
=== Datenbank <schema>
Im ersten Schritt wurde das vorhandene Datenbankschema an das in @dbschema erstellte Schema angeglichen.
Hierzu musste die in @dbstructure gezeigte schema.prisma-Datei bearbeitet werden. In der Prisma-Datei entspricht ein wie in @moduletable gezeigter Block einer Tabelle in der Datenbank. Einzelne Zeilen innerhalb des Blocks entsprechen Spalten in der Tabelle. Neben der Id-Zeile in @moduletable ist zu sehen, wie eine selbstständig hoch zählende Zahl möglich ist. Außerdem können in der Prisma-Datei Relationen zwischen Tabellen definiert werden, indem hinter eine entsprechende Zeile \@relation geschrieben wird. @RelationsReferencePrisma Hierbei ist zu beachten, dass immer in beiden Tabellen eine \@relation definiert werden muss. (siehe @moduleprismanew Zeile 4). Mithilfe von Konsolenbefehlen kann dann die Prisma-Datei auf die Datenbank angewendet werden.@PrismaSchemaOverview
]
#codeFigure("Beispiel für Relations-Felder", <moduleprismanew>, "modulePrismaNew")
Bei dem Prozess, die vorhandene Datenstruktur zu ändern, gingen die Test-Daten verloren. Es wurde kein Aufwand investiert, um die Migration verlustfrei zu gestalten. Nach Fertigstellung der Datenstruktur sollen die vom Studiendekan ermittelten Daten in die Datenbank eingesetzt werden, da diese auf einem neueren Stand sind, bereits geprüft wurden und vollständig sein sollten.
Die Datenübernahme wurde mithilfe von Python umgesetzt. Bei der Erstellung des Skripts wurde darauf geachtet, dass es bei jeder Ausführung zunächst die neue Datenbank leert, um anschließend die Daten von der alten Datenbank in die neue Datenbank zu kopieren. Anschließend wurden die Daten der verschiedenen Tabellen eingelesen, auf das neue Format konvertiert und in die neue Datenbank eingesetzt. Die hierzu genutzten Insert-Statements mussten aufgrund der Abhängigkeiten zwischen den verschiedenen Tabellen in einer bestimmten Reihenfolge erfolgen. Weil beispielsweise jedes Modul einem Studiengang zugewiesen wird, müssen erst alle Studiengänge in die Datenbank eingesetzt werden, bevor deren Module eingesetzt werden können.
=== HTTP-Endpunkte <createEndpoints>
Nachdem die Datenbank vorbereitet war, konnten nun die benötigten Endpunkte im Backend angelegt werden.
Hierzu wurden zunächst Controller-Klassen für die verschiedenen Entitäten angelegt. Beispielsweise wird ein DegreeController benötigt (@degreeController), um die #link(<degreesEndpoint>)[Endpunkte für Studiengänge] bereitzustellen. Innerhalb der Controller wurde anschließend für jeden benötigten Endpunkt eine Methode erstellt und mithilfe von Dekoratoren näher beschrieben. @ControllersDocumentationNestJS
Der `@Controller`-Dekorator (@controllerDecorator) sorgt dafür, dass NestJS die Klasse als Controller identifiziert und entsprechend die enthaltenen Endpunkte bereitstellt. Außerdem ist als Parameter angegeben, unter welchem Pfad die Endpunkte erreichbar sind (hier: /degrees).
Der `@ApiTags`-Dekorator (@apiTags) sorgt dafür, dass die Endpunkte in der automatisch generierten Dokumentation der API gruppiert in der Gruppe "Degrees" dargestellt werden. Weiterhin werden die Methoden für die Endpunkte mit einem Dekorator versehen, der die HTTP-Methode angibt, die genutzt werden muss, um den Endpunkt aufzurufen (@getDecorator). @nestjs Wenn der Endpunkt `/degrees` per GET-Request aufgerufen wird, wird das Ergebnis der findAll-Methode zurückgegeben. Wenn der Endpunkt `/degrees/5` aufgerufen wird, wird das Ergebnis der findOne-Methode zurückgegeben. Die findOne-Methode erhält außerdem weitere Parameter, die auch in vielen anderen Methoden im Backend ähnlich genutzt werden. Der erste Parameter enthält die Id aus dem Pfad der Anfrage (im Beispiel /degrees/5, wäre das die 5). Der zweite Parameter enthält ein Request-Objekt. Dieses wird genutzt, um die in dem Request übergebenen Header auszulesen. Im aktuellen Beispiel wird die angefragte Sprache ausgelesen, um vom DegreeService Informationen in der Sprache des Benutzers zu erhalten.
Über den Constructor (@constructor) werden per Dependency Injection @DependencyInjectionAngular die benötigten Services übergeben. Das Framework nest.js sorgt dafür, dass die Services einmalig instanziiert werden. Das Instanziieren muss also nicht selbst unternommen werden und durch die einmalige Instanziierung kann die Performance der Anwendung verbessert werden. @nestDocumentation
#codeFigure("degree.controller.ts (Auszug)", <degreeController>, "degree.controller")
#heading("Datenverändernde Endpunkte", level: 4, numbering: none, outlined: false)
Die Endpunkte, die Daten erstellen oder bearbeiten sind verglichen mit den bisher vorgestellten Endpunkten weitaus komplexer, sodass es mehrere Design-Entscheidungen zu treffen gibt.
Das aufrufende System (hier das Frontend) sendet Daten im JSON-Format an das Backend.
Ein erster Ansatz zur Erstellung einer Methode für das Erstellen und Bearbeiten eines Moduls ist es, das erhaltene JSON direkt an den Prisma-Client zu übergeben und zu hoffen, dass der Prisma-Client das JSON korrekt verarbeitet.
Allerdings gibt es bei diesem Ansatz gleich mehrere Hindernisse.
Wenn das JSON nur aus einfachen Datentypen wie Zeichenketten, Zahlen und Booleans bestehen würde, wäre der erste Ansatz ausreichend. Da das Modul-JSON jedoch auch Objekte und Arrays enthält, müssen diese zunächst herausgefiltert werden, weil Prisma sonst nicht weiß, wie mit den Objekten und Arrays umgegangen werden soll. Das Herausfiltern kann mithilfe von "destructuring assignment" @DestructuringAssignmentJavaScript2023 erledigt werden (siehe @extractComplexFields). Hierbei werden die Eigenschaften mit komplexeren Datentypen aus dem JSON (moduleDto) extrahiert und für die spätere Verwendung in eigene Variablen gespeichert. Die verbleibenden Eigenschaften befinden sich anschließend im Objekt "moduleData" (@moduleData).
Dieses Objekt kann dann tatsächlich direkt an den Prisma-Client übergeben werden, um die darin enthaltenen Werte in die Datenbank zu schreiben (@moduleData2).
Die zuvor extrahierten Daten können nun separat behandelt werden.
In @connectResponsible ist zu sehen, wie die Eigenschaft der Verantwortlichen Person (@responsible) gesetzt wird. Da beim Erstellen eines Moduls eine verantwortliche Person aus einem Dropdown ausgewählt wird, muss im Backend kein neuer Eintrag für die Person angelegt werden. Stattdessen muss der Eintrag des Moduls nur eine Referenz auf die ausgewählte, bereits in der Datenbank bestehende Person erhalten. Dies ist wie im Beispiel gezeigt mit der Funktion connect @RelationQueriesConcepts möglich. Auf die gleiche Art kann auch bei der Bearbeitung eines Moduls eine andere Person gesetzt werden. Die Funktion connect ändert im Hintergrund einfach die Eigenschaft responsibleId in der Modultabelle.
Auch für n-m-Beziehungen könnte die connect-Funktion von Prisma genutzt werden.
Ein Modul hat Voraussetzungen (Requirements). Eine Voraussetzung könnte es sein, dass die Module BIN-100 und BIN-101 abgeschlossen sein müssen. Ein Modul hat also eine Voraussetzung und eine Voraussetzung hat 0 bis n viele Module. Übergibt man die gewünschten Modul-Ids mit der Funktion connect, erstellt Prisma die benötigten Einträge in einer Zwischentabelle, um die Beziehung abzubilden. Allerdings werden dabei die bereits vorhandenen Einträge nicht automatisch gelöscht. Das Löschen der bereits vorhandenen Einträge muss manuell angefordert werden. Dies ist beispielsweise möglich, indem der set-Methode ein leeres Array übergeben wird. (siehe @clearModules). Alternativ kann auch direkt die set-Methode genutzt werden, um die neuen Module zu setzen (siehe @clearModules2). Das direkte Setzen der neuen Werte mithilfe der set-Methode ist die bevorzugte Variante, da hier mit weniger Anweisungen dasselbe Ergebnis erreicht wird. Der Code wird hierdurch lesbarer, deshalb sollte diese Variante verwendet werden.
Prisma bietet weiterhin eine Methode upsert an, die die Update-Methode und die Create-Methode kombiniert. Hierzu werden zunächst die Update und Create Objekte in eigene Variablen geschrieben. Anschließend können diese an die Upsert-Methode übergeben werden (siehe @upsert). Außerdem wird eine Filter-Abfrage benötigt, mit der Prisma ermitteln kann, ob ein Update, oder ein Create nötig ist (@upsertFilter).
#pagebreak()
#codeFigure("Backend: Erstellen und Bearbeiten von Modulen", <endpointBefore>, "endpointBefore")
#pagebreak()
Abschließend muss evaluiert werden, ob der entstandene Code verständlich und kompakt genug ist. Das vorgestellte Beispiel ist durch die vielen komplexen Datentypen stark gewachsen. Um den Code also wartbarer, lesbarer und verständlicher zu machen, wurde zuletzt noch die Codequalität optimiert. Hierzu wurden statt einer gemeinsamen Upsert-Methode zwei unterschiedliche Methoden (Create und Update) erstellt. Hierdurch wurde die Zuständigkeit klarer definiert. Außerdem wurden die verschiedenen Zuweisungen der komplexen Datentypen in jeweils eigene Methoden extrahiert. Dies hatte neben des nun weitaus besser lesbaren Codes den zusätzlichen Vorteil, dass die Methoden an verschiedenen Stellen verwendet werden konnten, sodass redundanter Code verringert wurde. Jedoch ergab sich daraus auch ein Nachteil. Durch das sequenzielle Verändern der Daten innerhalb der Methode bestand die Gefahr, dass die ersten Veränderungen erfolgreich sind, aber beispielsweise beim Zuweisen der zuständigen Person ein Fehler auftritt. In diesem Fall wäre das Update nur teilweise erfolgreich. In der früheren Version als alle Updates in einer Abfrage stattfanden, wäre in so einem Fall das gesamte Update fehlgeschlagen. Ein mögliches Teilupdate kann zu unerwarteten Fehlern führen und ist für den Benutzer des Systems entweder nur schwer zu erkennen oder unverständlich. Um dieses Verhalten wiederherzustellen, wurden letztlich alle Anweisungen in einer Transaktion @TransactionsBatchQueries zusammengefasst. Hierdurch konnte der Vorteil der besseren Codequalität bestehen bleiben und dennoch das gewünschte Verhalten erzielt werden. Im Falle eines Fehlers macht Prisma nun automatisch die bisher vorgenommenen Änderungen rückgängig, sodass keine inkonsistenten Daten entstehen können. Der neue Code ist deutlich lesbarer (siehe @endpointAfter).
#codeFigure("Backend: Erstellen und Bearbeiten von Modulen (Verbessert)", <endpointAfter>, "endpointAfter")
#heading("Changelog", level: 4, numbering: none, outlined: false)<implementChangelog>
Für die Anzeige der Änderungen (@SHOWCHANGES) müssen die Änderungen zunächst im Backend ermittelt werden.
Im gezeigten Codebeispiel werden zunächst alle verfügbaren Felder eines Modules ermittelt. Hierzu wird die Methode Object.keys @ObjectKeysJavaScript2023 verwendet, welche ein Array aller Felder des Modules zurückgibt. Die erhaltenen Felder werden im Anschluss in die Kategorien "Arrays", "Übersetzungen" und "Primitive Felder" aufgeteilt (@compareFields).
#codeFigure("compareFields", <compareFields>, "compareFields")
Damit die ermittelten Felder jetzt verglichen werden können, sind verschiedene Vergleiche nötig, die im folgenden kurz erklärt werden. Die Implementierungen der Compare-Methoden sind im Anhang (@compareFields2) zu finden.
Wenn das Feld einen primitiven Datentypen hat, kann der Feldinhalt miteinander verglichen werden (@comparePrimitiveField). Wenn es sich bei dem Feld jedoch um ein Array handelt, wird der Vergleich etwas komplizierter. In dem Fall muss herausgefunden werden, ob es neue Einträge gibt, oder ob Einträge entfernt wurden. Hierzu müssen dann die Ids verglichen werden (@compareArrayField). Für das Array translations, in dem die übersetzten Texte abgelegt werden, gibt es eine weitere Ausnahme. Hierbei müssen die Inhalte der Objekte im Array miteinander verglichen werden, die zu derselben Sprache gehören. Hierzu wird das entsprechende zu vergleichende Objekt mithilfe der filter-Methode @ArrayPrototypeFilter2023 herausgesucht (@compareTranslations) und die darin enthaltenen Eigenschaften verglichen.
#pagebreak()
#codeFigure("Vergleichsmethoden", <compareFields2>, "compareFields2")
#heading("Öffentliche Endpunkte", level: 4, numbering: none, outlined: false)
Des Weiteren ist es wichtig, zwischen öffentlichen und privaten Endpunkten zu unterscheiden. Damit User im Frontend auch ohne Anmeldung die Module ansehen können, müssen manche Endpunkte ohne Authentifizierung erreichbar sein. Hierzu wurde ein eigener Dekorator (@publicDecorator) erstellt. Dieser kann einfach über einen Endpunkt geschrieben werden, um diesen als öffentlich zu markieren (@moduleController). Damit dies funktioniert, musste zusätzlich der AuthGuard durch eine eigene Implementierung (@authGuard) ersetzt werden. Diese neue Implementierung überprüft, ob in den Metadaten "isPublic" steht. Wenn dies der Fall ist, kann die Anfrage mit `return true` genehmigt werden. Falls diese Metadaten nicht gesetzt sind, wird die ursprüngliche Implementierung von canActivate (@canActivateLine) aufgerufen, um zu überprüfen, ob ein gültiger Token mitgesendet wurde.
#codeFigure("public.decorator.ts", <publicDecorator>, "publicDecorator")
#pagebreak()
#codeFigure("module.controller.ts", <moduleController>, "getModule")
#codeFigure("jwt-auth.guard.ts", <authGuard>, "authGuard")
#heading("Informationen über den aufrufenden User", level: 4, numbering: none, outlined: false)
Manche Endpunkte benötigen genauere Informationen über den aufrufenden User, also den User, der im Frontend angemeldet ist. Das Bearbeiten von Modulen soll beispielsweise nur Usern erlaubt sein, die entweder verantwortlich für den gesamten Studiengang sind, oder verantwortlich für das bearbeitete Modul. Da sich die User mithilfe eines Jwt-Tokens authentifizieren, kann dieser hierzu einfach genutzt werden. In der jeweiligen Controller-Methode muss dann als Parameter lediglich `@User() user:UserDto` hinzugefügt werden, um dann mithilfe von user.role die Rolle des Users zu erfahren oder mit user.id die Id des Users.
Die Information über den User wird vom Framework NestJS beim Aufruf der Methode `canActivate` herausgefunden und wird dann automatisch als Parameter übergeben. In @authGuard ist jedoch zu sehen, dass der \@Public-Decorator aufgrund des frühen returns diese Anweisung überspringt. Für Methoden, die also für nicht angemeldete Benutzer zur Verfügung stehen sollen und die für angemeldete User anders funktionieren, funktioniert der \@User-Parameter also nicht ohne weiteren Aufwand. Ein Beispiel hierfür ist die Auflistung aller Studiengänge. Diese sollen auch unangemeldeten Besuchern angezeigt werden, jedoch sollen angemeldete studiengangsverantwortliche Personen auch versteckte Studiengänge angezeigt bekommen.
Damit der User auch bei öffentlichen Endpunkten verfügbar ist, gibt es zwei Möglichkeiten.
Als erste Möglichkeit könnte ein weiterer Guard erstellt werden (siehe @injectUser). @nestjs Dieser Guard kann mithilfe des \Use-Guards-Decorator aktiviert werden (@injectUserCall).
#codeFigure("InjectUser-Implementierung", <injectUser>, "injectUser")
#codeFigure("findOne() in department.controller.ts", <injectUserCall>, "injectUserAufruf")
Eine zweite Möglichkeit wäre, den Aufruf von canActivate vorzuziehen (@canActivateNew). Wenn dieser direkt als erstes durchgeführt wird, wird in jedem Fall der User verfügbar gemacht und öffentliche Endpunkte sind trotzdem möglich. Diese Möglichkeit hat den Vorteil, dass nicht daran gedacht werden muss, wie in @injectUserCall den InjectUser-Guard an die verschiedenen Methoden zu setzen. Aus diesem Grund wird diese Möglichkeit favorisiert.
Da canActivate eine Exception wirft, falls der User nicht eingeloggt ist, muss diese abgefangen werden, damit trotzdem geprüft werden kann, ob es den \@Public-Decorator gibt. Außerdem kann canActivate ein Observable zurückgeben. Da der Rückgabewert jedoch ein Boolean-Wert sein muss, wird die Methode lastValueFrom() aus der rxjs-Bibliothek genutzt, um einen konkreten Wert zu erhalten. @RxJSLastValueFrom
#codeFigure("canActivate() - Verbessert", <canActivateNew>, "canActivateNew")
// https://docs.nestjs.com/recipes/passport#request-scoped-strategies
=== PDFs generieren <pythonScript>
Das Generieren einer Modulbeschreibung in Form einer PDF-Datei verläuft in mehreren Teilschritten:
1. Die Studiengangsverantwortliche Person (User) fragt neue PDF Version an
2. Das Backend erstellt aus den vorliegenden Informationen eine .tex-Datei und veröffentlicht einen Auftrag zur Kompilierung
3. Ein Kompilierungs-Server nimmt den Auftrag an und ruft die .tex-Datei aus dem Backend ab
4. Der Kompilierungs-Server kompiliert die .tex-Datei zu einer PDF-Datei und gibt diese ans Backend zurück
5. Das Backend meldet das Ergebnis an den User zurück
6. Der User prüft das Ergebnis und gibt es frei
7. Die neue PDF-Version steht bereit
In den Schritten 2 bis 5 werden eine .tex-Datei und eine .pdf-Datei generiert. Dies wird im Folgenden näher beschrieben.
#heading("Generierung der .tex-Datei", level: 4, numbering: none, outlined: false)
Die Grundlage für die Generierung der .tex-Datei bildet ein Python-Skript, welches von #heine bereitgestellt wurde. Dieses Script wurde im Rahmen dieser Arbeit an die veränderte Datenstruktur angepasst. Anschließend wurde das Skript in TypeScript umgewandelt und in das neue Backend eingebaut. Hierzu wurde das Datenbankschema um die benötigten Einträge erweitert und es wurde ein neuer Controller mit dazugehörigem Service eingesetzt, welcher die Endpunkte und Methoden zur Generierung der .tex-Datei anbietet.
Das ursprüngliche Python-Skript enthielt eine statische Auflistung der Felder in der Tabelle des Modulhandbuches. Darin enthalten war der gewünschte Text (z. B. Moduldauer) und das dazugehörige Feld (module.courseLength). Diese statische Auflistung wurde im Rahmen der Umstellung in die Datenbank verschoben. Hierdurch soll der Wartungsaufwand reduziert werden. Mehrere Auslöser können dazu führen, dass sich die Struktur des zu generierenden PDFs ändert. In Zukunft könnte neben Englisch und Deutsch eine zusätzliche Sprache angeboten werden. Auch ist es denkbar, dass zusätzliche Felder eingeführt werden. Für die Studiengänge an der Fakultät 3 wird beispielsweise die Information "Gewichtung" auf den Modulhandbüchern abgedruckt. Um nun verschiedene PDF-Strukturen für verschiedene Studiengänge anzubieten, ist nun nur noch eine Veränderung der Datensätze in der Datenbank notwendig. Hierfür könnte eine zusätzliche Oberfläche erstellt werden, mit der die User selbst die PDF-Struktur konfigurieren können.
In @appendStructureItems ist zu sehen, wie der LaTeX-Code für ein SubModul generiert wird. Ein reduziertes Beispiel für ein StructureItem ist in @structureItem zu sehen. Mit der Eigenschaft takeTwoColumns (@structureItemTakeTwoColumns) können gewünschte Eigenschaften in @appendStructureItemsTakeTwoColumns breiter dargestellt werden. Dies passiert im Modulhandbuch der Abteilung Informatik beispielsweise für das Feld @erg, da dort in der Regel viel Text enthalten ist. In @structureItemSuffix ist zu sehen, wie an die gespeicherte Information ein Suffix angehangen werden kann. Dies ist beispielsweise wie im gezeigten Beispiel für Zeitdauern interessant, wird aber auch für die Anzeige der Dauer (z. B. 1 Semester) genutzt. In @structureItemName ist abschließend die Übersetzung für die Zeilenüberschrift angegeben.
#codeFigure("appendStructureItems()", <appendStructureItems>, "appendStructureItems")
#codeFigure("Beispiel eines StructureItems", <structureItem>, "structureItem")
Damit zu den Zeilenüberschriften auch die dazugehörigen Werte gedruckt werden können, wird die Methode getValue genutzt (@getValueCall). Hierzu wird die Eigenschaft path genutzt, die jedes Field besitzt (@structureItemPath). Im genannten Beispiel ist die Ermittlung noch einfach - hoursPresence ist ein Feld im Submodul und kann daher einfach ausgelesen werden. Es gibt jedoch auch komplexere Fälle, die betrachtet werden müssen. Es gibt zum Beispiel den Pfad responsible.firstName, bei dem auf das Attribut firstName des Objekts responsible zugegriffen wird. Im Falle der translations wird außerdem ein Zugriff auf ein Array benötigt (z. B. requirementsSoft.translations[0].name). Als letzte Art gibt es die Methodenaufrufe. Für das Feld @submodules wird beispielsweise eine Auflistung der Submodule benötigt. Diese benötigt zur Bereitstellung der gewünschten Informationen einen Zugriff auf die Datenbank und wird daher in einer eigenen Methode absolviert. Im Feld path steht dann der Name der aufzurufenden Methode "submodules()". Manche dieser Methoden könnten asynchron sein, weshalb hier auch noch einmal unterschieden werden muss (siehe @getValueFromPath). Die Methoden haben alle dieselbe Signatur, damit sie auf die gleiche Art aufgerufen werden können.
Der Wert für das komplexeste Beispiel "requirementsSoft.translations[0].name" wird wie folgt ermittelt:
1. Die Informationen des Teilmodules in eine Variable (submodule) laden
2. Den Pfad bei jedem Punkt trennen
3. Für den ersten Teil des Pfades (requirementsSoft) den Wert aus der Variable submodule auslesen
4. Aus diesem neuen Objekt wird der zweite Teil des Pfades ausgelesen (translations[0])
5. Zum Schluss wird aus dem neuen Objekt dann noch die Eigenschaft "name" ausgelesen
6. Alle Segmente des Pfades wurden abgelaufen, sodass das Ergebnis des letzten Schrittes zurückgegeben werden kann
Die Methode getNestedProperty (@getNestedProperty) sorgt für den soeben beschriebenen Ablauf. Mit der reduce-Methode (@reduce) werden die einzelnen Segmente des Pfades abgelaufen.@ArrayPrototypeReduce2023 Das RegEx-Muster (@detectArray) erkennt, ob das Segment ein Array ist und gibt das Segment, den Namen des Arrays sowie die angegebene Zahl zurück. Da das Segment nicht nochmal benötigt wird, wird es mithilfe des Unterstriches in @ignoreVar verworfen. @DestructuringAssignmentJavaScript2023
#codeFigure("getValue-Methoden", <getValueMethods>, "getValue")
#heading("Generierung der .pdf-Datei", level: 4, numbering: none, outlined: false)
Für die erfolgreiche Kompilierung der .tex-Datei muss die Server-Umgebung konfiguriert werden. Zusätzlich zur Möglichkeit, Latex kompilieren zu können, müssen die von der .tex-Datei benötigten Pakete bereitstehen. Um diesen Aufwand zu verringern wird ein Docker-Image eingesetzt, welches es ermöglicht, ohne weiteren Konfigurationsaufwand per HTTP-Request eine .tex-Datei zu kompilieren @YtoTechLatexonhttp2024.
Außerdem wurde ein neues Python-Skript erstellt, welches einen Kompilierungs-Server implementiert. Das Skript prüft in regelmäßigen Abständen, ob in der API ein Auftrag zur Erstellung einer neuen PDF-Datei vorliegt. Wird bei der Prüfung ein Auftrag gefunden, markiert der Server diesen als "laufend", damit dies auch im Frontend ersichtlich ist und damit kein anderer Server den Auftrag übernimmt. Anschließend ruft der Server die .tex-Datei aus dem Backend ab und übergibt sie an den Docker-Container. Der Docker-Container erstellt nun die PDF-Datei und gibt diese an den Server zurück. Der Server übermittelt das Ergebnis zurück an das Backend. @NestJSStreamingFiles Die Erstellung des PDFs ist entkoppelt vom Backend. Somit können beispielsweise mehrere Server betrieben werden, um die PDF-Erstellung zu parallelisieren. Auch können die Server unterschiedlich implementiert werden, sodass auch andere Dateiformate umsetzbar wären. Zukünftige Implementierungen könnten beispielsweise Word-Dokumente in ein PDF-Dokument umwandeln, oder LateX-Alternativen wie zum Beispiel Typst @TypstComposePapers in ein PDF-Dokument kompilieren. Beim Hinzufügen weiterer Kompilierungs-Server muss das Backend nicht angepasst werden, da dieses lediglich die Aufträge anbietet und die Aufträge nicht selbst an konkrete Server zuweist.
== Frontend <createFrontend>
Im Gegensatz zum Backend ist das Frontend eine neue Anwendung, zu der es keinen Bestandscode gab. Für das Frontend wurde ein neues Angularprojekt erstellt und mithilfe des Paketmanagers npm @NpmHome die benötigten Pakete hinzugefügt, von denen in den folgenden Unterabschnitten noch einige vorgestellt werden. Weiterhin werden in den folgenden Abschnitten anhand einiger Beispiele vorgestellt, wie das Frontend implementiert ist.
=== Routing
Der Code der Anwendung besteht aus Komponenten und Services. Die Komponenten werden in der Anwendung dargestellt und werden modular genutzt. Die Services können von allen Komponenten genutzt werden und bieten Methoden zum Laden von Daten aus dem Backend an. Damit die Services wissen, unter welcher URL das Backend erreichbar ist, ist diese URL in einer Datei `environment.ts` gespeichert und kann von da abgerufen werden. Dies ermöglicht den schnellen Austausch dieser URL. Für den produktiven Einsatz gibt es zudem eine `environment.prod.ts`, die die URL des produktiven Backends enthält. Sobald das Frontend mit dem Befehl `ng build --configuration=production` in der Produktiv-Version kompiliert wird, sorgt ein Eintrag in der `angular.json` (@angularJson) dafür, dass die Environment-Datei entsprechend ausgetauscht wird.
Die Entscheidung, welche Komponente in der Anwendung gezeigt wird, wird vom RouterModule übernommen. In der main.component.ts der Anwendung (@mainComponent) wird lediglich die Topbar (welche auf jeder Seite gezeigt werden soll) und das Router-Outlet platziert.
Das Router-Outlet wird dann in Abhängigkeit der besuchten URL anhand eines Eintrages aus der app.routes.ts (@appRoutes) mit der dort gesetzten Komponente ausgetauscht.
#codeFigure("angular.json (Auszug)", <angularJson>, "angular.json")
#codeFigure("main.component.html", <mainComponent>, "main.component")
#codeFigure("app.routes.ts (Auszug)", <appRoutes>, "app.routes")
Das Wechseln auf eine andere Seite ist nun sehr einfach mithilfe eines Methodenaufrufes möglich. Um Beispielsweise auf die Seite /faculty/4/department/2/course/1/module/1 zu wechseln, wird dieser Aufruf benötigt: `await this.router.navigate(['faculty', module.facultyId, 'department', module.departmentId, 'course', module.courseId, 'module', module.id]);`
Verkürzen lässt sich dies dann noch, falls ein Teil der URL bereits korrekt ist. Befindet man sich beispielsweise bereits auf der Seite /faculty/4/department/2/course/1 und möchte nur noch /module/1 anhängen, kann das Argument "relativeTo" genutzt werden, sodass nicht mehr alle Segmente angehängt werden müssen: `await this.router.navigate(['module', module.id], {relativeTo: this.route});`.
=== Design<design>
In diesem Unterabschnitt wird erklärt, wie das Design des Frontends implementiert wurde. Hierzu wird zunächst die Entscheidung für ein UI-Framework begründet. Anschließend wird die Arbeit mit SASS-Dateien und die Umsetzung des responsiven Designs erklärt.
#heading(level: 4, outlined: false, numbering: none)[UI-Framework]
Ein UI-Framework kann bei der Implementierung des Frontends unterstützen. Vom Framework angebotene vorgefertigte Komponenten müssen nicht selbst implementiert werden. Nach dem Dont-Repeat-Yourself-Prinzip wird dadurch der Entwicklungsaufwand reduziert und die Codequalität verbessert. @clean_code_2012_robert_martin Allerdings muss die Nutzung eines Frameworks sorgfältig abgewogen werden. Jede Einführung zusätzlicher Abhängkeiten birgt gewisse Risiken. Das Framework könnte eine Sicherheitslücke beeinhalten @NpmThreatsMitigations oder könnte zu anderen (zukünftigen) Abhängigkeiten inkompatibel sein. Diese Riskiken können durch eine vorherige Untersuchung der Frameworks verringert werden. Wenn ein Framework open source ist und eine große Anzahl an Unterstützern hat, ist es theoretisch möglich, dass Sicherheitslücken zügig gefunden und behoben werden @OpenSourceSicherheitVerstaendlichErklaert. Da dieses Projekt keine geheimen oder personenbezogenen Daten verarbeitet, wird das geringe Risiko, das mit der Verwendung eines Frameworks einhergeht. eingegangen - zu Gunsten einer angenehmeren Entwicklung und eines schöneren Ergebnisses.
Um das zu benutzende Framework zu identifizieren wurden zunächst zwei bekannte Frameworks `@ng-bootstrap/ng-bootstrap` @AngularPoweredBootstrap und `primeng` @PrimeNGAngularUI miteinander verglichen. Beide Frameworks haben hohe Downloadzahlen und eine gute Dokumentation, was ein Indikator dafür sein könnte, dass sie in diesem Projekt hilfreich sein könnten. Da PrimeNG weitaus mehr Komponenten anbietet, wird in diesem Projekt PrimeNG verwendet. Durch die Nutzung von PrimeNG sollte die Implementierung der verschiedenen Tabellen und Formularen weitaus effizienter sein. Außerdem sieht das System insgesamt einheitlich und modern aus, weil alle PrimeNG-Komponenten dem gleichen Theme folgen. @PrimeNGAngularUI
#heading(level: 4, outlined: false, numbering: none)[Styling]
Um die Darstellung der Inhalte von der Struktur der Inhalte zu trennen, werden in der Webentwicklung die Regeln zur Darstellung üblicherweise in CSS-Dateien definiert und dann in die HTML-Dateien eingebunden @css. Für dieses System wurde SASS @sass, eine Erweiterung von CSS verwendet, die zusätzlich Features einführt. Durch die Nutzung von Einrückungen kann der Code so etwas lesbarer gestaltet werden, da lange Selektoren übersichtlicher dargestellt werden können und nicht wiederholt werden müssen. @sassStyleRules
Es wurde eine globale SASS-Datei erstellt, um Klassen, die an vielen Stellen verwendet werden sollen, zu definieren (siehe @sassMain). Es gibt in der Anwendung viele klickbare Elemente. Um darzustellen, dass diese klickbar sind, soll sich der Cursor verändern, wenn er sich über dem Element befindet. Hierzu muss nun einfach die Klasse `.clickable` auf das Element gelegt werden. Neben `.clickable` gibt es noch zahlreiche weitere Klassen wie zum Beispiel (`fullWidth`, `smallPadding`, `mediumPadding` und `largePadding`), die für eine konsistente Darstellung in der Anwendung sorgen. Außerdem wurde `overwritePrimeNg.sass` erstellt, welche ausgewählte Eigenschaften von PrimeNG überschreibt. SASS erlaubt die Nutzung von Import-Statements, sodass die zusätzliche Datei einfach in der globalen SASS-Datei mit der Anweisung `@import "overwritePrimeNg"` importiert werden kann.
#codeFigure("Auszug styles.sass", <sassMain>, "sassMain")
Des Weiteren hat jede Komponente nochmal eine eigene .sass-Datei, in der Komponentenbezogene Darstellungseigenschaften gesetzt werden können. Diese .sass-Dateien werden nur auf die Elemente in der Komponente angewendet, sodass alle anderen Komponenten unverändert bleiben. @ViewEncapsulation
#heading(level: 4, outlined: false, numbering: none)[Responsive Design]<responsiveImplemented>
In verschiedenen Gesprächen mit zukünftigen Nutzern stellte sich heraus, dass die administrativen Oberflächen auf Desktop-PCs bedient werden. Für die administrativen Oberflächen muss die Ansicht auf mobilen Geräten also nicht optimiert werden. Die Übersicht der Studiengänge, die Übersicht der angebotenen Module sowie die moderne Ansicht der Moduldetails könnte jedoch von Studierenden auf mobilen Geräten geöffnet werden und sollte daher für die mobile Ansicht optimiert werden (@RESPONSIVE).
Damit die Anzeige der Studiengänge (@degreeProgramOverview) auf mobilen Geräten gut aussieht, musste nicht viel angepasst werden. Statt die Karten der Studiengänge nebeneinander aufzureihen, werden diese in der mobilen Ansicht nun untereinander platziert. Für die Desktopansicht wird hier ein Grid @cssGrid mit drei Spalten genutzt. Damit es in der mobilen Ansicht nur eine Spalte gibt, kann der Wert `grid-template-columns` mithilfe von `unset` @cssUnset zurück auf den ursprünglichen Wert gesetzt werden (siehe @cssUnsetCode). Für die Erkennung, ob die mobile Ansicht benötigt wird, wird eine Media Query genutzt. Diese sorgt dafür, dass die genannte Spalteneingenschaft nur für Geräte mit einer Bildschirmbreite unter 850 Pixeln zurückgesetzt wird. @ertel_responsive_nodate
#imageFigure(<degreeProgramOverview>, "../Images/DegreeProgramOverview.png", "Übersicht der Studiengänge")
#codeFigure("courses.component.sass", <cssUnsetCode>, "cssUnset")
Die Anzeige aller Module ist in der Desktopansicht eine Tabelle (@moduleOverviewResult). Diese wird auf mobilen Endgeräten zwar dargestellt, jedoch muss von links nach rechts gescrollt werden, um alle Felder sehen zu können. Um diese Ansicht zu optimieren, kann eine Funktion von PrimeNG genutzt werden, um für mobile Geräte aus der Tabelle eine Auflistung von Karten zu machen. Das Setzen von `responsiveLayout="stack"` reicht hier aus. Um die Felder auf den mobilen Karten noch zu beschriften, muss für jedes Feld eine Beschriftung hinzugefügt werden. Die Klasse `p-column-title` muss dabei auf die entsprechende Beschriftung gesetzt werden, damit PrimeNg sie passend ein und ausblendet. @primengTable
#imageFigure(<moduleOverviewResult>, "../Images/ModuleOverview.png", "Übersicht aller Module")
//#imageFigure(<responsiveModules>, "responsiveModules.png", "Mobile Auflistung der Module", width:60%)
//#imageFigure(<responsiveModuleDetails>, "../Images/responsiveModuleDetails.png", "Mobile Anzeige der Moduldetails", width:60%)
Zuletzt muss noch die Anzeige der Moduldetails optimiert werden. Diese ist etwas komplexer aufgebaut, da sie aus vielen verschiedenen Komponenten besteht. Die Komponenten in der ersten Reihe in @moduleDetailResult sind beispielsweise Info-Card-Components und bestehen aus einem Icon, einem Label und einem Anzeigewert. Neben den Info-Cards gibt es noch Stat-Cards für die Anzeige des Kuchen-Diagramms (siehe @moduleDetailResult), Text-Cards für die Anzeige von einfachen Texten (z. B. Voraussetzungen) und Split-Text-Cards für die Anzeige von zwei verschiedenen Texten innerhalb einer Karte. Für die Optimierung bei kleinen Bildschirmgrößen können Info-Card und Text-Card ignoriert werden, da diese bereits vollständig anzeigbar sind. Die Split-Text-Card muss auf kleinen Bildschirmgrößen die Texte untereinander statt nebeneinander zeigen. Hierzu musste die Flex-Direction mithilfe einer Media Query auf `column` gesetzt werden. @noauthor_flex-direction_2024 Dies war auch bei der Stats-Card erforderlich. Hier wurden zusätzlich die Texte anders ausgerichtet, damit sie auf der Karte zentriert angezeigt werden.
Die einzelnen Karten sind in der Ansicht der Moduldetails in einem Grid angeordnet. Dieses hat in der Desktopansicht 5 Spalten. Die Info-Karten passen in eine Spalte, während sich Karten mit mehr Inhalt auf mehrere Spalten verteilen dürfen. Damit auf der mobilen Ansicht die Karten vollständig angezeigt werden können, ohne dass ein horizontales Scrollen notwendig ist, wird die Eigenschaft `grid-column` von jeder Karte auf 5 gesetzt, sodass es pro Zeile jeweils eine Karte gibt. @cssGrid
#imageFigure(<moduleDetailResult>, "../Images/ModulDetails.png", "Desktopansicht Moduldetails")
=== Übersetzbarkeit <uebersetzbarkeit>
Damit jede Komponente weiß, welche Sprache gerade dargestellt werden soll, wird ein Service genutzt (@languageService). Dieser kann per Dependency Injection @DependencyInjectionAngular im Konstruktor einer beliebigen Komponente genutzt werden. Wenn in der Topbar (@grundgerüst) eine andere Sprache ausgewählt wird, wird die Eigenschaft `languageCode` im LanguageService verändert (`this.languageService.languageCode = selectedLanguageCode;`).
Der LanguageService hat eine Methode `getLanguages`, mit der an verschiedenen Stellen in der Anwendung angezeigt werden kann, welche Sprachen zur Auswahl stehen. Außerdem sind Getter und Setter für die Eigenschaft `languageCode` implementiert. Im Setter wird die ausgewählte Sprache in den LocalStorage geschrieben, damit die Benutzer der Website nicht bei jedem Besuch erneut ihre Sprache auswählen müssen. Außerdem wird die neu ausgewählte Sprache an das `languageSubject` weitergegeben. Das `languageSubject` ist ein BehaviourSubject aus der Erweiterungsbibliothek RxJS @RxJSBehaviorSubject. Nach dem Observer-Pattern-Prinzip können andere Komponenten und Services das languageSubject beobachten und erhalten im Falle einer Veränderung eine Benachrichtigung. Somit können beim Wechsel der Sprache die neuen Texte geladen werden.
#codeFigure("language.service.ts", <languageService>, "languageService")
Für die Übersetzung der Website müssen zwei verschiedene Arten von Texten übersetzt werden. Die statischen Elemente der Website, wie zum Beispiel Button-Beschriftungen, oder Tabellenüberschriften ändern sich in der Regel nicht und stehen fest im Quellcode der Angular Anwendung. Die dynamischen Texte, wie zum Beispiel Modulnamen ändern sich abhängig vom angezeigten Modul und werden aus dem Backend empfangen. Diese beiden Arten an Texten werden auf verschiedene Weise übersetzt.
#heading("Statische Elemente", level: 4, numbering: none, outlined: false)
Für den Wechsel zwischen verschiedenen Sprachen gibt es in Angular bereits zahlreiche Möglichkeiten. Bereits in Angular eingebaut ist das Paket `@angular/localize` @AngularInternationalization. Dieses bietet die Möglichkeit, die Angular Website für verschiedene Sprachen zu kompilieren. Mithilfe unterschiedlicher (Sub-) Domains oder Unterordner können die verschiedenen Sprachversionen dann bereitgestellt werden. Für den Wechsel der Sprache ist dann allerdings der Wechsel auf eine andere URL und ein damit verbundenes Neuladen der Website nötig. Ein weiterer Nachteil ist die hohe Komplexität der Einrichtung, sowie die mangelnde Flexibilität. Die entstehenden Übersetzungsdateien spiegeln die Struktur der HTML-Seiten wider, was bedeutet, dass bei Änderungen der HTML-Struktur auch die Übersetzungsdatei angepasst werden muss. Auch das Anlegen der Übersetzungsdatei ist dadurch nicht trivial. @angularInternationalizationExample
Ein simplerer Ansatz könnte die Nutzung von Key-Value-Paaren sein. Hierbei wird ein Key in die HTML-Seite geschrieben. Es gibt pro Sprache eine Übersetzungsdatei, die zu jedem Key einen Value zur Verfügung stellt, der die korrekte Übersetzung enthält. Ein Framework tauscht dann zur Laufzeit die Keys durch die gewünschten Values aus. Zur Auswahl eines geeigneten Frameworks wurden verschiedene Metriken betrachtet. Das genutzte Framework soll einfach zu nutzen sein, mit Key-Value-Dateien arbeiten können und eine gute Dokumentation haben. Auch sollten die Downloadzahlen auf NPM hoch genug sein, da ansonsten fraglich ist, ob das Paket die beste Wahl ist. Geringe Downloadzahlen können eine geringe Verbreitung bedeuten, was unter anderem dazu führen kann, dass das Paket keinen langfristigen Support erhält. Diese Anforderungen wurden von `@ngx-translate/core`@NgxtranslateCore2024 und von `@jsverse/transloco` @TranslocoAngularI18n (früher unter `@ngneat/transloco` bekannt @NgneatTransloco2023) erfüllt. Da `@ngx-translate/core` jedoch nicht mehr weiterentwickelt wird, wurde für dieses System `@jsverse/transloco` genutzt.
Um nun die statischen Texte in verschiedenen Sprachen anzubieten, wurden die Dateien en.json und de.json in den Assets-Ordner des Frontends gelegt. Die Angular-Konfiguration wurde erweitert, sodass beim Kompilieren die Übersetzungsdateien in den Build-Ordner kopiert werden, sodass diese später auf dem Webserver bereitliegen. Beim Laden der Anwendung stellt Transloco automatisch sicher, dass die benötigte Sprachdatei per HTTP-Request vom Webserver geladen wird. Anschließend mussten nur noch die .html-Dateien angepasst werden, damit dort auch die Texte aus den Übersetzungsdateien geladen werden. Hierzu wurde ein neues Element zu jeder HTML-Seite hinzugefügt: `<ng-container *transloco="let t; prefix:'faculties'">`. Durch das optionale Präfix ist es möglich, Übersetzungen zu gruppieren. Um jetzt beispielsweise das Wort "Fakultätsübersicht" auszugeben, muss `faculties: {overview: Fakultätsübersicht}` zu de.json hinzugefügt werden. Anschließend kann folgendes Element genutzt werden: `<span>{{t('overview')}}</span>`. @TranslocoAngularI18n
#heading("Dynamische Elemente", level: 4, numbering: none, outlined: false)
Damit die dynamischen Elemente übersetzt werden, benötigt das Backend die gewünschte Sprache. Diese wird im Header des GET-Requests übermittelt. Steht im Header `Language=DE`, werden deutsche Texte zurückgegeben. Damit nicht jeder HTTP-Request im Frontend manuell mit dem Header gefüllt werden muss, wird ein HTTPInterceptor @AngularHTTPClient genutzt (@languageInterceptor). Dieser erhält die aktuell gesetzte Sprache aus dem LanguageService (@getLanguage). Falls sich die dort eingestellte Sprache ändert, wird dies über ein BehaviourSubject kommuniziert und im LanguageInterceptor aktualisiert (@refreshLanguage). In der Methode `intercept()` wird dann der Header auf die aktuell eingestellte Sprache gesetzt. Dies passiert nicht, falls der ursprüngliche Request bereits einen Language-Header hat, damit das Verhalten übersteuert werden kann. Dies ist beispielsweise für die Bearbeitungsmaske eines Moduls hilfreich, in der die englische Modulbeschreibung bearbeitet werden soll, ohne dafür die gesamte UI auf Englisch stellen zu müssen.
In der `ApplicationConfig` der Angular Anwendung kann nun mithilfe einer Option konfiguriert werden, dass als HTTPInterceptor die neue Klasse LanguageInterceptor genutzt wird. Somit werden alle Requests mit der Sprache im Header erweitert.
Damit sich beim Wechsel der Sprache auch alle dynamischen Texte ändern, ist ein erneuter Aufruf der API notwendig. Hierzu wird das BehaviourSubject aus dem LanguageService (@languageService) genutzt. Somit können beim Sprachwechsel die dynamischen Informationen erneut aus dem Backend angefragt und in der Oberfläche dargestellt werden.
#codeFigure("language.interceptor.ts", <languageInterceptor>, "languageInterceptor")
=== Erstellen eines neuen PDFs<createPdfUI>
Das Erstellen eines neuen PDFs kann in der Studiengangsübersicht gestartet werden (@menu). Hierbei öffnet sich ein Popup, welches anzeigt, wann für den Studiengang zuletzt ein PDF veröffentlicht wurde. In Zukunft könnten hier auch die Details der Veränderungen seit der letzten Veröffentlichung aus dem Changelog angezeigt werden. Im Popup kann ausgewählt werden, für welche Sprachen das PDF generiert werden soll (@createPdfStep1). Während der Generierung wird dem User der Status angezeigt und sekündlich aktualisiert (@createPdfStep2). Der User kann nun entweder auf das Ergebnis warten, oder die Maske schließen und in einer separaten Maske die vergangenen Kompilierungsaufträge ansehen.
Sobald das PDF vorliegt, kann der User dieses ansehen und dann entweder verwerfen oder freigeben. Mit der Freigabe steht es dann auch für nicht angemeldete User bereit.
#imageFigure(<menu>, "../Images/Menu.png", "Menü - Studiengänge")
#imageFigure(<createPdfStep1>, "createPdf.png", "PDF veröffentlichen - Schritt 1", width: 90%)
#imageFigure(<createPdfStep2>, "CreatePdfStep2.png", "PDF veröffentlichen - Schritt 2")
=== Subscriptions, Intervalle und Memory Leaks
In @createPdfUI wurde beschrieben, wie der Status des Auftrages sekündlich aktualisiert wird. Hierzu wird ein Intervall genutzt, welches sekündlich eine Anfrage an das Backend sendet. Damit dieses Polling stoppt, sobald die Maske geschlossen wird, muss es per Befehl gestoppt werden.
Außerdem werden beim Wechseln der Anzeigesprache die angezeigten Daten in jeder Maske neu geladen. Hierzu wird beim Öffnen der Maske wie in @uebersetzbarkeit beschrieben ein BehaviourObject genutzt. Auch dieses sollte beim Schließen der Maske deabonniert werden. Andernfalls gibt es die Gefahr von Memoryleaks - solange Events abonniert sind, kann die Maske nicht aus dem Arbeitsspeicher entladen werden. @AngularComponentLifecycle
Aus diesen beiden Gründen, muss in einigen Masken das Interface OnDestroy @AngularComponentLifecycle implementiert werden. Dieses wird beim Schließen des Components aufgerufen. Der darin enthaltene Code (@onDestroy) ist dann recht simpel - das Intervall wird gestoppt und die Subcription auf das languageSubject wird deabonniert.
#codeFigure("onDestroy Implementierung", <onDestroy>, "onDestroy")
=== Suchfunktion<implementSearch>
Die Suchfunktion soll während der Eingabe geeignete Module vorschlagen (@SEARCH). Zur besseren Übersicht sollen diese nach Studiengang gruppiert werden. Hierzu müssen die aus dem Backend erhaltenen Daten auf das benötigte Format umgewandelt werden.
Mit der `.map`-Funktion lässt sich in JavaScript der Aufbau eines Arrays verändern. @MapJavaScriptMDN In @searchCode ist zu sehen, wie das neue Array zusammengebaut wird. Als Erstes werden die Studiengänge hinzugefügt. Für jeden Studiengang werden die darin enthaltenen Module hinzugefügt. Hierbei ist zu beachten, dass als `value` ein Link gesetzt werden muss, welcher beim Anklicken des Eintrages geöffnet werden soll.
#codeFigure("Daten für die Suche ermitteln", <searchCode>, "searchGroup")
=== URL-basierte Erkennung von Seitenelementen
Wenn ein User ein Modul öffnet, ändert sich die URL. Für das Modul mit der Id 1 könnte der Pfad dann beispielsweise so aussehen: /faculty/4/department/2/course/1/module/1. Dies hat den Vorteil, dass der User den Link mit anderen Usern teilen kann. Außerdem funktionieren dadruch die Navigationstasten im Browser und der Browserverlauf zeigt hilfreiche Informationen.
Für die Implementierung von verschiedenen Funktionen ergibt sich außerdem ein weiterer Vorteil. Durch die Angabe verschiedener Informationen in der URL können diese auch im Code verwendet werden. Mithilfe der Informationen aus der URL wird zum Beispiel der Breadcrumb in der oberen Leiste (@grundgerüst) befüllt (@PATH). Damit diese Funktionalität gekapselt ist und sich nicht wiederholt, wurde hierfür eine eigene Methode entworfen (@urlSegment). Mithilfe des Aufrufs von getIdFromSegment("faculty") kann dann beispielsweise herausgefunden werden, durch welche Fakultät der User gerade navigiert. Hierzu teilt die Methode getIdFromSegment() die aktuelle URL in Segmente auf, und gibt die Zahl nach dem gewünschten Segment zurück. Wenn der Pfad /faculty/4/department/2 wäre, würde getIdFromSegment("faculty") den Wert 4 zurückgeben.
#codeFigure("url-segment.service.ts", <urlSegment>, "urlSegmentService")
=== Anlegen und Bearbeiten von Modulen<createEditModules>
Die Masken zur Bearbeitung der Module und Teilmodule sind eine zentrale Stelle der Anwendung. Um hier eine gute Benutzbarkeit zu gewährleisten, sind mehrere Konzepte genutzt worden.
#heading("Übersetzbarkeit", level: 4, numbering: none, outlined: false)<translatability>
Für die Anforderung der Übersetzbarkeit wurde in @addModule, @translateDropdown und @translatePopup eine Möglichkeit konzipiert, Texte in verschiedenen Sprachen zu hinterlegen. Nach erneuter Betrachtung des Problems ergab sich eine einfachere Lösung. Ein Nachteil der ursprünglichen Lösung war, dass es für jedes Eingabefeld ein Popup gab. Dies erhöhte den Aufwand der Eingabe drastisch, da für jede Eingabe ein neues Fenster geöffnet wurde und auch wieder geschlossen werden musste. Um die Anzahl der Popups zu verringern, wurden stattdessen gewöhnliche Textfelder genutzt. Um dennoch verschiedene Sprachen zu unterstützen, wird die Eingabemaske nun für jede Sprache einmal wiederholt. Eine Anzeige im oberen Bereich zeigt die einzelnen Schritte des Bearbeitungsprozesses (@editModule).
#imageFigure(<editModule>, "../Images/EditModule.png", "Modul bearbeiten")
In @components sind die einzelnen Komponenten einer Bearbeitungsmaske (z.B. die Modulbearbeitung) zu sehen. Wenn auf "Bearbeiten" gedrückt wird, lädt der Router das Edit-Component (z.B. module-edit.component.ts). Das Edit-Component erhält das zu bearbeitende Modul mit allen Eigenschaften über einen \@Input-Parameter (siehe @twoWay). Dieses Objekt wird an die folgenden Komponenten weitergegeben. Hierzu wird das Two-Way-Binding von Angular verwendet, damit das Objekt in beide Richtungen synchronisiert wird. Dadurch kann das Preview-Component bei Änderungen im Editor automatisch aktualisiert werden, was eine Live-Vorschau der Änderungen ermöglicht. Damit das Two-Way-Binding funktioniert, muss zusätzlich ein \@Output-Parameter als EventEmitter definiert werden, der bei einer Änderung aufgerufen wird.
#codeFigure("Two-Way-Binding", <twoWay>, "two-way")
#pagebreak()
Außerdem lädt das Edit-Component für jede Sprache ein Translator-Component.
Das Translator-Component hat die Aufgabe, die benötigte Sprache zu laden und im Translations-Array an die erste Stelle zu schieben. Dies ist notwendig, weil in den folgenden Editor- und Preview-Komponenten immer auf den ersten Eintrag im Array geschaut wird. Wenn im Preview-Component beispielsweise der Name des Moduls gezeigt werden soll, wird `module.translations[0].name` aufgerufen.
#imageFigure(<components>, "translator.svg", "Komponenten der Modulbearbeitung")
#heading("Automatische Vervollständigung von Eingaben", level: 4, numbering: none, outlined: false)<autocomplete>
Um die Eingabe in Textfeldern zu erleichtern, wurde eine automatische Vervollständigung implementiert. In Textfeldern mit kurzen Texten (beispielsweise @exam) erscheint ein Vorschlag, sobald der User mit der Eingabe beginnt. Es werden Texte vorgeschlagen, die in anderen Modulen für dasselbe Eingabefeld verwendet werden. Somit kann der User zum einen selbstständig einen neuen Wert eintragen, oder alternativ einen vorgeschlagenen Wert auswählen, um nicht den gesamten Text immer wieder eingeben zu müssen.
In Textfeldern mit längeren Texten wurde dies nicht implementiert, da sich deren Inhalte nicht, oder nur sehr selten wiederholen (beispielsweise @literature).
#heading("Umwandlung von Textfeldern zu interaktiven Auswahl-Elementen", level: 4, numbering: none, outlined: false)
Des Weiteren wurden, wie bereits in @addModule konzipiert, einige Textfelder umgewandelt. In den ursprünglichen Daten, die für diese Arbeit vorlagen, bestanden alle Informationen aus Texten. Diese Informationen wurden teilweise umgewandelt, um deren Eingaben zu vereinfachen. Ein Beispiel hierfür ist die verantwortliche Person (@responsible), welche zuvor in einem Textfeld abgelegt wurde. In der implementierten Oberfläche gibt es nun ein Dropdown, in dem aus einer Liste an Personen ausgewählt werden kann. Im Backend wird dann nur die Id der Person gespeichert, statt des gesamten Textes. Auf eine ähnliche Art wurden diverse weitere Felder umgewandelt, sodass bei der Eingabe jetzt weniger Fehler gemacht werden können.
#heading("Plausibilitätschecks", level: 4, numbering: none, outlined: false)
Eingabefehler können unentdeckt bleiben und sich somit mit der Zeit häufen. Um diesem Problem entgegenzuwirken, wurden (wie in @CHECKMOD gefordert) Plausibilitätschecks implementiert. @designInterfaces[Kapitel 10] Sobald alle Eingaben getätigt wurden, kann ein User per Klick auf "weiter" auf die nächste Seite wechseln. Bevor jedoch gewechselt wird, werden die eingegebenen Daten überprüft. Fallen hierbei Unstimmigkeiten auf, wird der User darauf hingewiesen. Die entsprechenden Felder färben sich dann rot und zeigen in einem Tooltip den Grund dafür (@plausib). Ein User kann entweder die Daten korrigieren, oder die Warnung ignorieren und das Modul dennoch abspeichern. Das System soll vermeintlich falsche Eingaben nicht vollständig verhindern, sondern nur darauf hinweisen, da davon ausgegangen wird, dass das System von Experten bedient wird.
Neben der Prüfung, ob in jedes Feld ein Wert eingegeben wurde, gibt es folgende Überprüfungen:
1. Felder, die wie #link(<autocomplete>)[oben] beschrieben eine Autovervollständigung haben, sollten einen Wert beinhalten, den es bereits gibt.
2. Die Abkürzung eines (Teil-) Moduls entspricht einem bestimmten Muster. Dieses wird mithilfe eines regulären Ausdruckes überprüft. Im Falle der Teilmodule wird dieser Ausdruck genutzt: `/^[A-Z]{3}-[0-9]{3}-[0-9]{2}$/`. Die eingegebene Abkürzung muss mit drei Großbuchstaben (A-Z) beginnen, gefolgt von einem Bindestrich, drei Ziffern (0-9), einem weiteren Bindestrich und muss schließlich zwei Ziffern enden. Zeichen davor oder danach sind auch nicht zulässig. @RegularExpressionsJavaScript2024
3. Die Abkürzung sollte eindeutig, also noch nicht vergeben sein.
4. Der angegebene Zeitaufwand (@hours) muss zu den angegebenen ECTS (@credits) passen. Ein ECTS entspricht laut StudAkkVO einem Zeitaufwand von 25 bis 30 Stunden. @studAkkVO
5. Das Feld Semester (@recommendedSemester) kann einen Bindestrich enthalten (z. B. 4-6). In dem Fall muss die zweite Zahl größer als die erste Zahl sein.
#imageFigure(<plausib>, "../Images/Plausib.png", "Plausibilitätschecks")
== Dokumentation <createDocumentation>
Das neue System hat mehrere Komponenten, die zum einen bei der Einführung des Systems installiert werden müssen und zum anderen in Zukunft weiterentwickelt werden müssen. Um diese beiden Aufgaben zu unterstützen, wurden einige Informationen im Rahmen einer Dokumentation zusammengetragen. Die Dokumentation besteht aus vier Abschnitten: Frontend, Backend, API und Deployment. Die Abschnitte Frontend und Backend sind ähnlich aufgebaut. Beide enthalten Informationen zur erstmaligen Installation des Systems. Weiterhin ist beschrieben, wie neue Komponenten hinzugefügt werden können und was dabei zu beachten ist. Im Abschnitt API ist dahingegen beschrieben, wie die vom Backend bereitgestellte API genutzt werden kann, um verschiedene Datenabfragen durchzuführen. Kompliziertere Endpunkte sind hier außerdem aufgeführt. Es ist unter anderem beschrieben, wie der Login funktioniert und wie die Sprache der Antworten geändert werden kann. Im Abschnitt Deployment ist erklärt, wie das System mithilfe von Podman aufgesetzt werden kann.
Die Erstellung der Dokumentation lief parallel zur Entwicklung des Systems (@createBackend und @createFrontend). Um sicherzustellen, dass die wichtigsten Informationen bereitstehen, wurde anschließend das System erneut auf einem Testserver mithilfe der Anleitungen aus der Dokumentation installiert.
Die Texte sind im Markdown-Format verfasst, was bedeutet, dass sie von zahlreichen Editoren unterstützt werden. Zudem können die Plattformen GitHub und GitLab die Markdown-Dateien darstellen, wenn ein Entwickler dort den Quellcode durchsucht.
Zusätzlich zu der Möglichkeit, die Markdown-Dateien mit einem beliebigen Texteditor oder einer der genannten Plattformen zu lesen, wurde in dieser Arbeit zusätzlich das Framework Docusaurus
@docusaurus genutzt, um aus den Markdown-Dateien eine Website zu generieren (@documentation). Diese Website kann genutzt werden, um durch die vollständige Dokumentation in einer Benutzeroberfläche zu navigieren. Der Aufbau der Website könnte auf Entwickler bekannt wirken, da manche Open-Source-Projekte ihre Dokumentation mithilfe von Docusaurus realisieren. @DocusaurusSiteShowcase
Die Docusaurus-Website wurde überdies mit einer Suchfunktion erweitert, die von algolia bereitgestellt wird. @KISucheVersteht Auch diese Suchfunktion sollte Entwickelnden bekannt sein, da sie in vielen Dokumentationen genutzt wird. Die Suchfunktion kann mit der Tastenkombination Strg/Ctrl+K aufgerufen werden. In die Suchfunktion können beliebige Texte eingegeben werden, um schnell relevante Dokumentationsinhalte zu finden. Damit zu den Texten dann geeignete Vorschläge gemacht werden können (@docSearch), wird ein Crawler von algolia genutzt, welcher die Website in regelmäßigen Abständen indiziert. @CreateNewCrawler
#imageFigure(<documentation>, "../documentation.png", "Docusaurus-Website")
#imageFigure(<docSearch>, "../docSearch.png", "Suchfunktion der Dokumentation")
== Podman<podman>
Im letzten Schritt wurden alle Anwendungen für die Verwendung Podman @PodmanDesktopContainers vorbereitet. Podman erlaubt es, Anwendungen in Containern zu kapseln. Podman erinnert sehr stark an Docker @DockerAcceleratedContainer und nutzt ähnliche Befehle. Dieses System wurde mit Podman getestet, weil es in Zukunft auch mit Podman gehostet werden soll.
Um das neue System mit Podman bereitzustellen, sind einige Vorbereitungen nötig. Zunächst muss überlegt werden, welche Container benötigt werden. Für jede Anwendung soll ein eigener Container genutzt werden, um die Zuständigkeiten klar zu trennen. Dies bringt den Vorteil, dass einzelne Komponenten einfacher austauschbar sind, da sie über eine definierte Schnittstelle miteinander kommunizieren. Es wird für das Backend, das Frontend, die LaTeX-Api, das LaTeX-Poll-Script und die Dokumentation jeweils ein Container benötigt.
Im ersten Schritt musste nun in jedem Verzeichnis der soeben genannten Anwendungen ein Containerfile erstellt werden, welches beschreibt, wie sich der Container verhalten soll. Aus dem Containerfile wird später ein Image erstellt, mit dem der Container generiert werden kann. Das Image ist also die Vorlage für den Container. Für das Backend und die LaTeX-Api gab es bereits ein Containerfile. Für die Dokumentation wurde das Containerfile aus der Docusaurus-Dokumentation @DockerDeploymentDocusaurus2024 übernommen. Für das LaTeX-Poll-Skript und das neue Frontend wurden jeweils ein neues Containerfile erstellt.
Im Containerfile für das LaTeX-Poll-Skript (@latexDockerfile) ist ein einfaches Beispiel für ein Containerfile zu sehen. In @setImage wird die Basis des Images festgelegt. @DockerfileReference0200 In diesem Fall wird für das Skript Python benötigt, daher wird ein Python-Image als Basis verwendet. Es wurde eine Alpine Version des Python-Images ausgewählt. Die Alpine Version zeichnet sich dadurch aus, dass dessen Größe minimal gehalten wurde, indem nur die benötigten Werkzeuge (in diesem Fall Python) installiert sind. @IndexAlpineLinux Des Weiteren wird in @installPackage ein benötigtes Paket installiert, damit Http-Requests möglich sind. Abschließend wird dann noch ein Crontab installiert, welcher das Python-Skript in einem bestimmten Intervall regelmäßig ausführt.
#codeFigure("Containerfile für das Latex-Poll-Skript", <latexDockerfile>, "latexDockerfile")
Das Containerfile des Frontends ist komplexer. Es besteht aus zwei Stages. Die erste Stage basiert auf einem node-alpine-Image (@fromNodeAlpine) und ist für das Kompilieren des Quellcodes zuständig. Die zweite Stage (@secondStage) ist als Webserver für die Bereitstellung der Website zuständig und benutzt das Image `nginx:alpine` als Basis, beinhaltet also einen Webserver.
Für das Builden in der ersten Stage wurde darauf geachtet, dass nicht direkt alle Dateien kopiert werden (@copyAll). Stattdessen werden zunächst nur die package.json und die package-lock.json kopiert (@copyPackage) und ein npm ci ausgeführt, um die Pakete zu installieren. Dies hat den Vorteil, dass das Ergebnis gecacht werden kann. Podman arbeitet mit Layern, was in diesem Fall bedeutet, dass das Ergebnis nach dem Installieren der Packages in einem Layer abgespeichert wird. Dieses Layer kann nun beim Erneuten builden des Podman-Images aus dem Cache geladen werden (sofern sich die package.json nicht verändert hat). Wenn in @copyPackage alle Dateien direkt in das Image geladen würden, müssten bei jedem Build des Images erneut die Abhängigkeiten installiert werden, was zu einer verlängerten Laufzeit des Buildvorgangs führen würde. @DockerBuildCache
Damit die Ergebnisse aus der ersten Stage in der zweiten Stage genutzt werden können, werden diese mithilfe des Copy-Befehls in @copyFromBuild kopiert. Die Flag `--from=build` gibt an, dass aus der vorherigen Stage kopiert werden soll.
#codeFigure("Containerfile für das Frontend", <frontendDockerfile>, "FrontendDockerfile")
Nachdem alle Containerfiles bereitstehen, können die Images erstellt werden. Der Befehl `podman build -t studymodules-documentation .` erstellt beispielsweise das Image für die Dokumentation. Damit aus den Images Container generiert werden können, wurde eine compose-Datei erstellt (@compose). In dieser ist beschrieben, wie die Container konfiguriert sein sollen. Alle Container werden zur besseren Übersicht in einer Gruppe namens "studymodules_project" gruppiert. Der Container latex-poll-script ist am einfachsten zu erklären. Bei diesem ist lediglich das Image angegeben, auf dem er basiert. Da das latex-poll-script nur zwischen Backend und latex-api vermittelt, sind keine weiteren Konfigurationen notwendig.
Für die anderen Container ist mehr Konfigurationsaufwand nötig. Hier muss zum Beispiel noch das Port-Mapping gesetzt werden. Hierbei wird ein Port, der innerhalb des Containers existiert auf einen Port, der außerhalb des Containers existiert gemappt. Im Fall vom Backend wird beispielsweise der Port 3000 aus dem Container nach außen als Port 3000 freigegeben. Somit ist das Backend auf Port 3000 erreichbar. Bei der LaTeX-Api wurde der Port 8080 aus dem Container nach außen als Port 2345 freigegeben, da Port 8080 bereits für die Dokumentation belegt war. Auf dem Server, auf dem die Podman-Container laufen, ist die LaTeX-Api nun also unter dem Port 2345 zu erreichen. Allerdings gibt es einen Fallstrick: Das latex-poll-script soll auf die LaTeX-Api zugreifen. Dies funktioniert allerdings innerhalb des Containers latex-poll-script nicht über den Port 2345. Stattdessen hier als URL der Name des Containers verwendet, auf den zugegriffen wurde und als Port der Port innerhalb des Containers. Um also vom Poll-Skript auf die Api zuzugreifen, muss diese URL aufgerufen werden: latex-api:8080.
Das Backend benötigt außerdem eine Möglichkeit, Daten langfristig aufzubewahren. Bei einem Update des Images muss der Container des Backends neu erstellt werden, sodass darin enthaltene Daten verloren gehen. Um dieses Problem zu umgehen, können Volumes genutzt werden. @VolumesDockerDocs In der Compose-Datei ist in @volume zu sehen, wie eine Volume definiert wird. Hierzu wird einfach ein Ordner vom Hostsystem auf einen Ordner innerhalb des Containers gemappt. Beide Ordner werden automatisch synchronisiert. Wenn ein Container zerstört wird, bleibt die Volume bestehen und kann für den nächsten Container weiterverwendet werden. Als zusätzlichen Vorteil kann nun auch vom Hostsystem auf die Dateien in der Volume zugegriffen werden. In der Volume wird beispielsweise der Inhalt der Datenbank aufbewahrt.
Nachdem die Images nun erstellt sind und die Compose-Datei die Struktur der Container definiert, kann `podman compose up -d` ausgeführt werden, um die Container zu erstellen und zu starten. In der Desktopanwendung von Podman ist dies nachzuvollziehen (@podmanDesktop). In @dockerDiagram ist eine Übersicht der verschiedenen Container zu sehen. Dort sind die verwendeten Port aufgelistet und es kann erkannt werden, in welche Richtung kommuniziert wird.
#pagebreak()
#codeFigure("compose-Datei", <compose>, "compose")
#imageFigure(<podmanDesktop>, "podman.png", "Podman Desktop")
#imageFigure(<dockerDiagram>, "Docker.png", "Diagramm der eingesetzten Dockercontainer", width: 95%)
#pagebreak()
== Zwischenfazit
Nachdem Frontend und Backend implementiert wurden und eine Dokumentation erstellt wurde, besteht eine erste lauffähige Version des Systems. Diese Version kann im folgenden @review evaluiert werden, um herauszufinden, ob alle Anforderungen umgesetzt wurden.
|
|
https://github.com/daskol/typst-templates | https://raw.githubusercontent.com/daskol/typst-templates/main/neurips/README.md | markdown | MIT License | # Neural Information Processing Systems (NeurIPS)
## Usage
You can use this template in the Typst web app by clicking _Start from
template_ on the dashboard and searching for `bloated-neurips`.
Alternatively, you can use the CLI to kick this project off using the command
```shell
typst init @preview/bloated-neurips
```
Typst will create a new directory with all the files needed to get you started.
## Configuration
This template exports the `neurips2023` and `neurips2024` function with the
following named arguments.
- `title`: The paper's title as content.
- `authors`: An array of author dictionaries. Each of the author dictionaries
must have a name key and can have the keys department, organization,
location, and email.
- `abstract`: The content of a brief summary of the paper or none. Appears at
the top under the title.
- `bibliography`: The result of a call to the bibliography function or none.
The function also accepts a single, positional argument for the body of the
paper.
- `appendix`: A content which is placed after bibliography.
- `accepted`: If this is set to `false` then anonymized ready for submission
document is produced; `accepted: true` produces camera-redy version. If
the argument is set to `none` then preprint version is produced (can be
uploaded to arXiv).
The template will initialize your package with a sample call to the
`neurips2024` function in a show rule. If you want to change an existing
project to use this template, you can add a show rule at the top of your file
as follows.
```typst
#import "@preview/bloated-neurips:0.5.0": neurips2024
#show: neurips2024.with(
title: [Formatting Instructions For NeurIPS 2024],
authors: (authors, affls),
keywords: ("Machine Learning", "NeurIPS"),
abstract: [
The abstract paragraph should be indented ½ inch (3 picas) on both the
left- and right-hand margins. Use 10 point type, with a vertical spacing
(leading) of 11 points. The word *Abstract* must be centered, bold, and in
point size 12. Two line spaces precede the abstract. The abstract must be
limited to one paragraph.
],
bibliography: bibliography("main.bib"),
appendix: [
#include "appendix.typ"
#include "checklist.typ"
],
accepted: false,
)
#lorem(42)
```
With template of version v0.5.0 or newer, one can override some parts.
Specifically, `get-notice` entry of `aux` directory parameter of show rule
allows to adjust the NeurIPS 2024 template to Science4DL workshop as follows.
```typst
#import "@preview/bloated-neurips:0.5.0": neurips
#let get-notice(accepted) = if accepted == none {
return [Preprint. Under review.]
} else if accepted {
return [
Workshop on Scientific Methods for Understanding Deep Learning, NeurIPS
2024.
]
} else {
return [
Submitted to Workshop on Scientific Methods for Understanding Deep
Learning, NeurIPS 2024.
]
}
#let science4dl2024(
title: [], authors: (), keywords: (), date: auto, abstract: none,
bibliography: none, appendix: none, accepted: false, body,
) = {
show: neurips.with(
title: title,
authors: authors,
keywords: keywords,
date: date,
abstract: abstract,
accepted: false,
aux: (get-notice: get-notice),
)
body
}
```
## Issues
- The biggest and the most important issues is related to line ruler. We are
not aware of universal method for numbering lines in the main body of a
paper. Fortunately, line numbering support has been implemented at
[typst/typst#4516][4]. Let's wait for the next major release v0.12.0!
- There is an issue in Typst with spacing between figures and between figure
with floating placement. The issue is that there is no way to specify gap
between subsequent figures. In order to have behaviour similar to original
LaTeX template, one should consider direct spacing adjacemnt with `v(-1em)`
as follows.
```typst
#figure(
rect(width: 4.25cm, height: 4.25cm, stroke: 0.4pt),
caption: [Sample figure caption.#v(-1em)],
placement: top,
)
#figure(
rect(width: 4.25cm, height: 4.25cm, stroke: 0.4pt),
caption: [Sample figure caption.],
placement: top,
)
```
- Another issue is related to Typst's inablity to produce colored annotation.
In order to mitigte the issue, we add a script which modifies annotations and
make them colored.
```shell
../colorize-annotations.py \
example-paper.typst.pdf example-paper-colored.typst.pdf
```
See [README.md][1] for details.
- NeurIPS 2023/2024 instructions discuss bibliography in vague terms. Namely,
there is not specific requirements. Thus we stick to `ieee` bibliography
style since we found it in several accepted papers and it is similar to that
in the example paper.
- It is unclear how to render notice in the bottom of the title page in case of
final (`accepted: true`) or preprint (`accepted: none`) submission.
[1]: example-paper.latex.pdf
[2]: example-paper.typst.pdf
[3]: ../#colored-annotations
[4]: https://github.com/typst/typst/pull/4516
|
https://github.com/vEnhance/1802 | https://raw.githubusercontent.com/vEnhance/1802/main/src/vectors.typ | typst | MIT License | #import "@local/evan:1.0.0":*
= Review of vectors
== [TEXT] Notation for scalars, vectors, points
If you haven't seen $RR$ before, let's introduce it now:
#definition[
We denote by $RR$ the real numbers, so $3, sqrt(2), -pi$ are elements of $RR$.
Sometimes we'll also refer to a real number as a *scalar*.
]
The symbol "$in$", if you haven't seen it before, means "is a member of".
So $3 in RR$ is the statement "$3$ is a real number".
Or $x in RR$ means that $x$ is a real number.
Unfortunately, right off the bat I have to mention that the notation $RR^n$ could mean two things:
#definition[
By $RR^n$ we could mean one of two things, depending on context:
- The vectors of length $n$, e.g. the vector $vec(pi, 5)$ is a vector in $RR^2$.
- The points in $n$-dimensional space, e.g. $(sqrt(2), 7)$ is a point in $RR^2$.
]
To work around the awkwardness of $RR^n$ meaning two possible things,
this book will adopt the following conventions for variable names:
#typesig[
- Bold lowercase letters like $bf(u)$ and $bf(v)$ will be used for vectors.
When we draw pictures of vectors, we always draw them as _arrows_.
- Capital letters like $P$ and $Q$ are used for points.
When we draw pictures of points, we always draw them as _dots_.
]
We'll also use different notation for actual elements:
#typesig[
- A vector will either be written in column format like $vec(1,2,3)$,
or with angle brackets as $angle.l 1,2,3 angle.r$ if the column format is too tall to fit.
- But a point will always be written with parentheses like $(1,2,3)$.
]
Some vectors in $RR^3$ are special enough to get their own shorthand.
(The notation "$:=$" means "is defined as".)
#definition[
When working in $RR^2$, we define
$ bf(e)_1 := vec(1,0), #h(1em) bf(e)_2 := vec(0,1) $
and $ bf(0) = vec(0,0). $
]
#definition[
When working in $RR^3$, we define
$ bf(e)_1 := vec(1,0,0), #h(1em) bf(e)_2 := vec(0,1,0), #h(1em) bf(e)_3 := vec(0,0,1). $
We also let $ bf(0) := vec(0,0,0). $
In other places, you'll sometimes see $bf(i)$, $bf(j)$, $bf(k)$ instead,
but this book will always use $bf(e)_i$.
]
== [TEXT] Length
#definition[
The *length* of a vector is denoted by $|bf(v)|$
and corresponds to the length of the arrow drawn.
It is given by the Pythagorean theorem.
- In two dimensions:
$ bf(v) = vec(x,y) ==> |bf(v)| := sqrt(x^2+y^2). $
- If three dimensions:
$ bf(v) = vec(x,y,z) ==> |bf(v)| := sqrt(x^2+y^2+z^2). $
In $n$ dimensions, if $bf(v) = angle.l x_1, ..., x_n angle.r$,
the length is $|bf(v)| := sqrt(x_1^2 + ... + x_n^2)$.
]
#typesig[
The length $|bf(v)|$ has type scalar. It is always positive unless $bf(v) = bf(0)$,
in which case the length is $0$.
]
== [TEXT] Directions and unit vectors
Remember that a vector always has
- both a *magnitude*, which is how long the arrow is in the picture
- a *direction*, which refers to which way the arrow points.
In other words, the geometric picture of a vector always carries two pieces of information.
(Here, I'm imagining we've drawn the vector as an arrow
with one endpoint at the origin and pointing some way.)
In a lot of geometry situations we only care about the direction,
and we want to ignore the magnitude.
When that happens, one convention is to just set the magnitude equal to $1$:
#definition[
A *unit vector* will be a vector that has magnitude $1$.
]
Thus we use the concept of unit vector to capture direction.
So in $RR^2$, $vec(1,0)$ is thought of as "due east"
and $vec(-1,0)$ is "due west", while $vec(0,1)$ is "due north"
and $vec(1/sqrt(2), 1/sqrt(2))$ is "northeast".
#definition[
Given any vector $bf(v)$ in $RR^n$ besides the zero vector,
the *direction along $bf(v)$* is the unit vector
$ bf(v) / (|bf(v)|) $
which is the unit vector that points the same way that $bf(v)$ does.
]
We will avoid referring to the direction of the zero-vector $bf(0)$, which doesn't make sense.
(If you try to apply the formula here, you get division by $0$,
since $bf(0)$ is the only vector with length $0$.)
If you really want, you could say it has _every_ direction, but this is a convention.
#warning[
Depending on what book you're following,
more pedantic authors might write "the unit vector in the direction of $bf(v)$"
or even "the unit vector in the same direction as $bf(v)$"
rather than "direction along $bf(v)$".
This is too long to type, so I adopted the shorter phrasing.
I think everyone will know what you mean.
]
#typesig[
If $bf(v)$ is a nonzero vector of length $n$,
then the direction along $bf(v)$ is also a vector of length $n$.
]
#example[
Let's first do examples in $RR^2$ so we can drawn some pictures.
- The direction along the vectors $vec(1,0)$, $vec(5,0)$ or $vec(1337,0)$
are all $vec(1,0)$, thought of as _due east_.
- But the direction along the vectors $vec(-1,0)$ or $vec(-9,0)$
are both $vec(-1,0)$, thought of as _due west_.
- The direction along the vectors $vec(0,-2)$, $vec(0,-17)$
are all $vec(0,-1)$, thought of as _due south_.
]
#example[
How about the direction along $vec(3, -4)$?
We need to first find the length of the vector so we can scale it down.
That's given by the Pythagorean theorem, of course: $ lr(|vec(3,-4)|) = sqrt(3^2+4^2) = 5. $
So the direction along $vec(3,-4)$ would be
$ 1/5 vec(3,-4) = vec(3/5, -4/5). $
See @fig-vec-3-4. The direction is somewhere between south and southeast.
]
#figure(
image("figures/vectors-vec-3-4.png", width: auto),
caption: [The direction along $vec(3,-4)$ (blue) is $vec(3 slash 5, -4 slash 5)$ (red).
Unit vectors always lie on the grey circle (unit circle) by definition.],
) <fig-vec-3-4>
When drawn like @fig-vec-3-4 in the two-dimensional picture $RR^2$,
the notion of direction along $vec(x,y)$
is _almost_ like the notion of slope $y / x$ in high school algebra
(so the slope of the blue ray in @fig-vec-3-4).
But there are a few reasons our notion of direction is more versatile
than just using the slope of the blue ray.
- The notion of direction can tell the difference between $vec(3,-4)$, which goes southeast,
and $vec(-3,4)$, which goes northwest.
Slope cannot; it would assign both of these "slope $-4/3$.
- The due-north and due-south directions $vec(0,1)$ and $vec(0,-1)$ would have
undefined slope due to division-by-zero,
so you always have to worry about this extra edge case.
With unit vectors, due-north and due-south don't cause extra headache.
- Our definition of direction works in higher dimension $RR^3$.
There isn't a good analog of slope there;
a single number cannot usefully capture a notion of direction in $RR^n$ for $n >= 3$.
#example[
The direction along the three-dimensional vector $vec(12, -16, 21)$
is $ vec(12 slash 29, -16 slash 29, 21 slash 29). $
See if you can figure out where the $29$ came from.
]
== [RECIPE] Areas and volumes
If $bf(v)_1 = vec(x_1, y_1)$ and $bf(v)_2 = vec(x_2, y_2)$ are vectors,
drawn as arrows with a common starting point,
then their sum $bf(v)_1 + bf(v)_2$ makes a parallelogram in the plane with $bf(0)$
as shown in @fig-parallelogram.
#figure(
image("figures/vectors-area.png", width: auto),
caption: [Vector addition in $RR^2$.],
) <fig-parallelogram>
The following theorem is true, but we won't be able to prove it in 18.02.
#recipe(title: [Recipe for area of a parallelogram])[
The area of the parallelogram formed by $bf(v)_1 = vec(x_1, y_1)$ and $bf(v)_2 = vec(x_2, y_2)$ is equal to
the absolute value of the determinant
$ det mat(x_1, x_2; y_1, y_2) = x_1 y_2 - x_2 y_1. $
]
A similar theorem is true for the parallelepiped#footnote[I hate trying to spell this word.]
with three vectors in $RR^3$; see @fig-parallelepiped.
#recipe(title: [Recipe for volume of a parallelepiped])[
The volume of the parallelepiped formed by
$bf(v)_1 = vec(x_1, y_1, z_1)$,
$bf(v)_2 = vec(x_2, y_2, z_2)$,
$bf(v)_3 = vec(x_3, y_3, z_3)$
is equal to the absolute value of the determinant
$ det mat(x_1, x_2, x_3; y_1, y_2, y_3; z_1, z_2, z_3). $
]
#figure(
image("figures/vectors-parallelepiped.png", width: auto),
caption: [Three vectors in $RR^3$ making a parallelepiped.],
) <fig-parallelepiped>
#digression[
If you're interested in the proof of these results
and their $n$-dimensional generalizations, the tool needed is the *wedge product*,
which is denoted $and.big^k (RR^n)$.
This is well beyond the scope of 18.02,
but it's documented in Chapter 12 of my #link("https://web.evanchen.cc/napkin.html")[Napkin]
for those of you that want to read about it.
Alternatively, I think Wikipedia and Axler#footnote[Who
has a paper called #link("https://www.axler.net/DwD.html")[Down with Determinants!],
that I approve of.
], among others,
use a definition of the determinant as
the unique multilinear alternating map on $n$-tuples of column vectors in $RR^n$
that equals $1$ for the identity.
This definition will work, and will let you derive the formula for determinant,
and gives you a reason to believe it should match your concept of area and volume.
It's probably also easier to understand than wedge products.
However, in the long term I think wedge products are more versatile,
even though they take much longer to setup.
]
== [EXER] Exercises
#exer[
Calculate the unit vector along the direction of the vector
$ vec(-0.0008 pi, -0.0009 pi, -0.0012 pi). $
]
#pagebreak()
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/demos/fancy-arithmetic-sequence.typ | typst | #import "@local/typkit:0.1.0": *
#import "@preview/cetz:0.2.2"
#let number-sum-content(numbers) = {
let a = numbers.map((x) => $#x$).join(marks.math.plus)
let b = math-bold(numbers.sum())
return (a, b).join(marks.math.equals)
}
#let fancy-arithmetic-sequence(a: none, k: none, n: none, labels: none, braces: none) = {
let labels = resolve-array(labels)
let elements = ()
let last = n - 1
let middle = int(last / 2)
for i in range(n) {
let label = if labels != none {
if i == 0 and "first" in labels {
"first"
}
else if i == middle and "middle" in labels {
"middle"
}
else if i == last and "last" in labels {
"last"
}
} else {
none
}
let p = ( value: a + k * i, label: label )
elements.push(p)
}
cetz.canvas({
let offset = 0.5
// offset is important for centering the values
for (i, (label, value)) in elements.enumerate() {
drawing.rect(i, 0, i + 1, 1, math-bold(value))
if label != none {
drawing.content(i + offset, -1 + offset, bold(label))
}
}
let braces = resolve-array(braces)
let k = 0.3
for (i, brace-fn) in braces.enumerate() {
let tuple = brace-fn(n, middle)
let points = tuple.map((p) => (p + offset, i + 1 + k))
let numbers = n-range(tuple, (x) => elements.at(x).value)
let c = number-sum-content(numbers)
drawing.brace(..points, c, stroke: strokes.soft)
}
})
}
// #fancy-arithmetic-sequence(
// a: 1,
// k: 3,
// n: 7,
// labels: ("middle"),
// braces: (
// (n, middle) => (middle - 1, middle + 1),
// (n, middle) => (middle - 2, middle + 2),
// (n, middle) => (middle - 3, middle + 3),
// )
// )
|
|
https://github.com/Medushaa/typst-math-template- | https://raw.githubusercontent.com/Medushaa/typst-math-template-/main/README.md | markdown | # typst-math-template
Used some part of the template from this [repo](https://github.com/jskherman/jsk-lecnotes).
It looks like this ryt out of the box:

And could use the pretty boxes to make math notes like this too:

|
|
https://github.com/masaori/diffusion-model-quantum-annealing | https://raw.githubusercontent.com/masaori/diffusion-model-quantum-annealing/main/main.typ | typst | #import "@preview/cetz:0.1.2"
#import "@preview/commute:0.2.0": node, arr, commutative-diagram
#import "@preview/ctheorems:1.1.2": *
#import "theorem.typ": theorem, claim, proof, definition, note, theorem_rules
#set block(breakable: false)
#set heading(numbering: "1.1.")
#show: theorem_rules.with(qed-symbol: $square$)
次回(8/31)
- 順次定義を直す
- 一旦連続のみで
- counterが種類を跨いで通しになっている方が嬉しい
#claim("テスト")[
これはテストです
@testdef
]<testtheorem>
#definition("テストdef")[
これはテストです
]<testdef>
#set page(
paper: "a2",
margin: (left: 2cm, right: 2cm, top: 2cm, bottom: 2cm),
)
#let mapDef(f, A, B, a, b, comment) = {
$
#grid(
columns: 6,
gutter: 5pt,
$#f$, $:$, $#A$, $->$, $#B$, $#comment$,
"", "", rotate(-90deg, $in$), "", rotate(-90deg, $in$), "",
"", "", $#a$, $|->$, $#b$, ""
)
$
}
= ゴール
- 拡散モデルの数理を流し読みして、量子コンピューティング (量子アニーリング) と関係ありそうだと思った
- ので、これの数理的な関連をざっくりと理解したい
- 年内いっぱいくらいで「わかった」という気分になりたい
- なんでかというと、今から量子コンピューティングの勉強にリソース割いておくかどうかを見定めたい
== 関連しそうな項目
- 拡散モデル
- 確率過程
- シミュレーティッドアニーリング
- 量子アニーリング
- 代数的確率空間
- 量子力学においては、行列(=作用素)のtraceが期待値
- この辺を抽象化して、代数の元に「確率的」な情報が含まれているとみなしてゴニョゴニョするのが確率的代数空間 (イメージ)
- これを理解できると「拡散モデルのマルコフ過程は代数的確率空間的にはこう」みたいな話から「じゃあこんな種類の代数構造から考えたら拡散モデルに当たるものは何?」みたいな議論ができて面白いのでは、という仮説
= 課題感
- 大規模LLMは大手に独占されている
- GPT 4はパラメーター数が 170兆
- 圧倒的データ量
= 教科書
- *確率論*: #link("https://www.amazon.co.jp/gp/product/4254116004/ref=ox_sc_act_image_1?smid=AN1VRQENFRJN5&psc=1")
- *確率微分方程式とその応用:* #link("https://www.amazon.co.jp/gp/product/4627077815/ref=ox_sc_act_image_2?smid=AN1VRQENFRJN5&psc=1")
= 論文まとめ
== Deep Unsupervised Learning using Nonequilibrium Thermodynamics
非平衡熱力学を用いた教師なしディープラーニング
= 一般定理
== ガウス積分
$ integral_(- infinity)^(infinity) exp(-a(x-b)^2) dif x = sqrt(pi / a) quad Re{a} > 0, b in CC $
= 用語
== 可測空間
- 組み $(Omega, F)$
- $Omega$ : set
- $F$ : 完全加法族
- 完全加法性を満たす、$Omega$の冪集合の部分集合
== 可測写像
- $(Omega, F), (Psi, G):$ 可測空間
- $f: (Omega, F) -> (Psi, G)$ で以下を満たす
- $forall A in G space f^(-1)(A) in F$
- \*\* $f: (Omega, F) -> (Psi, G)$ こう書いたときの実態は $f: F -> G$
== 測度空間
- 組み$(Omega, F, mu)$
- $mu:F->RR_(>=0)$
- 可算加法性を満たす
- $forall i,j in NN, A_i, A_j in F space A_i union A_j = "empty" arrow.r.double mu(union_(i) A_(i) ) = sum_(i) mu(A_(i) )$
== 実数 (測度空間の具体例)
- $(RR,B(RR),mu)$
- $B(RR):$ ボレル集合族
- RR上の距離から定まる位相を含む最小の完全加法族
- $mu:$ ルベーグ測度
- 距離から自然に定まる「長さ」
- $mu([0,1]) = 1$
- $mu([a, b]) = b - a$
== 確率空間
- 測度空間 $(Omega, F, P)$で以下を満たすもの
- $P(Omega) = 1$
- $Omega$ を*標本空間*という
- $Omega$の元を*標本*という
- $F$ を*事象の全体*という
- $F$の元を*事象*という
- $P$ を*確率測度*という
== 確率変数 (random variety)
- $X: Omega -> RR$ で、以下を満たすもの
- 可測である。つまり、$forall omega in frak(B)(RR), X^(-1)(omega) in F$
== $X$に由来する確率測度
確率空間$(Omega, F, P)$と確率変数$X$について、
$P_(X): frak(B)(RR) -> [0,1],\ A arrow P(X^(-1)(A))$
が定まり、
$(RR,frak(B)(RR),P_X)$は確率空間になっている
== d変数確率変数 (random variety)
$X_(1), dots ,X_(d):$1変数確率変数
$
(X_(1), dots ,X_(d)): (Omega, F)->
(RR^d,frak(B)(RR^d)), \ omega arrow (X_(1)(omega), dots,X_(d)(omega))
$
== $(X_(1), dots ,X_(d))$に由来する確率測度
確率空間$(Omega, F, P)$とd変数確率変数$(X_(1), dots ,X_(d))$について、
$P_(
(X_(1), dots ,X_(d))
): frak(B)(RR^(d)) -> [0,1],\ A arrow P((X_(1), dots ,X_(d))^(-1)(A))$
が定まり、
$(RR,frak(B)(RR),P_X)$は確率空間になっている
#theorem("Lebesgueの分解定理")[
確率空間$(Omega, F, P)$と確率変数$X$について、
$(RR,frak(B)(RR), P_(X))$: 確率空間 が定まる。
$mu: frak(B)(RR) -> RR$ を Lebegue Measure とする.
$
P_X=P_(X_(abs))+P_(X_("sing"))+P_(X_("dis")) \ s.t.
$
- $P_(X_(abs))$ は $mu$ について、 absolutely conti.
- すなわち、 $mu(A)=0$ ならば $P_(X_(abs))(A)=0(forall A in B(RR))$
- $P_(X_("sing"))$ は $mu$ について、conti. かつ、 singular.
- すなわち、 $P_(X_("sing"))(a)=0(forall a in RR)$ かつ、 $exists A in A(RR)$ s.t. $mu(A)=0$ and $P_(X_("sing"))(A^c)=0$
- $P_(X_("dis"))$ は $mu$ について、 discrete.
- すなわち、 $exists{a_i}_(i=1)^(infinity) subset RR, {p_i}_(i=1)^(infinity) subset RR$ s.t. $P_(X_("dis"))(A)=sum_(i=1)^(infinity) a_i chi_(p_i)(A)$ ただし、$(chi_(p_i): B(RR) -> RR, chi_(p_i)(A):=cases(0(p_i not in A), 1(p_i in A)))$
と一意に分解できる.
]
- 拡散モデルの数理を読む上では$P_abs$だけ考えるでOK
=== 多変数の場合
確率空間$(Omega, F, P)$と確率変数$(X_(1),dots,X_(d))$について、
$(RR^(d),frak(B)(RR^(d)), P_(
(X_(1),dots,X_(d))
))$: 確率空間 が定まる。
$mu: frak(B)(RR^(d)) -> RR$ を Lebegue Measure とする.
以下は、1変数の場合と同様。
== Radon-Nikodymの定理
#theorem("Radon-Nikodymの定理")[
$X$: 確率変数
Lebegue の $P_(X_(abs))$ について、以下を満たす Integrable な関数 $p_(X_(abs)): RR -> RR_(>=0)$ が存在する。
$forall x in RR$
$
integral_(- infinity)^x p_(X_(abs))(x^') dif x^'=P_(X_(abs))((-infinity, x])
$
この $p_(X_(abs))$ を、確率密度関数 (Probabilty Density Function) と呼ぶ。
]
- 気温が20度から30度になる確率を求めたい時に、
- 「気温x度」を実数xにマップする ← 確率変数という
- 実数直線上で20-30の区間で積分する
=== 多変数の場合
#theorem("Radon-Nikodymの定理: 多変数の場合")[
確率空間$(Omega, F, P)$と$(X_(1),dots,X_(d))$: d変数確率変数について、
$(RR^(d),frak(B)(RR^(d)), P_(
(X_(1),dots,X_(d))
))$: 確率空間 が定まる。
Lebegue の $P_(
(X_(1), dots ,X_(d))_(abs)
)$ について、以下を満たす Integrable な関数 $p^("joint")_(
(X_(1), dots ,X_(d))_(abs)
): RR^(d) -> RR_(>=0)$ が存在する。
$forall x_(1), dots, x_(1) in RR$
$
integral_(- infinity)^(x_(1)) dots integral_(- infinity)^(x_(d)) p^("joint")_(
(X_(1), dots ,X_(d))_(abs)
)(x^') dif x^'=P_(
(X_(1), dots ,X_(d))_(abs)
)((-infinity, x_(1)] times dots times (-infinity, x_(d)])
$
この $p^("joint")_(
(X_(1), dots ,X_(d))_(abs)
)$ を、結合確率密度関数 (Joint Probabilty Density Function) と呼ぶ。
]
#block(inset: (left: 1em))[
フビニの定理により、$RR^(d)$についての積分はd回の$RR$についての積分と等しくなる。
]
$X_(1), dots ,X_(d)$ は互いに入れ替え可能である。
特に、$d=2$の場合、
$
p^("joint")_(
(X_(1), X_(2))_(abs)
)(x_(1), x_(2))=p^("joint")_(
(X_(2), X_(1))_(abs)
)(x_(2), x_(1))
$
#theorem("Radon-Nikodymの定理の逆っぽい定理")[
$d in ZZ_(>=1)$と、実数値関数 $p: RR^(d) -> RR_(>=0)$ について、
pが、
- $p$は可測関数
- $integral_(- infinity)^(infinity) dots integral_(- infinity)^(infinity) p(x^') dif x^'=1$
を満たすとき、
確率空間$(RR^(d),frak(B)(RR^(d)), P)$がただ一つ存在して、
$bold(x) in RR^(d)$
$
integral_(- infinity)^("pr"_(1)(bold(x))) dots integral_(- infinity)^("pr"_(d)(bold(x)))
p(bold(x^')) dif bold(x^')
=
P(
(-infinity, "pr"_(1)(bold(x))]
times dots times
(-infinity, "pr"_(d)(bold(x))]
)
$
を満たす。
ただし、$1 <= i <= d$ $X_(i) := "pr"_(i): RR^(d) -> RR$ (射影)
この実数値関数 $p$ も、用語の濫用で、結合確率密度関数と呼ぶ。
]
#proof[
確率空間を構成する。
- $P_(
(X_(1), dots ,X_(d))_(abs)
)(X_(1) <= x_(1) and dots and X_(d) <= x_(d))
:= integral_(- infinity)^(x^()_(1)) dots integral_(- infinity)^(x_(d))
p(x^'_(1), dots ,x^'_(d)) dif x^'_(1) dots dif x^'_(d)$
- $product_(i)(-infinity, x_(i)]$ は $frak(B)(RR^(d))$ の生成元
- よって、$P_(
(X_(1), dots ,X_(d))_(abs)
)$ は $frak(B)(RR^(d))$ 上の確率測度
]
== 累積分布関数
- 確率密度関数を$-infinity$から$x$まで積分したもの
== 確率質量関数 (= Px3の時に確率分布って適当に書かれてたらこれ)
$
p_(x_("dis")):RR -> [0,1] \ x arrow P_(x_(3))({x})
$
= 定義
#definition("")[
この節において、
$1 <= i <= d$について、$bb(R)_(i) := bb(R)$と定める。このとき、$product_(i=1)^(d) bb(R)_(i) = bb(R)^(d)$
#mapDef(
$p^(X^(d))_("abs")$,
$bb(R)^(d)$, $bb(R)$,
$(x_(1), ..., x_(d))$, $y$,
"可測関数"
)
は、
- $p^d_("abs")$は可測関数
- $integral_(- infinity)^(infinity) dots integral_(- infinity)^(infinity) p^d_("abs")(x^') dif x^'=1$
を満たす。
また、$bb(R)^(d)$上のルベーグ測度を$mu$と書く。
]
次回(8/31)
- 順次定義を直す
- 一旦連続のみで
== 平均情報量(エントロピー)
#definition("平均情報量(エントロピー)")[
$
H_("entropy")(p^d_("abs"))
:= -integral_(x in bb(R)^(d))
lr(
(
p^d_("abs")(x)
log (p^d_("abs")(x))
),
size: #200%
)
dif mu (x)
$
]
=== エントロピーの値の範囲
$ 0 <= H_("entropy")(p^d_("abs"))("誤り")$
// == 条件付き確率
// 確率密度関数
// $p_("condi")(dot.c | dot.c): F times F -> [0,1]$
// $
// P_("condi")(A|B)
// := (
// P(A sect B)
// )/(
// P(B)
// )
// $
// === 確率空間複数バージョン
// 確率空間 $(bb(R)^d, frak(B)(bb(R)^d),P_d)$, $(bb(R)^(d-1), frak(B)(bb(R)^(d-1)),P_(d-1))$
// 確率変数 $X_d: bb(R)^d -> bb(R)$, $X_(d-1): bb(R)^(d-1) -> bb(R)$ について、
// $A_d in frak(B)(bb(R)^d), B_(d-1) in frak(B)(bb(R)^(d-1))$ について、
// $P_("condi")^(P_d,P_(d-1)): frak(B)(bb(R)^d) times frak(B)(bb(R)^(d-1)) -> [0,1]$
// $
// P_("condi")^(P_d,P_(d-1))(A_d | B_(d-1))
// := (
// P_d(A_d sect (B_(d-1) times bb(R)))
// )/(
// P_(d-1)(B_(d-1))
// )
// $
== 条件つき確率密度関数
// 確率空間 $(bb(R), frak(B)(bb(R)),P)$
// $(Y_1, Y_2)$: 1変数確率変数 $Y_1, Y_2$ によって定まる2変数確率変数
// $p^("condi")_((Y_1, Y_2)_("abs"))(dot.c|dot.c):bb(R) times bb(R) -> bb(R)_(>=0)$
// $
// p^("condi")_((Y_1, Y_2)_("abs"))(y_1 | y_2)
// := (
// p^("joint")_((Y_1, Y_2)_("abs"))(y_1, y_2)
// )/(
// p_(Y_2\ "abs")(y_2)
// )
// $
// === 確率空間複数バージョン
// 確率測度、$P_("condi")^(P_d,P_(d-1))$ からRandon-Nikodymの定理により定まる、
// $
// p_("condi")^(P_d | P_(d-1)):
// bb(R)^d times bb(R)^(d-1) -> bb(R)_(>=0)
// $
// を、条件付き確率密度関数という
#definition("条件つき確率密度関数")[
$p_("abs")^(d), p_("abs")^(d^(prime))$ について、
#mapDef(
$p_("condi")^(p_("abs")^(d) | p_("abs")^(d-1))$,
$bb(R)^d times bb(R)^(d-1)$, $bb(R)_(>=0)$,
$(x^d, x^(d-1))$, $y$,
""
)
]
== 結合確率
確率空間 $(bb(R)^d, frak(B)(bb(R)^d),P_d)$, $(bb(R)^(d-1), frak(B)(bb(R)^(d-1)),P_(d-1))$
確率変数 $X_d: bb(R)^d -> bb(R)$, $X_(d-1): bb(R)^(d-1) -> bb(R)$ について、
$A_d in frak(B)(bb(R)^d), B_(d-1) in frak(B)(bb(R)^(d-1))$ について、
$
P_("joint")(A_d, B_(d-1))
:= P_d(A_d)P_("condi")(A_d | B_(d-1))
$
== 結合エントロピー (joint entropy)
=== 確率空間ひとつバージョン
確率空間 $(bb(R), frak(B)(bb(R)),P)$
確率変数 $X, Y$ について、
$
H^P_("joint")(X, Y)
:= H_("joint")(p^("joint")_((X, Y)_("abs")))
:= -integral_(x in X, y in Y) dif x dif y
p^("joint")_((X, Y)_("abs"))(x, y)
log (
p^("joint")_((X, Y)_("abs"))(x, y)
)
$
定義から直ちに、
$
H_("joint")(Y, X) = H_("joint")(X, Y)
#h(40pt) "論文(25)"
$
がいえる。
=== 確率空間複数バージョン
== 条件付きエントロピー (conditional entropy)
確率空間 $(bb(R), frak(B)(bb(R)),P)$
確率変数 $X, Y$ について、
$
H^P_("condi")(Y|X)
:= -integral_(x in X, y in Y) dif x dif y
p^("joint")_((Y, X)_("abs"))(y, x)
log (
(p^("joint")_((Y, X)_("abs"))(y, x))
/
(p_(X_("abs"))(x))
)
$
$
= -integral_(x in X, y in Y) dif x dif y
p^("joint")_((Y, X)_("abs"))(y, x)
log (
p^("condi")_((Y,X)_("abs"))(y | x)
)
$
#theorem("Claim")[
以下が成り立つ
$
H^P_("condi")(Y | X)
= H^P_("condi")(X | Y)
+ H^P_("entropy")(Y)
- H^P_("entropy")(X)
$
]
#proof[
$
("右辺")
&= H^P_("condi")(X | Y)
+ H^P_("entropy")(Y)
- H^P_("entropy")(X) \
&= -integral_(x in X, y in Y) dif x dif y
p^("joint")_((X, Y)_("abs"))(x, y)
log (
p^("condi")_((X, Y)_("abs"))(x | y)
)
- integral_(y in Y) dif y
p_(Y_("abs"))(y)
log p_(Y_("abs"))(y)
+ integral_(x in X) dif x
p_(X_("abs"))(x)
log p_(X_("abs"))(x)
#h(40pt) ("∵def.") \
&= -integral_(x in X, y in Y) dif x dif y
p^("joint")_((X, Y)_("abs"))(x, y) dot.c
log (
(p^("joint")_((X, Y)_("abs"))(x, y))
/
(p_(Y_("abs"))(y))
)
- integral_(y in Y) dif y
p_(Y_("abs"))(y)
log p_(Y_("abs"))(y)
+ integral_(x in X) dif x
p_(X_("abs"))(x)
log p_(X_("abs"))(x)
#h(40pt) ("∵" p_("joint") "のdef.") \
&= -integral_(x in X, y in Y) dif x dif y (
p^("joint")_((X, Y)_("abs"))(x, y) dot.c (
log (p^("joint")_((X, Y)_("abs"))(x, y))
- log (p_(Y_("abs"))(y))
)
)
- integral_(y in Y) dif y
p_(Y_("abs"))(y)
log p_(Y_("abs"))(y)
+ integral_(x in X) dif x
p_(X_("abs"))(x)
log p_(X_("abs"))(x) \
&= -integral_(x in X, y in Y) dif x dif y (
p^("joint")_((X, Y)_("abs"))(x, y) dot.c (
log (p^("joint")_((X, Y)_("abs"))(x, y))
)
)
+ cancel(
integral_(x in X, y in Y) dif x dif y (
p^("joint")_((X, Y)_("abs"))(x, y) dot.c (
log (p_(Y_("abs"))(y))
)
)
)
cancel(
- integral_(y in Y) dif y
p_(Y_("abs"))(y)
log p_(Y_("abs"))(y)
)
+ integral_(x in X) dif x
p_(X_("abs"))(x)
log p_(X_("abs"))(x) \
&= -integral_(x in X, y in Y) dif x dif y (
p^("joint")_((X, Y)_("abs"))(x, y) dot.c (
log (p^("joint")_((X, Y)_("abs"))(x, y))
)
)
+ integral_(x in X) dif x
p_(X_("abs"))(x)
log p_(X_("abs"))(x) \
&= -integral_(x in X, y in Y) dif x dif y (
p^("joint")_((X, Y)_("abs"))(x, y) dot.c (
log (p^("joint")_((X, Y)_("abs"))(x, y))
)
)
+ integral_(x in X, y in Y) dif x dif y (
p^("joint")_((X, Y)_("abs"))(x, y) dot.c (
log (p_(X_("abs"))(x))
)
) \
&= -integral_(x in X, y in Y) dif x dif y (
p^("joint")_((X, Y)_("abs"))(x, y) dot.c (
log (
(p^("joint")_((X, Y)_("abs"))(x, y))
/
(p_(X_("abs"))(x))
)
)
) \
&= -integral_(x in X, y in Y) dif x dif y (
p^("joint")_((Y, X)_("abs"))(y, x) dot.c (
log (
(p^("joint")_((Y, X)_("abs"))(y, x))
/
(p_(X_("abs"))(x))
)
)
) \
&= H^P_("condi")(Y | X)
#h(40pt) ("論文(27)")
$
]
// ... (前の部分の続き)
#heading(level: 2)[交差エントロピー (cross entropy)]
$X$: 可測空間$(Omega, F)$上の確率変数
$(Omega, F, P),(Omega,F, Q)$: 確率空間
$(RR, frak(B)(RR),P_X), (RR, frak(B)(RR),Q_X)$: 上記から定まる確率空間
について、
$
H_("cross")(P_X, Q_X) :=
-sum_(i=1)^(infinity) p_(X_("dis"))(x_i) log(q_(X_("dis"))(x_i))
- integral_(x in RR) dif x
p_(X_("abs"))(x) log(q_(X_("abs"))(x))
$
$p_(X_("dis")) = q_(X_("dis")) = 0$のとき、
$
H_("cross")(p_(X_("abs")), q_(X_("abs"))) := H_("cross")(P_X, Q_X)
$
ともかく。
#heading(level: 2)[KL-ダイバージェンス]
$X$: 可測空間$(Omega, F)$上の確率変数
$(Omega, F, P),(Omega,F, Q)$: 確率空間
$(RR,frak(B)(RR), P_X), (RR,frak(B)(RR), Q_X)$: 上記から定まる確率空間
について、
$
D_(K L)(P_X || Q_X) :=
sum_(i=1)^(infinity) p_(X_("dis"))(x_i) log(
frac(p_(X_("dis"))(x_i), q_(X_("dis"))(x_i))
)
+ integral_(RR) p_(X_("abs"))(x) log(
frac(p_(X_("abs"))(x), q_(X_("abs"))(x))
) dif x
$
$p_(X_("dis")) = q_(X_("dis")) = 0$のとき、
$
D_(K L)(p_(X_("abs")) || q_(X_("abs"))) := D_(K L)(P_X || Q_X)
$
ともかく。
#heading(level: 3)[確率変数が複数ある状況の場合]
$X, Y$: 可測空間$(Omega, F)$上の確率変数
$(Omega, F, P)$: 確率空間
を考えると、
$id_(RR)$: 可測空間$(RR,frak(B)(RR))$上の確率変数 (恒等写像)
$(RR,frak(B)(RR), P_X),(RR,frak(B)(RR), P_Y)$: 確率空間
$(RR,frak(B)(RR), (P_X)_(id_(RR))), (RR,frak(B)(RR), (Q_X)_(id_(RR)))$: 確率空間
として、KL-ダイバージェンス を考えることができる。
#heading(level: 2)[parametricな問題]
$
exists p: RR times RR -> RR, quad (x, theta) |-> p_theta(x), "具体的に計算可能", \
exists theta_0 in RR "s.t." p_(X_("abs")) = p_(theta_0)
$
$p_(X_("abs"))$を求める問題をparametricな問題という
($p_(x_3)$についてもだいたい同じ)
#heading(level: 2)[likelihood function]
$(x_i)_(i=1)^n$: n回のtrial が与えられた時、
$
L: RR -> RR, quad theta |-> product_(i=1)^n p(x_i, theta)
$
#heading(level: 2)[log-likelihood function]
$(x_i)_(i=1)^n$: n回のtrial が与えられた時、
$
L_("log"): RR -> RR, quad theta |-> sum_(i=1)^n log(p(x_i, theta))
$
#heading(level: 2)[likelihood estimation]
$L, L_("log")$の最大値、もしくは極値を求める
コイン投げの場合、尤度関数は上に凸なので、極値が求まれば良い
#heading(level: 1)[Sanovの定理]
参考) https://genkuroki.github.io/documents/mathtodon/2017-04-27%20Kullback-Leibler情報量とは何か?.pdf
#heading(level: 2)[経験分布]
r面サイコロを振るということを考える
$
cal(P) = {p = (p_1, ..., p_r) in RR^r | p_1, ..., p_r >= 0, p_1 + ... + p_r = 1}
$
と定めると、$cal(P)$は、有限集合 ${1, ..., r}$上の確率質量関数の集合と同一視できる。
$q = (q_1,...,q_r) in cal(P)$ を固定する。これはあるサイコロqを固定するということ。
$Omega_q := {"サイコロqを投げた時にiが出る" | i=1, ..., r}$
確率空間: $((Omega_q)^n, F_q^n = 2^((Omega_q)^n), P^n)$
$X in F_q^n$は、
$
X = {(ell_i^1)_(i=1,...,n) ,..., (ell_i^j)_(i=1,...,n)} \
(j=0,...,r^n, 1 <= ell_i^j <= r, "ただしj=0の時はX=" "empty")
$
と書ける
$
r^n: "全ての根源事象の数" \
(ell_i^j)_(i=1,...,n): "ある事象Xの中で、i回目に"ell_i^j"が出るようなj番目の根源事象"
$
$P^n: F_q^n -> RR $ を、
$
P^n({(ell_i^1)_(i=1,...,n) ,..., (ell_i^j)_(i=1,...,n)}) :=
(q_(ell^1_1) q_(ell^1_2) ... q_(ell^1_n))
+ ... +
(q_(ell^j_1) q_(ell^j_2) ... q_(ell^j_n))
$
と定める。
$(k_i)_(i=1,...,n)$について、
$
X_((k_w)_(w=1,...,r)) :=
{(ell_i^j)_(i=1,...,n) |
^(forall) w ((ell_i^j = w"となる個数") = k_w)}
$
なる事象の起こる確率は、$\#X_((k_w))_(w=1,...,r) = frac(n !, (k_1 ! ... k_r !))$なので、
$
P^n(X_((k_w)_(w=1,...,r))) = frac(n !, k_1 ! ... k_r !) q_1^(k_1) ... q_r^(k_r)
$
となる。
ここで、集合$cal(P)_n$を、
$
cal(P)_n = {(frac(k_1, n), ..., frac(k_r, n)) |
k_i = 0,1, ..., n, k_1 + ... + k_r = n}
$
と定めると、
$
cal(P)_n subset cal(P)
$
であり、$\#cal(P)_n <= (n+1)^r$ である。
このような$cal(P)_n$の元を、
$
X_((k_i)_(i=1,...,n))"に対しての経験分布"
$
という。
#heading(level: 2)[Sanovの定理]
$q = (q_1,...,q_r) in cal(P)$と、上記の記号の元、確率空間$(cal(P)_n, 2^(cal(P)_n), P_(cal(P)_n, q))$を考える
確率測度は以下のように定める
$
P_(cal(P)_n, q)^(prime): cal(P)_n "の一点集合の集合" -> RR \
{(frac(k_1, n), ..., frac(k_r, n))} |->
frac(n !, k_1 ! ... k_r !) q_1^(k_1) ... q_r^(k_r)
$
$
P_(cal(P)_n, q): 2^(cal(P)_n) -> RR \
{x_1,...,x_k} |-> sum_i^k P_(cal(P)_n, q)^(prime)({x_i})
$
#theorem("1")[
$A subset cal(P)$ がopenである時
$
liminf_(n -> infinity) frac(1, n) log P_(cal(P)_n, q)(A sect cal(P)_n)
>= -inf_(p in A) D_(\KL)(p || q)
$
Aを大きくすると、
((左辺)の$frac(1, n) log P_(cal(P)_n, q)(A sect cal(P)_n)$)は、大きくなるか変わらない
(右辺)は、大きくなるか変わらない
]
#theorem("2")[
$A subset cal(P)$について、
$
limsup_(n -> infinity) frac(1, n) log P_(cal(P)_n, q)(A sect cal(P)_n)
<= -inf_(p in A) D_(\KL)(p || q)
$
]
#theorem("3")[
$A subset cal(P)$が、内部が閉包に含まれるならば、
$
lim_(n -> infinity) frac(1, n) log P_(cal(P)_n, q)(A sect cal(P)_n)
= -inf_(p in A) D_(\KL)(p || q)
$
]
- 仮説Aをとる
- Aは絞られてるほうが、実用上「いい仮説」と言える
- が、Sanovの定理ではそこは興味ない
- $P_(cal(P)_n, q)(A sect cal(P)_n)$ : n回試行時の経験分布がAに入る確率
→ n回振って得られた経験分布を何個も取得して、$P_(cal(P)_n, q)(A sect cal(P)_n)$を定める
- 左辺のnをどんどん大きくして、収束する値によって、Aの「正解っぽさ」がわかる
- もし0に収束しているのならば、Aに真の分布qが含まれていることがわかる
= 2. Algorithm
- 順拡散過程と逆拡散過程の定義
- 逆拡散過程の学習方法
- 逆拡散過程のentropy bounds(エントロピー下界?)を導出する
=== マルコフ拡散カーネル (Markov kernel, 積分変換)
$
T_pi: RR^n times RR^n times RR -> RR_("≥0"),
(bold(y), bold(y)', beta) |-> (bold(y) | bold(y)'\; beta)
$ ($beta$は、拡散率)
$T_pi$は、$d in ZZ_("≥1")$として、任意の$n dot d$変数確率密度関数 $q: RR^(n dot d) -> RR$ に対して、
$
q(x_1, dots, x_d) dot T_pi(x_(d+1) | x_d\; beta)
"はn" dot (d+1)"変数確率密度関数"
$
$pi: RR^n -> RR$ は、以下の第二種フレドホルム積分方程式の解
$
pi(bold(y)) = integral dif bold(y)'
T_pi(bold(y) | bold(y)'\; beta)
pi(bold(y)')
$
===== 正規分布を使った$pi$と$T_pi$がフレドホルム積分方程式の解であること
一次元でチェックする
$pi(y) := cal(N)(y, 0, 1) = 1/(sqrt(2pi)) exp(-y^2/2)$
$
T_pi(y | y'\; beta) := cal(N)(y, y'sqrt(1-beta), beta)
= 1/(sqrt(2pi beta^2))
exp(-(y-y'sqrt(1-beta))^2/(2beta^2))
$
とおく
$pi(y) = integral dif y' T_pi(y | y'\; beta) pi(y')$ が、上記に対して成り立つことを確認する
$
("右辺")
&= integral dif y'
1/(sqrt(2pi beta^2))
exp(-(y-y'sqrt(1-beta))^2/(2beta^2))
1/(sqrt(2pi)) exp(-y'^2/2) \
&= 1/(2pi beta) integral dif y'
exp(
-(y-y'sqrt(1-beta))^2/(2beta^2)
- y'^2/2
) \
&= 1/(2pi beta) integral dif y'
exp(
-(y-y'sqrt(1-beta))^2/(2beta^2)
- y'^2 beta^2/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- (y'^2 beta^2/(2beta^2)
+ (-y'sqrt(1-beta) + y)^2/(2beta^2))
) \
&= 1/(2pi beta) integral dif y'
exp(
- (y'^2 beta^2 + (-y'sqrt(1-beta) + y)^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- (y'^2 beta^2 + (1-beta)y'^2
- 2sqrt(1-beta)y y' + y^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- (y'^2 (1-beta+beta^2) - 2sqrt(1-beta)y y' + y^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- ((1-beta+beta^2)
(y'^2 - (2sqrt(1-beta)y y')/(1-beta+beta^2))
+ y^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- ((1-beta+beta^2)
(y'^2 - (2sqrt(1-beta)y y')/(1-beta+beta^2)
+ ((1-beta)y^2)/((1-beta+beta^2)^2)
- ((1-beta)y^2)/((1-beta+beta^2)^2))
+ y^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- ((1-beta+beta^2)
((y' - (sqrt(1-beta)y)/(1-beta+beta^2))^2
- ((1-beta)y^2)/((1-beta+beta^2)^2))
+ y^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- ((1-beta+beta^2)(y' - (sqrt(1-beta)y)/(1-beta+beta^2))^2
- (1-beta+beta^2) ((1-beta)y^2)/((1-beta+beta^2)^2)
+ y^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- ((1-beta+beta^2)(y' - (sqrt(1-beta)y)/(1-beta+beta^2))^2
- ((1-beta)y^2)/(1-beta+beta^2)
+ y^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- ((1-beta+beta^2)(y' - (sqrt(1-beta)y)/(1-beta+beta^2))^2
- ((1-beta) - (1-beta+beta^2))
/(1-beta+beta^2) y^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- ((1-beta+beta^2)(y' - (sqrt(1-beta)y)/(1-beta+beta^2))^2
+ (beta^2)/(1-beta+beta^2) y^2)
/(2beta^2)
) \
&= 1/(2pi beta)
exp(
- ((beta^2)/(1-beta+beta^2) y^2)
/(2beta^2)
)
integral dif y'
exp(
- ((1-beta+beta^2)(y' - (sqrt(1-beta)y)/(1-beta+beta^2))^2)
/(2beta^2)
) \
&= 1/(2pi beta)
exp(
- ((beta^2)/(1-beta+beta^2) y^2)
/(2beta^2)
)
sqrt(pi / ((1-beta+beta^2)/(2beta^2))) \
&= 1/(2pi beta)
sqrt((2pi beta^2)/(1-beta+beta^2))
exp(
- (y^2)/(2(1-beta+beta^2))
) \
&= 1/(sqrt(2pi(1-beta+beta^2)))
exp(
- (y^2)/(2(1-beta+beta^2))
) \
&= cal(N)(y, 0, sqrt(1-beta+beta^2))
$
あわんかったので、$T_pi(y | y'\; beta) := cal(N)(y, m y', beta)$で計算して、噛み合う$m$を見つける。
$pi(y) := cal(N)(y, 0, 1) = 1/(sqrt(2pi)) exp(-y^2/2)$
$
T_pi(y | y'\; beta) := cal(N)(y, m y', beta)
= 1/(sqrt(2pi beta^2))
exp(-(y-m y')^2/(2beta^2))
$
とおく
$
("右辺")
&= integral dif y'
1/(sqrt(2pi beta^2))
exp(-(y-m y')^2/(2beta^2))
1/(sqrt(2pi)) exp(-y'^2/2) \
&= 1/(2pi beta) integral dif y'
exp(-(y'^2 beta^2 + m^2 y'^2 - 2m y y' + y^2)/(2beta^2)) \
&= 1/(2pi beta) integral dif y'
exp(-((beta^2 + m^2) y'^2 - 2m y y' + y^2)/(2beta^2)) \
&= 1/(2pi beta) integral dif y'
exp(
- ((beta^2 + m^2)
(y'^2 - (2m y y')/(beta^2 + m^2))
+ y^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- ((beta^2 + m^2)
(y'^2 - (2m y y')/(beta^2 + m^2)
+ (m^2 y^2)/((beta^2 + m^2)^2)
- (m^2 y^2)/((beta^2 + m^2)^2))
+ y^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- ((beta^2 + m^2)
((y' - (m y)/(beta^2 + m^2))^2
- (m^2 y^2)/((beta^2 + m^2)^2))
+ y^2)
/(2beta^2)
) \
&= 1/(2pi beta) integral dif y'
exp(
- ((beta^2 + m^2)
(y' - (m y)/(beta^2 + m^2))^2
- (m^2 y^2)/(beta^2 + m^2)
+ y^2)
/(2beta^2)
) \
&= 1/(2pi beta)
exp(
- ((m^2 y^2)/(beta^2 + m^2) - y^2)
/(2beta^2)
)
integral dif y'
exp(
- ((beta^2 + m^2)
(y' - (m y)/(beta^2 + m^2))^2)
/(2beta^2)
) \
&= 1/(2pi beta)
exp(
- ((m^2 y^2 - (beta^2 + m^2) y^2)
/(beta^2 + m^2))
/(2beta^2)
)
sqrt(pi / ((beta^2 + m^2)/(2beta^2))) \
&= 1/(2pi beta)
sqrt((2pi beta^2)/(beta^2 + m^2))
exp(
- ((beta^2 y^2)/(beta^2 + m^2))
/(2beta^2)
) \
&= 1/(sqrt(2pi(beta^2 + m^2)))
exp(
- (y^2)/(2(beta^2 + m^2))
) \
&= cal(N)(y, 0, sqrt(beta^2 + m^2)) (*)
$
$sqrt(beta^2 + m^2) = 1$ より、 $m = sqrt(1-beta^2)$
よって、
$
T_pi(y | y'\; beta) := cal(N)(y, sqrt(1 - beta^2) y', beta)
= 1/(sqrt(2pi beta^2))
exp(-(y-sqrt(1 - beta^2) y')^2/(2beta^2))
$
次回(6/1)
- 連続だと思って計算しているのが、本当は離散じゃないと成り立たないみたいな状況を定量化できると面白いのでは?
- 松尾研で質問してみる \@浅香先生 (6/10)
- Appendix Aの各定理をまとめる。(28) - (36)
- (28)を↑の積分チェックして完了
- $T_pi$になんか条件があるかも (Tpi自体確率密度関数みたいな) ($p(0) = pi$ とか)
- (次回:Appendix B. で、上記の計算を進める)
- $H_q(X^(T))$ を、定義に合わせる
- すると、Appendix B. (43) に着地
- Appendix A.を読む
- ↑ Lの下限が 2.4 (14) の形にすることで示せる
- [いつか] 離散で書き直してみる
- 関数解析に踏み込むとしたら
- 形状最適化問題
- vscodeでTexで書く方法に移植する
- ↑βが小さい時にforwardとreverseが等しくなる、はよくわからないので保留
- モデルの実装(on github)も見てみる https://github.com/Sohl-Dickstein/Diffusion-Probabilistic-Models/blob/master/model.py
- 一旦読み終えてみてから、参考文献見てみる?
- ガウス過程云々
---
$"def."$
$0 <= i <= T"に対して" X^(i) = RR^n$
$1 <= i <= T"に対して" beta_i in RR$ : t-1とtの間の拡散率
$X^(i dots j) := product_(t=i)^j X^(t)$
$bold(x)^(i dots j) := (bold(x)^(i), dots, bold(x)^(j)) in X^(i dots j)$ と書く
== 2.1. Forward Trajectory
次回(7/20)
- $q^(0)$という実数値函数から、$q^(0...T)$まで定める
- $q^(0)$の条件は可測で全域積分すると1, $q^(0...T)$も満たしている(はず)
- -> 確率空間$(RR^(T+1), cal(B)(RR^(T+1)), Q^(0...T))$ が定まる
- $q^(0...T)$を周辺化(Tの軸で微分する)すると、$q^(0...T-1)$になることを確かめる
- 結合確率・条件付き確率・エントロピーなど、一通り、確率密度関数を使って定義し直す
$Q^(0): cal(B)(X^(0)) -> RR$: 確率測度
$q^(0)_(X_("abs")): X^(0) -> RR,\ Q^(0)$から定まる確率密度関数
$q^(0 dots i)_(X_("abs")): X^(0 dots i) -> RR$を
$
q^(0 dots i)_(X_("abs"))(bold(x)^(0 dots i))
:= q^(0)_(X_("abs"))(bold(x)^(0))
product_(j=1)^i (
T_pi(bold(x)^(j) | bold(x)^(j-1)\; beta_j)
)
$
$q^(T)_(X_("abs")): X^(T) -> RR,\
q^(T)_(X_("abs"))(bold(x)^(T))
:= integral dif bold(y)^(0 dots T-1)
q^(0 dots T)_(X_("abs"))(
bold(y)^(0 dots T-1), bold(x)^(T)
)$
また、Radon-Nikodymの逆より、$q^(0 dots i)_(X_("abs")), q^(T)_(X_("abs"))$からそれぞれ、
$Q^(0...i): cal(B)(X^(0 dots i)) -> RR$: 確率測度
$Q^(T): cal(B)(X^(T)) -> RR$: 確率測度
が定まる。
===== 論文との対応
- $H_q(bold(x)^(t)) = H_("entropy")(q^(0 dots t)_(X_("abs")))$
- $
H_q(bold(x)^(t-1) | bold(x)^(t))
= -integral_(
bold(x)^(0 dots t-1) in product_(j=0)^(t-1) X^(j),
bold(x)^(0 dots t) in product_(j=0)^t X^(j)
)
dif bold(x)^(0 dots i) dif y
p^("joint")_((Y, X)_("abs"))(y, bold(x)^(0 dots i))
log(
p^("condi")_((Y, X)_("abs"))(y | bold(x)^(0 dots i))
)
$
- $q(bold(x)^(j) | bold(x)^(j-1)) = T_pi(bold(x)^(j) | bold(x)^(j-1)\; beta_j)$
==== 公式1 (ガウス積分)
$
integral_x (
alpha dot exp(-gamma dot (x-beta)^2)
) dif x
= alpha dot sqrt(pi/gamma)
$
==== 公式2
$
integral_x (
alpha dot
(-gamma dot (x-beta)^2) dot
exp(-gamma dot (x-beta)^2)
) dif x
= -alpha/2 sqrt(pi/gamma)
$
====== 導出
$y := sqrt(gamma)(x - beta) "とおくと、" dif x = 1/(sqrt(gamma)) dif y "より"$
$
integral_y (
alpha dot exp(-y^2) dot (-y^2)
) 1/(sqrt(gamma)) dif y \
&= -1/(sqrt(gamma)) alpha
integral_y y^2 dot exp(-y^2) dif y \
&= -1/(sqrt(gamma)) alpha (sqrt(pi)/2) \
&= -alpha/2 sqrt(pi/gamma)
$
#theorem(
$"Claim" H_("entropy")(q^((0 dots t))_(X_("abs"))) >= H_("entropy")(q^((0 dots t-1))_(X_("abs"))) ("論文"(28))$,
[
$
T_pi(
x^((t)) | x^((t-1))\; beta_t
)
:=
cal(N)(
x^((t)),
sqrt(1 - beta_t^2) x^((t-1)),
beta_t
)
=
1 / (
sqrt(2 pi beta_t^2)
)
exp(
-(
(x^((t)) - sqrt(1 - beta_t^2) x^((t-1)))^2
) / (
2 beta_t^2
)
)
$
とするとき、$beta_t >= sqrt(1 / (2 pi e))$ ならば、
$
H_("entropy")(
q^((0 dots t))_(X_("abs"))
)
>=
H_("entropy")(
q^((0 dots t-1))_(X_("abs"))
)
$
が成り立つ。
]
)
#proof[
$
q^((0 dots t))_(X_("abs"))(x^((0 dots t)))
=
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
T_pi(
x^((t)) | x^((t-1))\; beta_t
)
$
であるから、
$
"右辺"
=
H_("entropy")(q^((0 dots t-1))_(X_("abs")))
=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1))
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
log(
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
)
$
$
"左辺"
=
H_("entropy")(q^((0 dots t))_(X_("abs")))
&=
-integral_(x^((0 dots t)) in product_(j=0)^t X^((j)))
dif x^((0 dots t)) (
q^((0 dots t))_(X_("abs"))(x^((0 dots t)))
dot
log(
q^((0 dots t))_(X_("abs"))(x^((0 dots t)))
)
) \
&=
-integral_(x^((0 dots t)) in product_(j=0)^t X^((j)))
dif x^((0 dots t)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
T_pi(x^((t)) | x^((t-1))\; beta_t)
dot
log(
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
T_pi(x^((t)) | x^((t-1))\; beta_t)
)
) \
&=
-integral_(x^((0 dots t)) in product_(j=0)^t X^((j)))
dif x^((0 dots t)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
T_pi(x^((t)) | x^((t-1))\; beta_t)
dot (
log(
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
)
+
log(
T_pi(x^((t)) | x^((t-1))\; beta_t)
)
)
) \
&=
-integral_(x^((0 dots t)) in product_(j=0)^t X^((j)))
dif x^((0 dots t)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
T_pi(x^((t)) | x^((t-1))\; beta_t)
dot (
log(
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
)
)
) \
&quad
-integral_(x^((0 dots t)) in product_(j=0)^t X^((j)))
dif x^((0 dots t)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
T_pi(x^((t)) | x^((t-1))\; beta_t)
dot (
log(
T_pi(x^((t)) | x^((t-1))\; beta_t)
)
)
)
quad dots quad (*)
$
---
項を分ける
$
(*) "第1項"
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
integral_(x^((t)) in X^((t)))
dif x^((t)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
T_pi(x^((t)) | x^((t-1))\; beta_t)
dot
log(
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
)
)
) \
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
integral_(x^((t)) in X^((t)))
dif x^((t)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
log(
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
)
dot
T_pi(x^((t)) | x^((t-1))\; beta_t)
)
) \
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
log(
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
)
dot
integral_(x^((t)) in X^((t)))
dif x^((t)) (
T_pi(x^((t)) | x^((t-1))\; beta_t)
)
) \
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
log(
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
)
dot
integral_(x^((t)) in X^((t)))
dif x^((t)) (
1 / (
sqrt(2 pi beta_t^2)
)
exp(
-(
(x^((t)) - sqrt(1 - beta_t^2) x^((t-1)))^2
) / (
2 beta_t^2
)
)
)
) \
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
log(
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
)
dot
underbrace(
integral_(x^((t)) in X^((t)))
dif x^((t)) (
underbrace(
1 / (
sqrt(2 pi beta_t^2)
)
, alpha)
exp(
-underbrace(
1 / (
2 beta_t^2
)
, gamma)
dot (
x^((t)) - sqrt(1 - beta_t^2) x^((t-1))
)^2
)
)
, 1)
) \
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
log(
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
)
) \
&= "右辺" \
\
(*) "第2項"
&=
-integral_(x^((0 dots t)) in product_(j=0)^t X^((j)))
dif x^((0 dots t)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
T_pi(x^((t)) | x^((t-1))\; beta_t)
dot (
log(
T_pi(x^((t)) | x^((t-1))\; beta_t)
)
)
) \
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
integral_(x^((t)) in X^((t)))
dif x^((t)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
T_pi(x^((t)) | x^((t-1))\; beta_t)
dot (
log(
T_pi(x^((t)) | x^((t-1))\; beta_t)
)
)
)
) \
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
integral_(x^((t)) in X^((t)))
dif x^((t)) (
T_pi(x^((t)) | x^((t-1))\; beta_t)
dot (
log(
T_pi(x^((t)) | x^((t-1))\; beta_t)
)
)
)
) \
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot
integral_(x^((t)) in X^((t)))
dif x^((t)) (
1 / (
sqrt(2 pi beta_t^2)
)
exp(
-(
(x^((t)) - sqrt(1 - beta_t^2) x^((t-1)))^2
) / (
2 beta_t^2
)
)
dot (
log(
1 / (
sqrt(2 pi beta_t^2)
)
exp(
-(
(x^((t)) - sqrt(1 - beta_t^2) x^((t-1)))^2
) / (
2 beta_t^2
)
)
)
)
)
) \
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot (
integral_(x^((t)) in X^((t)))
dif x^((t)) (
1 / (
sqrt(2 pi beta_t^2)
)
exp(
-(
(x^((t)) - sqrt(1 - beta_t^2) x^((t-1)))^2
) / (
2 beta_t^2
)
)
dot
log(
1 / (
sqrt(2 pi beta_t^2)
)
)
)
+
integral_(x^((t)) in X^((t)))
dif x^((t)) (
1 / (
sqrt(2 pi beta_t^2)
)
exp(
-(
(x^((t)) - sqrt(1 - beta_t^2) x^((t-1)))^2
) / (
2 beta_t^2
)
)
dot (
-(
(x^((t)) - sqrt(1 - beta_t^2) x^((t-1)))^2
) / (
2 beta_t^2
)
)
)
)
) \
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot (
cancel(
1 / (
sqrt(2 pi beta_t^2)
)
)
dot
log(
1 / (
sqrt(2 pi beta_t^2)
)
)
dot
underbrace(
integral_(x^((t)) in X^((t)))
dif x^((t)) (
exp(
-(
(x^((t)) - sqrt(1 - beta_t^2) x^((t-1)))^2
) / (
2 beta_t^2
)
)
)
,
cancel(sqrt(2 pi beta_t^2)) quad ("∵ガウス積分")
)
+
cancel(
1 / (
sqrt(2 pi beta_t^2)
)
)
dot
underbrace(
integral_(x^((t)) in X^((t)))
dif x^((t)) (
exp(
-(
(x^((t)) - sqrt(1 - beta_t^2) x^((t-1)))^2
) / (
2 beta_t^2
)
)
dot (
-(
(x^((t)) - sqrt(1 - beta_t^2) x^((t-1)))^2
) / (
2 beta_t^2
)
)
)
, - 1/2 dot cancel(sqrt(2 pi beta_t^2)) quad ("∵公式2")
)
)
) \
&=
-integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
dot (
log(
1 / (
sqrt(2 pi beta_t^2)
)
)
-
1/2
)
) \
&=
-(
log(
1 / (
sqrt(2 pi beta_t^2)
)
)
-
1/2
)
dot
underbrace(
integral_(x^((0 dots t-1)) in product_(j=0)^(t-1) X^((j)))
dif x^((0 dots t-1)) (
q^((0 dots t-1))_(X_("abs"))(x^((0 dots t-1)))
)
, 1) \
&=
-(
log(
1 / (
sqrt(2 pi beta_t^2)
)
)
-
1/2
) \
&=
1/2
+
1/2
dot
log(
2 pi beta_t^2
) \
&=
1/2
dot (
1
+
log(
2 pi beta_t^2
)
)
$
よって、
$
"左辺" - "右辺"
&=
(
"右辺"
-
1/2 (
1
+
log(
2 pi beta_t^2
)
)
)
-
"右辺" \
&=
1/2 (
1
+
log(
2 pi beta_t^2
)
)
$
ゆえに、$beta_t >= sqrt(1 / (2 pi e))$ の時、不等式が成り立つ
]
#theorem("付録A (30)")[
$
H_q(
bold(X)^(t-1) | bold(X)^(t)
) <= H_q(
bold(X)^(t) | bold(X)^(t-1)
)
$
]
$
H^()_("condi") =
-integral(x in X, y in Y) dif x dif y
p^("joint")_((Y, X)_("abs"))(y, x)
log (
p^("condi")_((Y,X)_("abs"))(y | x)
)
$
(次回 6/29)
- ↑を$q^(0...i)$を使って書く
- この時、$q^(0...i)$ は joint としてしまえることがわかったので、p^(joint)のところにq^(0...i)をそのまま入れる
- 型は、$p^("condi")_((bold(X)^(t-1), bold(X)^(t)))_("abs")(dot.c|dot.c):RR^t times RR^(t-1) -> RR_(>=0)$ みたいになるはず。(ちゃんとやる)
$beta_(t) >= sqrt(1/(2 pi e))$ のとき、
(次回 6/22)
=== メモ
===== 大きな方針
- とりあえずこの本の理論は最後まで追ってみる
- 有限と捉えてちゃんと書いてみた時に、自然と$sqrt(1-beta)$が出てきてくれないか
- 代数的確率空間的に書いてみるとどうなるか
- 各ステップのエントロピー差が有界であることを示している
- (30)で上界がわかる
- ゴールは (36)
== 2.2. Reverse Trajectory
$
p^(T)_(X_("abs")):X^(T)->RR,
p^(T)_(X_("abs"))(bold(x)^(T)) := pi(bold(x)^(T))
$
$
p^(i dots T)_(X_("abs")):
product_(t=i)^T X^(t)->RR
$
$
p^(i dots T)_(X_("abs"))(bold(x)^(i dots T)) :=
p^(T)_(X_("abs"))(bold(x)^(T))
product_(t=1)^T T_pi(
bold(x)^(t-1) | bold(x)^(t)\;beta_(t)
)
$
===== 論文との対応
- $p(bold(x)^(j-1) | bold(x)^(j)) = T_pi(bold(x)^(j-1) | bold(x)^(j)\;beta_(j))$
== 2.3. Model Probability
> これは、統計物理学における準静的過程の場合に相当する
- [非平衡科学](https://sosuke110.com/noneq-phys.pdf)
- [機械学習のための確率過程](https://www.amazon.co.jp/%E6%A9%9F%E6%A2%B0%E5%AD%A6%E7%BF%92%E3%81%AE%E3%81%9F%E3%82%81%E3%81%AE%E7%A2%BA%E7%8E%87%E9%81%8E%E7%A8%8B%E5%85%A5%E9%96%80-%E2%80%95%E7%A2%BA%E7%8E%87%E5%BE%AE%E5%88%86%E6%96%B9%E7%A8%8B%E5%BC%8F%E3%81%8B%E3%82%89%E3%83%99%E3%82%A4%E3%82%BA%E3%83%A2%E3%83%87%E3%83%AB-%E6%8B%A1%E6%95%A3%E3%83%A2%E3%83%87%E3%83%AB%E3%81%BE%E3%81%A7%E2%80%95-%E5%86%85%E5%B1%B1%E7%A5%90%E4%BB%8B-ebook/dp/B0CK176SH5/ref=tmm_kin_swatch_0?_encoding=UTF8&qid=&sr=)
$
p^(0)_(X_("abs")):X^(0)->RR,
p^(0)_(X_("abs"))(bold(x)^(0)) :=
integral dif bold(y)^(1 dots T)
p^(0 dots T)_(X_("abs"))(
bold(x)^(0),bold(y)^(1 dots T)
)
$
$
=
integral dif bold(y)^(1 dots T)
p^(0 dots T)_(X_("abs"))(
bold(x)^(0),bold(y)^(1 dots T)
)
frac(
q^(0 dots T)_(X_("abs"))(
bold(x)^(0),bold(y)^(1 dots T)
),
q^(0 dots T)_(X_("abs"))(
bold(x)^(0),bold(y)^(1 dots T)
)
)
$
$
=
integral dif bold(y)^(1 dots T)
q^(0 dots T)_(X_("abs"))(
bold(x)^(0),bold(y)^(1 dots T)
)
frac(
p^(0 dots T)_(X_("abs"))(
bold(x)^(0),bold(y)^(1 dots T)
),
q^(0 dots T)_(X_("abs"))(
bold(x)^(0),bold(y)^(1 dots T)
)
)
$
$
=
integral dif bold(y)^(1 dots T)
q^(0 dots T)_(X_("abs"))(
bold(x)^(0),bold(y)^(1 dots T)
)
dot.c
frac(
p^(T)_(X_("abs"))(bold(y)^(T)),
q^(0)_(X_("abs"))(bold(x)^(0))
)
dot.c
frac(
T_pi(bold(x)^(0) | bold(y)^(1)\;beta_(t)),
T_pi(bold(y)^(1) | bold(x)^(0)\;beta_(t))
)
dot.c
(
product_(t=2)^T
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
)
$
この積分は、複数のサンプル $q^(0 dots T)_(X_("abs"))(bold(x)^(0),bold(y)^(1 dots T))$ の平均を取ることで、素早く評価できる。
$beta_(t)$が無限小のとき、$frac(T_pi(bold(x)^(0) | bold(y)^(1)\;beta_(t)), T_pi(bold(y)^(1) | bold(x)^(0)\;beta_(t))) dot.c (product_(t=2)^T frac(T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)), T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))))=1$となる。
- つまり、$1 <= t <= T$について、$T_pi(bold(x)^(t-1) | bold(y)^(t)\;beta_(t)) = T_pi(bold(x)^(t) | bold(y)^(t-1)\;beta_(t))$ ← ?
- このとき、上記の積分を評価するのに要求されるのは、単一のサンプル$q^(0 dots T)_(X_("abs"))(bold(x)^(0),bold(y)^(1 dots T))$のみである
> 💡 $q^(0)_(x_(i)):$ 与えられた真のデータの分布
> $p^(0)_(x_(i)):$ Reverse trajectoryを用いて計算された、$q^(0)_(x_(i))$の近似
以下で、$p^(0)_(x_(i)), q^(0)_(x_(i))$のCross Entropyを最小化する
== 2.4. Training
$H(p^(0)_(X_("abs")), q^(0)_(X_("abs"))):$ Cross Entropy
$
H(p^(0)_(X_("abs")), q^(0)_(X_("abs")))
=
-integral_(X^(0)) dif bold(y)^(0)
q_(X_("abs"))^(0)(bold(y)^(0))
dot.c
log p_(X_("abs"))^(0)(bold(y)^(0))
$
$
=
-integral_(X^(0)) dif bold(y)^(0)
q_(X_("abs"))^(0)(bold(y)^(0))
dot.c
log [
integral dif bold(y)^(1 dots T)
q^(0 dots T)_(X_("abs"))(
bold(y)^(0),bold(y)^(1 dots T)
)
dot.c
frac(
p^(T)_(X_("abs"))(bold(y)^(T)),
q^(0)_(X_("abs"))(bold(y)^(0))
)
dot.c
frac(
T_pi(bold(y)^(0) | bold(y)^(1)\;beta_(t)),
T_pi(bold(y)^(1) | bold(y)^(0)\;beta_(t))
)
dot.c
(
product_(t=2)^T
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
)
]
$
$
=
-integral_(X^(0)) dif bold(y)^(0)
q_(X_("abs"))^(0)(bold(y)^(0))
dot.c
log [
integral dif bold(y)^(1 dots T)
frac(
q^(0 dots T)_(X_("abs"))(
bold(y)^(0),bold(y)^(1 dots T)
),
q^(0)_(X_("abs"))(bold(y)^(0))
)
dot.c
p^(T)_(X_("abs"))(bold(y)^(T))
dot.c
frac(
T_pi(bold(y)^(0) | bold(y)^(1)\;beta_(t)),
T_pi(bold(y)^(1) | bold(y)^(0)\;beta_(t))
)
dot.c
(
product_(t=2)^T
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
)
]
$
$
>=
-integral_(X^(0)) dif bold(y)^(0)
q_(X_("abs"))^(0)(bold(y)^(0))
dot.c
(
integral_(X^(1 dots T)) dif bold(y)^(1 dots T)
dot.c
frac(
q^(0 dots T)_(X_("abs"))(
bold(y)^(0),bold(y)^(1 dots T)
),
q^(0)_(X_("abs"))(bold(y)^(0))
)
dot.c
log [
p^(T)_(X_("abs"))(bold(y)^(T))
dot.c
frac(
T_pi(bold(y)^(0) | bold(y)^(1)\;beta_(t)),
T_pi(bold(y)^(1) | bold(y)^(0)\;beta_(t))
)
dot.c
(
product_(t=2)^T
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
)
]
)
$ #h(40pt) (∵ [Jensenの不等式](https://ja.wikipedia.org/wiki/%E3%82%A4%E3%82%A7%E3%83%B3%E3%82%BB%E3%83%B3%E3%81%AE%E4%B8%8D%E7%AD%89%E5%BC%8F), $integral_(X^(1...T)) frac(q^(0 dots T)_(X_("abs"))(bold(y)^(0),bold(y)^(1 dots T)), q^(0)_(X_("abs"))(bold(y)^(0))) = 1$ (∵ 周辺分布の定義) )
$
=
-integral_(X^(0)) dif bold(y)^(0)
(
integral_(X^(1 dots T)) dif bold(y)^(1 dots T)
q_(X_("abs"))^(0)(bold(y)^(0))
dot.c
frac(
q^(0 dots T)_(X_("abs"))(
bold(y)^(0),bold(y)^(1 dots T)
),
q^(0)_(X_("abs"))(bold(y)^(0))
)
dot.c
log [
p^(T)_(X_("abs"))(bold(y)^(T))
dot.c
frac(
T_pi(bold(y)^(0) | bold(y)^(1)\;beta_(t)),
T_pi(bold(y)^(1) | bold(y)^(0)\;beta_(t))
)
dot.c
(
product_(t=2)^T
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
)
]
)
$ #h(40pt) (∵ $q_(X_("abs"))^(0)(bold(y)^(0))$は$integral_(X^(1...T))$において定数)
$
=
- integral_(X^(0 dots T)) dif bold(y)^(0 dots T)
q^(0 dots T)_(X_("abs"))(bold(y)^(0 dots T))
dot.c
log [
p^(T)_(X_("abs"))(bold(y)^(T))
dot.c
(
product_(t=1)^T
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
)
]
$
#h(40pt) (∵ 約分 & 重積分はまとめられる & 細かい略記) (Appendix B. (38) と一致)
$
=
- integral_(X^(0 dots T)) dif bold(y)^(0 dots T)
q^(0 dots T)_(X_("abs"))(bold(y)^(0),bold(y)^(1 dots T))
dot.c
(
log [p^(T)_(X_("abs"))(bold(y)^(T))]
+ sum_(t=1)^T
(
log [
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
]
)
)
$ (1) #h(40pt) (∵ logを和に分解)
$
=
- integral_(X^(0 dots T)) dif bold(y)^(0 dots T)
q^(0 dots T)_(X_("abs"))(bold(y)^(0),bold(y)^(1 dots T))
dot.c
(
sum_(t=1)^T
(
log [
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
]
)
+ log [p^(T)_(X_("abs"))(bold(y)^(T))]
)
$ (1.5) #h(40pt) (∵ 括弧内の和の順序入れ替え)
$
=
- integral_(X^(0 dots T))
(
q^(0 dots T)_(X_("abs"))(bold(y)^(0),bold(y)^(1 dots T))
dot.c
sum_(t=1)^T
(
log [
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
]
)
) dif bold(y)^(0 dots T)
- integral_(X^(0 dots T))
(
q^(0 dots T)_(X_("abs"))(bold(y)^(0),bold(y)^(1 dots T))
dot.c
log [p^(T)_(X_("abs"))(bold(y)^(T))]
) dif bold(y)^(0 dots T)
$ (2) #h(40pt) (∵ 積分を和で分解)
$
=
- integral_(X^(0 dots T))
(
q^(0 dots T)_(X_("abs"))(bold(y)^(0),bold(y)^(1 dots T))
dot.c
sum_(t=1)^T
(
log [
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
]
)
) dif bold(y)^(0 dots T)
- integral_(X^(T)) integral_(X^(0 dots T-1))
(
q^(0 dots T)_(X_("abs"))(bold(y)^(0),bold(y)^(1 dots T))
dot.c
log [p^(T)_(X_("abs"))(bold(y)^(T))]
) dif bold(y)^(0 dots T)
$ (2.5) #h(40pt) (∵ 第二項の積分を被積分変数で分解)
$
=
- integral_(X^(0 dots T))
(
q^(0 dots T)_(X_("abs"))(bold(y)^(0),bold(y)^(1 dots T))
dot.c
sum_(t=1)^T
(
log [
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
]
)
) dif bold(y)^(0 dots T)
- integral_(X^(T))
(
q_(X_("abs"))^(T)(bold(y)^(T))
dot.c
log [p^(T)_(X_("abs"))(bold(y)^(T))]
) dif bold(y)^(T)
$ (3) #h(40pt) (∵ 第二項の内側の積分実行)
$
=
- integral_(X^(0 dots T)) dif bold(y)^(0 dots T)
q^(0 dots T)_(X_("abs"))(bold(y)^(0),bold(y)^(1 dots T))
dot.c
sum_(t=1)^T
(
log [
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
]
)
- H_("cross")(q^(T)_(X_("abs")), p^(T)_(X_("abs")))
$ (4)
$
=
- integral_(X^(0 dots T)) dif bold(y)^(0 dots T)
q^(0 dots T)_(X_("abs"))(bold(y)^(0),bold(y)^(1 dots T))
dot.c
sum_(t=1)^T
(
log [
frac(
T_pi(bold(y)^(t-1) | bold(y)^(t)\;beta_(t)),
T_pi(bold(y)^(t) | bold(y)^(t-1)\;beta_(t))
)
]
)
- H_("cross")(q^(T)_(X_("abs")), p^(T)_(X_("abs")))
$ (5) #h(40pt) ← (論文14と対応させたい)
== 2.5. Multiplying Distributions, and Computing Posteriors
== 2.6. Entropy of Reverse Process
= 3. Experiments
== 3.1. Toy Problem
== 3.2. Images
= 4. Conclusion
= メモ
- 小林さんMTGめも
== 小林さんMTGメモ
= ざっくりした物理的イメージ
- 生成モデルって?
- 何か → 似たやつを作る
- → = 確率分布
- 確率分布 = 分配関数
- 分配関数がわかれば確率分布がわかる
- エネルギーが定義できる状況ならなんでも分配関数が使える
- 情報では?
- 尤度 = エネルギー
- 学習したデータの尤度を高める = その点のポテンシャルを最小化する
- エネルギー(尤度)を最適させるのに適切な関数は何?
- 機械学習で言えば損失関数
-
- 量子コンピュータの種類
- 量子アニーリング
- 量子ゲート
|
|
https://github.com/dankelley/typst_templates | https://raw.githubusercontent.com/dankelley/typst_templates/main/ex/0.0.1/README.md | markdown | MIT License | # Hints for using qe
See `../README.md` for how to install typst and then to install templates,
assuming a macOS machine. (Consult the web for use on other machines.)
To speed the learning process, examine the `sample.typ` file. If you run this
file using
```sh
typst compile sample.typ
```
you ought to get as you see here, in the `sample.pdf` file.
Note that there is also a typst app, but I've not tried using that, because I
prefer editing files in my favourite text editor, and I like using the unix
command-line interface.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/touying/0.2.1/examples/example.typ | typst | Apache License 2.0 | #import "../lib.typ": s, pause, meanwhile, touying-equation, touying-reducer, utils, states, pdfpc, themes
#import "@preview/cetz:0.2.0"
#import "@preview/fletcher:0.4.1" as fletcher: node, edge
#let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide)
#let fletcher-diagram = touying-reducer.with(reduce: (arr, ..args) => fletcher.diagram(..args, ..arr))
// You can comment out the theme registration below and it can still work normally
#let s = themes.metropolis.register(s, aspect-ratio: "16-9", footer: self => self.info.institution)
#let s = (s.methods.info)(
self: s,
title: [Title],
subtitle: [Subtitle],
author: [Authors],
date: datetime.today(),
institution: [Institution],
)
#let s = (s.methods.enable-transparent-cover)(self: s)
#let s = (s.methods.append-preamble)(self: s, pdfpc.config(
duration-minutes: 30,
start-time: datetime(hour: 14, minute: 10, second: 0),
end-time: datetime(hour: 14, minute: 40, second: 0),
last-minutes: 5,
note-font-size: 12,
disable-markdown: false,
default-transition: (
type: "push",
duration-seconds: 2,
angle: ltr,
alignment: "vertical",
direction: "inward",
),
))
// #let s = (s.methods.enable-handout-mode)(self: s)
#let (init, slide, touying-outline, alert) = utils.methods(s)
#show: init
#show strong: alert
// simple animations
#slide[
a simple #pause *dynamic*
#pause
slide.
#meanwhile
meanwhile #pause with pause.
][
second #pause pause.
]
// complex animations
#slide(setting: body => {
set text(fill: blue)
body
}, repeat: 3, self => [
#let (uncover, only, alternatives) = utils.methods(self)
in subslide #self.subslide
test #uncover("2-")[uncover] function
test #only("2-")[only] function
#pause
and paused text.
])
// math equations
#slide[
Touying equation with pause:
#touying-equation(`
f(x) &= pause x^2 + 2x + 1 \
&= pause (x + 1)^2 \
`)
#meanwhile
Touying equation is very simple.
]
// cetz animation
#slide[
Cetz in Touying:
#cetz-canvas({
import cetz.draw: *
rect((0,0), (5,5))
(pause,)
rect((0,0), (1,1))
rect((1,1), (2,2))
rect((2,2), (3,3))
(pause,)
line((0,0), (2.5, 2.5), name: "line")
})
]
// fletcher animation
#slide[
Fletcher in Touying:
#fletcher-diagram(
node-stroke: .1em,
node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%),
spacing: 4em,
edge((-1,0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center),
node((0,0), `reading`, radius: 2em),
edge((0,0), (0,0), `read()`, "--|>", bend: 130deg),
pause,
edge(`read()`, "-|>"),
node((1,0), `eof`, radius: 2em),
pause,
edge(`close()`, "-|>"),
node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)),
edge((0,0), (2,0), `close()`, "-|>", bend: -40deg),
)
]
// multiple pages for one slide
#slide[
#lorem(200)
test multiple pages
]
// appendix by freezing last-slide-number
#let s = (s.methods.appendix)(self: s)
#let (slide,) = utils.methods(s)
#slide[
appendix
] |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/babel/0.1.1/CHANGELOG.md | markdown | Apache License 2.0 | # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.1.1](https://codeberg.org/afiaith/babel/releases/tag/0.1.1) - 2024-10-02
### Changed
- License changed from [CC0](https://creativecommons.org/publicdomain/zero/1.0/) to [MIT-0](https://spdx.org/licenses/MIT-0.html), since CC0 is not OSI-approved and thus cannot be submitted to [Typst Universe](https://typst.app/universe/).
- The precompiled PDF manual moved to the Git repository itself.
## [0.1.0](https://codeberg.org/afiaith/babel/releases/tag/0.1.0) - 2024-10-02
Initial Release.
### Added
- `baffle()`, `redact()`, and `tippex` commands ([`src/baffle.typ`](./src/baffle.typ))
- 75 alphabets ([`src/alphabets.yaml`](./src/alphabets.yaml))
- Logo ([`assets/logo.typ`](./assets/logo.typ))
- ‘Tower of `Babel`’ poster ([`assets/poster.typ`](./assets/poster.typ))
- Manual ([`docs/manual.typ`](./docs/manual.typ))
- Scripts (used for development; [`scripts/`](./scripts/))
- Fundamental files:
- [`README.md`](./README.md)
- [`LICENSE`](./LICENSE)
- [`Justfile`](./Justfile)
- [`typst.toml`](./typst.toml)
- [`CHANGELOG.md`](./CHANGELOG.md) (this file)
|
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/identify-auton-movement/entry.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Identify: Autonomous Movement",
type: "identify",
date: datetime(year: 2023, month: 8, day: 29),
author: "<NAME>",
witness: "<NAME>",
)
Now that we have position tracking we need to put it to use. Autonomous movement
is a tricky problem to solve, especially now that we're tracking the robot in 2
dimensions instead of 1.
#image("./identify.svg", width: 75%)
= Design Constraints
- Cannot be more precise than the position tracking
= Design Goals
- Be able to move in a straight line without drifting from side to side.
- Be able to move to a target point within 0.5" of error.
- Be able to correct for interference.
|
https://github.com/BreakingLead/note | https://raw.githubusercontent.com/BreakingLead/note/main/Math/template-mathnote.typ | typst | #import "@preview/showybox:2.0.1": *
#let law(title,..content) = {
showybox(
title: text(size:1.2em)[*Law: * #title],
title-style:(
boxed-style:(
anchor:(
x: start
)
)
),
frame:(
title-color: green.darken(30%),
body-color: green.lighten(80%),
border-color: green.darken(60%)
),
..content,
)
}
#let definition(title,..content) = {
showybox(
title: text(size:1.2em)[*Definition: * #title],
title-style:(
boxed-style:(
anchor:(
x: start
)
)
),
frame:(
title-color: blue.darken(30%),
body-color: blue.lighten(80%),
border-color: blue.darken(60%)
),
..content,
)
}
#let theorem(title,..content) = {
showybox(
title: text(size:1.2em)[*Theorem: * #title],
title-style:(
color: black,
boxed-style:(
anchor:(
x: start
)
)
),
frame:(
title-color: teal,
body-color: eastern.lighten(80%),
border-color: eastern.darken(60%)
),
..content,
)
}
#let prereqs(title,..content) = {
showybox(
title: text(size:1.2em)[#title],
title-style:(
color: black,
boxed-style:(
anchor:(
x: start
)
)
),
frame:(
title-color: teal,
body-color: eastern.lighten(80%),
border-color: eastern.darken(60%)
),
..content,
)
}
#let statement(title,..content) = {
showybox(
title: text(size:1.2em)[*Statement: #title*],
frame:(
title-color: red.lighten(10%),
body-color: red.lighten(80%),
border-color: red.darken(60%)
),
..content,
)
}
#let warn(title,content) = {
rect(
width: 100%,
stroke:(left:4pt + yellow.darken(10%)),
inset: 10pt,
fill: luma(95%),
)[
#emoji.warning
#text(weight: "bold",size: 1.2em, title)
#linebreak()
#content
]
}
#let answer(content) = rect(fill: luma(240), stroke: (left: 0.25em))[
#content
]
#let template(doc) = {
set text(
font: ("Linux Libertine", "STSong")
)
set page(
paper:"a4",
)
set heading(
numbering: "1.1 ",
bookmarked: true,
)
show heading.where(level: 1): it => {
set align(center)
it
}
show heading.where(level: 2): it => {
set align(center)
it
}
set enum(indent: 2em,numbering: "A)")
doc
} |
|
https://github.com/RhenzoHideki/desenvolvimento-em-fpga | https://raw.githubusercontent.com/RhenzoHideki/desenvolvimento-em-fpga/main/Projeto-Final/relatorio.typ | typst | #import "../typst-ifsc/templates/article.typ":*
#show: doc => article(
title: "Relatório",
subtitle: "Cenário 2 - Travessia Controlada por Botoeira com Sinalização Noturna, Sinalização Piscante, Avisos Sonoros",
// Se apenas um autor colocar , no final para indicar que é um array
authors: ("<NAME>","<NAME> "),
date: "17 de Dezembro de 2023",
doc,
)
= Introdução
== Objetivo
Este projeto, feito na matéria de Dispositivos lógicos programáveis , tem como objetivo simular uma situação de transito , onde, como descrito, é feita a travessia de pedestres em diferentes cenários tanto de manhã quanto a noite . Além de tentar otimizar o transito , evitando fechamentos de semáforos da via principal de forma desnecessária.
== Motivação
Em aula foram ensinados novos conceitos de VHDL, e agora como foi aplicado desde o mais básico até conceitos mais complexos. Dessa forma esse projeto visa certificar que foram aprendidos todos esses conhecimentos.
#pagebreak()
= Descrição do Projeto
== Cenário 2 - Descrição
Visa garantir uma travessia de pedestres diurna e noturna segura e consciente. Ao acionar a botoeira, será ativada uma iluminação branca sobre a faixa de passagem zebrada e nas áreas de espera dos pedestres, assegurando melhor visibilidade e segurança para o pedestre a noite. Simultaneamente, o semáforo emitirá sinais visuais e sonoros, indicando ao pedestre que o botão foi acionado com sucesso e alertando motoristas sobre a intenção de travessia. Durante a fase de liberação para veículos, o semáforo do pedestre permanecerá vermelho, economizando energia até que o botão seja acionado. Após a solicitação, os grupos focais do pedestre exibirão luz verde em ambos os lados da via, enquanto o semáforo dos carros exibirá sinal vermelho, garantindo a máxima segurança para os pedestres e reforçando a prioridade de travessia.
Para orientar pedestres de maneira eficaz, o semáforo do pedestre apresentará um contador regressivo, indicando o tempo restante para a travessia. O tempo total de travessia será ajustável, permitindo personalização conforme as necessidades locais. Nos últimos 30% do tempo, o sinal verde do semáforo do pedestre piscará, visualmente alertando que o tempo para a travessia está se encerrando. É importante ressaltar que a iluminação estará ativa apenas durante o tempo em que a botoeira foi acionada até 5 segundos após o término do tempo de travessia. Este ajuste visa otimizar o consumo de energia e garantir que a iluminação cumpra sua função apenas quando necessária.
#pagebreak()
== Procedimento
Fora de aula foram decididas como seria a divisão do projeto. Foi decidido que era necessário ilustrar como seria feito a maquina de estados antes mesmo de começar o código em vhdl.
#align(center)[
#figure(
image(
"./Figuras/MaquinaDeEstado.svg",width: 110%,
),
caption: [
Elaboração das máquinas de estado \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
Nesse levantamento baseado nos semáforos visto em aula foi possível visualizar quais seriam as diferenças e semelhanças , além de ter ideia das entradas e saídas da máquina de estado do cenário 2.
Após pensar em como seria levantado a máquina de estado , fizemos uma varredura em quais componentes iriam ser necessários para a simular o cenário escolhido , e também atender as requisições feitas pelo professor.
#pagebreak()
Os componentes que foram escolhidos para compor o resto do projeto foram , um conversor bin2bcd , 2 conversores bcd2ssd e um divisor de clock.
A visualização do projeto ficou dessa forma:
#align(center)[
#figure(
image(
"./Figuras/ProjetoVisualicao.jpg",width: 110%,
),
caption: [
Elaboração das máquinas de estado \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
== Componentes utilizados
O componentes utilizados para o projeto podem ser visualizados na Figura 2.
No total foram utilizados 2 displays de sete segmentos , 2 conversor de BCD para ssd , 1 conversor de Binário para BCD , 1 maquina de estados , 1 divisor de clock e 1 clock de 50 MHz , 2 botões para pedestres , 2 LEDs para simbolizar som e luz , 3 LEDs para semáforo de carros e mais 2 LEDs para semáforo de pedestres.
Um divisor de clock com 2 entradas , reset e clock in , e uma saída clock out . Esse divisor tem como objetivo diminuir os pulsos de enable dos segundos , podendo ajustar toda contagem do sistema para diferentes clocks . Apenas trocando o valor genérico do componente "div". Esse divisor de clock foi utilizado anteriormente no projeto do relógio que foi feito em sala , dessa maneira para otimizar o tempo foi decidido reutiliza-lo.
Para a maquina de estado foram criada com 5 entradas , a divisão delas sendo , 1 entrada padrão de reset, 1 entrada para o clock onde é conectada com o divisor de clock. 2 entradas que são das botoeiras para os pedestres que quando apertarem faz o estado mudar para abrir o semáforo dos pedestres e por ultimo uma entrada do sensor de noite.
Existem 8 saídas para a maquina de estado , 3 LEDs que servem para o semáforo dos carros , 2 LEds para o semáforo dos pedestres junto a 1 saída de contagem , uma saída de som e outra para luzes .
A saída de contagem tem como objetivo passar por um conversor binário para bcd , desse saem 2 pontos , 1 deles é para o decimal e outro a unidade que passa para um conversor bcd2ssd , esses são mostrados em 2 display de 7 segmentos que é habilitado quando o pedestre deve passar.
== Sistema Completo
Após ter todos os componentes do projeto foi feita a junção deles.
=== Elementos lógicos do sistema
O numero de elementos lógicos por componente:
#align(center)[
#figure(
image(
"./Figuras/div_clock_EL.png",width: 100%,
),
caption: [
Elementos lógicos do divisor de clock \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
Pode ser observado o uso de 11 elementos lógicos no divisor de clock
#align(center)[
#figure(
image(
"./Figuras/bin2bcd_EL.png",width: 100%,
),
caption: [
Elementos lógicos do bin2bcd \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
No conversor bin2bcd foram utilizadas 98 unidades lógicas , esse valor alto pro conversor deve-se ao conversor binário para bcd que tem um custo alto para ser implementado de forma isolada.
#align(center)[
#figure(
image(
"./Figuras/bcd2ssd_EL.png",width: 100%,
),
caption: [
Elementos lógicos do bcd2ssd \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
Para o conversor bcd para ssd foram utilizados 11 elementos , porém cada elemento trabalha de forma separada . Assim a estimativa para o total de elementos lógicos presente no projeto seria de 22 elementos lógicos para todo o grupo de conversores.
#align(center)[
#figure(
image(
"./Figuras/sinaleira_EL.jpeg",width: 100%,
),
caption: [
Elementos lógicos da maquina de estado \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
A maquina de estado , descrito com o nome 'sinaleira' , sendo o componente mais complexo , ainda sim teve ao todo 66 elementos lógicos utilizados , um numero ainda sim menor que o próprio conversor bin2bcd utilizado.
#pagebreak()
#align(center)[
#figure(
image(
"./Figuras/cenario2_EL.jpeg",width: 100%,
),
caption: [
Elementos lógicos do cenario \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
Por fim temos o número de elementos lógicos do cenário completo. Ao todo foram utilizados menos elementos lógicos do que a soma deles de forma separada , isso porque o Quartus tem diferentes maneiras de otimizar os códigos que são dados a ele.
=== RTL Viewer
Aqui estão os RTLS viewers para cada componente:
#align(center)[
#figure(
image(
"./Figuras/div_clock_RTL.png",width: 100%,
),
caption: [
RTL viewer do divisor de clock \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
Um divisor de clock simples baseado em um contador.
#align(center)[
#figure(
image(
"./Figuras/bin2bcd_RTL.png",width: 100%,
),
caption: [
RTL viewer do bin2bcd \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
O uso de divisão e da operação Mod , duas operações custosas para o hardware.
#align(center)[
#figure(
image(
"./Figuras/bcd2ssd_RTL.png",width: 100%,
),
caption: [
RTL viewer do bcd2ssd \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
A conversão de bcd para ssd , que são vários Mux
#align(center)[
#figure(
image(
"./Figuras/sinaleira_RTL.jpeg",width: 120%,
),
caption: [
RTL viewer da sinaleira \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
A maquina de estado , que ficou com um nível de complexidade em questão de número de elementos aparecendo, e por fim não foi possível tirar print de como ficou os estados dentro da componente amarela isso pois o quartus quando aberta a componente da máquina de estados não mostravas os diferentes estados e suas conexões.
= Implementação na placa
A implementação na placa foi feita em aula com o kit DE2-115 da TERASIC.
== Simulações
#align(center)[
#figure(
image(
"./Figuras/dia.png",width: 120%,
),
caption: [
Simulação Dia \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
#align(center)[
#figure(
image(
"./Figuras/noite.png",width: 120%,
),
caption: [
Simulação Noite \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
Estas são as 2 simulações feitas , visando testar as diferentes possibilidades e erros que podem acontecer em um caso mais proximo da realidade.
Temos 2 imagens , uma representando uma simulação voltada para o dia , onde não se deve ter a saída de luzes , já a outra imagem é feita a simulação representando a noite , dessa forma é possível ver alterações em algumas saídas , como o ativamento de uma luz noturna para o pedestre.
Nessas imagens também é possível observar um caso tratado em aula , caso o botão da botoeira emperre , o fluxo dos carros deve ser mantido até a botoeira ser concertado , por isso foi deixada a botoeira de forma continua para averiguar se foi possível alcançar o que foi desejado.
#pagebreak()
== Pinagem
#align(center)[
#figure(
image(
"./Figuras/pinagem1.png",width: 120%,
),
caption: [
pinagem \ Fonte: Elaborada pelo autor
],
supplement: "Figura"
)
]
Pinagem posteriormente em aula foi trocada para facilitar o uso , trocando os botões pelas chaves . Apenas alterando o botao1 para SW[17] (PIN_Y23) , botao 2 para SW[16] (PIN_Y24) e reset para SW[15] (PIN_AA22). A razão dessa troca dos botões pelos switchs é que testando de diferentes formas , não foi possível inverter a entrada dos botões que começam em 1.g
= Dificuldades
Nesse projeto houveram alguns contra-tempos . Alguns desses como a implementação de uma maquina de estado , pensar na botoeira travada e a criação diferentes situações na simulação. Estes foram alguns do maiores desafios encontrados durante este projeto.
As maquinas de estados se mostraram desafiadoras , pois além de um conteúdo novo , foi-se colocado de forma aos alunos desenvolverem suas próprias máquinas sem o auxilio do professor. Assim necessitando de um maior planejamento e visualização de como deveriam ser feitas os diferentes estados.
A implementação na botoeira foi feita de maneira simples , porém não se tinha pensado em diferentes situações cotidianas como o travamento de uma botoeira, para implementa-lo foi decidido utilizar um contador que contaria o intervalo de tempo que a botoeira ficaria ativa , após um determinado tempo , as botoeiras seriam desabilitadas até que houve-se alguma intervenção que tirasse os inputs das botoeiras.
A criação de diferentes cenários para testagem do cenário se mostrou extremamente complicado uma vez que envolvia diferentes métodos para diferentes falhas. Além disso ao primeiro contato sempre é pensado em cenários mais ideais , deixando complexo a visão de como implementar cenário que podem comprometer o fluxo desejado.
#pagebreak()
= Conclusão
Com esse projeto foi possível colocar em prática todo o conhecimento aprendido nesse semestre. Desde da composição de entidades menores , até maquinas de estados que exigem um maior planejamento .
Com este projeto também é possível visualizar o potencial de utilizar o vhdl para compor um cenário em uma linguagem lógica que pode representar entradas , saídas e diferentes estados.
Por tanto , com a finalização deste projeto foi possível visualizar e aplicar as maquinas de estado em um código , além de uni-lo com o uso de componentes . Tudo isso em um cenário plausível que faz parte do cotidiano. |
|
https://github.com/Leedehai/typst-physics | https://raw.githubusercontent.com/Leedehai/typst-physics/master/physica-manual.typ | typst | MIT License | // Copyright 2023 Leedehai
// This document is shared under the Creative Commons BY-ND 4.0 license.
#import "physica.typ": *
#let version = "0.9.3"
#set document(
title: [physica-manual.typ],
author: ("Leedehai"),
// Prevents setting the creation date to PDF metadata, so the same *.typ
// file content will result in the same *.pdf binary.
date: none,
)
#set page(
numbering: "1/1",
header: align(right)[#text(8pt)[The `physica` package\ version #version]],
)
#set heading(numbering: "1.")
#align(center, text(16pt)[*The `physica` package*])
#let linkurl(s, url) = {
link(url)[#underline(text(fill: blue, s))]
}
#align(center)[
Leedehai \
#linkurl("GitHub", "https://github.com/leedehai/typst-physics") |
#linkurl("Typst", "https://typst.app/docs/packages/")
]
#set par(justify: true)
#v(1em)
#align(center)[
/ physica: _noun_. Latin, study of nature.
]
#v(1em)
#outline(indent: true)
#pagebreak(weak: true)
= Introduction
#v(1em)
#linkurl("Typst", "https://typst.app") is typesetting framework aiming to become the next generation alternative to LATEX. It excels in its friendly user experience and performance.
The `physica` package provides handy Typst typesetting functions that make academic writing for natural sciences simpler and faster, by simplifying otherwise very complex and repetitive expressions in the domain of natural sciences.
This manual itself was generated using the Typst CLI and the `physica` package, so hopefully this document is able to provide you with a sufficiently self evident demonstration of how this package shall be used.
= Using `physica`
#v(1em)
With `typst`'s #linkurl("package management", "https://github.com/typst/packages"):
```typst
#import "@preview/physica:0.9.3": *
$ curl (grad f), pdv(,x,y,z,[2,k]), tensor(Gamma,+k,-i,-j) = pdv(vb(e_i),x^j)vb(e^k) $
```
$ curl (grad f), pdv(,x,y,z,[2,k]), tensor(Gamma,+k,-i,-j)=pdv(vb(e_i),x^j)vb(e^k) $
= The symbols
#v(1em)
// Put the superscript *before* the symbol, in case there are symbols after it.
#let builtin(symbol) = [#super(text(fill: blue, "typst "))#symbol]
#let hl(s) = { // Highlight. Usage: hl("..."), hl(`...`)
show regex("#\(.+?\)|#(\d|\w)+"): set text(eastern)
show regex("\[|\]"): set text(red)
show regex("\w+:"): set text(blue)
show regex(";"): set text(red, weight: "bold")
s
}
#let SUM = $limits(sum)_(i=0)^n i$
Some symbols are already provided as a Typst built-in. They are listed here just for completeness with annotation like #builtin([`this`]), as users coming from LATEX might not know they are already available in Typst out of box.
All symbols need to be used in *math mode* `$...$`.
== Braces
#v(1em)
#table(
columns: (auto, auto, auto, auto),
align: left,
stroke: none,
[*Symbol*], [*Abbr.*], [*Example*], [*Notes*],
[#builtin([`abs(`_content_`)`])],
[],
[`abs(phi(x))` #sym.arrow $abs(phi(x))$],
[absolute],
[#builtin([`norm(`_content_`)`])],
[],
[`norm(phi(x))` #sym.arrow $norm(phi(x))$],
[norm],
[`Order(`_content_`)`],
[],
[`Order(x^2)` #sym.arrow $Order(x^2)$],
[big O],
[`order(`_content_`)`],
[],
[`order(1)` #sym.arrow $order(1)$],
[small O],
[`Set(`_content_`)`],
[],
[
`Set(a_n), Set(a_i, forall i)` \ #sym.arrow $Set(a_n), Set(a_i, forall i)$ \
`Set(vec(1,n), forall n)` \ #sym.arrow $Set(vec(1,n), forall n)$
],
[math set, use `Set` not `set` since the latter is a Typst keyword],
[`evaluated(`_content_`)`],
[`eval`],
[
`eval(f(x))_0^infinity` \ #sym.arrow $eval(f(x))_0^infinity$ \
`eval(f(x)/g(x))_0^1` \ #sym.arrow $eval(f(x)/g(x))_0^1$
],
[attach a vertical bar on the right to denote evaluation boundaries],
[`expectationvalue`],
[`expval`],
[
`expval(u)` #sym.arrow $expval(u)$ \
`expval(p,psi)` #sym.arrow $expval(p,psi)$ \
],
[expectation value, also see bra-ket @dirac-braket below],
)
== Vector notations
#v(1em)
#table(
columns: (5fr, 2fr, auto, 5fr),
align: left,
stroke: none,
[*Symbol*], [*Abbr.*], [*Example*], [*Notes*],
[#builtin([`vec(`...`)`])],
[],
[`vec(1,2)` #sym.arrow $vec(1,2)$],
[column vector],
[`vecrow(`...`)`],
[],
[
`vecrow(alpha, b)` \ #sym.arrow $vecrow(alpha, b)$ \
`vecrow(sum_0^n i, b, delim:"[")` \ #sym.arrow $vecrow(sum_0^n i,b,delim:"[")$ \
],
[row vector],
[`TT`],
[],
[`v^TT, A^TT` #sym.arrow $v^TT, A^TT$],
[transpose, also see\ @matrix-transpose],
[`vectorbold(`_content_`)`],
[`vb`],
[`vb(a),vb(mu_1)` #sym.arrow $vb(a),vb(mu_1)$],
[vector, bold],
[`vectorunit(`_content_`)`],
[`vu`],
[`vu(a),vu(mu_1)` #sym.arrow $vu(a),vu(mu_1)$],
[unit vector],
[`vectorarrow(`_content_`)`],
[`va`],
[`va(a),va(mu_1)` #sym.arrow $va(a),va(mu_1)$],
[vector, arrow \ #sub[(not bold: see ISO 80000-2:2019)]],
[`grad`],
[],
[`grad f` #sym.arrow $grad f$],
[gradient],
[`div`],
[],
[`div vb(E)` #sym.arrow $div vb(E)$],
[divergence],
[`curl`],
[],
[`curl vb(B)` #sym.arrow $curl vb(B)$],
[curl],
[`laplacian`],
[],
[`diaer(u) = c^2 laplacian u` \ #sym.arrow $diaer(u) = c^2 laplacian u$],
[Laplacian,\ not #builtin(`laplace`) $laplace$],
[`dotproduct`],
[`dprod`],
[`a dprod b` #sym.arrow $a dprod b$],
[dot product],
[`crossproduct`],
[`cprod`],
[`a cprod b` #sym.arrow $a cprod b$],
[cross product],
[`innerproduct`],
[`iprod`],
[
`iprod(u, v)` #sym.arrow $iprod(u, v)$ \
`iprod(sum_i a_i, b)` \ #sym.arrow $iprod(sum_i a_i, b)$
],
[inner product],
)
== Matrix notations
#v(1em)
=== Determinant, (anti-)diagonal, identity, zero matrix
#table(
columns: (auto, auto, auto, auto),
align: left,
stroke: none,
[*Symbol*], [*Abbr.*], [*Example*], [*Notes*],
[`TT`],
[],
[`v^TT, A^TT` #sym.arrow $v^TT, A^TT$],
[transpose, also see\ @matrix-transpose],
[#builtin([`mat(`...`)`])],
[],
[`mat(1,2;3,4)` #sym.arrow $mat(1,2;3,4)$],
[matrix],
[`matrixdet(`...`)`],
[`mdet`],
[
#hl(`mdet(1,x;1,y)`) #sym.arrow $mdet(1,x;1,y)$
],
[matrix determinant],
[`diagonalmatrix(`...`)`],
[`dmat`],
[
`dmat(1,2)` #sym.arrow $dmat(1,2)$ \
#hl(`dmat(1,a,xi,delim:"[",fill:0)`) \ #sym.arrow $dmat(1,a,xi,delim:"[",fill:0)$
],
[diagonal matrix],
[`antidiagonalmatrix(`...`)`],
[`admat`],
[
`admat(1,2)` #sym.arrow $admat(1,2)$ \
#hl(`admat(1,a,xi,delim:"[",fill:dot)`) \ #sym.arrow $admat(1,a,xi,delim:"[",fill:dot)$
],
[anti-diagonal matrix],
[`identitymatrix(`...`)`],
[`imat`],
[
`imat(2)` #sym.arrow $imat(2)$ \
#hl(`imat(3,delim:"[",fill:*)`) #sym.arrow \ $imat(3,delim:"[",fill:*)$
],
[identity matrix],
[`zeromatrix(`...`)`],
[`zmat`],
[
`zmat(2)` #sym.arrow $zmat(2)$ \
#hl(`zmat(3,delim:"[")`) #sym.arrow \ $zmat(3,delim:"[")$
],
[zero matrix],
)
=== Jacobian matrix
`jacobianmatrix(`...`)`, i.e. `jmat(`...`)`.
#table(
columns: (25%, auto, auto),
align: center,
stroke: none,
column-gutter: 1em,
[
\ Typst (like LaTeX) \ cramps fractions in a matrix...
],
[
#hl(`jmat(f_1,f_2; x,y)`)
$ jmat(f_1,f_2;x,y) $
],
[
#hl(`jmat(f,g; x,y,z; delim:"[")`)
$ jmat(f,g;x,y,z;delim:"[") $
],
[
\ ...but you can uncramp them using argument #hl(`big:#true`) here
],
[
#hl(`jmat(f_1,f_2;x,y;big:#true)`)
$ jmat(f_1,f_2;x,y;big:#true) $
],
[
#hl(`jmat(f,g;x,y,z;delim:"|",big:#true)`)
$ jmat(f,g;x,y,z;delim:"|",big:#true) $
],
)
=== Hessian matrix
`hessianmatrix(`...`)`, i.e. `hmat(`...`)`.
#table(
columns: (25%, auto, auto),
align: center,
stroke: none,
column-gutter: 1em,
[
\ Typst (like LaTeX) \ cramps fractions in a matrix...
],
[
#hl(`hmat(f; x,y)`)
$ hmat(f; x,y) $
],
[
#hl(`hmat(; x,y,z; delim:"[")`)
$ hmat(; x,y,z; delim:"[") $
],
[
\ ...but you can uncramp them using argument #hl(`big:#true`) here
],
[
#hl(`hmat(f;x,y;big:#true)`)
$ hmat(f;x,y;big:#true) $
],
[
#hl(`hmat(;x,y,z;delim:"|",big:#true)`)
$ hmat(; x,y,z;delim:"|",big:#true) $
],
)
=== Matrix with an element builder
`xmatrix(`_m, n, func_`)`, i.e. `xmat(`...`)`. The element building function
_func_ takes two integers which are the row and column numbers starting from 1.
#table(
columns: (auto, auto),
align: left,
stroke: none,
column-gutter: 1em,
[
#hl(`#let g = (i,j) => $g^(#(i - 1)#(j - 1))$
xmat(2, 2, #g)`)
$ #let g = (i,j) => $g^(#(i - 1)#(j - 1))$
xmat(2, 2, #g) $
],
)
=== Rotation matrices, 2D and 3D
#table(
columns: (auto, auto, auto),
align: center,
stroke: none,
column-gutter: 1em,
[
#hl(`rot2mat(theta)`)
$ rot2mat(theta) $
],
[
#hl(`rot2mat(-a/2,delim:"[")`)
$ rot2mat(-a/2, delim:"[") $
],
[
#hl(`rot2mat(display(a/2),delim:"[")`)
$ rot2mat(display(a/2),delim:"[") $
],
[
#hl(`rot3xmat(theta)`)
$ rot3xmat(theta) $
],
[
#hl(`rot3ymat(45^degree)`)
$ rot3ymat(45^degree) $
],
[
#hl(`rot3zmat(theta,delim:"[")`)
$ rot3zmat(theta,delim:"[") $
],
)
=== Gram matrix
#table(
columns: (auto, auto, auto),
align: center,
stroke: none,
column-gutter: 1em,
[
#hl(`grammat(alpha,beta)`)
$ grammat(alpha, beta) $
],
[
#hl(`grammat(v_1,v_2,v_3, delim:"[")`)
$ grammat(v_1,v_2,v_3, delim:"[") $
],
[
#hl(`grammat(v_1,v_2, norm:#true)`)
$ grammat(v_1,v_2, norm:#true) $
],
)
== Dirac braket notations <dirac-braket>
#v(1em)
#table(
columns: (auto, 1fr, 6fr, 3fr),
align: left,
stroke: none,
[*Symbol*], [*Abbr.*], [*Example*], [*Notes*],
[`bra(`_content_`)`],
[],
[
`bra(u)` #sym.arrow $bra(u)$ \
`bra(vec(1,2))` #sym.arrow $bra(vec(1,2))$
],
[bra],
[`ket(`_content_`)`],
[],
[
`ket(u)` #sym.arrow $ket(u)$ \
`ket(vec(1,2))` #sym.arrow $ket(vec(1,2))$
],
[ket],
[`braket(`..`)`],
[],
[
`braket(a), braket(u, v)` \ #sym.arrow $braket(a), braket(u, v)$ \
`braket(psi,A/N,phi)` #sym.arrow $braket(psi,A/N,phi)$
],
[braket, with 1, 2, or 3 arguments],
[`ketbra(`..`)`],
[],
[
`ketbra(a), ketbra(u, v)` \ #sym.arrow $ketbra(a), ketbra(u, v)$ \
`ketbra(a/N, b)` #sym.arrow $ketbra(a/N, b)$
],
[ketbra, with 1 or 2 arguments],
[`expval(`_content_`)`],
[],
[
`expval(u)` #sym.arrow $expval(u)$ \
`expval(A,psi)` #sym.arrow $expval(A,psi)$
],
[expectation],
[`matrixelement(`..`)`],
[`mel`],
[
`mel(n, diff_nu H, m)` \ #sym.arrow $mel(n, diff_nu H, m)$
],
[matrix element, same as `braket(n,M,n)`],
)
== Math functions
#v(1em)
Typst built-in math operators: #linkurl(`math.op`, "https://typst.app/docs/reference/math/op/").
#table(
columns: (auto, auto),
align: left,
stroke: none,
column-gutter: 25pt,
[*Expressions*], [*Results*],
[`sin(x), sinh(x), arcsin(x), asin(x)`],
[$sin(x), sinh(x), arcsin(x), asin(x)$],
[`cos(x), cosh(x), arccos(x), acos(x)`],
[$cos(x), cosh(x), arccos(x), acos(x)$],
[`tan(x), tanh(x), arctan(x), atan(x)`],
[$tan(x), tanh(x), arctan(x), atan(x)$],
[`sec(x), sech(x), arcsec(x), asec(x)`],
[$sec(x), sech(x), arcsec(x), asec(x)$],
[`csc(x), csch(x), arccsc(x), acsc(x)`],
[$csc(x), csch(x), arccsc(x), acsc(x)$],
[`cot(x), coth(x), arccot(x), acot(x)`],
[$cot(x), coth(x), arccot(x), acot(x)$],
)
#table(
columns: (3fr, 3fr, 4fr),
align: left,
stroke: none,
[*Expressions*], [*Results*], [*Notes*],
[#builtin([`Pr(x)`])],
[$Pr(x)$],
[probability],
[#builtin([`exp x`])],
[$exp x$],
[exponential],
[#builtin([`log x, lg x, ln x`])],
[$log x, lg x, ln x$],
[logarithmic],
[`lb x`],
[$lb x$],
[binary logarithm],
[#builtin([`det A`])],
[$det A$],
[matrix determinant],
[`diag(-1,1,1,1)`],
[$diag(-1,1,1,1)$],
[diagonal matrix, compact form (use `dmat` for the "real" matrix form)],
[`trace A, tr A`],
[$trace A, tr A$],
[matrix trace],
[`Trace A, Tr A`],
[$Trace A, Tr A$],
[matrix trace, alt.],
[`rank A`],
[$rank A$],
[matrix rank],
[`erf(x)`],
[$erf(x)$],
[Gauss error function],
[`Res A`],
[$Res A$],
[residue (complex analysis)],
[`Re z, Im z `],
[$Re z, Im z$],
[real, imaginary (complex analysis)],
[`sgn x`],
[$sgn x$],
[sign function],
)
== Differentials and derivatives
#v(1em)
#table(
columns: (auto, 1fr, 6fr, 5fr),
align: left,
stroke: none,
[*Symbol*], [*Abbr.*], [*Example*], [*Notes*],
[`differential(`...`)`],
[`dd`],
[
e.g. $dd(f), dd(x,y), dd(x,3), dd(x,y,p:and)$ \
See @differentials
],
[differential],
[`variation(`...`)`],
[`var`],
[
`var(f)` #sym.arrow $var(f)$ \
`var(x,y)` #sym.arrow $var(x,y)$ \
],
[variation, shorthand of \ `dd(..., d: delta)`],
[`difference(`...`)`],
[],
[
`difference(f)` #sym.arrow $difference(f)$ \
`difference(x,y)` #sym.arrow $difference(x,y)$ \
],
[difference, shorthand of \ `dd(..., d: Delta)`],
[`derivative(`...`)`],
[`dv`],
[
e.g. $dv(,x), dv(f,x), dv(f,x,k,d:Delta), dv(f,x,s:\/)$ \
See @ordinary-derivatives
],
[derivative],
[`partialderivative(`...`)`],
[`pdv`],
[
e.g. $pdv(,x), pdv(f,x), pdv(f,x,y,2), pdv(f,x,y,[2,3]), pdv(f,x,s:\/)$ \
See @partial-derivatives
],
[partial derivative, could be mixed order],
)
=== Differentials <differentials>
#v(1em)
Functions: `differential(`\*_args_, \*\*_kwargs_`)`, abbreviated as `dd(`...`)`.
- positional _args_: the variable names, *optionally* followed by an order number e.g. `2`, or an order array e.g. `[2,3]`, `[k]`, `[m n, lambda+1]`.
- named _kwargs_:
- `d`: the differential symbol [default: `upright(d)`].
- `p`: the product symbol connecting the components [default: `none`].
- `compact`: only effective if `p` is `none`. If `#true`, will remove the TeXBook-advised thin spaces between the d-units [default: `#false`].
TeXBook advises _[f]ormulas involving calculus look best when an extra thin space
appears before dx or dy or d whatever_ (Chapter 18 p.168), and this package
heeds this advice. If you don't want the spaces between the d-units, you may
pass a `compact:#true` argument: $dd(r,theta) "vs." dd(r,theta,compact:#true)$ (compact).
// https://github.com/typst/typst/issues/147 advocates for set rules for
// non built-in functions. When that's implemented, user can do a
// #set dd(compact: true) to set this param for all dd() invocations.
*Order assignment algorithm:*
- If there is no order number or order array, all variables have order 1.
- If there is an order number (not an array), then this order number is assigned to _every_ variable, e.g. `dd(x,y,2)` assigns $x <- 2, y <- 2$.
- If there is an order array, then the orders therein are assigned to the variables in order, e.g. `dd(f,x,y,[2,3])` assigns $x <- 2, y <- 3$.
- If the order array holds fewer elements than the number of variables, then the orders of the remaining variables are 1, e.g. `dd(x,y,z,[2,3])` assigns $x <- 2, y <- 3, z <- 1$.
- If a variable $x$ has order 1, it is rendered as $upright(d) x$ not $upright(d)^1 x$.
#align(center, [*Examples*])
#grid(
columns: (50%, 50%),
row-gutter: 1em,
column-gutter: 2em,
[
*(1)* #hl(`dd(f), f(r,theta) dd(r,theta)`) \
$ dd(f), f(r,theta) dd(r,theta) $
],
[
*(2)* #hl(`dd(x,3), dd(f,[k]), dd(f,[k],d:delta)`) \
$ dd(x,3), dd(f,[k]), dd(f,[k],d:delta) $
],
[
*(3)* #hl(`dd(f,2), dd(vb(x),t,[3,])`) \
$ dd(f,2), dd(vb(x),t,[3,]) $
],
[
*(4)* #hl(`dd(x,y), dd(x,y,[2,3]), dd(x,y,z,[2,3])`) \
$ dd(x,y), dd(x,y,[2,3]), dd(x,y,z,[2,3]) $
],
[
*(5)* #hl(`dd(x, y, z, [[1,1],rho+1,n_1])`) \
$ dd(x, y, z, [[1,1],rho+1,n_1]) $
],
[
*(6)* #hl(`dd(x,y,d:Delta), dd(x,y,2,d:Delta)`) \
$ dd(x,y,d:Delta), dd(x,y,2,d:Delta) $
],
[
*(7)* #hl(`dd(t,x_1,x_2,x_3,p:and)`) \
$ dd(t,x_1,x_2,x_3,p:and) $
],
[
*(7)* #hl(`dd(t,x_1,x_2,x_3,d:upright(D))`) \
$ dd(t,x_1,x_2,x_3,d:upright(D)) $
]
)
=== Ordinary derivatives <ordinary-derivatives>
#v(1em)
Function: `derivative(`_f_, \*_args_, \*\*_kwargs_`)`, abbreviated as `dv(`...`)`.
- _f_: the function, which can be `#none` or omitted,
- positional _args_: the variable name, *optionally* followed by an order number e.g. `2`,
- named _kwargs_:
- `d`: the differential symbol [default: `upright(d)`].
- `s`: the "slash" separating the numerator and denominator [default: `none`], by default it produces the normal fraction form $dv(f,x)$. The most common non-default is `slash` or simply `\/`, so as to create a flat form $dv(f,x,s:\/)$ that fits inline.
*Order assignment algorithm:* there is just one variable, so the assignment is trivial: simply assign the order number (default to 1) to the variable. If a variable $x$ has order 1, it is rendered as $x$ not $x^1$.
#align(center, [*Examples*])
#grid(
columns: (50%, 50%),
row-gutter: 1em,
column-gutter: 2em,
[
*(1)* #hl(`dv(,x), dv(,x,2), dv(f,x,k+1)`) \
$ dv(,x), dv(,x,2), dv(f,x,k+1) $
],
[
*(2)* #hl(`dv(, vb(r)), dv(f, vb(r)_e, 2)`) \
$ dv(, vb(r)), dv(, vb(r)_e, 2) $
],
[
*(3)* #hl(`dv(f,x,2,s:\/), dv(f,xi,k+1,s:slash)`) \
$ dv(f,x,2,s:\/), dv(f,xi,k+1,s:slash) $
],
[
*(4)* #hl(`dv(, x, d:delta), dv(, x, 2, d:Delta)`) \
$ dv(, x, d:delta), dv(, x, 2, d:Delta) $
],
[
*(5)* #hl(`dv(vb(u), t, 2, d: upright(D))`) \
$ dv(vb(u), t, 2, d: upright(D)) $
],
[
*(6)* #hl(`dv(vb(u),t,2,d:upright(D),s:slash)`) \
$ dv(vb(u),t,2,d:upright(D),s:slash) $
],
)
=== Partial derivatives (incl. mixed orders) <partial-derivatives>
#v(1em)
Function: `partialderivative(`_f_, \*_args_, \*\*_kwargs_`)`, abbreviated as `pdv(`...`)`.
- _f_: the function, which can be `#none` or omitted,
- positional _args_: the variable names, *optionally* followed by an order number e.g. `2`, or an order array e.g. `[2,3]`, `[k]`, `[m n, lambda+1]`.
- named _kwargs_:
- `s`: the "slash" separating the numerator and denominator [default: `none`], by default it produces the normal fraction form $pdv(f,x)$. The most common non-default is `slash` or simply `\/`, so as to create a flat form $pdv(f,x,s:\/)$ that fits inline.
- `total`: the user-specified total order.
- If it is absent, then (1) if the orders assigned to all variables are numeric, the total order number will be *automatically computed*; (2) if non-number symbols are present, computation will be attempted with minimum effort, and a user override with argument `total` may be necessary.
*Order assignment algorithm:*
- If there is no order number or order array, all variables have order 1.
- If there is an order number (not an array), then this order number is assigned to _every_ variable, e.g. `pdv(f,x,y,2)` assigns $x <- 2, y <- 2$.
- If there is an order array, then the orders therein are assigned to the variables in order, e.g. `pdv(f,x,y,[2,3])` assigns $x <- 2, y <- 3$.
- If the order array holds fewer elements than the number of variables, then the orders of the remaining variables are 1, e.g. `pdv(f,x,y,z,[2,3])` assigns $x <- 2, y <- 3, z <- 1$.
- If a variable $x$ has order 1, it is rendered as $x$, not $x^1$.
#align(center, [*Examples*])
#grid(
columns: (50%, 50%),
row-gutter: 1em,
column-gutter: 2em,
[
*(1)* #hl(`pdv(,x), pdv(,t,2), pdv(,lambda,[k])`) \
$ pdv(,x), pdv(,t,2), pdv(,lambda,[k]) $
],
[
*(2)* #hl(`pdv(f,vb(r)), pdv(phi,vb(r)_e,2)`) \
$ pdv(phi,vb(r)), pdv(phi,vb(r)_e,2) $
],
[
*(3)* #hl(`pdv(,x,y), pdv(,x,y,2)`) \
$ pdv(,x,y), pdv(,x,y,2) $
],
[
*(4)* #hl(`pdv(f,x,y,2), pdv(f,x,y,3)`) \
$ pdv(phi,x,y,2), pdv(phi,x,y,3) $
],
[
*(5)* #hl(`pdv(,x,y,[2,]), pdv(,x,y,[1,2])`) \
$ pdv(,x,y,[2,]), pdv(,x,y,[1,2]) $
],
[
*(6)* #hl(`pdv(,t,2,s:\/), pdv(f,x,y,s:slash)`) \
$ pdv(,t,2,s:\/), pdv(f,x,y,s:slash) $
],
[
*(7)* #hl(`pdv(, (x^1), (x^2), (x^3), [1,3])`) \
$ pdv(, (x^1), (x^2), (x^3), [1,3]) $
],
[
*(8)* #hl(`pdv(phi,x,y,z,tau, [2,2,2,1])`) \
$ pdv(phi,x,y,z,tau, [2,2,2,1]) $
],
[
*(9)* #hl(`pdv(,x,y,z,t,[1,xi,2,eta+2])`) \
$ pdv(,x,y,z,t,[1,xi,2,eta+2]) $
],
[
*(10)* #hl(`pdv(,x,y,z,[xi n,n-1],total:(xi+1)n)`) \
$ pdv(,x,y,z,[xi n,n-1],total:(xi+1)n) $
],
)
*(11)* #hl(`integral_V dd(V) (pdv(cal(L), phi) - diff_mu (pdv(cal(L), (diff_mu phi)))) = 0`) \
$ integral_V dd(V) (pdv(cal(L), phi) - diff_mu (pdv(cal(L), (diff_mu phi)))) = 0 $
== Special show rules
#v(1em)
=== Matrix transpose with superscript T <matrix-transpose>
#v(1em)
Matrix transposition can be simply written as `..^T`, just like handwriting,
and the only superscript `T` will be formatted properly to represent
transposition instead of a normal capital letter $T$.
This $square.stroked.dotted^T => square.stroked.dotted^TT$
conversion is disabled if the base is either
- a `limits(...)` or `scripts(...)` element, or
- an integration $integral$ or sum $sum$ (not greek $Sigma$) or product $product$ (not greek $Pi$) or vertical bar $|$, or
- an equation or `lr(...)` element whose last child is one of the above.
Overrides: if you really want to
- print a transpose explicitly: use symbol `TT`: `A^TT` $=> A^TT$;
- print a superscript letter $T$: use `scripts(T)`: `2^scripts(T)` $=> 2^scripts(T)$.
This feature needs to be enabled explicitly through a _show rule_.
```typ
#show: super-T-as-transpose
(A B)^T = B^T A^T
```
If you only want to enable it within a content block's scope, you may do
```typ
#[
#show: super-T-as-transpose // Enabled from here till the end of block.
(A B)^T = B^T A^T
]
```
#align(center, [*Examples*])
#show: super-T-as-transpose // Necessary!
#grid(
columns: (auto, auto),
row-gutter: 1em,
column-gutter: 2em,
[
*(1)* #hl(`(U V_n W')^T = W'^T V_n^T U^T`) \
$ (Sigma V_n W')^T = W'^T V_n^T Sigma^T $
],
[
*(2)* #hl(`vec(a, b)^T, mat(a, b; c, d)^T`) \
$ vec(a, b)^T, mat(a, b; c, d)^T $
],
[
*(3)* #hl(`abs(a)^T, norm(a)^T, eval(F(t))^T_0`) \
$ abs(a)^T, norm(a)^T, eval(F(t))^T_0 $
],
[
*(4)* #hl(`integral^T, sum^T, product^T`) \
$ integral^T, sum^T, product^T $
],
[
*(5)* #hl(`limits(e)^T, scripts(e)^T`) \
$ limits(e)^T, scripts(e)^T $
],
[
*(6)* #hl(`(M+N)^T, (m+n)^scripts(T)`) \
$ (M+N)^T, (m+n)^scripts(T) $
]
)
=== Matrix dagger with superscript +
The conjugate transpose, also known as the Hermitian transpose, transjugate, or
adjoint, of a complex matrix $A$ is performed by first transposing and then
complex-conjugating each matrix element. It is often denoted as $A^*$,
$A^upright(sans(H))$, and sometimes with a dagger symbol:
`A^dagger` $=> A^dagger$.
Writing `..^dagger` often visually clutters an equation in the source code form.
Therefore, the package offers the ability to write `..^+` instead.
This $square.stroked.dotted^+ => square.stroked.dotted^dagger$ conversion is
disabled if the base is either
- a `limits(...)` or `scripts(...)` element, or
- an equation or `lr(...)` element whose last child is one of the above.
This feature needs to be enabled explicitly through a _show rule_.
```typ
#show: super-plus-as-dagger
U^+U = U U^+ = I
```
If you only want to enable it within a content block's scope (e.g. you want
to have $square.stroked.dotted^+$ for ions or Moore–Penrose inverse outside the
block), you may do
```typ
#[
#show: super-plus-as-dagger // Enabled from here till the end of block.
U^+U = U U^+ = I
]
```
Overrides: if you really want to
- print a dagger explicitly: use the built-in symbol `dagger` as normal: `A^dagger` $=> A^dagger$;
- print a superscript plus sign: use `scripts(+)`: `A^scripts(+)` $=> A^scripts(+)$.
#align(center, [*Examples*])
#show: super-plus-as-dagger // Necessary!
#grid(
columns: (auto, auto),
row-gutter: 1em,
column-gutter: 2em,
[
*(1)* #hl(`U^+U = U U^+ = I`) \
$ U^+U = U U^+ = I $
],
[
*(2)* #hl(`mat(1+i,1;2-i,1)^+ = mat(1-i,2+i;1,1)`) \
$ mat(1+i,1;2-i,1)^+ = mat(1-i,2+i;1,1) $
],
[
*(3)* #hl(`limits(N)^+, scripts(N)^+`) \
$ limits(N)^+, scripts(N)^+ $
],
[
*(4)* #hl(`#let eq = $scripts(N)$; eq^+`) \
$ #let eq = $scripts(N)$; eq^+ $
],
)
== Miscellaneous
#v(1em)
=== Reduced Planck constant (hbar)
#v(1em)
In the default font, the Typst built-in symbol `planck.reduce` $planck.reduce$ looks a bit off: on letter "h" there is a slash instead of a horizontal bar, contrary to the symbol's colloquial name "h-bar". This package offers `hbar` to render the symbol in the familiar form: $hbar$. Contrast:
#table(
columns: (auto, auto, auto, auto, auto),
align: horizon,
column-gutter: 1em,
stroke: none,
[Typst's `planck.reduce`],
[$ E = planck.reduce omega $],
[$ (pi G^2) / (planck.reduce c^4) $],
[$ A e^(frac(i(p x - E t), planck.reduce)) $],
[$ i planck.reduce pdv(,t) psi = -frac(planck.reduce^2, 2m) laplacian psi $],
[this package's `hbar`],
[$ E = hbar omega $],
[$ (pi G^2) / (hbar c^4) $],
[$ A e^(frac(i(p x - E t), hbar)) $],
[$ i hbar pdv(,t) psi = -frac(hbar^2, 2m) laplacian psi $],
)
=== Tensors
#v(1em)
Tensors are often expressed using the #linkurl("abstract index notation", "https://en.wikipedia.org/wiki/Abstract_index_notation"), which makes the contravariant and covariant "slots" explicit. The intuitive solution of using superscripts and subscripts do not suffice if both upper (contravariant) and lower (covariant) indices exist, because the notation rules require the indices be vertically separated: e.g. $tensor(T,+a,-b)$ and $tensor(T,-a,+b)$, which are of different shapes. "$T^a_b$" is flatly wrong, and `T^(space w)_(i space j)` produces a weird-looking "$T^(space w)_(i space j)$" (note $w,j$ vertically overlap).
Function: `tensor(`_symbol_, \*_args_`)`.
- _symbol_: the tensor symbol,
- positional _args_: each argument takes the form of $+dots.h$ or $-dots.h$, where a `+` prefix denotes an upper index and a `-` prefix denotes a lower index.
#align(center, [*Examples*])
#grid(
columns: (50%, 50%),
row-gutter: 1em,
column-gutter: 2em,
[
*(1)* #hl(`tensor(u,+a), tensor(v,-a)`) \
$ tensor(u,+a), tensor(v,-a) $
],
[
*(2)* #hl(`tensor(h,+mu,+nu), tensor(g,-mu,-nu)`) \
$ tensor(h, +mu, +nu), tensor(g, -mu, -nu) $
],
[
*(3)* #hl(`tensor(T,+a,-b), tensor(T,-a,+b)`) \
$ tensor(T,+a,-b), tensor(T,-a,+b) $
],
[
*(4)* #hl(`tensor(T, -i, +w, -j)`) \
$ tensor(T, -i, +w, -j) $
],
[
*(5)* #hl(`tensor((dd(x^lambda)),-a)`) \
$ tensor((dd(x^lambda)),-a) $
],
[
*(6)* #hl(`tensor(AA,+a,+b,-c,-d,+e,-f,+g,-h)`) \
$ tensor(AA,+a,+b,-c,-d,+e,-f,+g,-h) $
],
[
*(7)* #hl(`tensor(R, -a, -b, +d)`) \
$ tensor(R, -a, -b, +d) $
],
[
*(8)* #hl(`tensor(T,+1,-I(1,-1),+a_bot,-+,+-)`) \
$ tensor(T,+1,-I(1,-1),+a_bot,-+,+-) $
],
)
*(9)* `grad_mu A^nu = diff_mu A^nu + tensor(Gamma,+nu,-mu,-lambda) A^lambda`
$ grad_mu A^nu = diff_mu A^nu + tensor(Gamma,+nu,-mu,-lambda) A^lambda $
=== Isotopes
#v(1em)
Function: `isotope(`_element_, _a_: ..., _z_: ...`)`.
- _element_: the chemical element (use `".."` for multi-letter symbols)
- _a_: the mass number _A_ [default: `none`].
- _z_: the atomic number _Z_ [default: `none`].
*Change log*: Typst merged my #linkurl("PR", "https://github.com/typst/typst/pull/825"), which fixed a misalignment issue with the surrounding text.
#align(center, [*Examples*])
#grid(
columns: (50%, 50%),
row-gutter: 1em,
column-gutter: 2em,
[
*(1)* #hl(`isotope(I, a:127)`) \
$ isotope(I, a:127) $
],
[
*(2)* #hl(`isotope("Fe", z:26)`) \
$ isotope("Fe", z:26) $
],
)
*(3)* #hl(`isotope("Bi",a:211,z:83) -> isotope("Tl",a:207,z:81) + isotope("He",a:4,z:2)`)
$ isotope("Bi",a:211,z:83) -> isotope("Tl",a:207,z:81) + isotope("He",a:4,z:2) $
*(4)* #hl(`isotope("Tl",a:207,z:81) -> isotope("Pb",a:207,z:82) + isotope(e,a:0,z:-1)`)
$ isotope("Tl",a:207,z:81) -> isotope("Pb",a:207,z:82) + isotope(e,a:0,z:-1) $
=== The n-th term in Taylor series
#v(1em)
Function: `taylorterm(`_func_, _x_, _x0_, _idx_`)`.
- _func_: the function e.g. `f`, `(f+g)`,
- _x_: the variable name e.g. `x`,
- _x0_: the variable value at the expansion point e.g. `x_0`, `(1+a)`,
- _idx_: the index of the term, e.g. `0`, `1`, `2`, `n`, `(n+1)`.
If _x0_ or _idx_ is an add/sub sequence e.g. `-a`, `a+b`, then the function
automatically adds a parenthesis where appropriate.
#align(center, [*Examples*])
#grid(
columns: (50%, 50%),
row-gutter: 1em,
column-gutter: 2em,
[
*(1)* #hl(`taylorterm(f,x,x_0,0)`) \
$ taylorterm(f,x,x_0,0) $
],
[
*(2)* #hl(`taylorterm(f,x,x_0,1)`) \
$ taylorterm(f,x,x_0,1) $
],
[
*(3)* #hl(`taylorterm(F,x^nu,x^nu_0,n)`) \
$ taylorterm(F,x^nu,x^nu_0,n) $
],
[
*(4)* #hl(`taylorterm(f,x,x_0,n)`) \
$ taylorterm(f,x,x_0,n) $
],
[
*(5)* #hl(`taylorterm(f,x,1+a,2)`) \
$ taylorterm(f,x,1+a,2) $
],
[
*(6)* #hl(`taylorterm(f_p,x,x_0,n-1)`) \
$ taylorterm(f_p,x,x_0,n-1) $
],
)
=== Signal sequences (digital timing diagrams)
In engineering, people often need to draw digital timing diagrams for signals, like $signals("1|0|1|0")$.
Function: `signals(str`, `step:`:..., `style`:...`)`.
- `str`: a string representing the signals. Each character represents an glyph (see below).
- `step` (optional): step width, i.e. how wide each glyph is [default: `#1em`].
- `color` (optional): the stroke color [default: `#black`].
#align(center, [*Glyph characters*])
#grid(
columns: (1fr, 1fr, 1fr, 1fr),
row-gutter: 1em,
column-gutter: 2em,
[`HLM` #sym.arrow.l.r.double `"10-"` #text(size: 0.5em, [full step]) \ $ signals("HLM&10-") $],
[`hlm ^v` #text(size: 0.5em, [1/2 step, 1/10 step]) \ $ signals("hlm&^v") $],
[`| ' ,` (edge) #text(size: 0.5em, [0 step]) \ $ signals("|&'&,") $],
[`= #` #text(size: 0.5em, [empty, shaded]) \ $ signals("=&#") $],
[`R` (rise) \ $ signals("R") $],
[`F` (fall) \ $ signals("F") $],
[`C` (charge) \ $ signals("C") $],
[`D` (drain) \ $ signals("D") $],
[`<` \ $ signals("<") $],
[`>` \ $ signals(">") $],
[`X` \ $ signals("X") $],
[],
[ignore: (blankspace) \ separate: `&`],
[repeat: `.` (dot)],
)
#align(center, [*Examples*])
*(1)* `signals("10.1"), signals("1|0|1|0R"), signals("CD"), signals("CD", step: #2em)`
$ signals("10.1"), signals("1|0|1|0R"), signals("CD"), signals("CD", step: #2em) $
*(2)* `signals("M'H|L|h|l|^|v,&|H'M'H|l,m,l|")` (the ampersand `&` serves as a separator)
$ signals("M'H|L|h|l|^|v,&|H'M'H|l,m,l|") $
*(3)* `signals("-|=|-", step: #2em), signals("-|#|-"), signals("-<=>-<=")`
$ signals("-|=|-", step: #2em), signals("-|#|-"), signals("-<=>-<=") $
*(4)* `signals("R1..F0..", step: #.5em)signals("R1.|v|1", step: #.5em, color:#fuchsia)`
$ signals("R1..F0..", step: #.5em)signals("R1.|v|1", step: #.5em, color:#fuchsia) $
*(5)*
```typst
"clk:" & signals("|1....|0....|1....|0....|1....|0....|1....|0..", step: #0.5em) \
"bus:" & signals(" #.... X=... ..... ..... X=... ..... ..... X#.", step: #0.5em)
```
$
"clk:" & signals("|1....|0....|1....|0....|1....|0....|1....|0..", step: #0.5em) \
"bus:" & signals(" #.... X=... ..... ..... X=... ..... ..... X#.", step: #0.5em)
$
== Symbolic addition
#v(1em)
This package implements a very rudimentary, *bare-minimum-effort* symbolic addition function to aid the automatic computation of a partial derivative's total order in the absence of user override (see @partial-derivatives). Though rudimentary and unsophisticated, this should suffice for most use cases in partial derivatives.
Function: `BMEsymadd([`...`])`.
- `...`: symbols that need to be added up e.g. `[1,2]`, `[a+1,b^2+1,2]`.
#align(center, [*Examples*])
#grid(
columns: (auto, auto, auto),
row-gutter: 1em,
column-gutter: 2em,
[*(1)* #hl(`BMEsymadd([1]), BMEsymadd([2, 3])`)],
[#sym.arrow],
[$BMEsymadd([1]), BMEsymadd([2, 3])$],
[*(2)* #hl(`BMEsymadd([a, b^2, 1])`)],
[#sym.arrow],
[$BMEsymadd([a, b^2, 1])$],
[*(3)* #hl(`BMEsymadd([a+1,2c,b,2,b])`)],
[#sym.arrow],
[$BMEsymadd([a+1,2c,b,2,b])$],
[*(4)* #hl(`BMEsymadd([a+1,2(b+1),1,b+1,15])`)],
[#sym.arrow],
[$BMEsymadd([a+1,2(b+1),1,b+1,15])$],
[*(5)* #hl(`BMEsymadd([a+1,2(b+1),1,(b+1),15])`)],
[#sym.arrow],
[$BMEsymadd([a+1,2(b+1),1,(b+1),15])$],
[*(6)* #hl(`BMEsymadd([a+1,2(b+1),1,3(b+1),15])`)],
[#sym.arrow],
[$BMEsymadd([a+1,2(b+1),1,3(b+1),15])$],
[*(7)* #hl(`BMEsymadd([2a+1,xi,b+1,a xi + 2b+a,2b+1])`)],
[#sym.arrow],
[$BMEsymadd([2a+1,xi,b+1,a xi + 2b+a,2b+1])$],
)
#pagebreak()
= Acknowledgement
#v(1em)
Huge thanks to these LATEX packages, for lighting the way of physics typesetting.
- `physics` by <NAME>,
- `derivatives` by <NAME>,
- `tensor` by <NAME> et al.
= License
Source code:
#sym.copyright Copyright 2023 Leedehai. See the license
#linkurl("here", "https://github.com/Leedehai/typst-physics/blob/master/LICENSE.txt").
The document:
Creative Commons Attribution-NoDerivatives 4.0 license (#linkurl("CC BY-ND 4.0", "https://creativecommons.org/licenses/by-nd/4.0/legalcode")).
|
https://github.com/ruziniuuuuu/modern-cv-zh | https://raw.githubusercontent.com/ruziniuuuuu/modern-cv-zh/main/README.md | markdown | # modern-cv-zh
Typst实现的modern-cv简历中文版本,改自[modern-cv.git](https://github.com/DeveloperPaul123/modern-cv.git)。

## 中文字体
用了比较时髦的LXGW WenKai字体,安装方法参考[LxgwWenKai.git](https://github.com/lxgw/LxgwWenKai.git)
|
|
https://github.com/alberto-lazari/computer-science | https://raw.githubusercontent.com/alberto-lazari/computer-science/main/type-theory/theory-exercises/theory-exercises.typ | typst | #set page(numbering: "1")
#set list(marker: ([•], [◦], [--]))
#let unipd-red = rgb(180, 27, 33)
#show heading.where(level: 1): it => {
v(0.5em)
set text(size: 18pt, fill: unipd-red)
[#it.body]
v(0.5pt)
}
#let make_title(title: none, subtitle: none, author: none, date: none) = align(center, [
#text(size: 35pt, weight: "bold", fill: unipd-red, smallcaps(title)) \
#v(5pt)
#text(size: 25pt, weight: "bold", fill: unipd-red, subtitle)
#set text(size: 18pt)
#author
#date
]
)
#v(10em)
#figure(image("images/unipd-logo.png", width: 50%))
#v(3em)
#make_title(
title: [Type Theory],
subtitle: [Theory exercises],
author: [<NAME>],
date: [II Semester A.Y. 2022-2023],
)
#pagebreak()
#include "exercises/singleton.typ"
#include "exercises/natural-numbers.typ"
#include "exercises/equality.typ"
#include "exercises/extra.typ"
|
|
https://github.com/pluttan/typst-g7.32-2017 | https://raw.githubusercontent.com/pluttan/typst-g7.32-2017/main/README.md | markdown | MIT License | # [GOST 7.32-2017 typst](https://github.com/pluttan/g7.32-2017)
В данном репозитории представлены стили для блоков [Typst](https://typst.app) в соответствии с [ГОСТ 7.32-2017](https://github.com/pluttan/typst-g7.32-2017/blob/main/g7.32_2017.pdf).
## Установка
Склонируйте репозиторий в `$HOME`
```bash
git clone https://github.com/pluttan/g7.32-2017
```
И запустите `make`:
```bash
make
```
## Пример работы
`TODO`
## Файл конфигурации
Конфигурация находится там же, где и библиотека, при установки создается мягкая ссылка в директории `.config/typst`(`Appdata/typst` для Windows). Конфигурационный файл распространяется на все файлы, использующие библиотеку.
## TODO
- [ ] Пример работы
- [ ] Проверить правильность ГОСТов
- [x] Конфиг-файл
- [ ] Скрины в readme |
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/text/baseline.typ | typst | Apache License 2.0 | // Test baseline handling.
---
Hi #text(1.5em)[You], #text(0.75em)[how are you?]
Our cockatoo was one of the
#text(baseline: -0.2em)[#box(circle(radius: 2pt)) first]
#text(baseline: 0.2em)[birds #box(circle(radius: 2pt))]
that ever learned to mimic a human voice.
---
Hey #box(baseline: 40%, image("/files/tiger.jpg", width: 1.5cm)) there!
|
https://github.com/yingziyu-llt/blog | https://raw.githubusercontent.com/yingziyu-llt/blog/main/typst_document/linear_algebra/README.md | markdown | ## 模板介绍
SimpleNote 是为撰写简易课程笔记而设计的 Typst 模板,修改自 [jsk-lecnotes](https://github.com/jskherman/jsk-lecnotes),有问题欢迎提交 Issue。
## 使用方法
> [!NOTE]
>
> 此模板需要使用 Typst 0.11.0 及以上版本进行编译。
页面右边点击:**Clone or download -> Download Zip**,将模板文件下载到本地并解压
模板文件夹内主要包含以下七部分:
- main.typ 主文件
- refs.bib 参考文献
- template.typ 文档格式控制,包括一些基础的设置、函数
- resource.typ 存放模板 svg 资源
- /content 正文文件夹,存放正文章节
- /fonts 字体文件夹
- /figures 图片文件夹
使用模板首先需配置 `main.typ`,设置标题、描述、作者等信息,如需要进一步更改文档格式,请修改 `template.typ`。撰写文档请修改 `/content` 文件夹内的文件。
本地编辑建议使用 VSCode 编辑器,并推荐安装 [Tinymist](https://marketplace.visualstudio.com/items?itemName=mgt19937.typst-preview) 与 [Typst Preview](https://marketplace.visualstudio.com/items?itemName=mgt19937.typst-preview) 插件。
## 模板预览
| [封面](https://github.com/a-kkiri/SimpleNote/blob/main/figures/cover.jpg) | [正文1](https://github.com/a-kkiri/SimpleNote/blob/main/figures/content1.jpg) | [正文2](https://github.com/a-kkiri/SimpleNote/blob/main/figures/content2.jpg) |
|:---:|:---:|:---:|
|  |  |  |
> [!CAUTION]
>
>如果要将文档拆分为多个文件进行组织,需要将 `#import "../template.typ": *` 添加到每个文件的顶部,以使某些函数(例如 `blockquote()`)正常工作。
>
> 例如,假设你在项目根目录下有一个 `./content/chapter.typ` 文件和一个 `./template.typ` 文件,那么你需要在 `chapter.typ` 文件顶部添加 `#import "../template.typ": *`。
## 更改记录
2024-5-13
- 修复页眉章节标题显示问题
- 修复公式编号记数问题
- 调整定理环境标题显示位置
2024-4-30
- 更新 typst 包
- codelst: 2.0.0 ——> 2.0.1
- ctheorems: 1.1.0 ——> 1.1.2
- 移除 mitex 包
- 替换默认封面图片
- 更改封面日期显示格式
- 优化页眉章节标题显示逻辑
- 将变量名中的下横线替换为连字号
- 默认使用 codelst 包显示行间代码块 |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/features-11.typ | typst | Other | // Error: 21-26 expected array or dictionary, found boolean
#set text(features: false)
|
https://github.com/francescoo22/kt-uniqueness-system | https://raw.githubusercontent.com/francescoo22/kt-uniqueness-system/main/src/annotation-system.typ | typst | #include "annotation-system/formalization.typ" |
|
https://github.com/sysu/better-thesis | https://raw.githubusercontent.com/sysu/better-thesis/main/utils/datetime-display.typ | typst | MIT License | // 显示中文日期
#let datetime-display(date) = {
date.display("[year] 年 [month] 月 [day] 日")
}
// 显示英文日期
#let datetime-en-display(date) = {
date.display("[month repr:short] [day], [year]")
} |
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/show-selector.typ | typst | Apache License 2.0 | // Test show rule patterns.
---
// Inline code.
#show raw.where(block: false): box.with(
radius: 2pt,
outset: (y: 2.5pt),
inset: (x: 3pt, y: 0pt),
fill: luma(230),
)
// Code blocks.
#show raw.where(block: true): block.with(
outset: -3pt,
inset: 11pt,
fill: luma(230),
stroke: (left: 1.5pt + luma(180)),
)
#set page(margin: (top: 12pt))
#set par(justify: true)
This code tests `code`
with selectors and justification.
```rs
code!("it");
```
You can use the ```rs *const T``` pointer or
the ```rs &mut T``` reference.
---
#show heading.where(level: 1): set text(red)
#show heading.where(level: 2): set text(blue)
#show heading: set text(green)
= Red
== Blue
=== Green
---
// Error: 7-35 this selector cannot be used with show
#show selector(heading).or(figure): none
|
https://github.com/kdog3682/2024-typst | https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/chess-slideshow.typ | typst | #import "base-utils.typ": *
#set page(width: 400pt, height: 300pt)
// 400 to 300 represents 4:3 aspect ratio
// which is the ratio for ipad mini2
#let url = "../chess-assets/interview-demo-tactics/"
#let create-image = create-icon-factory(url)
#let create(n) = {
let img-item = create-image(n, size: 300 - 50)
return align(center + horizon, img-item)
// let label-item = "hi"
// return flex.with(vertical: true)(img-item, label-item)
// need to implement vertical flex
}
#let items = step(12).map(create).join(pagebreak())
#items
|
|
https://github.com/MichaelFraiman/TAU_template | https://raw.githubusercontent.com/MichaelFraiman/TAU_template/main/mfraiman-theorem.typ | typst |
#let theorem(
c, // counter
body,
name: "Theorem",
note: none,
les_num: none,
les_num_symb: "",
body_style: "italic",
numbered: true,
name_func: smallcaps
) = {
if numbered == true {c.step()}
set text(weight: "black")
name_func(name)
if numbered == true {
[ ]
if ( les_num == none ){
context counter(heading).at(here()).first()
} else {les_num}
les_num_symb + [.] + c.display("A") }
if note != none { text(weight: "medium")[ (#smallcaps(note))] }
[.]
text(style: body_style, weight: "regular")[#body]
} |
|
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/src/coords.typ | typst | MIT License | #import "utils.typ": *
#import "deps.typ": cetz
/// Convert from elastic to absolute coordinates, $(u, v) |-> (x, y)$.
///
/// _Elastic_ coordinates are specific to the diagram and adapt to row/column
/// sizes; _absolute_ coordinates are the final, physical lengths which are
/// passed to `cetz`.
///
/// - grid (dictionary): Representation of the grid layout, including:
/// - `origin`
/// - `centers`
/// - `spacing`
/// - `flip`
/// The `grid` is passed to #the-param[diagram][render].
/// - uv (array): Elastic coordinate, `(float, float)`.
#let uv-to-xy(grid, uv) = {
let (i, j) = vector.sub(vector-2d(uv), grid.origin)
let (n-x, n-y) = grid.centers.map(array.len)
if grid.flip.xy { (n-x, n-y) = (n-y, n-x) }
if grid.flip.x { i = (n-x - 1) - i }
if grid.flip.y { j = (n-y - 1) - j }
if grid.flip.xy { (i, j) = (j, i) }
(i, j).zip(grid.centers, grid.spacing)
.map(((t, c, s)) => interp(c, t, spacing: s))
}
/// Convert from absolute to elastic coordinates, $(x, y) |-> (u, v)$.
///
/// Inverse of `uv-to-xy()`.
#let xy-to-uv(grid, xy) = {
let (i, j) = xy.zip(grid.centers, grid.spacing)
.map(((x, c, s)) => interp-inv(c, x, spacing: s))
let (n-x, n-y) = grid.centers.map(array.len)
if grid.flip.xy { (n-x, n-y) = (n-y, n-x) }
if grid.flip.xy { (i, j) = (j, i) }
if grid.flip.x { i = (n-x - 1) - i }
if grid.flip.y { j = (n-y - 1) - j }
vector.add((i, j), grid.origin)
}
/// Jacobian of the coordinate map `uv-to-xy()`.
///
/// Used to convert a "nudge" in $u v$ coordinates to a "nudge" in $x y$
/// coordinates. This is needed because $u v$ coordinates are non-linear
/// (they're elastic). Uses a balanced finite differences approximation.
///
/// - grid (dictionary): Representation of the grid layout.
/// The `grid` is passed to #the-param[diagram][render].
/// - uv (array): The point `(float, float)` in the $u v$-manifold where the
/// shift tangent vector is rooted.
/// - duv (array): The shift tangent vector `(float, float)` in $u v$ coordinates.
#let duv-to-dxy(grid, uv, duv) = {
let duv = vector.scale(duv, 0.5)
vector.sub(
uv-to-xy(grid, vector.add(uv, duv)),
uv-to-xy(grid, vector.sub(uv, duv)),
)
}
/// Jacobian of the coordinate map `xy-to-uv()`.
#let dxy-to-duv(grid, xy, dxy) = {
let dxy = vector.scale(dxy, 0.5)
vector.sub(
xy-to-uv(grid, vector.add(xy, dxy)),
xy-to-uv(grid, vector.sub(xy, dxy)),
)
}
/// Return a vector rooted at a $x y$ coordinate with a given angle $θ$ in $x
/// y$-space but with a length specified in either $x y$-space or $u v$-space.
#let vector-polar-with-xy-or-uv-length(grid, xy, target-length, θ) = {
if type(target-length) == length {
vector-polar(target-length, θ)
} else {
let unit = vector-polar(1pt, θ)
let det = vector.len(dxy-to-duv(grid, xy, unit))
vector.scale(unit, target-length/det)
}
}
#let NAN_COORD = (float("nan"),)*2
#let default-ctx = (
prev: (pt: (0, 0)),
transform: cetz.matrix.ident(),
// transform:
// ((1, 0,-.5, 0),
// (0,-1,+.5, 0),
// (0, 0, .0, 0),
// (0, 0, .0, 1)),
nodes: (:),
length: 1cm,
em-size: (width: 11pt, height: 11pt),
)
#let resolve-system(coord) = {
if type(coord) == dictionary and ("u", "v").all(k => k in coord) {
return "uv"
} else if type(coord) == label {
return "element"
}
let cetz-system = cetz.coordinate.resolve-system(coord)
if cetz-system == "xyz" and coord.len() == 2 {
if coord.all(x => type(x) == length) {
"xyz"
} else if coord.all(x => type(x) in (int, float)) {
"uv"
} else {
error("Coordinates must be two numbers (for elastic coordinates) or two lengths (for physical coordinates); got #0.", coord)
}
} else {
cetz-system
}
}
#let resolve-anchor(ctx, c) = {
// (name: <string>, anchor: <number, angle, string> or <none>)
// "name.anchor"
// "name"
if type(c) == label { c = str(c) }
let (name, anchor) = if type(c) == str {
let (name, ..anchor) = c.split(".")
if anchor.len() == 0 {
anchor = "default"
}
(name, anchor)
} else {
(c.name, c.at("anchor", default: "default"))
}
// Check if node is known
assert(name in ctx.nodes,
message: "Unknown element '" + name + "' in elements " + repr(ctx.nodes.keys()))
// Resolve length anchors
if type(anchor) == length {
anchor = util.resolve-number(ctx, anchor)
}
// Check if anchor is known
let node = ctx.nodes.at(name)
let pos = (node.anchors)(anchor)
if anchor != "default" {
// TODO: support anchors!
// this would require moving edge positioning into a cetz ctx callback
error("Element anchors aren't supported yet! (Found #..0.)", anchor)
}
if pos.all(x => type(x) in (int, float)) {
pos = cetz.util.revert-transform(
ctx.transform,
pos
)
}
return pos
}
#let resolve-relative(resolve, ctx, c) = {
// (rel: <coordinate>, update: <bool> or <none>, to: <coordinate>)
let update = c.at("update", default: true)
let target-system = ctx.target-system
let sub-ctx = ctx + (target-system: auto)
let (ctx, rel) = resolve(sub-ctx, c.rel, update: false)
ctx.target-system = target-system
let (ctx, to) = if "to" in c {
resolve(ctx, c.to, update: false)
} else {
(ctx, ctx.prev.pt)
}
let is-xy(coord) = coord.any(x => type(x) == length)
let is-uv(coord) = not is-xy(coord)
let error-value = (coord: NAN_COORD, update: update)
if is-xy(rel) and is-uv(to) {
if "grid" not in ctx { return error-value }
to = uv-to-xy(ctx.grid, to)
} else if is-uv(rel) and is-xy(to) {
if "grid" not in ctx { return error-value }
to = xy-to-uv(ctx.grid, to)
}
c = vector.add(rel, to)
if ctx.target-system == "xyz" and is-uv(c) {
if "grid" not in ctx { return error-value }
c = uv-to-xy(ctx.grid, c)
} else if ctx.target-system == "uv" and is-xy(c) {
if "grid" not in ctx { return error-value }
c = xy-to-uv(ctx.grid, c)
}
(coord: c, update: update)
}
/// Resolve CeTZ-style coordinate expressions to absolute vectors.
///
/// This is an drop-in replacement of `cetz.coordinate.resolve()` but extended
/// to handle fletcher's elastic $u v$ coordinates alongside CeTZ' physical $x
/// y$ coordinates. The target coordinate system must be specified in the
/// context object `ctx`.
///
/// Resolving $u v$ coordinates to or from $x y$ coordinates requires the
/// diagram's `grid`, which defines the non-linear maps `uv-to-xy()` and
/// `xy-to-uv()`. The `grid` may be supplied in the context object `ctx`.
///
/// If `grid` is not supplied, *coordinate resolution may fail*, in which case
/// the vector #fletcher.NAN_COORD is returned.
///
/// - ctx (dictionary): CeTZ canvas context object, additionally containing:
/// - `target-system`: the target coordinate system to resolve to, one of
/// `"uv"` or `"xyz"`.
/// - `grid` (optional): the diagram's grid specification, defining the
/// coordinate maps $u v <-> x y$. If not given, coordinates requiring this
/// map resolve to #fletcher.NAN_COORD.
///
/// - ..coordinates (coordinate): CeTZ-style coordinate expression(s), e.g.,
/// `(1, 2)`, `(45deg, 2cm)`, or `(rel: (+1, 0), to: "name")`.
#let resolve(ctx, ..coordinates, update: true) = {
assert(ctx.target-system in (auto, "uv", "xyz"))
let result = ()
for c in coordinates.pos() {
let t = resolve-system(c)
let out = if t == "uv" {
if ctx.target-system in (auto, "uv") {
let (u, v) = c // also works for dictionaries
(u, v)
} else if ctx.target-system == "xyz" {
if "grid" in ctx { uv-to-xy(ctx.grid, c) }
else { NAN_COORD }
}
} else if t == "xyz" {
let c = cetz.coordinate.resolve-xyz(c)
c = vector-2d(c).map(x => x.abs + x.em*ctx.em-size.width)
if ctx.target-system in (auto, "xyz") {
c
} else if ctx.target-system == "uv" {
if "grid" in ctx { xy-to-uv(ctx.grid, c) }
else { NAN_COORD }
}
} else if t == "previous" {
(ctx, c) = resolve(ctx, ctx.prev.pt)
c
} else if t == "polar" {
c = vector-2d(cetz.coordinate.resolve-polar(c))
resolve(ctx, c).at(1) // ensure uv <-> xyz conversion
} else if t == "barycentric" {
cetz.coordinate.resolve-barycentric(ctx, c)
} else if t in ("element", "anchor") {
resolve-anchor(ctx, c)
} else if t == "tangent" {
cetz.coordinate.resolve-tangent(resolve, ctx, c)
} else if t == "perpendicular" {
cetz.coordinate.resolve-perpendicular(resolve, ctx, c)
} else if t == "relative" {
let result = resolve-relative(resolve, ctx, c)
update = result.update
result.coord
} else if t == "lerp" {
cetz.coordinate.resolve-lerp(resolve, ctx, c)
} else if t == "function" {
cetz.coordinate.resolve-function(resolve, ctx, c)
} else {
error("Failed to resolve coordinate #0.", c)
}
out = vector-2d(out)
if update { ctx.prev.pt = out }
result.push(out)
}
assert(result.all(c => c.len() == 2))
return (ctx, ..result)
}
#let is-grid-independent-uv-coordinate(coord) = {
let ctx = default-ctx + (target-system: "uv")
(ctx, coord) = resolve(ctx, coord)
not is-nan-vector(coord)
}
|
https://github.com/juruoHBr/typst_xdutemplate | https://raw.githubusercontent.com/juruoHBr/typst_xdutemplate/main/README.md | markdown | # 西安电子科技大学本科毕业设计论文模板
```
#import "template.typ": *
#show: xdudoc.with(
fonts: (
en-main-font: "Times New Roman",
en-heading-font: "Times New Roman",
ch-main-font: "SimSun",
ch-heading-font: "SimHei",
), // 这里配置字体
fontsize : 12pt, //正文字体大小
factor: 1.5, //正文字体行间距
)
#let info = (
title : "某雷达脉压模块与实测数据的分析软件设计", // 论文标题 显示在页眉
covertitle : "某雷达脉压模块与实测数据的\n分析软件设计", //论文标题 显示在封面 使用\n断行
school: "电子工程学院",
major: "电子信息工程",
name : "郑XX",
class : [2101010],
tutor : "陈XX",
number : "21009100000"
)
```
在utils文件中提供了几个有用的工具:
- `fake-par` 假段落 用于占位 解决typst在某些地方不能自动缩进的bug
- `hei` 黑体
- `kai` 楷体
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/numbering-04.typ | typst | Other | #for i in range(0, 4) {
numbering("イ", i)
[ (or ]
numbering("い", i)
[) for #i \ ]
}
... \
#for i in range(47, 51) {
numbering("イ", i)
[ (or ]
numbering("い", i)
[) for #i \ ]
}
... \
#for i in range(2256, 2260) {
numbering("イ", i)
[ for #i \ ]
}
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/call-00.typ | typst | Other | // Ref: true
// Omitted space.
#let f() = {}
#[#f()*Bold*]
// Call return value of function with body.
#let f(x, body) = (y) => [#x] + body + [#y]
#f(1)[2](3)
// Don't parse this as a function.
#test (it)
#let f(body) = body
#f[A]
#f()[A]
#f([A])
#let g(a, b) = a + b
#g[A][B]
#g([A], [B])
#g()[A][B]
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/dynamic/cover.md | markdown | # Cover mode
Covered content (using `#uncover`, `#one-by-one`, `#line-by-line`, or `pause`)
is completely invisible, by default.
You can decide to make it visible but less prominent using the optional `mode`
argument to each of those functions.
The `mode` argument takes two different values: `"invisible"` (the default) and
`"transparent"`.
(This terminology is taken from LaTeX beamer as well.)
With `mode: "transparent"`, text is printed in a light gray.
Use it as follows:
```typ
{{#include cover.typ:6:16}}
```
resulting in

**Warning!**
The transparent mode really only wraps the covered content in a
```typ
#text(fill: gray.lighten(50%)[...]
```
so it has only limited control over the actual display.
Especially
- text that defines its own color (e.g. syntax highlighting),
- visualisations,
- images
will not be affected by that.
This makes the transparent mode only somewhat useful today.
([Relevant GitHub issue](https://github.com/andreasKroepelin/polylux/issues/17))
|
|
https://github.com/hekzam/test | https://raw.githubusercontent.com/hekzam/test/main/template.typ | typst | #import "style.typ": *
#import "write.typ": *
#let f = "file"
#let g = "model"
#let qr(id, page, active) = {
if active {
image("qr/qrcode-" + str(id) + "-" + str(page) + ".png", width: qr_code_size, height: qr_code_size)
} else {
square(size: qr_code_size, fill: white, stroke: 0pt)
}
}
#let sw = 0.50pt
#let case(id, size: 10pt, outset: 0pt, kind: "Unkown") = {
locate(loc => {
let sz = size + outset;
let l = loc.position()
let bb = (t: kind, p: l.page, at: (x: tocm(l.x), y: tocm(l.y), dx: tocm(size+sw/2), dy: tocm(size+sw/2)))
[#append(f, ("q", id), bb)
#square(size: size, outset: outset, stroke: sw + black)]
})
}
#let bcase = case.with(kind: "Binary")
#let marker(id, size: 5pt, fill: black) = {
locate(loc => {
let l = loc.position()
let bb = (x: tocm(l.x+size), y: tocm(l.y+size))
[#checked_new_append(f, ("mk", "d"), tocm(size*2))
#append(f, ("mk", id), bb)
#square(size: size*2, fill: fill.negate(), stroke: 0pt, inset: 0pt, circle(radius: size, fill: fill, stroke: 0pt))]
})
} |
|
https://github.com/jamesrswift/ionio-illustrate | https://raw.githubusercontent.com/jamesrswift/ionio-illustrate/main/src/extras/callout-above.typ | typst | MIT License | #import "@preview/cetz:0.1.2"
#let _prepare(self, ctx) = {
if (self.mz <= ctx.prototype.range.at(0) or
self.mz >= ctx.prototype.range.at(1) ){ return (:) }
let data = (if ( ctx.reflected ){ ctx.prototype.data2 } else { ctx.prototype.data1 })
let y = (ctx.prototype.get-intensity-at-mz)(self.mz, input: data)
self.coordinates = ( (self.mz, y),)
return self
}
#let _stroke(self, ctx) = {
cetz.draw.content(
anchor: self.anchors.at(0),
self.coordinates.at(0),
//(72, 80),
box(inset: self.inset, [#self.content]),
..ctx.prototype.style.callouts
)
}
#let callout-above(mz, content:none, inset: 0.3em, ) = {
if ( content == none ) { content = mz }
return ((
type: "callout",
mz: mz,
content: content,
inset: inset,
anchors: ("bottom",),
plot-prepare: _prepare,
plot-stroke: _stroke,
),)
} |
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/dynamic/handout.md | markdown | # Handout mode
If you distribute your slides after your talk for further reference, you might
not want to keep in all the dynamic content.
Imagine using `one-by-one` on a bullet point list and readers having to scroll
through endless pages when they just want to see the full list.
You can use `#enable-handout-mode(true)` at the top of your code to achieve this:
It has the effect that all dynamic visibility of elements _that reserve space_
is switched off.
For example,
```typ
{{#include handout.typ:5:11}}
```
becomes:

Note that `only` and `alternatives` are **not** affected as there is no obvious
way to unify their content to one slide.
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-A930.typ | typst | Apache License 2.0 | #let data = (
("REJANG LETTER KA", "Lo", 0),
("REJANG LETTER GA", "Lo", 0),
("REJANG LETTER NGA", "Lo", 0),
("REJANG LETTER TA", "Lo", 0),
("REJANG LETTER DA", "Lo", 0),
("REJANG LETTER NA", "Lo", 0),
("REJANG LETTER PA", "Lo", 0),
("REJANG LETTER BA", "Lo", 0),
("REJANG LETTER MA", "Lo", 0),
("REJANG LETTER CA", "Lo", 0),
("REJANG LETTER JA", "Lo", 0),
("REJANG LETTER NYA", "Lo", 0),
("REJANG LETTER SA", "Lo", 0),
("REJANG LETTER RA", "Lo", 0),
("REJANG LETTER LA", "Lo", 0),
("REJANG LETTER YA", "Lo", 0),
("REJANG LETTER WA", "Lo", 0),
("REJANG LETTER HA", "Lo", 0),
("REJANG LETTER MBA", "Lo", 0),
("REJANG LETTER NGGA", "Lo", 0),
("REJANG LETTER NDA", "Lo", 0),
("REJANG LETTER NYJA", "Lo", 0),
("REJANG LETTER A", "Lo", 0),
("REJANG VOWEL SIGN I", "Mn", 0),
("REJANG VOWEL SIGN U", "Mn", 0),
("REJANG VOWEL SIGN E", "Mn", 0),
("REJANG VOWEL SIGN AI", "Mn", 0),
("REJANG VOWEL SIGN O", "Mn", 0),
("REJANG VOWEL SIGN AU", "Mn", 0),
("REJANG VOWEL SIGN EU", "Mn", 0),
("REJANG VOWEL SIGN EA", "Mn", 0),
("REJANG CONSONANT SIGN NG", "Mn", 0),
("REJANG CONSONANT SIGN N", "Mn", 0),
("REJANG CONSONANT SIGN R", "Mn", 0),
("REJANG CONSONANT SIGN H", "Mc", 0),
("<NAME>", "Mc", 9),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
("REJANG SECTION MARK", "Po", 0),
)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/op-01.typ | typst | Other | // With or without parens.
$ &sin x + log_2 x \
= &sin(x) + log_2(x) $
|
https://github.com/piepert/typst-custombib | https://raw.githubusercontent.com/piepert/typst-custombib/main/typst-custombib-generator.typ | typst | #import "remove-accents.typ": remove-accents
#let TCBSTATES = (
last-citation: state("tcb-last-citation"),
used-citations: state("tcb-bibliography-citations-used"),
citation-history: state("tcb-bibliography-citation-history"),
data: state("tcb-bibliography-data"),
style: state("tcb-bibliography-style")
)
#let parse-name(name) = {
let splits = name.replace("\\ ", "<SPACE>").split(" ")
let first = none
let middle = none
let last = none
if splits.len() == 1 {
last = splits.at(0)
} else if splits.len() == 2 {
first = splits.at(0)
last = splits.at(1)
} else if splits.len() > 2 {
first = splits.first()
last = splits.last()
middle = splits.slice(1, splits.len()-1).join(" ")
}
(first: if first != none { first.replace("<SPACE>", " ") },
middle: if middle != none { middle.replace("<SPACE>", " ") },
last: if last != none { last.replace("<SPACE>", " ") })
}
#let parse-names(names) = {
if type(names) == "array" {
names.map(e => parse-name(e))
} else {
(parse-name(names),)
}
}
#let get-option(location, keys) = {
let keys = keys.split(".")
let style = TCBSTATES.style.at(location)
for key in keys {
if key in style or type(style) != "dictionary" {
style = style.at(key)
} else {
return strong(text(red, [OPTION #(keys.join(".")) NOT FOUND!]))
}
}
return style
}
#let has-option(location, keys) = {
let keys = keys.split(".")
let style = TCBSTATES.style.at(location)
for key in keys {
if key in style or type(style) != "dictionary" {
style = style.at(key)
} else {
return false
}
}
return true
}
#let generate-citation(location,
style,
bib-data,
key,
postfix: none,
prefix: none,
citation-position: "inline") = {
// for custom run custom
// format-by-entry-type(format-fields(entry))
// ...
let bib-data = TCBSTATES.data.at(location)
let style = TCBSTATES.style.at(location)
if bib-data == none or style == none {
panic("bibliography error!")
}
let entry = bib-data.at(key, default: none)
let format = get-option(location, citation-position+".format")
let mutator = get-option(location, citation-position+".mutator")
if type(format) == "content" {
return format
}
if entry == none {
return strong(text(red, [KEY #key NOT FOUND!]))
}
entry.insert("postfix", postfix)
entry.insert("prefix", prefix)
if type(mutator) != "content" {
entry = mutator(entry)
}
if entry.entry-type == "custom" {
let styler = get-option(location, "custom."+citation-position)
if type(styler) == "content" {
return styler // is error
}
return format(entry, styler(entry))
}
let fallback = get-option(location, citation-position+".types.fallback")
let styler = get-option(location, citation-position+".types."+entry.entry-type)
let citation = (:)
if type(fallback) == "content" {
return fallback // is error
}
let author = if has-option(location, citation-position+".fields.author") {
get-option(location, citation-position+".fields.author")
} else {
get-option(location, "fields.author")
}
let authors = get-option(location, "fields.authors")
if type(authors) != "content" { // NO ERROR, STYLE AUTHORS
citation.insert("authors", authors(entry, parse-names(entry.author)
.map(e => if type(author) == "content" {
e
} else {
author(entry, e)
})))
}
for field in entry.keys() {
if field == "author" {
continue
}
let fallback = get-option(location, "fields.fallback")
let styler = if has-option(location, citation-position+".fields."+field) {
get-option(location, citation-position+".fields."+field)
} else {
get-option(location, "fields."+field)
}
if type(fallback) == "content" {
return fallback
}
if type(styler) == "content" {
citation.insert(field, fallback(entry, entry.at(field)))
} else {
citation.insert(field, styler(entry, entry.at(field)))
}
}
format(entry, if type(styler) == "content" {
fallback(entry, citation)
} else {
styler(entry, citation)
})
}
#let generate-citation-inline(location,
style,
bib-data,
key,
postfix: none,
prefix: none) = {
generate-citation(location,
style,
bib-data,
key,
postfix: postfix,
prefix: prefix,
citation-position: "inline")
}
#let generate-citation-bibliography(location,
style,
bib-data,
key,
postfix: none,
prefix: none) = {
generate-citation(location,
style,
bib-data,
key,
postfix: postfix,
prefix: prefix,
citation-position: "bibliography")
}
#let get-sorter(location, object) = {
if object.at("entry-type") == "custom" {
let s = get-option(location, "custom.sort-by")
if type(s) == "content" {
return s
}
return object.at(s, default: strong(text(red, [THE SORT-BY FACTOR #s IS NOT IN #object.key!])))
}
let names = parse-names(object.at("author"))
return remove-accents(if "author-sorter" in object { object.author-sorter } else { names.map(name => name.last+", "+name.first+" "+name.middle).join("; ", last: " & ") } + ": " + object.at("title") + ". " + object.at("year"))
}
#let generate-bibliography(location,
style,
bib-data,
used) = {
heading(get-option(location, "options.title"))
let used = ("none": (section: none, heading: none, used: ()))
let sections = get-option(location, "sections")
if type(sections) == "content" {
return sections // is an error
}
let show-sections = get-option(location, "options.show-sections")
if type(show-sections) == "content" {
return show-sections // is error
}
for s in sections.keys() {
used.insert(s, (section: s, heading: sections.at(s), used: ()))
}
let bib-data = TCBSTATES.data.at(location)
for key in TCBSTATES.used-citations.at(location) {
let entry = bib-data.at(key, default: none)
if entry == none {
return strong(text(red, [KEY #key NOT FOUND!]))
}
entry.insert("key", key)
let sorter = get-sorter(location, entry)
if type(sorter) == "content" {
return sorter
}
let sec-key = entry.at("section", default: "none")
let arr = used.at(sec-key).used
arr.push((
key: key,
sort-by: sorter,
entry: entry
))
if not show-sections {
for e in arr {
used.at("none").used.push(e)
}
} else {
used.at(sec-key).used = arr
}
}
let splitter = "\\#"
let unsectioned-citations = used.at("none", default: ())
.used
.map(e => e.sort-by+splitter+e.key)
.sorted()
.map(e => par(hanging-indent: 1.5em,
generate-citation(location,
TCBSTATES.style.at(location),
TCBSTATES.data.at(location),
e.split(splitter).last(), // key
citation-position: "bibliography")))
if unsectioned-citations.len() > 0 {
stack(dir: ttb,
spacing: 1em,
..unsectioned-citations)
}
if show-sections {
for s in used.keys() {
let used = used.at(s)
if used.section == none {
continue
}
if used.used.len() > 0 {
heading(level: 2, eval("["+used.heading+"]"))
stack(dir: ttb,
spacing: 1em,
..used.used
.map(e => e.sort-by+splitter+e.key)
.sorted()
.map(e => par(hanging-indent: 1.5em,
generate-citation(location,
TCBSTATES.style.at(location),
TCBSTATES.data.at(location),
e.split(splitter).last(),
citation-position: "bibliography"))))
}
}
}
} |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/foundations-13.typ | typst | Other | // Test the `type` function.
#test(type(1), "integer")
#test(type(ltr), "direction")
#test(type(10 / 3), "float")
|
https://github.com/barrel111/readings | https://raw.githubusercontent.com/barrel111/readings/main/problems/external/1910SU/week2.typ | typst | #import "@local/preamble:0.1.0": *
#import "@preview/cetz:0.2.2": canvas, plot
#show: project.with(
course: "1910SU",
sem: "Summer",
title: "Group Discussion: Differentiation II",
subtitle: "Solutions",
contents: false,
)
= Quotient Rule
== $d/(d x) tan x$
$ d/(d x) tan(x) &= d/(d x) ((sin x)/(cos x)) \ &= sin x (d/(d x) 1/(cos x)) + 1/(cos x) (d/(d x) sin x) \ &= sin x (-1/(cos^2 x) dot (- sin x)) + (cos x)/(cos x) \ &= (sin^2 x)/(cos^2 x) + 1 \ &= 1/(cos^2 x) = sec^2 x. $
== $d/(d x) sec x$
$ d/(d x) sec x &= d/(d x) (1/(cos x)) \ &= -1/(cos^2 x) dot (- sin (x)) \ &= (sin x)/(cos^2 x) \ &= tan x sec x. $
== $d/(d x) csc x$
$ d/(d x) csc x &= d/(d x) (1/(sin x)) \ &= -(cos x)/(sin^2 x) \ &= - cot x csc x. $
= Chain Rule
== $d/(d x) arcsin x$
~
By definition,
$ sin(arcsin x) = x. $
Differentiating both sides,
$ d/(d x) sin(arcsin x) = d/(d x) x. $
To be a bit more explicit about the use of the Chain Rule, suppose $y = arcsin x$.
Then,
$ implies (d/(d y) sin y) (d/(d x) arcsin x) = 1 \
implies d/(d x) arcsin x = 1/(cos y) = 1/(cos(arcsin x)) = 1/(sqrt(1 - x^2)). $
How do we show that $cos(arcsin x) = sqrt(1 - x^2)$ ? There are two methods
(though, maybe a better descriptor would be that they are two different
perspectives for the same underlying proof):
=== Algebraically showing $cos(arcsin x) = sqrt(1 - x^2)$
Recall that $ sin^2 theta + cos^2 theta = 1. $
So, $ cos theta = plus.minus sqrt(1 - (sin theta)^2). $
In our case, $theta = arcsin x$. The range of $arcsin x$ is $theta in [- pi/2, pi/2]$.
In this range, $cos$ is always positive, so it suffices to take just the
positive square root to obtain
$ cos(arcsin x) = sqrt(1 - sin^2(arcsin x)) = sqrt(1 - x^2). $
=== Geometrically showing $cos(arcsin x) = sqrt(1 - x^2)$
Let $y = arcsin x$. Then note that $y$ represents the angle in a right-angled
triangle with unit hypotenuse and perpendicular with side length $sin(y) = x$.
Pictorally,
#align(center)[#image("graphics/cos arcsin.png", width: 35%)]
Note that $cos y$ then corresponds to the adjacent side whose length can be
obtained by using Pythagoras's Theorem-- $ cos y &= sqrt(1 - sin^2 y) \ &= sqrt(1 - x^2) \ implies cos (arcsin x) &= sqrt(1 - x^2.) $
== $d/(d x) arctan x$
~
By definition,
$ tan(arctan x) = x. $
Differentiating both sides,
$ d/(d x) tan(arctan x) = d/(d x) x. $
To be a bit more explicit about the use of the Chain Rule, suppose $y = arccos x$.
Then,
$ implies (d/(d y) tan y) (d/(d x) arctan x) = 1 \
implies d/(d x) arctan x = 1/(sec^2 y) = 1/(sec^2 arctan x) = 1/(1 + x^2). $
How do we show that $sec^2(arctan x) = 1 + x^2$ ? Again, there are two methods:
=== Algebraically showing $sec^2(arctan x) = 1 + x^2$.
Note that
$ sec^2 theta = tan^2 theta + 1. $
In our case, $theta = arctan x$. So, $ sec^2 arctan x = x^2 + 1. $
=== Geometrically showing $sec^2(arctan x) = 1 + x^2$.
Consider a right-angled triangle with angle $theta$ such that the perpendicular
side has length $x$ and adjacent side has length $1$. Then $theta = arctan x$.
Pictorally,
#align(center)[#image("graphics/sec^2 arctan.png", width: 30%)]
So, the hypotenuse has length $sqrt(x^2 + 1)$. Then,
$ sec^2 theta = 1/(cos^2 theta) = (sqrt(1 + x^2))^2 = 1 + x^2 \ sec^2 arctan x = 1 + x^2. $
|
|
https://github.com/HollowNumber/DDU-Rapport-Template | https://raw.githubusercontent.com/HollowNumber/DDU-Rapport-Template/main/src/chapters/appendix.typ | typst | #import "@preview/codelst:1.0.0": sourcecode, sourcefile
#set heading(numbering: "A.1", supplement: "Bilag")
#set page(columns: 1)
#counter(heading).update(0)
|
|
https://github.com/fyuniv/typstModernCV | https://raw.githubusercontent.com/fyuniv/typstModernCV/main/README.md | markdown | MIT License | # A Modern CV Template with Typst
This is a Typst resume template that imitates the popular [LaTeX Modern CV template](https://ctan.org/pkg/moderncv).
It was inspired by the Typst template <https://github.com/DeveloperPaul123/modern-cv> created by [DeveloperPaul123](https://github.com/DeveloperPaul123).
## Features
- The default font is Noto Sans. You may set up font in the `theme` dictionary as seen in the `example.typ` file.
- Currently, there are three themes: defult, blue, and orange.
- Enumerate list numbering can be reversed using the function `#reverse[]`. The definition of this function was taken from [frozolotl](https://github.com/frozolotl). I would like to thank [frozolotl](https://github.com/frozolotl) for the help.
## Usage
Below is a basic usage of the template.
```typst
#import "lib.typ": *
// #set text(font: "Merriweather")
#show: resume.with(
title: "Curriculum Vitae",
author: (
firstname: "John",
lastname: "Doe",
email: "<EMAIL>",
address: [Dept. of Math\ home number, street name,\ city, zipcode],
positions: (
"Mathematician",
),
phone: "(000) 123 4567",
github: "abcd",
orcid: "0000-0000-0000-0000",
web: "https://..."
),
date: datetime.today().display(),
theme: (
color: "orange",
font: "Inter"
)
)
#show link: set text(fill: blue)
= Education
#resume_entry(
date: "August 2019 - May 2024",
title: "Ph.D. in Mathematics",
university: "University of ABC",
location: "City A, USA",
description: "Advisor: Prof. "
)
= Research Interests
#resume_content[
All fields of Mathematics
]
= Papers
#resume_list[
+ #lorem(15)
+ #lorem(20)
]
= Talks
#resume_list[
#reverse[
+ #lorem(15)
+ #lorem(20)
]
]
```
## Sample Output
<img src="sample.png" width="500" />
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-14.typ | typst | Other | // Error: 3-12 cannot divide these two lengths
#(1em / 5pt)
|
https://github.com/lvignoli/diapo | https://raw.githubusercontent.com/lvignoli/diapo/main/README.md | markdown | MIT License | # diapo
A simplistic [Typst](https://typst.app) template for presentations.
Copy the [template](template.typ) to your project folder and start your document with a global show rule using `diapo.with()`.
For a new slide with a title, use the first level heading syntax `= Title`. \
For a new slide without a title, use a `pagebreak()`. \
To get a transition slide with additional impact, call `#transition[BANG]`.
It is intentionally basic and _not_ dynamic.
Customize it to your liking if needed.
## Minimal document
[This example](example.pdf) is given by the following code:
```typst
#import "template.typ": diapo, transition
#show: diapo.with(
title: "My last vacations",
author: "<NAME>",
date: "2023-04-20",
// display_lastpage: false,
)
= Introduction
It was great!
#lorem(20)
#transition[Day one]
= Travelling
#lorem(30)
#lorem(30)
= Relax
#align(horizon)[
#set text(size: 28pt)
$ e^(i pi) + 1 = 0 $
]
= The journey back home
It was exhausting.
= Conclusion
That was short.
```
See also [a longer example](long_example.typ).
|
https://github.com/fredguth/mwe-citation-quarto-typst | https://raw.githubusercontent.com/fredguth/mwe-citation-quarto-typst/main/_extensions/mwe/typst-template.typ | typst | #import "@preview/drafting:0.2.0": *
#let margincite(key, mode, prefix, suffix, noteNum, hash) = context {
if query(bibliography).len()>0 {
let supplement = suffix.split(",").filter(value => not value.contains("dy.")).join(",")
let dy = if suffix.contains("dy.") {
eval(suffix.split("dy.").at(1, default: "").split(",").at(0, default: "").trim())
} else {none}
cite(key, form: "normal", supplement: supplement)
if dy!=none {
set text(size: 8pt)
[#margin-note(dy:dy, dx:100%+.1em)[#block(width: 7cm, inset:1em)[#cite(key, form:"full", supplement: supplement)]]]
}
}
}
#let article(
title: none,
authors: none,
date: none,
abstract: none,
abstract-title: none,
cols: 1,
paper: "a4",
margin: (left: 1cm, right: 7cm, top: 2cm, bottom: 2cm),
lang: "en",
region: "US",
font: (),
fontsize: 11pt,
sectionnumbering: none,
toc: false,
toc_title: none,
toc_depth: none,
toc_indent: 1.5em,
bib: none,
doc,
) = {
set page(
paper: paper,
margin: margin,
numbering: "1",
)
set par(justify: true)
set text(lang: lang,
region: region,
font: font,
size: fontsize)
set heading(numbering: sectionnumbering)
if title != none {
align(center)[#block(inset: 2em)[
#text(weight: "bold", size: 1.5em)[#title]
]]
}
if authors != none {
let count = authors.len()
let ncols = calc.min(count, 3)
grid(
columns: (1fr,) * ncols,
row-gutter: 1.5em,
..authors.map(author =>
align(center)[
#author.name \
#author.affiliation \
#author.email
]
)
)
}
if date != none {
align(center)[#block(inset: 1em)[
#date
]]
}
if abstract != none {
block(inset: 2em)[
#text(weight: "semibold")[#abstract-title] #h(1em) #abstract
]
}
if toc {
let title = if toc_title == none {
auto
} else {
toc_title
}
block(above: 0em, below: 2em)[
#outline(
title: toc_title,
depth: toc_depth,
indent: toc_indent
);
]
}
show cite.where(form:"prose"): none
// set-page-properties() // I don't want it to calculate, I want to give my calculations
set-margin-note-defaults(
stroke: none,
side: right,
margin-right: 1cm, // 1cm is absurd.. just to show that it is being ignored!!!
margin-left: 1cm,
page-width: 21cm-8.25cm
)
// set-page-properties()
place(dx: 100%, dy: 3cm, block(width: 7cm, height: 7cm, fill: rgb("#dbdbc5"))[
#let n = 1
#set text(fill: gray)
#while n < 17 {
[Please do not put your citations here.]
n = n+1
}
]
)
if cols == 1 {
doc
} else {
columns(cols, doc)
}
if bib != none {
heading(level:1,[References])
bib
}
}
#set table(
inset: 6pt,
stroke: none
)
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/192.%20think.html.typ | typst | think.html
How to Think for Yourself
November 2020There are some kinds of work that you can't do well without thinking
differently from your peers. To be a successful scientist, for
example, it's not enough just to be correct. Your ideas have to be
both correct and novel. You can't publish papers saying things other
people already know. You need to say things no one else has realized
yet.The same is true for investors. It's not enough for a public market
investor to predict correctly how a company will do. If a lot of
other people make the same prediction, the stock price will already
reflect it, and there's no room to make money. The only valuable
insights are the ones most other investors don't share.You see this pattern with startup founders too. You don't want to
start a startup to do something that everyone agrees is a good idea,
or there will already be other companies doing it. You have to do
something that sounds to most other people like a bad idea, but
that you know isn't � like writing software for a tiny computer
used by a few thousand hobbyists, or starting a site to let people
rent airbeds on strangers' floors.Ditto for essayists. An essay that told people things they already
knew would be boring. You have to tell them something new.But this pattern isn't universal. In fact, it doesn't hold for most
kinds of work. In most kinds of work � to be an administrator, for
example � all you need is the first half. All you need is to be
right. It's not essential that everyone else be wrong.There's room for a little novelty in most kinds of work, but in
practice there's a fairly sharp distinction between the kinds of
work where it's essential to be independent-minded, and the kinds
where it's not.I wish someone had told me about this distinction when I was a kid,
because it's one of the most important things to think about when
you're deciding what kind of work you want to do. Do you want to
do the kind of work where you can only win by thinking differently
from everyone else? I suspect most people's unconscious mind will
answer that question before their conscious mind has a chance to.
I know mine does.Independent-mindedness seems to be more a matter of nature than
nurture. Which means if you pick the wrong type of work, you're
going to be unhappy. If you're naturally independent-minded, you're
going to find it frustrating to be a middle manager. And if you're
naturally conventional-minded, you're going to be sailing into a
headwind if you try to do original research.One difficulty here, though, is that people are often mistaken about
where they fall on the spectrum from conventional- to independent-minded.
Conventional-minded people don't like to think of themselves as
conventional-minded. And in any case, it genuinely feels to them
as if they make up their own minds about everything. It's just a
coincidence that their beliefs are identical to their peers'. And
the independent-minded, meanwhile, are often unaware how different
their ideas are from conventional ones, at least till they state
them publicly.
[1]By the time they reach adulthood, most people know roughly how smart
they are (in the narrow sense of ability to solve pre-set problems),
because they're constantly being tested and ranked according to it.
But schools generally ignore independent-mindedness, except to the
extent they try to suppress it. So we don't get anything like the
same kind of feedback about how independent-minded we are.There may even be a phenomenon like Dunning-Kruger at work, where
the most conventional-minded people are confident that they're
independent-minded, while the genuinely independent-minded worry
they might not be independent-minded enough.
___________
Can you make yourself more independent-minded? I think so. This
quality may be largely inborn, but there seem to be ways to magnify
it, or at least not to suppress it.One of the most effective techniques is one practiced unintentionally
by most nerds: simply to be less aware what conventional beliefs
are. It's hard to be a conformist if you don't know what you're
supposed to conform to. Though again, it may be that such people
already are independent-minded. A conventional-minded person would
probably feel anxious not knowing what other people thought, and
make more effort to find out.It matters a lot who you surround yourself with. If you're surrounded
by conventional-minded people, it will constrain which ideas you
can express, and that in turn will constrain which ideas you have.
But if you surround yourself with independent-minded people, you'll
have the opposite experience: hearing other people say surprising
things will encourage you to, and to think of more.Because the independent-minded find it uncomfortable to be surrounded
by conventional-minded people, they tend to self-segregate once
they have a chance to. The problem with high school is that they
haven't yet had a chance to. Plus high school tends to be an
inward-looking little world whose inhabitants lack confidence, both
of which magnify the forces of conformism. So high school is
often a bad time for the
independent-minded. But there is some advantage even here: it
teaches you what to avoid. If you later find yourself in a situation
that makes you think "this is like high school," you know you should
get out.
[2]Another place where the independent- and conventional-minded are
thrown together is in successful startups. The founders and early
employees are almost always independent-minded; otherwise the startup
wouldn't be successful. But conventional-minded people greatly
outnumber independent-minded ones, so as the company grows, the
original spirit of independent-mindedness is inevitably diluted.
This causes all kinds of problems besides the obvious one that the
company starts to suck. One of the strangest is that the founders
find themselves able to speak more freely with founders of other
companies than with their own employees.
[3]Fortunately you don't have to spend all your time with independent-minded
people. It's enough to have one or two you can talk to regularly.
And once you find them, they're usually as eager to talk as you
are; they need you too. Although universities no longer have the
kind of monopoly they used to have on education, good universities
are still an excellent way to meet independent-minded people. Most
students will still be conventional-minded, but you'll at least
find clumps of independent-minded ones, rather than the near zero
you may have found in high school.It also works to go in the other direction: as well as cultivating
a small collection of independent-minded friends, to try to meet
as many different types of people as you can. It will decrease the
influence of your immediate peers if you have several other groups
of peers. Plus if you're part of several different worlds, you can
often import ideas from one to another.But by different types of people, I don't mean demographically
different. For this technique to work, they have to think differently.
So while it's an excellent idea to go and visit other countries,
you can probably find people who think differently right around the
corner. When I meet someone who knows a lot about something unusual
(which includes practically everyone, if you dig deep enough), I
try to learn what they know that other people don't. There are
almost always surprises here. It's a good way to make conversation
when you meet strangers, but I don't do it to make conversation.
I really want to know.You can expand the source of influences in time as well as space,
by reading history. When I read history I do it not just to learn
what happened, but to try to get inside the heads of people who
lived in the past. How did things look to them? This is hard to do,
but worth the effort for the same reason it's worth travelling far
to triangulate a point.You can also take more explicit measures to prevent yourself from
automatically adopting conventional opinions. The most general is
to cultivate an attitude of skepticism. When you hear someone say
something, stop and ask yourself "Is that true?" Don't say it out
loud. I'm not suggesting that you impose on everyone who talks to
you the burden of proving what they say, but rather that you take
upon yourself the burden of evaluating what they say.Treat it as a puzzle. You know that some accepted ideas will later
turn out to be wrong. See if you can guess which. The end goal is
not to find flaws in the things you're told, but to find the new
ideas that had been concealed by the broken ones. So this game
should be an exciting quest for novelty, not a boring protocol for
intellectual hygiene. And you'll be surprised, when you start asking
"Is this true?", how often the answer is not an immediate yes. If
you have any imagination, you're more likely to have too many leads
to follow than too few.More generally your goal should be not to let anything into your
head unexamined, and things don't always enter your head in the
form of statements. Some of the most powerful influences are implicit.
How do you even notice these? By standing back and watching how
other people get their ideas.When you stand back at a sufficient distance, you can see ideas
spreading through groups of people like waves. The most obvious are
in fashion: you notice a few people wearing a certain kind of shirt,
and then more and more, until half the people around you are wearing
the same shirt. You may not care much what you wear, but there are
intellectual fashions too, and you definitely don't want to participate
in those. Not just because you want sovereignty over your own
thoughts, but because unfashionable
ideas are disproportionately likely to lead somewhere interesting.
The best place to find undiscovered ideas is where no one else is
looking.
[4]
___________
To go beyond this general advice, we need to look at the internal
structure of independent-mindedness � at the individual muscles
we need to exercise, as it were. It seems to me that it has three
components: fastidiousness about truth, resistance to being told
what to think, and curiosity.Fastidiousness about truth means more than just not believing things
that are false. It means being careful about degree of belief. For
most people, degree of belief rushes unexamined toward the extremes:
the unlikely becomes impossible, and the probable becomes certain.
[5]
To the independent-minded, this seems unpardonably sloppy.
They're willing to have anything in their heads, from highly
speculative hypotheses to (apparent) tautologies, but on subjects
they care about, everything has to be labelled with a carefully
considered degree of belief.
[6]The independent-minded thus have a horror of ideologies, which
require one to accept a whole collection of beliefs at once, and
to treat them as articles of faith. To an independent-minded person
that would seem revolting, just as it would seem to someone fastidious
about food to take a bite of a submarine sandwich filled with a
large variety of ingredients of indeterminate age and provenance.Without this fastidiousness about truth, you can't be truly
independent-minded. It's not enough just to have resistance to being
told what to think. Those kind of people reject conventional ideas
only to replace them with the most random conspiracy theories. And
since these conspiracy theories have often been manufactured to
capture them, they end up being less independent-minded than ordinary
people, because they're subject to a much more exacting master than
mere convention.
[7]Can you increase your fastidiousness about truth? I would think so.
In my experience, merely thinking about something you're fastidious
about causes that fastidiousness to grow. If so, this is one of
those rare virtues we can have more of merely by wanting it. And
if it's like other forms of fastidiousness, it should also be
possible to encourage in children. I certainly got a strong dose
of it from my father.
[8]The second component of independent-mindedness, resistance to being
told what to think, is the most visible of the three. But even this
is often misunderstood. The big mistake people make about it is to
think of it as a merely negative quality. The language we use
reinforces that idea. You're unconventional. You don't care
what other people think. But it's not just a kind of immunity. In
the most independent-minded people, the desire not to be told what
to think is a positive force. It's not mere skepticism, but an
active delight in ideas that subvert
the conventional wisdom, the more counterintuitive the better.Some of the most novel ideas seemed at the time almost like practical
jokes. Think how often your reaction to a novel idea is to laugh.
I don't think it's because novel ideas are funny per se, but because
novelty and humor share a certain kind of surprisingness. But while
not identical, the two are close enough that there is a definite
correlation between having a sense of humor and being independent-minded
� just as there is between being humorless and being conventional-minded.
[9]I don't think we can significantly increase our resistance to being
told what to think. It seems the most innate of the three components
of independent-mindedness; people who have this quality as adults
usually showed all too visible signs of it as children. But if we
can't increase our resistance to being told what to think, we can
at least shore it up, by surrounding ourselves with other
independent-minded people.The third component of independent-mindedness, curiosity, may be
the most interesting. To the extent that we can give a brief answer
to the question of where novel ideas come from, it's curiosity. That's
what people are usually feeling before having them.In my experience, independent-mindedness and curiosity predict one
another perfectly. Everyone I know who's independent-minded is
deeply curious, and everyone I know who's conventional-minded isn't.
Except, curiously, children. All small children are curious. Perhaps
the reason is that even the conventional-minded have to be curious
in the beginning, in order to learn what the conventions are. Whereas
the independent-minded are the gluttons of curiosity, who keep
eating even after they're full.
[10]The three components of independent-mindedness work in concert:
fastidiousness about truth and resistance to being told what to
think leave space in your brain, and curiosity finds new ideas to
fill it.Interestingly, the three components can substitute for one another
in much the same way muscles can. If you're sufficiently fastidious
about truth, you don't need to be as resistant to being told what
to think, because fastidiousness alone will create sufficient gaps
in your knowledge. And either one can compensate for curiosity,
because if you create enough space in your brain, your discomfort
at the resulting vacuum will add force to your curiosity. Or curiosity
can compensate for them: if you're sufficiently curious, you don't
need to clear space in your brain, because the new ideas you discover
will push out the conventional ones you acquired by default.Because the components of independent-mindedness are so interchangeable,
you can have them to varying degrees and still get the same result.
So there is not just a single model of independent-mindedness. Some
independent-minded people are openly subversive, and others are
quietly curious. They all know the secret handshake though.Is there a way to cultivate curiosity? To start with, you want to
avoid situations that suppress it. How much does the work you're
currently doing engage your curiosity? If the answer is "not much,"
maybe you should change something.The most important active step you can take to cultivate your
curiosity is probably to seek out the topics that engage it. Few
adults are equally curious about everything, and it doesn't seem
as if you can choose which topics interest you. So it's up to you
to find them. Or invent them, if
necessary.Another way to increase your curiosity is to indulge it, by
investigating things you're interested in. Curiosity is unlike
most other appetites in this respect: indulging it tends to increase
rather than to sate it. Questions lead to more questions.Curiosity seems to be more individual than fastidiousness about
truth or resistance to being told what to think. To the degree
people have the latter two, they're usually pretty general, whereas
different people can be curious about very different things. So
perhaps curiosity is the compass here. Perhaps, if your goal is to
discover novel ideas, your motto should not be "do what you love"
so much as "do what you're curious about."Notes[1]
One convenient consequence of the fact that no one identifies
as conventional-minded is that you can say what you like about
conventional-minded people without getting in too much trouble.
When I wrote "The Four Quadrants of
Conformism" I expected a firestorm of rage from the
aggressively conventional-minded, but in fact it was quite muted.
They sensed that there was something about the essay that they
disliked intensely, but they had a hard time finding a specific
passage to pin it on.[2]
When I ask myself what in my life is like high school, the
answer is Twitter. It's not just full of conventional-minded people,
as anything its size will inevitably be, but subject to violent
storms of conventional-mindedness that remind me of descriptions
of Jupiter. But while it probably is a net loss to spend time there,
it has at least made me think more about the distinction between
independent- and conventional-mindedness, which I probably wouldn't
have done otherwise.[3]
The decrease in independent-mindedness in growing startups is
still an open problem, but there may be solutions.Founders can delay the problem by making a conscious effort only
to hire independent-minded people. Which of course also has the
ancillary benefit that they have better ideas.Another possible solution is to create policies that somehow disrupt
the force of conformism, much as control rods slow chain reactions,
so that the conventional-minded aren't as dangerous. The physical
separation of Lockheed's Skunk Works may have had this as a side
benefit. Recent examples suggest employee forums like Slack may not
be an unmitigated good.The most radical solution would be to grow revenues without growing
the company. You think hiring that junior PR person will be cheap,
compared to a programmer, but what will be the effect on the average
level of independent-mindedness in your company? (The growth in
staff relative to faculty seems to have had a similar effect on
universities.) Perhaps the rule about outsourcing work that's not
your "core competency" should be augmented by one about outsourcing
work done by people who'd ruin your culture as employees.Some investment firms already seem to be able to grow revenues
without growing the number of employees. Automation plus the ever
increasing articulation of the "tech stack" suggest this may one
day be possible for product companies.[4]
There are intellectual fashions in every field, but their
influence varies. One of the reasons politics, for example, tends
to be boring is that it's so extremely subject to them. The threshold
for having opinions about politics is much lower than the one for having
opinions about set theory. So while there are some ideas in politics,
in practice they tend to be swamped by waves of intellectual fashion.[5]
The conventional-minded are often fooled by the strength of
their opinions into believing that they're independent-minded. But
strong convictions are not a sign of independent-mindedness. Rather
the opposite.[6]
Fastidiousness about truth doesn't imply that an independent-minded
person won't be dishonest, but that he won't be deluded. It's sort
of like the definition of a gentleman as someone who is never
unintentionally rude.[7]
You see this especially among political extremists. They think
themselves nonconformists, but actually they're niche conformists.
Their opinions may be different from the average person's, but they
are often more influenced by their peers' opinions than the average
person's are.[8]
If we broaden the concept of fastidiousness about truth so that
it excludes pandering, bogusness, and pomposity as well as falsehood
in the strict sense, our model of independent-mindedness can expand
further into the arts.[9]
This correlation is far from perfect, though. G�del and Dirac
don't seem to have been very strong in the humor department. But
someone who is both "neurotypical" and humorless is very likely to
be conventional-minded.[10]
Exception: gossip. Almost everyone is curious about gossip.
Thanks to <NAME>, <NAME>, <NAME>, Jessica
Livingston, <NAME>, <NAME>, and <NAME> for reading
drafts of this.Italian Translation
|
|
https://github.com/piepert/typst-hro-iph-seminar-paper | https://raw.githubusercontent.com/piepert/typst-hro-iph-seminar-paper/main/custombib-hro-iph-style.typ | typst | // TODO: add english as a language for this style (Hrsg./ders.)
#let ifnotnone(elem, fn-true, fn-false: k => none) = if elem != none {
fn-true(elem)
} else {
fn-false(elem)
}
#let ifhaskey(elem, key, fn-true, ..k) = if elem.at(key, default: none) != none {
fn-true(elem)
} else if k.pos().len() > 0 {
k.pos().first()(elem)
}
#let dotted(s) = {
let s = s.trim()
return s.ends-with(".") or s.ends-with("!") or s.ends-with("?")
}
#let evc(e) = eval("["+e+"]")
#let dot(e) = if not dotted(e) { evc(e)+[.] } else { e }
#let make-title(element) = emph({
evc(element.title)
if "subtitle" in element and element.subtitle != none {
if not dotted(element.title) {
[. ]
}
dot(element.subtitle)
} else if not dotted(element.title) {
[.]
}
})
#let make-booktitle(element) = {
let element = element
element.title = element.booktitle
element.subtitle = if "booksubtitle" in element {
element.booksubtitle
} else {
none
}
make-title(element)
}
#let hro-iph-bibstyle-types = (
// == Monographie ==
// Verfassername, Vorname: Titel. Untertitel. Auflage [falls nicht 1. Aufl.]. Ort Jahr.
// Rosenberg, <NAME>.: Philosophieren. Ein Handbuch für Anfänger. 6. Auflage. Frankfurt am Main 1986.
// KEYS: authos, title, year, location, (pages, edition, volume, volume-title, series, series-volume)
monography: (entry, element) => [#element.authors:
#make-title(element)
#ifhaskey(element, "volume", e => [Band #e.volume#ifhaskey(element, "volume-title", e => [: ]+emph(evc(e.volume-title))).])
#ifhaskey(element, "series", e => [#ifhaskey(e, "series-volume", e => [Band ]+e.series-volume, e => [Teil ]) der Serie ]+emph(e.series)+[.])
#ifhaskey(element, "edition", e => if int(e.edition) > 1 {
e.edition+[. Auflage.]
})
#element.location #element.year.
#ifhaskey(element, "pages", e => [S. #dot(e.pages)])
],
// == Onlinequelle ==
// Verfassername, Vorname: Titel. URL (Abfragedatum).
// <NAME>: Law and Ideology. http://plato.stanford.edu/entries/law-ideology/ (11.10.2014).
// KEYS: authors, title, url, year
url: (entry, element) => [#element.authors:
#make-title(element)
#raw(element.url)
(letzter Zugriff #element.year).],
// == Zeitschriftenaufsätze ==
// Verfassername, Vorname: Titel. Untertitel. In: Zeitschriftentitel Jahrgangsnummer (Jahr). S. x-z.
// <NAME>: Gerechte Verteilung – spielend leicht? In: ZDPE. Heft „Globale Gerechtigkeit“. Jg. 33 (3/2011). S. 200-203.
// KEYS: authors, title, journal, (publisher, volume, issue, pages, url, year)
article: (entry, element) => [
#element.authors:
#make-title(element)
In: #emph(evc(element.journal)).
#ifhaskey(element, "publisher", e => [Hrsg. von #element.publisher.join(", ", last: " und ").])
#ifhaskey(element, "volume", element => [Jg. #element.volume (#ifhaskey(element, "issue", e => e.issue+[/])#element.year).])
#ifhaskey(element, "pages", e => [S. #dot(e.pages)])
#ifhaskey(element, "url", e => [URL: ]+link(e.url)+[ (letzter Zugriff #e.year)])
],
// == Sammelbände/Herausgeberschriften ==
// Autor X, Autor Y (Hgg.): Titel. Untertitel. Auflage. Ort Jahr.
// Schönecker, <NAME> Wood, <NAME>. (Hgg.): Kants „Grundlegung zur Metaphysik der Sitten“. Ein einführender Kommentar. Paderborn, München, Wien, Zürich 2002.
// KEYS: authors, title, year, location, (volume, volume-title, edition)
collection: (entry, element) => [
#element.authors (#if entry.author.len() > 1 {[Hgg.]} else {[Hg.]}):
#make-title(element)
#ifhaskey(element, "volume", e => [Band #e.volume#ifhaskey(element, "volume-title", e => [: ]+emph(evc(e.volume-title))).])
#ifhaskey(element, "edition", e => if int(e.edition) > 1 {
e.edition+[. Auflage.]
})
#element.location
#element.year.
#ifhaskey(element, "pages", e => [S. #dot(e.pages)])
],
// == Aufsätze in Sammelbänden ==
// Verfassername, Vorname: Titel. Untertitel. In: Titel. Untertitel. Hrsg. von Vorname Nachname. Auflage [falls nicht 1. Aufl.]. Ort Jahr. S. x-z
// <NAME>: Persönliche Verantwortung und Urteilsbildung. In: Ich denke, also bin ich. Grundtexte der Philosophie. Hrsg. von <NAME>. München 2006. S. 239-244.
// KEYS: authors, title, publisher, location, year, (pages, volume, volume-title)
collection-article: (entry, element) => [
#element.authors:
#make-title(element)
In: #make-booktitle(element)
#ifhaskey(element, "volume", e => [Band #e.volume#ifhaskey(element, "volume-title", e => [: ]+emph(evc(e.volume-title))).])
Hrsg. von #element.publisher.join(", ", last: " und ").
#ifhaskey(element, "edition", e => if int(e.edition) > 1 {
e.edition+[. Auflage.]
})
#element.location
#element.year.
#ifhaskey(element, "pages", e => [S. #dot(e.pages)])
],
// == Lexikonartikel ==
// Verfassername, Vorname: <NAME>. In: Lexikon-Name, evtl. Band. Hrsg. von Vorname Nachname. Ort Jahr. S. x-z.
// <NAME>: Erkennen, Erkenntnis. In: Historisches Wörterbuch der Philosophie. Band 2. Hrsg. von <NAME> und <NAME>. Basel, Stuttgart 1972. S. 662-681.
// KEYS: authors, title, booktitle, publisher, location, year, (pages, volume, volume-title)
lexicon: (entry, element) => [
#element.authors:
#make-title(element)
In: #make-booktitle(element)
#ifhaskey(element, "volume", e => [Band #e.volume#ifhaskey(element, "volume-title", e => [: ]+emph(evc(e.volume-title))).])
Hrsg. von #element.publisher.join(", ", last: " und ").
#ifhaskey(element, "edition", e => if int(e.edition) > 1 {
e.edition+[. Auflage.]
})
#element.location
#element.year.
#ifhaskey(element, "pages", e => [S. #dot(e.pages)])
],
// == Werkausgabe ==
// Verfassername, Vorname: Titel. In: ders.: Titel der Ausgabe. Hrsg. von Vorname Nachname. Bandnummer: Bandtitel. Ort Jahr. S. x-z.
// <NAME>: Oase des Glücks. In: ders.: <NAME>usgabe. Hrsg. von <NAME>, <NAME>, <NAME>. Bd. 7: Spiel als Weltsymbol. München 2010. S. 11-29.
// KEYS: authors, title, booktitle, publisher, location, year, (pages, volume, edition)
edition: (entry, element) => [
#element.authors:
#make-title(element)
In: ders.: #make-booktitle(element)
Hrsg. von #element.publisher.join(", ", last: " und ").
#ifhaskey(element, "volume", e => [Band #e.volume#ifhaskey(element, "volume-title", e => [: ]+emph(evc(e.volume-title))).])
#ifhaskey(element, "edition", e => if int(e.edition) > 1 {
e.edition+[. Auflage.]
})
#element.location
#element.year.
#ifhaskey(element, "pages", e => [S. #dot(e.pages)])
],
fallback: (entry, element) => [#element.authors: #emph["#element.title"]. #element.year.]
)
#let clear-pages(style, key) = {
let style = style
style.at(key) = (entry, element) => {
element.pages = none
hro-iph-bibstyle-types.at(key)(entry, element)
}
style
}
// changes specific for bibliography
#let hro-iph-bibstyle-types-bibliography = {
let bst = hro-iph-bibstyle-types
// remove pages from ...
bst = clear-pages(bst, "monography")
bst = clear-pages(bst, "collection")
bst
}
#let hro-iph-bibstyle = (
options: (
is-numerical: false,
show-sections: true,
show-bibliography: true,
title: "Bibliographie",
separator: ", "
),
// how each field is formatted (from entry (source-string) to citation (content))
fields: (
// performed on each author name
author: (entry, author) =>
smallcaps(author.last
+ ifhaskey(author, "first", e => [, #e.first])
+ ifhaskey(author, "middle", e => [ ] + e.middle
.split(" ")
.map(e => e.split("-")
.map(e => e.at(0)+[.])
.join("-"))
.join(" "))),
// performed on the list of authors
authors: (entry, authors) =>
(if authors.len() >= 3 {
authors.at(0) + [, ] + authors.at(1) + [ et al.]
} else {
authors.join(" und ")
}),
publisher: (entry, publisher) => (publisher,).flatten(),
// performed on each prefix and postfix
postfix: (entry, postfix) => [#ifnotnone(postfix, e => [, #postfix])],
prefix: (entry, prefix) => [#ifnotnone(prefix, e => [#e ])],
// title: (entry, field) => eval("["+field+"]"),
// fallback
fallback: (entry, field) => field
),
// for entry-type "custom"
custom: (
sort-by: "marker",
inline: (entry) => [#ifhaskey(entry, "prefix", e => (e.prefix+" "))#eval("["+entry.show-inline+"]")],//#ifhaskey(entry, "postfix", e => (" "+e.postfix))],
bibliography: (entry) => [#eval("["+entry.show-bibliography+"]").]
),
inline: (
// fields: (
// performed on each author name
// author: (entry, author) =>
// smallcaps(if author.first != none { [#author.first.at(0)] + [. ] }
// + ifhaskey(author, "middle", e => [ #e.middle ])
// + [ ]
// + author.last)
// ),
// added after citation
citation-begin: (entry, citation) => citation,
// added before citation
citation-end: (entry, citation) => citation,
// format single citation inside
format: (entry, citation) => [#ifhaskey(entry, "prefix", e => e.prefix+[ ]) #citation #ifhaskey(entry, "postfix", e => e.postfix+[ ])],
// on multiple citations, wrap all of them into this
wrap-multi: (citations) => [#citations],
// on all citations cited together tcb-cites / tcb-cite, wrap all of them into this
wrap-any: (citations) => [#citations],
mutator: (entry) => {
if entry.postfix != none and entry.postfix.trim().starts-with("S.") {
entry.pages = none
}
return entry
},
types: hro-iph-bibstyle-types
),
bibliography: (
format: (entry, citation) => {
set par(leading: 0.65em)
citation
},
types: hro-iph-bibstyle-types-bibliography
),
sections: (
primary: "Primärliteratur",
secondary: "Sekundärliteratur",
other: "Sonstige"
)
) |
|
https://github.com/WindowDump/typst-ttrpg | https://raw.githubusercontent.com/WindowDump/typst-ttrpg/main/fist-handbook.typ | typst | The Unlicense | // FIST - https://claymorerpgs.itch.io/fist
// character sheet & quick reference by window dump
// https://github.com/WindowDump/typst-ttrpg
// print, fold in half, give to player, start mission
// fonts used
// Orbitron
// https://www.theleagueofmoveabletype.com/orbitron
// Michroma (you can use Microgramma if you have it)
// https://github.com/googlefonts/Michroma-font
// Space Grotesk
// https://floriankarsten.github.io/space-grotesk/
// note: Typst does not support variable fonts
// possible alternates:
// Fivo Sans
// https://drive.google.com/file/d/0B47FBrwbA6rBNjlrbWtqTzVpWFU/view?resourcekey=<KEY>
#set document(
title: "FIST Operative Handbook",
author: "<NAME>",
keywords: ("fist", "world of dungeons", "wodu", "pbta", "osr"),
)
#set page(
paper: "us-letter",
flipped: true,
margin: (x: 36pt, top: 36pt, bottom: 36pt),
footer-descent: 30%,
footer: [
#set text(
font: "Space Grotesk",
weight: 400,
features: ("ss01": 1, "ss02": 0, "ss03": 0, "ss04": 1),
size: 8pt,
tracking: -0.01em,
)
Text adapted from FIST Ultra Edition by CLAYMORE Roleplaying Games,\ licensed under CC-BY-SA 4.0. #link("https://creativecommons.org/licenses/by-sa/4.0/")[creativecommons.org/licenses/by-sa/4.0/]
],
)
#let sheet-label(
it,
) = text(
font: "Space Grotesk",
features: ("ss04",), // alternate "D"
size: 8pt,
tracking: 0.04em,
weight: 500,
ligatures: false,
upper(it)
)
#let statbox(
name,
desc,
box-fill: luma(100%),
box-stroke: none,
name-fill: luma(100%),
text-fill: luma(100%),
text-weight: 700,
) = grid(
rows: (1fr, auto),
row-gutter: 4pt,
columns: (1fr, auto),
column-gutter: 4pt,
grid.cell(
align: horizon + right,
rowspan: 2,
)[
#block(
spacing: (0pt),
below: 4pt,
text(
font: "Orbitron",
weight: "black",
tracking: 0.05em,
size: 18pt,
features: ("kern": 1, "ss01": 0, "ss02": 0, "ss03": 0, "ss04": 0),
spacing: 4pt,
fill: name-fill,
)[#name],
)
#block(
spacing: 0pt,
text(
font: "Space Grotesk",
tracking: -0.02em,
features: ("ss01": 1, "ss02": 0, "ss03": 0, "ss04": 0),
weight: text-weight,
size: 8pt,
fill: text-fill,
)[#desc],
)
],
grid.cell(
rowspan: 2,
align: (center + horizon),
rect(
fill: box-fill,
stroke: box-stroke,
width: 34pt,
height: 34pt,
radius: 4pt,
),
),
)
#let statbox_light(
name,
desc,
box-fill: luma(100%),
box-stroke: none,
name-fill: luma(0%),
text-fill: luma(0%),
text-weight: 500,
) = statbox(
name,
desc,
box-fill: box-fill,
box-stroke: box-stroke,
name-fill: name-fill,
text-fill: text-fill,
text-weight: text-weight,
)
#let character_sheet = grid( // character sheet
columns: (1fr,)*6,
rows: (
auto, // header
48pt, // identity
48pt, // traits
48pt,
48pt,
48pt, // inventory
48pt,
42pt, // stats box
38pt,
42pt, // secondary stats
38pt,
auto, // notes
),
row-gutter: (
0pt,
0pt,
0pt,
0pt,
0pt,
0pt,
0pt,
0pt,
4pt, // gap between stats boxes
0pt,
0pt,
0pt,
),
grid.cell( // header
colspan: 6,
align: bottom,
grid(
rows: (auto, 4pt),
columns: (auto, auto),
align: bottom,
grid.cell(
rowspan: 2,
rect(
fill: luma(0%),
outset: (left: 2pt),
inset: (y: 4pt, left: 4pt, right: 6pt),
text(
font: "Orbitron",
weight: "black",
fill: luma(100%),
size: 40pt
)[FIST]
),
),
grid.cell(
inset: (bottom: 4pt, left: 5pt, right: 2pt,),
align: bottom + left,
par(
leading: 3.5pt,
text(
font: "Michroma",
weight: "regular",
size: 14pt,
)[#upper[Operative Handbook]],
)
),
grid.cell(
rect(
fill: luma(0%),
width: 100%,
height: 4pt,
outset: (left: 4pt, right: 2pt),
)
),
),
),
grid.cell( // identity
colspan: 6,
rowspan: 1,
inset: (left: 2pt, bottom: 4pt, top: 50% - 8pt,),
align: bottom,
grid(
columns: (3fr, 2fr),
row-gutter: 1fr,
sheet-label[Codename:],
sheet-label[Pronouns:],
sheet-label[Role:],
)
),
grid.hline(
y: 2,
stroke: (thickness: 0.5pt,),
),
grid.cell(
colspan: 6,
rowspan: 3,
align: left + top,
inset: (top: 4pt, left: 2pt),
sheet-label[Traits]
),
grid.hline(
y: 5,
stroke: (thickness: 0.5pt,),
),
grid.cell(
colspan: 6,
rowspan: 2,
align: left + top,
inset: (top: 4pt, left: 2pt),
sheet-label[Inventory]
),
grid.cell(
colspan: 6,
rowspan: 2,
rect(
fill: luma(0%),
width: 100%,
height: 100%,
radius: 6pt,
inset: 4pt,
grid(
rows: (1fr, 1fr),
columns: (1fr, 1fr),
row-gutter: 4pt,
column-gutter: 4pt,
align: (left + horizon),
statbox("FRC", "Strength, brute force, threats"),
statbox("TAC", "Knowledge, skill, intellect"),
statbox("CRE", "Diplomacy, deceit, psionics"),
statbox("RFX", "Precision, dexterity, aim"),
)
)
),
grid.cell(
colspan: 6,
rowspan: 2,
rect(
fill: luma(85%),
radius: 6pt,
width: 100%,
height: 100%,
inset: 4pt,
grid(
rows: (1fr, 1fr),
columns: (1fr, 1fr),
row-gutter: 4pt,
column-gutter: 4pt,
align: (left + horizon),
statbox_light("ARMOR", "Subtract from damage taken"),
statbox_light("MAX HP", "Capacity to take damage"),
statbox_light("WAR DICE", [Spend for +1D6 to *any* roll],
name-fill: gradient.linear(
(luma(45%), 0%),
(luma(40%), 5%),
(luma(15%), 90%),
(luma(0%), 100%),
angle: 90deg,
),
),
statbox_light("HP", "Operative death occurs at 0 HP"),
)
)
),
grid.cell(
colspan: 6,
align: (left + top),
inset: (top: 4pt, left: 2pt),
sheet-label[Notes]
),
)
#let body_cols(it) = {
set text(
font: "Space Grotesk",
size: 9pt,
weight: "regular",
tracking: -0.01em,
spacing: 100%,
ligatures: true,
features: ("ss04", "ss03", "ss02"), // alternate "D", "y", "g",
)
columns(
2,
gutter: 72pt,
it,
)
}
#let gray_block(it) = block(
stroke: (paint: luma(65%), thickness: 1.5pt),
inset: (x: 4pt, y: 8pt),
outset: (x: 2pt),
width: 100%,
radius: 2pt,
it,
)
#let emph_block(it) = block(
fill: luma(0%),
inset: (x: 4pt, y: 8pt),
outset: (x: 2pt),
width: 100%,
radius: 2pt,
text(
fill: luma(100%),
it,
),
)
#show heading.where(level: 1): it => {
set align(left + bottom)
block(
width: 100%,
inset: (bottom: 8pt),
outset: (x: 2pt),
below: 12pt,
stroke: (bottom: (2pt)),
text(
font: "Michroma",
size: 14pt,
tracking: 0.04em,
)[#upper(it.body)],
)
}
#show heading.where(level: 2): it => block(
width: 100%,
above: 13pt,
text(
font: "Space Grotesk",
size: 9pt,
weight: "bold",
tracking: 0pt,
ligatures: false,
it.body,
),
)
#show par: set block(
below: 12pt,
fill: luma(50%),
)
#set par(leading: 7pt)
#show link: it => text(
weight: 500,
fill: luma(20%),
// underline(it)
it
)
// just two character sheets
// #body_cols[#character_sheet #character_sheet]
#body_cols[
= Character creation
#grid(
columns: (3fr, 2fr),
column-gutter: 12pt,
rows: 1,
gray_block[
#block(below: 7pt)[Create a *FIST* operative as follows:]
#enum(
tight: true,
[Choose two *traits*, or roll 2D666],
[Based on your traits, fill out your stats:\ ATTRIBUTES (FRC, TAC, CRE, RFX), ARMOR, WAR DICE start at 0,\ MAX HP starts at 6, HP at MAX],
[Choose one: +1D6 additional MAX HP,\
+1D6 WAR DICE, 1 standard issue item],
[Choose a *role* not already in use],
[Choose an appropriate *codename*, and a real name only the player knows],
)
],
gray_block[
#block(below: 7pt)[
*Standard issue items*\
Roll 1D6 or choose:
]
#enum(
tight: true,
[Balaclava\ (hides identity)],
[Flashlight (can be used as an attachment)],
[Knife (1D6 DAMAGE)],
[MRE (+1D6 HP, one use)],
[Pistol (1D6 DAMAGE)],
[Riot shield (1 ARMOR, equip as weapon)],
)
],
)
Traits and roles index available online at #link("https://fistref.com")[fistref.com] or in FIST Ultra Edition.\
You are encouraged to reflavor traits and items.
*Traits* are snippets of special rules for individual characters which cover a unique talent, ability, or advantage, usually accompanied by a downside, boundary, or caveat if the trait's beneficial aspects are particularly powerful. Traits may offer narrative background, add new mechanics, alter pre-existing mechanics, or involve entire mini-games. Traits come packaged with an item (like a weapon, tool, or piece of clothing) and a modification to your base stats.
*Roles* define your character's narrative archetype. Roles come with a relevant backstory prompt (usually beginning with “Describe...") and a difficult condition which must be fulfilled by mission completion to advance (e.g. a pacifist cannot be violent, a wildcard must behave unpredictably). When a character *advances*, they can take another trait, +1D6 MAX HP, or +1D6 WAR DICE. Traits may change these rules.
#grid(
columns: (5fr, 4fr),
column-gutter: 8pt,
rows: 1,
[
== Emergency insertion
If your character dies, or you're joining in the middle of a mission, create a fresh character while play continues. When you're ready to deploy, signal the referee - note that boss battles and other dangerous areas may be no-insertion zones. When prompted, roll on the table on the right and jump into the fray.
],
emph_block[
Roll *2D6* to emergency insert:
#list(
tight: true,
[*6 OR LESS:* Deployment goes wrong somehow.],
[*7-9:* Deploy normally.],
[*10 OR ABOVE:* Deploy with\ an extra standard issue item.],
[*DOUBLE SIXES:* As above,\ and +3 to your first roll.],
)
],
)
#colbreak()
#character_sheet
]
#pagebreak()
#body_cols[
= Rules Summary
Full rules available at #link("https://claymorerpgs.itch.io/fist")[claymorerpgs.itch.io/fist]
In *FIST* (Freelance Infantry Strike Team), you portray a team of paranormal mercenaries doing the jobs that no one else can (or wants) in the military-espionage ecosystem of the Cold War. You are an unconventional kind of mercenary who cares more about being true to yourself, your community, or your ideals than turning a profit, and you may have been forced into this line of work due to incompatibility with non-violent, non-paranormal society.
Gameplay involves deploying your mercenary character on missions with other players, where you talk to people, solve problems, and engage in espionage and combat. The story and reality of your FIST game exists as an ongoing conversation between the players and the referee, and it's everyone's job to treat this game world like it actually exists, then act accordingly.
== Playing the game
Players and the referee take turns talking. The referee describes the scene the players are in (along with portraying people and providing background info), and the players respond by describing their actions within the game world. If an action would be risky or the outcome is otherwise uncertain, the referee establishes possible consequences of a failure, then the player rolls *2D6* and adds their most relevant *ATTRIBUTE* score: FORCEFUL (*FRC*),\
TACTICAL (*TAC*), CREATIVE (*CRE*), or REFLEXIVE (*RFX*). Don't roll the dice if the action described is easily accomplished or totally impossible.
#block(
stroke: (paint: luma(75%), thickness: 1pt),
inset: (x: 4pt, y: 8pt),
outset: (x: 2pt),
width: 100%,
radius: 2pt,
)[
When a character *does something risky*, the player rolls *2D6+ATTRIBUTE* and the referee narrates how the situation changes based on the total:
#list(
tight: true,
[*6- / FAILURE:* Things go wrong somehow],
[*7-9 / PARTIAL:* Things go right but with a complication or downside],
[*10+ / SUCCESS:* Things go right with no additional headaches],
[*DOUBLE SIXES / ULTRA:* Things go right with some spectacular bonus],
)
]
The referee never uses this system for non-player characters, but may roll the dice to determine damage, random behavior, content, etc. Referee controlled characters simply take action, and the players are given a chance to react or respond by roleplaying and/or rolling the dice.
Players can spend one *WAR DIE* to add +1D6 to *any* type of dice roll in the game, no matter who makes it (including the referee). WAR DICE are *consumable* -- when you use a WAR DIE, it's gone.
#colbreak()
== Combat and death
Attacking someone or dealing with being attacked is the same as any other risky action and handled accordingly with a 2D6 roll. Characters deal their weapon's *DAMAGE* (if rolling to attack) on a success and may take DAMAGE from their target on a failure.
If the players are engaged in active combat, rolling a failure always incurs DAMAGE. Using stealth, tricks, and tactical retreats to avoid active combat leads to better chances of survival. Players do not take regimented turns but should avoid hogging the spotlight with combat actions. Enemies controlled by the referee never roll to attack, but telegraph attacks for the players to respond to.
DAMAGE is subtracted from the victim's *HP*. *ARMOR* is subtracted from DAMAGE taken (e.g. 6 DAMAGE vs. 2 ARMOR subtracts 4 HP). Reaching 0 HP means a character has died. If a player's character dies, they are encouraged to insert a new character as soon as the story allows. Some characters may be revived through complex science or magic.
== Items
Items marked with a number of uses are unavailable when depleted, but replenish between missions; they are common and easily replaceable. Items marked *consumable* never return once used; they are uncommon, irreplaceable, or unique. Some items can be used indefinitely, like simple tools or trinkets. All items carry over from mission to mission, but items not granted by traits or standard issue are lost if left behind or destroyed.
Baseline FIST characters can wield one *weapon* at a time. Weapon damage depends on the type and size of the weapon, ranging from 3 DAMAGE for small holdout weapons, to 1D6+2 DAMAGE for heavy weapons, and possibly more. Unarmed/non-weapon attacks deal the worst of 2D6 DAMAGE.
Baseline FIST characters can wear one piece of body-sized *armor* at a time, in addition to an unlimited amount of non-armoring clothes and accessories that grant ARMOR (like helmets or shields). Some wearable items (capes, helmets, small shields) are *accessories*, which can be voluntarily destroyed to negate DAMAGE once.
== Rendezvous points
Once per mission, the players may request a rendezvous point, and the referee will describe a nearby but difficult-to-reach safe location where the players can recuperate. At the rendezvous point, each player chooses one: REST (heal 1D6 HP), RESTOCK (replenish one item or resource),\
or INTEL (one useful fact about the mission).
]
|
https://github.com/phinixplus/docs | https://raw.githubusercontent.com/phinixplus/docs/master/source/cpu/preface.typ | typst | Other | #let preface = [
#import "/source/template.typ": discord-link, license-link
#let serif = "https://fonts.google.com/specimen/IBM+Plex+Serif"
#let sans = "https://fonts.google.com/specimen/IBM+Plex+Sabs"
#let mono = "https://fonts.google.com/specimen/Inconsolata"
#let nerd = "https://www.nerdfonts.com/font-downloads"
= Preface
This section discusses the nature of the documentation itself, the scope and
aim of the PHINIX+ project, and about the author as an individual and their
motives. As a result, the use of the first person in the following section is
unavoidable. The formal specification begins at @heading-introduction if such
details are irrelevant for the reader.
== About the Document
The purpose of the document is to describe with maximum possible detail all the
features of the PHINIX+ system. It therefore tries to conform to the typical
requirements expected from technical documentation. The most important details
to be transparent about regarding the document itself are thus the decisions
about the look of the document (styling) and about the licensing around the
document.
=== Styling Decisions
This document was written using the "#link("https://typst.app/")[Typst]"
typesetting program. If the source code of the used template is not available
or the reader is not aware of Typst's syntax, the decisions made regarding
styling are hereby given:
- Pages are A4 sized with 25mm of vertical
and 20mm of horizontal margins.
- For the bulk of the text the serif font
"#link(serif)[IBM Plex Serif]" was used.
- For the headings and for the title the sans serif font
"#link(sans)[IBM Plex Sans]" was used.
- For the code blocks the #link(nerd)[Nerd Fonts] variant
of the monospace font"#link(mono)[Inconsolata]" was used.
- Internal links (references) are in blue color with the
exception of the contents page and footnotes.
- External links (hyperlinks) are underlined and
in blue color (as shown above).
=== Licensing Decisions
This document is licensed under the Creative Commons
#link(license-link)[BY-NC-SA 4.0] license. This project is not currently
intended to generate direct profit for the author and/or any other user of the
project, focusing instead on educational and novelty value. If you are making a
derivative of PHINIX+, you are kindly requested to retain this license per the
requirements of the license and attribute the original author. The license only
covers the architecture itself (this document) and not any implementations of
the described architecture.
== About the Author
Though I do know my way around the field of processor design and implementation,
I have no formal experience with the subject. Everything I know about regarding
the topic I have learned by myself and with help from other people online.
However, I am in the process of attending a computer engineering course at a
polytechnic university.
Typesetting is also an activity which I have had to teach myself. My university
did provide me a "Technical Document Writing" lesson though it was in reality
of little help. As a result, if you would like to suggest something regarding
the document, don't hesitate to reach out on #link(discord-link)[Discord].
== About the Project
This documentation and the overall design and direction of the PHINIX+ project
is my personal project which I have been working on during my free time. I never
got to experience early computing or the home computer revolution. As a result,
I made it my goal to come up with a completely independent computational system
that would mimic the experience of using systems of the late 1980s to early
1990s.
PHINIX+ attempts to be a platform from which many of the concepts common in
the modern computing environment could be understood (such as Operating Systems)
through re-implementation, as well as a platform on which the retro community
could build upon. PHINIX+ thus tries to cater to many use cases and it should
be wholly up to the implementer which of those use cases is most important for
what they want out of the system.
]
|
https://github.com/kazewong/lecture-notes | https://raw.githubusercontent.com/kazewong/lecture-notes/main/Engineering/SoftwareEngineeringForDataScience/lab/rust.typ | typst | #set page(
paper: "us-letter",
header: align(center, text(17pt)[
*An introduction to Rust*
]),
numbering: "1",
)
#import "./style.typ": style_template
#show: doc => style_template(doc,)
= Foreword
This session is somewhat a bias introduction from me because I love `Rust`. Here is the backstory: I was first introduced to `Rust` in 2022, mostly because of the #link("https://en.wikipedia.org/wiki/Rust_(programming_language)#Mozilla_layoffs_and_Rust_Foundation_(2020%E2%80%93present")[controversy] around it, and I did part of the #link("https://adventofcode.com/")[advent-of-code] (AOC) in Rust. At the time, I could not see much point of learning and using `Rust`, mostly because I do not know where to use `Rust`. I went on a year without using and following `Rust`, then I did most of AOC 2023 in `julia`. On December 24, 2023, I came across an article about web assembly (`wasm`), which talks about how `wasm` can be used to distribute code on the web which run on client-side with almost native performance, and how one of the main use case for `Rust` is to compile to `wasm`. I unfortunately and willingly sacrifice my 25th day of AOC to learn about `Rust` and `wasm`, and it was awesome. For the next couple of months I was exploring `Rust` a lot, and it was such a fun experience.
In case you do not realize how interesting it is, let me break it down for you. If you have supervised students or collaborate with others on a code project before, especially with someone using a MacOS, the most difficult part of the job could be getting them to install the dependencies correctly. Nowaday most python package can be install with ```bash pip install [package]```, but sometimes people need to build a package dependencies from source, and that is a highway to nightmare if the code is not supported by a huge community. Being able to write in a programming language like `Rust`, compile it to `wasm` and run it directly on a browser without any installation is a complete game changer. No install needed, just open the browser and boom, the code runs. Say in a dire situation like needing to factor some prime numbers in a party, you can just pull out your phone, open the browser and check whether a number is a prime. Isn't that cool?
Beside, I really had a great time coding Rust in general. It takes some time to get used to the language, but once you are more familiar with Rust, it is a great language to go hard core with. In this lab, we are going to go through the following topics:
= Key Concepts
== Rust is a compiled language
Unlike `python` and `julia` we have been playing with in the last two sessions, `Rust` does not offer a REPL, and it is not designed to be an interactive language. Instead, `Rust` is an ahead-of-time compiled language, which means you need to compile the code before you can run it. Similar to `c` and `c++`, `Rust` code is compiled into machine code and into executable, which then the users can execute.
== Rust is strongly and statically typed
Another major difference between `Rust` and the other two languages is that `Rust` is a strongly and statically typed language. This means that the type of every variable must be known at compile time, and the compiler will check that the types are used correctly. If you try to assign a variable of type `i32` to a variable of type `f64`, the compiler will throw an error. However, it does offer type inference, meaning the compiler will try to figure out the type of the variable if it is not explicitly stated. This is not gaurenteed to work all the time, but it is a nice feature to have.
== Borrow checker for memory management
The biggest innovation Rust brings to the table of programming language is the concept of ownership, or more commonly referred as the borrow checker #footnote[Most people encounter the concept of ownership through the borrow checker.]. This is to address the age old problem of memory management. There are usually two routes different programming languages take to manage memory: garbage collection and manual memory management. Both `python` and `julia` have a garbage collector that will regularly look for unused memory and release them. This is a very convenient way to manage memory, but it comes with overheads. On the other hand, languages like `c` demands the user to manually manage the memory allocation and deallocation, which could create segmatation fault if not done correctly.
`Rust` takes a different approach: it uses the concept of ownership to manage memory. The idea is that every value in `Rust` has a variable that is its owner, and there can only be one owner at a time. When the owner goes out of scope, the value is dropped, and the memory is deallocated. We will explore this more in the next section.
= Basic Syntax
== Variables
=== Scalar types
As opposed to `python` and `julia`, `Rust` requires you to declare the type of a variable when you define it #footnote[While type inference does exist in `Rust`, it is still a good practice to write the type of your variable explicitly.]. Here is an example of how you would declare a variable in `Rust`:
```rust
let x: i32 = 5;
```
In this example, we declare a variable `x` of type `i32` and assign it the value `5`. The `let` keyword is used to declare a variable, and the `:` is used to specify the type of the variable. The `i32` type is a 32-bit signed integer. You may be tempted to leave out the type declaration and let the compiler infer the type, but here is an example that shows why it is a good idea to specify the type explicitly:
```rust
let guess = "42".parse().expect("Not a number");
```
In this example, we try to convert a string into numeric type, but without specifying what is the type of the variable `guess`, the compiler will not know what type to convert the string to. This will result in a compilation error.
Another thing to pay attention to is mutability. By default, variables in `Rust` are immutable, meaning you cannot change the value of the variable once it is assigned. If you want to make a variable mutable, you need to use the `mut` keyword:
```rust
let mut x = 5;
x = 6;
```
=== Compound types
Compound types such as tuple and array are also available in `Rust`, and they are quite different from the other languages we have seen so far. Here is an example of how you would declare a tuple in `Rust`:
```rust
let tup: (i32, f64, u8) = (500, 6.4, "a");
println!("The value of y is: {}", tup.1);
```
You have to declare the type of each element in the tuple, and the type of the tuple itself is a combination of the types of its elements. We can access the elements of the tuple using the `.` operator followed by the index of the element we want to access.
Moving on to arrays. The definition of an array in `Rust` is different again. In `python` and `julia`, you can create an array without specifying its length at initialization. However, the compiler will need to know about the length of the array at compile time:
```rust
let a: [i32; 5] = [1, 2, 3, 4, 5];
```
And the elements of the array can be accessed using the `[]` operator:
```rust
let first = a[0];
```
Note that all the types we have discussed so far are fixed-length, and they are allocated to the stack, which is faster than the heap but do not allow for dynamic resizing.
If you want to create an "array" with variable length, you can use the `Vec` type:
```rust
let v: Vec<i32> = Vec::new();
for i in 1..5 {
v.push(i);
}
// You can also do this: let v = vec![1, 2, 3, 4, 5];
```
The `Vec` type is a growable array type that is allocated on the heap. This means that the size of the array can change at runtime, and it is slower than the fixed-length arrays. There are similar data type like `string` and `hashmap` that are also allocated on the heap. See #link("https://doc.rust-lang.org/book/ch08-00-common-collections.html")[here for more information].
== Functions
To write a function in `Rust`, you need to use the `fn` keyword followed by the name of the function and the arguments it takes. Unlike `python`, you need to specify the type of the arguments and the return type of the function, otherwise the compiler will throw an error. Here is an example:
```rust
fn add(x: i32, y: i32) -> i32 {
x + y
}
```
Note that the last expression in the function is the return value of the function, and you do not need to use the `return` keyword. You can still use the `return` keyword if you want to return early from the function.
== Control flow
Compared to all the definitions you have seen, the syntax of control flows in `Rust` is actually pretty similar to other languages. For example, to write a `for` loop in `Rust`, you can do the following:
```rust
for i in 1..5 {
println!("{}", i);
}
```
This is very similar to the `for` loop in `python` and `julia`. The `1..5` syntax is a range, which can be iterated through.
Since this is pretty simple and straight forward, we are not going to spend more time on this topic. For more detail on control flow, see #link("https://doc.rust-lang.org/book/ch03-05-control-flow.html")[here].
== Scope and borrowing
Now let's get to the fun part: ownership. This is `Rust` unique way to manage memory, and it is the biggest reason why others consider `Rust` a very safe language. If you come from a `c` background and you maybe somewhat familiar with this syntax, but there should be a significant difference in terms of how `Rust` handle memory compared to `c`.
The basic problem statement of memory management is basically you need to allocate a chunk of address to store some of the values related to your computing task, and once you are done with the task, you should release the memory back to the system.
In `c`, it could be done by
```c
int *x = (int *)malloc(sizeof(int));
*x = 5;
free(x);
```
Here, we allocate the memory space for an integer, assign the value `5` to it, and then free the memory space. However, no matter how experience you are, you may eventually run into some memory issue. For example, if you try to access a memory that has been deallocated, you will get a segmentation fault. For example,
```c
int *x = (int *)malloc(sizeof(int));
*x = 5;
free(x);
printf("%d\n", *x);
```
This code will compile, but when you run it, you will get a segmentation fault. This is because the memory space that `x` points to has been deallocated, and you are trying to access it.
In `Rust`, there is a very smart approach to handle this. The idea is that every value in `Rust` has a variable that is its owner, and there can only be one owner at a time. When the owner goes out of scope, the value is dropped, and the memory is deallocated. Here is an example:
```rust
{
let x = 5;
println!("{}", x);
}
```
In this example, the curly braces define a new scope, and the variable `x` is the owner of the value `5`. When the scope ends, which is when the closing curly brace is reached, the value `5` is dropped, and the memory is deallocated. And if you try to access the value of `x` after the scope ends, you will get a compilation error, so you will find out your mistake way before you hit it in runtime. In this way, the users do not need to worry about memory managment (as much), and we don't have to pay the price of garbage collection.
Now this comes with some counterintuitive behavior for beginners. Let's see how we will 'borrow' a variable in `Rust`:
```rust
fn modify(x: &mut i32) {
*x = 5;
}
fn main() {
let mut x = 0;
modify(&mut x);
println!("{}", x);
}
```
You see the `&` symbol in front of the variable `x` in the `modify` function. This is called a reference, and it is a way to borrow a variable in `Rust`. The `&mut` keyword means that the reference is mutable, which means that the function can modify the value of the variable. The `*` symbol is used to dereference the reference, which means to get the value that the reference points to. In this example, the `modify` function takes a mutable reference to an integer, and it sets the value of the integer to `5`.
If you try to remove the `&mut` keyword in the `modify` function, you will get a compilation error, because you are trying to modify a borrowed value, and that is not mutable.
Now there are more intrincate examples to really show the reason why this way to manage memory is out right awsome on the #link("https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html")[official documentation]. I highly encourage you read through that as it will allow you to understand `Rust` deeper. And then #link("https://doc.rust-lang.org/book/ch16-00-concurrency.html")[the concurrency chapter] is my favorite chapter that makes this way of handling memory really shines thorugh.
= We will write a simple MCMC algorithm this time
To switch things up a bit, instead of coding an insertion sort yet again, we will code a simple Metropolis-Hastings algorithm in Rust. More specifically, we are going to sample from a Gaussian distribution with a Gaussian proposal distribution.
== Step 0: Install Rust
Follow the instruction on #link("https://www.Rust-lang.org/tools/install")[this link]. After installing Rust, you should have access to the `cargo` command in the terminal. If you are using VSCode as your IDE, you can also install the `Rust-analyzer` extension to get better support for Rust.
== Step 1: Clone the class repository
Clone the template repo from #link("https://github.com/KazeClasses/Rust_guide.git")[this link].
== Step 2: Implement the Metropolis-Hastings algorithm
The pseudocode for the Metropolis-Hastings algorithm is as follows:
+ Start at an arbitrary point `x`
+ Repeat the following steps for `n` iterations:
+ Sample a candidate point $y$ from a Gaussian distribution with mean $x$ and variance $sigma$, $y tilde N(x, sigma^2)$
+ Calculate the acceptance probability $p = min(1, p(y) / p(x))$, where $p$ is the target distribution
+ Sample a uniform random number $u tilde U(0, 1)$
+ If `u < acceptance probability`, set `x = y`
+ Store `x` in a list
There should be some starter code in the `sampler.rs` file, which contains the following functions: a struct named `State` to store the current state of the sampler, a function named `long_likelihood` as our target function, implementation of the `State` struct with a `new` function, and a `take _step` function to sample a new state from the proposal distribution. We will implement them one by one in the following section.
=== Step 2.1: Creating a struct for the sampler state
In the `sampler.rs` file, you will see a struct named `State` that is used to store the current state of the sampler. We need three fields in this struct: a random number generator `rng`, an array containing the current state `x`, and the proposal distribution.
I have import some relevant libraries on the top of the file, try to look through them and understand how why they are imported. By the end of this step, your `State` struct should look like this:
```rust
pub struct State<const N_DIM: usize> {
rng: StdRng,
pub arr: [f64; N_DIM],
proposal_distribution: MultivariateNormal,
}
```
Notice the `pub` keyword in front of the struct, this is to make sure one can import the struct from other files. Another fancy syntax I put it is the `const N_DIM: usize`. This is called generics parameters in `Rust`, and it allows you to write functions or struct over a range of types in order to reduce code duplication.
=== Step 2.2: Implementing the target function
For the target distribution, let's just choose a simple Gaussian distribution with mean 0 and variance 1. Instead of specifying the probability function itself, it is often more practical to specify the log of the probability function. Try implementing the `log_likelihood` function that corresponds to
$ log p(x) = -sum_(i=0)^n x_i^2/2 $. This should be easy enough that I don't want to give away the answer here.
=== Step 2.3: Implementing the `new` function in the `State` struct
The next thing we have to do is to implement the body functions related to the `State` struct. The first function we are going to implement is the `new` function, which is used to initialize the state of the sampler.
To initialize the random number generator, we will use the `StdRng` struct from the `rand` crate. It is always a good practice to set a seed for your random number generator, so that you can reproduce the results later. The function needed for generating such random number generator is `SeedableRng::from_seed`. Here is the #link("https://docs.rs/rand_core/latest/rand_core/trait.SeedableRng.html#tymethod.from_seed")[doc page] to this function.
The next thing we need to do is to initialize the array `arr` with zeros. This step should be trivial enough so answer is not given here.
Finally, we need to initialize the proposal distribution. As shown in the definition for the struct, the `proposal_distribution` is of the type `MultivariateNormal` as defined in `statrs`. The function signature should look like this:
```rust
let proposal_distribution = MultivariateNormal::new(mean, var).unwrap();
```
where `mean` and `var` are vectors of length `N_DIM` and `N_DIM x N_DIM` respectively. This function returns a `Result` type, which is commonly used for handling potential errors. To extract the actual object we need, we have to unwrap the result.
=== Step 2.4: Implementing the `take_step` function in the `State` struct
The last thing we have to implement is the `take_step` function, which is used to sample a new state.
To sample a propsal state from the proposal distribution, use these follwoing lines:
```rust
let binding = self.proposal_distribution.sample(&mut self.rng);
let proposal= binding.as_slice();
```
The next thing you need is to compute the log likelihood ratio between the proposed location and the current location, then draw a random number from a uniform distribution to decide whether to accept the proposal. If you decide to accept the proposal, then you have to update the current location to the proposed location. There are some tricky bits here which I want to leave for you to figure out. But if you get stuck in this process, the completed code after this section is in the `MCMC` branch of the template repo.
== Step 3: Test the algorithm
While `Rust` is an awesome language and give developer a lot of low level access such as GPU programming, interactive workflow such as making a plot in a data science workflow is not `Rust`'s main focus. There are some visualization library in `Rust` such as `plotters`, but in order to visualize the result we have generated, the script needed is linked #link("https://github.com/plotters-rs/plotters/blob/master/plotters/examples/normal-dist.rs")[here], which is quite long compared to python. For people who want to try it out, go for it. But this part, we are just going to run a scatter plot with `python` and `matplotlib`.
Once you have implemented algorithm as stated in Step 2, run the following command in the terminal to generate the data:
```bash
cargo run | test.text
```
This should run your main function and dump the output to a file called `test.text`. Now, run the following python script to visualize the result:
```python
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt("test.text")
plt.scatter(data[:, 0], data[:, 1])
plt.show()
```
Now you saw the message saying the code is compiled but not optimized, and you are wondering why. The reason is there are different optimization configurations that offers different trade-offs between compile time and runtime performance. To compile the code with optimization, run the following command:
```bash
cargo run --release | test.text
```
This code should run faster than the previous one.
= Putting the MCMC algorithm on the Web
Now you have familiarized yourself with the basic syntax of `Rust`, let's get to the *really* fun part: serving your code as a client-side web application. We are going to compile our `Rust` code into `WebAssembly` (`wasm`) and run it in the browser. While `WebAssembly` itself is a programming language, it is more maded to be a compilation target for other languages such as `Rust`, `c`, `c++`, meaning you can write in `Rust` then compile the code into `wasm`. WebAssembly provides a way to run code in the browser at near-native speed on client side.
== Step 0: Installing wasm-pack
The package we will use to bundle our `wasm` code such that we can use in a normal web development workflow is called `wasm-pack`. To install `wasm-pack`, run the following command:
```bash
cargo add wasm-pack
```
== Step 1: Restructuring the code
In order to compile our code into `wasm`, we need to adda couple more functions to the `lib.rs` file and modify the `Cargo.toml` file.
Starting with the `Cargo.toml` file, we need to add the following lines:
```toml
[lib]
crate-type = ["cdylib"]
```
This compiles the code into a dynamic library that can be load at runtime, and in this way it can be used in the browser.
The `lib.rs` file should look like this:
```rust
pub mod sampler;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn run() {
const N_STEP: usize = 100;
const N_DIM: usize = 2;
let mut state = sampler::State::<N_DIM>::new(0xdeadbeef);
for _ in 0..N_STEP {
state.take_step();
log(&format!("{:?}, {:?}", state.arr[0], state.arr[1]));
}
}
#[wasm_bindgen]
extern "C" {
fn alert(s: &str);
// Use `js_namespace` here to bind `console.log(..)` instead of just
// `log(..)`
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
#[wasm_bindgen]
pub fn greet() {
alert("Hello from wasm");
}
```
== Step 2: Scaffolding the frontend
Since we are going to learn more about frontend development in the future session, we are not going to get fancy here. Instead, we are going to create the bare minimum needed to demonstrate we can run our `Rust` code in the browser.
We basically need two files: `index.html` and `index.js`. The `index.html` file will be defining the end point for where the `wasm` code will be loaded, and the `index.js` file will be loading the `wasm` code and running it. Here is the content of the `index.html` file:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World - Rust</title>
<script type="module" src="./index.js"></script>
</head>
<body></body>
</html>
```
This file is as barebone as it gets. It is just a simple HTML file that includes the `index.js` file. The `index.js` file will be responsible for loading the `wasm` code and running it. Here is the content of the `index.js` file:
```javascript
// Import our outputted wasm ES6 module
// Which, export default's, an initialization function
import init from "./pkg/mcmc_example.js";
const runWasm = async () => {
// Instantiate our wasm module
const helloWorld = await init("./pkg/mcmc_example_bg.wasm");
// Call the run function in the wasm module, which will return the result of our calculation
helloWorld.run();
};
runWasm();
```
This file is also very simple: it imports the `init` function from the `mcmc_example.js` file, which is generated by `wasm-pack`, and then calls the `init` function with the path to the `wasm` file. The `init` function will return a promise that resolves to the `wasm` module, which we can then use to call the `run` function.
== Step 3: Magic moment
If you start a runtime with the following command at the root of the project (where the html file is located), say with `python -m http.server`, you should be able to see the result of the MCMC algorithm in console of the browser.
= Development tips
== Make sure you check how active a crate is
`Rust` eco-system kind of have the same problem as `julia` from time to time, that is there could be multiple crates trying to do the same thing and you may pick a crate that sounds good on paper but may not actually solve your problem.
== Use linter/formatter/extensions
There are great IDE extension for `Rust` that can help you write better code. For example, the `Rust-analyzer` extension for `VSCode` is a great tool that will save you a lot of fustrations. It highlights codes that will rise a compilation error, and it also helps you format your code, plus a bunch of other features. Highly recommended.
== Don't forget `Rust` is a low level language
Coming from `python` or `julia`, you may have several habits on relying on existing packages or try to think in a vectorized way, i.e. "how should I use numpy instead of writing my own code?". This is completely valid, and more often than not encouraged, because there might be people with more experience working on the same algorithm who have made a crate already. However, in the end of the day, the only thing that matters is whether you code does what you want. If you are confident in the vision of your program and in how to implement the corresponding algorithm, doing it yourself maybe faster than looking up a solution, since `Rust`'s community has very different focus compared to other more data science focused languages.
= Noteworthy libraries
These libraries I mention below are not necessary considered packages for data science directly. However, they give you a good sample of what `Rust` is capable of.
== Bevy
#link("https://bevyengine.org/")[Bevy] is a "data-driven" game engine that allows you to build game fully with `Rust`. Since it is still in its early days, I don't usually consider it a fully production ready game engine like `Unreal`, `Unity` or event `Godot`. However, I do find it quite educational and light weight enough to be a platform to add interactibility to a demo. Because everthing is in `Rust`, it is actually great for building data-driven demos, since you can just build your data processing code in `Rust`, and then use `Bevy` to visualize the result.
== Axum/Actix
`Axum` and `Actix` are the two most popular web framework in `Rust`. If you want to build a backend that handls compute and requests, they are both pretty solid options. From what I have read around, `Axum` seems to have more support around it, tho the first framework I picked up was `Actix` simply because it has a nonstandard standalone documentation page.
== wGPU -> rerun.io
#link("https://wgpu.rs/")[wGPU] is a graphic library for `Rust` that is based on the WebGPU API. Despite this description as a "graphic library", it is more like a low level API that allows you to interact with the GPU directly#footnote[Similar to Vulkan if people have experience with that.]. When combined with `wasm`, it allows you to ship computation through browser that run on the client's GPU. One example is this #link("https://github.com/simbleau/nbody-wasm-sim")[demon site], which uses your GPU to simulate a 2D n-body problem.
In preparing this lecture note, I also discovered #link("https://rerun.io/")[rerun.io], which is mostly written in `Rust` and uses `wGPU` for rendering, it is pretty sick.
== candle/burn
`candle` and `burn` are two machine learning libraries that I think they are pretty interesting. `candle` has more stars on GitHub, and it is under the hugging face organization. There are many existing production level examples you can look into, even pretty recent models such as Segment Anything. On the other hand, burn is more experimental and they are trying to really do everything from scratch in `Rust`. For example, they have a lot of worked done on asynchronous execution, which could make it a very interesting option for embedded systems in the long run.
== Yew/leptos/dioxus
There are a number of frontend frameworks in `Rust` that are under active development. The biggest frontend framework so far is #link("https://yew.rs/")[Yew], which is a frontend framework inspired by `React`. The next two that are pretty similar in community size are #link("https://leptos.dev/")["leptos"] and #link("https://dioxuslabs.com/")[dioxus]. While they all sounds pretty cool and can be fun to play with, none of them have reached version 1.0 yet. This means their API is not yet stable and could cause some hassle in your development. For this reason, I am staying with javascript for frontend development, and only use `Rust` whenever I have performance critical functions. |
|
https://github.com/maxwell-thum/typst-pf3 | https://raw.githubusercontent.com/maxwell-thum/typst-pf3/main/pf3.typ | typst | MIT License | /*
pf3
Written by <NAME> (@maxwell-thum on GitHub)
Last modified: September 5, 2023
Based on the LaTeX style "pf2" by Leslie Lamport (https://lamport.azurewebsites.net/latex/pf2.sty)
See also "How to Write a 21st Century Proof" by Lamport (2011) (https://lamport.azurewebsites.net/pubs/proof.pdf)
*/
/*
TODO:
- When custom elements are added to Typst, make #pfstep one so that its behaviors can be customized throughout a document using set rules.
*/
#let currentstep = state("currentstep", (0,)) // array of integers representing the current step
#let pfdict = state("pfdict", (:)) // dictionary of steps corresponding to each label. currently steps are stored as a pair (array, string/content). this is because it is easier to find the proof depth from the array than the string (for qed throwing out steps which should no longer be referenced), but seemingly very difficult or impossible for #stepref to correctly format the step number given that its format in #pfstep is determined by a parameter of #pfstep.
// these produce the corresponding text and indent the argument for visual clarity
#let assume(cont) = grid(
columns: (4.5em, 1fr),
smallcaps("Assume:"), cont
)
#let prove(cont) = grid(
columns: (4.5em, 1fr),
smallcaps("Prove:"), cont
)
#let case(cont) = grid(
columns: 2,
smallcaps("Case:") + h(0.25em), cont
)
#let suffices(cont) = grid(
columns: 2,
smallcaps("Suffices:") + h(0.25em), cont
)
#let pflet(cont) = grid(
columns: 2,
smallcaps("Let:") + h(0.25em), cont
)
#let pfdef(cont) = grid(
columns: 2,
smallcaps("Define:") + h(0.25em), cont
)
// these just produce text
#let pf = smallcaps("Proof:")
#let pfsketch = smallcaps("Proof sketch:")
// ideally this (or your favorite alternative symbol) is placed at the end of every *completed* paragraph proof. i imagine this will helps one keep track of unfinished proofs.
#let qed = math.qed
#let shortstepnumbering(steparray) = [#sym.angle.l] + str(steparray.len()) + [#sym.angle.r#steparray.at(-1)]
// step of a structured proof.
#let pfstep(
hidepf: false, // you can optionally hide a specific step's proof.
pfhidelevel: 128, // deepest proof level to show. (optional; intended only to be customized with set rules once custom elements are added to Typst)
pflongindent: false, // if set to true, each indent is the full length of the step number. (optional; ditto)
pfmixednumbers : 1, // use short step numbers for all levels >= N. (optional; ditto)
pflongnumbers : false, // use long step numbers for all levels. in practice you could also just set pfmixednumbers to be very large. (optional; ditto)
steplabel, // step name label for referencing (note this is required)
claim, // text/claim of step
pf_content // proof of step
) = {
// increment current step number
currentstep.update(x => {
x.push(x.pop()+1)
return x
})
locate(loc => {
let currentstep_array = currentstep.at(loc) // current step number array
// corresponding formatted step number
let currentstep_number = {
if currentstep_array.len() >= pfmixednumbers and not pflongnumbers {
shortstepnumbering(currentstep_array)
} else {
currentstep_array.map(str).join(".")
}
}
// add label/step number pair to dictionary
pfdict.update(x => {
x.insert(steplabel, (currentstep_array,currentstep_number))
return x
})
if pflongindent {
grid(
columns: 2,
rows: 1,
currentstep_number + "." + h(0.25em),
[
#claim
// show this step if the proof depth is <= pfhidelevel and it hasn't been hidden manually
#if (not hidepf and currentstep_array.len() < pfhidelevel ) {
// now that we might add substeps, add a 0 to the end of the step number array
currentstep.update(x => {
x.push(0)
return x
})
pf_content
// after the step is proved, remove the leftover substep index
currentstep.update(x => {
x.pop()
return x
})
}
]
)
} else [
// display the proof number followed by the step's claim
#grid(
columns: 2,
rows: 1,
currentstep_number + "." + h(0.25em),
[#claim]
)
// show this step if the proof depth is <= pfhidelevel and it hasn't been hidden manually
#if (not hidepf and currentstep_array.len() < pfhidelevel ) {
// now that we might add substeps, add a 0 to the end of the step number array
currentstep.update(x => {
x.push(0)
return x
})
// indent the proof of the step
pad(left: 1em, pf_content)
// after the step is proved, remove the leftover substep index
currentstep.update(x => {
x.pop()
return x
})
}
]
})
}
// final proof step (necessary for top-level proofs!)
#let qedstep(pf_content) = {
pfstep("qed", "Q.E.D.", pf_content) // display a proof step with generic "qed" label and claim "Q.E.D."
// (only needed for top-level steps) at the end of the step, reset the lowest-level step counter to 0
currentstep.update(x => {
x.last() = 0
return x
})
// remove the "qed" key from the dictionary
locate(loc => if pfdict.at(loc).keys().contains("qed") {
pfdict.update(x => {
x.remove("qed")
return x
})})
// remove the dictionary keys of the previous steps at this level so they can no longer be referred to
locate(loc => pfdict.update(x => {
for steplabel in x.keys() {
if x.at(steplabel).first().len() >= currentstep.at(loc).len() {
x.remove(steplabel)
}
}
return x
}))
}
#let stepref(steplabel) = locate(loc => pfdict.at(loc).at(steplabel).last())
|
https://github.com/vEnhance/1802 | https://raw.githubusercontent.com/vEnhance/1802/main/src/chvar.typ | typst | MIT License | #import "@local/evan:1.0.0":*
= Change of variables
We'll do just two variables for now;
the 3-D situation is exactly the same and we cover it later.
== [TEXT] Interval notation
One quick notational thing if you haven't seen this before:
#definition(title: [Definition: Interval notation])[
Suppose $[a,b]$ and $[c,d]$ are closed intervals in $RR$ (so $a <= b$ and $c <= d$).
By $[a,b] times [c,d]$ we mean the rectangle consisting of points
$(x,y)$ such that $a <= x <= b$ and $c <= y <= d$.
(So the four corners of the rectangle are $(a,c)$, $(a,d)$, $(b,c)$, $(b,d)$.)
]
#example[
For example $[0,1] times [0,1]$ would be a unit square whose southwest
corner is at the origin.
Similarly, $[0,5] times [0,3]$ would be a rectangle of width $5$ and height $3$.
]
#figure(
image("figures/chvar-rect.png", width: auto),
caption: [A picture of $[0,5] times [0,3]$. This is just the set of points where $x$ is in
the interval $[0,5]$ and $y$ is in the closed interval $[0,3]$.],
)
== [TEXT] Transition maps
As it turns out $x y$-integration (or $x y z$-integration in 3D) isn't always
going to be nice, even if you try both horizontal and vertical slicing.
The standard example that's given looks something like this:
suppose you want to integrate the region bounded by the four lines
$ x y = 16/9, #h(1em) x y = 16/25, #h(1em) x = 4 y, #h(1em) y = 4 x. $
This region is sketched in @fig-chvar-ex.
As I promised you, I think it's better for your thinking if you write these as inequalities:
#eqn[
$ 16/25 <= x y <= 16 / 9 \
1/4 <= y / x <= 4. $
]
#figure(
image("figures/chvar-region.png", width: auto),
caption: [A cursed region bounded by four curves.
Trying to do $x y$-integration in either direction will be annoying as heck.],
) <fig-chvar-ex>
This section introduces a technique called "change of variables" that will
allow us to handle this annoying-looking yellow region for when we don't want to do $x y$-integration.
The idea is to make a new map of the yellow region with a different coordinate system.
To do this, I need to tell you a new term:
#definition(title: [Definition of transition map])[
Suppose $cal(R)$ is a region.
Let $cal(S)$ be another region, often a rectangle.
A *transition map* for $cal(R)$ is a function $bf(T) : cal(S) -> cal(R)$
that transforms $cal(S)$ to $cal(R)$.
In 18.02 we always require that all the points except possibly the boundaries of $cal(S)$
get mapped to different points in $cal(R)$.
Thus, writing the inverse $bf(T)^(-1)$ usually also makes sense.
]
If $cal(S)$ is a rectangle --- and again, that's quite common ---
then sometimes $bf(T)$ is also called a cell
(e.g. my Napkin does this when discussing differential forms).
#remark(title: [Remark: An analogy to the world map])[
Cartography or geography enthusiasts will find that the word "map" gives them the right instincts.
If you print a world map on an $8.5 times 11$ or A4 sheet of paper,
it gives you a coordinate system for the world with longitude and latitude.
So $cal(R)$ can be thought of as the surface of the Earth,
while $cal(S)$ is the rectangular sheet of paper.
The map is always distorted in some places, because the Earth is not flat:
the north and south pole will often get stretched a ton, for example.
But that's okay --- *as long as each longitude and latitude gives you a different point on
Earth, we're satisfied*. Technically there are exceptions at the north and south poles,
but those are on the boundary and we let it slide.
This corresponds to the idea that a cell can capture a complicated area with two coordinates.
See @fig-xkcd-charts.
]
#figure(
box(image("media/xkcd-977.png", width: 40%), stroke: 1pt),
caption: [One of the map projections from #link("https://xkcd.com/977/")[XKCD 977],
a chart titled _What your favorite map projection says about you_.
There's several more if you're curious.],
) <fig-xkcd-charts>
Now how does a transition map help us?
Well, first, let's show how we can do cartography on the region we just saw,
and then worry about the integration later.
The key idea is that we need to rig our transition function such that
$ u = y / x, #h(2em) v = x y $
so that our two inequalities we saw earlier are just
$ 1/4 <= v <= 4, #h(2em) 16/25 <= v <= 16/9. $
This lets us make a portrayal of the yellow region as a sheet of paper.
See @fig-chvar-trans, which is really important to us!
#figure(
image("figures/chvar-trans.png", width: auto),
caption: [We use a $(u,v)$ rectangle as a transition map to
do cartography on the region $cal(R)$.],
) <fig-chvar-trans>
How do we actually express the transition map of $bf(T)$?
It's actually easier to write the _inverse_;
in this context it's actually more natural to write
$ bf(T)^(-1)(x,y) = (y/x, x y). $
If you really need $bf(T)$ itself,
you would solve for $u$ and $v$ in terms of $x$ and $y$ to get
$ x &= sqrt(v / u) \
y &= sqrt(u v) $
so that our transition map is given exactly by
$ bf(T)(u,v) = (sqrt(v/u), sqrt(u v)). $
However, actually for integration purposes (we'll see this next section)
you can actually get away with only the formula for $bf(T)^(-1)$ instead.
== [TEXT] Integration once you have a transition map
If you remember change-of-variables from 18.01,
the 18.02 is the grown-up version where you have a transition map instead.
#definition(title: [Definition: Jacobian determinant])[
Let $bf(T)$ be a transition map defined from a region in $RR^n$ to $RR^n$.
The *Jacobian matrix* is the determinant of the matrix
whose rows are the gradients of each component written as row vectors.
In these notes we denote it my $J_(bf(T))$.
]
#example[
Let's consider the transition map $bf(T)(u,v)$ we saw earlier, that is
$ bf(T)(u,v) = (sqrt(v/u), sqrt(u v)). $
We compute the gradient of $(u,v) |-> sqrt(v/u)$ by taking the two partials:
$ partial / (partial u) sqrt(v/u) &= -1/2 u^(-3/2) v^(1/2) \
partial / (partial v) sqrt(v/u) &= 1/2 u^(-1/2) v^(-1/2). $
The other component $(u,v) |-> sqrt(u v)$ has the following gradient:
$ partial / (partial u) sqrt(u v) &= 1/2 u^(-1/2) v^(1/2) \
partial / (partial v) sqrt(u v) &= 1/2 u^(1/2) v^(-1/2). $
So the Jacobian matrix for $bf(T)$ is
$ J_(bf(T)) = mat(1/2 u^(-3/2) v^(1/2), 1/2 u^(-1/2) v^(-1/2);
1/2 u^(-1/2) v^(1/2), 1/2 u^(1/2) v^(-1/2)). $
]
#example[
We can also find the Jacobian of the _inverse_ map too,
that is the transition map $bf(T) : bf(R) -> bf(S)$ defined by
$ bf(T)^(-1)(x,y) = (y/x, x y). $
In other words, this is the map that transforms $(x,y)$ into $(u,v)$.
This is actually less painful because you don't have to deal with the square roots everywhere.
$ partial / (partial x) (y/x) &= -y/x^2, &#h(2em) partial / (partial y) (y/x) &= 1/x \
partial / (partial x) (x y) &= y, &#h(2em) partial / (partial y) (x y) &= x. $
So the Jacobian matrix for $bf(T)^(-1)$ is
$ J_(bf(T)^(-1)) = mat(-y/x^2, 1/x; y, x). $
]
Okay, now for the result.
#memo(title: [Memorize: Change of variables])[
Suppose you need to integrate $iint_(cal(R)) f(x,y) dif x dif y$
and you have a transition map $bf(T)(u,v) : cal(S) -> cal(R)$.
Then the transition map lets you change the integral as follows:
$ iint_(cal(R)) f(x,y) dif x dif y = iint_(cal(S)) f(u,v)/(|det J_(bf(T))|) dif u dif v $
Alternatively, if it's easier to compute $J_(bf(T)^(-1))$, the following formula also works:
$ iint_(cal(R)) f(x,y) dif x dif y = iint_(cal(S)) f(u,v) |det J_(bf(T)^(-1))| dif u dif v $
]
Here $|det J_(bf(T))|$ is called the *area scaling factor*:
it's the absolute value of the determinant of the Jacobian matrix.
It's indeed true that $ det J_(bf(T)^(-1)) = 1 / det(J_(bf(T))) $
which means that if your transition map has a nicer inverse than the original,
you might prefer to use that instead.
#typesig[
The area scaling is always a _nonnegative_ real number.
]
#tip[
You might find it easier to remember both formulas if you write
$ dif u dif v = |det J_(bf(T))| dif x dif y $
so it looks more like $dif u = (partial u) / (partial x) dif x$ from 18.01.
]
#digression(title: [Digression on what $dif u dif v$ means])[
For 18.02, the equation $dif u dif v = |det J_(bf(T))| dif x dif y$
is more of a mnemonic right now than an actual equation;
that's because in 18.02 we don't give a definition of what $dif x$ or $dif y$ etc.
It can be made into a precise statement using something called a _differential form_.
This is out of scope for 18.02, which has the unfortunate consequence
that I can't give a formal explanation why the change-of-variable formula works.
]
This is the analog in 18.01 when you did change of variables from $x$ to $u$
(called $u$-substitution sometimes), and you changed $dif x$ to $(dif x)/(dif u) dif u$.
In 18.02, the derivative from 18.01 is replaced by the enormous Jacobian determinant.
Let's see an example of how to carry out this integration.
#sample[
Find the area of the region $cal(R)$ bounded by the curves
$ x y = 16/9, #h(1em) x y = 16/25, #h(1em) x = 4 y, #h(1em) y = 4 x. $
]
#soln[
In the previous sections we introduced variables $u = y/x$ and $v = x y$,
and considered the region $ cal(S) = [1/4, 4] times [16/25, 16/9] $
which were the pairs of points $(u,v$).
We made a transition map $bf(T) : cal(S) -> cal(R)$ written as either
$ bf(T)(u,v) &= (sqrt(v/u), sqrt(u v)) \
bf(T)^(-1)(x,y) &= (y/x, x y). $
We don't like square roots, so we'll the determinant of the Jacobian for $bf(T)^(-1)$, which is
$ det (J_(bf(T)^(-1))) = det mat(-y/x^2, 1/x; y, x)
= (- y / x^2) dot x - 1 / x dot y = - y / x - y / x = - (2 y) / (x) . $
Since $u = y / x$, we can express this as:
$ det (J_(bf(T)^(-1))) = - 2 u . $
Hence, the area is given by the double integral
$
op("Area")(cal(R))
&= int_(u = 1 / 4)^4 int_(v = 16 / 25)^(16 / 9) lr(|det (J)|) dif v dif u \
&= int_(u = 1 / 4)^4 int_(v = 16 / 25)^(16 / 9) 2u dif v dif u \
&= int_(u = 1 / 4)^4 2u (16/9-16/25) dif u = 512/225 int_(u = 1 / 4)^4 u dif u \
&= 512 / 225 [u^2 / 2]_(u = 1 / 4)^4 = 512 / 225 dot 1 / 2 (4^2 - (1 / 4)^2) = 272/15. #qedhere
$
]
== [TEXT] Another example: the area of a unit disk <sec-chvar-polar>
#sample[
Show that the area of the unit disk $x^2 + y^2 <= 1$ is $pi$.
]
#soln[
For reasons that will soon be obvious,
we use the letters $r$ and $theta$ rather than $u$ and $v$ for this problem.
This time our cartographer's transition map is going to be given by
$ bf(T) : [0,1] times [0, 2pi] &-> RR^2 \
bf(T)(r, theta) &:= (r cos theta, r sin theta). $
You might recognize this as polar coordinates.
This gives us a way to plot the unit disk as a rectangular map; see the figure.
(Careful students might notice that the points on $(0,0)$ to $(1,0)$
are repeated more than once under the transition map;
again, in 18.02 we allow this repetition on the boundary.)
We calculate the Jacobian of $bf(T)$:
$ J_(bf(T)) = mat(
partial / (partial r) cos theta,
partial / (partial r) sin theta;
partial / (partial theta) (r cos theta),
partial / (partial theta) (r sin theta))
= mat(cos theta, sin theta; -r sin theta, r cos theta). $
The area scaling factor is then
$ |det J_(bf(T))| =
det mat(cos theta, sin theta; -r sin theta, r cos theta)
= r cos^2 theta - (-r sin^2 theta) = r(cos^2 theta + sin^2 theta) = r. $
Hence, the transition map gives us the following change of variables:
$ iint_(x^2+y^2=1) 1 dif x dif y
= int_(r=0)^1 int_(theta=0)^(2 pi) r dif theta dif r. $
This is easy to integrate:
$
int_(r=0)^1 ( int_(theta=0)^(2 pi) r dif theta) dif r
&= int_(r=0)^1 ( 2 pi r ) dif r \
&= 2 pi int_(r=0)^1 ( r ) dif r \
&= 2 pi [r^2/2]_(r=0)^(r=1) = pi. #qedhere
$
]
== [EXER] Exercises
|
https://github.com/tingerrr/subpar | https://raw.githubusercontent.com/tingerrr/subpar/main/test/util.typ | typst | MIT License | #let fake-image = block(stroke: red, inset: 1em, lorem(10))
|
https://github.com/DieracDelta/presentations | https://raw.githubusercontent.com/DieracDelta/presentations/master/08_09_24/main.typ | typst | #import "polylux/polylux.typ": *
#import themes.metropolis: *
#import "common.typ": *
#show: metropolis-theme.with(
footer: [#logic.logical-slide.display() / #utils.last-slide-number]
)
#set text(font: font, weight: wt, size: 25pt)
// #show math.equation: set text(font: "Fira Math")
#set strong(delta: 100)
#set par(justify: true)
#title-slide(
author: [<NAME>],
title: "Slides - 8/09",
)
#slide(title: "Abbreviated Pitch" )[
- Compile C to a subset of Rust (RustLight)
- Memory model
- Borrow checking
- Operational semantics
- LLMs
- Proposer's day registration
]
#slide(title: "This week")[
- Literature
- goto 🚧
- Aeneas 🚧
- Initialization (miri, rust-internals)
- Minor technical improvements
]
#slide(title: "Next week")[
- Slides
- Aeneas
- goto
- Implementation: goto
]
// #slide(title: "Aside on Aeneas")[
// #image("./ss.png")
// ]
|
|
https://github.com/Origami404/kaoyan-shuxueyi | https://raw.githubusercontent.com/Origami404/kaoyan-shuxueyi/main/main.typ | typst | #import "template.typ": *
#show: template.with(
title: [考研数学一 复习笔记],
short_title: "数一笔记",
description: [
复习考研数学一时的背诵大纲
],
date: datetime(year: 2024, month: 06, day: 04),
authors: (
(
name: "GitHub @ Origami404",
link: "",
affiliations: "",
),
),
affiliations: (),
lof: false,
lot: false,
lol: false,
// bibliography_file: "refs.bib",
paper_size: "a4",
cols: 1,
text_font: "Noto Serif CJK SC",
code_font: "Cascadia Mono",
accent: blue, // blue
)
#show heading: it => { it; h(1em) }
#include "./微积分/01-三角函数公式.typ"
#include "./微积分/02-极限与导数.typ"
#include "./微积分/03-一元积分.typ"
#include "./微积分/04-一元微分方程.typ"
#include "./微积分/05-中值定理.typ"
#include "./微积分/06-多元微分学.typ"
#include "./微积分/07-级数.typ"
#include "./微积分/08-空间解析几何.typ"
#include "./线性代数.typ"
#include "./概率与统计.typ"
|
|
https://github.com/ymgyt/techbook | https://raw.githubusercontent.com/ymgyt/techbook/master/math/function/function.typ | typst | = 関数
== 2次関数
2次関数を$y = a(x-p)^2 + q$で表すことを考える。\
$a > 0$の場合、$(x-p)^2$は必ず0以上なので、$(x-p)$が0の時、yは最小値、qとなる。\
$a < 0$の場合、$(x-p)$が0の時、yは最大値,qとなる\
$(x-p)$は$x = p$のとき0になるので、2次関数を$y = a(x-p)^2 + q$で表せる時、その頂点は$(p,q)$となる
=== 平方完成
2次関数を$y = a(x-p)^2 + q$で表現できると頂点の情報がえられる。\
そこで、一般的な2次関数$y = a x^2 + b x + c$を上記の形に変換する方法を考える。これを平方完成という。
$ y &= a x^2 + b x + c \
y &= a ( x^2 + frac(b,a) x ) + c \
y &= a ((x + frac(b,2a))^2 - frac(b^2, 4 a^2)) + c \
y &= a (x + frac(b,2a))^2 - frac(b^2, 4a) + c \
y &= a (x + frac(b,2a))^2 + frac(-b^2 + 4 a c, 4a) \
y &= a (x - (- frac(b, 2a))) ^2 + frac(-b^2 + 4 a c, 4a)
$
したがって、2次関数$y = a x^2 + b x + c$の頂点は\
$(- frac(b,2a), frac(-b^2 + 4 a c, 4a))$となる。 \
なお、3次関数以上はどうするかというと、微分する。
=== 解の公式
$
a x^2 + b x + c &= 0 wide &"(ただし "a != 0")" \
a (x^2 + frac(b,a) x) + c &= 0 wide &"(aでくくる)"\
a ((x + frac(b,2a))^2 - frac(b^2, 4a^2)) + c &= 0 \
a (x + frac(b,2thin a))^2 - frac(b^2,4a) + c &= 0 wide &"(aを分配)" \
a (x + frac(b,2a))^2 + frac(-b^2+4 a c, 4a) &= 0 \
a (x + frac(b,2a))^2 &= - frac(-b^2+4 a c, 4a) \
(x + frac(b,2a))^2 &= - frac(-b^2+4 a c, 4a^2) \
(x + frac(b,2a))^2 &= frac(b^2-4 a c, 4a^2) \
sqrt((x + frac(b,2a))^2) &= sqrt(frac(b^2-4 a c, 4a^2)) wide &"(両辺のrootをとる)" \
sqrt((x + frac(b,2a))^2) &= frac(sqrt(b^2-4 a c), sqrt(4a^2)) wide & (sqrt(frac(a,b)) = frac(sqrt(a),sqrt(b))) \
sqrt((x + frac(b,2a))^2) &= frac(sqrt(b^2-4 a c), 2a) \
sqrt(A^2) &= abs(A) "より" \
abs((x + frac(b,2a))) &= frac(sqrt(b^2-4 a c), 2a) \
(x+frac(b,2a)) &>= 0 "のとき" abs((x+frac(b,2a))) = x+frac(b,2a) & "(絶対値なので場合分けする)" \
x + frac(b,2a) &= frac(sqrt(b^2-4 a c), 2a) \
x &= - frac(b,2a) + frac(sqrt(b^2-4 a c), 2a) \
x &= frac(-b + sqrt(b^2-4 a c), 2a) & "(1)" \
$
$
(x+frac(b,2a)) &< 0 "のとき" abs((x+frac(b,2a))) = -(x+frac(b,2a)) &"(絶対値が負の場合)" \
-(x + frac(b,2a)) &= frac(sqrt(b^2-4 a c), 2a) \
x + frac(b,2a) &= - frac(sqrt(b^2-4 a c), 2a) \
x &= -frac(b,2a) - frac(sqrt(b^2-4 a c), 2a) \
x &= frac(-b -sqrt(b^2-4 a c), 2a) & "(2)" \
"(1),(2)より " x &= frac(-b +sqrt(b^2-4 a c), 2a) or
x = frac(-b -sqrt(b^2-4 a c), 2a)
$
$
<=> x &= frac(-b plus.minus sqrt(b^2-4 a c), 2a)
$
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1E900.typ | typst | Apache License 2.0 | #let data = (
("ADLAM CAPITAL LETTER ALIF", "Lu", 0),
("ADLAM CAPITAL LETTER DAALI", "Lu", 0),
("ADLAM CAPITAL LETTER LAAM", "Lu", 0),
("ADLAM CAPITAL LETTER MIIM", "Lu", 0),
("ADLAM CAPITAL LETTER BA", "Lu", 0),
("ADLAM CAPITAL LETTER SINNYIIYHE", "Lu", 0),
("ADLAM CAPITAL LETTER PE", "Lu", 0),
("ADLAM CAPITAL LETTER BHE", "Lu", 0),
("ADLAM CAPITAL LETTER RA", "Lu", 0),
("ADLAM CAPITAL LETTER E", "Lu", 0),
("ADLAM CAPITAL LETTER FA", "Lu", 0),
("ADLAM CAPITAL LETTER I", "Lu", 0),
("ADLAM CAPITAL LETTER O", "Lu", 0),
("ADLAM CAPITAL LETTER DHA", "Lu", 0),
("ADLAM CAPITAL LETTER YHE", "Lu", 0),
("ADLAM CAPITAL LETTER WAW", "Lu", 0),
("ADLAM CAPITAL LETTER NUN", "Lu", 0),
("ADLAM CAPITAL LETTER KAF", "Lu", 0),
("ADLAM CAPITAL LETTER YA", "Lu", 0),
("ADLAM CAPITAL LETTER U", "Lu", 0),
("ADLAM CAPITAL LETTER JIIM", "Lu", 0),
("ADLAM CAPITAL LETTER CHI", "Lu", 0),
("ADLAM CAPITAL LETTER HA", "Lu", 0),
("ADLAM CAPITAL LETTER QAAF", "Lu", 0),
("ADLAM CAPITAL LETTER GA", "Lu", 0),
("ADLAM CAPITAL LETTER NYA", "Lu", 0),
("ADLAM CAPITAL LETTER TU", "Lu", 0),
("ADLAM CAPITAL LETTER NHA", "Lu", 0),
("ADLAM CAPITAL LETTER VA", "Lu", 0),
("ADLAM CAPITAL LETTER KHA", "Lu", 0),
("ADLAM CAPITAL LETTER GBE", "Lu", 0),
("ADLAM CAPITAL LETTER ZAL", "Lu", 0),
("ADLAM CAPITAL LETTER KPO", "Lu", 0),
("ADLAM CAPITAL LETTER SHA", "Lu", 0),
("ADLAM SMALL LETTER ALIF", "Ll", 0),
("ADLAM SMALL LETTER DAALI", "Ll", 0),
("ADLAM SMALL LETTER LAAM", "Ll", 0),
("ADLAM SMALL LETTER MIIM", "Ll", 0),
("ADLAM SMALL LETTER BA", "Ll", 0),
("ADLAM SMALL LETTER SINNYIIYHE", "Ll", 0),
("ADLAM SMALL LETTER PE", "Ll", 0),
("ADLAM SMALL LETTER BHE", "Ll", 0),
("ADLAM SMALL LETTER RA", "Ll", 0),
("ADLAM SMALL LETTER E", "Ll", 0),
("ADLAM SMALL LETTER FA", "Ll", 0),
("ADLAM SMALL LETTER I", "Ll", 0),
("ADLAM SMALL LETTER O", "Ll", 0),
("ADLAM SMALL LETTER DHA", "Ll", 0),
("ADLAM SMALL LETTER YHE", "Ll", 0),
("ADLAM SMALL LETTER WAW", "Ll", 0),
("ADLAM SMALL LETTER NUN", "Ll", 0),
("ADLAM SMALL LETTER KAF", "Ll", 0),
("ADLAM SMALL LETTER YA", "Ll", 0),
("ADLAM SMALL LETTER U", "Ll", 0),
("ADLAM SMALL LETTER JIIM", "Ll", 0),
("ADLAM SMALL LETTER CHI", "Ll", 0),
("ADLAM SMALL LETTER HA", "Ll", 0),
("ADLAM SMALL LETTER QAAF", "Ll", 0),
("ADLAM SMALL LETTER GA", "Ll", 0),
("ADLAM SMALL LETTER NYA", "Ll", 0),
("ADLAM SMALL LETTER TU", "Ll", 0),
("ADLAM SMALL LETTER NHA", "Ll", 0),
("ADLAM SMALL LETTER VA", "Ll", 0),
("ADLAM SMALL LETTER KHA", "Ll", 0),
("ADLAM SMALL LETTER GBE", "Ll", 0),
("ADLAM SMALL LETTER ZAL", "Ll", 0),
("ADLAM SMALL LETTER KPO", "Ll", 0),
("ADLAM SMALL LETTER SHA", "Ll", 0),
("ADLAM ALIF LENGTHENER", "Mn", 230),
("ADLAM VOWEL LENGTHENER", "Mn", 230),
("ADLAM GEMINATION MARK", "Mn", 230),
("ADLAM HAMZA", "Mn", 230),
("ADLAM CONSONANT MODIFIER", "Mn", 230),
("ADLAM GEMINATE CONSONANT MODIFIER", "Mn", 230),
("ADLAM NUKTA", "Mn", 7),
("ADLAM NASALIZATION MARK", "Lm", 0),
(),
(),
(),
(),
("ADLAM DIGIT ZERO", "Nd", 0),
("ADLAM DIGIT ONE", "Nd", 0),
("ADLAM DIGIT TWO", "Nd", 0),
("ADLAM DIGIT THREE", "Nd", 0),
("ADLAM DIGIT FOUR", "Nd", 0),
("ADLAM DIGIT FIVE", "Nd", 0),
("ADLAM DIGIT SIX", "Nd", 0),
("ADLAM DIGIT SEVEN", "Nd", 0),
("ADLAM DIGIT EIGHT", "Nd", 0),
("ADLAM DIGIT NINE", "Nd", 0),
(),
(),
(),
(),
("ADLAM INITIAL EXCLAMATION MARK", "Po", 0),
("ADLAM INITIAL QUESTION MARK", "Po", 0),
)
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/all.typ | typst | #show <X>: it => {
if it.location().position().y > 480pt [$ $ #colbreak() #it]
else [#it]
}
#include "1_templates/Hlas1-2.typ"
// #include "1_templates/Hlas3-4.typ"
// #include "1_templates/Hlas5-6.typ"
// #include "1_templates/Hlas7-8.typ" |
|
https://github.com/pluttan/typst-g7.32-2017 | https://raw.githubusercontent.com/pluttan/typst-g7.32-2017/main/gost7.32-2017/utils/raw.typ | typst | MIT License | #import "../g7.32-2017.config.typ":config
#let theme = "../themes/"+config.raw.theme
#if (config.raw.theme != ""){
set raw(theme:theme)
}
// Функция разбивающая файл на подстроки по пробелам в начале строки
// [@example
// ```cpp
// int qu(){
// return 1;
// }
//
// int main(){
// return 0;
// }
// ``` => ```typst ('int qu(){\n return 1;\n', '}', 'int main(){ return 0;\n', '}')```
// ]
#let parse(lst) = {
let carr = ()
let i = 0
let fnc = ""
let nocol = 1
lst = lst.split("")
let func = 0
while (i < lst.len()) {
let dict = (
text: "",
tab : 0,
func: func,
nocol: nocol,
len: 0,
)
let predi = i
let tab = true
while (i < lst.len() and lst.at(i)!="\n"){
if (tab and lst.at(i)==" "){
dict.tab+=1
}
if (tab and lst.at(i) != " "){
if (dict.tab == 0){
func = nocol
}
tab = false
}
dict.text += lst.at(i)
i += 1
}
dict.len = i - predi
dict.func = func
carr.push(dict)
nocol += 1
i += 1
}
return carr
}
// deprecated
#let parsecpp(lst) = {parse(lst)}
#let parseasm(lst) = {parse(lst)}
// end-deprecated
#let разбор(лист) = {parse(лист)}
// Функция, выводящая переданное значение от f-той строки до t-той
#let writeft(lst, f, t) = {
let fi = 0
let i = 0
let fo = 0
let out = ""
let nlst = ()
lst = lst.split("\n")
while (i < lst.len()) {
i += 1
if (i >= f and i <= t) {
nlst.push(lst.at(i))
}
}
return nlst.join("\n")
}
#let вывединк(лист, нач, кон) = {writeft(лист, нач, кон)}
// Функция, выводящая код по ГОСТу
#let code(data, lang, lable, num: config.raw.num, num_splitter: config.raw.splitter, size: config.raw.size) = {
[
#set text(size)
#if (num){
show raw.line: it => {
if (it.number < 10){h(0.6em)}
text(fill: gray)[#it.number]
h(0.2em)
text(fill: gray)[num_splitter]
h(0.5em)
it.body
}
align(center)[
#if(config.raw.theme!=""){
raw(data, lang:lang, theme:theme)
} else {
raw(data, lang:lang)
}
#config.raw.counter.step()
]
} else {
align(center)[
#if(config.raw.theme!=""){
raw(data, lang:lang, theme:theme)
} else {
raw(data, lang:lang)
}
#config.raw.counter.step()
]
}
]
align(center)[
Листинг #config.raw.counter.display() #sym.bar.h _ #lable _
]
}
#let код(данные, язык, описание, нумерация: false, разделитель: "|", размер: 14pt) = {code(данные, язык, описание, num: нумерация, num_splitter: разделитель, size: размер)}
|
https://github.com/pal03377/master-thesis | https://raw.githubusercontent.com/pal03377/master-thesis/main/thesis_typ/abstract_de.typ | typst | MIT License | #let abstract_de() = {
set page(
margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm),
numbering: none,
number-align: center,
)
let body-font = "New Computer Modern"
let sans-font = "New Computer Modern Sans"
set text(
font: body-font,
size: 12pt,
lang: "en"
)
set par(leading: 1em)
// --- Abstract (EN) ---
v(1fr)
align(center, text(font: body-font, 1em, weight: "semibold", "Zusammenfassung"))
par(justify: true)[
Während sich Bildungsplattformen weiterentwickeln, um modernen Lernansätzen gerecht zu werden, spielen Learning-Management-Systeme wie Artemis eine entscheidende Rolle in der Organisation von Programmierkursen. Trotzdem stehen Dozenten und Tutoren vor der zeitaufwendigen Herausforderung, detailliertes Feedback zu liefern. Obwohl das kürzlich eingeführte Athena-System bereits einen semi-automatisierten Ansatz für Textaufgaben bietet, existiert eine noch ungeschlossene Lücke im Bereich der Programmieraufgaben. Die in dieser Masterarbeit durchgeführte Forschung zielt darauf ab, diese Lücke zu schließen, indem Athena so modifiziert wird, dass es sowohl Text- als auch Programmieraufgaben in einer einheitlichen Weise behandeln kann.
Wir setzen ein modulares Design um, das die Hinzufügung und Austauschbarkeit von Komponenten zur Feedbackgenerierung vereinfacht. In dieser neuen Architektur sind sowohl CoFee, Athenas aktuelles Modul für Feedback zu Textaufgaben, als auch ein für Programmieraufgaben spezialisiertes Modul auf Basis von maschinellem Lernen integriert. Dieses erweiterte Athena-System integrieren wir in Artemis.
Wir analysieren die bestehende Struktur von Athena, um Verbesserungspotenziale zu identifizieren. Daraufhin entwerfen und implementieren wir eine modulare Architektur, die speziell darauf zugeschnitten ist, verschiedene Arten von Übungsaufgaben zu unterstützen und das System durch das Hinzufügen neuer Feedback-Module erweitern zu können. Außerdem führen wir eine kurze Evaluierung durch, um die Qualität des automatisierten Feedbacks zu beurteilen.
Indem wir die Fähigkeiten von Athena ausbauen, verfolgt diese Masterarbeit das Ziel, die Feedback-Loop in der Programmierausbildung zu verkürzen, was sowohl für Dozenten als auch für Studierende deutliche Vorteile bietet.
]
v(1fr)
} |
https://github.com/ustctug/ustc-thesis-typst | https://raw.githubusercontent.com/ustctug/ustc-thesis-typst/main/chapters/floats.typ | typst | MIT License | = 浮动体
<浮动体>
== 三线表
<三线表>
三线表是《撰写手册》推荐使用的格式,如表~#link(<tab:exampletable>)[1.1]。
#block[
#align(center)[#table(
columns: 2,
align: (col, row) => (center,left,).at(col),
inset: 6pt,
[类型], [描述],
[挂线表],
[挂线表也称系统表、组织表,用于表现系统结构],
[无线表],
[无线表一般用于设备配置单、技术参数列表等],
[卡线表],
[卡线表有完全表,不完全表和三线表三种],
)
#align(center, [表号和表题在表的正上方])
]
] <tab:exampletable>
编制表格应简单明了,表达一致,明晰易懂,表文呼应、内容一致。
排版时表格字号略小,或变换字体,尽量不分页,尽量不跨节。
表格太大需要转页时,需要在续表上方注明"续表",表头页应重复排出。
== 插图
<插图>
有的同学可能听说"LaTeX 只能使用 eps 格式的图片",甚至把 jpg 格式转为
eps。 事实上,这种做法已经过时。 而且每次编译时都要要调用外部工具解析
eps,导致降低编译速度。 所以我们推荐矢量图直接使用 pdf 格式,位图使用
jpeg 或 png 格式。
// #figure([#box(width: 30%, image("../figures/ustc-badge.pdf", width: 30%))],
// caption: [
// 图号、图题置于图的下方
// ]
// )
// <fig:badge>
关于图片的并排,推荐使用较新的 宏包, 不建议使用 或 等宏包。
== 算法环境
<算法环境>
模板中使用 宏包实现算法环境。关于该宏包的具体用法,
请阅读宏包的官方文档。
#block[
initialization
]
注意,我们可以在论文中插入算法,但是插入大段的代码是愚蠢的。
然而这并不妨碍有的同学选择这么做,对于这些同学,建议用 宏包。
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/src/utils.typ | typst | Apache License 2.0 | // Joins two dictionaries together by inserting `new` values into `old`.
// When only-update is true, values will only be inserted if they keys exist in old.
#let combine-dict(new, old, only-update: false) = {
if only-update {
for (k, v) in new {
if k in old {
old.insert(k, v)
}
}
return old
} else {
return old + new
}
}
#let content-to-string(it) = {
return if type(it) == str {
it
} else if it == [ ] {
" "
} else if it.has("children") {
it.children.map(content-to-string).join()
} else if it.has("body") {
content-to-string(it.body)
} else if it.has("text") {
it.text
} else if it.has("base") { // attach
content-to-string(it.base) + "^" + content-to-string(it.t)
}
} |
https://github.com/voxell-tech/velyst | https://raw.githubusercontent.com/voxell-tech/velyst/main/README.md | markdown | Apache License 2.0 | # Velyst
Interactive [Typst](https://typst.app) content creator using [Vello](https://github.com/linebender/vello) and [Bevy](https://bevyengine.org).

*Associated example [here](./examples/hello_world.rs)!*
## Quickstart
Velyst renders Typst content using Typst functions. To get started rendering a simple box, create a function inside a `.typ` file:
```typ
#let main(width, height) = {
// Convert float to length
let width = (width * 1pt)
let height = (height * 1pt)
box(width: width, height: height, fill: white)
}
```
Then, in your `.rs` file, register your Typst asset file and function.
```rs
use bevy::prelude::*;
use bevy_vello::VelloPlugin;
use velyst::{prelude::*, VelystPlugin};
fn main() {
App::new()
.add_plugins((DefaultPlugins, VelloPlugin::default()))
.add_plugins(VelystPlugin::default())
.register_typst_asset::<HelloWorld>()
.compile_typst_func::<HelloWorld, MainFunc>()
.render_typst_func::<MainFunc>()
.insert_resource(MainFunc {
width: 100.0,
height: 100.0,
})
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2dBundle::default());
}
// `main` function in Typst with their respective values.
#[derive(TypstFunc, Resource, Default)]
#[typst_func(name = "main")] // name of function in the Typst file
struct MainFunc {
width: f64,
height: f64,
}
// Path to the Typst file that you created.
#[derive(TypstPath)]
#[typst_path = "path/to/file.typ"]
struct HelloWorld;
```
## Interactions
Velyst comes with built-in interactions using `bevy_ui`.

*Associated example [here](./examples/game_ui.rs)!*
## Join the community!
You can join us on the [Voxell discord server](https://discord.gg/Mhnyp6VYEQ).
## License
`velyst` is dual-licensed under either:
- MIT License ([LICENSE-MIT](LICENSE-MIT) or [http://opensource.org/licenses/MIT](http://opensource.org/licenses/MIT))
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0))
This means you can select the license you prefer!
This dual-licensing approach is the de-facto standard in the Rust ecosystem and there are [very good reasons](https://github.com/bevyengine/bevy/issues/2373) to include both.
|
https://github.com/Az-21/typst-components | https://raw.githubusercontent.com/Az-21/typst-components/main/components/deprecated/note.typ | typst | Creative Commons Zero v1.0 Universal | // Deprecated in favor of `showybox`
// https://github.com/Pablo-Gonzalez-Calderon/showybox-package
#let note(content, title: "Note", outline_color: luma(180), leading: "✅") = block(width: 100%, stroke: outline_color, inset: 16pt, radius: 4pt)[
#text(weight: "bold", smallcaps(raw(leading) + h(8pt) + title))
#parbreak()
#text(content)
]
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/web3/weeks/week10.typ | typst | #import "../../utils.typ": *
#section("Angular Architectures")
- MVC (Model View Controller)
- MVC + S (Model View Controller + Services -> API abstracted as it can often
change)
- Flux
- Flux single store
- unistore
- Flux multi store
- data is divided into multiple stores -> your transactions might not want to live
in the accounts store
- Redux -> while used with react, it's not bound to it!
- implementation of multistore
#align(
center,
[#image("../../Screenshots/2023_11_24_05_24_25.png", width: 60%)],
)
#text(
teal,
)[Note, angular does not come with a store! This is also why the assigment got a
bit annoying with a missing store -> see new transaction added, how to inform
the get transaction component.]
#subsection("Model View Controller")
#columns(2, [
- Angular offers RxJS -> UI / Service / Data Resource
- angular streams -> see pipes
#colbreak()
#align(
center,
[#image("../../Screenshots/2023_11_24_05_26_17.png", width: 80%)],
)
])
#subsubsection("Observables")
#align(
center,
[#image("../../Screenshots/2023_11_24_05_28_04.png", width: 100%)],
)
- Stream like
- stores and caches objects
- heart of observable is *Subject*
- *subject represents a traditional multicast event bus, but more powerful*
- provides all RxJS functional operators
- EventEmitter<T> provided by Angular
- hot observable
- *does not provide the latest value*
- reason: events can be lost if not accessed before next event
#set text(14pt)
Postfixing an observable with \$ will make it a hot observable! ```ts
// Behavior Subject
// used to store the last state and to notify subscribers about updates
// THIS CAN'T BE USED BY UI
private samples: BehaviorSubject<SampleModel[]> = new BehaviorSubject([ ]);
// hot obsersable
// USED BY UI!!
public samples$: Observable<SampleModel[]> = this.samples.asObservable();
```
#set text(11pt)
#subsubsubsection("Behavior Subject")
#text(
red,
)[This can't be used by UI! The last state does not interest the UI, it is only
interested in the latest state!]
#align(
center,
[#image("../../Screenshots/2023_11_24_05_37_33.png", width: 100%)],
)
This essentially caches events by providing the initial state when subscribing
and then the subsequent next state.\
#text(
teal,
)[Note, as this caches events, the behaviorsubject can't expose the next()
function for events. It would break the idea of it.]
#subsubsubsection("Cold to Hot")
As already explained, we use hot observables for events, which is what the UI
also wants.\
Before it was explained that things like a data request -> post or get return
cold observables, aka they give you the full stored data all the time.\
However, there is also a way to turn this cold observable into a hot observable!
->
- Data resources return cold observables
- this should not be returned -> otherwhise makes the request again!
- stores all data
- conversion from cold to hot possible
- RxJS has a share() operator for this purpose
Example with a request in angular -> BehaviorSubject("warm observable" to hot
observable) ```ts
@Injectable({providedIn: 'root'})
export class SampleService {
private samples: BehaviorSubject<SampleModel[]> = new BehaviorSubject([ ]);
public samples$: Observable<SampleModel[]> = this.samples.asObservable();
constructor(
private resourceService: SampleResourceService) {
}
public addSample(newSample: SampleModel): Observable<any> {
return this.resourceService
// store value on server with post
.post(newSample)
.pipe(
tap(res => {
// notify subscribers about chagne with BehaviorSubject
this.samples.next([...this.samples.getValue(), newSample]);
}),
catchError((err) => this.handleError(err)) );
}
private handleError(err: HttpErrorResponse) {
return new ErrorObservable(err.message);
}
}
```
#section("Flux Architecture")
The store solves the age old question of where do I store values to that
component X can access it, even though it is in a completely different spot in
the hierarchy?\
#text(
teal,
)[Note, this is essentially a pattern, not really a framework -> Redux would be a
framework]
#align(
center,
[#image("../../Screenshots/2023_11_24_05_52_18.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_05_53_22.png", width: 100%)],
)
#subsection("Redux in Angular (ngrx)")
#align(
center,
[#image("../../Screenshots/2023_11_24_05_55_31.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_05_55_46.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_11_24_05_56_03.png", width: 100%)],
)
#columns(2, [
- Benefits
- Enhanced debugging, testability and maintainability
- Undo/redo can be implemented easily
- Reduced code in Angular Components
- Well known data flow (Component → Store → Component)
- Reduces change detection overhead
- Compatible with Redux DevTools
#colbreak()
- Liabilities
- Additional 3rd party library required (ngrx)
- More complex architecture
- Lower cohesion, “Global State” may contain business and UI data
- Data logic may be fragmented into numerous Effects/Reducers
])
#text(
teal,
)[In short, today most applications use some sort of a flux store, angular with
it's object oriented design does not offer a similarly fast and safe to
implement pattern.]
#section("UI Advanced in Angular")
#subsection("Pipes (|)")
- can be applied within templates:\
```html
<p>{{counter.team | uppercase}}</p>
```
- It is also possible to chain pipes:\
```html
<p>{{counter.team | uppercase | lowercase}}</p>
```
- Multiple paramters with:\
```html
<p>{{counter.date | date:'longDate'}}</p>
<!-- results in "February 25, 1970" -->
```
#subsubsection("Pure and Impure")
According to the functional paradigm, pipes can also be pure and unpure:
- pure means no side effects aka everything is immutable
- impure means mutable state
#subsubsubsection("Pure")
- run everytime the input of a pipe changes -> aka it's a closure with an input
that is run each time the input is "new"
- changes of other components are ignored
#subsubsubsection("Impure")
- run on events -> keystroke event, mouse move event, other events
- reduces time that impure pipe is running
- impure pipes can often destroy user experience! -> you do not want continuous
change on UI
#subsubsubsection("Predefined Pipes")
- AsyncPipe
- observable_or_promise_expression | async
- Impure - Unwraps a value from an asynchronous primitive.
- DecimalPipe
- number_expression | number[:digitSInfo[:locale] ]
- Pure - Formats a number according to locale rules.
- CurrencyPipe
- number_expression | currency[:currencyCode [:display [:digitSInfo [:locale] ] ]
]
- Pure - Formats a number as currency using locale rules. Deprecated
- DatePipe
- date_expression | date[:format [:timezone [:locale] ] ]
- Pure - Formats a date according to locale rules. Warning: It uses the
Internationalization API
- PercentPipe
- number_expression | percent[:digitsInfo [:locale] ]
- Pure - Formats a number as a percentage according to locale rules.
#subsubsubsection("Filter and OrderBy Pipes")
- Angular does not provide these
- instead implement filtering and sorting on component
- filter and orderby pipes can perform poorly with massive amount of data
- filter and orderby use "aggressive minification" -> this changes names of
properties to something smaller -> something.count to something.a
- done to improve performance
- results in unexpected behavior -> something.count not found???
#subsubsubsection("Custom Pipes")
- class decorated with \@Pipe directive
- specify name to identify pipe within template
- implement PipeTransform interface
- each paramater passed will become additional argument for pipe
- return transformed value
- add Pipe to current Module
Example: ```ts
// pure pipe or not
// name must be the same in template!
@Pipe({name: 'logo', pure: true})
export class LogoPipe implements PipeTransform {
private logos = { /*...*/ };
transform(value?: string, transformSettings?: string): string {
if (value && transformSettings && this.logos[value]) {
return (this.logos[value][transformSettings] || this.logos[value]['unspec']);
}
return value;
}
}
``` ```html
<!-- Make sure you use the same name as in TS! -->
<img src="{{counter?.team | logo:'toImage'}}">
```
#subsubsection("Async Pipes")
- Observables can be bound to pipes
- changes are automatically tracked
- pipe subscribes and unsubscribes to bound observables
- for change, the pipe must be given new values/references -> *same array results
in no change*
- on change pipe calls *markForCheck()* on the change detector
- bound observable must be bound exactly once!
- *async pipes are impure!*
Example:\
```html
<h1>WE3 - Sample Component</h1>
<section>
<li *ngFor="let s of sampleService.samples$ | async">
<ul>{{s.name}}</ul>
</li>
</section>
```
```ts
@Component({...})
export class CounterComponent {
constructor(
public sampleService:SampleService) {
}
}
```
#subsection("SCSS")
- scss compiled to css
- per component scss
- selectors only available within this component / or in root
- no selector conflicts mean you can have the same name in multiple components!
#subsubsection("Special CSS selectors")
- :host
- target styles in the element that hosts said component
- :host{} -> targets host element
- :host(.active){} -> targets host element when it has active class
- :host-context
- looks for a css class in any ancestor of the component, up to document root
- :host-context(.theme-light) h2 {} applies style to all h2 elements inside the
component, if some ancestor has the theme-light class
#subsubsection("Link Styles to Components")
- Add a styles array property to the \@Component decorator\
```ts
@Component({ /*...*/
styles: ['h1 { font-weight: normal; }']
// don't
})
```
- Add styleUrls attribute into a components \@Component decorator\
```ts
export class WedNavComponent { }
@Component({ /*...*/
styleUrls: ['app/nav.component.css']
// yes
})
```
- Template inline tags/styles\
```ts
export class WedNavComponent { }
@Component({ /*...*/
template: `<style>…</style> … <link rel="stylesheet" href="app/nav.component.css">`
// don't
})
export class WedNavComponent { }
```
#subsubsubsection("Encapsulation")
- styles are encapsulated into the component view
- encapsulation can be controlled on a per component basis ```ts
@Component({
// set your mode here
encapsulation: ViewEncapsulation.Native
})
export class WedNavComponent { }
```
- The following modes exist:
- Native -> Uses the browser's native shadow DOM implementation
- Emulated(default) -> Emulates the behavior of shadow DOM by preprocessing and
renaming the CSS code
- None -> No view encapsulation (no scope rules) are applied. All css are added to
the global style
Example:
#align(
center,
[#image("../../Screenshots/2023_11_24_06_37_08.png", width: 100%)],
)
#section("Ahead-Of-Time Compilation (AOT))")
- meaningless name... -> it's just regular compilation
- Angular uses a compiler to translate components/services into browser executable code
- until angular 8 compiler was delivered to the client
- allows for dynamic JIT compilation
- now aot with webpack
- compiler is about 60% of the angular package
- pre-compiling is possible to reduce size
- enabled by default
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/document_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 21-28 expected datetime, none, or auto, found string
// #set document(date: "today") |
https://github.com/f14-bertolotti/bedlam | https://raw.githubusercontent.com/f14-bertolotti/bedlam/main/src/measure-theory/introduction.typ | typst | #import "../notation/main.typ": inverse, preimage, half-open-rectangle, symmetric-difference
#import "../topology/main.typ": topological-space
#import "../theme.typ": proof, proposition, theorem, definition, example, comment
== Introduction
#let set-algebra = (
tag : link(<set-algebra>)[set algebra]
)
#definition("Set algebra")[
Let $X$ be a set, and $cal(A) subset.eq 2^X$ such that:
1. $X in cal(A)$. #comment[Unit].
2. $A,B in cal(A) ==> A union B in cal(A)$. #comment[Closed under union].
3. $A in cal(A) ==> X without A in cal(A)$. #comment[Closed under complement].
Then $(X,cal(A))$ is called a *set algebra*.
]<set-algebra>
#let set-ring = (
tag : link(<set-ring>)[set ring]
)
#definition("Set ring")[
Let $X$ be a set, and $cal(R) subset.eq 2^X$ such that:
1. $cal(R) != nothing$. #comment[Non-empty].
2. $A,B in cal(R) ==> A sect B in cal(R)$. #comment[Closed under intersection].
3. $A,B in cal(R) ==> A #symmetric-difference.sym B in cal(R)$. #comment[Closed under symmetric difference].
Then $(X, cal(R))$ is called a *set ring*
]<set-ring>
#proposition(text[intersection of #text[#set-ring.tag]s is a #set-ring.tag])[
Let $(X,cal(R_0))$ and $(X,cal(R_1))$ be two #text[#set-ring.tag]s. Then $(X, cal(R_0) sect cal(R_1))$ is a #set-ring.tag.
]<insersection-of-set-ring-is-a-set-ring>
#proof(text[of @insersection-of-set-ring-is-a-set-ring])[
Given two #text[#set-ring.tag]s $(X,cal(R_0))$ and $(X,cal(R_1))$. We need to show that $(X,cal(R) = cal(R_0) sect cal(R_1))$ is a #set-ring.tag:
1. Suppose $A_0 in cal(R_0)$ and $A_1 in cal(R_1)$ #comment[(such $A_0$ and $A_1$ exists since $cal(R_0)$ and $cal(R_1)$ are non-empty)]. Then $nothing in cal(R_0)$ since $nothing = A_0 #symmetric-difference.sym A_1 in cal(R_0)$. Similarly, $nothing in cal(R_1)$. Therefore $nothing in cal(R_0) sect cal(R_1)$
2. Suppose $A,B in cal(R)$. Then $A,B in cal(R_0)$ and $A,B in cal(R_1)$. Then $A sect B in cal(R_0)$ and $cal(R_1)$. Therefore $A sect B in cal(R)$.
3. Suppose $A,B in cal(R)$. Then $A,B in cal(R_0)$ and $A,B in cal(R_1)$. Then $A #symmetric-difference.sym B in cal(R_0)$ and $cal(R_1)$. Therefore $A #symmetric-difference.sym B in cal(R)$.
]
#let sigma-algebra = (
tag : link(<sigma-algebra>)[$sigma$-algebra]
)
#definition(text[$sigma$-algebra])[
Let $X$ be a set. $Sigma subset.eq 2^X$ is said a *sigma algebra of X* iff.:
1. $X in Sigma$
2. $E in Sigma ==> X without E in Sigma$. #comment[close under complement].
3. ${A_n in Sigma}_(n=1)^(oo) ==> union.big_(i=1)^(oo) A_i in Sigma$. #comment[close under infinite unions].
]<sigma-algebra>
#proposition(text[a #sigma-algebra.tag is a #set-ring.tag])[
Let $(X,Sigma)$ be a #sigma-algebra.tag, then $(X,Sigma)$ is a #set-ring.tag
]<sigma-algebra-is-a-set-ring>
#proof(text[of @sigma-algebra-is-a-set-ring])[
We need to show that, given a #sigma-algebra.tag $(X,Sigma)$ the axioms of #text[#set-ring.tag]s hold:
1. $Sigma != nothing$. This is true since $X in Sigma$.
2. $A,B in Sigma ==> A sect B in Sigma$. This is true since $A sect B = (X without A) union (X without B)$ #comment[(a #sigma-algebra.tag is closed under $union$ and $without$)].
3. $A,B in Sigma ==> A #symmetric-difference.sym B in Sigma$. This is true since $A #symmetric-difference.sym B = (A without B) union (B without A)$ #comment[(a #sigma-algebra.tag is closed under $union$ and $without$)].
]
#let generated-sigma-algebra = (
tag : link(<generated-sigma-algebra>)[generated $sigma$-algebra],
sym : (universe,content) => link(<generated-sigma-algebra>)[$sigma_(#universe)(#content)$]
)
#definition(text[generate $sigma$-algebra])[
Let $X$ be a set and $G subset.eq 2^X$. The *$sigma$-algebra generated by $G$*, denoted #(generated-sigma-algebra.sym)("X","G"), is the smallest #link(<sigma-algebra>)[$sigma$-algebra] such that:
1. $G subset.eq #(generated-sigma-algebra.sym)("X","G")$.
2. $forall Sigma " "#text[#sigma-algebra.tag]: G subset.eq Sigma ==> sigma_(X)(G) subset.eq Sigma$. #comment[Every other #sigma-algebra.tag that contains $G$ contains also the generated one, #(generated-sigma-algebra.sym)("X","G")].
]<generated-sigma-algebra>
#let borel-sigma-algebra = (
tag : link(<borel-sigma-algebra>)[Borel sigma algebra],
sym : (universe, topology) => link(<borel-sigma-algebra>)[$cal(B)(#universe, #topology)$]
)
#definition(text[borel $sigma$-algebra])[
Let $(X,G)$ be a #topological-space.tag. We refer to $#(generated-sigma-algebra.sym)("X","G")=#(borel-sigma-algebra.sym)("X","G")$ as a *Borel $sigma$-algebra*.
]<borel-sigma-algebra>
#let sigma-algebra-product = (
tag : link(<sigma-algebra-product>)[$sigma$-algebra product],
sym : link(<sigma-algebra-product>)[#sym.times.circle]
)
#definition(text[$sigma$-algebra product])[
Let $Sigma_1$ and $Sigma_2$ be #sigma-algebra.tag on $X_1$ and $X_2$ respectively. The *product $sigma$-algebra* denoted $Sigma_1 #sigma-algebra-product.sym Sigma_2$ is defined as #(generated-sigma-algebra.sym)($X_1 times X_2$,${S_1 times S_2 | S_1 in Sigma_1, S_2 in Sigma_2}$)
]<sigma-algebra-product>
#let measurable-space = (
tag : link(<measurable-space>)[measurable space]
)
#definition("measurable space")[
$(X,Sigma)$ is said *measurable* iff. #sym.Sigma is a #sigma-algebra.tag of $X$.
]<measurable-space>
#let measure = (
tag : link(<measure>)[measure],
ax1 : measure => text[$#measure (nothing) = 0$],
ax2 : measure => text[$E in Sigma ==> #measure (E)>=0$],
ax3 : measure => text[${E_n in Sigma}_(n in NN) " pairwise disjoint " ==> #measure (union_(n in NN) E_b) = sum_(n in NN) #measure (E_n)$]
)
#definition("measure")[
Given $(X,Sigma)$ #measurable-space.tag. $mu:Sigma --> RR union {+oo,-oo}$ is said a *measure* iff.
1. $mu(nothing)=0$ #comment[Empty set].
2. $E in Sigma ==> mu(E)>=0$. #comment[Positiveness].
3. ${E_n in Sigma}_(n in NN) " pairwise disjoint " ==> mu(union_(n in NN) E_b) = sum_(n in NN) mu(E_n)$. #comment[Countable additivity].
]<measure>
#let measure-space = (
tag : link(<measure-space>)[measure space]
)
#definition("measure space")[
$(X,Sigma,mu)$ is said a *measure space* iff. $(X,Sigma)$ is a #sigma-algebra.tag and #sym.mu is a #measure.tag of $(X,Sigma)$.
]<measure-space>
#let measurable-function = (
tag : link(<measurable-function>)[measurable function]
)
#definition("measurable function")[
Let $(X_1, Sigma_1)$ and $(X_2, Sigma_2)$ be #text[#measurable-space.tag]s. $f:X_1 --> X_2$ is said a *measurable function* iff. $forall E in Sigma_2: #(inverse.sym)("f") (E) in Sigma_1$. #comment[The #preimage.tag of each measurable set is again measurable].
]<measurable-function>
#let pushforward = (
tag : link(<pushforward>)[pushforward],
sym : (fname,measure) => link(<pushforward>)[$#(fname)_(hash) #measure$]
)
#definition("pushforward")[
Let $(X_1,Sigma_1,mu)$ be a #measure-space.tag. Let $(X_2,Sigma_2)$ be a #measurable-space.tag. Let $f:X_1 --> X_2$ be a #measurable-function.tag. The *pushforwad of $mu$ under $f$* is the mapping $#(pushforward.sym)("f",sym.mu): Sigma_2 --> RR_(>=0) union {oo}$ defined as: $ forall E in Sigma_2 : #(pushforward.sym)("f", sym.mu) = mu(#(inverse.sym)("f") (E)) $
]<pushforward>
The pushforward is simply a function that generates a measure for a measurable space starting from a different measure space and a measurable function acting as bridge between the two spaces.
#proposition("pushforward of a measure is a measure")[
Let $(X_1,Sigma_1,mu)$ be a #measure-space.tag. Let $(X_2,Sigma_2)$ be a #measurable-space.tag. Let $f:X_1 --> X_2$ be a #measurable-function.tag. Then $(X_2,Sigma_2,#(pushforward.sym)("f",sym.mu))$ is a #measure-space.tag.
]<pushforward-of-a-measure-is-a-measure>
#proof(text[of @pushforward-of-a-measure-is-a-measure])[
To prove that statement, we need to prove only the axioms of a #measure.tag.
1. Let $E in Sigma_2$, we need to show that $f_(\#)mu(E) >= 0$. This is trivial by definition of #pushforward.tag and #measure.tag.
2. Let $[E_n in Sigma_2]_(n=1)^(oo)$ be a sequence of pairwise disjoint sets. We need to show that: $#(pushforward.sym)("f",sym.mu) (union.big_(n=1)^(oo)E_n)=sum_(n=1)^(oo) #(pushforward.sym)("f",sym.mu) (E_n)$.
$ #(pushforward.sym)("f",sym.mu) (union.big_(n=1)^(oo)E_n) &= mu(#(inverse.sym)("f") (union.big_(n=1)^(oo) E_n)) #comment[definition of #pushforward.tag] \
&= mu(union.big_(n=1)^(oo) #(inverse.sym)("f") (E_n)) \
&= sum_(n=1)^(oo) mu(#(inverse.sym)("f") (E_n)) #comment[definition of #measure.tag] \
&= sum_(n=1)^(oo) #(pushforward.sym)("f",sym.mu) (E_n) #comment[definition of #pushforward.tag]
$
3. We need to show that $exists E in Sigma_1$ such that $#(pushforward.sym)("f",sym.mu) (E) >= 0$. Let $E' in Sigma_1$ such that $mu(E') >= 0$ (such $E'$ exists by defintion of measure). Then, $f(E')$ is a set that meets the requirements, that is
$ #(pushforward.sym)("f",sym.mu) (f(E')) = mu(#(inverse.sym)("f") (f(E'))) = mu(E') >= 0 $
]
#example("pushforward example")[
Consider the #measure-space.tag $(NN,2^NN,mu(E)=|E|)$. Consider the #measurable-space.tag $(RR, #(generated-sigma-algebra.sym)(sym.RR,(half-open-rectangle.sym)("n")))$. Consider the #measurable-function.tag $f:NN --> RR$ such that f(x) = x. Consider #pushforward.tag $#(pushforward.sym)("f",sym.mu):RR --> RR_(>=0) union {oo}$. Then $#(pushforward.sym)("f",sym.mu)$ is a #measure.tag for the #measurable-space.tag $(RR, #(generated-sigma-algebra.sym)(sym.RR,(half-open-rectangle.sym)("n")))$ since:
1. $#(pushforward.sym)("f",sym.mu) (E in #(generated-sigma-algebra.sym)(sym.RR,(half-open-rectangle.sym)("n"))) = |{n in NN | n in E}| >= 0$.
2. Let ${E_n}_(n=1)^(oo)$ pairwise disjoint, then $#(pushforward.sym)("f",sym.mu) (union.big_(n=1)^(oo) E_n) = mu(#(inverse.sym)("f") (union.big_(n=1)^(oo) E_n)) = mu(union.big_(n=1)^(oo) #(inverse.sym)("f") (E_n)) = sum_(n=1)^(oo) mu(#(inverse.sym)("f") (E_n)) = sum_(n=1)^(oo) #(pushforward.sym)("f",sym.mu) (E_n)$.
3. $#(pushforward.sym)("f",sym.mu) (nothing) = mu(#(inverse.sym)("f") (nothing)) = mu(nothing) = 0$
]
#let pre-measure = (
tag : link(<pre-measure>)[pre-measure]
)
#definition("pre-measure")[
Let $(X, Sigma)$ be a #set-algebra.tag. Let $mu:S --> R_(>=0) union {+oo}$. $mu$ is said a *pre-measure* iff.
1. $mu(nothing) = 0$. #comment[Empty set].
2. Given a collection of pairwise disjoint sets ${A_n in S}_(n in NN)$ such that $union.big_(n in NN) A_n in S ==> mu(union.big_(n in NN) A_n) = sum_(n in NN) mu(A_n)$. #comment[Countable additivity].
3. $forall A in S: mu(A) >= 0$. #comment[Positiveness].
]<pre-measure>
A #pre-measure.tag is a precursor of a full-fledge #measure.tag. The main difference is that a #measure.tag is defined on #text[#sigma-algebra.tag]s, meanwhile the #pre-measure.tag is defined on a simple collection of subsets. Further, given that this collection is not necessarily closed under unions as a #sigma-algebra.tag does, we also need to check that, in the second requirement, the union of $A_n$ is indeed contained in the collection.
#let outer-measure = (
tag : link(<outer-measure>)[outer measure],
ax1 : measure => text[$#measure (nothing) = 0$],
ax2 : measure => text[$forall A,B: A subset.eq B ==> #measure (A) <= #measure (B)$],
ax3 : measure => text[$forall {A_n}_(n in NN): #measure (union.big_(n in NN) A_n) <= sum_(n in NN) #measure (A_n)$]
)
#definition("Outer measure")[
Let $X$ be a set. An *outer measure* $mu: 2^X --> RR_(>=0) union {oo}$ such that:
1. #(outer-measure.ax1)($mu$). #comment[empty set].
2. #(outer-measure.ax2)($mu$). #comment[Monotonicity].
3. #(outer-measure.ax3)($mu$). #comment[Countable subadditivity].
]<outer-measure>
An #text[#outer-measure.tag]s are weaker wrt. #text[#measure.tag]s as they are only countably subadditive rather than countably additive. However, they are able to measure all subset of $X$ rather than only a #text[#sigma-algebra.tag]s.
|
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/复变函数/作业/hw2.typ | typst | #import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark, proposition,der, partialDer, Spec
#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: note.with(
title: "作业2",
author: "YHTQ",
date: none,
logo: none,
withOutlined : false,
withTitle :false,
)
(应交时间为3月15日)
= p24 Ex. 6
设集合 $S$ 完全有界,也即任取 $epsilon > 0$存在有限个 $x_i$,满足:
$
S subset union.big_i B(x_i, 1/2 epsilon)
$
两侧取闭包,立得:
$
overline(S) subset union.big_i overline(B(x_i, 1/2 epsilon)) subset union.big_i B(x_i, epsilon)
$
由 $epsilon$ 的任意性命题得证
= p28
== Ex. 4
设 $f, g$ Lipschitz 连续,也即满足:
$
d(f(x), f(y)) <= M_1 d(x, y), forall x, y \
d(g(x), g(y)) <= M_2 d(x, y), forall x, y \
$
则任取 $x, y$,将有:
$
d(g(f(x)), g(f(y))) <= M_2 d(f(x), f(y)) <= M_1 M_2 d(x, y)
$
表明 $g(f(x))$ Lipschitz 连续
设 $f, g$ 一致连续,对任意 $epsilon >0, exists delta_2 > 0$ 使得:
$
d(g(x), g(y)) <= epsilon, forall x, y, d(x, y) < delta_2\
$
再对 $delta_2$ 利用 $f$ 的一致连续性,存在 $delta_1 > 0$ 使得:
$
d(f(x), f(y)) <= delta_2, forall x, y, d(x, y) < delta_1\
$
两式结合便有:
$
d(g(f(x)), g(f(y))) <= epsilon, forall x, y, d(x, y) < delta_1
$
得证 $g(f(x))$ 一致连续
== Ex. 8
任取 $epsilon > 0$,对每个 $x in X$,由连续性可以找到一个开邻域 $U_x$ 使得:
$
diam(f(U_x)) <= epsilon
$
$E := {U_x}_(x in X)$ 构成 $X$ 的开覆盖,由 Lebesgue's Covering Lemma(注意到度量空间中紧致等价于列紧),存在 $delta > 0$ 使得:
$
forall x in X, exists e in E: B(x, delta) in e
$
由 $E$ 的构造,这表明:
$
forall x in X, exists e in E: diam(B(x, delta)) < epsilon
$
显然将有:
$
d(f(x), f(y)) <= epsilon, forall x, y, d(x, y) < delta
$
得证
= p29 Ex. 1
任取 $epsilon > 0$,由一致收敛性,存在 $ n in NN$ 使得:
$
d(f(x), f_n (x)) < 1/3 epsilon, forall x in X
$
注意到 $f_n (x)$ 一致连续,因此存在 $delta > 0$ 使得:
$
d(f_n (x), f_n (y)) < 1/3 epsilon, forall x, y, d(x, y) < delta
$
从而:
$
forall x, y, d(x, y) < delta:\
d(f(x), f(y)) <= d(f(x), f_n (x)) + d(f_n (x), f_n (y)) + d(f_n (y), f(y)) \
< 1/3 epsilon + 1/3 epsilon + 1/3 epsilon = epsilon
$
得证 $f$ 一致连续
对于第二个结论,记 $sup{f(x) - g(x) | x in X} := norm(f - g)$\
$forall n in NN^+$, 注意到 $f_n (x)$ Lipschitz 连续,因此:
$
d(f_n (x), f_n (y)) < M_n d(x, y), forall x, y
$
从而:
$
forall x, y:\
d(f(x), f(y)) <= d(f(x), f_n (x)) + d(f_n (x), f_n (y)) + d(f_n (y), f(y)) \
< M_n d(x, y) + 2 norm(f_n - f)
$
注意到上式左侧与 $n$ 无关,因此有:
$
d(f(x), f(y)) <= limsup_(n -> +infinity ) (M_n d(x, y) + 2 norm(f_n - f)) = (limsup_(n -> +infinity ) M_n) d(x, y)
$
由条件 $0< limsup_(n -> +infinity ) M_n < +infinity$ 知结论成立
考虑 $f_n (x) = sqrt(x + 1/n), x in [0, 1], f(x) = sqrt(x)$,有:
$
norm(f(x) - f_n (x)) = norm(sqrt(x+ 1/n) - sqrt(x)) = 1/n 1/norm(sqrt(x+ 1/n) + sqrt(x)) <= 1/n sqrt(n) = 1/sqrt(n) -> 0
$
因此 $f_n (x)$ 一致收敛于 $f(x)$\
此外,计算得:
$
f'_n (x) = 1/(2 sqrt(x + 1/n)) <= 1/2 sqrt(n)
$
因此每个 $f_n (x)$ 都是 Lipschitz 连续的,但 :
$
f'(x) = 1/(2 sqrt(x)) -> + infinity (x -> 0)
$
因此不是 Lipschitz 连续的
= p44 Ex. 14
首先断言 $forall z in G, f'(z) = 0$,事实上,在:
$
f'(z) = lim_(h -> 0) (f(a+h) - f(a))/h
$
中:
- 取 $h = Delta in RR$,显然上式右侧总是实数,继而 $"Im"(f'(z)) = 0$
- 取 $h = Delta i, Delta in RR$,显然上式右侧实部总为零,继而 $"Re"(f'(z)) = 0$
表明 $f'(z) = 0$\
利用书上命题2.10 可得 $f$ 是常函数 |
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/type_check/sig_template.typ | typst | Apache License 2.0 | #let tmpl(content) = content |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.