repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/floriandejonckheere/utu-thesis
https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/chapters/07-proposed-solution/03-requirements.typ
typst
#import "/helpers.typ": * == Requirements Our approach needs to fulfill certain requirements. We make a distinction between functional and non-functional requirements. In software engineering, functional requirements describe requirements that impact the design of the application in a functional way @software_engineering_body_of_knowledge_2001. Non-functional requirements are additional requirements imposed at design-time that do not directly impact the functionality of the application @software_engineering_body_of_knowledge_2001. The functional requirements we prioritized for our proposed solution are: - *Quality*: the solution provides a high-quality decomposition of the monolith application, based on a set of quality metrics - *Automation*: the solution automates the decomposition process as much as possible - *Visual*: the solution can output the proposed decomposition in a visual manner, to aid understanding of the process and the results The non-functional requirements identified for our solution are: - *Performance*: the solution performs the analysis, decomposition, and evaluation reasonably fast
https://github.com/sitandr/typst-examples-book
https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/typstonomicon/try_catch.md
markdown
MIT License
# Try & Catch ```typ // author: laurmaedje // Renders an image or a placeholder if it doesn't exist. // Don’t try this at home, kids! #let maybe-image(path, ..args) = context { let path-label = label(path) let first-time = query((context {}).func()).len() == 0 if first-time or query(path-label).len() > 0 { [#image(path, ..args)#path-label] } else { rect(width: 50%, height: 5em, fill: luma(235), stroke: 1pt)[ #set align(center + horizon) Could not find #raw(path) ] } } #maybe-image("../tiger.jpg") #maybe-image("../tiger1.jpg") ```
https://github.com/eusebe/sorbonne-slides-typst
https://raw.githubusercontent.com/eusebe/sorbonne-slides-typst/main/README.md
markdown
# sorbonne-slides-typst A typst slide template for Sorbonne University based on polylux
https://github.com/ShapeLayer/ucpc-solutions__typst
https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/docs/utils.md
markdown
Other
--- title: ucpc.utils supports: ["0.1.0"] --- ```typst #import "/lib/ucpc.typ": utils utils. ``` This is a utility prepared to quickly create various formats. Using this utility, you can create cover words and descriptions. ## make-hero ```typst make-hero( title: str | content, subtitle?: str | content, fgcolor?: color, bgcolor?: color, height?: relative, authors?: array<str>, datetime?: str | content, ) ``` Generates hero cover page. ## make-prob-meta ```typst make-prob-meta( tags?: array<str>, difficulty?: str | content, authors?: array<str> | content, stat-open?: ( submit-count: int, ac-count: int, ac-ratio: float, first-solver: str | content, first-solve-time: int, ), stat-onsite?: ( submit-count: int, ac-count: int, ac-ratio: float, first-solver: str | content, first-solve-time: int, ), i18n?: i18n-dictionary.make-prob-meta ) ``` ## make-prob-overview ```typst make-prob-overview( font-size?: length, i18n?: i18n-directory.make-prob-overview, ..items, ) ``` ## make-problem ```typst make-problem( id: str, title: str, tags?: array<str>, difficulty?: str | content, authors?: array<str> | content, stat-open?: ( submit-count: int, ac-count: int, ac-ratio: float, first-solver: str | content, first-solve-time: int, ), stat-onsite?: ( submit-count: int, ac-count: int, ac-ratio: float, first-solver: str | content, first-solve-time: int, ), pallete?: ( primary: color, secondary: color, ), i18n: i18n-dictionary.make-prob-meta, body ) ```
https://github.com/typst-jp/typst-jp.github.io
https://raw.githubusercontent.com/typst-jp/typst-jp.github.io/main/docs/tutorial/1-writing.md
markdown
Apache License 2.0
--- description: Typstのチュヌトリアルです。 --- # Typstで執筆するには さあ始めたしょうあなたが倧孊で専門的なレポヌトを曞くこずになったずしたしょう。そこには文章、数匏、芋出し、図が含たれおいたす。 曞き始めるには、たずTypst appで新しいプロゞェクトを䜜成したす。゚ディタヌに移動するず、2぀のパネルが衚瀺されたす。 1぀は文曞を䜜成する゜ヌスパネル、もう1぀はレンダリングされた文曞が衚瀺されるプレビュヌパネルです。 ![Typst app screenshot](1-writing-app.png) レポヌトの良い切り口はすでに考えおあるので、たずは導入を曞いおみたしょう。 ゚ディタヌパネルにいく぀かのテキストを入力しおください。テキストがすぐにプレビュヌペヌゞに衚瀺されるのがわかるでしょう。 ```example In this report, we will explore the various factors that influence fluid dynamics in glaciers and how they contribute to the formation and behaviour of these natural structures. ``` _このチュヌトリアル党䜓を通しお、このようなコヌド䟋を玹介したす。アプリず同様に、最初のパネルにはマヌクアップが含たれ、2番目のパネルにはプレビュヌが衚瀺されたす。䜕が起こっおいるかわかりやすいように䟋に合わせおペヌゞを瞮小しおいたす。_ 次のステップは、芋出しを远加しお、いく぀かのテキストを匷調するこずです。 Typstでは、頻繁に䜿う曞匏をシンプルなマヌクアップで衚珟するようになっおいたす。芋出しを远加するには `=` の文字を入力したす。テキストを斜䜓で匷調するには、テキストを `[_アンダヌスコア_]` で囲みたす。 ```example = Introduction In this report, we will explore the various factors that influence _fluid dynamics_ in glaciers and how they contribute to the formation and behaviour of these natural structures. ``` 簡単でしたね新しい段萜を远加するには、2行のテキストの間に空行を远加するだけです。 その段萜に小芋出しが必芁な堎合は、`=` の代わりに `==` を入力しお䜜成したす。 `=` の数が芋出しのネストレベルを決定したす。 次に、氷河の動態に圱響を䞎える芁因をいく぀か列挙しおみたしょう。 そのために、ここでは番号付きリストを䜿いたしょう。リストの各項目に぀いお、行の先頭に `+` 文字を入力したす。 するず、Typstが自動的に項目を番号付けしおくれるのです。 ```example + The climate + The topography + The geology ``` 箇条曞きリストを远加したい堎合は、`+` 文字の代わりに `-` 文字を䜿甚したす。 たた、リストをネストするこずもできたす。 䟋えば、䞊蚘のリストの最初の項目にサブリストを远加するには、それをむンデントしたす。 ```example + The climate - Temperature - Precipitation + The topography + The geology ``` ## 図衚を远加する {#figure} あなたは「レポヌトに図衚を入れるずもっず良くなる」ず考えおいるずしたす。やりたしょう。 Typstでは、PNG、JPEG、GIF、SVGの圢匏の画像をサポヌトしおいたす。 プロゞェクトに画像ファむルを远加するには、たず巊サむドバヌのボックスアむコンをクリックしお _ファむルパネル_ を開きたす。 ここにはプロゞェクト内のすべおのファむルのリストが衚瀺されたす。 珟圚、ここにあるのはあなたが曞いおいるメむンのTypstファむルだけです。 別のファむルをアップロヌドするには、右䞊隅の矢印のボタンをクリックしたす。 これによりアップロヌドダむアログが開き、コンピュヌタからアップロヌドするファむルを遞択できたす。 レポヌトに甚いる画像ファむルを遞んでください。 ![Upload dialog](1-writing-upload.png) 以前にも芋おきたように、Typstでは特定の蚘号 _マヌクアップ_ ず呌ばれるが特有の意味を持ちたす。 `=`、`-`、`+`、`_` をそれぞれ芋出し、リスト、匷調テキストを䜜成するために䜿甚するこずができたす。 しかし、文曞に挿入したいもの党おに特別な蚘号を割り圓おるず、すぐに分かりづらく、そしお扱いづらくなっおしたいたす。 そのため、Typstでは䞀般的な曞匏にのみマヌクアップ蚘号を甚意し、それ以倖は党お _関数_ を䜿っお挿入したす。 ペヌゞに画像を衚瀺させるためには、Typstの [`image`] 関数を䜿甚したす。 ```example #image("glacier.jpg") ``` 䞀般的に、関数は䞀連の _匕数_ に察しお䜕らかの出力を生成したす。 マヌクアップ内で関数を _呌び出す_ 時は、あなたが関数の匕数を指定するず、Typstがその結果関数の _戻り倀_ を文曞に挿入しおくれたす。 今回の堎合、`image` 関数は䞀぀の匕数ずしお画像ファむルぞのパスを受け取りたす。 マヌクアップで関数を呌び出すには、たず `#` 文字を入力し、盎埌に関数の名前を蚘述したす。 その埌、匕数を䞞括匧で囲みたす。 Typstは匕数リスト内でさたざたなデヌタ型を認識したす。 私たちの画像のファむルパスは短い [文字列]($str) ですので、二重匕甚笊で囲む必芁がありたす。 挿入された画像はペヌゞ党䜓の幅を䜿いたす。これを倉曎するには、`image` 関数に `width `匕数を枡したす。 これは _名前付き_ 匕数であり、`匕数の名前: 匕数の倀` ずいう圢匏で指定されたす。 耇数の匕数がある堎合はカンマで区切りたす。そのため、ここでは先ほど指定したファむルパスの埌ろにカンマを付ける必芁がありたす。 ```example #image("glacier.jpg", width: 70%) ``` `width` 匕数は [盞察的な長さ]($relative) です。 䞊の䟋では、画像がペヌゞの幅の `{70%}` を占めるようにパヌセンテヌゞを指定しおいたす。 たた、`{1cm}` や `{0.7in}` のような絶察倀を指定するこずもできたす。 テキストず同様に、画像もデフォルトではペヌゞの巊偎に配眮されたす。さらに、図衚の説明キャプションも欠けおいたす。 これらを修正するために、[figure]($figure) 関数を䜿甚したしょう。 この関数には、名前付きでない通垞の匕数䜍眮匕数ずしお、図衚を指定する必芁がありたす。さらにオプションずしお、図衚に付ける説明文`caption`を名前付き匕数で指定できたす。 `figure` 関数の匕数リスト内では、Typstは既にコヌドモヌドになっおいたす。 これは、 `image` 関数の呌び出し前にある `#` 蚘号を削陀する必芁があるこずを意味したす。 `#` 蚘号は、マヌクアップ内でテキストず関数呌び出しを区別するために曞くものなのです。 キャプションの䞭には、任意のマヌクアップを含めるこずが出来たす。 ある関数の匕数ずしおマヌクアップを指定するためには、それを角括匧 `[ ]` で囲みたす。この「マヌクアップが角括匧で囲たれおいる構造」のこずを、_コンテンツブロック_ ず呌ばれたす ```example #figure( image("glacier.jpg", width: 70%), caption: [ _Glaciers_ form an important part of the earth's climate system. ], ) ``` あなたはレポヌトの執筆を続けるうちに、今床は先ほど挿入した図を文䞭から参照したくなったずしたす。 その堎合、たず図にラベルを付けたす。 ラベルずは、文曞内の芁玠を䞀意に識別するための名前のこずです。先ほど挿入した図の埌ろに、その図のラベルを山括匧 `< >` で囲んで曞き加えたす。 これで、テキスト内で `[@]` 蚘号を曞いた埌ろにラベル名を指定するず、その図を参照できるようになりたした。 芋出しや方皋匏もラベルを付けお参照可胜にするこずができたす。 ```example Glaciers as the one shown in @glaciers will cease to exist if we don't take action soon! #figure( image("glacier.jpg", width: 70%), caption: [ _Glaciers_ form an important part of the earth's climate system. ], ) <glaciers> ``` <div class="info-box"> これたでに、コンテンツブロック角括匧 `[ ]` 内のマヌクアップず文字列二重匕甚笊 `" "` 内のテキストを関数に枡しおきたした。 どちらもテキストを含んでいるように芋えたすが、違いは䜕でしょうか コンテンツブロックはテキストを含むこずができたすが、それ以倖にもさたざたなマヌクアップ、関数呌び出しなどを含むこずができたす。 䞀方、文字列は本圓に _文字の䞊び_ に過ぎたせん。 䟋えば、image 関数は、匕数ずしお画像ファむルぞのパスが枡されるこずを想定しおいたす。ここに文章の段萜や他の画像を枡しおも意味がありたせん。 image関数の匕数ずしおマヌクアップがダメで文字列が蚱可されるのは、そういうわけなのです。 それずは反察に、文字列はコンテンツブロックが期埅される堎所であればどこにでも曞くこずが出来たす。なぜなら、文字列は単なる文字の䞊びであり、文字の䞊びは有効なコンテンツの䞀皮だからです。 </div> ## 参考文献の远加 {#bibliography} レポヌトを䜜成する際には、その䞻匵を裏付ける必芁がありたすよね。 参考文献を文曞に远加するには、[`bibliography`]($bibliography) 関数を䜿甚できたす。 この関数は、匕数ずしお参考文献ファむルぞのパスが枡されるこずを想定しおいたす。 Typstでは、ネむティブな参考文献の圢匏ずしお[Hayagriva](https://github.com/typst/hayagriva/blob/main/docs/file-format.md)を䜿甚しおいたすが、 互換性のためにBibLaTeXファむルも䜿甚できたす。 クラスメヌトが既に文献調査を行い、`.bib` ファむルを送っおくれたので、それを䜿甚したしょう。 ファむルパネルを通じおファむルをアップロヌドし、Typst appでアクセスできるようにしたす。 文曞に参考文献が远加されおいる堎合、参考文献欄にある文献を文䞭で匕甚するこずができたす。 匕甚はラベルぞの参照ず同じ構文を䜿甚したす。デフォルトでは、文䞭に文献の匕甚を蚘述した時点で初めお、その文献がTypstの参考文献セクションに衚瀺されるようになっおいたす。 Typstはさたざたな匕甚および参考文献のスタむルをサポヌトしおいたす。詳现に぀いおは [リファレンス]($bibliography.style)を参照しおください。 ```example = Methods We follow the glacier melting models established in @glacier-melt. #bibliography("works.bib") ``` ## 数匏 {#maths} 方法に関する節を肉付けした埌、文曞の䞻芁な郚分である方皋匏に進みたす。 Typstには組み蟌みの数孊蚘法があり、独自の数孊衚蚘を䜿甚したす。 簡単な方皋匏から始めたしょう。Typstに数孊的な衚珟を期埅するこずを知らせるために、`[$]` 蚘号で囲みたす。 ```example The equation $Q = rho A v + C$ defines the glacial flow rate. ``` 方皋匏はむンラむンで衚瀺され、呚囲のテキストず同じ行に配眮されたす。 それを独立した行にしたい堎合は、方皋匏の最初ず最埌にそれぞれ1぀ず぀スペヌスを挿入する必芁がありたす。 ```example The flow rate of a glacier is defined by the following equation: $ Q = rho A v + C $ ``` Typstでは、単䞀の文字 `Q`, `A`, `v`, `C` はそのたた衚瀺され、䞀方で `rho` はギリシャ文字に倉換されおいるのがわかりたす。 数匏モヌドでは、単䞀の文字は垞にそのたた衚瀺されたす。しかし、耇数個が連なっおいる文字は蚘号、倉数、たたは関数名ずしお扱われたす。 異なる皮類の文字どうしの乗算を乗算蚘号を省略しお瀺すためには、文字ず文字の間にスペヌスを挿入しおください。 耇数の文字からなる倉数を衚したい堎合は、倉数の名前を匕甚笊で囲みたす。 ```example The flow rate of a glacier is given by the following equation: $ Q = rho A v + "time offset" $ ``` レポヌトには総和の匏も必芁です。 `sum` 蚘号を䜿甚しお、総和の範囲を䞋付き文字ず䞊付き文字で指定するこずができたす。 ```example Total displaced soil by glacial flow: $ 7.32 beta + sum_(i=0)^nabla Q_i / 2 $ ``` シンボルや倉数に䞋付き文字を远加するには、`_` の文字を入力しおから䞋付き文字を入力したす。 同様に、䞊付き文字を远加するには `^` の文字を䜿甚したす。 もし䞋付き文字や䞊付き文字が耇数の芁玠からなる堎合は、それらを䞞括匧で囲む必芁がありたす。 䞊蚘の䟋から分数の挿入方法もわかるず思いたす。 分子ず分母の間に `/` の文字を眮くだけで、Typstは自動的にそれを分数に倉換したす。 Typstでは、䞞括匧のネストをスマヌトに解決するようになっおいたす。プログラミング蚀語や関数電卓のように、䞞括匧を入れ子にした匏を入力するず、 Typstは䞞括匧で囲たれた郚分匏を適切に解釈しお自動的に眮き換えたす。 ```example Total displaced soil by glacial flow: $ 7.32 beta + sum_(i=0)^nabla (Q_i (a_i - epsilon)) / 2 $ ``` 数孊のすべおの抂念に特別な構文があるわけではありたせん。 代わりに、先皋の `image` 関数のように関数を䜿甚したす。 䟋えば、列ベクトルを挿入するには、`vec` 関数を䜿甚できたす。 数匏モヌド内では、関数呌び出しは `#` で始める必芁はありたせん。 ```example $ v := vec(x_1, x_2, x_3) $ ``` 数匏モヌド内でのみ䜿甚可胜な関数もありたす。 䟋えば、[`cal`]($math.cal) 関数は集合などに䞀般的に䜿甚されるカリグラフィ文字を衚瀺するために䜿われたす。 数匏モヌドが提䟛するすべおの関数の完党なリストに぀いおは、[リファレンスの数匏セクション]($category/math)を参照しおください。 もう䞀぀、矢印などの倚くの蚘号には倚くのバリ゚ヌションがありたす。 こうした様々なバリ゚ヌションの䞭から特定の蚘号を遞択するには、その蚘号のカテゎリ名の埌に、ドットず具䜓的な蚘号の皮類を瀺す修食子を远加したす。 ```example $ a arrow.squiggly b $ ``` この衚蚘法はマヌクアップモヌドでも利甚可胜ですが、そこでは蚘号名の前に `#sym.` を付ける必芁がありたす。 利甚可胜なすべおの蚘号に぀いおは[蚘号セクション]($category/symbols/sym)を参照しおください。 ## たずめ {#review} あなたはTypstで基本的な文曞を曞く方法を孊びたした。テキストの匷調やリストの曞き方、画像の挿入、コンテンツの配眮、Typstにおける数孊的な匏の組版などを孊びたした。たた、Typstの関数に぀いおも孊びたした。 Typstでは文曞に挿入できるさたざたなコンテンツがありたす。たずえば、[衚]($table)や[図圢]($category/visualize)、[コヌドブロック]($raw)などです。さらにこれらや他の機胜に぀いお詳しく孊ぶには[リファレンス]($reference)を参照しおください。 ここたでで、レポヌトの執筆は完了したした。 あなたは右䞊のダりンロヌドボタンをクリックしおPDFを保存したはずです。 しかし、あなたはレポヌトがあたりにも玠朎に芋えるず感じるかもしれたせん。 次のセクションでは、文曞の倖芳をカスタマむズする方法を孊びたす。
https://github.com/omroali/SegmentationsFeaturingAndTracking
https://raw.githubusercontent.com/omroali/SegmentationsFeaturingAndTracking/main/Report/code.typ
typst
#import "@preview/problemst:0.1.0": pset #show: pset.with( class: "Computer Vision", student: "<NAME> - 28587497", title: "Assignment 1", date: datetime.today(), ) == image_segmentation.py ```python import os import cv2 from cv2.typing import MatLike import numpy as np from segmentation.utils import fill import math class ImageSegmentation: def __init__(self, image_path: str, save_dir: str = None): self.processing_data = [] self.image_path = image_path self.image = cv2.imread(image_path) self.processing_images = [] self.save_dir = save_dir def log_image_processing(self, image, operation: str): """log the image processing""" self.processing_data.append(operation) self.processing_images.append(image) def gblur(self, image, ksize=(3, 3), iterations=1): """apply gaussian blur to the image""" blur = image.copy() for _ in range(iterations): blur = cv2.GaussianBlur(blur, ksize, cv2.BORDER_DEFAULT) self.log_image_processing(blur, f"gblur,kernel:{ksize},iterations:{iterations}") return blur def mblur(self, image, ksize=3, iterations=1): """apply gaussian blur to the image""" blur = image.copy() for _ in range(iterations): blur = cv2.medianBlur(blur, ksize) self.log_image_processing( blur, f"medianblur,kernel:{ksize},iterations:{iterations}" ) return blur def adaptive_threshold(self, image, blockSize=15, C=3): """apply adaptive threshold to the image""" image = image.copy() adaptive_gaussian_threshold = cv2.adaptiveThreshold( src=image, maxValue=255, adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C, thresholdType=cv2.THRESH_BINARY, blockSize=blockSize, ``` ```python C=C, ) self.log_image_processing( adaptive_gaussian_threshold, f"adaptive_threshold,blockSize:{blockSize},C:{C}", ) return adaptive_gaussian_threshold def dilate(self, image, kernel=(3, 3), iterations=1, op=cv2.MORPH_ELLIPSE): """apply dilation to the image""" image = image.copy() kernel = cv2.getStructuringElement(op, kernel) dilation = cv2.dilate( src=image, kernel=kernel, iterations=iterations, ) self.log_image_processing( dilation, f"erode,kernel:{kernel},iterations:{iterations}", ) return dilation def erode(self, image, kernel=(3, 3), iterations=1, op=cv2.MORPH_ELLIPSE): """apply dilation to the image""" image = image.copy() kernel = cv2.getStructuringElement(op, kernel) dilation = cv2.erode( src=image, kernel=kernel, iterations=iterations, ) self.log_image_processing( dilation, f"dilate,kernel:{kernel},iterations:{iterations}", ) return dilation def closing(self, image, kernel=(5, 5), iterations=10): """apply closing to the image""" image = image.copy() kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, kernel) closing = cv2.morphologyEx( src=image, op=cv2.MORPH_CLOSE, kernel=kernel, iterations=iterations, ) self.log_image_processing( closing, f"closing,kernel:{kernel},iterations:{iterations}", ) return closing ``` ```python def opening(self, image, kernel=(5, 5), iterations=1, op=cv2.MORPH_ELLIPSE): """apply opening to the image""" image = image.copy() kernel = cv2.getStructuringElement(op, kernel) opening = cv2.morphologyEx( src=image, op=cv2.MORPH_OPEN, kernel=kernel, iterations=iterations, ) self.log_image_processing( opening, f"opening,kernel:{kernel},iterations:{iterations}", ) return opening def generic_filter(self, image, kernel, iterations=1, custom_msg="genertic_filter"): result = image.copy() for i in range(iterations): result = cv2.filter2D(result, -1, kernel) self.log_image_processing( result, f"{custom_msg},kernel:{kernel},iterations:{iterations}" ) return result def dilate_and_erode( self, image, k_d, i_d, k_e, i_e, iterations=1, op=cv2.MORPH_ELLIPSE ): image = image.copy() for _ in range(iterations): for _ in range(i_d): image = self.dilate(image, (k_d, k_d), op=op) for _ in range(i_e): image = self.erode(image, (k_e, k_e), op=op) self.log_image_processing( image, f"dilate_and_erode,k_d:{(k_d,k_d)},i_d={i_d},k_e:{(k_e, k_e)},i_e={i_e},iterations:{iterations}", ) return image def fill_image(self, image_data, name, show=True): self.log_image_processing( image_data[name], f"fill_{name}", ) image_data[f"fill_{name}"] = { "image": fill(image_data[name]["image"].copy()), "show": show, } ``` ```python def find_ball_contours( self, image, circ_thresh, min_area=400, max_area=4900, convex_hull=False, ): img = image.copy() cnts = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cnts[1] blank_image = np.zeros(img.shape, dtype=img.dtype) for c in cnts: # Calculate properties peri = cv2.arcLength(c, True) # Douglas-Peucker algorithm approx = cv2.approxPolyDP(c, 0.0001 * peri, True) # applying a convex hull if convex_hull == True: c = cv2.convexHull(c) # get contour area area = cv2.contourArea(c) if area == 0: continue # Skip to the next iteration if area is zero circularity = 4 * math.pi * area / (peri**2) if ( (len(approx) > 5) and (area > min_area and area < max_area) and circularity > circ_thresh ): cv2.drawContours(blank_image, [c], -1, (255), cv2.FILLED) return blank_image @staticmethod def preprocessing(image): image_data = {} image_data["original"] = { "image": image.image, "show": True, } image_data["grayscale"] = { "image": cv2.cvtColor(image.image, cv2.COLOR_BGRA2GRAY), "show": False, } ``` ```python image_data["hsv"] = { "image": cv2.cvtColor(image.image.copy(), cv2.COLOR_BGR2HSV), "show": False, } (_, _, intensity) = cv2.split(image_data["hsv"]["image"]) image_data["intensity"] = { "image": intensity, "show": False, } image_data["gblur"] = { "image": image.gblur( image_data["intensity"]["image"], ksize=(3, 3), iterations=2 ), "show": False, } image_data["blur"] = { "image": image.mblur( image_data["intensity"]["image"], ksize=3, iterations=2 ), "show": False, } intensity_threshold = cv2.threshold( image_data["intensity"]["image"], 125, 255, cv2.THRESH_BINARY )[1] image_data["intensity_threshold"] = { "image": intensity_threshold, "show": False, } name = "adap_gaus_thrsh" image_data[name] = { "image": image.adaptive_threshold( image=image_data["blur"]["image"].copy(), blockSize=19, C=5, ), "show": False, } image_data["open"] = { "image": image.opening( image=image_data["adap_gaus_thrsh"]["image"].copy(), kernel=(5, 5), iterations=4, ), "show": False, } image_data["dilate"] = { "image": image.dilate( image=image_data["open"]["image"].copy(), kernel=(3, 3), iterations=2, ), "show": False, ``` ```python } image_data["erode"] = { "image": image.erode( image=image_data["open"]["image"].copy(), kernel=(3, 3), iterations=2, ), "show": True, } fill_erode = image.fill_image(image_data, "erode") image_data["dilate_and_erode"] = { "image": image.dilate_and_erode( image_data["fill_erode"]["image"], k_d=4, i_d=5, k_e=5, i_e=2, iterations=1, ), "show": False, } contours = image.find_ball_contours( cv2.bitwise_not(image_data["dilate_and_erode"]["image"]), 0.32, ) image_data["contours"] = { "image": contours, "show": False, } image_data["im_1"] = { "image": cv2.bitwise_not( image_data["intensity_threshold"]["image"], ), "show": False, } image_data["im_2"] = { "image": cv2.bitwise_not( image_data["contours"]["image"], ), "show": False, } image_data["segmentation_before_recontour"] = { "image": cv2.bitwise_not( cv2.bitwise_or( image_data["im_1"]["image"], image_data["im_2"]["image"] ), ), "show": True, } recontours = image.find_ball_contours( ``` ```python image_data["segmentation_before_recontour"]["image"], 0.0, min_area=100, max_area=4900, convex_hull=True, ) image_data["convex_hull"] = { "image": recontours, "show": True, } image_data["opening_after_segmentation"] = { "image": image.opening( image_data["convex_hull"]["image"], kernel=(3, 3), iterations=5, ), "show": True, } image_data["segmentation"] = { "image": image.find_ball_contours( image_data["opening_after_segmentation"]["image"], 0.72, 250, 5000, True, ), "show": True, } return image_data ``` #pagebreak() == utils.py ```python import os import glob from natsort import natsorted import numpy as np import matplotlib.pyplot as plt import cv2 def get_images_and_masks_in_path(folder_path): images = sorted(filter(os.path.isfile, glob.glob(folder_path + "/*"))) image_list = [] mask_list = [] for file_path in images: if "data.txt" not in file_path: if "GT" not in file_path: image_list.append(file_path) else: mask_list.append(file_path) return natsorted(image_list), natsorted(mask_list) # source and modofied from https://stackoverflow.com/a/67992521 def img_is_color(img): if len(img.shape) == 3: # Check the color channels to see if they're all the same. c1, c2, c3 = img[:, :, 0], img[:, :, 1], img[:, :, 2] if (c1 == c2).all() and (c2 == c3).all(): return True return False from heapq import nlargest, nsmallest def dice_score(processed_images, masks, save_path): eval = [] score_dict = {} for idx, image in enumerate(processed_images): score = dice_similarity_score(image, masks[idx], save_path) score_dict[image] = score if len(eval) == 0 or max(eval) < score: max_score = score max_score_image = image if len(eval) == 0 or min(eval) > score: min_score = score min_score_image = image eval.append(score) avg_score = sum(eval) / len(eval) max_text = f"Max Score: {max_score} - {max_score_image}\n" min_text = f"Min Score: {min_score} - {min_score_image}\n" avg_text = f"Avg Score: {avg_score}\n" ``` ```python print("--- " + save_path + "\n") print(max_text) print(min_text) print(avg_text) print("---") FiveHighest = nlargest(5, score_dict, key=score_dict.get) FiveLowest = nsmallest(5, score_dict, key=score_dict.get) with open(f"{save_path}/dice_score.txt", "w") as f: f.write("---\n") f.write(max_text) f.write(min_text) f.write(avg_text) f.write("---\n") f.write("Scores:\n") for idx, score in enumerate(eval): f.write(f"\t{score}\t{masks[idx]}\n") f.write("---\n") f.write("5 highest:\n") for v in FiveHighest: f.write(f"{v}, {score_dict[v]}\n") f.write("---\n") f.write("5 lowest:\n") for v in FiveLowest: f.write(f"{v}, {score_dict[v]}\n") frame_numbers = [extract_frame_number(key) for key in score_dict.keys()] plt.figure(figsize=(12, 3)) plt.bar(frame_numbers, score_dict.values(), color="c") plt.title("Dice Score for Each Image Frame") plt.xlabel("Image Frame") plt.ylabel("Dice Similarity Similarity Score") plt.ylim([0.8, 1]) plt.xticks( frame_numbers, rotation=90 ) # Rotate the x-axis labels for better readability plt.grid(True) plt.tight_layout() # Adjust the layout for better readability plt.savefig(f"Report/assets/dice_score_barchart.png") # standard deviation std_dev = np.std(eval) print(f"Standard Deviation: {std_dev}") mean = np.mean(eval) print(f"Mean: {mean}") # plot boxplot plt.figure(figsize=(12, 3)) plt.violinplot(eval, vert=False, showmeans=True) plt.title("Dice Score Distribution") plt.xlabel("Dice Similarity Score") plt.grid(True) plt.tight_layout() plt.text(0.83, 0.9, f'Standard Deviation: {std_dev:.2f}', transform=plt.gca().transAxes) ``` ```python plt.text(0.83, 0.80, f'Mean: {mean:.2f}', transform=plt.gca().transAxes) plt.savefig(f"Report/assets/dice_score_violin.png") def extract_frame_number(path): components = path.split("/") filename = components[-1] parts = filename.split("-") frame_number_part = parts[-1] frame_number = frame_number_part.split(".")[0] return int(frame_number) def dice_similarity_score(seg_path, mask_path, save_path): seg = cv2.threshold(cv2.imread(seg_path), 127, 255, cv2.THRESH_BINARY)[1] mask = cv2.threshold(cv2.imread(mask_path), 127, 255, cv2.THRESH_BINARY)[1] intersection = cv2.bitwise_and(seg, mask) dice_score = 2.0 * intersection.sum() / (seg.sum() + mask.sum()) difference = cv2.bitwise_not(cv2.bitwise_or(cv2.bitwise_not(seg), mask)) cv2.imwrite(save_path + f"/difference_ds_{dice_score}.jpg", difference) return dice_score def show_image_list( image_dict: dict = {}, list_cmaps=None, grid=False, num_cols=2, figsize=(20, 10), title_fontsize=12, save_path=None, ): list_titles, list_images = list(image_dict.keys()), list(image_dict.values()) assert isinstance(list_images, list) assert len(list_images) > 0 assert isinstance(list_images[0], np.ndarray) if list_titles is not None: assert isinstance(list_titles, list) assert len(list_images) == len(list_titles), "%d imgs != %d titles" % ( len(list_images), len(list_titles), ) if list_cmaps is not None: assert isinstance(list_cmaps, list) assert len(list_images) == len(list_cmaps), "%d imgs != %d cmaps" % ( len(list_images), len(list_cmaps), ) ``` ```python num_images = len(list_images) num_cols = min(num_images, num_cols) num_rows = int(num_images / num_cols) + (1 if num_images % num_cols != 0 else 0) # Create a grid of subplots. fig, axes = plt.subplots(num_rows, num_cols, figsize=figsize) # Create list of axes for easy iteration. if isinstance(axes, np.ndarray): list_axes = list(axes.flat) else: list_axes = [axes] for i in range(num_images): img = list_images[i] title = list_titles[i] if list_titles is not None else "Image %d" % (i) cmap = ( list_cmaps[i] if list_cmaps is not None else (None if img_is_color(img) else "gray") ) list_axes[i].imshow(img, cmap=cmap) list_axes[i].set_title(title, fontsize=title_fontsize) list_axes[i].grid(grid) list_axes[i].axis("off") for i in range(num_images, len(list_axes)): list_axes[i].set_visible(False) fig.tight_layout() if save_path is not None: fig.savefig(save_path) plt.close(fig) def fill(img): des = cv2.bitwise_not(img.copy()) contour, hier = cv2.findContours(des, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) for cnt in contour: cv2.drawContours(des, [cnt], 0, 255, -1) return cv2.bitwise_not(des) ``` #pagebreak() == seg_main.py ```python import os import cv2 from tqdm import tqdm from datetime import datetime from segmentation.image_segmentation import ImageSegmentation from segmentation.utils import ( dice_score, get_images_and_masks_in_path, show_image_list, ) import multiprocessing as mp dir_path = os.path.dirname(os.path.realpath(__file__)) path = "data/ball_frames" def store_image_data(log_data, time: datetime): """method to store in a text file the image data for processing""" check_path = os.path.exists(f"process_data/{time}/data.txt") if not check_path: with open(f"process_data/{time}/data.txt", "w") as f: for log in log_data: f.write(f"{log}\n") def process_image(inputs: list[list, bool]) -> None: """method to process the image""" [image_path, save, time, save_dir] = inputs image = ImageSegmentation(image_path, save_dir) data = image.preprocessing(image) processed_images = {} for key in data.keys(): if data[key]["show"] is not False: processed_images[key] = data[key]["image"] log_data = image.processing_data name = os.path.splitext(os.path.basename(image_path))[0] save_path = None if save: save_path = f"{save_dir}/{name}" if not os.path.exists(save_dir): os.mkdir(save_dir) store_image_data(log_data, time) if data["segmentation"]["image"] is not None: segmentation_path = f"{save_dir}/segmentation/" if not os.path.exists(segmentation_path): os.mkdir(segmentation_path) seg_path = f"{segmentation_path}{os.path.basename(image.image_path)}" cv2.imwrite(seg_path, data["segmentation"]["image"]) ``` ```python show_image_list( image_dict=processed_images, figsize=(10, 10), save_path=save_path, ) def process_all_images(images, save=False): time = datetime.now().isoformat("_", timespec="seconds") save_path = f"process_data/{time}" seg_path = f"{save_path}/segmentation" with mp.Pool() as pool: inputs = [[image, save, time, save_path] for image in images] list( tqdm( pool.imap_unordered(process_image, inputs, chunksize=4), total=len(images), ) ) pool.close() pool.join() return save_path, seg_path def main(): images, masks = get_images_and_masks_in_path(path) processed_image_path, seg_path = process_all_images(images, True) processed_images, _ = get_images_and_masks_in_path(seg_path) dice_score(processed_images, masks, seg_path) if __name__ == "__main__": main() ``` #pagebreak() == seg_main.py ```python import os import re import cv2 from cv2.gapi import bitwise_and from matplotlib import pyplot as plt from matplotlib.artist import get from segmentation.utils import get_images_and_masks_in_path import numpy as np from segmentation.utils import fill import math from skimage.feature import graycomatrix, graycoprops BALL_SMALL = "Tennis" BALL_MEDIUM = "Football" BALL_LARGE = "American\nFootball" def shape_features_eval(contour): area = cv2.contourArea(contour) # getting non-compactness perimeter = cv2.arcLength(contour, closed=True) non_compactness = 1 - (4 * math.pi * area) / (perimeter**2) # getting solidity convex_hull = cv2.convexHull(contour) convex_area = cv2.contourArea(convex_hull) solidity = area / convex_area # getting circularity circularity = (4 * math.pi * area) / (perimeter**2) # getting eccentricity ellipse = cv2.fitEllipse(contour) a = max(ellipse[1]) b = min(ellipse[1]) eccentricity = (1 - (b**2) / (a**2)) ** 0.5 return { "non_compactness": non_compactness, "solidity": solidity, "circularity": circularity, "eccentricity": eccentricity, } def texture_features_eval(patch): # # Define the co-occurrence matrix parameters distances = [1] angles = np.radians([0, 45, 90, 135]) levels = 256 symmetric = True ``` ```python normed = True glcm = graycomatrix( patch, distances, angles, levels, symmetric=symmetric, normed=normed ) filt_glcm = glcm[1:, 1:, :, :] # Calculate the Haralick features asm = graycoprops(filt_glcm, "ASM").flatten() contrast = graycoprops(filt_glcm, "contrast").flatten() correlation = graycoprops(filt_glcm, "correlation").flatten() # Calculate the feature average and range across the 4 orientations asm_avg = np.mean(asm) contrast_avg = np.mean(contrast) correlation_avg = np.mean(correlation) asm_range = np.ptp(asm) contrast_range = np.ptp(contrast) correlation_range = np.ptp(correlation) return { "asm": asm, "contrast": contrast, "correlation": correlation, "asm_avg": asm_avg, "contrast_avg": contrast_avg, "correlation_avg": correlation_avg, "asm_range": asm_range, "contrast_range": contrast_range, "correlation_range": correlation_range, } def initialise_channels_features(): def initialise_channel_texture_features(): return { "asm": [], "contrast": [], "correlation": [], "asm_avg": [], "contrast_avg": [], "correlation_avg": [], "asm_range": [], "contrast_range": [], "correlation_range": [], } return { "blue": initialise_channel_texture_features(), "green": initialise_channel_texture_features(), "red": initialise_channel_texture_features(), } def initialise_shape_features(): return { "non_compactness": [], "solidity": [], ``` ```python "circularity": [], "eccentricity": [], } def get_all_features_balls(path): features = { BALL_LARGE: { "shape_features": initialise_shape_features(), "texture_features": initialise_channels_features(), }, BALL_MEDIUM: { "shape_features": initialise_shape_features(), "texture_features": initialise_channels_features(), }, BALL_SMALL: { "shape_features": initialise_shape_features(), "texture_features": initialise_channels_features(), }, } images, masks = get_images_and_masks_in_path(path) for idx, _ in enumerate(images): image = images[idx] mask = masks[idx] msk = cv2.imread(mask, cv2.IMREAD_GRAYSCALE) _, msk = cv2.threshold(msk, 127, 255, cv2.THRESH_BINARY) # overlay binay image over it's rgb counterpart img = cv2.imread(image) img = cv2.bitwise_and(cv2.cvtColor(msk, cv2.COLOR_GRAY2BGR), img) contours, _ = cv2.findContours(msk, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) for contour in contours: area = cv2.contourArea(contour) ball_img = np.zeros(msk.shape, dtype=np.uint8) cv2.drawContours(ball_img, contour, -1, (255, 255, 255), -1) fill_img = cv2.bitwise_not(fill(cv2.bitwise_not(ball_img))) rgb_fill = cv2.bitwise_and(cv2.cvtColor(fill_img, cv2.COLOR_GRAY2BGR), img) out = fill_img.copy() out_colour = rgb_fill.copy() # Now crop image to ball size (y, x) = np.where(fill_img == 255) (topy, topx) = (np.min(y), np.min(x)) (bottomy, bottomx) = (np.max(y), np.max(x)) padding = 3 out = out[ topy - padding : bottomy + padding, topx - padding : bottomx + padding ] out_colour = out_colour[ ``` ```python topy - padding : bottomy + padding, topx - padding : bottomx + padding ] # getting ball features shape_features = shape_features_eval(contour) texture_features_colour = { "blue": texture_features_eval(out_colour[:, :, 0]), "green": texture_features_eval(out_colour[:, :, 1]), "red": texture_features_eval(out_colour[:, :, 2]), } # segmenting ball by using area if area > 1300: # football append_ball = BALL_LARGE elif area > 500: # soccer_ball append_ball = BALL_MEDIUM else: # tennis ball append_ball = BALL_SMALL for key in shape_features: features[append_ball]["shape_features"][key].append(shape_features[key]) for colour in texture_features_colour.keys(): for colour_feature in texture_features_colour[colour]: features[append_ball]["texture_features"][colour][ colour_feature ].append(texture_features_colour[colour][colour_feature]) return features def feature_stats(features, ball, colours=["blue", "green", "red"]): def get_stats(array): return { "mean": np.mean(array), "std": np.std(array), "min": np.min(array), "max": np.max(array), } def get_ball_shape_stats(features, ball): feature_find = ["non_compactness", "solidity", "circularity", "eccentricity"] return { feature: get_stats(features[ball]["shape_features"][feature]) for feature in feature_find } def get_ball_texture_stats(features, ball, colour): feature_find = ["asm_avg", "contrast_avg", "correlation_avg"] return { texture: get_stats(features[ball]["texture_features"][colour][texture]) for texture in feature_find } ``` ```python stats = { ball: { "shape_features": get_ball_shape_stats(features, ball), "texture_features": { colour: get_ball_texture_stats(features, ball, colour) for colour in colours }, }, } return stats def get_histogram(data, Title): """ data {ball: values} """ for ball, values in data.items(): plt.figure(figsize=(3,3)) plt.hist(values, bins=20, alpha=0.5, label=ball) plt.xlabel(Title) plt.ylabel("Frequency") plt.legend() plt.tight_layout() plt.savefig("Report/assets/features/"+ Title + "_histogram_" + ball.replace("\n", "_")) # plt.show() if __name__ == "__main__": features = get_all_features_balls("data/ball_frames") balls = [ BALL_SMALL, BALL_MEDIUM, BALL_LARGE, ] non_compactness = { ball: features[ball]["shape_features"]["non_compactness"] for ball in balls } solidity = {ball: features[ball]["shape_features"]["solidity"] for ball in balls} circularity = { ball: features[ball]["shape_features"]["circularity"] for ball in balls } eccentricity = { ball: features[ball]["shape_features"]["eccentricity"] for ball in balls } get_histogram(non_compactness, "Non-Compactness") get_histogram(solidity, "Soliditiy") get_histogram(circularity, "Circularity") ``` ```python get_histogram(eccentricity, "Eccentricity") channel_colours = ["red", "green", "blue"] def get_ch_features(feature_name): return { colour: { ball: features[ball]["texture_features"][colour][feature_name] for ball in balls } for colour in channel_colours } def get_ch_stats(feature_data, colours=channel_colours): return [[feature_data[colour][ball] for ball in balls] for colour in colours] asm_avg = get_ch_features("asm_avg") contrast_avg = get_ch_features("contrast_avg") correlation_avg = get_ch_features("correlation_avg") asm_range = get_ch_features("asm_range") asm_data = get_ch_stats(asm_avg) contrast_data = get_ch_stats(contrast_avg) correlation_data = get_ch_stats(correlation_avg) asm_range_data = get_ch_stats(asm_range) asm_title = "ASM Avg" contrast_title = "Contrast Avg" correlation_title = "Correlation Avg" asm_range_title = "ASM Range Avg" plt_colours = ["yellow", "white", "orange"] channels = ["Red Channel", "Green Channel", "Blue Channel"] plt.figure() def get_boxplot(data, title, colours=plt_colours, rows=3, columns=3, offset=0): channels = ["Red Channel", "Green Channel", "Blue Channel"] fig = plt.figure(figsize=(8,3)) # Get the Figure object fig.suptitle(title) # Set the overall title for i, d in enumerate(data): ax = plt.subplot(rows, columns, i + offset + 1) ax.set_facecolor(channel_colours[i]) ax.patch.set_alpha(0.5) violins = plt.violinplot( d, showmeans=True, showmedians=False, showextrema=False ) for j, pc in enumerate(violins["bodies"]): pc.set_facecolor(colours[j]) pc.set_edgecolor("black") pc.set_alpha(0.2) plt.xticks([1, 2, 3], balls, rotation=45) plt.title(channels[i]) ``` ```python def get_boxplot_specific(data, title, i, colours=plt_colours): plt.figure(figsize=(2.5,6)) d = data[i] violins = plt.violinplot( d, showmeans=True, showmedians=False, showextrema=False ) for j, pc in enumerate(violins["bodies"]): pc.set_facecolor(colours[j]) pc.set_edgecolor("black") pc.set_alpha(0.5) plt.xticks([1, 2, 3], balls, rotation=45) plt.title(title + '\n' + channels[i]) ax = plt.gca() # Get the current Axes instance ax.set_facecolor(channel_colours[i]) # Set the background color ax.patch.set_alpha(0.1) # Set the alpha value columns = 3 rows = 1 get_boxplot_specific(asm_data, asm_title, 2) plt.tight_layout() plt.savefig("Report/assets/features/asm_data_blue_channel") plt.close() get_boxplot_specific(asm_range_data, asm_range_title, 2) plt.tight_layout() plt.savefig("Report/assets/features/asm_range_data_blue_channel") plt.close() get_boxplot_specific(contrast_data, contrast_title, 0) plt.tight_layout() plt.savefig("Report/assets/features/contrast_data_red_channel") plt.close() get_boxplot_specific(correlation_data, correlation_title, 1) plt.tight_layout() plt.savefig("Report/assets/features/correlation_green_channel") plt.close() ``` #pagebreak() = tracking_main.py ```python from matplotlib import pyplot as plt import numpy as np def kalman_predict(x, P, F, Q): xp = F * x Pp = F * P * F.T + Q return xp, Pp def kalman_update(x, P, H, R, z): S = H * P * H.T + R K = P * H.T * np.linalg.inv(S) zp = H * x xe = x + K * (z - zp) Pe = P - K * H * P return xe, Pe def kalman_tracking( z, x01=0.0, x02=0.0, x03=0.0, x04=0.0, dt=0.5, nx=0.16, ny=0.36, nvx=0.16, nvy=0.36, nu=0.25, nv=0.25, kq=1, kr=1, ): # Constant Velocity F = np.matrix([[1, dt, 0, 0], [0, 1, 0, 0], [0, 0, 1, dt], [0, 0, 0, 1]]) # Cartesian observation model H = np.matrix([[1, 0, 0, 0], [0, 0, 1, 0]]) # Motion Noise Model Q = kq*np.matrix([[nx, 0, 0, 0], [0, nvx, 0, 0], [0, 0, ny, 0], [0, 0, 0, nvy]]) # Measurement Noise Model R = kr*np.matrix([[nu, 0], [0, nv]]) x = np.matrix([x01, x02, x03, x04]).T P = Q N = len(z[0]) s = np.zeros((4, N)) ``` ```python for i in range(N): xp, Pp = kalman_predict(x, P, F, Q) x, P = kalman_update(xp, Pp, H, R, z[:, i]) val = np.array(x[:2, :2]).flatten() s[:, i] = val px = s[0, :] py = s[1, :] return px, py def rms(x, y, px, py): return np.sqrt(1/len(px) * (np.sum((x - px)**2 + (y - py)**2))) def mean(x, y, px, py): return np.mean(np.sqrt((x - px)**2 + (y - py)**2)) if __name__ == "__main__": x = np.genfromtxt("data/x.csv", delimiter=",") y = np.genfromtxt("data/y.csv", delimiter=",") na = np.genfromtxt("data/na.csv", delimiter=",") nb = np.genfromtxt("data/nb.csv", delimiter=",") z = np.stack((na, nb)) dt = 0.5 nx = 160.0 ny = 0.00036 nvx = 0.00016 nvy = 0.00036 nu = 0.00025 nv = 0.00025 px1, py1 = kalman_tracking(z=z) nx = 0.16 * 10 ny = 0.36 nvx = 0.16 * 0.0175 nvy = 0.36 * 0.0175 nu = 0.25 nv = 0.25 * 0.001 kq = 0.0175 kr = 0.0015 px2, py2 = kalman_tracking( nx=nx, ny=ny, nvx=nvx, nvy=nvy, nu=nu, nv=nv, kq=kq, kr=kr, z=z, ) ``` ```python plt.figure(figsize=(12, 5)) plt.plot(x, y, label='trajectory') plt.plot(px1, py1, label=f'intial prediction, rms={round(rms(x, y, px1, py1), 3)}') print(f'initial rms={round(rms(x, y, px1, py1), 3)}, mean={round(mean(x, y, px1, py1), 3)}') plt.plot(px2, py2,label=f'optimised prediction, rms={round(rms(x, y, px2, py2), 3)}') print(f'optimised rms={round(rms(x, y, px2, py2), 3)}, mean={round(mean(x, y, px2, py2), 3)}') plt.scatter(na, nb,marker='x',c='k',label=f'noisy data, rms={round(rms(x, y, na, nb), 3)}') print(f'noise rms={round(rms(x, y, na, nb), 3)}, mean={round(mean(x, y, na, nb), 3)}') plt.legend() plt.title("Kalman Filter") plt.savefig("Report/assets/tracking/kalman_filter.png") # plt.show() ```
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/georges-yetyp/0.1.0/template/main.typ
typst
Apache License 2.0
#import "@preview/georges-yetyp:0.1.0": rapport #show: rapport.with( nom: "Georgette Lacourgette", titre: "Titre du stage", entreprise: ( nom: "Nom de l'entreprise", adresse: [ 12 rue de la Chartreuse, \ 38000 Grenoble, \ France ], logo: image("logo.png", height: 4em), ), responsable: ( nom: "<NAME>", fonction: "CTO", téléphone: "+33 6 66 66 66 66", email: "<EMAIL>" ), tuteur: ( nom: "<NAME>", téléphone: "+33 6 66 66 66 66", email: "<EMAIL>" ), référent: ( nom: "<NAME>", téléphone: "+33 6 66 66 66 66", email: "<EMAIL>" ), résumé: [ #lorem(100) #lorem(20) ], glossaire: [ / Georges : Prénom de la mascotte de l'école. ] ) = Introduction == Présentation de l'entreprise #lorem(30) #lorem(50) #figure( image("logo.png"), caption: [Le logo de l'entreprise] ) #lorem(100) == Mes missions #lorem(50) #figure( ```rust fn main() { println!("Hello world!"); } ```, caption: [Le fameux programme "Hello world"] ) #lorem(130)
https://github.com/TimPaasche/Typst.Template.CoverLetter
https://raw.githubusercontent.com/TimPaasche/Typst.Template.CoverLetter/master/README.md
markdown
MIT License
# Typst.Template.CoverLetter
https://github.com/Amelia-Mowers/typst-tabut
https://raw.githubusercontent.com/Amelia-Mowers/typst-tabut/main/doc/example-snippets/rearrange.typ
typst
MIT License
#import "@preview/tabut:<<VERSION>>": tabut #import "example-data/supplies.typ": supplies #tabut( supplies, ( (header: [Price], func: r => r.price), // This column is moved to the front (header: [Name], func: r => r.name), (header: [Name 2], func: r => r.name), // copied // (header: [Quantity], func: r => r.quantity), // removed via comment ) )
https://github.com/JarKz/math_analysis_with_typst
https://raw.githubusercontent.com/JarKz/math_analysis_with_typst/main/groups/fifth.typ
typst
MIT License
= Пятая группа вПпрПсПв 1. *ОпреЎелеМОе сПбствеММПгП ОМтеграла, завОсящегП Пт параЌетра, егП МепрерывМПсть О ОМтегрОрПваМОе.* 2. *ДОффереМцОрПваМОе сПбствеММПгП ОМтеграла, завОсящегП Пт параЌетра (правОлП ЛейбМОца).* 3. *ОпреЎелеМОе МесПбствеММПгП ОМтеграла, завОсящегП Пт параЌетра.* 4. *РавМПЌерМая схПЎОЌПсть МесПбствеММПгП ОМтеграла ,завОсящегП Пт параЌетра. КрОтерОй КПшО.* 5. *ПрОзМак Вейерштрасса равМПЌерМПй схПЎОЌПстО МесПбствеММПгП ОМтеграла, завОсящегП Пт параЌетра.* 5. *ПрОзМак ДОрОхле равМПЌерМПй схПЎОЌПстО МесПбствеММПгП ОМтеграла, завОсящегП Пт параЌетра.* 7. *НепрерывМПсть МесПбствеММПгП ОМтеграла, завОсящегП Пт параЌетра.* 8. *ИМтегрОрПваМОе МесПбствеММПгП ОМтеграла, завОсящегП Пт параЌетра.* 9. *ДОффереМцОрПваМОе МесПбствеММПгП ОМтеграла, завОсящегП Пт параЌетра.* 10. *ИМтеграл ДОрОхле.* 11. *ИМтеграл ПуассПМа.* 12. *Бета-фуМкцОя Эйлера О ее свПйства.* 13. *ГаЌЌа-фуМкцОя Эйлера О ее свПйства.* 14. *Связь ЌежЎу бета- О гаЌЌа-фукМцОяЌО.* 15. *ОпреЎелеМОе $n$-ЌерМПй Ќеры ЌМПжества.* 16. *ММПжества Ќеры Муль.* 17. *КубОруеЌые ЌМПжества.* 18. *ОпреЎелеМОе кратМПстО ОМтеграла.* 19. *СуЌЌы Дарбу. КрОтерОй существПваМОя кратМПгП ОМтеграла.* 20. *ДПстатПчМПе услПвОе существПваМОя кратМПгП ОМтеграла.* 21. *СвПйства кратМПгП ОМтеграла.* 22. *СвеЎеМОе ЎвПйМПгП ОМтеграла к пПвтПрМПЌу.* 23. *ВычОслеМОе плПщаЎО О ПбъеЌа с пПЌПщью ЎвПйМПгП ОМтеграла.* 24. *СвеЎеМОе $n$-кратМПгП ОМтеграла к пПвтПрМПЌу.* 25. *ГеПЌетрОческОй сЌысл ЌПЎуля якПбОаМа.* 26. *ЗаЌеМа переЌеММых в ЎвПйМПЌ ОМтеграле.* 27. *ЗаЌеМа переЌеММых в кратМПЌ ОМтеграле.* 28. *КрОвПлОМейМый ОМтеграл 1-гП рПЎа.* 29. *КрОвПлОМейМый ОМтеграл 2-гП рПЎа.* 30. *ЀПрЌула ГрОМа.* 31. *КрОвПлОМейМые ОМтегралы, Ме завОсящОе Пт путО ОМтегрОрПваМОя.* 32. *ППМятОе пПверхМПстО.* 33. *ПлПщаЎь пПверхМПстО.* 34. *ОрОеМтацОя глаЎкПй пПверхМПстО.* 35. *ППверхМПстМые ОМтегралы 1-гП рПЎа.* 36. *ППверхМПстМые ОМтегралы 2-гП рПЎа.* 37. *ОпреЎелеМОе граЎОеМта, ЎОвергеМцОО, рПтПра.* 38. *ЊОркуляцОя О пПтПк вектПрМПгП пПля.* 39. *ЀПрЌула ОстрПграЎскПгП.* 40. *ЀПрЌула СтПкса.* 41. *СПлеМПОЎальМПе О пПтеМцОальМПе вектПрМые пПля.*
https://github.com/max-niederman/MTH311
https://raw.githubusercontent.com/max-niederman/MTH311/main/ivt.typ
typst
#import "./lib.typ": * #show: common.with(title: "Intermediate Value Theorem") = Induction on the Nonnegative Reals Let $A$ be a subset of $RR$ such that - If $[0, x) subset.eq A$, then $x in A$. - For any $a$ in $A$, there exists some $b in RR$ such that $a < b$ and $(a, b) subset.eq A$. Then $A supset.eq [0, oo)$. _Proof_: Consider the set $A^c = [0, oo) backslash A$, and assume by contradiction that it is nonempty. It is bounded below by zero, as all elements of $[0, oo)$ are nonnegative. Therefore, $inf A^c$ exists and is a nonnegative real number. Numbers in the interval $[0, inf A^c)$ cannot be in $A^c$, as $inf A^c$ is a lower bound on $A^c$. However, such numbers are in $[0, oo)$ and thus also in $[0, oo) backslash A^c = A$. That is, $[0, inf A^c) subset.eq A$. By condition one, we have $[0, inf A^c] subset.eq A$. We then apply condition two to $inf A^c$ to find some $b in RR$ such that $inf A^c < b$ and $(inf A^c, b) subset.eq A$. Taking the union of the two intervals, we have $[0, b) subset.eq A$, with $inf A^c < b$. Now take some $x in A^c$. It must be greater than or equal to $b$, because if it were less than $b$, it would be in $[0, b)$ and therefore in $A$. Therefore, $b$ is a lower bound on $A^c$, which contradicts $inf A^c < b$. Hence, the assumption that $A^c$ is nonempty must be false, and $A supset.eq [0, oo)$. #sym.qed #colbreak() = Increasing Nonnegative Domain For any $L in RR$ and $b in [0, oo)$, and some function $f : RR -> RR$, if $f$ is continuous on $[0, b]$ and $f(0) <= L <= f(b)$, then there exists some $c in [0, b]$ such that $f(c) = L$. _Proof_: Consider the set $ B = { b in [0, oo) | &f "continuous on" [0, b] \ &and f(0) <= L <= f(b) \ &quad => exists c in [0, b], f(c) = L } "." $ That is, the set of $b$ values for which the proposition holds w.r.t. $f$ and $L$. == Limit Case Assume that there is some $x$ such that $[0, b) subset.eq B$, and furthermore that $f$ is continuous on $[0, b]$ and $f(0) <= L <= f(b)$. If $L = f(b)$, then we have that there exists $c$ such that $f(c) = L$ trivially. Otherwise, $L < f(b)$ and so $0 < f(b) - L$. Then, because $f$ is continuous at $b$, we can apply the limit definition to find that there exists $delta > 0$ such that for all $x in RR$, $ |b - x| < delta => |f(b) - f(x)| < f(b) - L "." $ Define $b' = max(0, b - delta/2)$. Observe that $ b - delta/2 &<= b' \ b - b' &<= delta/2 \ b - b' &< delta "," $ and because $b' > b$, $ abs(b - b') &< delta "." $ Now we apply the limit to get $ abs(f(b) - f(b')) &< f(b) - L \ f(b) - f(b') &< f(x) - L \ - f(b') &< - L \ L &< f(b') "." $ We already know that $f(0) < L$, so $ f(0) < L < f(b') "," $ and because $b' in [0, b)$, we have $c in [0, b')$ such that $ f(c) = L "." $ Furthermore, $[0, b')$ is a subset of $[0, b)$, so that $c$ also satisfies the proposition for $b$. == Successor Case Assume that $b in B$. That is, if $f$ is continuous on $[0, b]$ and $f(0) <= L <= f(b)$, then there exists $c in [0, b]$ such that $f(c) = L$. === Case 1: $L <= f(b)$ Let $b' = b + 1$. Consider any $x in (b, b')$, and assume that $f$ is continuous on $[0, x]$ and $f(0) <= L <= f(x)$. Because $x > b$, we have that $f$ is continuous on $[0, b]$ and $f(0) <= L$. Furthermore, $L <= f(b)$, so the conditions for $b$ are satisfied. Therefore, there exists $c in [0, b + 1]$ such that $f(c) = L$. === Case 2: $f(b) < L$, $f$ discontinuous at $b$ Let $b' = b + 1$. For any $x in (b, b')$, we know that $f$ is not continuous on the interval $[0, x]$ because it is not continuous at $b in [0, x]$. Therefore, it follows from the principle of explosion that the continuity of that interval implies the existence of some $c in [0, x]$ such that $f(c) = L$. === Case 3: $f(b) < L$, $f$ continuous at $b$ Define $epsilon = L - f(b)$. Because $L > f(b)$, we have $epsilon > 0$. Applying the limit of $f$ at $b$, we find that there exists $delta > 0$ such that for all $x in RR$, $ |b - x| < delta => |f(b) - f(x)| < epsilon "." $ Let $b' = b + delta$ and consider any $x in (b, b')$. Then $ b <& x &<& b + delta \ 0 <& x - b &<& delta \ -delta <& x - b &<& delta \ & abs(x - b) &<& delta \ & abs(b - x) &<& delta "." $ Therefore, $ abs(f(b) - f(x)) &< epsilon \ abs(f(x) - f(b)) &< epsilon \ f(x) - f(b) &< epsilon \ f(x) - f(b) &< L - f(b) \ f(x) &< L "." $ So it would be a contradiction to have $L <= f(x)$. Once again, the membership condition holds for $x$ by the principle of explosion. == Conclusion By applying the limit and successor cases to the induction result, we have that $B supset.eq [0, b)$. Because $B subset.eq [0, b)$ as well, we have that $B = [0, oo)$. Hence, the proposition holds for all $b in [0, oo)$. #sym.qed
https://github.com/alberto-lazari/cns-report
https://raw.githubusercontent.com/alberto-lazari/cns-report/main/introduction.typ
typst
= Introduction == Related works In recent years, the widespread adoption of Quick Response (QR) codes has introduced new challenges for the security and robustness of mobile applications. QR codes, while they can be used to provide simple and immediate access to information, they also present potential security vulnerabilities that can be exploited by malicious actors, being them just another form of input for an application. The paper "If You’re Scanning This, It’s Too Late! A QR Code-Based Fuzzing Methodology to Identify Input Vulnerabilities in Mobile Apps." by @carboni2023if made a first effort towards an automated fuzzing-based methodology able to address this problem. Their proposal required the use of a real smartphone to run the tests on, which limited the possibility of automation and the reproducibility of the results, being them based on various factors that depends on the device, that also causes some hardware-related probems. == Contributions Our work #cite(<QRFuzz-2>, form: "normal") builds upon the @carboni2023if research, which introduced a fuzzing framework designed to uncover QR code input vulnerabilities in mobile apps. However, to improve the efficiency of the proposed approach with the aim of making the testing more scalable, we propose an alternative design. Our proposal is based on the virtualization of the mobile phone, that allows for a more detailed configuration of the environment and potentially for the creation of multiple parallel testing sessions, without the need of large quantities of dedicated hardware. Our framework also uses a virtual camera, linked to the virtual device, such that it is possible to virtually display QR codes on it, cutting out the hardware-related problems the previous proposal suffers of. By virtualizing the testing infrastructure, we aim to overcome the limitations of traditional physical devices, providing researchers and developers with a more versatile platform for uncovering potential vulnerabilities in Android applications that provide QR code interactions. The introduced virtualization not only improves the efficiency of the fuzzing process but also simplifies the adoption of this fuzzing methodology for new users. The source code of our system is freely available on GitHub #footnote(link("https://github.com/albertolazari/qrfuzz")). #v(5em) == Report's structure In the following sections of this report, we present the details of our virtualization approach. We provide a comprehensive overview of the previous work (@previous_work), critically analyze the key aspects of its original design (@critical_aspects), and illustrate the details of our approach (@our_approach). Subsequent sections discuss the technological and implementation details of webcam (@webcam_virtualization) and device virtualization (@device_virtualization), how the entire process is automated (@automation), results of the performed tests (@test_results) and conclude with insights into future possible actions that could further improve this field (@future_work).
https://github.com/maucejo/book_template
https://raw.githubusercontent.com/maucejo/book_template/main/template/main.typ
typst
MIT License
#import "../src/book.typ": * #show: book.with( author: "<NAME>", commity: ( ( name: "<NAME>", position: "Professeur des Universités", affiliation: "Streeling university", role: "Rapporteur", ), ( name: "<NAME>", position: "Maître de conférences - HDR", affiliation: "Synnax University", role: "Rapporteur" ), ( name: "<NAME>", position: "Maître de conférences", affiliation: "Beltegeuse University", role: "Examinateur" ), ( name: "<NAME>", position: "Maître de conférences", affiliation: "Caladan University", role: "Examinateur" ), ), lang: "fr" ) #show: front-matter #include "front_matter/front_main.typ" #show: main-matter #tableofcontents() #listoffigures() #listoftables() #include "chapters/ch_main.typ" // #bibliography("bibliography/sample.yml") #bibliography("bibliography/sample.bib") #show: appendix #include "appendix/app_main.typ" #back-cover(resume: lorem(100), abstract: lorem(100))
https://github.com/Blezz-tech/math-typst
https://raw.githubusercontent.com/Blezz-tech/math-typst/main/КартОМкО/ДеЌП варОаМт 2024/ЗаЎаМОе 01.3.typ
typst
#import "@preview/cetz:0.1.2" #import "/lib/my_cetz.typ": defaultStyle #set align(center) #cetz.canvas(length: 0.5cm, { import cetz.draw: * import cetz.angle: angle set-style(..defaultStyle) let (A, B, C, D, O) = ((0,4), (-10,0), (0,-4), (10,0), (0,0)) angle(B, A, O, label: text([$13 degree$], size: 8pt) ) angle(B, C, O, label: text([$13 degree$], size: 8pt) ) angle(C, B, D, radius: 0.6) angle(C, B, D, radius: 0.45) line(A, B, C, D, close: true) circle(O, fill: blue, stroke: (paint: blue), radius: 0.07) content(O, $ O $, anchor: "top-left") content(A, $ A $, anchor: "bottom") content(B, $ B $, anchor: "right") content(C, $ C $, anchor: "top") content(D, $ D $, anchor: "left") line(B, D, stroke: (dash: "dashed", paint: blue)) line(A, C, stroke: (dash: "dashed", paint: blue)) })
https://github.com/EpicEricEE/typst-marge
https://raw.githubusercontent.com/EpicEricEE/typst-marge/main/tests/overlap/side/test.typ
typst
MIT License
#import "/src/lib.typ": sidenote #set par(justify: true) #set page(width: 12cm, height: auto, margin: (x: 4cm, rest: 5mm)) #let sidenote = sidenote.with(numbering: "1") #lorem(8) #sidenote(side: right)[This sidenote is on the right side.] #lorem(2) #sidenote(side: left)[ This one is on the left side and thus doesn't overlap with the previous one. ] #lorem(6) #sidenote(side: left)[ This is also on the left side and does overlap. ] #lorem(28)
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/055%20-%20Murders%20at%20Karlov%20Manor/006_Episode%206%3A%20Explosions%20of%20Genius.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 6: Explosions of Genius", set_name: "Murders at Karlov Manor", story_date: datetime(day: 12, month: 01, year: 2024), author: "<NAME>", doc ) "Where are we going, exactly?" "All will be clear in short order." "Mmmm 
" Etrata tapped her chin and grabbed Proft's arm. Before he could react, she pulled him into a nearby alley, spun him around, and pressed his back against the wall. He blinked as she loomed over him. She wasn't taller than he was; looming should have been impossible, and yet, she was accomplishing it. "No," she said in a level, reasonable tone. "All will be clear right now, or we're not going any farther. I've had to prevent one attempt on your life. If it hadn't been someone who knows me, that would #emph[not] have ended well for you. So, you're going to tell me where we're going, or we're not going there." Proft raised an eyebrow. She didn't flinch. After a long, strained silence, he sighed and glanced toward the street, apparently checking to see if their little altercation had attracted any unwanted attention. Seeing that they were alone, he turned back to Etrata. "I'll need you to release me first." Grudgingly, she let go of his arm. Proft rubbed the spot she'd been gripping as he shook his head. "Is such violence a common means of discussion among House Dimir?" he asked. "It seems a bit 
 blunt." "Only when the person we're dealing with is immune to seeing sense," she said. "Where are we going?" "The powder I found in your chamber is like nothing I've encountered before. We need to have it analyzed by someone we can trust not to be working against us." "You told me we were going to see a friend of yours," said Etrata. "Not that it would involve walking down the street in broad daylight. I'm a fugitive." "Yes, and apparently I'm a marked man. Your point would be?" Something in Etrata's expression must have told Proft he was on thin ice, because he continued: "Kylox is 
 a sensitive individual. After some issues with espionage and patent theft, he has become very attuned to anything that smacks of subterfuge or deceit. With him, you're #emph[more] likely to be seen and intercepted if you attempt to come in via a back route or hidden passage than if you approach openly." Etrata blinked. "That may be the most ridiculous thing I've ever heard." "He's brilliant, really, just paranoid—if it can be called paranoia when every one of his wild assertions has eventually proven true. Regardless, any other route could do us material harm." "And we're going to him, not someone else, because 
?" "We can't go to the Agency without revealing my involvement in your escape. We can't go to the guilds until we know who set an assassin on my trail. This is someone I trust implicitly, who fears discovery enough to understand any requests we make for circumspection, who will ask few questions. There's none better in this city, I assure you." Etrata frowned. "I still don't like this open of an approach." "We're nearly there." "You need to start telling me things. You can't hold them back just because you want to look clever when you reveal them." Proft smiled, very faintly. "I'll take that under consideration." They left the alley for the street. At the corner, Proft turned, then turned again, heading down a narrow lane between two shops. Etrata followed. When the lane branched, he turned again onto an even narrower sub-street barely wide enough to allow the shops on either side to open their doors. The street ended at a blank wall. Proft touched the wall, almost in imitation of Etrata at her hideout, then backtracked three storefronts to a door with a small plaque identifying it as a bookkeeper's office. He rapped his knuckles against it and stepped back, waiting. After several seconds ticked by without anything changing, he frowned and knocked again. He waited longer this time. When he began to step forward again, Etrata held up a hand to stop him. "I'm sturdier than you are," she explained, moving to try the doorknob. "If this thing is set up to shock or poison me or something, I'll probably be fine. You wouldn't be." "A valid reason, if not one I particularly care for—oh, hello." The doorknob twisted easily when she turned it, and when she let go, the door swung silently inward. "That's unusual. He never leaves the door unlocked." "Lovely," said Etrata. "So we're probably walking into a trap." "I certainly hope not," said Proft. He pushed past her, stepping into the darkness beyond. Etrata sighed and followed. As soon as they were both inside, a series of linked tubes around the edges of the room lit up as the lightning elemental contained inside began darting back and forth, filling the air with a jittering, flickering light. There was a break in one of the containment units, which probably explained the flickering; under ideal conditions, the elemental's light would have been steady enough to work by. The light was still enough to reveal a small workshop, the sort of place maintained by a single inventor for their private use, cozy and compact—and destroyed. It looked as if an entire gang of people had passed through, smashing everything they could get their hands on. Scraps of paper and bits of blueprint littered the floor. The active tubes were clearly a backup system; larger tubes lower on the wall had been smashed, adding shards of glass to the debris. Proft moved to the center of the room, not saying a word. The crunch of glass under his feet and Etrata's quiet exclamation of general dismay were both swallowed by the silence. Proft stopped to take another look around before pressing his index fingers together, resting them against his chin, and bowing his head in apparent concentration. Thin blue lines spread outward from his feet, racing across the room to crawl up the walls and across the ceiling. They met there, knotting together in an elaborate network of delicate tangles. The space between them lit up blue-white, until the entire room was bathed in a magical glow, Proft at the center. #figure(image("006_Episode 6: Explosions of Genius/01.png.jpg", width: 100%), caption: [Art by: Daarken], supplement: none, numbering: none) "Hmm," he said, lowering his hands. "This isn't correct." The light pulsed, and the workshop was no longer destroyed. It was perfect and pristine, cluttered as Izzet workshops almost always were, but with no sign that anything more dramatic than a late-night brainstorming session had ever happened here. The light steadied, flicker fading as the containment system was restored. Slowly, Proft began pacing around the outside of the room, occasionally ruffling through a stack of light-limned papers or adjusting a pencil that Etrata knew for a fact wasn't actually there anymore. Finally, he paused in front of a patch of wall, squinting at it before looking at the floor. "Etrata, your assistance, if you would be so kind." He snapped his fingers, and the light shattered around them, replaced by the wreckage of the workshop as it actually existed. Etrata hurried across the room to stand beside him. He was looking at the floor when she got there, or more specifically, at a capsized bookshelf covering a large section of the floor. "What do you need?" asked Etrata. "I need this moved." "And you think I can do it?" "I do." It was a simple statement, made with such assurance that Etrata was bending to move the bookshelf aside almost before she realized she was going to agree. It was made of good, sturdy hardwood and had clearly been designed to stand up to the rigors of the workshop; as she hoisted it off the floor, books and small boxes fell from the shelves, landing around her feet. Moving the bookshelf revealed a rumpled rug, which had been almost entirely obscured. Proft nodded satisfaction and crouched down. "This is normally where you would say 'thank you,'" said Etrata. Proft ignored her, flipping back the edge of the rug and revealing 
 absolutely nothing. "Your secret door was Izzet work," he said, standing again as she set the bookshelf on its base. "Try the same patterns here, if you would be so kind." Etrata looked at him suspiciously but got down on her knees and began drumming her fingers against the floor. The first several taps sounded solid. The next sounded almost hollow. She looked up again. "No one builds a hidey-hole like an Izzet inventor, but once they have a mechanism that works, they tend to keep it until someone else manages to come up with something better," said Proft, taking a step back to give her room. "It's always amused me that Kylox was so angry about spies in his last shared lab. He's as big a thief as the rest of them." A square portion of floor dropped several inches with a loud click. Etrata kept drumming, rolling her eyes at the same time. "Oh, and I suppose you like having people who are smarter than you around while #emph[you're] trying to work?" "I wouldn't know," said Proft, as the floor dropped again, this time all the way, revealing a trapdoor. He stepped forward, offering Etrata a hand up. "It's never happened. Shall we descend?" #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The trapdoor led to a ladder; the ladder led down into the boilerpits, distant firelight illuminating the web of tangled pipes and exposed steam vents. The air was hot, heavy, and remarkably fragrant. Proft took a satisfied breath, then coughed. "Breathe shallowly," he advised. "This isn't the sewer, but filth still sinks, regardless of the intent." "I've been here before," said Etrata. "Which way?" "Kylox never leaves Izzet-controlled territory if he can help it," said Proft. "This pipe runs in two directions. That way, he leaves the district. This way, he moves deeper in." He began walking away from the district. Etrata followed without hesitation. They had gone about ten feet when Etrata grabbed Proft by the shoulder. He stopped, looking back at her. She gestured downward. He glanced at the ground. "Yes, the tripwire. I saw it," he said. "It's too obvious. There's probably—" "A pressure plate on the other side. I anticipated that." She threw up her hands. "Why am I trying so hard to keep you alive? Clearly, you don't need it." "No, but it's sweet of you." Proft turned, scanning the pipes until he found a break in the pattern. "This way. I believe we'll find our host in short order." They squeezed through the gap he'd spotted, following the series of bends on the other side until it opened into a larger chamber. There, hunched over a makeshift drafting desk and writing furiously, was a red viashino, facial scales reflecting the pallid light of the lantern on the desk's edge. "Hello, Kylox," said Proft. "You've looked better." Kylox's head jerked up, eyes widening behind their magnifying lenses. "Alquist!" he exclaimed, dropping his pen. Seen more closely, he obviously hadn't escaped the destruction of his workshop unscathed. He was missing several scales, his clothing was torn and disarrayed, and the short spikes atop his head looked as if they'd been brushed backward, creating a prickly hedgehog effect. "How did you 
?" he asked, then stopped. "Why am I asking? You'll have some nonsensical answer that ends with you here whether I want you here or not. What do you want?" "I found a substance I want you to analyze," said Proft, as calm as if this were a perfectly normal place to have a conversation about science. Kylox didn't appear to agree. He gaped at Proft. "Get out," he said. "What?" "Get out. No matter how many favors I owe you, I'm not doing this right now." He cast an anxious glance at the passage they'd come through. "Were you followed?" "No," said Etrata with certainty. "How did you get here?" "The door in your workshop," said Proft. "Really, Kylox, if you would just—" "How did you open that? Why—no, never mind." Kylox rose, gathering an armful of papers from the desk, tail swaying as he moved toward a small shelf jammed below a row of pipes. "I don't have the equipment here to do what you need, Proft. Go. I'll send a message when it's safe." "If you tell us what happened, perhaps we can help," said Proft. "You can't help," said Kylox, glancing around as he stacked his papers. Everything about the inventor radiated anxiety: the way he stood, the way he moved, the tenor of his voice. "I was working—I was working on something secret. Something no one was meant to know." "What sort of something?" asked Proft. Kylox whirled, exploding into motion. The spikes on his head rose in agitation. "No, no! Not you! I can't tell #emph[you] ! I can tell Ezrim. Only Ezrim. Can you get me to him without being seen? Is that within your power, oh great detective?" The way he spoke the words, they weren't praise. He turned them into a cutting insult, and Etrata glanced to Proft to see how the man would react. His expression hadn't changed, and didn't as the sound of footsteps echoed along the tunnels, racing toward their location. Kylox's eyes widened. "They're here," he moaned. Then, in a much softer voice, he commanded, "Leave me. #emph[Hide!] " Proft moved then, grabbing Etrata by the arm and pulling her with him across the room to a bank of unusually dense piping. He let her go to grab a section of the grid, pulling down and yanking it toward himself. It swung outward, and he jumped inside, Etrata close behind. When closed, the false wall of piping was solid, with only a few gaps through which they could see the room. They watched in silence as a group of goblins poured through another hidden passageway, surrounding Kylox, who flinched away from them. Proft tensed. The goblins produced thin lengths of mizzium chain, wrapping them around Kylox, who said nothing and only allowed himself to be taken. Proft slumped against the wall of their narrow hiding space. Etrata kept her eyes on the attack. Something moved in the corner, catching Proft's attention, and he glanced toward it, watching a spider creep down the wall and vanish back into shadow. When he looked back, the goblins were gone, and Kylox was gone with them. He frowned and gestured for Etrata to open the wall again. The two stepped back into the now abandoned chamber. "Do you allow all your friends to be taken captive like that?" demanded Etrata. "Kylox is a coward in many ways," said Proft, scanning the area. "He wouldn't have suggested we hide if he thought we could help him. We were well outnumbered. He doesn't know your capabilities, but by allowing himself to be taken, we can now follow and hopefully recover him. Come along." He strode across the room, heading for the entry the goblins had used. On the way, he paused by the shelf Kylox had been next to, just long enough to grab a small, unornamented wooden box and tuck it under his arm. Etrata frowned. He didn't pause, and in the end, she had to follow. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Being back on the busy streets of Ravnica was more of a relief than Kaya would have believed before visiting the moor outside of Vitu-Ghazi. Ravnica was supposed to be a place of constant sound and motion, life without end, even when it ended. Open spaces and green places were for Kaldheim and Dominaria, not for here. Not for the plane that had become her home. She knew these crowds. Even after everything, she knew these people, knew the way they moved and hurried from place to place 
 knew when something broke the pattern. The people behind them weren't moving the right way. She set a hand on Kellan's arm, guiding him toward the nearest alley. He started turning toward her, and she tightened her grip, still facing forward. "Say nothing," she said pleasantly. "We're being followed." Kellan blinked, letting her lead him away from the crowd. Once they were in the alley, they turned, waiting. It was a short wait. A group of six people in long, dark robes followed them, too quickly to have arrived by accident, and fanned out to surround the pair. One of them had a hefty hammer. Kaya frowned. "What is this?" she asked. "An ambush, or a staring contest?" The nearest robed figure lunged. Kaya danced back and kept moving as the other five joined the fray, all six attacking at once. Not in unison, but not in the convenient one-by-one pattern so many groups seemed to use, either. Three grabbed for Kaya, the other three lunging for Kellan. Kaya turned partially insubstantial, letting the first attacker charge right through her, his own momentum carrying him into the nearby wall. He impacted with a sickening crunch. #figure(image("006_Episode 6: Explosions of Genius/02.png.jpg", width: 100%), caption: [Art by: Durion], supplement: none, numbering: none) Drawing her daggers, Kaya focused on the others who had decided she was the better target, shifting her weight to her rear foot while she waited for them to come at her. They were both substantially larger than she was, making speed her best asset in this fight. Speed, and the ability to turn insubstantial. It was almost exhilarating, having something as straightforward as a simple alley brawl to worry about. She spun and wove, letting them reach for her, striking when they got too close. She dropped the first almost before the fight had been joined in earnest. The one with the hammer was down, felled by a blow to the back of the neck, before she had a chance to check on Kellan. Like her, he was down to his last opponent; the other two were on the ground, their faces pressed to the alley floor. Kellan had his swords drawn and was matching blade for blade with his remaining attacker, who held a pair of vicious-looking knives. Kaya kicked her remaining opponent, first in the knee, then in the groin. He folded like a broken ladder, and she kicked him in the head for good measure before she started toward Kellan. Then she stopped dead, blinking. Kellan had hooked his blades around the attacker's knives and disarmed him with expert skill, leaving the man looking helplessly around for something else he could use as a weapon. Before he could find it, Kellan slammed his shoulder into the man's chest, knocking him back. Kaya moved toward the man, who was at least still conscious, and wrapped one hand around his throat, spinning her dagger in the other hand as she pinned him to the wall, trapping one arm against his body. "Hello," she said. "We're your intended victims. You want to tell us why you came after us?" The man moved his free arm quickly enough that if he'd been holding another knife, he could have hurt her grievously. Instead, he shoved something that looked like a tiny green sprout into his mouth, triumph lighting up his eyes as he swallowed. "What was that?" Kaya demanded. "I don't know, but the ones on the ground just did the same thing," said Kellan. Kaya could only stare as the flesh of the man in front of her softened and turned green, growing plush as it transmuted into moss beneath her hand. Then he dissolved, moss scattering across the alley floor, leaving his empty robe to drop to the ground. Kaya danced backward with a wordless sound of disgust, shaking his remains from her fingers. They didn't stick, and no signs of the same transmutation marred her skin. Kellan was retching. Kaya turned to face him. All the other attackers had transformed into the same mossy scatter. Kellan bent forward, hands on his knees, and paused. "Kaya, come over here." "Why?" "Because I need you to see something." Careful not to step in the moss, Kaya moved to Kellan's side. He drew one of his bracers and stooped, shifting the cloak with the tip. "Look," he said. A tuft of white fur tipped in gray clung to the fabric. Kaya straightened, staring at him. Kellan did the same, nodding very slightly as he did. They were still staring at each other when an Agency thopter zipped into the alley. It flew to a stop between them before projecting a holo-message of Ezrim in his office, looking at them sternly. "Your recent altercation has been noted," it said. "Boros officers are on their way to your location. Secure the scene and return to headquarters." "Yes, sir," said Kellan automatically. The thopter zipped away as he pulled a pair of weighted ovals out of his pocket, gesturing for Kaya to step out of the alley as he affixed one to either side of the entrance. As soon as he let go, a ribbon of pure light extended between the two. "Agency barrier wards," said Kellan. "They'll let our investigators through, but no one else. Come on." Together, they moved down the street, moving through the crowds swiftly and without further challenge. The street outside the Agency headquarters was clear, the previous swarm of gossiping agents dissipated. Kaya still ducked behind Kellan as they climbed off their mounts and made for the doors, letting the actual, official agent precede her into the building. The ghost of Agrus Kos was waiting in the foyer. "The boss wants you," he said as they entered. "Says it's urgent. Doubly so for you, ma'am." He nodded to Kaya, a sympathetic look on his faintly translucent face. That was enough to tell Kaya what Ezrim had for her, and she hurried down the hall, leaving Kellan and Agrus Kos to follow. Ezrim's door was closed when she arrived. She didn't bother knocking but simply walked straight through. Ezrim was behind his desk. He looked up when she appeared, seemingly unsurprised by her entrance. "Thank you for coming so quickly," he said. "Though I have a door for a reason." There was a knock at the door. Ezrim glanced toward it. "Some people remember manners," he said. "Come in!" Kellan slipped into the room, Agrus Kos close behind. "You called for us?" "Yes." Ezrim returned his attention to Kaya. "Teysa's killer has been apprehended by the Azorius." Kaya's legs felt suddenly weak. She grabbed the edge of a bookshelf to hold herself up. "Sir?" "A low-level hitman, no guild affiliation," said Ezrim. "He swears he doesn't know what happened. One minute he was walking through the Eighth District, and the next, he was in Karlov Manor, covered in Teysa's blood. He ran. Someone saw him leaving the area, and the Azorius were called. They have him in custody." Kaya and Kellan were gaping at him when the door slammed open and Aurelia appeared, dragging a thrashing woman in Rakdos colors by the hair. The woman had been tied up, hands secured behind her back, but she fought like she thought she could break free. Aurelia half-threw her to the floor, wings spread in indignation. "She was coming for #emph[me] ," she snapped, voice cold as the grave. "She killed ten of my guards before I stopped her." "You #emph[cheated] ," snapped the woman. "Not supposed to bring wings to a ground fight. Naughty and nasty and not playing fair." Aurelia ignored her, absorbed in her own fury. "This is the one they call <NAME>, and her presence proves the Cult of Rakdos is behind all this senseless slaughter. We should have known. I'll gather the Legion, and we'll march—" If the Boros Legion marched to war against another guild with the city in such a delicate state of recovery, everything would collapse. The Dimir were missing, and the Golgari were in self-imposed exile. Ravnica couldn't afford to lose another guild. This might not be her home anymore. That didn't mean Kaya wanted to see the place burn. "Wait," said Kaya desperately. "Better listen, bird-lady," said Massacre Girl snidely. Kaya resisted the urge to kick her. "These agents have been to see Judith of the Rakdos and were returning to make their report," said Ezrim. "Agents?" Aurelia looked at Kaya quizzically, rage temporarily dimmed by confusion. "For this case," said Kaya. "I'm more neutral than many. Massacre Girl. Why did you attack the Boros warleader when you knew the possible consequences?" "I don't know," said Massacre Girl. "I don't remember anything before she was sweeping my legs out from under me and stepping on my chest. I didn't even get paid." Kaya turned back to Aurelia. "You see, this could be connected to the other attack. In both cases, the assailant didn't remember the act, or know to evade the aftermath. Warleader, we spoke to Judith, and she didn't have the demeanor of a guilty person. If anything, she was helpful. She directed us toward a lead, which we're presently investigating. Please, we need time before open accusations are made against another guild." "Even in the face of your own loss, you would press for patience," said Aurelia. "You would do the same, if you were thinking clearly," said <NAME>os. "Listen to her. She speaks sense." Aurelia frowned at him. "#emph[You] would advise #emph[me] ?" "You sent me to oversee. I'm overseeing." He looked at her calmly. "They need time." Aurelia closed her wings, still frowning. "Twenty-four hours, no more, and the assassin stays with us," she said. "If another prisoner is lost, heads will roll." #figure(image("006_Episode 6: Explosions of Genius/03.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "That's all we'll need," said Kaya with evident relief. Aurelia gathered her prisoner and her pride and swept away. As soon as she was gone, Kaya sagged. Kellan put out an arm to steady her. "It's fine," she said, waving him away. "Just 
 having a killer means this isn't a trick. Teysa's really gone." One more person she hadn't saved, one more friend she'd never see again—not in the same way. Teysa's ghost might come back, but that wouldn't undo the damage. Kaya rubbed her face with one hand. Being someone she cared about was starting to feel like a dangerous proposition. "We have twenty-four hours," she said, lowering her hand. "Let's get to work." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The goblins who had captured Kylox clearly hadn't realized anyone was watching; they made no effort to cover their tracks as they passed through the boilerpits to their own ladder to the street above. Proft and Etrata stayed back far enough not to be seen and followed them out into the early evening air. The kidnappers made no effort to hide their thrashing captive, either, but no one looked too closely or stopped to ask them what they were doing. Proft and Etrata continued to follow, not interfering, as the goblins carried Kylox to a disreputable-looking pawnshop. They exchanged a look then hurried to the store, stopping outside. Proft produced something that looked like a small trumpet from inside his jacket, pressing one end to his ear and the other to the glass. Etrata began to ask him a question. He waved her off then pressed a finger to his lips, signaling her to stay quiet. Inside, the familiar, faintly nasal voice of Krenko rang out clear and true: "What do you know?" "Nothing!" Kylox replied. "I'm not—I don't understand what you think I—" "The #emph[killings] , what do you know about the #emph[killings] ?" Krenko sniffed. "I know enough to know I'm at risk here. You're #emph[going] to tell me everything you know." Proft lowered the trumpet. "That sounded like a threat to me," he said, looking to Etrata. "Those guards, do you think you could take them?" Etrata looked mildly offended. "I'm a professional." "Excellent," Proft said and kicked the door open. Etrata surged into the room like a shadowy tide, Proft strolling along behind her. "That will be quite enough of that," he said mildly as Etrata disarmed the first of the goblin guards. Krenko squawked in surprise, moving so two more of his men could cover him, only to watch them go down as well. The Dimir assassin moved with restrained grace, and in moments, all six guards were on the ground, not moving. Etrata moved to start untying Kylox, while Proft focused on Krenko. "What," he asked, "are you doing?" "I—important people have been dying!" said Krenko. "#emph[I'm] important! I could be next! #emph[He] "—he indicated Kylox—"was talking about doing work for important people, but he wouldn't work for me! He might know something! He's #emph[going] to tell me!" "I did tell you," said Kylox, rubbing his wrists as he stood. "I don't know anything. Alquist, thank you. I hoped you'd understand what I was asking for." Proft didn't have time to respond before the window smashed in and a bulky man in laborer's clothes crashed into the room. He charged for Krenko, swinging a dagger—and ran into Kylox first. There was a strangled gasp as the viashino fell out of the way and slid, motionless, to the floor. Proft moved to his friend while Etrata slashed at the curled grip of the attacker, knocking the dagger loose. She jumped onto his back, then, and wrapped an arm around his throat. #figure(image("006_Episode 6: Explosions of Genius/04.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "Krenko, you useless pile, the chains!" she shouted. Surprise broke through Krenko's look of terror, and he hurried to get the chain that had been used to tie up Kylox, tossing it to Etrata. She squeezed the man's neck a little tighter, then slid down and began tying him up quickly, immobilizing him. When she turned, Proft was there, a bleak look on his face. "Kylox?" she asked. He shook his head. "I'm so sorry." "As am I." He stepped toward the attacker. "Why are you here?" The man didn't answer, only snarled at the cowering Krenko. Proft frowned. "His eyes aren't focused, Etrata," he said. "See?" "His pupils are too dilated," she said. "He's clearly intoxicated." "Perhaps 
" Proft glanced over his shoulder. "We need to break the fugue somehow." "Allow me," Etrata said and stepped in front of the man, locking her gaze on his own. There was no outward display of her psychic abilities, but he jerked back, pupils returning to a more normal state as he tried to recoil from her and the fear she had induced. "What am I doing here?" he demanded, nearly sounding panicked. "This isn't the florist. My husband's going to kill me!" "As I suspected." Proft turned to Etrata. "People are being brainwashed into these attacks. They can't be held responsible, as you can't. Someone is doing this. And I am #emph[going] to find out who."
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/appendix/questionnaire_answers.typ
typst
#import "@preview/tablex:0.0.5": tablex, cellx = Design Iteration One - Survey Results <design_iteration_one_survey_results> The design evaluation questionnaire (as described in @design_eval_questionnaire) was given to 7 students and exprienced programmers. These are the results: #let questionnaireResult( participant, participantDescription, answersPerConcept, generalComments: [] ) = { [=== Survey Results from #participant] // the heading_increase don't seem to affect this participantDescription for conceptAnswers in answersPerConcept { let (concept, meaningAnswer, lookAnswer, teachingAnswer, scalingAnswer, suggestionsAndComments) = conceptAnswers heading(level: 5, numbering: none, concept) // the heading_increase don't seem to affect this figure( tablex( columns: 2, stroke: .5pt, cellx(align: center + horizon)[*Question*], cellx(align: center + horizon)[*Answer*], cellx()[*Were you able to understand the meaning of the boxes and arrows?*], cellx(conceptAnswers.meaningAnswer), cellx()[*Do you find the concept nice to look at?*], cellx(conceptAnswers.lookAnswer), cellx()[*Could you imagine teaching functional programming using this vizualization?*], cellx(conceptAnswers.teachingAnswer), cellx()[*Could you imagine how the concept scales to more complex expressions?*], cellx(conceptAnswers.scalingAnswer), cellx()[*Do you have any suggestions for improvement or general comments on the concept?*], cellx(conceptAnswers.suggestionsAndComments), ), kind: "table", supplement: "Table", caption: "Design questionnaire answers for " + concept + " design from " + participant ) } if (generalComments != "") { heading(level: 5, numbering: none, "General Comments") generalComments } } #questionnaireResult( "Prof. Dr. <NAME>", "Prof. Dr. <NAME> is a lecturer at OST and advisor of this project.", ( ( concept: "Flo-inspired", meaningAnswer: "Not really. Semantics & the arrows are unclear (insertion or reverse result)", lookAnswer: "Not really.", teachingAnswer: "Not really. The arrows obsucre the denotational semantics.", scalingAnswer: "Yes. The arrows allow blocks to remain small.", suggestionsAndComments: "", ), ( concept: "Scratch-inspired", meaningAnswer: "Somewhat better than the Flo-inspired version.", lookAnswer: "Somewhat better than the Flo-inspired version.", teachingAnswer: "Somewhat better than the Flo-inspired version.", scalingAnswer: "Somewhat better than the Flo-inspired version.", suggestionsAndComments: "Without types, one has no guidance on which blocks fit where", ), ( concept: "Haskell Function-Notation inspired", meaningAnswer: "Better than the other two, but not quite there yet.", lookAnswer: "Better than the other two, but not quite there yet.", teachingAnswer: "Better than the other two, but not quite there yet.", scalingAnswer: "Better than the other two, but not quite there yet.", suggestionsAndComments: "", ) ), generalComments: [ The questionnaire may not do full justice to the visual programming methods since it only reviews the end state, and not the method of programming. All methods seem to have a "bottom-up" strategy on constructing programs (i.e. start with small steps with what is available, and tinker with it unit you come up with something that you can use). The imperative paradigm forces one to do this (top level blocks are always ";", and therefore uninteresting). In FP, we are able to design our programs "top-down", starting with a specification (type definition at least). This specification often admits a top-level function that is often interesting (e.g. filter, map), with further "holes" that can similarly be filled successively. It may be a good idea to design the VP tool around to support the method we want people to learn "how to design programs" (see "recipe for defining functions" & video on "Schreib dein program"). There are huge parallels between programming & constructing formal proofs (Curry-Howard-Lambek isomorphism) that can be a mental aid in designing such a tool - even if one does not immediately expose this to the beginner (please don't). The more I think about it, the more I am under the impression the VP tool and concept should support the existing recommended methodology and process of designing (functional) programs. This process has been quite well thought out, and does not need to be re-invented. What I feel is missing, when doing this in a textual form, is that the "visual model" of what this text should look like in the minds of the learners is not immediately visible. A visual tool can help learners build the correct visual model/intuition faster. Once this visual model/intuition is finally in place, the tool will often little benefit and become tedious to use. The users will then switch to the textual representation, but still always have the visual model in mind. ] ) #questionnaireResult( "<NAME>", "<NAME> is a scientific employee at the institute for software at OST", ( ( concept: "Flo-inspired", meaningAnswer: [ Mostly. I was first wondering why the arrow in the "Product of Numbers" example goes from the interim-result-ellipse 'Num a => a' to the argument slot of "(\*):apply", instead of the product-block as with all other cases where functions are passed as parameters. But then I realised that the result of the function call with xs is passed and not the function itself. ], lookAnswer: "No, too noisy.", teachingAnswer: "Perhaps, but only as an aid to show certain signatures of a partial expression, not in general to teach functional programming from the ground up.", scalingAnswer: "It'll get very complex very fast.", suggestionsAndComments: [ - Move type-signatures into the blocks instead of above them - Make type-signatures hideable - Option to switch between curried-interpretation and n-ary-function interpretation ] ), ( concept: "Scratch-inspired", meaningAnswer: "I think so.", lookAnswer: "Yes", teachingAnswer: "Yes, but I don't see an advantage compared to a pretty AST.", scalingAnswer: "It'll look like a mountain-skyline.", suggestionsAndComments: "Highlight which argument-instances belong to which argument-bindings when hovering over them.", ), ( concept: "Haskell Function-Notation inspired", meaningAnswer: "Mostly, but I'm not sure if I understood everything right.", lookAnswer: "Yes", teachingAnswer: "Perhaps, but only as an aid to show certain signatures of a partial expression, not in general to teach functional programming from the ground up.", scalingAnswer: "It would probably get complex too, but probably not as complex as the other two designs.", suggestionsAndComments: [ - Put the function-types next to the function name, so that there is no danger of confusing them. - Your approach for pattern-matching nicely shows that you don't have access to parts of a pattern that aren't named. But somehow the way it's visualized seems strange to me and is somewhat unsatisfying. But I don't know how to do it better. ] ) ), generalComments: [ I quite like the bock-arrow diagrams in "The state monad" in "Programming in Haskell" by <NAME> (second edition, chapter 12.3 Monads, pages 168 - 141). I don't know how well that approach generalises without overloading it like the Flo-inspired examples. In contrast to your examples the diagrams from the book show the data flow (but not how calls are plugged together syntactically). ] ) #questionnaireResult( "<NAME>", "<NAME> is a third-year software-development apprentice at Vontobel.", ( ( concept: "Flo-inspired", meaningAnswer: "No, but I assume that the squares are some kind of input?", lookAnswer: "If I understood this concept, I assume that I would've thought that it looked to complicated.", teachingAnswer: "", scalingAnswer: "", suggestionsAndComments: "" ), ( concept: "Scratch-inspired", meaningAnswer: "I think I understood this concept the most.", lookAnswer: "Yes", teachingAnswer: "Probably.", scalingAnswer: "I think complex expressions would take up a wide space and would be very complicated to understand.", suggestionsAndComments: "Keep the explanation (like in the first example) of the boxes (definition, declaration & parameters)", ), ( concept: "Haskell Function-Notation inspired", meaningAnswer: "No.", lookAnswer: "", teachingAnswer: "", scalingAnswer: "", suggestionsAndComments: "" ) ) ) #questionnaireResult( "<NAME>", "<NAME> is a student at OST and has visited the functional programming lecture.", ( ( concept: "Flo-inspired", meaningAnswer: "", lookAnswer: "No, very confusing with too many arrows and annotations.", teachingAnswer: "", scalingAnswer: "", suggestionsAndComments: "" ), ( concept: "Scratch-inspired", meaningAnswer: "", lookAnswer: "Yes", teachingAnswer: "", scalingAnswer: "", suggestionsAndComments: [ - No type-annotations, so it's difficult to tell what goes where - Type-Hole isn't intuitive - Operators should be treated like any other function ], ), ( concept: "Haskell Function-Notation inspired", meaningAnswer: "", lookAnswer: "Yes", teachingAnswer: "", scalingAnswer: "", suggestionsAndComments: "" ) ), generalComments: "It would be nice to have 'referential-transparency', i.e. hovering over a block to see the type of a specific argument." ) #questionnaireResult( "<NAME>", "<NAME> is a technical employee at the institute for software at OST", ( ( concept: "Flo-inspired", meaningAnswer: "I don't know Flo and for me it is not a very obvious notation. I can guess the semantics though.", lookAnswer: "It looks a bit cluttered to me.", teachingAnswer: "I think I would visualize it differently.", scalingAnswer: "It will probably clutter quite fast, I already find 'Product of Numbers' hard to read. I don't see a simple way to split it into multiple parts.", suggestionsAndComments: "Maybe multiple argument functions can have the argument in the same block instead of the :apply notation? I understand that this is to highlight currying, but I think you could also explain this by only highlighting the empty argument boxes. This would reduce clutter and make it more scalable." ), ( concept: "Scratch-inspired", meaningAnswer: "I find this quite easy to read. The only confusing bits I find are the type annotations (purple), especially because it mixes up constraints and types, but also because it could be interpreted as being part of the lower layer (i.e. in 'Map Add 5 Function' it could be interpreted as describing the (+) and not the 5).", lookAnswer: "Yes, it looks clean and colorful.", teachingAnswer: "Yes.", scalingAnswer: "It seems to clutter up less fast, and even then, it could be possible to split it up into multiple towers with references to each other (maybe when visualizing Haskell code, definitions in 'where' or in a let expression could be a separate tower, this would also solve the problem of multiple references.", suggestionsAndComments: [ - Type annotations: There could be a separate type annotation tower that can be enabled or disabled. Or it should be more obvious where the type annotation applies. At the moment it looks like the types are arguments to the function (which is actually the case in GHC Core or with the TypeApplications extension, but not in normal Haskell). Constraints should be ignored or handled differently. - Infix functions should look like +, not (+), if they are visualized in an infix way. ], ), ( concept: "Haskell Function-Notation inspired", meaningAnswer: "I find this one difficult to read. I especially have difficulty with the apparent mix-up of types and values. It seems that the last part of an arrow chain is the return type, and the rest is a value if present and a type if partially applied? I like the currying visualization with nested boxes though.", lookAnswer: "It looks more formal than Scratch-inspired, which to me is a disadvantage. It also has more text.", teachingAnswer: "No, I find it difficult to describe the semantics of single components. Maybe I'd be able to if you gave me an explanation of their meaning.", scalingAnswer: "I guess it would be possible to use cross references. It looks less cluttered than the Flo -inspired one.", suggestionsAndComments: "It seems like the single component semantics are not entirely consistent here." ) ), generalComments: [ - I think it is important to have clear and simple semantics for single components of your visualization. In order to ensure this, it may be useful to think about reduction rules for your visualization. - I like your use of color and how it distinguishes different things (types, value, arguments, ...) - Type polymorphism and constraints seems to be a challenge to visualize. For polymorphic types, TypeApplications may be a useful inspiration (i.e. receive types as a different kind of argument to functions). Constraints could maybe then be applied to these kinds of type arguments. Con of this approach is that in Haskell, you don't pass types as arguments. - Do you also plan on visualizing type definitions? - My vote is on a Scratch-inspired version. ] ) #questionnaireResult( "<NAME>", "<NAME> is a master student & scientific assistant at the institute for software at OST", ( ( concept: "Flo-inspired", meaningAnswer: [ Ja, ich bin mir jedoch nicht sicher, ob man es ohne Haskell Erfahrung versteht. Ausserdem hÀtte ich die Pfeile fÌrs VerstÀndnis eher von unten nach oben gemacht (siehe erste Box). Ich möchte nicht vom Resultat zurÌck gehen, sondern wende ein Argument nach dem anderen an und gelange am Schluss zum Resultat. (wenn man jedoch die Argumente im UI dann so hinziehen kann macht von unten nach oben mehr Sinn) ], lookAnswer: "GrundsÀtzlich ja, es wird jedoch schnell unÌbersichtlich. Es brÀuchte noch mehr Farbe und die Pfeile könnten je nach FunktionalitÀt unterschiedlich gestaltet werden.", teachingAnswer: "So wie es jetzt ist, eher nicht, da es zu unÌbersichtlich ist. Aber wenn es etwas ausgereifter ist, denke ich schon. Man kann es ja dann wahrscheinlich Schritt fÌr Schritt einblenden, bzw. zusammensetzen.", scalingAnswer: "Ich glaube es wird immer unÌbersichtlicher...", suggestionsAndComments: "Ich finde die Rekursion nicht so verstÀndlich. Man sieht nicht, dass product rekursiv aufgerufen wird. Ich hÀtte die match Box als noch mit product beschriftet und mit Farbe gearbeitet. Die ::Num a -> a Box verwirrt mich. Ausserdem fÀnde ich es besser die Applikation in einer Box zu machen" ), ( concept: "Scratch-inspired", meaningAnswer: "Ja, ich finde hier sieht man am besten, wie die Parameter in einander verschachtelt sind", lookAnswer: "Ja, die Farben sind mega gut fÌrs VerstÀndnis und es ist sehr Ìbersichtlich. Rein visuell der beste Vorschlag.", teachingAnswer: "Gut ist hier, dass man sieht wie man Schritt fÌr Schritt etwas einblenden könnte. Ich weiss jedoch nicht, ob es wirklich einen Mehrwert gegenÌber dem Code bietet... Bzw. Man sieht wie im Code die ZusammenhÀnge nicht ganz", scalingAnswer: "Ich könnte mir vorstellen, dass es schnell zu Ìberladen wird", suggestionsAndComments: [ - Type annotations: There could be a separate type annotation tower that can be enabled or disabled. Or it should be more obvious where the type annotation applies. At the moment it looks like the types are arguments to the function (which is actually the case in GHC Core or with the TypeApplications extension, but not in normal Haskell). Constraints should be ignored or handled differently. - Infix functions should look like +, not (+), if they are visualized in an infix way. ], ), ( concept: "Haskell Function-Notation inspired", meaningAnswer: "Ich finde es schlechter verstÀndlich als der erste Vorschlag. Ich könnte mir aber vorstellen, dass eine Kombination aus diesem und dem ersten funktionieren könnte.", lookAnswer: "Farben und Boxen finde ich gut und dass die Applikation und der Zusammenhang zwischen Argumenten und den Typen besser sichtbar ist. Aber es sieht irgendwie zu mathematisch aus :) Ich könnte mir vorstellen, dass das Personen abschrecken könnte", teachingAnswer: "So nicht unbedingt. Aber wenn man es mit dem ersten Vorschlag verbinden wÌrde, denke ich schon", scalingAnswer: "Ich glaube, es wird mega kompliziert mit der Verschachtelung. Ich finde die Pfeile beim ersten Vorschlag besser", suggestionsAndComments: "It seems like the single component semantics are not entirely consistent here." ) ), generalComments: [ #figure( image("../static/general_comments_eliane_schmidli_1.png") ) #figure( image("../static/general_comments_eliane_schmidli_2.png") ) ] ) #questionnaireResult( "<NAME>", "<NAME> is a scientific assistant at the institute for software at OST", ( ( concept: "Flo-inspired", meaningAnswer: "Mostly. It is confusing, that the input (e.g.) a and output (results) have the same arrow direction. It is not clear where to begin and how the data 'flows'", lookAnswer: "No. In my opinion it looks more complicated than the code", teachingAnswer: "No", scalingAnswer: "No. More complex would probably look more messy", suggestionsAndComments: "If grey boxes are type only, draw just a line or place it inside. But use no arrow" ), ( concept: "Scratch-inspired", meaningAnswer: "The match-case are where confusing to me. But the rest yes", lookAnswer: "Better than Flo. Cleaner and smaler. It has some structure visible", teachingAnswer: "Rather no", scalingAnswer: "Yes (at least better than the others)", suggestionsAndComments: "Maybe an other syntax for match-case to dinstinguish between functions names", ), ( concept: "Haskell Function-Notation inspired", meaningAnswer: "No", lookAnswer: "No, gets to big/messy soon", teachingAnswer: "No", scalingAnswer: "No, gets big very soon", suggestionsAndComments: "" ) ), generalComments: "Maybe something like a tree structure (similar to expression trees) that goes from top to bottom? It would may be some kind of mix between Flo and Scratch. Make a own symbol for match-cases (to distinguish from functions). Make sure it is tidy (same thing on same height level etc.)" ) #pagebreak()
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/linebreak-no-justifiables.typ
typst
Apache License 2.0
// Test breaking a line without justifiables. --- #set par(justify: true) #block(width: 1cm, fill: aqua, lorem(2))
https://github.com/HitZhouzhou/SecondYear_FirstSemester
https://raw.githubusercontent.com/HitZhouzhou/SecondYear_FirstSemester/main/algorithm/4homework/template.typ
typst
//--------------------------------------------------------------------- //-------------------------------need to modify------------------------ #let heiti = ("Noto Sans CJK SC", "Times New Roman") #let songti = ("Noto Serif CJK SC", "Times New Roman") #let mono = ("FiraCode Nerd Font Mono", "Sarasa Mono SC","Courier New", "Courier", "Noto Serif CJK SC") //--------------------------------------------------------------------- // some handly functions #let equation_num(_) = { locate(loc => { let chapt = counter(heading).at(loc).at(0) let c = counter("equation-chapter" + str(chapt)) let n = c.at(loc).at(0) "(" + str(chapt) + "-" + str(n + 1) + ")" }) } #let table_num(_) = { locate(loc => { let chapt = counter(heading).at(loc).at(0) let c = counter("table-chapter" + str(chapt)) let n = c.at(loc).at(0) str(chapt) + "-" + str(n + 1) }) } #let image_num(_) = { locate(loc => { let chapt = counter(heading).at(loc).at(0) let c = counter("image-chapter" + str(chapt)) let n = c.at(loc).at(0) str(chapt) + "-" + str(n + 1) }) } #let equation(equation, caption: "") = { figure( equation, caption: caption, supplement: [公匏], numbering: equation_num, kind: "equation", ) } #let tbl(tbl, caption: "") = { figure( tbl, caption: caption, supplement: [衚], numbering: table_num, kind: "table", ) } #let img(img, caption: "") = { figure( img, caption: caption, supplement: [囟], numbering: image_num, kind: "image", ) } #let empty_par() = { v(-1em) box() } #let project( logopath: "", subject: "", labname: "", kwargs: (), firstlineindent: 0em, body, ) = { // 匕甚的时候囟衚公匏等的 numbering 䌚有错误所以甚匕甚 element 手劚查 show ref: it => { if it.element != none and it.element.func() == figure { let el = it.element let loc = el.location() let chapt = counter(heading).at(loc).at(0) // 自劚跳蜬 link(loc)[#if el.kind == "image" or el.kind == "table" { // 每章有独立的计数噚 let num = counter(el.kind + "-chapter" + str(chapt)).at(loc).at(0) + 1 it.element.supplement " " str(chapt) "-" str(num) } else if el.kind == "equation" { // 公匏有 '(' ')' let num = counter(el.kind + "-chapter" + str(chapt)).at(loc).at(0) + 1 it.element.supplement " (" str(chapt) "-" str(num) ")" } else { it } ] } else { it } } // 囟衚公匏的排版 show figure: it => { set align(center) if it.kind == "image" { set text(font: heiti, size: 12pt) it.body it.supplement " " + it.counter.display(it.numbering) " " + it.caption locate(loc => { let chapt = counter(heading).at(loc).at(0) let c = counter("image-chapter" + str(chapt)) c.step() }) } else if it.kind == "table" { set text(font: songti, size: 12pt) it.body set text(font: heiti, size: 12pt) it.supplement " " + it.counter.display(it.numbering) " " + it.caption locate(loc => { let chapt = counter(heading).at(loc).at(0) let c = counter("table-chapter" + str(chapt)) c.step() }) } else if it.kind == "equation" { // 通过倧比䟋来蟟到䞭闎和靠右的排垃 grid( columns: (20fr, 1fr), it.body, align(center + horizon, it.counter.display(it.numbering) ) ) locate(loc => { let chapt = counter(heading).at(loc).at(0) let c = counter("equation-chapter" + str(chapt)) c.step() }) } else { it } } set page(paper: "a4", margin: ( top: 2.5cm, bottom: 2cm, left: 2cm, right: 2cm )) // 封面 align(center)[ #v(30pt) #image(logopath, width: 100%) #v(50pt) #text( size: 36pt, font: songti, weight: "bold" )[《#subject》#linebreak()#labname] #set align(bottom) #let info_value(body) = { rect( width: 100%, inset: 2pt, stroke: ( bottom: 1pt + black ), text( font: songti, size: 16pt, bottom-edge: "descender" )[ #body ] ) } #let info_key(body) = { rect(width: 100%, inset: 2pt, stroke: none, text( font: songti, size: 16pt, body )) } #let pair_into(pair) = { let (key, value) = pair (info_key(key + ":"), info_value(value)) } #grid( columns: (70pt, 240pt), rows: (40pt, 40pt), gutter: 3pt, ..kwargs.pairs().map(pair_into).flatten() ) ] counter(page).update(1) set page( header: { set text(font: songti, 10pt, baseline: 8pt, spacing: 3pt) set align(center) [《#subject》#labname] line(length: 100%, stroke: 0.7pt) }, footer: { set align(center) text(font: songti, 10pt, baseline: -3pt, counter(page).display("1")) // grid( // columns: (5fr, 1fr, 5fr), // line(length: 100%, stroke: 0.7pt), // text(font: songti, 10pt, baseline: -3pt, // counter(page).display("1") // ), // line(length: 100%, stroke: 0.7pt) // ) } ) set text(font: songti, 12pt) set par(justify: true, leading: 1.24em, first-line-indent: firstlineindent) show par: set block(spacing: 1.24em) // TODO // 目前先硬猖码 set heading( numbering: (..nums) => { let vars = nums.pos() if vars.len() == 1 { numbering("䞀、 ", vars.last()) } else { numbering("1. ", vars.last()) } }, ) show heading.where(level: 1): it => { // set align(center) set text(weight: "bold", font: heiti, size: 18pt) set block(spacing: 1.5em) it } show heading.where(level: 2): it => { set text(weight: "bold", font: heiti, size: 14pt) set block(above: 1.5em, below: 1.5em) it } // 銖段䞍猩进手劚加䞊 box show heading: it => { set text(weight: "bold", font: heiti, size: 12pt) set block(above: 1.5em, below: 1.5em) it } + empty_par() counter(page).update(1) // 行内代码 show raw.where(block: false): it => { set text(font: mono, 12pt) it } show raw.where(block: false): box.with( fill: rgb(217, 217, 217, 1), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt ) // 代码块 // 玧接着的段萜无猩进加入䞀䞪空行 show raw.where(block: true): it => { set text(font: mono, 10pt) set block(inset: 5pt, fill: rgb(217, 217, 217, 1), radius: 4pt, width: 100%) set par(leading: 0.62em, first-line-indent: 0em) it } + empty_par() // 无序列衚 show list: it => { it } + empty_par() // 有序列衚 show enum: it => { it } + empty_par() body }
https://github.com/csimide/SEU-Typst-Template
https://raw.githubusercontent.com/csimide/SEU-Typst-Template/master/README.md
markdown
MIT License
# 䞜南倧孊论文暡板 䜿甚 Typst 倍刻䞜南倧孊「本科毕䞚讟计论文报告」暡板和「研究生孊䜍论文」暡板。 请圚 [`init-files`](./init-files/) 目圕内查看 Demo PDF。 > [!IMPORTANT] > > 歀暡板是民闎暡板有䞍被孊校讀可的风险。 > > 本暡板虜已尜力尝试倍原原始 Word 暡板䜆可胜仍然存圚诞倚栌匏问题。 > > Typst 是䞀䞪仍圚掻跃匀发、可胜䌚有蟃倧变曎的排版工具请选择最新版暡板䞎本暡板建议的 Typst 版本盞配合䜿甚。 > [!CAUTION] > > 本暡板圚 [`0.2.2`](https://github.com/csimide/SEU-Typst-Template/tree/c44b5172178c0c2380b322e50931750e2d761168) -> `0.3.0` 时进行了砎坏性变曎。有关歀次变曎的诊细信息请查看[曎新日志](CHANGELOG.md) - [䞜南倧孊论文暡板](#䞜南倧孊论文暡板) - [䜿甚方法](#䜿甚方法) - [本地䜿甚](#本地䜿甚) - [Web App](#web-app) - [暡板内容](#暡板内容) - [研究生孊䜍论文暡板](#研究生孊䜍论文暡板) - [本科毕䞚讟计论文报告暡板](#本科毕䞚讟计论文报告暡板) - [目前存圚的问题](#目前存圚的问题) - [参考文献](#参考文献) - [友情铟接](#友情铟接) - [匀发䞎协议](#匀发䞎协议) - [二次匀发](#二次匀发) ## 䜿甚方法 本暡板需芁䜿甚 Typst 0.11.x 猖译。 歀暡板已䞊䌠 Typst Universe 可以䜿甚 `typst init` 功胜初始化也可以䜿甚 Web App 猖蟑。Typst Universe 䞊的暡板可胜䞍是最新版本。劂果需芁䜿甚最新版本的暡板从本 repo 䞭获取。 ### 本地䜿甚 请先安装䜍于 `fonts` 目圕内的党郚字䜓。然后悚可以䜿甚以䞋䞀种方匏䜿甚本暡板 - 䞋蜜/clone 本 repo 的党郚文件猖蟑 `init-files` 目圕内的瀺䟋文件。 - 䜿甚 `typst init @preview/cheda-seu-thesis:0.3.0` 来获取歀暡板䞎初始化文件。 随后悚可以通过猖蟑瀺䟋文件来生成想芁的论文。䞀种论文栌匏的诎明郜圚对应的瀺䟋文档内。 劂悚䜿甚 VSCode 䜜䞺猖蟑噚可以尝试䜿甚 [Tinymist](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp) 侎 [Typst Preview](https://marketplace.visualstudio.com/items?itemName=mgt19937.typst-preview) 插件。劂有本地包云同步需求可以䜿甚 [Typst Sync](https://marketplace.visualstudio.com/items?itemName=OrangeX4.vscode-typst-sync) 插件。曎倚猖蟑技巧可查阅 <https://github.com/nju-lug/modern-nju-thesis#vs-code-%E6%9C%AC%E5%9C%B0%E7%BC%96%E8%BE%91%E6%8E%A8%E8%8D%90> 。 ### Web App > [!NOTE] > > 由于字䜓原因䞍建议䜿甚 Web App 猖蟑歀暡板。 请打匀 <https://typst.app/universe/package/cheda-seu-thesis> 并点击 `Create project in app` 或圚 Web App 䞭选择 `Start from a template`再选择 `cheda-seu-thesis`。 然后请将 <https://github.com/csimide/SEU-Typst-Template/tree/master/fonts> 内的 **所有** 字䜓䞊䌠到 Typst Web App 内该项目的根目圕。泚意之后每次打匀歀项目浏览噚郜䌚花莹埈长时闎从 Typst Web App 的服务噚䞋蜜这䞀批字䜓䜓验蟃差。 最后请按照自劚打匀的文件的提瀺操䜜。 ## 暡板内容 ### 研究生孊䜍论文暡板 æ­€ Typst 暡板按照[《䞜南倧孊研究生孊䜍论文栌匏规定》](https://seugs.seu.edu.cn/2023/0424/c26669a442680/page.htm)制䜜制䜜时参考了 [SEUThesis 暡板](https://ctan.math.utah.edu/ctan/tex-archive/macros/latex/contrib/seuthesis/seuthesis.pdf)。 圓前支持进床 - 文档构件 - [x] 封面 - [x] 䞭英文扉页 - [x] 䞭英文摘芁 - [x] 目圕 - [x] 术语衚 - [x] 正文 - [x] 臎谢 - [x] 参考文献 - [x] 附圕 - [ ] 玢匕 - [ ] 䜜者简介 - [ ] 后记 - [ ] 封底 - 功胜 - [ ] 盲审 - [x] 页码猖号正文前䜿甚眗马数字正文及正文后䜿甚阿拉䌯数字 - [x] 正文、附圕囟衚猖号栌匏诊见研院芁求 - [x] 数孊公匏攟眮䜍眮犻页面巊䟧䞀䞪汉字距犻 - [x] 数孊公匏猖号公匏块右䞋 - [x] 插入空癜页新章节总圚奇数页䞊 - [x] 页眉奇数页星瀺章节号和章节标题偶数页星瀺固定内容 - [x] 参考文献支持双语星瀺 ### 本科毕䞚讟计论文报告暡板 æ­€ Typst 暡板基于䞜南倧孊本科毕䞚讟计论文报告暡板2024 幎 1 月仿制原暡板可以圚教务倄眑站䞊䞋蜜[2019 幎 9 月版](https://jwc.seu.edu.cn/2021/1108/c21686a389963/page.htm) , [2024 幎 1 月版](https://jwc.seu.edu.cn/2024/0117/c21686a479303/page.htm)。 圓前支持进床 - 文档构件 - [x] 封面 - [x] 䞭英文摘芁 - [x] 目圕 - [x] 正文 - [x] 参考文献 - [x] 附圕 - [x] 臎谢 - [ ] 封底 - 功胜 - [ ] 盲审 - [x] 页码猖号正文前䜿甚眗马数字正文及正文后䜿甚阿拉䌯数字 - [x] 正文、附圕囟衚猖号栌匏诊见本科毕讟芁求 - [x] 数孊公匏攟眮䜍眮犻页面巊䟧䞀䞪汉字距犻 - [x] 数孊公匏猖号公匏块右䟧䞭心 - [x] 页眉星瀺固定内容 - [x] 参考文献支持双语星瀺 - [ ] ~~衚栌星瀺“续衚”~~ 由于教务倄提䟛的暡板䞭没有给出“续衚”星瀺样䟋故暂䞍实现。 > [!NOTE] > > 可以看看隔壁 <https://github.com/TideDra/seu-thesis-typst/> 项目也正圚䜿甚 Typst 实现毕䞚讟计论文报告暡板还提䟛了毕讟翻译暡板。该项目的实现细节䞎本暡板并䞍盞同悚可以根据自己的喜奜选择。 ## 目前存圚的问题 - 䞭文銖段有时䌚自劚猩进有时䞍䌚。劂果没有自劚猩进需芁䜿甚 `#h(2em)` 手劚猩进䞀䞪字笊。 - 参考文献栌匏䞍完党笊合芁求。请见䞋方参考文献小节。 - 行距、蟹距等有埅继续调敎。 ### 参考文献 参考文献栌匏䞍完党笊合芁求。Typst 自垊的 GB/T 7714-2015 numeric 栌匏䞎孊校芁求栌匏盞比有以䞋问题 1. 孊校芁求圚䜜者数量蟃倚时英文䜿甚 `et al.` 䞭文䜿甚 `等` 来省略。䜆是Typst 目前仅可以星瀺䞺单䞀语蚀。 **A:** 该问题系 Typst 的 CSL 解析噚䞍支持 CSL-M 富臎的。 <details> <summary> 诊细原因 </summary> - 䜿甚 CSL 实现这䞀 feature 需芁甚到 [CSL-M](https://citeproc-js.readthedocs.io/en/latest/csl-m/index.html#cs-layout-extension) 扩展的倚 `layout` 功胜而 Typst 尚䞍支持 CSL-M 扩展功胜。诊见 https://github.com/typst/typst/issues/2793 侎 https://github.com/typst/citationberg/issues/5 。 - Typst 目前䌚応视 BibTeX/CSL 侭的 `language` 字段。参见 https://github.com/typst/hayagriva/pull/126 。 因䞺䞊述原因目前埈隟䜿甚 Typst 原生方法实现根据语蚀自劚选甚 `et al.` 侎 `等`。 </details> OrangeX4 和我写了䞀䞪基于查扟替换的 `bilingual-bibliography` 功胜试囟圚 Typst 支持 CSL-M 前实现䞭文西文䜿甚䞍同的关键词。 本暡板的 Demo 文档内已䜿甚 `bilingual-bibliography` 匕甚请查看 Demo 文档以了解甚法。泚意该功胜仍圚测试埈可胜有 Bug诊见 https://github.com/csimide/SEU-Typst-Template/issues/1 。 > 请圚 https://github.com/nju-lug/modern-nju-thesis/issues/3 查看曎倚有关双语参考文献实现的讚论。 > > 本暡板曟经尝试䜿甚 https://github.com/csimide/cslper 䜜䞺双语参考文献的实现方法。 2. 孊校给出的范䟋䞭陀了纯电子资源即䜿匕甚文献来自线䞊枠道也均䞍加 `OL`、访问日期、DOI 侎 铟接。䜆是Typst 内眮的 GB/T 7714-2015 numeric 栌匏䌚䞺所有 bib 内定义了铟接/DOI 的文献添加 `OL` 标记和铟接/DOI 。 **A:** 该问题系孊校的标准䞎 GB/T 7714-2015 䞍完党䞀臎富臎的。 请䜿甚 `style: "./seu-thesis/gb-t-7714-2015-numeric-seu.csl"` 䌚自劚䟝据文献类型选择是吊星瀺 `OL` 标记和铟接/DOI。 > 该 csl 修改自 <https://github.com/redleafnew/Chinese-STD-GB-T-7714-related-csl/blob/main/003gb-t-7714-2015-numeric-bilingual-no-url-doi.csl> > > 原文件基于 CC-BY-SA 3.0 协议共享。 3. 䜜者倧小写或者其他细节䞎孊校范䟋䞍䞀臎。 4. 孊䜍论文䞭孊校芁求匕甚其他孊䜍论文的文献类型应圓写䜜 `[D]: [博士孊䜍论文].` 栌匏䜆暡板星瀺䞺 `[D]` 䞍星瀺子类别。 5. 孊䜍论文䞭孊校给出的范䟋䜿甚党角笊号劂党角方括号、党角句点等。 6. 匕甚条目䞢倱 `. ` 劂 `[M]2nd ed`。 **3~6 A:** 孊校甚的是 GB/T 7714-2015 的方蚀曟经有孊长把它叫做 GB/T 7714-SEU 目前没扟到完矎匹配孊校芁求的 CSL䞍同孊院的芁求也䞍倪䞀样后续䌚写䞀䞪笊合芁求的 CSL 文件。 **2024-05-02 曎新:** 现已初步实现 CSL。䞍埗䞍诎 Typst 的 CSL 支持成谜  目前修倍情况劂䞋 - 问题 3 已修倍 - 问题 4 圚孊䜍论文的 CSL 内已修倍䜆 Typst 䌌乎䞍支持这䞀字段因歀无法星瀺 - 问题 5 䞍准倇修倍查阅数篇已发衚的孊䜍论文䜿甚的也是半角笊号 - 问题 6 䌌乎是 Typst 的 CSL 支持的问题本暡板附垊的 CSL 文件已经做了额倖倄理应该䞍䌚䞢 `. ` 了。 7. 匕甚其他孊䜍论文时GB7714-2015/本科毕讟/孊䜍论文均芁求泚明 `地点: 孊校名称, 幎仜.` 。䜆是暡板䞍星瀺这䞀项。 **A:** Typst 䞍支持 `school` `institution` 䜜䞺 `publisher` 的别名亊䞍支持解析 csl 侭的 `institution`  https://github.com/typst/hayagriva/issues/112 。劂需修倍请手劚修改 bib 文件内对应条目圚 `school = {孊校名称},` 䞋加䞀行 `publisher = {孊校名称},` 。 <details> <summary> 修改瀺䟋 </summary> ```biblatex @phdthesis{Example1, type = {{硕士孊䜍论文}}, title = {{摞鱌背景䞋的Typst暡板䜿甚研究}}, author = {<NAME>}, year = {2024}, langid = {chinese}, address = {南京}, school = {䞜南倧孊}, publisher = {䞜南倧孊}, } ``` </details> 8. 正文䞭连续匕甚䞊标合并错误䟋劂匕甚 1 2 3 4 应圓星瀺䞺 [1-4] 䜆是星瀺䞺 [1,4] 。 **A:** 䞎时方案是把 csl 文件里 `after-collapse-delimiter=","` 改成 `after-collapse-delimiter="-"`。本暡板附垊的 CSL 文件已做歀修改。 诊细原因请见 https://github.com/typst/hayagriva/issues/154 。 https://github.com/typst/hayagriva/pull/176 正尝试解决这䞀 bug。**该 bug 修倍后请及时撀销䞊述对 csl 的䞎时修改。** ## 友情铟接 - Typst Touying 䞜南倧孊䞻题幻灯片暡板 by QuadnucYard - https://github.com/QuadnucYard/touying-theme-seu - 䞜南倧孊 Typst 本科毕讟暡板䞎毕讟翻译暡板 by Geary.Z (TideDra) - https://github.com/TideDra/seu-thesis-typst ## 匀发䞎协议 劂果悚圚䜿甚过皋䞭遇到任䜕问题请提亀 issue。本项目欢迎悚的 PR。劂果有其他暡板需求也可以圚 issue 䞭提出。 陀䞋述特殊诎明的文件倖歀项目䜿甚 MIT License 。 - `init-files/demo_image/` 路埄䞋的文件来自䞜南倧孊教务倄本科毕讟暡板。 - `seu-thesis/assets/` 路埄䞋的文件是由䞜南倧孊教务倄暡板经二次加工埗到或从䞜南倧孊视觉讟计䞭取埗。 - `fonts` 路埄䞋的文件是歀暡板甚到的字䜓。 - `䞜南倧孊本科毕䞚讟计论文参考暡板 (2024幎1月修订).docx` 是教务倄提䟛的毕讟论文暡板。 ### 二次匀发 本暡板欢迎二次匀发。圚二次匀发前建议了解本暡板的䞻芁特性䞎关联的文件 - 有蟃䞺麻烊的囟衚、公匏猖号囟衚猖号栌匏䞍盞同甚至附圕䞎正文䞭囟衚猖号栌匏也䞍盞同囟的名称圚囟䞋方衚的名称圚衚䞊方公匏䞍是居䞭对霐公匏猖号䜍眮䞍是右䟧䞊䞋居䞭。 - 已经改甚 `i-figured` 包完成。 - 仅研究生孊䜍论文奇数页偶数页页眉䞍同䞔有页眉䞭星瀺章节名称的需求。 - 该功胜䜍于 `seu-thesis/parts/main-body-degree-fn.typ`。 - 掚荐改甚 `chic-hdr` 而䞍是自造蜮子由于历史遗留问题本暡板暂未改甚。 - 支持双语星瀺参考文献自劚䜿甚 `et al.` 和 `等` - 该功胜来自 `bilingual-bibliography`关联的文件是 `seu-thesis/utils/bilingual-bibliography.typ`。 - 有关 `bilingual-bibliography` 的曎倚信息请查看 https://github.com/nju-lug/modern-nju-thesis/issues/3 > [!NOTE] > > 本暡板内造的蜮子比蟃倚而䞔我的代码莚量䞀般请酌情取甚。
https://github.com/katamyra/Notes
https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS1332/Modules/BasicSorts.typ
typst
#import "../../../template.typ": * = Basic Sorts == Insertion Sort #theorem[ At iteration j, everything before index j is sorted. "Insert" the item at index j into the sorted array from 0 to j - 1 by swapping leftwards. ] For insertion sort, we basically create a sub array starting from the front of the main array that is always sorted. Then for each element, we place it into its correct location in the sorted subarray. #note[ For *stability*, do not swap items with the same value! Example: #let values = (2, 4, 6, 8, 6) #values When at the second 6, we will swap it iwth 8, instead of 6 in order to main stability. Another note: In insertion sort, before the last iteration, it is possible that none of the items are in their final position. ] #theorem[ *Time Complexity* *Best*: Already sorted: O(n) - This is because we still need to look at every data item to make sure everything is in order. *Worst*: Reverse sorted order: O(n^2) - Each element needs to be swapped all the way to the front (aka moving it the maximum distance). ] == Selection Sort #theorem[ For each index in the array, find the largest/smallest item in the unsorted part of the array, and then place it into that position repeatedly until sorted. ] In this case, each element is being placed into its final spot in the array. This is different from selection sort where we cant guaruntee anything is in its correct spot until the end. #theorem[ *Time Complexity* *Best*: $O(n^2)$ *Worst*: $O(n^2)$ ]
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/dynamic/complex.md
markdown
# Complex display rules There are multiple options to define more complex display rules than a single number. ### Array The simplest extension is to use an array. For example ```typ {{#include rule-array.typ:5:}} ``` results in: ![rule-array](rule-array.png) The array elements can actually themselves be any kind of rule that is explained on this page. ### Interval You can also provide a (bounded or half-bounded) interval in the form of a dictionary with a `beginning` and/or an `until` key: ```typ {{#include rule-interval.typ:5:}} ``` results in: ![rule-interval](rule-interval.png) In the last case, you would not need to use `#only` anyways, obviously. ### Convenient syntax as strings In principle, you can specify every rule using numbers, arrays, and intervals. However, consider having to write ```typ #uncover(((until: 2), 4, (beginning: 6, until: 8), (beginning: 10)))[polylux] ``` That's only fun the first time. Therefore, we provide a convenient alternative. You can equivalently write: ```typ {{#include rule-string.typ:6}} ``` which results in: ![rule-string](rule-string.png) Much better, right? The spaces are optional, so just use them if you find it more readable. Unless you are creating those function calls programmaticly, it is a good recommendation to use the single-number syntax (`#only(1)[...]`) if that suffices and the string syntax for any more complex use case.
https://github.com/typst-community/mantodea
https://raw.githubusercontent.com/typst-community/mantodea/main/src/style.typ
typst
MIT License
#import "_pkg.typ" #import "_valid.typ" #import "theme.typ" as _theme /// The default style applied over the whole document. /// /// - theme (theme): The theme to use for the document styling. /// -> function #let default( theme: _theme.default, _validate: true, ) = body => { let theme = theme if _validate { import _valid as z theme = z.parse(theme, _theme.schema(), scope: ("theme",)) } set page( numbering: "1", header: context { let section = _pkg.hydra.hydra(2, display: (_, it) => { numbering("1.1", ..counter(heading).at(it.location()).slice(1)) [ ] it.body }) align(center, emph(section)) }, ) set text(12pt, font: theme.fonts.text, lang: "en") set par(justify: true) set heading(numbering: "I.1.") show heading: it => { let scale = if it.level == 1 { 1.8 } else if it.level == 2 { 1.4 } else if it.level == 3 { 1.2 } else { 1.0 } let size = 1em * scale; let above = if it.level == 1 { 1.8em } else { 1.44em } / scale; let below = 0.75em / scale; set text(size, font: theme.fonts.headings) set block(above: above, below: below) if it.level == 1 { pagebreak(weak: true) block({ if it.numbering != none { text(fill: theme.colors.primary, { [Part ] counter(heading).display() }) linebreak() } it.body }) } else { block({ if it.numbering != none { text(fill: theme.colors.primary, counter(heading).display()) [ ] } it.body }) } } show raw: set text(9pt, font: theme.fonts.code) show figure.where(kind: raw): set block(breakable: true) body }
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/7e1810-algo_hw/hw3.typ
typst
#import "utils.typ": * == HW 3 (Week 4) Due: 2024.03.31 #rev1_note[ + Review: 二叉树 遍历方匏: 先序遍历, 䞭序遍历, 后序遍历. + Review: 二叉搜玢树 - 二叉搜玢树是䞀种二叉树, 其䞭每䞪节点 $x$ 郜有䞀䞪关键字 $"key"[x]$ 以及䞀䞪指向 $x$ 的父节点的指针 $p[x]$, 以及指向巊右孩子的指针 $"left"[x]$ 和 $"right"[x]$. 二叉搜玢树性莚: + 对于任意节点 $x$, 其巊子树䞭的*所有*关键字的倌郜小于 $"key"[x]$. + 对于任意节点 $x$, 其右子树䞭的*所有*关键字的倌郜倧于 $"key"[x]$. - 二叉搜玢树的䞭序遍历是䞀䞪有序序列. 歀倖, 通过䞀颗二叉搜玢树的先序/后序遍历结果, 可以反掚出这颗树的结构. 䜆是通过䞭序遍历结果无法唯䞀确定䞀颗二叉树. - 前驱的搜玢逻蟑: - 劂果巊节点䞍䞺空, 那么只需芁搜玢巊节点的最倧倌(尜可胜的向右、向䞋遍历) - 劂果巊节点䞺空, 向䞊扟到第䞀䞪向巊的 parent , 也就是诎对这䞪 parent 来诎, 圓前节点是右孩子. 劂果是巊孩子的话那就持续向䞊遍历. - 返回最后䞀䞪父节点. 劂果到根郚䟝旧䞍存圚向巊的 parent, 那么只胜诎明最匀始的节点已经倄圚敎棵树的巊䞋角, 它没有前驱, 返回空. + Review: 红黑树 圚 BST 的基础䞊增加 color 字段, 取倌䞺红或黑. 红黑树的性莚: - 每䞪节点或者是红色, 或者是黑色. - 根节点是黑色. - 每䞪叶子节点是黑色.(空节点) - 劂果䞀䞪节点是红色, 则它的䞀䞪子节点郜是黑色. - 对于每䞪节点, 从该节点到其所有后代叶子节点的简单路埄䞊, 各䞪颜色的节点数目盞同. (黑高盞同) + Review: 逆序对 $ \#{(i,j) | i < j quad and quad A[i] > A[j]} $ + Review: 区闎树 我们对红黑树的结构进行扩匠来存傚䞀组区闎, $A^((i))=[t^((i))_1, t^((i))_2]$. 䞎实数䞀样, 区闎有着䞉分埋, 即对于䞀䞪区闎 $A, B$ 来诎, 芁么 $A sect B != emptyset$, 芁么 $A$ 圚 $B$ 的巊䟧/右䟧, 这䞉种情况互斥. 区闎树的䜿甚巊端点 (䜎端点) 䜜䞺排序的 key (关键字), 并䞔额倖绎技䞀䞪 $x.max$, 代衚圓前节点对应的子树䞭, 所有区闎的右端点 (高端点) 的最倧倌, 构建方匏类䌌蜬移方皋, 绎技方匏只需芁向䞊曎新, 郜䞍超过䞀般红黑树的倍杂床. ] === Question 12.2-3 Write the `TREE-PREDECESSOR` procedure(which is symmetric to `TREE-SUCCESSOR`). #ans[ ```txt TREE-PREDECESSOR(x) if x.left != nil return TREE-MAXIMUM(x.left) y = x.p while y != nil and x == y.left x = y y = y.p return y ``` ] === Question 13.1-5 Show that the longest simple path from a node $x$ in red-black tree to a descendant leaf at most twice that of the shortest simple path from node $x$ to a descendant leaf. #rev1_note[ 证明从红黑树节点 $x$ 到叶子节点的最长简单路埄长床至倚是最短简单路埄长床的䞀倍. 䞋面这䞪答案实际䞊诎明: 任意䞀条路埄的黑高盞同, 红色节点由于䞀定存圚黑色的子节点, 那么红色节点的数量也䞍倧于黑高. 最短路埄䞍小于黑高, 最长路埄䞍倧于二倍黑高, 埗证. ] #ans[ Consider the longest simple path $(a_1, ... ,a_s)$ & the shortest simple path $(b_1, ... ,b_t)$, they have equal number of black nodes (Property 5). Neither of the paths can have repeated red node (Property 4). Thus at most $floor((s - 1) / 2)$ of the nodes in the longest path are red, so $ t >= ceil((s+1)/2) $ If by way of contradiction, we had $s > t dot 2$, then $ t >= ceil((s+1) / 2) >= ceil(t+1) = t+1 $ which is a contradiction. ] === Question 17.1-7 Show how to use an order-statistic tree to count the number of inversions in an array of $n$ distinct elements in $O(n lg n)$ time. #rev1_note[ 考虑按照劂䞋方匏去重计算: $ "Inv"(j)=\#{(i,j) | i < j quad and quad A[i] > A[j]}\ "TotalInv" = sum_(j=1)^(n) "Inv"(j) $ 按照这样的思路, $"Inv"(j)$只䟝赖前 $A[1:j]$ 序列䞭元玠, 具䜓的诎, $"Inv"(j)$ 只跟 $A[j]$ 圚 $A[1:j]$ 的排名盞关, 记䜜 $r(j)$. 那么我们有: $ "Inv"(j) = j - r(j) >=0 $ 这样的思路䞎插入排序的思路是䞀臎的, 圓 $A[1:j-1]$ 已经是有序数组时, $A[j]$ 新的插入䜍眮 ($r(j)$) 意味着䞎 $j - r(j)$ 䞪元玠亀换了䜍眮, 即䞺向前的逆序数. 每次插入时闎和查询䜍眮时闎所甚时闎郜是 $O(log k)$. 总甚时 $O(log n!)=O(n log n)$ ] #ans[ $O(n lg(n))$ time is required to build a red-black treem so everytime we insert a node, we can calculate the number of inversion using $"OS-RANK"$ (which is the rank of the node, thus calculating inversions). ] === Question 17.3-2 Describe an efficient algorithm that, given an interval $i$, returns an interval overlapping $i$ that has the minimum low endpoint, or $T."nil"$ if no such interval exists. #ans[ Modify the usual interval search not to break out the loop when a overlap is found, but to keep track of the minimum low endpoint. Return the interval with the minimum low endpoint if found, otherwise return $T."nil"$. ]
https://github.com/leiserfg/fervojo
https://raw.githubusercontent.com/leiserfg/fervojo/master/typst-package/examples/simple.typ
typst
MIT License
#import "@preview/fervojo:0.1.0": * = The rendered svg #render(``` {[`select-stmt` ["WITH" <!, "RECURSIVE"> 'common-table-expression'*","]?#`Common table expressions`], <{[["SELECT" <!, "DISTINCT", "ALL"> 'result-column'*","]#`Projection clause` ["FROM" <'table-or-subquery'*",", 'join-clause'>]?#`From clause`], [["WHERE" 'expr']?#`Where clause` ["GROUP" "BY" 'expr'*"," ["HAVING" 'expr']?]?#`Grouping`] }#`Single SELECT`, ["VALUES" ["(" 'expr'*"," ")"]*","]#`Literal values` >*['compound-operator'#[`E.g. "SELECT` "UNION" `SELECT"`]]#`Compounded SELECT`, [["ORDER" "BY" 'ordering-item'*","]?#`Ordering` ["LIMIT" 'expr' <!, ["OFFSET"? 'expr']>]?#`Limiting`] } ```) = The default.css #text(str(default-css()))
https://github.com/sitandr/typst-examples-book
https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/packages/code.md
markdown
MIT License
# Code ## `codly` > See docs [there](https://github.com/Dherse/codly) ``````typ #import "@preview/codly:0.1.0": codly-init, codly, disable-codly #show: codly-init.with() #codly(languages: ( typst: (name: "Typst", color: rgb("#41A241"), icon: none), ), breakable: false ) ```typst #import "@preview/codly:0.1.0": codly-init #show: codly-init.with() ``` // Still formatted! ```rust pub fn main() { println!("Hello, world!"); } ``` #disable-codly() `````` ## Codelst ``````typ #import "@preview/codelst:2.0.0": sourcecode #sourcecode[```typ #show "ArtosFlow": name => box[ #box(image( "logo.svg", height: 0.7em, )) #name ] This report is embedded in the ArtosFlow project. ArtosFlow is a project of the Artos Institute. ```] ``````
https://github.com/maxi0604/typst-builder
https://raw.githubusercontent.com/maxi0604/typst-builder/main/example.typ
typst
MIT License
For example, you could have files on the root directory.
https://github.com/EricWay1024/Homological-Algebra-Notes
https://raw.githubusercontent.com/EricWay1024/Homological-Algebra-Notes/master/ha/2-ab.typ
typst
#import "../libs/template.typ": * = Abelian Categories <ab-cat> == $Ab$-enriched Categories We have seen, for example, that in $veck$ every hom-set not only is a collection (or set) of morphisms but also has some "additional structures", i.e., a vector space. This leads to the idea of enriched categories, where enriching means equipping the hom-sets with "additional structures". The following is an instance where every hom-set is an abelian group. #definition[ We call a category $cC$ *$Ab$-enriched* if every $Hom(C)(X, Y)$ is a abelian group, subject to bilinear morphism composition, namely $ (f + g) compose h = f compose h + g compose h quad "and" quad f compose (k + h) = f compose k + f compose h $ for all $f, g : Y-> Z$ and $h, k : X->Y$. ] #remark[ An equivalent way to put the bilinearity is the following: the composition mappings $ c_(X Y Z): Hom(C)(X, Y) times Hom(C)(Y, Z) -> Hom(C)(X, Z), quad (f, g) mapsto g oo f $ are group homomorphisms in each variable @borceux[Definition 1.2.1]. ] // The abelian group structure on hom-sets means that we are allowed to add two morphisms (as above) in $Hom(C)(X, Y)$. #definition[ Let $cC$ be an $Ab$-enriched category and $X, Y in cC$. The *zero morphism* $0 in Hom(C)(X, Y)$ is defined as the identity of the abelian group $Hom(C) (X, Y)$. ] However, note that an $Ab$-enriched category needs not have a zero object, so this is actually a redefinition of a zero morphism from @zero-factor. We will see later that the two definitions match when the zero object is present. Since group homomorphisms map identity to identity, we have the following: #proposition[ In an *Ab*-enriched category, let $X->^g Y->^f Z->^h W$. If $f$ is a zero morphism, then $f oo g$ and $h oo f$ are zero morphisms. ] <zero-composition> #endlec(3) We can also define functors between $Ab$-enriched categories which respect the abelian group structures of the hom-set: #definition[ If $cC, cD$ are $Ab$-enriched, we call $F : cC -> cD$ an *additive functor* if $ Hom(C)(X, Y) -> Hom(D)(F(X), F(Y)) $ is a group homomorphism for any $X, Y in cC$. ] #proposition[ If $cC$ is an *Ab*-enriched category, then so is $cC^op$. ] #proof[ The definition is self-dual. Namely, reversing all the arrows in $cC$ breaks neither the group structure on hom-sets nor the bilinear morphism composition. ] An $Ab$-enriched category needs not have a zero object. Nevertheless, once it has an initial or final object, it has a zero object, as shown below. #proposition[Let $*$ be an object in an *Ab*-enriched category, then the followings are equivalent: + $*$ is a final object; + $*$ is an initial object; + $*$ is a zero object. ] <ab-zero> #proof[ (3) $=>$ (1) and (3) $=>$ (2) is obvious. We only prove (1) $=>$ (3), and (2) $=>$ (3) follows from duality. Suppose $*$ is a terminal object and let $id_* : * -> *$ be the unique morphism in the abelian group of $Hom(C)(*, *)$, and so $id_* = 0$. For any object $A$ and $f : * -> A$ (because $Hom(C)(*, A) $ contains at least the zero morphism), we have $ f = f compose id_* = f compose 0 = 0 in Hom(C)(*, A). $ So there is a unique morphism from $*$ to $A$ and therefore $*$ is also initial. ] // This also includes the case of the empty product and coprodut, namely any final object is initial and thus zero. In fact, a final object is an empty product and an initial object an empty coproduct, and the previous result can be generalised. #proposition[ In an *Ab*-enriched category $cC$, let $X_1, X_2$ be two objects. Then + If the product $X_1 times X_2$ exists, then the coproduct $X_1 union.sq X_2$ also exists and is isomorphic to $X_1 times X_2$; + If the coproduct $X_1 union.sq X_2$ exists, then the product $X_1 times X_2$ also exists and is isomorphic to $X_1 union.sq X_2$. ] <ab-product> #proof[@notes[Proposition 3.7] // , @li[Theorem 3.4.9] and @borceux[Proposition 1.2.4]. We prove statement (1) and leave (2) to duality. Suppose the product $X_1 times X_2$ exists with projections $p_k colon X_1 times X_2 arrow.r X_k$. By definition of products, there are unique morphisms $i_k colon X_k arrow.r X_1 times X_2$ such that the following diagrams commute. // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBpiBdUkANwEMAbAVxiRAA0B9YgAjwFt4PLgCYQAX1LpMufIRQAGclVqMWbLsQlSQGbHgJERy6vWatEHTmMnT9cokoUqz6y5u13ZhlMZEu1CysbFRgoAHN4IlAAMwAnCH4kJRAcCCRiWxB4xOT<KEY> #align(center, commutative-diagram( node-padding: (80pt, 50pt), node((1, 1), [$X_1 times X_2$]), node((1, 0), [$X_1$]), node((1, 2), [$X_2$]), node((0, 0), [$X_1$]), node((2, 2), [$X_2$]), arr((1, 1), (1, 0), [$p_1$], label-pos: -1em), arr((1, 1), (1, 2), [$p_2$]), arr((0, 0), (1, 0), [$id_(X_1)$]), arr((0, 0), (1, 2), [$0$], curve: 30deg), arr((0, 0), (1, 1), [$exists ! i_1$], label-pos: 1em, "dashed"), arr((2, 2), (1, 2), [$id_(X_2)$], label-pos: -1.5em), arr((2, 2), (1, 0), [$0$], label-pos: -1em, curve: 30deg), arr((2, 2), (1, 1), [$exists ! i_2$], label-pos: -1em, "dashed"), )) Explicitly, we have for $j, k in {1, 2}$, $ p_j oo i_k = cases(id_(X_j) quad &"if " j = k, 0 quad &"otherwise") $ // #image("imgs/16.png") Then we have $ p_1 compose lr((i_1 p_1 plus i_2 p_2)) eq p_1 comma quad p_2 compose lr((i_1 p_1 plus i_2 p_2)) eq p_2. $ By definition of products, $id_(X_1 times X_2) $ is the unique morphism $h : X_1 times X_2 -> X_1 times X_2$ with $p_k compose h eq p_k$ for each $k$, so $i_1 p_1 plus i_2 p_2 eq id_(X_1 times X_2)$. We claim that $ X_1 rgt(i_1) X_1 times X_2 lft(i_2) X_2 $ is a universal cocone and thus a coproduct. Suppose $X_1 rgt(f_1) A lft(f_2) X_2 $ is another cocone. Then we have a map $ phi eq f_1 compose p_1 plus f_2 compose p_2 colon X_1 times X_2 arrow.r A $ such that for $k = 1, 2$, $phi oo i_k = f_k $. This gives a commutative diagram // #align(center,image("../imgs/2023-10-29-11-34-35.png",width:30%)) // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRAA0B9ARhAF9S6TLnyEUAJnJVajFmy7j+gkBmx4CRblOr1mrRBx4ACPAFt4RhUqFrRm0t2m65BgIL9pMKAHN4RUABmAE4QpkhkIDgQSJIyemxYPNYgwaFIWpHRiLHO+iCJigKBIWGIEVFIAMw6snkBSUUpJenUFYjVcS4pnIXKqaWxbR0MWGB5UHRwABZeIDXxBmhTWB58QA #align(center, commutative-diagram( node-padding: (60pt, 50pt), node((0, 0), [$X_1$]), node((0, 2), [$X_2$]), node((0, 1), [$X_1 times X_2$]), node((1, 1), [$A$]), arr((0, 0), (0, 1), [$i_1$]), arr((0, 2), (0, 1), [$i_2$], label-pos: right), arr((0, 0), (1, 1), [$f_1$], label-pos: right), arr((0, 2), (1, 1), [$f_2$]), arr((0, 1), (1, 1), [$phi$], "dashed"), )) It remains to show that $phi$ is unique. To see this, note that for any such $phi$ we have $ phi & eq phi compose id_(X_1 times X_2)\ & eq phi compose lr((i_1 p_1 plus i_2 p_2))\ & eq phi i_1 compose p_1 plus phi i_2 compose p_2\ & eq f_1 compose p_1 plus f_2 compose p_2 dot.basic $ ] #definition[ Let $cC$ be an $Ab$-enriched category and let $X_1, X_2 in cC$. The *biproduct* of $X_1$ and $X_2$ is an object $X_1 xor X_2$ with morphisms $p_k : X_1 xor X_2 -> X_k$ and $i_k : X_k -> X_1 xor X_2 $ for $k = 1, 2$, such that - $p_k oo i_k = 1_(X_k)$; - $p_j oo i_k = 0 $ for $k != j$; - $i_1 oo p_1 + i_2 oo p_2 = 1_(X_1 xor X_2)$. // - $X_1 xor X_2$ with $(p_1, p_2)$ is a product of $X_1$ and $X_2$; // - $X_1 xor X_2$ with $(i_1, i_2)$ is a coproduct of $X_1$ and $X_2$. // If $X$ and $Y$ has a product (or a coproduct) in $cC$, then it is called the *biproduct* of $X$ and $Y$, denoted as $X xor Y$. ] #corollary[ In an $Ab$-enriched category, a binary biproduct is both a product and a coproduct, and a binary product (or a binary coproduct) is a biproduct. ] #proof[ This follows from the proof of @ab-product. ] // We can show that $x union.sq y iso x times y$ and we use the notation of a biproduct $x ds y$ to denote both. #remark[This extends to all _finite_ products and coproducts but does not extend to _infinite_ products or coproducts. ] #lemma[ In an $Ab$-enriched category, an additive functor preserves biproducts. ] <additive-preserve-biproduct> #proof[ Notice that an additive functor preserves identity morphisms, zero morphisms, morphism compositions and morphism additions, and they are all we need in the definition of biproducts. ] Being able to add and subtract parallel morphisms means we can rephrase the definitions for a monomorphism and epimorphism. #proposition[ In an $Ab$-enriched category $cC$, $f : B-> C$ is a monomorphism if and only if $f oo u = 0$ implies $u = 0$ for all $u : A -> B$. Dually, $f : B -> C$ is an epimorphism if and only if $v oo f = 0$ implies $v = 0$ for all $v : C -> D$. ] <ab-mono> #proof[ $f : B -> C$ is a monomorphism, if and only if $(f oo -) : hom_cC (A, B) -> Hom(C) (A, C)$ is injective for any $A$, if and only if $(f oo -)$ (as a $ZZ$-homomorphism) has kernel $0$. ] == Additive Categories Inspired by @ab-zero and @ab-product, we naturally define the following: #definition[ An $Ab$-enriched category $cC$ is *additive* if it has all finite biproducts, including the zero object. ] Now we can reconcile the two definitions we have had for zero morphisms. #proposition[ In an additive category $cC$, let $f: A->B$. Then $f$ is the identity of $Hom(C) (A, B)$ if and only if it can be factored as $A -> 0 -> B$. ] #proof[ Since $Hom(C) (A, 0)$ has an unique element $h$, it must be the identity of the group. Similarly, $Hom(C) (0, B)$ contains only the identity $g$. The composition $g oo h$ is the identity of $Hom(C) (A, B)$ by @zero-composition. ] #proposition[ In an additive category, if a monomorphism $i : A-> B$ is a zero morphism, then $A$ is the zero object. Dually, if an epimorphism $p : C -> D$ is a zero morphism, then $D$ is the zero object. ] <additive-mono-zero> #proof[ Take any $X$ and $u : X -> A$, we have $ X arrow^u A ->^i B. $ $i = 0$, so $i oo u = 0$; but since $i$ is monic, $u = 0$ by @ab-mono. Therefore there is a unique (zero) morphism from any $X$ to $A$, so $A$ is final and thus zero. ] #proposition[@rotman[Proposition 5.89]. Let $f colon A arrow.r B$ be a morphism in an additive category $cal(C)$. If $ker f$ exists, then $f$ is monic if and only if $ker f eq 0$. Dually, if $coker f$ exists, then $f$ is epic if and only $coker f eq 0$. ] <additive-ker> #proof[ Let $ker f$ be $i : K -> A$. Suppose $i = 0$. Since we know a kernel is a monomorphism, by @additive-mono-zero, $K = 0$. To show that $f$ is monic, take any $u : X -> A$ such that $f oo u = 0$. Then by the universal property of a kernel, there exists a unique morphism $h : X -> K$ such that $u = i oo h$. Thus $u$ factors through $K = 0$, so $u = 0$, proving $f$ is monic by @ab-mono. // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRAGkQBfU9TXfIRQBGclVqMWbAILdeIDNjwEiAJjHV6zVohAAhOXyWCiZYeK1TdADW7iYUAObwioAGYAnCAFskAZmocCCQyEAYsMB0QKDo4AAsHEE1JKLjDEE8ff0DgxFEJbTYmdMzfPJykdQKrDJKvMtCgpHzLKKw7LiA #align(center, commutative-diagram( node-padding: (50pt, 50pt), node((0, 0), [$K$]), node((0, 1), [$A$]), node((0, 2), [$B$]), node((1, 0), [$X$]), arr((1, 0), (0, 0), [$h$], label-pos: 1em, "dashed"), arr((1, 0), (0, 1), [$u$], label-pos: -1em), arr((0, 1), (0, 2), [$f$]), arr((0, 0), (0, 1), [$i$]), )) On the other hand, suppose $f$ is monic. Then $ker f = 0$ directly follows from @ab-mono. // We refer to the diagrams in the definitions of kernel and // cokernel. Let ker $u$ be $iota colon K arrow.r A$, and assume that // $iota eq 0$. If $g colon X arrow.r A$ satisfies $u g eq 0$, then the // universal property of kernel provides a morphism // $theta colon X arrow.r K$ with $g eq iota theta eq 0$ \(because // $iota eq 0$). Hence, $u$ is monic. Conversely, if $u$ is monic, // consider $ K arrows.rr^iota_0 A arrow.r^u B dot.basic $ // Since $u iota eq 0 eq u 0$, we have $iota eq 0$. The proof for // epimorphisms and cokers is dual. // #TODO modify ] == Pre-abelian Categories Now inspired by @additive-ker, we define the following: #definition[ An additive category $cC$ is *pre-abelian* if any morphism has a kernel and a cokernel. ] #corollary[ Let $f$ be a morphism in a pre-abelian category. $f$ is monic if and only if $ker f$ = 0. Dually, $f$ is epic if and only if $coker f = 0$. ] <pre-add-mono> In fact, we get more than just kernels and cokernels: #proposition[ A pre-abelian category has all finite limits and colimits. ] #proof[ Let $cC$ be a pre-abelian category. Since $Eq(f, q) = ker(f - g)$, $cC$ has all equalisers and coequalisers. We also know that $cC$ has all finite products and coproducts as an additive category. Thus it has all finite limits and colimits by @all-finite-limits. ] #proposition[ If $cC$ is pre-abelian, for every morphism $f : X-> Y$, there exists a unique morphism $G -> D$ as shown below. // // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRAGsYAnAAgAoAZgEoQAX1LpMufIRQBGclVqMWbABpiJIDNjwEiAJkXV6zVohABNTZN0yiAZmPKzbAMYROXQSPG3p+vKkckqmqhYeXnxRwr5aOgGyyEYhJirmHNx8kVmxYkowUADm8ESgAlwQALZIZCA4EEhyfiAV1U3UDUhGLuGtNq2VNYg9XYgOLW3DCvWNiAAsk0NIAKydcwZL7Qvrq9QMWGAZUHRwABaFIGmuFjAAHlhwOHA8AIT5okA // #align(center, commutative-diagram( // node-padding: (50pt, 50pt), // node((0, 0), [$ker (f)$]), // node((0, 1), [$X$]), // node((0, 2), [$Y$]), // node((0, 3), [$coker(f)$]), // node((1, 1), [$coker(ker(f))$]), // node((1, 2), [$ker(coker(f))$]), // arr((0, 0), (0, 1), []), // arr((0, 1), (0, 2), [$f$]), // arr((0, 2), (0, 3), []), // arr((0, 1), (1, 1), []), // arr((1, 2), (0, 2), []), // arr((1, 1), (1, 2), [$exists !$], "dashed"), // )) // https://t.yw.je/#N4Igdg9<KEY> #align(center, commutative-diagram( node((0, 0), [$K$]), node((0, 1), [$X$]), node((0, 2), [$Y$]), node((0, 3), [$C$]), node((1, 1), [$G$]), node((1, 2), [$D$]), arr((0, 0), (0, 1), [$ker(f)$]), arr((0, 1), (0, 2), [$f$]), arr((0, 2), (0, 3), [$coker(f)$]), arr((0, 1), (1, 1), [$coker (ker (f))$], label-pos: -3.5em), arr((1, 2), (0, 2), [$ker(coker(f))$], label-pos: -3.5em), arr((1, 1), (1, 2), [$exists !$], "dashed"), )) ] <pre-ab-morphism> #proof[ Since $coker(f) oo f = 0$, by the universal property of kernel, there exists $c : X -> D$ such that $f = ker(coker(f)) oo c$. Since $f oo ker(f) = 0$, we have $ker(coker(f)) oo c oo ker(f) = 0$. Now notice $ker(coker(f))$ is monic, and hence by @pre-add-mono, $ker(ker(coker(f))) = 0$. By the universal property of kernel again, there exists $d : K -> 0$ such that $c oo ker(f) = ker(ker(coker(f))) oo d$. Thus $c oo ker(f)$ factors through the zero object and thus is $0$. The desired morphism is obtained from the universal property of cokernel. #align(center, commutative-diagram( node((0, 0), [$K$]), node((0, 1), [$X$]), node((0, 2), [$Y$]), node((0, 3), [$C$]), node((1, 1), [$G$]), node((1, 2), [$D$]), node((2, 2), [$0$]), arr((0, 0), (0, 1), [$ker(f)$]), arr((0, 1), (0, 2), [$f$]), arr((0, 2), (0, 3), [$coker(f)$]), arr((0, 1), (1, 1), [$coker (ker (f))$], label-pos: 0), arr((1, 2), (0, 2), [$ker(coker(f))$], label-pos: -3.5em), arr((1, 1), (1, 2), [$exists !$], "dashed"), arr((0, 1), (1, 2), [$c$]), arr((2, 2), (1, 2), [$ker(ker(coker(f)))$], label-pos: -4.5em), arr((0, 0), (2, 2), [$d$], curve: -40deg) )) ] #definition[In a pre-abelian category, we define the *coimage* of a morphism $f$ as $ coim (f) = coker(ker(f)) $ and *image* of $f$ as $ im(f) = ker(coker(f)). $ Continuing with @ker-notation, we have $G = Coim(f)$ and $D = IM(f)$ in the above diagram. We call $f$ *strict* if the map $Coim (f) -> IM f$ is an isomorphism. ] == Abelian Categories #definition[ A pre-ablian category is *abelian* if all morphisms are strict. ] #corollary[ In an abelian category, every morphism $f : X-> Y$ has a factorisation $ X ->^g IM (f) ->^h Y, $ where $g$ is an epimorphism and $h$ is a monomorphism. ] #proof[ Notice $g = coker(ker(f)) = coim(f)$ and $h = ker(coker(f)) = im(f)$. ] We can always write $f = im(f) oo coim(f)$ and consider $im(f)$ as a subobject of $Y$. #remark[ The followings are two equivalent definitions of an abelian category: - A pre-abelian category where every monomorphism is a kernel and every epimorphism is a cokernel; - A pre-abelian category where every monomorphism is the kernel of its cokernel and every epimorphism is the cokernel of its kernel. ] We prove part of the equivalence: #proposition[ In an abelian category, every monomorphism is the kernel of its cokernel, and every epimorphism is the cokernel of its kernel. ] #proof[ Use the diagram in the proof of @pre-ab-morphism. Let $f$ be a monomorphism, then $ker(f) = 0$ and $K = 0$. It is not to hard to find $G = X$ and $coker(ker(f)) = id_X$. Since $D$ and $G$ are isomorphic, we see that $X$ is isomorphic to $D$ and thus $f = ker(coker(f))$. ] #remark[ Now it is time to give a list of properties that abelian categories have, packing everything we have picked up along the way: - Every hom-set is an abelian group subject to bilinear morphism composition; - It has a zero object and has a zero morphism between any two objects, which is the identity of the abelian group and factors through $0$; - It has all limits and colimits; - Any finite product and coproduct coincide as the biproduct; - $f$ is monic if and only if $f oo u = 0$ implies $u = 0$, if and only if $ker f = 0$, if and only if $f = im(f)$; - $g$ is epic if and only if $v oo g = 0$ implies $v = 0$, if and only if $coker g = 0$, #iff $g = colim(g)$; - $f$ is monic and $f = 0$ implies the domain of $f$ is $0$; - $g$ is epic and $g = 0$ implies the codomain of $g$ is $0$; - $Coim(f) -> IM(f)$ is an isomorphism; - Any $f$ can be factorised as $f = ker(coker(f)) oo coker(ker(f)) = im(f) oo coim(f)$. ] // Remark. This is equivalent to: (The converses are always true in any category.) This is equivalent to every mono is the kernel of its cokernel and every epi is the cokernel of its kernel. (? TODO) We now introduce the most important member in the family of abelian categories. #proposition[ For any ring $R$, the category $RMod$ is an abelian category. In particular, $Ab$ is an abelian category. ] #proof[ ($RMod$ is $Ab$-enriched.) For any $A, B in RMod$, the set $homr(A, B)$ of module homomorphisms $A -> B$ can be naturally seen as an abelian group under pointwise addition. It is easy to check that the composition is bilinear. ($RMod$ is additive.) We know that the direct sum exists as a coproduct for any finite family of modules $(M_i)_(i in I)$ in $RMod$. ($RMod$ is pre-abelian.) Let $f : A -> B$ be a morphism in $RMod$. Then $ Ker(f) = {a in A : f(a) = 0} $ with $ker(f) : Ker(f) -> A$ being the inclusion map, is a categorical kernel. Also, $ Coker(f) = B over IM(f) $ where $IM(f) = {f(a) in B : a in A}$, with $coker(f) : B -> Coker(f)$ being the quotient map, is a categorical cokernel. ($RMod$ is abelian.) We find $ Coker(ker(f)) = A over Ker(f) iso IM(f) $ by the First Isomorphism Theorem and $ Ker(coker(f)) = IM(f) $ by construction. Hence the image and coimage coincide up to isomorphism, i.e., any $f$ is strict. ] #remark[ Note that the product and coproduct of a family $(M_i)_(i in I)$ coincide when $I$ is finite but differ when $I$ is infinite: $ union.sq.big _(i in I) M_i = plus.circle.big_(i in I) M_i = {(m_i) _(i in I) | m_i in M_i, m_i = 0 "for almost all" i}, $ $ product _( i in I) M_i = {(m_i) _(i in I) | m_i in M_i}. $ ] #proposition[ In $RMod$, a monomorphism is equivalent to an injective homomorphism and an epimorphism is equivalent to a surjective homomorphism. ] #example[If $cA$ is an abelian category and $cC$ is any small category, then the category of functors $Fun(cC, cA)$ is abelian.] #example[ The category of Banach spaces over $RR$ is not an abelian category, but a *quasi-abelian category*. // We have $V attach(arrow.r.hook, t: i) W$ which are open. Then $coker i = W \/ overline(V)$. Then $ker coker i = overline(V) != V$. (The closure of $V$.) // This is an example of quasi-abelian categories. ] == Exact Sequences and Functors #note[ All discussions in this section are limited to an abelian category. ] We have trekked a long way to establish abelian categories. The key element that we seek from an abelian category is the notion of exactness: #definition[ In an abelian category, a sequence of maps $A attach(->, t: f) B attach(->, t: g) C $ is called *exact* at $B$ if $ker g = im f$ (as equivalent subobjects of $B$). ] #definition[ In an abelian category, a *short exact sequence* $0 -> A attach(->, t: f) B attach(->, t: g) C -> 0$ is exact at $A$, $B$ and $C$, or "exact everywhere". ] #lemma[ $im (0 -> A) = 0$ and $im(A -> 0) = 0$. ] #proposition[ $0 -> A attach(->, t: f) B attach(->, t: g) C -> 0$ is a #sest if and only if $f$ is monic, $g$ is epic, and $ker g = im f$. ] #proof[ - Exactness at $A$ $<=>$ $ker f = im (0 -> A) = 0$ $<=>$ $f$ is monic. - Exactness at $B$ $<=>$ $ker g = im f$. - Exactness at $C$ $<=>$ $im g = ker (C -> 0) = id_C$ $<=>$ $g = coim (g )$ $<=>$ $g$ is epic. ] #proposition[ If $ses(A, B, C, f:f, g:g)$ is a #sest, then $f = ker g$ and $g = coker f$. ] #proof[ $f$ is monic, so $f = im(f) = ker(g)$. $g$ is epic, so $g = coim(g) = coker(ker(g)) = coker(f)$. ] #corollary[ $ses(A, B, C, f:f, g:g)$ can be rewritten as $ ses(IM(f), B, Coker(f), f:"", g:coker(f)) $ or $ ses(Ker(g), B, Coim(g), f:ker(g), g:""). $ ] #proposition[ If $A->^f B->C->D->^g E$ is an exact sequence, then $ ses(Coker(f), C, Ker(g)) $ is a #sest. ] <five-to-ses> #definition[ A #sest $ses(A, B, C)$ is *split* if $B$ is isomorphic to $A ds C$. // #image("imgs/19.png") ] // #lemma[ // An additive functor preserves split short exact sequences. // ] // <additive-preserve-split> // #proof[ // This follows from @additive-preserve-biproduct. // ] #lemma("Splitting Lemma")[ Let $ses(A, B, C, f:f, g:g)$ be a short exact sequence. The followings are equivalent: + The short exact sequence is split; + There exists a *retraction*#footnote[The terms "retraction" and "section" come from algebraic topology, but for our purpose they are nothing more than certain morphisms.] $r: B->A$ such that $r oo f = id_A$; + There exists a *section* $s : C -> B$ such that $g oo s = id_C$. ] <splitting-lemma> #proof[ // #TODO https://math.stackexchange.com/questions/748699/abstract-nonsense-proof-of-the-splitting-lemma Although it is possible to give a purely category-theoretic proof, as can be seen @splitting-lemma-doc, we give a proof in $RMod$, which is in fact sufficient in view of @metatheorem. (1) $=>$ (2) and (1) $=>$ (3) are trivial by the definition of biproducts. (2) $=>$ (1). We first claim that $B = IM f + Ker r$. Take any $b in B$, then plainly $b = f r(b) + (b - f r(b)) $. Since $r (b - f r(b)) = r (b) - r f r (b) = 0$, we have $b - f r(b) in Ker r$. Also obviously $f r (b) in IM f$. We further claim that $B = IM f ds Ker r$. Suppose $b in IM f sect Ker r$, then there exists $a in A$ such that $b = f(a)$; also $r (b) = 0$. Then $0 = r f (a) =a$, so $b = f(a) = 0$. Now we claim that $Ker r iso C$; in particular, the restriction $g|_(Ker r) : Ker r -> C$ is an isomorphism. Take any $c in C$, then since $g$ is a surjection, there exists some $f(a) + k in B$, where $a in A$ and $k in Ker r$, such that $g (f(a) + k) = c$. Note that $g f(a) = 0$, because $f(a) in IM f = Ker g$ by exactness at $B$, so for any $c in C$, there exists $k in Ker r$ such that $g(k) = c$. Thus $g|_(Ker r)$ is surjective. On the other hand, if $g(k) = 0$ for $k in Ker r$, then $k in Ker g = IM f$, but $IM f sect Ker r = {0}$, so $k = 0$. Thus $g|_(Ker r)$ is injective. Finally, observe that $f$ is an injection, so $IM(f) iso A$. (3) $=>$ (1). The proof is similar as above and thus omitted. ] #corollary[Let $M, S, T$ be $R$-modules. - If $M = S ds T$ and $S subset.eq N subset.eq M$, then $N = S ds (N sect T)$. - If $M = S ds T$ and $S' subset.eq S$, then $M over S' = S over S' ds (T + S') over S'$. ] <split-sub> #proof[ @rotman[Corollary 2.24]. ] #definition[ An additive functor $F: cC -> cD$ is called - *right exact* if the exactness of $A-> B-> C-> 0$ implies the exactness of $F(A) -> F(B) -> F(C) -> 0 $; - *left exact* if the exactness of $0-> A-> B-> C$ implies the exactness of $0 -> F(A) -> F(B) -> F(C) $; - *exact* if the exactness of $0->A->B->C->0$ implies the exactness of $ses(F(A), F(B), F(C))$, for any $A, B, C in cC$. ] #remark[ By definition, _right exactness preserves cokernels_, since $C$ is the cokernel of the map $A -> B$ and $F(C)$ is the cokernel of the map $F(A) -> F(B)$. Similarly, _left exactness preserves kernels_. ] #lemma[ Let $cA$ be an abelian category. Let $M in cA$. The functor $ Hom(A)(M, -): cA -> Ab $ is left exact. ] <hom-left-exact> #proof[ Let $0->A->^f B->^g C$ be exact in $cA$, then we want to prove $ 0 -> Hom(A)(M, A) ->^(f oo -) Hom(A)(M, B) ->^(g oo -) Hom(A)(M, C) $ is exact in $Ab$. Exactness at $Hom(A) (M, A)$ is equivalent to $(f oo -) $ being monic, so let us calculate $Ker(f oo -)$. Let $u in Hom(A)(M, A)$ such that $(f oo -) (u) = 0$, i.e., $f oo u = 0$. But $f$ is monic, so $u = 0$, and thus $Ker(f oo -) = 0$ and $(f oo -)$ is monic. Exactness at $Hom(A) (M, B)$ is equivalent to $Ker(g oo -) = IM(f oo -)$. To show that $Ker(g oo -) subset.eq IM(f oo -)$, let $ v in Ker(g oo -)$. Then $v : M -> B$ such that $g oo v = 0$. Note that $A = Ker(g)$ and $f = ker(g)$, so by the universal property of kernel, there exists $h : M -> A$ such that $v = f oo h$, hence $v in IM(f oo -)$. On the other hand, to show that $IM(f oo -) subset.eq Ker(g oo -)$, notice that if $v in IM (f oo -)$, then $v = f oo h$ for some $h$ and then $g oo v = g oo f oo h = 0$ since $g oo f = 0$. ] // #TODO how to understand $f oo -$ #remark[ The functor $Hom(A) (M, -)$ fails to be exact in general because it does not necessarily send an epimorphism to an epimorphism. For a counterexample, let $cA = Ab$ (where an epimorphism is equivalent to a surjective homomorphism) and $M = ZZ over 2 ZZ$. The quotient map $h: ZZ -> ZZ over 4 ZZ $ is an surjective homomorphism. On the other hand, for any abelian group $A$, an element in $hom_Ab (ZZ over 2 ZZ, A)$ (i.e., a group homomorphism $ZZ over 2ZZ -> A$) is uniquely determined by an element in $A$ with order $2$. Hence $hom_Ab ( ZZ over 2 ZZ, ZZ) = 0$ and $hom_Ab ( ZZ over 2 ZZ, ZZ over 4ZZ) = ZZ over 2ZZ$, and we see the induced map $ (h oo -) : hom_Ab ( ZZ over 2 ZZ, ZZ) -> hom_Ab ( ZZ over 2 ZZ, ZZ over 4ZZ) $ cannot be surjective. ] #corollary[Dually, $Hom(A) (-, M): cA^op -> Ab$ is also left exact. ] <hom-left-exact-2> #note[ What does left exactness mean for a contravariant functor? If $X -> Y -> Z -> 0$ is exact in $cA$, then $0 -> Z -> Y -> X$ is exact in $cA^op$, and $0 -> Hom(A)(Z, M) -> Hom(A)(Y, M) -> Hom(A)(X, M)$ is exact in $Ab$. ] #endlec(4) == Projective and Injective Objects #definition[ Let $cA$ be an abelian category. An object $P$ is called *projective* if $Hom(A) (P, -)$ is exact. Dually, an object $I$ is called *injective* if $Hom(A) (-, I)$ is exact. ] In other words, $P$ is projective if for any #sest $ses(X, Y, Z)$ in $cA$, $ ses(Hom(A)(P, X), Hom(A)(P, Y), Hom(A)(P, Z)) $ is a #sest. #proposition[ The followings are equivalent: 1. $P$ is a projective object; 2. For any epimorphism $h : Y -> Z$, the induced map $(h oo -) : Hom(A) (P, Y) -> Hom(A) (P, Z)$ is surjective; 3. For any epimorphism $h : Y-> Z$ and any morphism $f : P -> Z$, there exists (not necessarily unique) $g : P -> Y$ such that $f = h oo g$, i.e. the following commutes (which we refer to as the *lifting property*): // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBoAGAXVJADcBDAGwFcYkQAFEAX1PU1z5CKAEyli1Ok1btyPPiAzY8BImQk0GLNohAAtef2VCi5cZK0zdATR6SYUAObwioAGYAnCAFskZkDgQSGJS2uxuhiCePsE0gUjEvO5evogAzHFBiCGWOiAAFpHRqf7x6TSMWGB5UPRw+Q4gmtJ5MAAeWHA4CNyU3EA #align(center, commutative-diagram( node-padding: (50pt, 50pt), node((0, 1), [$P$]), node((1, 2), [$0$]), node((1, 1), [$Z$]), node((1, 0), [$Y$]), arr((0, 1), (1, 1), [$f$]), arr((1, 1), (1, 2), []), arr((1, 0), (1, 1), [$h$]), arr((0, 1), (1, 0), [$exists g$], "dashed"), )) 4. Any #sest $ses(A, B, P)$ splits. ] <projective-split> #proof[ (1) $=>$ (2) is obvious; (2) $=>$ (1) by @hom-left-exact. (2) $<=>$ (3) is also obvious. (3) $=>$ (4). // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBpiBdUkANwEMAbAVxiRAEEQBfU9TXfIRQAmclVqMWbAELdeIDNjwEiAZjHV6zVohAAFOXyWCiAFg0TtbAAyGF-ZUOTWLWqbts8j<KEY>bnEYK<KEY>AWyQ<KEY>Cg<KEY>qrMQ<KEY>JA6q10EUuakc3akaynElpc5zsWKxByaxFUuCi4gA #align(center, commutative-diagram( node-padding: (50pt, 40pt), node((1, 1), [$A$]), node((1, 2), [$B$]), node((1, 3), [$P$]), node((1, 4), [$0$]), node((1, 0), [$0$]), node((0, 3), [$P$]), arr((0, 3), (1, 3), [$id_P$]), arr((1, 2), (1, 3), [$g$]), arr((0, 3), (1, 2), [$s$], label-pos: -1em, "dashed"), arr((1, 0), (1, 1), []), arr((1, 1), (1, 2), []), arr((1, 3), (1, 4), []), )) Since $g : B-> P$ is an epimorphism, we can always find $s : P -> B$ such that $g oo s= id_P$ by the lifting property. Then (4) holds by @splitting-lemma[Splitting Lemma]. (4) $=>$ (3). See @ses-split-projective. ] #corollary[Dually, the followings are equivalent: 1. $I$ is injective; 2. For any monomorphism $h: X->Y$, the induced map $(- oo h) : Hom(A) (Y, I) -> Hom(A) (X, I)$ is surjective; 3. For any monomorphism $h: X->Y$ and any $f: X->I$, there exists $g: Y->I$ such that $f = g oo h$, i.e., the following commutes (which we refer to as the *extension property*): // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBpiBdUkANwEMAbAVxiRAEkQBfU9TXfIRQAGUsKq1GLNsO68QGbHgJEy46vWatEIABpy+SwUQBMYiZuk6AmtwkwoAc3hFQAMwBOEALZIzIHAgkUUktNjcDEE8fJDIAoMQTHncvX0TqQKQAZg0pbRAAC0jotJz44OoGLDB8qDo4AocQXLCdGAAPLDgcOAACRzsuIA #align(center, commutative-diagram( node-padding: (50pt, 50pt), node((1, 1), [$I$]), node((0, 0), [$0$]), node((0, 1), [$X$]), node((0, 2), [$Y$]), arr((0, 1), (1, 1), [$f$]), arr((0, 0), (0, 1), []), arr((0, 1), (0, 2), [$h$]), arr((0, 2), (1, 1), [$exists g$], "dashed"), )) 4. Any #sest $ses(I, A, B)$ splits. ] == Categories of Modules #proposition[ Ring $R$ viewed as an object in $RMod$ is projective. ] #proof[ It is equivalent to say the functor $ homr (R, -)$ is exact. In fact, $homr (R, M) iso M $ because any module morphism $phi : R -> M $ is entirely determined by $phi(1_R)$. Given any #sest $ses(M, M', M'') $, if we apply $homr (R, -)$, we get the same #sest, which is exact. ] // #corollary[ // Any free module $R^(ds I)$ is projective. // ] // #proof[ // The proof is similar as above. #TODO // ] #note[In $RMod$, we have $ homr (R, plus.circle.big_(i in I) M_i) = plus.circle.big_(i in I) M_i = plus.circle.big_(i in I) homr (R, M_i). $ This does not follow from the universal property of the direct sum; this is because $R$ is special. ] #definition[ Let $cA$ be an additive category. We call an object $C$ *compact* if the canonical morphism $ product.co_(i in I) Hom(A) (C, G_i) -> Hom(A)(C, product.co_(i in I) G_i) $ is an isomorphism for any family ${G_i}_(i in I)$ of objects in $cA$ such that $product.co_(i in I) G_i$ exists. ] #remark[ You might find different definitions for an arbitrary category (not necessarily additive), but they are equivalent under the additive context. ] #definition[ In a category $cC$ with coproducts, an object $G$ is called a *generator* if for any $X in cC$, there is an epimorphism $product.co_I G -> X -> 0$. ] #lemma[ $R$ is a generator of $RMod$. ] #proof[ Recall @module-generator. ] #lemma[ In an abelian category $cA$, any hom-set $hom_cA (X, Y)$ can be seen as a right module over ring $End(A)(X)$, or equivalently a left module over $End(A)(X)^op$. ] #proof[ First notice $End(A)(X)$ is indeed a ring with composition as multiplication. Take any $m in Hom(A)(X, Y)$ and $r in End(A)(X)$. Define the multiplication $m r$ as $m oo r in Hom(A)(X, Y)$. It is easy to verify that this makes $Hom(A) (X, Y)$ a right module over $End(A)(X)$. ] #theorem("Morita's Theorem")[ Let $cA$ be an abelian category. Assume $cA$ has (small) coproducts. Assume that $P$ is a compact, projective generator. Let ring $R = End(A) (P)$, then the functor $ Hom(A)(P, -) : cA -> ModR $ is an equivalence of categories. ] #note[ If $cA = SMod$ for some ring $S$, we have observed that $S$ (as an object of $SMod$) is a compact, projective generator. In this case, $R = end_S (S)$. We observe that any module homomorphism $phi: S -> S$ is uniquely determined by $phi(1) in S$ with $phi(s) = s phi(1)$, and the composition of two homomorphisms $phi_1 , phi_2 : S-> S$ is in the opposite direction of multiplication in $S$: $ phi_1 (phi_2(s)) = s phi_2(1) phi_1(1) $ Therefore, $R = end_S (S) = S^op$. Thus, indeed, we have $SMod$ is equivalent to $ModR$, which is $Mod$-$S^op$. ] // #remark[ // Using the definition of equivalence, you want to construct another functor in the opposite direction and show their composites are natural isomorphic to identity functors. Alternatively, you might also prove that the functor is fully faithful and essentially surjective, if you can. // ] #proof[ @rotman[Theorem 5.55] and @pareigis[p. 211]. // https://cornellmath.wordpress.com/2008/04/10/abelian-categories-and-module-categories/ Denote $ F:=Hom(A)(P, -) : cA -> ModR$. Using the definition of categorical equivalence, we want to construct another functor $G : ModR -> cA$ and show $F G$ and $G F$ are naturally isomorphic to identity functors. We see that in this way $G$ should be left adjoint to $F$, so $G$ must preserves colimits and in particular be right exact. Inspired by the discussion above, we define $G$ in the following way. We first set $G(R) = P$ and $G(R^(ds I)) = P^(ds I)$. Any morphism $f: R^(ds J) -> R^(ds I)$ can be represented by a (possibly infinite) matrix with entries $a_(i j) in R$ for all $i in I$ and $j in J$. However, notice that $R = End(A) (P)$ by definition and thus the same matrix $(a_(i j))_(i in I, j in J)$ can also be seen as a morphism $P^(ds J) -> P^(ds I)$, which is defined to be $G(f)$. Now, for any $R$-module $M$, we can find a presentation $ R^(ds J) ->^f R^(ds I) -> M -> 0 $ Under $G$, this becomes $ P^(ds J) ->^(G(f)) P^(ds I) -> G(M) -> 0 $ where we define $G(M) = Coker(G(f))$. It can be verified that $G$ is a functor. // TODO ? Since $P$ is a projective object, $F$ is exact and preserves cokernels; since $P$ is compact, $F$ preserves direct sums. On the other hand, $G$ is right exact and preserves direct sums by construction. Hence the composites $F G$ and $G F$ are right exact and preserves direct sums. Now we check $F G$ and $G F$ are naturally isomorphic to identity functors. For $F G : ModR -> ModR$, we have $ F G (R) = F (P) = hom_cA (P, P) = R $ and hence $F G(R^(ds I)) = R^(ds I)$. Now for any $M in ModR$, there is a commutative diagram // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJ<KEY> #align(center, commutative-diagram( node-padding: (50pt, 50pt), node((0, 0), [$R^(ds J)$]), node((0, 1), [$R^(ds I)$]), node((0, 2), [$M$]), node((1, 0), [$F G ( R^(ds J) )$]), node((1, 1), [$F G (R^(ds I))$]), node((1, 2), [$F G (M)$]), node((0, 3), [$0$]), node((1, 3), [$0$]), arr((0, 0), (1, 0), []), arr((0, 1), (1, 1), []), arr((0, 2), (1, 2), []), arr((0, 0), (0, 1), []), arr((0, 1), (0, 2), []), arr((0, 2), (0, 3), []), arr((1, 0), (1, 1), []), arr((1, 1), (1, 2), []), arr((1, 2), (1, 3), []), )) Since $F G$ preserves cokernels, we see that $F G(M) iso M$. Hence $F G$ is naturally isomorphic to the identity functor of $ModR$. For $G F: cA -> cA$, we have $G F (P) = G( R) = P $, so $ G F (P^(ds I)) =P^( ds I)$. Now take any $X in cA$, since $P$ is a generator, we can find $ P^(ds J) -> P^(ds I) -> X -> 0 $ A similar argument as before gives the result. // #TODO review ] #remark[ $cA$ can have more than one compact, projective generator, say $P_1$ and $P_2$. Then $A = End(A) (P_1)^op hyph Mod = End(A) (P_2)^op hyph Mod$, where rings $End(A) (P_1)$ and $End(A) (P_2)$ are not necessarily isomorphic. This is *Morita equivalence* of rings. For example, consider $veck$ for some field $k$. Then $k$ and $k^n$ are both compact, projective generators of $veck$. Then $k$ and $M_n (k)$ ($n times n$ matrices over $k$) both are equivalent to $veck$ as categories. // #TODO ] #theorem("Freyd-Mitchell Embedding Theorem")[ If $cA$ is a small abelian category, there is a ring $R$ and an exact, fully faithful embedding functor $cA -> RMod$. ] <metatheorem> #proof[ // Using Yoneda embeddings. $cA -> Fun(cA^op, Ab)$. (?) @weibel[p. 25]. ] This theorem indicates that we can embed an abstract category into a concrete one. From a practical perspective, we can prove any reasonable statements for $RMod$ and they will also hold for abelian categories. An example is the following. #lemma("Snake Lemma")[ Suppose we have a commutative diagram of objects in an abelian category or $RMod$ // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBpiBdUkANwEMAbAVxiRAEEQBfU9TXfIRQAmclVqMWbAELdeIDNjwEiAZjHV6zVohABhOXyWCiZAAzitU3ew<KEY>sk<KEY>yv<KEY>ja2Is7qusQAVmompFEh<KEY>qS2LEiKsZ7p-qn5hV2QLvHj9YA2P3P9xAB2Q5a7i5aXgY8w3Sxl8cG6zmW10aBA1AYWDAXjgEEhUG4FC4QA #align(center, commutative-diagram( node-padding: (50pt, 50pt), node((1, 1), [$A$]), node((1, 2), [$B$]), node((1, 3), [$C$]), node((0, 1), [$A'$]), node((0, 2), [$B'$]), node((0, 3), [$C'$]), node((0, 4), [$0$]), node((1, 0), [$0$]), arr((0, 1), (1, 1), [$f$]), arr((0, 2), (1, 2), [$g$]), arr((0, 3), (1, 3), [$h$]), arr((0, 1), (0, 2), [$i'$]), arr((0, 2), (0, 3), [$p'$]), arr((0, 3), (0, 4), []), arr((1, 0), (1, 1), []), arr((1, 1), (1, 2), [$i$]), arr((1, 2), (1, 3), [$p$]), )) // #image("imgs/23.png") such that the rows are exact, then there is an exact sequence $ Ker f -> Ker g -> Ker h attach(->, t: diff) Coker f -> Coker g -> Coker h $ where the *connecting (homo)morphism* $diff$ is given by a well-defined formula $ diff(c') = i^(-1) g p'^(-1) (c') + IM(f) $ where $p'^(-1)$ means finding some element $b' in B'$ such that $p'(b') = c'$ and so on. Further, if $A' -> B'$ is monic, so is $Ker f -> Ker g$. If $B -> C$ is epic, so is $Coker g -> Coker h$. ] <snake> #proof[A detailed proof can be seen @snake-lemma-doc. We have the following commutative diagram: #v(20pt) // https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBoAmAXVJADcBDAGwFcYkQBBEAX1PU1z5CKchWp0mrdgCEefEBmx4CRAMxiaDFm0QgAwnP5KhRMsXFapujgHJDCgcuHJR5zZJ0hpd3kcEqUdTcJbXY9H3lFf2cyAAYLD3YAaxgAJwACADN7KKciUXj3UN0UjIBzHMcTQNJCkKsQUvSAC0rj<KEY> #align(center, commutative-diagram( node-padding: (50pt, 50pt), node((2, 1), [$A$]), node((2, 2), [$B$]), node((2, 3), [$C$]), node((1, 1), [$A'$]), node((1, 2), [$B'$]), node((1, 3), [$C'$]), node((0, 1), [$Ker f$]), node((0, 2), [$Ker g$]), node((0, 3), [$Ker h$]), node((3, 1), [$Coker f$]), node((3, 2), [$Coker g$]), node((3, 3), [$Coker h$]), node((1, 4), [$0$]), node((2, 0), [$0$]), arr((0, 1), (1, 1), []), arr((1, 1), (2, 1), [$f$]), arr((2, 1), (3, 1), []), arr((0, 2), (1, 2), []), arr((1, 2), (2, 2), [$g$]), arr((2, 2), (3, 2), []), arr((0, 3), (1, 3), []), arr((1, 3), (2, 3), [$h$]), arr((2, 3), (3, 3), []), arr((1, 1), (1, 2), [$i'$]), arr((1, 2), (1, 3), [$p'$]), arr((1, 3), (1, 4), []), arr((2, 0), (2, 1), []), arr((2, 1), (2, 2), [$i$]), arr((2, 2), (2, 3), [$p$]), arr((0, 3), (3, 1), [$diff$], curve: -68deg, "dashed"), arr((3, 1), (3, 2), [$j$]), arr((3, 2), (3, 3), [$q$]), arr((0, 1), (0, 2), [$j'$]), arr((0, 2), (0, 3), [$q'$]), )) In the first row, consider map $j' := i'|_(Ker f) : Ker f -> B'$. We claim that $j' : Ker f -> Ker g$. Indeed, take any $a' in Ker f subset.eq A'$, we have $ g(j'(a')) = g(i'(a')) = i(f(a')) = i(0) = 0. $ Then $j'(a') in Ker g$ and thus $j' : Ker f -> Ker g$. Similarly, $q' := p'|_(Ker g) : Ker g -> Ker h$. We then see the first row is exact because of the exactness of $A' -> B' -> C'$. Also, if $i'$ is an injection, i.e., $Ker(i') = 0$, then obviously $Ker(j') = 0$. In the last row, define $j : Coker(f) -> Coker(g)$ as $a + IM(f) |-> i(a) + IM(g)$ for any $a in A$. We claim that this map is well-defined. If $a_1, a_2 in A$ such that $a_1 + IM(f) = a_2 + IM(f)$, then $a_1 - a_2 in IM(f)$, thus there exists $a' in A'$ so that $a_1 - a_2 = f(a')$. Then $i(a_1 - a_2) = i(f(a')) = g(i'(a')) in IM(g). $ Then $ j(a_1 + IM(f)) = i(a_1) + IM(g) = i(a_2) + IM(g) = j(a_2 + IM(f)). $ So $j$ is well-defined. Similarly, we can define $q : Coker g -> Coker h$ and show the exactness of the last row. We can also see that the surjection of $p$ implies the surjection of $q$. Now all arrows except $diff$ are clear. Pick any $c' in Ker h subset.eq C'$. Since $p'$ is surjective, there exists $b' in B'$ so that $p'(b') = c'$. Now $0 = h(c') = h(p'(b')) = p(g(b')), $ so $g(b') in Ker p = IM i$, and there exists unique $a in A$ such that $i(a) = g(b')$. We thus define $diff: Ker h -> Coker f$ as $diff(c') = a + IM(f). $ We claim this is a well-defined function. Then it suffices to show for any two choices $b'_1, b'_2$ of $b'$ and corresponding choices $a_1, a_2$ of $a$, $diff (c')$ gives the same value. Since $p'(b'_1) = p'(b'_2) = c'$, we have $b'_1 - b'_2 in Ker(p') = IM(i')$. Thus we can write $b'_1 - b'_2 = i'(a')$ for some $a' in A'$. Then $i(a_1 - a_2) = g(b'_1 - b'_2) = g(i'(a')) = i (f (a')), $ but $i$ is injective, and hence $a_1 - a_2 = f(a') in IM f$. We omit the proof of the exactness at $Ker h$ and $Coker f$. // See @li[Theorem 6.8.6]. ] #endlec(5)
https://github.com/jneug/schule-typst
https://raw.githubusercontent.com/jneug/schule-typst/main/src/kl.typ
typst
MIT License
#import "core/document.typ" #import "core/layout.typ": base-header, header-left, header-right #import "_imports.typ": * #let grading-table = ( "0": .0, "1": .20, "2": .27, "3": .33, "4": .40, "5": .45, "6": .50, "7": .55, "8": .60, "9": .65, "10": .70, "11": .75, "12": .80, "13": .85, "14": .90, "15": .95, ) #let ewh(exercises) = { v(8mm) [Name: #box(stroke:(bottom:.6pt+black), width:6cm)] // TODO: Should the grading table be created here? ex.grading.display-expectations-table-expanded(exercises) v(4mm) align(right, [*Note:* #box(stroke:(bottom:.6pt+black), width:4cm)]) align(right, [Datum, Unterschrift: #box(stroke:(bottom:.6pt+black), width:4cm)]) v(1fr) align( center, ex.grading.display-grading-table( exercises, grading-table, ), ) } #let kl-title( doc, ) = block( below: 0.65em, width: 100%, rect( width: 100%, stroke: ( right: 10pt + theme.muted, bottom: 10pt + theme.muted, ), inset: -2pt, )[ #rect(width: 100%, stroke: 2pt + black, fill: white, inset: 0.25em)[ #set align(center) #set text(fill: theme.text.title) #heading( level: 1, outlined: false, bookmarked: false, )[ #smallcaps(doc.title) (#doc.duration Minuten) ] #v(-1em) #heading(level: 2, outlined: false, bookmarked: false)[ #args.if-none(doc.subject, () => []) #args.if-none(doc.class, () => []) #(doc.author-abbr)() ] #v(0.25em) ] ], ) #let klausur( ewh: ewh, ..args, body, ) = { let (doc, page-init, tpl) = base-template( type: "KL", type-long: "Klausur", _tpl: ( options: ( duration: t.integer(default: 180), split-expectations: t.boolean(default: false), ), aliases: ( dauer: "duration", erwartungen-einzeln: "split-expectations", ), ), fontsize: 10pt, title-block: kl-title, ..args, body, ) { show: page-init.with(header: base-header.with(rule: true)) tpl } if doc.solutions == "page" { show: page-init.with(header-center: (..) => [= Lösungen]) context ex.solutions.display-solutions-page(ex.get-exercises()) } { show: page-init.with( header-center: (..) => [= Erwartungshorizont], footer: (..) => [], ) context ewh(ex.get-exercises()) } } // TODO: Rework this. Maybe add "pre-pages" and "post-pages" as conecpt in base-template / document? #let deckblatt(message: [Klausuren und Informationen fÌr die Aufsicht]) = [ #v(.5fr) #align(center)[ #text(4em, font: theme.fonts.sans, weight: "bold")[ #the-number. #the-type #the-subject ] #text(3em, font: theme.fonts.sans, weight: "bold")[ #sym.tilde #the-class #sym.tilde ] #v(4em) #text(3em, font: theme.fonts.sans, weight: "bold")[ #document.use-value("date", d => d.display()) // #options.display( // "datum", // format: dt => if dt != none { // ("Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag").at(dt.weekday()) // dt.display(", [day].[month].[year]") // }, // ) ] #v(2em) #text(2em, weight: 400, message) #v(2em) #block()[ #set text(1.2em) #set align(right) // / Beginn: #luecke(width: 2cm) Uhr // / Abgabe: #luecke(width: 2cm) Uhr ] ] #v(1fr) #grid( columns: (1fr, 1fr), gutter: 3cm, [*Anwesend:*], [*Abwesend:*], ) #v(1fr) #pagebreak() ] #let teilaufgabe = teilaufgabe.with(points-format: ex.points-format-join)
https://github.com/Quaternijkon/Typst_FLOW
https://raw.githubusercontent.com/Quaternijkon/Typst_FLOW/main/src/magic.typ
typst
// --------------------------------------------------------------------- // List, Enum, and Terms // --------------------------------------------------------------------- /// Align the list marker with the baseline of the first line of the list item. /// /// Usage: `#show: align-list-marker-with-baseline` #let align-list-marker-with-baseline(body) = { show list.item: it => { let current-marker = { set text(fill: text.fill) if type(list.marker) == array { list.marker.at(0) } else { list.marker } } let hanging-indent = measure(current-marker).width + .6em + .3pt set terms(hanging-indent: hanging-indent) if type(list.marker) == array { terms.item( current-marker, { // set the value of list.marker in a loop set list(marker: list.marker.slice(1) + (list.marker.at(0),)) it.body }, ) } else { terms.item(current-marker, it.body) } } body } /// Scale the font size of the list items. /// /// Usage: `#show: scale-list-items.with(scale: .75)` /// /// - `scale` (number): The ratio of the font size of the current level to the font size of the upper level. #let scale-list-items( scale: .75, body, ) = { show list.where().or(enum.where().or(terms)): it => { show list.where().or(enum.where().or(terms)): set text(scale * 1em) it } body } /// Make the list, enum, or terms nontight by default. /// /// Usage: `#show list: nontight(list)` #let nontight(lst) = { let fields = lst.fields() fields.remove("children") fields.tight = false return (lst.func())(..fields, ..lst.children) } /// Make the list, enum, and terms nontight by default. /// /// Usage: `#show: nontight-list-enum-and-terms` #let nontight-list-enum-and-terms(body) = { show list.where(tight: true): nontight show enum.where(tight: true): nontight show terms.where(tight: true): nontight body } // --------------------------------------------------------------------- // Bibliography // --------------------------------------------------------------------- #let bibliography-counter = counter("footer-bibliography-counter") #let bibliography-state = state("footer-bibliography-state", ()) #let bibliography-map = state("footer-bibliography-map", (:)) /// Display the bibliography as footnote. /// /// Usage: `#show: magic.bibliography-as-footnote.with(bibliography("ref.bib"))` /// /// Notice: You cannot use the same key twice in the same document, unless you use the escape option like `@key[-]`. /// /// - numbering (string): The numbering format of the bibliography in the footnote. /// /// - escape (content): The escape string which will be used to escape the cite key, in order to avoid the conflict of the same key. /// /// - bibliography (bibliography): The bibliography argument. You should use the `bibliography` function to define the bibliography like `bibliography("ref.bib")`. #let bibliography-as-footnote(numbering: "[1]", escape: [-], bibliography, body) = { show cite: it => if it.supplement != escape { box({ place(hide(it)) context { let bibitem = bibliography-state.final().at(bibliography-counter.get().at(0)) footnote(numbering: numbering, bibitem) bibliography-map.update(map => { map.insert(str(it.key), bibitem) map }) } bibliography-counter.step() }) } else { footnote(numbering: numbering, context bibliography-map.final().at(str(it.key))) } // Record the bibliography items. { show grid: it => { bibliography-state.update( range(it.children.len()).filter(i => calc.rem(i, 2) == 1).map(i => it.children.at(i).body), ) } place(hide(bibliography)) } body } /// Display the bibliography. /// /// You can avoid `multiple bibliographies are not yet supported` error by using this function. /// /// Usage: `#magic.bibliography()` #let bibliography(title: auto) = { context { let title = title let bibitems = bibliography-state.final() if title == auto { if text.lang == "zh" { title = "参考文献" } else { title = "Bibliography" } } if title != none { heading(title) v(.45em) } grid( columns: (auto, 1fr), column-gutter: .7em, row-gutter: 1.2em, ..range(bibitems.len()).map(i => (numbering("[1]", i + 1), bibitems.at(i))).flatten(), ) } }
https://github.com/Trebor-Huang/HomotopyHistory
https://raw.githubusercontent.com/Trebor-Huang/HomotopyHistory/main/infcat.typ
typst
#import "common.typ": * = 无穷范畎 无穷范畎的基本想法非垞简掁. 对象之闎有态射, 态射之闎有 2-态射, 2-态射之闎有 3-态射, 以歀类掚. 产生这种抂念有倚重历史劚机, 接䞋来我们䟝次对各䞪劚机的历史线条进行梳理. == 范畎的局限 === 同䌊范畎 拓扑空闎的范畎䟿于研究拓扑性莚, 䟋劂 $sans("Top")$ 的同构就是拓扑空闎的同胚. 䜆是同䌊论䞭曎垞见的是拓扑空闎的同䌊等价, 即存圚 $f : X -> Y$, $g : Y -> X$ 䜿埗 $f compose g$ 侎 $g compose f$ 郜䞎恒同凜数同䌊. 这自然匕出了*同䌊范畎*的定义. $sans("Ho")(sans("Top"))$ 的对象是拓扑空闎, 而态射是连续映射圚同䌊䞋的等价类. 这䞪范畎䞭的同构就是同䌊等价. 然而, 这种定义有诞倚问题. 䟋劂其䞭的极限䞎䜙极限并䞍对应同䌊极限䞎䜙极限, 甚至圚埈倚情况䞋郜根本䞍存圚. 这是因䞺商去同䌊关系抛匃了曎高阶的信息, 因歀各种同䌊操䜜郜隟以正确进行. 暡型范畎是䞀种避免商去同䌊, 利甚额倖添加的结构圚 $sans("Top")$ 䞭进行同䌊操䜜的办法. 同样的现象圚代数䞭也有出现. 圚铟倍圢的研究䞭, 各种凜子对同调矀的圱响可以由其富出凜子描述. 䜆是这种描述非垞倍杂, 䟋劂倚䞪凜子倍合对铟倍圢的圱响需芁繁杂的谱序列衚述. 究其根本, 是富出凜子取同调操䜜富臎信息的䞢倱. 然而, 富出凜子的构造䞭, 投射预解是䞍唯䞀的, 仅仅圚铟同䌊意义䞋唯䞀, 因歀才需芁取同调确保良定义. å› æ­€, 由 Grothendieck 䞎其孊生 <NAME> 圚 1960 幎代考虑了铟倍圢范畎 $"Ch"(A)$ 商去铟同䌊埗到范畎 $cal(K)(A)$, 䞎局郚化拟同构 (即保持所有同调矀的映射, 类比匱同䌊等价) 埗到的范畎 $cal(D)(A)$. 这些范畎可以类䌌于暡型范畎䞀样赋予额倖的结构, 称䜜*䞉角范畎*. 事实䞊, 代数拓扑䞭也出现了䞀䞪非垞重芁的䞉角范畎, 也就是谱的同䌊范畎. 埈早就发现了䞊同调䞎同䌊之闎的关系 $ H^n (X; G) tilde.equiv [X, K(G, n)] $ å…¶äž­ $[X, Y]$ 衚瀺 $X -> Y$ 映射圚同䌊关系䞋的等价类. $K(G, n)$ 是䞀类特殊的空闎, 称䜜 *Eilenberg–Mac Lane 空闎*. 对于任䜕广义的䞊同调理论 $h^bullet$, 则由 <NAME> 圚 1962 幎给出了著名的*可衚定理*, 即它总是可以写成 $ h^n (X) tilde.equiv [X, S_n] $ å…¶äž­ $S_n$ 是䞀列空闎, 有映射 $S_n -> Omega S_(n+1)$ (也等价于 $Sigma S_n -> S_(n+1)$, 因䞺这䞀䞪凜子䌎随). 这种结构称䜜*è°±* (spectrum). 这䞪抂念由 Elon Lages Lima 圚 1958 幎最初匕入. 最重芁的广义䞊同调理论就是 $K$-理论, 利甚拓扑空闎䞊的向量䞛给出䞊同调矀. 䜿甚实向量空闎的版本称䞺 $K upright(O)$, 它对应的谱有非垞有趣的呚期性结构, 读者可以翻到封面页欣赏. 这种结构称䜜 *Bott 呚期性*. 圚前蚀䞭列出的球面同䌊矀衚栌, 细心观察可以看到沿着对角方向埀右䞋移劚时, 总是䌚收敛到䞀䞪固定的矀, 称䜜球面的*皳定同䌊矀*. 这是由同䌊的 Freuthendal 纬悬定理保证的, 即满足特定条件的空闎 $X$, 䞍断取纬悬埗到䞀列同䌊矀 $ pi_n (X), pi_(n+1) (Sigma X), pi_(n+2) (Sigma^2 X), dots $ 最终总是趋于皳定. 这䞪矀记䜜 $pi_n^s (X)$. 皳定同䌊矀之于同䌊矀, 正劂谱之于拓扑空闎. 换蚀之, 谱是皳定同䌊矀这种代数结构的拓扑对应. 䟋劂球面构成谱 $SS$, 其皳定同䌊矀也圚封面页列出. 谱䞊的同䌊论称䜜皳定同䌊论, 它盞蟃于同䌊论而蚀曎容易做计算. $sans("Ho")(sans("Spec"))$ 也构成䞉角范畎, 这诎明这些领域出现的问题是盞通的, 因歀䞀䞪统䞀的解决方案将䌚揭瀺同䌊论䞭的深层结构. === 高绎代数 䞊同调最重芁的结构就是杯积 $H^n (X) times.circle H^m (X) -> H^(n+m) (X)$. 这翻译到谱䞊, 对应的是*环谱* (ring spectrum). 谱䞊可以定义猩积 $X and Y$, 类比亀换矀的匠量积. 猩积的单䜍元是球谱 $SS$, 类比亀换矀 $ZZ$. 环谱就是携垊了乘法 $mu : X and X -> X$ 䞎单䜍元 $eta : SS -> X$ 的谱, 䜿埗乘法单䜍埋䞎结合埋圚同䌊意义䞋成立. 类䌌的对象还有 H 空闎, 就是垊点拓扑空闎 $X$ 䞊给定连续映射 $m : X times X -> X$, 满足 $m(*, -)$ 侎 $m(-, *)$ 郜同䌊于恒同映射. 这可以看䜜同䌊意义䞋的矀公理匱化版. 尜管圚埈倚情况䞋只需芁匱化的公理即可, 䜆是䞀些构造䞭需芁曎完敎的公理才胜䜓现蟃奜的性莚. 䟋劂, 环谱䞭四䞪元玠的乘法䌚有五种结合方匏, 结合埋给出同䌊五蟹圢 #box(width: 100%)[ #set align(center) #fletcher.diagram(spacing: (0cm, 1.5cm), node-defocus: 0, $ & (x dot y) dot (z dot w) edge("dr", bend: #20deg) & \ x dot (y dot (z dot w)) edge("ur", bend: #20deg) edge("d") && ((x dot y) dot z) dot w \ x dot ((y dot z) dot w) edge("rr") && (x dot (y dot z)) dot w edge("u") $)] 歀五蟹圢䞍䞀定可猩, 即它们尜管结合, 䜆是结合的“方匏䞍唯䞀”. 芁求了歀五蟹圢可猩后, 五䞪元玠的乘法又䌚构成䞀䞪九面䜓, 以歀类掚. 这䞀系列几䜕䜓称䜜 *Stasheff 倚胞圢*. 1963 幎, Stasheff 利甚它提出了有无穷高绎的结合埋的运算, 称䜜 $A_oo$ 代数. 而若再加䞊亀换埋, 就埗到 $E_oo$ 代数. 这些代数的研究称䜜 “矎䞜新代数”. #footnote[《矎䞜新䞖界》是䞀本反乌托邊小诎.] == 高绎范畎 自范畎论提出以来, 它就以胜借简掁地衚蟟各䞪数孊分支䞭隐藏的抜象结构而闻名. 然而讜刺的是, 范畎论本身华无法自然地纳入范畎的研究框架䞋. 劂果将范畎视䜜对象, 凜子视䜜态射, 就応略了凜子之闎自然同构的信息. 埈倚情况䞋实际䞊凜子并䞍完党盞等, 而是盞差䞀䞪自然同构. 劂果只考虑凜子圚自然同构䞋的等价类, 就䌚䞎 $sans("Ho")(sans("Top"))$ 䞀样出现讞倚问题. 事实䞊, 党䜓范畎构成的是䞀䞪 *2-范畎* $sans("Cat")$, 而非范畎 —— 也称䜜 1-范畎. 2-范畎陀了对象䞎态射之倖, 还有态射之闎的 2-态射. 具䜓来诎, 每䞀䞪对象之闎的态射䞎 2-态射构成䞀䞪 1-范畎 $hom(X, Y)$. 有恒等态射 $id in hom(X, X)$, 䞎䞀族二元凜子 $hom(Y, Z) times hom(X, Y) -> hom(X, Z)$ 衚瀺 1-态射的倍合. 对于 $sans("Cat")$ 来诎, $hom(X, Y)$ 就是凜子䞎自然态射构成的范畎. 1-态射倍合的结合埋䞍胜盎接甚盞等关系描述, 因䞺我们讀䞺 “盞同” 的 1-态射埀埀盞差䞀䞪同构. 因歀我们匕入自然同构 $ alpha_(f,g,h) &:& f compose (g compose h) &tilde.equiv (f compose g) compose h \ lambda_f &:& id compose f &tilde.equiv f \ rho_f &:& f compose id &tilde.equiv f $ 我们每次圚数孊对象䞭匕入映射, 就需芁考虑这些映射是吊满足等匏. 这里, 这些自然同构也需芁满足䞀些额倖的等匏 (由于这些同构是 1-范畎 $hom(X, Y)$ 侊的, 所以可以盎接谈论盞等). 䟋劂四䞪态射的倍合有五种方匏, 可以甚 $alpha_(bullet, bullet, bullet)$ 连接它们: #box(width: 100%)[ #set align(center) #fletcher.diagram(spacing: (0cm, 1.5cm), node-defocus: 0, $ & (f compose g) compose (h compose k) edge("dr", ->, bend: #20deg) & \ f compose (g compose (h compose k)) edge("ur", ->, bend: #20deg) edge("d", ->) && ((f compose g) compose h) compose k \ f compose ((g compose h) compose k) edge("rr", ->) && (f compose (g compose h)) compose k edge("u", ->) $)] 囟衚䞭䞀条路埄倍合需芁盞等. 对于 $lambda_bullet, rho_bullet$ 也各自有䞀䞪䞉角圢等匏. 这些倍杂的等匏称䜜*融莯性* (coherence) 等匏. 2-范畎的理论时刻需芁倄理这些高阶等匏, 因歀皍星繁琐. 读者可以试囟验证任䜕 1-范畎可以看䜜 2-范畎, 即将 $hom(X, Y)$ 从集合升级䞺只有恒同态射的范畎. 定义 2-范畎之闎的凜子时, 同样需芁给出䞀些融莯性等匏. 这时我们需芁证明䞀䞪六蟹圢囟衚䞎䞀䞪四蟹圢囟衚分别亀换. 自然变换又需芁䞀系列亀换囟衚. 最后, 2-范畎䞭的自然变换之闎还有曎高层的映射, 称䜜*调敎*. 2-范畎理论圚 1967 幎由 <NAME> 提出. 这是䞺了衚述代数几䜕的䞋降理论䞭自然出现的结构. 甹 2-范畎的语蚀, 可以将它衚述䞺凜子 $F : cal(B) -> sans("Cat")$, å…¶äž­ $cal(B)$ 是 1-范畎视䜜退化的 2-范畎. 䜆是由于起初没有 2-范畎的工具, Grothendieck 将其衚述䞺 1-范畎的凜子 $p : cal(E) -> cal(B)$, 甚每䞪对象 $X in cal(B)$ 䞊的纀绎代指 $F(X)$. 2-范畎可以曎加盎接地衚述歀事. 虜然有些讞繁琐, 2-范畎的理论仍然圚人类操䜜的范囎内. 䜆是 3-范畎的倍杂床迅速超过了理解䞎记忆的限床. 圚 @tricategory äž­, 3-范畎的定义就占据了 6 页, 而加䞊对应的凜子、自然变换、调敎, 还有调敎之闎的映射 —— 称䜜*埮扰* —— 蟟到了惊人的 19 页. 这仅仅是眗列定义, 还未匀始证明任䜕性莚或给出任䜕构造. 星然, 这种做法是无法持续的. å› æ­€, 绝倧郚分的范畎论研究郜局限圚 $n$-范畎 $(n <= 2)$ äž­. 既然 3-范畎的理论就已经隟以理解, 埈长䞀段时闎内, 无穷范畎郜被讀䞺是曎加䞍可觊碰的对象. 无穷范畎理论的䞀倧莡献就是打砎了这䞀讀知, 并䞥栌地建立了无穷范畎论的各种可以类比 1-范畎论的定理. == 䜕䞺空闎? === 组合拓扑 䞀盎以来, 同䌊论的研究受制于空闎的性莚. 讞倚定理郜是先圚性莚蟃奜的空闎䞊建立的. 起初䜿甚的是 (几䜕) 单纯倍圢. 点、线段、䞉角圢、四面䜓的 $n$ 绎掚广称䜜*单纯圢* (simplex, 简称单圢). 劂果某䞪空闎被䞀族单纯圢子空闎 $cal(K)$ 芆盖, 䜿埗每䞪单纯圢 $s in cal(K)$ 的面也属于 $cal(K)$, 并䞔任䜕䞀䞪单纯圢的亀集 $s_1 sect s_2$ 芁么空, 芁么是 $s_1$ 侎 $s_2$ 的面, 就称 $cal(K)$ 是这䞪空闎䞊的*单纯倍圢*结构. 流圢的䞉角剖分就是指流圢䞊的单纯倍圢结构. 圚拓扑空闎还未出现的时候, 单纯倍圢就可以盎接䜜䞺空闎的定义. 我们也可以脱犻拓扑空闎而完党抜象的考虑单纯倍圢. 泚意到单纯倍圢䞭, 顶点集完党决定了单纯圢. 因䞺劂果有䞀䞪 $n$ 绎单圢的顶点盞同, 那么它们盞亀需芁是这䞀䞪单圢的面, 矛盟. 因歀我们可以讟有䞀䞪集合 $V$ 衚瀺倍圢的顶点, 并䞔有䞀族有限非空子集 $cal(K) subset.eq cal(P)(V)$ 描述了倍圢的单纯圢集合. 其䞭需芁每䞪顶点的单点集 ${v} in cal(K)$, 衚瀺零绎单圢, 并䞔任䜕单圢 $s in cal(K)$ 的非空子集 (几䜕意义是单圢的面) 也属于 $cal(K)$. 这称䜜*抜象单纯倍圢*. 这可以视䜜是单纯倍圢的蓝囟, 可以按照抜象单纯倍圢的指富拌莎几䜕䜓埗到几䜕单纯倍圢. 这种倍圢犁止倍杂的粘合情况出现. 䟋劂圆 $SS^1$ 必须由䞉条线段构成, 䞍胜盎接由䞀条线段将䞀䞪顶点粘合; 球 $SS^2$ 则最少需芁四䞪䞉角圢构成空心四面䜓状. 因歀圚做具䜓计算时埀埀䌚需芁埈倚单圢, 比蟃繁琐. 同时, 圚构造单纯倍圢时埀埀䌚遇到䞍满足条件的情况, 就需芁额倖匕入操䜜修正. Eilenberg 侎 Zilber @semisimplicial 圚 1949 幎匕入了曎加宜束的倍圢, 称䜜*半单纯倍圢* (semi-simplicial complex). 因䞺单圢䞍再由顶点决定, $n$ 绎单圢䞍胜看䜜顶点集的子集, 而是需芁额倖确定䞀䞪集合 $K_n$. 其有 $(n+1)$ 䞪 $(n-1)$ 绎面, 因歀有凜数 $sigma_i : K_n -> K_(n-1)$, å…¶äž­ $0 <= i <= n$. 䞺了保证拌接关系正确, 这些凜数需芁满足䞀些等匏. $n$ 绎单纯圢的 $k$ 绎面有 $binom(n+1,k+1)$ 䞪, 劂果我们记 $[n] = {0, dots, n}$, 就和 $[k] -> [n]$ 的单调单射䞀䞀对应. 我们可以甚范畎语蚀重新衚蟟半单纯倍圢, 即 $Delta_"inj"^"op" -> sans("Set")$ 的凜子. å…¶äž­ $Delta_"inj"$ 是 $[1], [2], dots$ 䞎它们之闎的单调单射构成的范畎. 这些单射可以讀䞺是指代单圢的某䞪面的圢匏笊号. 圚 @semisimplicial äž­, Eilenberg 侎 Zilber 还讚论了及䞀类对象, 称䜜*完倇半单纯倍圢* (complete semi-simplicial complex). 圚半单纯倍圢的基础䞊匕入了*退化*的单圢. 䟋劂长床䞺零的线段就是退化 $1$-单圢. 完倇半单纯倍圢可以衚述䞺 $Delta^"op" -> sans("Set")$ 的凜子, å…¶äž­ $Delta$ 是 $[1], [2], dots$ 䞎它们之闎的党䜓单调映射构成的范畎. 每䞪半单纯倍圢郜可以靠添加退化的单圢构成完倇半单纯倍圢, 䜆是反之䞍然. 䟋劂球面 $SS^2$ 可以衚述䞺恰奜有䞀䞪非退化 $2$-单圢, 并䞔它的䞉䞪面郜是退化的 $1$-单圢. 由于这些结构本莚䞊只需芁集合之闎的映射关系, 䞍需芁拓扑信息就可以讚论, 因歀圓代䞀般称之䞺半单纯集, 而䞍称倍圢. 同时, 由于完倇半单纯倍圢非垞重芁, 䜿甚过皋䞭逐析简化, 最终名称变䞺*单纯集* (simplicial set). 给定单纯集或半单纯集, 总胜以之䞺蓝囟, 构造出对应的拓扑空闎, 称䜜其*几䜕实现*. 同幎, Whitehead 定义了曎加宜束的 *CW 倍圢*, 或称胞腔倍圢 (cellular complex). å…¶äž­, 粘接䞍需芁沿着单圢的面, 而可以随意粘接. å› æ­€, 单圢的结构就䞍再重芁, 可以盎接替换成实心球䜓. 䟋劂, 可以将圆盘的蟹界沿着圆绕䞀圈粘接埗到 $RR PP^2$. Whitehead 证明了著名的 Whitehead 定理, 即对于 CW 倍圢来诎, 劂果 $f : X -> Y$ 诱富了同䌊矀的同构, 那么就䞀定存圚同䌊意义䞋的逆映射. 换句话诎, 匱同䌊等价可以掚出同䌊等价. å› æ­€, CW 倍圢䞀方面非垞灵掻, 及䞀方面排陀了圚同䌊视角䞋病态的拓扑空闎. 䟋劂 *Warsaw 圆*, 由 $sin(1/x)$ 曲线䞎 ${(0, y) | -1 <= y <= 1}$ 粘接而成.\ #box(width: 100%)[ #set align(center) #import cetz.draw: * #cetz.canvas( { cetz.plot.plot(name: "plot", size: (20/calc.pi, 2), axis-style: none, x-tick-step: none, y-tick-step: none, { cetz.plot.add(domain: (calc.sqrt(2*calc.pi), 8), samples: 400, t => (1/(t*t), calc.sin(t*t)), style: (stroke: black)) cetz.plot.add(domain: (calc.sqrt(2*calc.pi), 8), samples: 400, t => (-1/(t*t), -calc.sin(t*t)), style: (stroke: black)) cetz.plot.add-anchor("center", (0,0)) cetz.plot.add-anchor("left", (-1/(2*calc.pi),0)) cetz.plot.add-anchor("left-up", (-1/(2*calc.pi)-1/(4*calc.pi*calc.pi), 1)) cetz.plot.add-anchor("right", (1/(2*calc.pi),0)) cetz.plot.add-anchor("right-down", (1/(2*calc.pi)+1/(4*calc.pi*calc.pi), -1)) }) rect((rel: (20/63, 1), to: "plot.center"), (rel: (-20/63, -1), to: "plot.center"), stroke: none, fill: black) bezier("plot.left", (0,-1), "plot.left-up", (-2,-1)) line((0,-1), (20/calc.pi, -1)) bezier("plot.right", (20/calc.pi, -1), "plot.right-down", (20/calc.pi + 0.5, -1)) } )] 这条曲线所有同䌊矀均䞺零, 因歀从同䌊的视角没有任䜕可识别的性莚. 䜆是它并䞍可猩. CW 倍圢规避了这种情况, 䜆是任䜕拓扑空闎郜䞎某䞪 CW 倍圢匱同䌊等价 (对于 Warsaw 圆来诎, 它䞎单点空闎匱同䌊等价). å› æ­€, CW 倍圢成䞺了代数拓扑䞎同䌊论䞍可或猺的工具. <NAME> 圚 1956 幎起系统地发展了单纯集䞭的同䌊论. 尜管没有拓扑的抂念, 同䌊的各种关键结构郜可以圚单纯集䞭䜓现. 从同䌊的角床, 单纯集范畎 $sans("sSet")$ 䞎拓扑空闎的范畎 $sans("Top")$ 是等价的. 䞥栌来诎, 就是这䞀者构成的暡型范畎之闎有 Quillen 等价. å› æ­€, 我们也可以把单纯集称䜜 “空闎”. // Kan 提出了䞀种满足特殊条件的单纯集, 称䜜 *Kan 倍圢*. 将 $n$ 绎单圢看䜜单纯集, 记䜜 $Delta^n$. 将其挖去䞭心䞎其䞭䞀䞪面, 就埗到了“角” $Lambda^n_i$, å…¶äž­ $0 <= i <= n$ 衚瀺挖去了第几䞪面. 给定单纯圢 $X$, 劂果对于任䜕角 $Lambda^n_i -> X$, 郜存圚填充 $Delta^n -> X$, 就称其䞺 Kan 倍圢. 换句话诎, 所有劂囟所瀺的亀换方郜可以填入对角线. === 无穷矀胚 圚代数拓扑的匀端提出的基本矀的抂念, 需芁选择䞀䞪基点. 可以给出䞀䞪䞍选择基点的版本, 称䜜*基本矀胚*. 矀胚即所有态射郜可逆的范畎. 矀可以看䜜只有䞀䞪对象的矀胚, 矀的元玠对应这䞪对象到自身的态射. 基本矀胚的对象是拓扑空闎䞭的点, 而态射是道路的同䌊等价类. 那么基本矀胚䞭对象圚同构关系䞋的等价类就是拓扑空闎的道路连通分支 $pi_0 (X)$. å› æ­€, 基本矀胚同时包含了 $pi_0(X)$ 侎 $pi_1 (X)$ 的信息, 可以记䜜 $pi_(<= 1) (X)$. 泚意到䞺了道路倍合的结合埋等等匏, 这商去了道路之闎的同䌊, 因歀损倱了䞀些信息. 对于没有曎高绎的结构的空闎 —— 即 $pi_n (X) = 0$ $(n > 1)$, 称䜜 *1-截断*空闎 —— 来诎, 基本矀胚就包含了党郚的信息. 䞥栌来诎, 矀胚构成的 2-范畎 $sans("Grpd") arrow.hook sans("Cat")$ 侎 1-截断拓扑空闎、连续映射、映射同䌊的等价类构成的 2-范畎 $sans("Top")_(<= 1)$ 是等价的. 䞋䞀步掚广就是 2-矀胚, 即所有映射郜可逆的 2-范畎, 以歀类掚. 劂果芁芆盖党䜓空闎而䞍损倱任䜕信息, 自然就需芁对 $n$-矀胚取极限 $n -> oo$. 这样, 就胜定义 “基本无穷矀胚”, 盎接取道路而䞍商去任䜕同䌊. 这就䜿埗空闎的抂念完党摆脱拓扑, 从而也避免了病态拓扑空闎的问题. Grothendieck 圚著名的手皿《远寻叠》@PursuingStacks 䞭提出甚无穷矀胚䜜䞺空闎的等价定义. “叠” 指代的就是现代所称的无穷矀胚. 无穷矀胚䞎空闎的等价性称䜜*同䌊假讟*. 䜆是劂䞊所瀺, 1-截断的同䌊假讟需芁甚到 2-范畎的等价, 因歀仅仅是衚述出完敎的同䌊假讟就必须定义无穷范畎之闎的等价, 曎䞍甚诎证明了. å› æ­€, 无穷范畎的理论也䌚给出 (同䌊意义䞋) 空闎的本莚的启瀺. == 无穷范畎 这䞉条线的发展, 最终聚合催生了无穷范畎的研究. 1973 幎, Boardman 侎 Vogt @quasicategory 匕入了*拟范畎* (quasicategory), 标志着无穷范畎论的匀端. 这是基于单纯集的定义. 单纯集䞭的顶点代衚对象, 蟹代衚态射. 䞉角圢衚瀺䞀䞪态射的倍合是第䞉䞪态射. 泚意这意味着䞀䞪态射倍合可以䞍唯䞀, 它们只需芁圚曎高绎的同䌊意义䞋唯䞀即可. 同时, 䞉条蟹之闎可以有倚于䞀䞪䞉角圢, 衚瀺它们之闎的同䌊可以非平凡. 这种改劚䜿埗无穷绎的融莯埋可以统䞀地描述. 无穷范畎的操䜜就变成了有限集的䞀些组合问题. 随后, 操䜜无穷范畎所需的工具皳步发展. 无穷范畎的其他定义也逐析出现. 䟋劂 $sans("sSet")$-充实范畎, $sans("Top")$-充实范畎等等. 这些定义郜是互盞等价的. 进入 21 䞖纪, <NAME> 写出了《高绎意象论》@HTT, 系统地描述了无穷范畎䞎无穷意象的理论. 同时, 《高绎代数》@HA 将䞉角范畎的理论拓展䞺皳定无穷范畎. 圚这䞪框架䞋, 同䌊范畎可以看䜜是无穷范畎包含信息的截断, 正劂基本矀是拓扑空闎所包含信息的截断. 这样, 之前提到的同䌊困隟就迎刃而解.
https://github.com/TeunSpithoven/Signals-And-Embedded-Systems
https://raw.githubusercontent.com/TeunSpithoven/Signals-And-Embedded-Systems/main/starter.typ
typst
// CHANGE THIS TO THE CORRECT PATH #import "./template/fhict-template.typ": * #import "./components/terms.typ": term_list #show: fhict_doc.with( title: "", subtitle: "", authors: ( ( name: "dsdss", ), ), version-history: ( ( version: "", date: "", author: [ddd], changes: "", ), ), pre-toc: [#include "./components/pre-toc.typ"], // bibliography-file: "my-sources.bib", glossary-terms: term_list, ) Hoi @banaan
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/table-lines_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(height: 50pt) Hello #table( columns: 4, [1], [2], [3], [4] )
https://github.com/ukihot/igonna
https://raw.githubusercontent.com/ukihot/igonna/main/articles/shell-work/reg.typ
typst
== 正芏衚珟 正芏衚珟は、文字列のパタヌンを衚珟するための蚘法である。 これにより、特定の条件を満たす文字列を効果的に怜玢したり、眮換したりするこずができる。 基本的な正芏衚珟を以䞋に瀺すが正芏衚珟のあずにコロン`:`を付䞎するため泚意しおほしい。 === Character Class文字 - [abc]: いずれか䞀぀ - => a, b, c - [^abc]: 含たない - => d など === Metacharactersメタ文字 - `.`: 任意の1文字 - `\n`: 改行コヌド - `^`: 行の先頭 - `$`: 行の末尟 - `\d`: 半角数字 - `\s`: 空癜 - `\S`: 空癜以倖すべお - `\w`:半角英数字ずアンダヌスコア - `\l`:半角英小文字 - `\u`:半角英倧文字 === Quantifiers量指定 - `*`: 盎前の芁玠が0回以䞊繰り返しワむルドカヌドずもいう - `+`: 盎前の芁玠が1回以䞊繰り返し - `?`: 盎前の芁玠が0回たたは1回 - {n}: 盎前のパタヌンをn回繰り返し === Grouping : グルヌピング - (): 括匧内のパタヌンを1぀の芁玠ずしお扱う == 正芏衚珟の䟋 電話番号は以䞋の正芏衚珟が適甚できる。 ```re ^(\d{3}-\d{4}-\d{4}|\d{10})$ ``` ハむフンを含む圢匏䟋: 123-4567-8901たたはハむフンなしの圢匏䟋: 1234567890にマッチする。
https://github.com/Complex2-Liu/macmo
https://raw.githubusercontent.com/Complex2-Liu/macmo/main/contests/2023/content/problem-12.typ
typst
#import "../lib/math.typ": problem, proof, note, ans #let triangle = math.class("normal", sym.triangle.stroked.t) #problem[ 劂䞋囟所瀺, 讟 $H$ 侎 $O$ 分别䞺䞉角圢 $A B C$ 的垂心及倖心. 试确定向量和 $arrow(O A) + arrow(O B) + arrow(O C) - arrow(O H)$, å…¶äž­ $arrow(O A)$, $arrow(O B)$, $arrow(O C)$ 及 $arrow(O H)$ 䞺向量, 并给出证明. ] #proof[ 事实䞊劂果䜠尝试过甚倍数倧法来炞 IMO 几䜕题, 䜠应该埈熟悉这样䞀䞪性莚: $h = a + b + c$, 所以这题的答案就是 $0$. #align(center)[ #image("../diagram-12.svg", width: 40%) ] 銖先讟 $arrow(O D) = arrow(O A) + arrow(O B)$, 因䞺 $triangle A O B$ 是等腰䞉角圢, 所以 $D$ 实际䞊是 $O$ 关于 $A B$ 的 relfection. 䞋面我提及䞀些平面几䜕垞见的基本囟圢和性莚, 䞀䞪合栌的孊生应该对歀比蟃熟悉: #enum(numbering: "(1)", indent: 1em)[ $C H D O$ 是平行四蟹圢. ][ $2 O M = C H$. ][ 讟 $C'$ 是 $C O$ 䞎倖接圆的亀点, 则 $C'$ 实际䞊是 $H$ 关于 $A B$ 的䞭点的 reflection. ][ $H$ 关于 $A B$ 的 relfection 萜圚倖接圆䞊. ] 这䞀切的性莚郜源于 $H$ 侎 $O$ 等角共蜭, i.e. $angle A C O = angle B C H$. ] #note[ 这里我们以点 $C$ 䞺_䞻视角_, 实际䞊䜠以 $A, B$ 䞺䞻视角也胜埗到平行的结论. ] /* vim: set ft=typst: */
https://github.com/lcharleux/LCharleux_Teaching_Typst
https://raw.githubusercontent.com/lcharleux/LCharleux_Teaching_Typst/main/README.md
markdown
MIT License
# Support de cours Auteur: <NAME> (<EMAIL>) Ce dépÎt contient des éléments de cours écrits avec Typst. ## Eléments disponibles ### [**MECA510** & **MECA512**] Rappels communs sur les vecteurs et les torseurs pour - [MECA510-512_Rappels.pdf](https://github.com/lcharleux/LCharleux_Teaching_Typst/raw/outputs/MECA510-512_Rappels.pdf) ### [**MECA510**] Statique des solides - [MECA510_Statique.pdf](https://github.com/lcharleux/LCharleux_Teaching_Typst/raw/outputs/MECA510_Statique.pdf) ### [**MECA512**] Cinématique des solides indéformables - [MECA512_Cinematique.pdf](https://github.com/lcharleux/LCharleux_Teaching_Typst/raw/outputs/MECA512_Cinematique.pdf) ### Divers essais de figures et d'environnements Typst - [demo.pdf](https://github.com/lcharleux/LCharleux_Teaching_Typst/raw/outputs/demo.pdf)
https://github.com/EpicEricEE/typst-marge
https://raw.githubusercontent.com/EpicEricEE/typst-marge/main/tests/overlap/multiple/test.typ
typst
MIT License
#import "/src/lib.typ": sidenote #set par(justify: true) #set page(width: 8cm, height: 20cm, margin: (outside: 4.5cm, rest: 5mm)) #let sidenote = sidenote.with(numbering: "1") #lorem(5) #sidenote[This is the first sidenote.] #for n in range(13) [ oh #sidenote[This one is moved down to prevent overlap.] ]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/let-19.typ
typst
Other
// Ref: false // Destructuring with an empty sink. #let (a: _, ..b) = (a: 1) #test(b, (:))
https://github.com/Mendrejk/thesis
https://raw.githubusercontent.com/Mendrejk/thesis/master/typst/main.typ
typst
#set page(margin: ( top: 0cm, bottom: 0cm, x: 0cm, )) #image("pd_mgr_pl.docx.svg") #set page(margin: ( top: 2.5cm, bottom: 2.5cm, x: 2.5cm, )) // #set text(font: "Montserrat") #set text( font: "Satoshi", size: 12pt ) #set par(justify: true) #show link: underline #set text(lang: "PL") #set page(numbering: "1") #set heading(numbering: "1.1)") #import "@preview/big-todo:0.2.0": * // Strona tytułowa // #set align(center) // #text(size: 22pt)[ // Politechnika Wrocławska\ // Wydział Informatyki i Telekomunikacji // ] // #line(length: 100%) // #align(left)[ // Kierunek: *IST* \ // Specjalność: *PSI* // ] // #block(spacing: 1em)#set text(font: "Atkinson Hyperlegible") // #text(size: 32pt)[ // PRACA DYPLOMOWA \ // MAGISTERSKA // ] // *Analiza moÅŒliwości wykorzystania metod uczenia maszynowego w rekonstrukcji nagrań dźwiękowych* // #block(spacing: 1em) // <NAME> // #block(spacing: 1em) // Opiekun pracy // *Dr inÅŒ <NAME>* // #set align(left) // #pagebreak(weak: true) #pagebreak(weak: true) #outline(indent: true) #pagebreak(weak: true) = Wstęp == Tło historyczne nagrań dźwiękowych Historia rejestracji dźwięku sięga połowy XIX wieku, kiedy to w 1857 roku <NAME> skonstruował fonoautograf - pierwsze urządzenie zdolne do zapisywania dźwięku @first-recorded-sound. Choć fonoautograf nie umoÅŒliwiał odtwarzania zarejestrowanych dźwięków, stanowił przełom w dziedzinie akustyki i zapoczątkował erę nagrań dźwiękowych. Pierwszym nagraniem uznawanym za moÅŒliwe do odtworzenia była francuska piosenka ludowa "<NAME>", zarejestrowana przez Scotta w 1860 roku @first-recorded-sound. Kolejnym kamieniem milowym w historii rejestracji dźwięku było wynalezienie fonografu przez <NAME> w 1877 roku. Urządzenie to nie tylko zapisywało dźwięk, ale równieÅŒ umoÅŒliwiało jego odtwarzanie, co otworzyło drogę do komercjalizacji nagrań dźwiękowych @edison-phonograph. W następnych dekadach technologia nagrywania ewoluowała, przechodząc przez etapy takie jak płyty gramofonowe, taśmy magnetyczne, aÅŒ po cyfrowe nośniki dźwięku @sound-recording-history. Kluczowe momenty w historii rejestracji dźwięku obejmują: 1. 1888 - Wprowadzenie płyt gramofonowych przez <NAME> @berliner-gramophone 2. 1920-1930 - Rozwój nagrań elektrycznych, znacząco poprawiających jakość dźwięku @electrical-recording 3. 1948 - Pojawienie się płyt długogrających (LP) @lp-record 4. 1963 - Wprowadzenie kaset kompaktowych przez Philips @compact-cassette 5. 1982 - Komercjalizacja płyt CD, rozpoczynająca erę cyfrową w muzyce @cd-introduction Rozwój technologii nagrywania miał ogromny wpływ na jakość i dostępność nagrań muzycznych. Wczesne nagrania charakteryzowały się ograniczonym pasmem częstotliwości, wysokim poziomem szumów i zniekształceń @early-recording-limitations. Wraz z postępem technologicznym, jakość dźwięku stopniowo się poprawiała, osiągając szczyt w erze cyfrowej. Jednocześnie, ewolucja nośników dźwięku od płyt gramofonowych przez kasety magnetyczne po pliki cyfrowe, znacząco zwiększyła dostępność muzyki dla szerokiego grona odbiorców @music-accessibility. Warto zauwaÅŒyć, ÅŒe mimo znacznego postępu technologicznego, wiele historycznych nagrań o ogromnej wartości kulturowej i artystycznej wciÄ…ÅŒ pozostaje w formie, która nie oddaje pełni ich oryginalnego brzmienia. Stwarza to potrzebę rozwoju zaawansowanych technik rekonstrukcji i restauracji nagrań, co stanowi jedno z głównych wyzwań współczesnej inÅŒynierii dźwięku i muzykologii @13 @historical-remastering-challenges. #pagebreak(weak: true) == Problematyka jakości historycznych nagrań Historyczne nagrania dźwiękowe, mimo ich ogromnej wartości kulturowej i artystycznej, często charakteryzują się niską jakością dźwięku, co stanowi istotne wyzwanie dla współczesnych słuchaczy i badaczy. Problematyka ta wynika z kilku kluczowych czynników. Ograniczenia wczesnych technologii nagrywania stanowiły główną przeszkodę w uzyskiwaniu wysokiej jakości dźwięku. Wczesne urządzenia rejestrujące charakteryzowały się wąskim pasmem przenoszenia, co skutkowało utratą zarówno niskich, jak i wysokich częstotliwości @early-recording-limitations. Typowe pasmo przenoszenia dla nagrań z początku XX wieku wynosiło zaledwie 250-2500 Hz, co znacząco ograniczało pełnię brzmienia instrumentów i głosu ludzkiego @audio-bandwidth-history. Ponadto, pierwsze systemy nagrywające wprowadzały znaczne szumy i zniekształcenia do rejestrowanego materiału, co było spowodowane niedoskonałościami mechanicznymi i elektrycznymi ówczesnych urządzeń @noise-in-early-recordings. Wpływ warunków przechowywania na degradację nośników jest kolejnym istotnym czynnikiem wpływającym na jakość historycznych nagrań. Nośniki analogowe, takie jak płyty gramofonowe czy taśmy magnetyczne, są szczególnie podatne na uszkodzenia fizyczne i chemiczne @analog-media-degradation. Ekspozycja na wilgoć, ekstremalne temperatury czy zanieczyszczenia powietrza moÅŒe prowadzić do nieodwracalnych zmian w strukturze nośnika, co przekłada się na pogorszenie jakości odtwarzanego dźwięku. W przypadku taśm magnetycznych, zjawisko print-through, polegające na przenoszeniu sygnału magnetycznego między sąsiednimi warstwami taśmy, moÅŒe wprowadzać dodatkowe zniekształcenia @print-through-effect. Przykłady znaczących nagrań historycznych o niskiej jakości dźwięku są liczne i obejmują wiele kluczowych momentów w historii muzyki. Jednym z najbardziej znanych jest nagranie <NAME> wykonującego fragment swojego "Tańca węgierskiego nr 1" z 1889 roku, które jest najstarszym znanym nagraniem muzyki powaÅŒnej @brahms-recording. Nagranie to, mimo swojej ogromnej wartości historycznej, charakteryzuje się wysokim poziomem szumów i zniekształceń. Innym przykładem są wczesne nagrania bluesa, takie jak "Crazy Blues" <NAME> z 1920 roku, które pomimo przełomowego znaczenia dla rozwoju gatunku, cechują się ograniczonym pasmem częstotliwości i obecnością szumów tła @early-blues-recordings. Wyzwania związane z odtwarzaniem i konserwacją starych nagrań są złoÅŒone i wymagają interdyscyplinarnego podejścia. Odtwarzanie historycznych nośników często wymaga specjalistycznego sprzętu, który sam w sobie moÅŒe być trudny do utrzymania w dobrym stanie @playback-equipment-challenges. Proces digitalizacji, choć kluczowy dla zachowania dziedzictwa audio, niesie ze sobą ryzyko wprowadzenia nowych zniekształceń lub utraty subtelnych niuansów oryginalnego nagrania @music-digitization-challenges. Ponadto, konserwacja fizycznych nośników wymaga stworzenia odpowiednich warunków przechowywania, co moÅŒe być kosztowne i logistycznie skomplikowane @preservation-storage-requirements. Dodatkowo, etyczne aspekty restauracji nagrań historycznych stanowią przedmiot debaty w środowisku muzycznym i konserwatorskim. Pytanie o to, jak daleko moÅŒna posunąć się w procesie cyfrowej rekonstrukcji bez naruszenia integralności oryginalnego dzieła, pozostaje otwarte @ethical-considerations-in-audio-restoration. Problematyka jakości historycznych nagrań stanowi zatem nie tylko wyzwanie techniczne, ale równieÅŒ kulturowe i etyczne. Rozwój zaawansowanych technik rekonstrukcji audio, w tym metod opartych na sztucznej inteligencji, otwiera nowe moÅŒliwości w zakresie przywracania i zachowania dziedzictwa dźwiękowego, jednocześnie stawiając przed badaczami i konserwatorami nowe pytania dotyczące granic ingerencji w historyczny materiał @ai-in-audio-restoration. #linebreak() == Znaczenie rekonstrukcji nagrań muzycznych Rekonstrukcja historycznych nagrań muzycznych odgrywa kluczową rolę w zachowaniu i promowaniu dziedzictwa kulturowego, oferując szereg korzyści zarówno dla badaczy, jak i dla szerszej publiczności. Wartość kulturowa i historyczna archiwów muzycznych jest nieoceniona. Nagrania dźwiękowe stanowią unikalne świadectwo rozwoju muzyki, technik wykonawczych i zmian w stylistyce muzycznej na przestrzeni lat @cultural-value-of-music-archives. Rekonstrukcja tych nagrań pozwala na zachowanie i udostępnienie szerszemu gronu odbiorców dzieł, które w przeciwnym razie mogłyby zostać zapomniane lub stać się niedostępne ze względu na degradację nośników @preservation-of-audio-heritage. Ponadto, zrekonstruowane nagrania umoÅŒliwiają współczesnym słuchaczom doświadczenie wykonań legendarnych artystów w jakości zbliÅŒonej do oryginalnej, co ma ogromne znaczenie dla zrozumienia historii muzyki i ewolucji stylów wykonawczych @historical-performance-practice. Rola zrekonstruowanych nagrań w badaniach muzykologicznych jest fundamentalna. Wysokiej jakości rekonstrukcje pozwalają naukowcom na dokładną analizę technik wykonawczych, interpretacji i stylów muzycznych z przeszłości @musicological-research-methods. UmoÅŒliwiają one równieÅŒ badanie ewolucji praktyk wykonawczych oraz porównywanie róŌnych interpretacji tego samego utworu na przestrzeni lat @performance-practice-evolution. W przypadku kompozytorów, którzy sami wykonywali swoje dzieła, zrekonstruowane nagrania stanowią bezcenne źródło informacji o intencjach twórców @composer-performances. Wpływ jakości nagrań na percepcję i popularność utworów muzycznych jest znaczący. Badania wskazują, ÅŒe słuchacze są bardziej skłonni do pozytywnego odbioru i częstszego słuchania nagrań o wyÅŒszej jakości dźwięku @music-audio-quality-perception. Rekonstrukcja historycznych nagrań moÅŒe przyczynić się do zwiększenia ich dostępności i atrakcyjności dla współczesnych odbiorców, potencjalnie prowadząc do odkrycia na nowo zapomnianych artystów lub utworów @rediscovery-of-forgotten-music. Ponadto, poprawa jakości dźwięku moÅŒe pomóc w lepszym zrozumieniu i docenieniu niuansów wykonania, które mogły być wcześniej niezauwaÅŒalne ze względu na ograniczenia techniczne oryginalnych nagrań @nuance-in-restored-recordings. #pagebreak(weak: true) Ekonomiczne aspekty rekonstrukcji nagrań są równieÅŒ istotne. Rynek remasterów i zrekonstruowanych nagrań historycznych stanowi znaczący segment przemysłu muzycznego @remastered-recordings-market. Wydawnictwa specjalizujące się w tego typu projektach, takie jak "<NAME>" czy "Naxos Historical", odnoszą sukcesy komercyjne, co świadczy o istnieniu popytu na wysokiej jakości wersje klasycznych nagrań @classical-music-reissues. Ponadto, rekonstrukcja nagrań moÅŒe prowadzić do powstania nowych źródeł przychodów dla artystów lub ich spadkobierców, a takÅŒe instytucji kulturalnych posiadających prawa do historycznych nagrań @remastered-recordings-market @remastering-education. Warto równieÅŒ zauwaÅŒyć, ÅŒe rekonstrukcja nagrań muzycznych ma istotne znaczenie dla edukacji muzycznej. Zrekonstruowane nagrania historyczne mogą słuÅŒyć jako cenne narzędzie dydaktyczne, umoÅŒliwiając studentom muzyki bezpośredni kontakt z wykonaniami wybitnych artystów z przeszłości i pomagając w zrozumieniu ewolucji stylów muzycznych. Podsumowując, znaczenie rekonstrukcji nagrań muzycznych wykracza daleko poza samą poprawę jakości dźwięku. Jest to proces o fundamentalnym znaczeniu dla zachowania dziedzictwa kulturowego, wspierania badań naukowych, edukacji muzycznej oraz rozwoju przemysłu muzycznego. W miarę jak technologie rekonstrukcji dźwięku, w tym metody oparte na sztucznej inteligencji, stają się coraz bardziej zaawansowane, moÅŒna oczekiwać, ÅŒe ich rola w przywracaniu i promowaniu historycznych nagrań będzie nadal rosła, przynosząc korzyści zarówno dla świata nauki, jak i dla miłośników muzyki na całym świecie @future-of-audio-restoration. #linebreak() == Cel i zakres pracy Głównym celem pracy jest dogłębna analiza i ocena potencjału metod uczenia maszynowego w dziedzinie rekonstrukcji nagrań dźwiękowych. Szczególny nacisk połoÅŒony zostanie na zbadanie efektywności zaawansowanych technik sztucznej inteligencji w przywracaniu jakości historycznym nagraniom muzycznym, koncentrując się na wyzwaniach, które tradycyjne metody przetwarzania sygnałów audio często pozostawiają nierozwiązane @ai-in-audio-restoration. W ramach pracy zostanie połoÅŒony nacisk na trzy kluczowe zagadnienia: 1. Eliminacja szumów i zakłóceń typowych dla historycznych nagrań @noise-reduction-techniques. 2. Poszerzanie pasma częstotliwościowego w celu wzbogacenia brzmienia nagrań o ograniczonym paśmie @bandwidth-extension-methods. 3. Rekonstrukcja uszkodzonych fragmentów audio, co jest szczególnie istotne w przypadku wielu historycznych nagrań @audio-inpainting-techniques. Podejście badawcze opiera się na implementacji i analizie wybranych metod uczenia maszynowego, skupiając się na architekturze *Generatywnych Sieci Przeciwstawnych* (Generative Adversarial Networks - GAN) @gan-in-audio-processing. Wybór tej architektury wynika z jej udokumentowanej skuteczności w zadaniach generatywnych i rekonstrukcyjnych w innych powiązanych dziedzinach, takich jak przetwarzanie obrazów @gan-image-restoration. W ramach badań zostanie podjęta próba opracowania zaawansowanego modelu GAN, który będzie wykorzystywał strukturę enkoder-dekoder z połączeniami skip dla generatora oraz architekturę konwolucyjną dla dyskryminatora. Zastosowany zostanie szereg technik normalizacji i regularyzacji, takich jak Batch Normalization, Spectral Normalization czy Gradient Penalty, celem poprawy stabilności i wydajności treningu. Kluczowym elementem będzie wykorzystanie kompleksowego zestawu funkcji strat, obejmującego Adversarial Loss, Content Loss, oraz specjalistyczne funkcje straty dla domen audio, jak Spectral Convergence Loss czy Phase-Aware Loss. Zaimplemenotwane zostaną zaawansowane techniki optymalizacji, w tym Adam Optimizer z niestandardowymi parametrami oraz dynamiczne dostosowywanie współczynnika uczenia. Metodologia badawcza obejmuje kilka kluczowych etapów. Na początku przygotowany zostanie obszerny zestaw danych treningowych, składający się z par nagrań oryginalnych i ich zdegradowanych wersji. Następnie zaimplementowane zostaną róŌnorodne warianty architektury GAN, dostosowane do specyfiki przetwarzania sygnałów audio. Proces treningu będzie wykorzystywał zaawansowane techniki, takie jak augmentacja danych czy przetwarzanie na spektrogramach STFT. Ostatnim etapem będzie wszechstronna ewaluacja wyników, łącząca wiele obiektywnych metryk jakości audio. Oczekiwane rezultaty pracy obejmują kompleksową ocenę skuteczności proponowanych metod uczenia maszynowego w zadaniach rekonstrukcji nagrań audio, w zestawieniu z tradycyjnymi technikami przetwarzania sygnałów. Przeprowadzona zostanie szczegółowa analizę wpływu róŌnych komponentów architektury i parametrów modeli na jakość rekonstrukcji. Istotnym elementem będzie identyfikacja mocnych stron i ograniczeń metod opartych na AI w kontekście specyficznych wyzwań związanych z restauracją historycznych nagrań muzycznych. Na podstawie uzyskanych wyników, zostaną sformułowane wnioski dotyczące potencjału sztucznej inteligencji w dziedzinie rekonstrukcji nagrań, wraz z rekomendacjami dla przyszłych badań i zastosowań praktycznych @ai-remastering-ethics. Realizacja powyÅŒszych celów ma potencjał nie tylko do znaczącego wkładu w dziedzinę przetwarzania sygnałów audio i uczenia maszynowego, ale równieÅŒ do praktycznego zastosowania w procesach restauracji i zachowania dziedzictwa muzycznego @preservation-of-audio-heritage. Wyniki pracy mogą znaleźć zastosowanie w instytucjach kulturalnych, archiwach dźwiękowych oraz w przemyśle muzycznym, przyczyniając się do lepszego zachowania i udostępnienia cennych nagrań historycznych szerokiej publiczności. #pagebreak(weak: true) = Zagadnienie poprawy jakości sygnałów dźwiękowych #linebreak() == Charakterystyka zniekształceń w nagraniach muzycznych Zagadnienie poprawy jakości sygnałów dźwiękowych jest ściśle związane z charakterystyką zniekształceń występujących w nagraniach muzycznych. Zrozumienie natury tych zniekształceń jest kluczowe dla opracowania skutecznych metod ich redukcji lub eliminacji. Główne typy zniekształceń występujących w nagraniach audio obejmują szereg problemów, które Szczotka @1 identyfikuje w swojej pracy, w tym szumy, brakujące dane, intermodulację i flutter. Szczególnie istotnym problemem, zwłaszcza w przypadku historycznych nagrań, jest ograniczenie pasma częstotliwościowego, co stanowi główny przedmiot badań w pracy nad BEHM-GAN @9. Wczesne systemy rejestracji dźwięku często były w stanie uchwycić jedynie wąski zakres częstotliwości, co prowadziło do utraty wielu detali dźwiękowych, szczególnie w zakresie wysokich i niskich tonów. Ponadto, jak wskazują badania nad rekonstrukcją mocno skompresowanych plików audio @11, kompresja moÅŒe wprowadzać dodatkowe zniekształcenia, które znacząco wpływają na jakość dźwięku. Zniekształcenia nieliniowe stanowią kolejną kategorię problemów, które mogą powaÅŒnie wpłynąć na jakość nagrania. Mogą one wynikać z niedoskonałości w procesie nagrywania, odtwarzania lub konwersji sygnału. Efektem tych zniekształceń moÅŒe być wprowadzenie niepoŌądanych harmonicznych składowych lub intermodulacji, co prowadzi do zmiany charakteru dźwięku @analog-media-degradation. W przypadku historycznych nagrań na nośnikach analogowych, takich jak płyty winylowe czy taśmy magnetyczne, często występują specyficzne rodzaje zniekształceń. Na przykład, efekt print-through w taśmach magnetycznych moÅŒe prowadzić do pojawienia się echa lub przesłuchów między sąsiednimi warstwami taśmy @print-through-effect. Z kolei w przypadku płyt winylowych, charakterystyczne trzaski i szumy powierzchniowe są nieodłącznym elementem, który moÅŒe znacząco wpływać na odbiór muzyki. Wpływ tych zniekształceń na percepcję muzyki i jej wartość artystyczną jest znaczący. Badania pokazują, ÅŒe jakość dźwięku ma istotny wpływ na to, jak słuchacze odbierają i oceniają muzykę @audio-quality-perception. Zniekształcenia mogą maskować subtelne niuanse wykonania, zmieniać barwę instrumentów czy głosu, a w skrajnych przypadkach całkowicie zniekształcać intencje artystyczne twórców. W kontekście historycznych nagrań, zniekształcenia mogą stanowić barierę w pełnym docenieniu wartości artystycznej i kulturowej danego dzieła. Nawet niewielkie poprawy w jakości dźwięku mogą znacząco wpłynąć na odbiór i interpretację wykonania. #pagebreak(weak: true) Jednocześnie warto zauwaÅŒyć, ÅŒe niektóre rodzaje zniekształceń, szczególnie te charakterystyczne dla określonych epok czy technologii nagrywania, mogą być postrzegane jako element autentyczności nagrania. To stawia przed procesem rekonstrukcji dźwięku wyzwanie znalezienia równowagi między poprawą jakości a zachowaniem historycznego charakteru nagrania @ethical-considerations-in-audio-restoration. Zrozumienie charakterystyki zniekształceń w nagraniach muzycznych jest kluczowym krokiem w opracowaniu skutecznych metod ich redukcji. W kolejnych częściach pracy skupię się na tym, jak zaawansowane techniki uczenia maszynowego, w szczególności sieci GAN, mogą być wykorzystane do adresowania tych problemów, jednocześnie starając się zachować artystyczną integralność oryginalnych nagrań. #linebreak() === Szumy i trzaski Szumy i trzaski stanowią jeden z najbardziej powszechnych problemów w historycznych nagraniach. Źródła szumów są róŌnorodne i obejmują ograniczenia sprzętowe, takie jak szum termiczny w elektronice, oraz zakłócenia elektromagnetyczne pochodzące z otoczenia lub samego sprzętu nagrywającego @noise-in-early-recordings. Charakterystyka trzasków jest często związana z przyczynami mechanicznymi, takimi jak uszkodzenia powierzchni płyt winylowych, lub elektronicznymi, wynikającymi z niedoskonałości w procesie zapisu lub odtwarzania. Wpływ szumów i trzasków na jakość odsłuchu jest znaczący. Mogą one maskować subtelne detale muzyczne, zmniejszać dynamikę nagrania oraz powodować zmęczenie słuchacza. W skrajnych przypadkach, intensywne szumy lub częste trzaski mogą całkowicie zaburzyć odbiór muzyki, czyniąc nagranie trudnym lub niemoÅŒliwym do słuchania @audio-quality-perception. #linebreak() === Ograniczenia pasma częstotliwościowego Historyczne ograniczenia w rejestrowaniu pełnego spektrum częstotliwości są jednym z kluczowych wyzwań w rekonstrukcji nagrań. Wczesne systemy nagrywania często były w stanie zarejestrować jedynie wąski zakres częstotliwości, typowo między 250 Hz a 2500 Hz @audio-bandwidth-history. To ograniczenie miało powaÅŒne konsekwencje dla brzmienia instrumentów i wokalu, prowadząc do utraty zarówno niskich tonów, nadających muzyce głębię i ciepło, jak i wysokich częstotliwości, odpowiedzialnych za klarowność i przestrzenność dźwięku. Znaczenie szerokiego pasma dla naturalności i pełni dźwięku jest trudne do przecenienia. Współczesne badania pokazują, ÅŒe ludzkie ucho jest zdolne do percepcji dźwięków w zakresie od około 20 Hz do 20 kHz, choć z wiekiem górna granica często się obniÅŒa. Pełne odtworzenie tego zakresu jest kluczowe dla realistycznego oddania brzmienia instrumentów i głosu ludzkiego. Rekonstrukcja szerokiego pasma częstotliwościowego w historycznych nagraniach stanowi zatem jedno z głównych zadań w procesie ich restauracji, co odzwierciedlają badania nad technikami takimi jak BEHM-GAN @9. #pagebreak(weak: true) === Zniekształcenia nieliniowe Zniekształcenia nieliniowe stanowią szczególnie złoÅŒoną kategorię problemów w rekonstrukcji nagrań audio. Definiuje się je jako odstępstwa od idealnej, liniowej relacji między sygnałem wejściowym a wyjściowym w systemie audio. Przyczyny tych zniekształceń mogą być róŌnorodne, obejmując między innymi nasycenie magnetyczne w taśmach analogowych, nieliniową charakterystykę lamp elektronowych w starszym sprzęcie nagrywającym, czy teÅŒ ograniczenia mechaniczne w przetwornikach @analog-media-degradation. Wpływ zniekształceń nieliniowych na nagrania jest znaczący i często subtelny. Prowadzą one do powstania dodatkowych harmonicznych składowych dźwięku, które nie były obecne w oryginalnym sygnale, oraz do zjawiska intermodulacji, gdzie róŌne częstotliwości wejściowe generują nowe, niepoŌądane tony. W rezultacie, brzmienie instrumentów moÅŒe ulec zmianie, a czystość i przejrzystość nagrania zostaje zaburzona. W niektórych przypadkach, zwłaszcza w muzyce elektronicznej czy rockowej, pewne formy zniekształceń nieliniowych mogą być celowo wprowadzane dla uzyskania poŌądanego efektu artystycznego. Korekcja zniekształceń nieliniowych stanowi jedno z największych wyzwań w procesie rekonstrukcji audio. W przeciwieństwie do zniekształceń liniowych, które moÅŒna stosunkowo łatwo skorygować za pomocą filtrów, zniekształcenia nieliniowe wymagają bardziej zaawansowanych technik. Tradycyjne metody często okazują się niewystarczające, co skłania badaczy do poszukiwania rozwiązań opartych na uczeniu maszynowym, takich jak adaptacyjne modelowanie nieliniowości czy zastosowanie głębokich sieci neuronowych @11. Trudność polega na tym, ÅŒe korekta tych zniekształceń wymaga precyzyjnego odtworzenia oryginalnego sygnału, co jest szczególnie skomplikowane w przypadku historycznych nagrań, gdzie brakuje referencyjnego materiału wysokiej jakości. #linebreak() == Tradycyjne metody poprawy jakości nagrań Ewolucja technik restauracji nagrań audio przeszła znaczącą transformację od prostych metod analogowych do zaawansowanych technik cyfrowych. Początkowo, restauracja nagrań opierała się głównie na fizycznej konserwacji nośników i optymalizacji sprzętu odtwarzającego. Wraz z rozwojem technologii cyfrowej, pojawiły się nowe moÅŒliwości manipulacji sygnałem audio, co znacząco rozszerzyło arsenał narzędzi dostępnych dla inÅŒynierów dźwięku @6. Nogales i inni w swojej pracy porównują efektywność klasycznych metod filtracji, takich jak filtr Wienera, z nowoczesnymi technikami głębokiego uczenia, ilustrując tę ewolucję. Jednak tradycyjne metody, mimo swojej skuteczności w wielu przypadkach, mają pewne ograniczenia. Głównym problemem jest trudność w selektywnym usuwaniu szumów bez wpływu na oryginalny sygnał muzyczny. Ponadto, rekonstrukcja utraconych lub zniekształconych częstotliwości często prowadzi do artefaktów dźwiękowych, które mogą być równie niepoŌądane jak oryginalne zniekształcenia. Cheddad i Cheddad @5 w swoich badaniach nad aktywną rekonstrukcją utraconych sygnałów audio podkreślają te ograniczenia, proponując jednocześnie nowe podejścia uzupełniające klasyczne techniki restauracji. === Filtracja cyfrowa Filtracja cyfrowa stanowi podstawę wielu technik restauracji audio. WyróŌniamy trzy podstawowe typy filtrów: dolnoprzepustowe, górnoprzepustowe i pasmowe. Dai i inni @8 w swoich badaniach nad super-rozdzielczością sygnałów muzycznych pokazują, jak tradycyjne metody filtracji mogą być rozszerzone i ulepszone dzięki zastosowaniu uczenia maszynowego. Zastosowanie filtracji w redukcji szumów polega na identyfikacji i selektywnym tłumieniu częstotliwości, w których dominuje szum. W korekcji częstotliwościowej, filtry są uÅŒywane do wzmacniania lub osłabiania określonych zakresów częstotliwości, co pozwala na poprawę balansu tonalnego nagrania. Wady filtracji cyfrowej obejmują ryzyko wprowadzenia artefaktów dźwiękowych, zwłaszcza przy agresywnym filtrowaniu, oraz potencjalną utratę subtelnych detali muzycznych. Zaletą jest natomiast precyzja i powtarzalność procesu, a takÅŒe moÅŒliwość niedestrukcyjnej edycji. #linebreak() === Remasterowanie Remasterowanie to proces poprawy jakości istniejącego nagrania, często z wykorzystaniem nowoczesnych technologii cyfrowych. Celem remasteringu jest poprawa ogólnej jakości dźwięku, zwiększenie głośności do współczesnych standardów oraz dostosowanie brzmienia do współczesnych systemów odtwarzania. Typowe etapy remasteringu obejmują normalizację, kompresję i korekcję EQ. Moliner i VÀlimÀki @8 w swojej pracy nad BEHM-GAN pokazują, jak nowoczesne techniki mogą być wykorzystane do przezwycięŌenia ograniczeń tradycyjnego remasteringu, szczególnie w kontekście rekonstrukcji wysokich częstotliwości w historycznych nagraniach muzycznych. Kontrowersje wokół remasteringu często dotyczą konfliktu między zachowaniem autentyczności oryginalnego nagrania a dÄ…ÅŒeniem do poprawy jakości dźwięku. Lattner i Nistal @11 w swoich badaniach nad stochastyczną restauracją mocno skompresowanych plików audio pokazują, jak zaawansowane techniki mogą być wykorzystane do poprawy jakości nagrań bez utraty ich oryginalnego charakteru, co stanowi istotny głos w debacie o autentyczności vs. jakość dźwięku. Mimo swoich ograniczeń, tradycyjne metody poprawy jakości nagrań wciÄ…ÅŒ odgrywają istotną rolę w procesie restauracji audio. JednakÅŒe, rosnąca złoÅŒoność wyzwań związanych z restauracją historycznych nagrań skłania badaczy do poszukiwania bardziej zaawansowanych rozwiązań, w tym metod opartych na sztucznej inteligencji, które mogą przezwycięŌyć niektóre z ograniczeń tradycyjnych technik. #pagebreak(weak: true) == Wyzwania w rekonstrukcji historycznych nagrań muzycznych Proces rekonstrukcji historycznych nagrań muzycznych stawia przed badaczami szereg złoÅŒonych wyzwań, wymagających interdyscyplinarnego podejścia i zaawansowanych technik przetwarzania sygnałów. Fundamentalnym problemem jest brak oryginalnych, wysokiej jakości źródeł dźwięku. Wiele historycznych nagrań przetrwało jedynie w formie znacznie zdegradowanej, często na nośnikach analogowych, które same uległy deterioracji @analog-media-degradation. Szczotka @1 zwraca uwagę, ÅŒe niedobór niezakłóconych sygnałów referencyjnych komplikuje proces uczenia modeli rekonstrukcyjnych, zmuszając do opracowywania zaawansowanych metod symulacji degradacji dźwięku. Identyfikacja i separacja poszczególnych instrumentów w nagraniach historycznych stanowi kolejne istotne wyzwanie. Dai i współpracownicy @8 podkreślają znaczenie tego aspektu, szczególnie w kontekście rekonstrukcji złoÅŒonych utworów orkiestrowych, gdzie ograniczenia wczesnych systemów nagrywania często prowadziły do nakładania się ścieÅŒek instrumentalnych. Kluczowym dylematem jest zachowanie autentyczności brzmienia przy jednoczesnej poprawie jakości. Moliner i VÀlimÀki @9 akcentują potrzebę znalezienia równowagi między poprawą technicznej jakości dźwięku a utrzymaniem charakterystycznego, historycznego brzmienia nagrania. Zbyt agresywna ingerencja moÅŒe prowadzić do utraty autentyczności i kontekstu historycznego. Etyczne aspekty ingerencji w historyczne nagrania budzą kontrowersje w środowisku muzycznym i konserwatorskim. Lattner i Nistal @11 poruszają kwestię granic dopuszczalnej modyfikacji oryginalnego nagrania, argumentując za ostroÅŒnym stosowaniem zaawansowanych technik rekonstrukcji. Techniczne ograniczenia w odtwarzaniu oryginalnego brzmienia wynikają z fundamentalnych róŌnic między historycznymi a współczesnymi technologiami audio. Cheddad @5 zwracają uwagę na trudności w wiernym odtworzeniu charakterystyki akustycznej dawnych sal koncertowych czy specyfiki historycznych instrumentów. ZłoÅŒoność wyzwań związanych z rekonstrukcją historycznych nagrań muzycznych wymaga kompleksowego podejścia. Integracja zaawansowanych technik przetwarzania sygnałów, metod uczenia maszynowego, wiedzy muzykologicznej oraz refleksji etycznej jest kluczowa dla skutecznego rozwiązywania napotkanych problemów. Badania prowadzone przez Nogalesa i in. @6 wskazują na potrzebę ciągłego doskonalenia istniejących metod oraz opracowywania nowych rozwiązań. Przyszłość rekonstrukcji nagrań historycznych zaleÅŒy od zdolności naukowców do tworzenia innowacyjnych technik, które będą w stanie sprostać unikalnym wymaganiom kaÅŒdego historycznego dzieła muzycznego, zachowując jednocześnie jego autentyczność i wartość artystyczną. #pagebreak(weak: true) = Metody sztucznej inteligencji w poprawie jakości nagrań dźwiękowych #linebreak() == Przegląd technik uczenia maszynowego w przetwarzaniu dźwięku Rozwój metod uczenia maszynowego w ostatnich latach przyniósł znaczący postęp w dziedzinie przetwarzania i analizy sygnałów dźwiękowych. Techniki te znajdują coraz szersze zastosowanie w poprawie jakości nagrań, rekonstrukcji uszkodzonych fragmentów oraz ekstrakcji informacji z sygnałów audio. #linebreak() === Ewolucja zastosowań uczenia maszynowego w dziedzinie audio Początki wykorzystania uczenia maszynowego w przetwarzaniu dźwięku sięgają lat 90. XX wieku, kiedy to zaczęto stosować proste modele statystyczne do klasyfikacji gatunków muzycznych czy rozpoznawania mowy @4. Wraz z rozwojem mocy obliczeniowej komputerów oraz postępem w dziedzinie sztucznych sieci neuronowych, nastąpił gwałtowny wzrost zainteresowania tymi technikami w kontekście analizy i syntezy dźwięku. Przełomowym momentem było zastosowanie głębokich sieci neuronowych, które umoÅŒliwiły modelowanie złoÅŒonych zaleÅŒności w sygnałach audio. Badania wykazały, ÅŒe głębokie sieci konwolucyjne potrafią skutecznie wyodrębniać cechy charakterystyczne dźwięków, co otworzyło drogę do bardziej zaawansowanych zastosowań, takich jak separacja źródeł dźwięku czy poprawa jakości nagrań. W ostatnich latach coraz większą popularność zyskują modele generatywne, takie jak sieci GAN (Generative Adversarial Networks) czy modele dyfuzyjne, które umoÅŒliwiają nie tylko analizę, ale takÅŒe syntezę wysokiej jakości sygnałów audio @8. Te zaawansowane techniki znajdują zastosowanie w rekonstrukcji uszkodzonych nagrań oraz rozszerzaniu pasma częstotliwości starych rejestracji dźwiękowych. #linebreak() === Klasyfikacja głównych podejść: nadzorowane, nienadzorowane, półnadzorowane W kontekście przetwarzania sygnałów audio moÅŒna wyróŌnić trzy główne podejścia do uczenia maszynowego: a) Uczenie nadzorowane: W tym podejściu model uczy się na podstawie par danych wejściowych i oczekiwanych wyników. W dziedzinie audio moÅŒe to obejmować uczenie się mapowania między zaszumionymi a czystymi nagraniami w celu usuwania szumów, czy teÅŒ klasyfikację instrumentów na podstawie oznaczonych próbek dźwiękowych. Przykładem zastosowania uczenia nadzorowanego jest praca Nogales A. i innych @6, w której autorzy wykorzystali konwolucyjne sieci neuronowe do rekonstrukcji uszkodzonych nagrań audio. b) Uczenie nienadzorowane: Techniki nienadzorowane skupiają się na odkrywaniu ukrytych struktur w danych bez korzystania z etykiet. W kontekście audio moÅŒe to obejmować grupowanie podobnych dźwięków czy wyodrębnianie cech charakterystycznych bez uprzedniej wiedzy o ich znaczeniu. c) Uczenie półnadzorowane: To podejście łączy elementy uczenia nadzorowanego i nienadzorowanego, wykorzystując zarówno oznaczone, jak i nieoznaczone dane. Jest szczególnie przydatne w sytuacjach, gdy dostępna jest ograniczona ilość oznaczonych próbek, co często ma miejsce w przypadku historycznych nagrań audio. #linebreak() === Rola reprezentacji dźwięku w uczeniu maszynowym: spektrogramy, cechy MFCC, surowe próbki Wybór odpowiedniej reprezentacji dźwięku ma kluczowe znaczenie dla skuteczności modeli uczenia maszynowego w zadaniach przetwarzania audio. a) Spektrogramy: Przedstawiają rozkład częstotliwości sygnału w czasie, co pozwala na analizę zarówno cech czasowych, jak i częstotliwościowych. Spektrogramy są szczególnie przydatne w zadaniach takich jak separacja źródeł czy poprawa jakości nagrań. W pracy @8 autorzy wykorzystali spektrogramy logarytmiczne jako wejście do modelu GAN, osiągając dobre wyniki w zadaniu rozszerzania pasma częstotliwości nagrań muzycznych. b) Cechy MFCC (Mel-Frequency Cepstral Coefficients): Reprezentują charakterystykę widmową dźwięku w sposób zbliÅŒony do ludzkiego systemu słuchowego. MFCC są często stosowane w zadaniach klasyfikacji i rozpoznawania mowy. Badania wykazały, ÅŒe cechy MFCC mogą być skutecznie wykorzystywane w ocenie jakości rekonstrukcji nagrań historycznych. c) Surowe próbki: Niektóre modele, szczególnie te oparte na sieciach konwolucyjnych, mogą pracować bezpośrednio na surowych próbkach audio. Podejście to eliminuje potrzebę ręcznego projektowania cech, pozwalając modelowi na samodzielne odkrywanie istotnych wzorców w sygnale. Wybór odpowiedniej reprezentacji zaleÅŒy od specyfiki zadania oraz architektury modelu. Coraz częściej stosuje się teÅŒ podejścia hybrydowe, łączące róŌne reprezentacje w celu uzyskania lepszych wyników. #pagebreak(weak: true) Techniki uczenia maszynowego oferują szerokie spektrum moÅŒliwości w dziedzinie przetwarzania i poprawy jakości sygnałów audio. Ewolucja tych metod, od prostych modeli statystycznych po zaawansowane sieci generatywne, umoÅŒliwia rozwiązywanie coraz bardziej złoÅŒonych problemów związanych z rekonstrukcją i poprawą jakości nagrań dźwiękowych. W kontekście przetwarzania sygnałów audio kluczowe znaczenie ma odpowiedni dobór podejścia (nadzorowane, nienadzorowane lub półnadzorowane) oraz reprezentacji dźwięku. Właściwe decyzje w tym zakresie pozwalają na optymalne wykorzystanie potencjału uczenia maszynowego, co przekłada się na skuteczność i efektywność opracowywanych rozwiązań. Postęp w tej dziedzinie otwiera nowe moÅŒliwości w zakresie zachowania i odtwarzania dziedzictwa kulturowego, jakim są historyczne nagrania dźwiękowe. #linebreak() == Sieci neuronowe w zadaniach audio Sieci neuronowe stały się fundamentalnym narzędziem w przetwarzaniu sygnałów dźwiękowych, oferując niezrównaną elastyczność i zdolność do modelowania złoÅŒonych zaleÅŒności. Ich adaptacyjna natura pozwala na automatyczne wyodrębnianie istotnych cech z surowych danych audio, co czyni je niezwykle skutecznymi w szerokiej gamie zastosowań - od klasyfikacji dźwięków po zaawansowaną syntezę mowy. RóŌnorodność architektur sieci neuronowych pozwala na dobór optymalnego rozwiązania do specyfiki danego zadania audio. Konwolucyjne sieci neuronowe (CNN) wykazują szczególną skuteczność w analizie lokalnych wzorców w spektrogramach, podczas gdy rekurencyjne sieci neuronowe (RNN) doskonale radzą sobie z modelowaniem długoterminowych zaleÅŒności czasowych. Autoenkodery z kolei znajdują zastosowanie w kompresji i odszumianiu sygnałów, oferując moÅŒliwość redukcji wymiarowości przy zachowaniu kluczowych cech dźwięku. Efektywność poszczególnych architektur moÅŒe się znacząco róŌnić w zaleÅŒności od konkretnego zadania. Badania empiryczne wskazują, ÅŒe hybrydowe podejścia, łączące zalety róŌnych typów sieci, często prowadzą do najlepszych rezultatów w złoÅŒonych scenariuszach przetwarzania audio. #linebreak() === Konwolucyjne sieci neuronowe (CNN) Konwolucyjne sieci neuronowe zrewolucjonizowały sposób, w jaki analizujemy sygnały audio. Ich unikalna architektura, inspirowana biologicznym systemem wzrokowym, okazała się niezwykle skuteczna w wyodrębnianiu hierarchicznych cech z reprezentacji czasowo-częstotliwościowych dźwięku. W kontekście analizy audio, CNN operują najczęściej na spektrogramach, traktując je jako dwuwymiarowe "obrazy" dźwięku. Warstwy konwolucyjne działają jak filtry, wyodrębniając lokalne wzorce spektralne, które mogą odpowiadać konkretnym cechom akustycznym, takim jak akordy, formanty czy charakterystyki instrumentów. Klasyfikacja dźwięków i rozpoznawanie mowy to obszary, w których sieci CNN wykazują szczególną skuteczność. W zadaniach identyfikacji gatunków muzycznych czy detekcji słów kluczowych, sieci te potrafią automatycznie nauczyć się rozpoznawać istotne cechy spektralne, często przewyÅŒszając tradycyjne metody oparte na ręcznie projektowanych cechach. Adaptacje CNN do specyfiki danych dźwiękowych obejmują m.in. zastosowanie dilated convolutions. Ta technika pozwala na zwiększenie pola recepcyjnego sieci bez zwiększania liczby parametrów, co jest szczególnie przydatne w modelowaniu długoterminowych zaleÅŒności czasowych w sygnałach audio. Dilated CNN znalazły zastosowanie m.in. w generowaniu dźwięku w czasie rzeczywistym. === Rekurencyjne sieci neuronowe (RNN) Rekurencyjne sieci neuronowe wyróŌniają się zdolnością do przetwarzania sekwencji danych, co czyni je naturalnym wyborem do analizy sygnałów audio. Ich architektura, oparta na pętlach sprzęŌenia zwrotnego, pozwala na uwzględnienie kontekstu czasowego w przetwarzaniu dźwięku, co jest kluczowe w wielu zadaniach, takich jak modelowanie muzyki czy rozpoznawanie mowy ciągłej. LSTM (Long Short-Term Memory) i GRU (Gated Recurrent Unit) to popularni "następcy" klasycznych RNN, którzy rozwiązują problem zanikającego gradientu. Te zaawansowane jednostki rekurencyjne potrafią efektywnie przetwarzać długie sekwencje audio, zachowując informacje o odległych zaleÅŒnościach czasowych. W syntezie mowy, modele oparte na LSTM wykazały się zdolnością do generowania naturalnie brzmiących wypowiedzi, uwzględniających niuanse prozodyczne. W dziedzinie modelowania muzyki, sieci rekurencyjne znalazły zastosowanie w generowaniu sekwencji akordów czy komponowaniu melodii, potrafiąc uchwycić złoÅŒone struktury harmoniczne i rytmiczne. #linebreak() === Autoenkodery Autoenkodery to fascynująca klasa sieci neuronowych, której głównym zadaniem jest nauczenie się efektywnej, skompresowanej reprezentacji danych wejściowych. W kontekście audio, ta zdolność do redukcji wymiarowości otwiera szereg moÅŒliwości - od kompresji sygnałów po zaawansowane techniki odszumiania. Klasyczny autoenkoder składa się z enkodera, który "ściska" dane wejściowe do niÅŒszego wymiaru, oraz dekodera, który próbuje odtworzyć oryginalne dane z tej skompresowanej reprezentacji. W zastosowaniach audio, autoenkodery mogą nauczyć się reprezentacji, które zachowują kluczowe cechy dźwięku, jednocześnie eliminując szum czy niepoŌądane artefakty. #pagebreak(weak: true) Wariacyjne autoenkodery (VAE) idą o krok dalej, wprowadzając element losowości do procesu kodowania. Ta cecha czyni je szczególnie przydatnymi w generowaniu nowych, unikalnych dźwięków, zachowujących charakterystykę danych treningowych. VAE znalazły zastosowanie m.in. w syntezie mowy i efektów dźwiękowych. Splotowe autoenkodery (CAE) łączą zalety autoenkoderów i CNN, co czyni je skutecznymi w zadaniach związanych z przetwarzaniem spektrogramów. Ich zdolność do wyodrębniania lokalnych cech spektralnych przy jednoczesnej redukcji wymiarowości sprawia, ÅŒe są cennym narzędziem w odszumianiu i restauracji nagrań audio. #linebreak() == Generatywne sieci przeciwstawne (GAN) w kontekście audio Generatywne sieci przeciwstawne (GAN) to innowacyjna architektura uczenia maszynowego, która zrewolucjonizowała podejście do generacji i przetwarzania danych, w tym sygnałów audio. Podstawowa idea GAN opiera się na "rywalizacji" dwóch sieci neuronowych: generatora, który tworzy nowe dane, oraz dyskryminatora, który ocenia ich autentyczność. Ta koncepcja, początkowo opracowana dla obrazów, została z powodzeniem zaadaptowana do domeny audio, otwierając nowe moÅŒliwości w syntezie i manipulacji dźwiękiem. W kontekście danych dźwiękowych, architektura GAN wymaga specyficznego podejścia. Generator często pracuje na reprezentacjach czasowo-częstotliwościowych, takich jak spektrogramy, tworząc nowe "obrazy" dźwięku. Dyskryminator z kolei analizuje te reprezentacje, ucząc się rozróŌniać między autentycznymi a wygenerowanymi próbkami. Kluczowym wyzwaniem jest zapewnienie, aby wygenerowane spektrogramy były nie tylko realistyczne wizualnie, ale takÅŒe przekładały się na spójne i naturalne brzmienia po konwersji z powrotem do domeny czasowej. Zastosowania GAN w dziedzinie audio są niezwykle róŌnorodne. W syntezie dźwięku, sieci te potrafią generować realistyczne efekty dźwiękowe czy nawet całe utwory muzyczne, naśladując style konkretnych artystów. W zadaniach super-rozdzielczości audio, sieci GAN wykazują imponującą zdolność do rekonstrukcji wysokich częstotliwości w nagraniach o ograniczonym paśmie, co znajduje zastosowanie w restauracji historycznych nagrań. Transfer stylu audio, inspirowany podobnymi technikami w przetwarzaniu obrazów, pozwala na przenoszenie charakterystyk brzmieniowych między róŌnymi nagraniami, otwierając fascynujące moÅŒliwości w produkcji muzycznej. Trening GAN dla sygnałów audio niesie ze sobą specyficzne wyzwania. Niestabilność treningu, charakterystyczna dla GAN, jest szczególnie problematyczna w domenie audio, gdzie nawet drobne artefakty mogą znacząco wpłynąć na jakość percepcyjną. Projektowanie odpowiednich funkcji straty, które uwzględniają specyfikę ludzkiego słuchu, stanowi kolejne wyzwanie. Ponadto, zapewnienie spójności fazowej w generowanych spektrogramach wymaga dodatkowych technik, takich jak wykorzystanie informacji o fazie lub bezpośrednie generowanie w domenie czasowej. #pagebreak(weak: true) == Modele dyfuzyjne w rekonstrukcji dźwięku Modele dyfuzyjne reprezentują nowatorskie podejście do generacji danych, które w ostatnich latach zyskało ogromną popularność w dziedzinie przetwarzania dźwięku. U podstaw tej koncepcji leÅŒy idea stopniowego dodawania szumu do danych, a następnie uczenia się procesu odwrotnego - usuwania szumu, co prowadzi do generacji nowych, wysokiej jakości próbek. Proces generacji dźwięku w modelach dyfuzyjnych moÅŒna podzielić na dwa etapy. W pierwszym, zwanym procesem forward, do oryginalnego sygnału audio stopniowo dodawany jest szum gaussowski, aÅŒ do otrzymania czystego szumu. W drugim etapie, zwanym procesem reverse, model uczy się krok po kroku usuwać ten szum, rozpoczynając od losowej próbki szumu i stopniowo przekształcając ją w realistyczny sygnał audio. Ta unikalna architektura pozwala na generację dźwięku o wysokiej jakości i szczegółowości. Zastosowania modeli dyfuzyjnych w rekonstrukcji i syntezie audio są obiecujące. W zadaniach rekonstrukcji uszkodzonych nagrań, modele te wykazują zdolność do "wypełniania" brakujących fragmentów w sposób spójny z resztą nagrania. W syntezie mowy, modele dyfuzyjne potrafią generować niezwykle naturalne i ekspresyjne wypowiedzi, uwzględniając subtelne niuanse prozodyczne. W porównaniu z GAN, modele dyfuzyjne oferują kilka istotnych zalet w kontekście zadań audio. Przede wszystkim, ich trening jest bardziej stabilny i przewidywalny, co przekłada się na konsekwentnie wysoką jakość generowanych próbek. Modele dyfuzyjne wykazują równieÅŒ lepszą zdolność do modelowania róŌnorodności danych, unikając problemu "mode collapse" charakterystycznego dla GAN. JednakÅŒe, kosztem tych zalet jest zazwyczaj dłuÅŒszy czas generacji, co moÅŒe ograniczać ich zastosowanie w aplikacjach czasu rzeczywistego. Aktualne osiągnięcia w dziedzinie modeli dyfuzyjnych dla dźwięku są imponujące. Modele takie jak WaveGrad czy DiffWave demonstrują wysoką jakość w syntezie mowy, często przewyÅŒszając modele autoregresyjne. W dziedzinie muzyki, modele dyfuzyjne pokazują rezultaty w generacji instrumentalnej i wokalnej, zachowując niezwykłą szczegółowość brzmienia. Eksplorowane są techniki łączenia modeli dyfuzyjnych z innymi architekturami, takimi jak transformery, w celu lepszego modelowania długoterminowych zaleÅŒności w sygnałach audio. Rosnące zainteresowanie multimodalnych modeli dyfuzyjnych otwiera moÅŒliwości syntezy audio skorelowanej z innymi modalnościami, takimi jak obraz czy tekst. Zarówno GAN, jak i modele dyfuzyjne reprezentują przełomowe podejścia w dziedzinie generacji i rekonstrukcji dźwięku. KaÅŒda z tych technik oferuje unikalne zalety. Dalszy rozwój tych metod niewątpliwie przyczyni się do postępu w takich dziedzinach jak restauracja historycznych nagrań, synteza mowy czy produkcja muzyczna, otwierając nowe horyzonty w przetwarzaniu i generacji sygnałów audio. = Zastosowania metod sztucznej inteligencji w rekonstrukcji nagrań muzycznych #linebreak() == Ogólny przegląd praktycznych zastosowań AI w restauracji nagrań Zastosowanie sztucznej inteligencji (AI) w rekonstrukcji nagrań muzycznych stale zyskuje na popularności. Tradycyjne techniki restauracji, jak filtry analogowe i cyfrowe, miały swoje ograniczenia, szczególnie w kontekście skomplikowanych sygnałów muzycznych. Nowoczesne metody AI, w tym głębokie uczenie i generatywne sieci przeciwstawne (GAN), oferują nowe moÅŒliwości w przywracaniu uszkodzonych i zdegradowanych nagrań muzycznych, poprawiając ich jakość w sposób, który wcześniej nie był moÅŒliwy. Przykładowo, praca Dai et al. pokazuje, jak sieci GAN mogą być wykorzystane do poprawy rozdzielczości sygnałów muzycznych, co prowadzi do bardziej precyzyjnej i szczegółowej rekonstrukcji dźwięku @8. Z kolei badania przedstawione przez Nogales et al. wykorzystują głębokie autoenkodery do przywracania jakości nagrań, przewyÅŒszając tradycyjne metody, takie jak filtracja Wienera @6. #linebreak() == Porównanie skuteczności metod AI z tradycyjnymi technikami Tradycyjne metody rekonstrukcji nagrań muzycznych, takie jak filtry Wienera czy metody interpolacji oparte na DSP, są powszechnie stosowane, ale ich skuteczność jest ograniczona. Wprowadzenie technik AI, w szczególności głębokich sieci neuronowych, znacząco poprawiło jakość odtwarzania i rekonstrukcji nagrań. Przykładem jest zastosowanie GAN do poprawy jakości mocno skompresowanych plików MP3. Artykuł z MDPI pokazuje, jak stochastyczne generatory oparte na GAN są w stanie wytworzyć próbki bliÅŒsze oryginałowi niÅŒ tradycyjne metody DSP, szczególnie w przypadku dźwięków perkusyjnych i wysokich częstotliwości @11. Dodatkowo, metody takie jak nienegatywna faktoryzacja macierzy (NMF) i głębokie sieci neuronowe (DNN) zostały zastosowane do odrestaurowania historycznych nagrań fortepianowych, jak pokazuje praca na temat rekonstrukcji nagrania Johannesa Brahmsa z 1889 roku @4. #pagebreak(weak: true) == Wpływ postępu w dziedzinie AI na moÅŒliwości rekonstrukcji nagrań Postęp w dziedzinie AI, a zwłaszcza rozwój modeli dyfuzyjnych i GAN, otworzył nowe moÅŒliwości w rekonstrukcji nagrań muzycznych. Modele te pozwalają na generowanie dźwięku o wysokiej jakości, nawet z uszkodzonych i silnie skompresowanych źródeł. Artykuł na temat modeli dyfuzyjnych dla restauracji dźwięku przedstawia kompleksowe omówienie tego tematu, podkreślając ich zdolność do generowania naturalnie brzmiących próbek dźwiękowych @13. #linebreak() == Usuwanie szumów i zakłóceń Usuwanie szumów i zakłóceń z nagrań muzycznych stanowi kluczowe wyzwanie w procesie rekonstrukcji dźwięku, szczególnie w kontekście metod opartych na sztucznej inteligencji. Nagrania muzyczne mogą być naraÅŒone na róŌnorodne typy szumów, takie jak szumy tła, impulsowe zakłócenia oraz artefakty powstałe podczas konwersji analogowo-cyfrowej. W celu ich skutecznego usunięcia, konieczne jest zrozumienie charakterystyki kaÅŒdego z tych szumów, a takÅŒe ich wpływu na jakość odbioru dźwięku przez słuchacza. W ostatnich latach, metody oparte na sztucznej inteligencji, w tym sieci neuronowe, zyskały na popularności w kontekście identyfikacji i separacji szumów od sygnału muzycznego. Zastosowanie autoenkoderów oraz sieci GAN okazało się szczególnie efektywne w odszumianiu nagrań, co potwierdzają liczne badania @14. Autoenkodery, ze względu na swoją zdolność do kompresji danych i ich rekonstrukcji, umoÅŒliwiają wyodrębnienie istotnych cech sygnału, a jednocześnie eliminację niepoŌądanych szumów. Z kolei sieci GAN, które składają się z generatora i dyskryminatora, pozwalają na generowanie bardziej realistycznych rekonstrukcji sygnału dźwiękowego, dzięki czemu moÅŒliwe jest zachowanie większej ilości detali muzycznych podczas usuwania szumów @14. Porównanie efektywności róŌnych architektur sieci neuronowych w zadaniu usuwania szumów wykazało, ÅŒe tradycyjne metody oparte na filtracji spektralnej ustępują nowoczesnym podejściom opartym na głębokim uczeniu się. Przykładem moÅŒe być zastosowanie bloków rezydualnych oraz technik normalizacji w architekturze sieci, co prowadzi do znaczącej poprawy jakości odszumionego dźwięku @14. Niemniej jednak, wyzwania związane z zachowaniem detali muzycznych podczas usuwania szumów pozostają istotnym problemem. Głębokie sieci uczące się często mają tendencję do usuwania nie tylko szumów, ale równieÅŒ subtelnych niuansów muzycznych, co moÅŒe prowadzić do utraty pierwotnego charakteru nagrania. Aby zminimalizować ten efekt, stosowane są zaawansowane funkcje strat, takie jak Perceptual Loss czy Signal-to-Noise Ratio Loss, które pomagają w zachowaniu jak największej ilości oryginalnych detali dźwiękowych @15. #pagebreak(weak: true) == Rozszerzanie pasma częstotliwościowego Rozszerzanie pasma częstotliwościowego w historycznych nagraniach stanowi istotne wyzwanie technologiczne i badawcze, mające na celu poprawę jakości dźwięku przy zachowaniu integralności oryginalnego materiału. #linebreak() === Problematyka ograniczonego pasma w historycznych nagraniach Historyczne nagrania, z uwagi na ograniczenia technologiczne ówczesnych systemów rejestracji dźwięku, często charakteryzują się ograniczonym pasmem przenoszenia, co prowadzi do utraty wyÅŒszych częstotliwości i w rezultacie zuboÅŒenia jakości dźwięku. Tego typu nagrania są zwykle poddawane cyfryzacji, a następnie obróbce mającej na celu odzyskanie jak największej ilości utraconej informacji. Rozszerzanie pasma częstotliwościowego staje się tutaj kluczowym narzędziem, które umoÅŒliwia przywrócenie pełniejszego brzmienia nagrania, a co za tym idzie, zbliÅŒenie się do oryginalnego zamysłu artystycznego twórcy. #linebreak() === Techniki AI do estymacji i syntezy brakujących wysokich częstotliwości Zastosowanie sztucznej inteligencji, w szczególności technik uczenia maszynowego, przyniosło nowe moÅŒliwości w zakresie rekonstrukcji brakujących informacji w historycznych nagraniach. Przykładem tego jest metoda Blind Audio Bandwidth Extension (BABE), która wykorzystuje model dyfuzyjny do estymacji brakujących wysokich częstotliwości w nagraniach o ograniczonym paśmie przenoszenia. Model ten, działający w tzw. trybie zero-shot, pozwala na realistyczne odtworzenie utraconych części spektrum częstotliwości bez konieczności znajomości szczegółów degradacji sygnału @16. Testy subiektywne potwierdziły, ÅŒe zastosowanie BABE znacząco poprawia jakość dźwięku w nagraniach historycznych @16. #linebreak() === Zastosowanie sieci GAN w super-rozdzielczości spektralnej Sieci generatywne (GAN) znalazły szerokie zastosowanie w przetwarzaniu dźwięku, w tym w rozszerzaniu pasma częstotliwościowego. Metoda BEHM-GAN wykorzystuje sieci GAN do rozszerzania pasma częstotliwościowego w nagraniach muzycznych z początku XX wieku. Zastosowanie GAN pozwala na realistyczną syntezę brakujących wysokich częstotliwości, co przekłada się na znaczną poprawę percepcyjnej jakości dźwięku @9. #pagebreak(weak: true) === Metody oceny jakości rozszerzonego pasma częstotliwościowego Ocena jakości dźwięku po zastosowaniu technik rozszerzania pasma częstotliwościowego jest kluczowym etapem procesu. W przypadku historycznych nagrań ocena ta jest szczególnie istotna, poniewaÅŒ dodanie nowych informacji moÅŒe wpłynąć na oryginalny charakter nagrania. W związku z tym stosuje się zarówno metody obiektywne, jak i subiektywne. Przykładem są testy preferencyjne, w których słuchacze oceniają jakość dźwięku pod kątem jego spójności i naturalności @16. #linebreak() === Etyczne aspekty dodawania nowych informacji do historycznych nagrań Dodawanie nowych informacji do historycznych nagrań rodzi szereg pytań etycznych. Główna kwestia dotyczy tego, na ile moÅŒemy modyfikować oryginalny materiał, by nie zatracić jego autentyczności. Rozszerzanie pasma częstotliwościowego za pomocą AI i GAN musi być prowadzone z poszanowaniem dla oryginalnego dzieła, aby zachować jego integralność i nie wprowadzać zmian, które mogłyby zostać odebrane jako manipulacje oryginałem @17 @3. #linebreak() == Uzupełnianie brakujących fragmentów #linebreak() === Przyczyny i charakterystyka ubytków Braki w nagraniach muzycznych mogą mieć róŌnorodne przyczyny, takie jak uszkodzenia fizyczne nośników, błędy w digitalizacji, czy celowe wycięcia fragmentów w procesie edycji. Charakterystyka tych ubytków jest równie zróŌnicowana – od krótkich, niemal niezauwaÅŒalnych przerw, po dłuÅŒsze fragmenty, które znacząco wpływają na integralność utworu muzycznego. W związku z tym, rekonstrukcja brakujących fragmentów stała się kluczowym zadaniem w konserwacji i restauracji nagrań dźwiękowych. #linebreak() === Metody AI do interpolacji brakujących fragmentów W ostatnich latach znaczący postęp dokonał się w dziedzinie sztucznej inteligencji, szczególnie w kontekście interpolacji brakujących danych audio. Metody te wykorzystują zaawansowane modele uczenia maszynowego, które są zdolne do odtwarzania brakujących próbek dźwiękowych w sposób, który jest trudny do odróŌnienia od oryginału. Na przykład, techniki oparte na modelach autoregresyjnych, takich jak Rekurencyjne Sieci Neuronowe (RNN) i Long Short-Term Memory (LSTM), umoÅŒliwiają przewidywanie brakujących próbek na podstawie istniejącego kontekstu dźwiękowego, co prowadzi do bardziej naturalnej rekonstrukcji @18. #linebreak() === Wykorzystanie kontekstu muzycznego w rekonstrukcji ubytków Modele te mogą efektywnie wykorzystywać kontekst muzyczny, analizując struktury melodyczne, rytmiczne i harmoniczne, co pozwala na precyzyjne wypełnienie braków w sposób, który zachowuje spójność i naturalność nagrania. WaÅŒnym aspektem jest tutaj takÅŒe ocena spójności muzycznej rekonstruowanych fragmentów, która moÅŒe być przeprowadzona zarówno subiektywnie, poprzez testy odsłuchowe, jak i obiektywnie, z wykorzystaniem narzędzi analitycznych @1. #linebreak() == Poprawa jakości mocno skompresowanych plików audio Kompresja stratna, taka jak MP3, AAC, czy OGG, jest powszechnie stosowana w celu redukcji rozmiaru plików audio. Jednak proces ten nieodłącznie wiÄ…ÅŒe się z utratą pewnych informacji, co wpływa na jakość dźwięku. W szczególności mogą pojawić się artefakty, takie jak brakujące detale w wyÅŒszych częstotliwościach czy zniekształcenia perkusji, które negatywnie wpływają na odbiór muzyczny @8. Aby przeciwdziałać tym problemom, rozwijane są techniki oparte na sztucznej inteligencji (AI). Jednym z obiecujących podejść jest zastosowanie głębokich sieci neuronowych, które mogą identyfikować i redukować artefakty kompresji. Przykładowo, modele oparte na architekturze U-Net czy Wave-U-Net są w stanie skutecznie poprawiać jakość dźwięku, szczególnie w przypadku nagrań mocno skompresowanych @6. Zastosowanie Generatywnych Sieci Przeciwstawnych (GAN) otwiera nowe moÅŒliwości w odtwarzaniu detali utraconych podczas kompresji. GAN-y potrafią generować brakujące fragmenty sygnału audio w sposób realistyczny, co pozwala na znaczną poprawę jakości muzyki. Badania wykazują, ÅŒe sieci GAN są szczególnie skuteczne w zwiększaniu rozdzielczości częstotliwościowej nagrań oraz w poprawie jakości dźwięku w skompresowanych plikach MP3 @11. Istotną częścią tych procesów jest odpowiednie szkolenie modeli AI. Trening odbywa się na parach nagrań przed i po kompresji, co umoÅŒliwia modelom nauczenie się odtwarzania utraconych detali. Wyzwanie stanowi jednak generalizacja tych modeli na róŌne formaty kompresji, gdyÅŒ algorytmy mogą wykazywać róŌną skuteczność w zaleÅŒności od typu kompresji. Dalsze badania są konieczne, aby zapewnić efektywne działanie tych technologii w szerokim spektrum formatów @10 @12. #pagebreak(weak: true) = Charakterystyka wybranej metody - sieci GAN w rekonstrukcji nagrań muzycznych Generatywne Sieci Przeciwstawne (GAN) to potęŌne narzędzie w przetwarzaniu i rekonstrukcji sygnałów dźwiękowych. Składają się z generatora, który tworzy nowe próbki, oraz dyskryminatora, który ocenia ich jakość. W kontekście audio, sieci GAN umoÅŒliwiają przywracanie zniekształconych sygnałów poprzez identyfikację i korekcję utraconych detali, wykorzystując techniki takie jak szybka transformacja Fouriera (STFT) @19. Wybór GAN jako głównej metody do analizy w tej pracy wynika z jej ponad przeciętnej zdolności do odtwarzania cech sygnału, które zostały utracone podczas kompresji oraz z powodu innych zniekształceń @11. #linebreak() == Architektura sieci GAN dla zadań audio W kontekście zadań przetwarzania audio, architektura Generatywnych Sieci Przeciwstawnych (GAN) składa się z dwóch głównych komponentów: generatora i dyskryminatora. Generator jest odpowiedzialny za tworzenie nowych próbek danych, które mają naśladować rzeczywiste dane, podczas gdy dyskryminator ocenia te próbki, starając się odróŌnić generowane dane od prawdziwych. Proces ten polega na iteracyjnym szkoleniu obu komponentów, gdzie generator uczy się tworzyć coraz bardziej realistyczne dane, a dyskryminator staje się coraz bardziej wyrafinowany w wykrywaniu sztucznie wygenerowanych danych @6. Adaptacje architektury GAN do specyfiki danych audio często obejmują zastosowanie konwolucji jednokierunkowych (1D), które są bardziej odpowiednie do przetwarzania sygnałów dźwiękowych niÅŒ tradycyjne konwolucje dwuwymiarowe. W modelach audio GAN konwolucje 1D pozwalają na skuteczniejsze modelowanie ciągłości czasowej sygnału dźwiękowego, co jest kluczowe dla zachowania naturalnego brzmienia @20. Znaczącą rolę w architekturze GAN dla zadań audio odgrywają spektrogramy oraz reprezentacje czasowo-częstotliwościowe. Spektrogramy, które reprezentują sygnał audio w domenie czasowo-częstotliwościowej, są często uÅŒywane jako wejście do generatora lub dyskryminatora. Tego typu reprezentacje pozwalają modelom GAN na lepsze wychwycenie charakterystycznych wzorców akustycznych, co przekłada się na wyÅŒszą jakość generowanych sygnałów dźwiękowych @21. Przykłady konkretnych implementacji GAN dla rekonstrukcji nagrań muzycznych obejmują takie podejścia jak Dual-Step-U-Net, które łączą konwencjonalne techniki głębokiego uczenia z GAN. W tego typu modelach, szczególnie waÅŒne jest eliminowanie zakłóceń obecnych w nagraniach analogowych, co osiąga się poprzez głębokie uczenie na rzeczywistych, zaszumionych danych audio @22. #pagebreak(weak: true) == Proces uczenia sieci GAN Generatywne Sieci Przeciwstawne (GAN) opierają się na zasadzie przeciwstawnego uczenia, gdzie dwie sieci neuronowe – generator i dyskryminator – rywalizują ze sobą. Generator stara się tworzyć próbki danych, które mają naśladować rzeczywiste próbki, podczas gdy dyskryminator ocenia, czy próbka pochodzi od generatora, czy jest oryginalnym danymi. Proces ten prowadzi do stopniowego udoskonalania obu modeli: generator staje się coraz lepszy w tworzeniu realistycznych danych, a dyskryminator w ich rozróŌnianiu @4. Trening GAN na danych audio niesie ze sobą specyficzne wyzwania. Ze względu na róŌnorodność sygnałów dźwiękowych oraz ich reprezentacji, takie jak spektrogramy czy bezpośrednie fale dźwiękowe, trening wymaga precyzyjnego dopasowania architektury sieci oraz funkcji straty. Jednym z problemów jest zachowanie ciągłości sygnału oraz uniknięcie problemu zaniku gradientu, który moÅŒe prowadzić do niestabilności procesu uczenia @6. Aby stabilizować proces uczenia, w kontekście przetwarzania dźwięku często stosuje się techniki takie jak normalizacja spektralna. Pozwala ona na lepsze zarządzanie wartościami wag sieci i zapobiega eksplozji gradientów, co jest kluczowe dla zachowania stabilności modelu w dłuÅŒszej perspektywie @21. Strategie doboru hiperparametrów, takie jak rozmiar wsadu (batch size), stopa uczenia się, czy wybór optymalizatora, są kluczowe dla efektywnego treningu sieci GAN. W kontekście przetwarzania dźwięku istotne jest równieÅŒ zarządzanie procesem treningowym poprzez monitorowanie postępów modelu i dynamiczne dostosowywanie parametrów, aby unikać problemów takich jak nadmierne dopasowanie (overfitting) @1. #linebreak() == Funkcje straty i metryki oceny jakości W kontekście GAN stosowanych do rekonstrukcji audio, funkcje straty odgrywają kluczową rolę w kształtowaniu jakości generowanych danych. Najczęściej stosowane są adversarial loss, która odpowiada za przeciwstawne uczenie generatora i dyskryminatora, oraz reconstruction loss, która pomaga w precyzyjnym odtwarzaniu szczegółów sygnału dźwiękowego @8. Do obiektywnej oceny jakości rekonstrukcji audio stosuje się metryki takie jak PESQ (Perceptual Evaluation of Speech Quality) i STOI (Short-Time Objective Intelligibility). Metryki te pozwalają na ilościowe porównanie jakości sygnałów oryginalnych i odtworzonych, co jest kluczowe dla oceny efektywności modeli GAN w zadaniach rekonstrukcji dźwięku @23. Oprócz obiektywnych metryk, subiektywne metody ewaluacji, takie jak testy odsłuchowe przeprowadzone przez ekspertów, są często uÅŒywane do oceny jakości generowanych próbek dźwiękowych. Metody te pozwalają na uwzględnienie percepcji ludzkiego słuchu, co jest niezbędne przy ocenie jakości nagrań muzycznych @12. #pagebreak(weak: true) == Modyfikacje i rozszerzenia standardowej architektury GAN W standardowej architekturze GAN, mimo jej licznych zalet, istnieje szereg ograniczeń, które mogą wpływać na skuteczność i stabilność modeli, zwłaszcza w kontekście zadań związanych z przetwarzaniem dźwięku. Motywacja do wprowadzania modyfikacji w standardowej architekturze GAN wynika z potrzeby przezwycięŌenia tych ograniczeń, takich jak problem zaniku gradientów, wolna konwergencja, czy trudności z generowaniem wysokiej jakości próbek w złoÅŒonych przestrzeniach danych. W ciągu ostatnich lat powstało wiele wariantów GAN, które zostały dostosowane do specyficznych wymagań zadań związanych z przetwarzaniem dźwięku. Do najwaÅŒniejszych wariantów stosowanych w audio naleŌą m.in. Conditional GAN, który pozwala na kontrolowane generowanie danych na podstawie dodatkowych informacji, oraz WaveGAN, który jest szczególnie przydatny do generowania surowych sygnałów audio. Warianty te wprowadzają unikalne modyfikacje zwiększające ich efektywność w określonych zastosowaniach @24. #linebreak() === Conditional GAN Conditional GAN (cGAN) wprowadza koncepcję warunkowego generowania, gdzie proces generowania danych jest kontrolowany przez dodatkowe informacje, takie jak etykiety klas czy inne cechy danych. W ten sposób moÅŒliwe jest uzyskanie bardziej precyzyjnych wyników, dostosowanych do specyficznych wymagań zadania. W kontekście rekonstrukcji nagrań audio, cGAN moÅŒe być wykorzystany do kontrolowania parametrów rekonstrukcji, co pozwala na lepsze odwzorowanie oryginalnego sygnału lub dostosowanie go do określonych warunków @25. Zastosowania Conditional GAN w rekonstrukcji nagrań obejmują m.in. rozszerzenie pasma częstotliwości dźwięku, co jest szczególnie istotne w przypadku nagrań o ograniczonej jakości. Modele cGAN są wykorzystywane do augmentacji danych audio, co pozwala na zwiększenie ilości danych treningowych i poprawę jakości wyników w zadaniach takich jak diagnostyka oparta na dźwięku @26. #linebreak() === CycleGAN CycleGAN jest modelem generatywnym, który umoÅŒliwia uczenie się transformacji między róŌnymi domenami danych bez potrzeby posiadania sparowanych próbek treningowych. W przeciwieństwie do tradycyjnych metod nadzorowanych, CycleGAN wykorzystuje mechanizm dwóch cykli generacyjnych (cykl do przodu i cykl do tyłu), co pozwala na uczenie bez nadzoru. Główna idea tego podejścia polega na tym, ÅŒe model uczy się odwzorowywać dane z jednej domeny na drugą w taki sposób, aby moÅŒliwe było odzyskanie oryginalnych danych przy odwrotnym procesie transformacji. #pagebreak(weak: true) CycleGAN znalazł szerokie zastosowanie w transferze stylu audio i konwersji głosu. Dzięki zdolności do uczenia się z danych nieparowanych, model ten jest wykorzystywany do zmiany stylu muzycznego utworów czy konwersji głosu pomiędzy róŌnymi mówcami. CycleGAN został uÅŒyty w celu transformacji dźwięków silników okrętowych @27. CycleGAN oferuje ogromny potencjał w rekonstrukcji nagrań bez par treningowych. Dzięki swojej zdolności do pracy z nieparowanymi danymi, model ten moÅŒe być uÅŒywany do odtwarzania sygnałów dźwiękowych w przypadkach, gdy brak jest sparowanych próbek treningowych, co czyni go wyjątkowo uÅŒytecznym w rekonstrukcji historycznych nagrań lub innych złoÅŒonych zadań dźwiękowych @27. #linebreak() === Progressive GAN Progressive GAN (ProGAN) wprowadza innowacyjną koncepcję stopniowego zwiększania rozdzielczości generowanych danych. Zamiast trenować model na danych o docelowej rozdzielczości od samego początku, ProGAN zaczyna od niskiej rozdzielczości i stopniowo dodaje nowe warstwy, które zwiększają poziom szczegółowości generowanych danych. Takie podejście pozwala na uzyskanie bardziej stabilnych i realistycznych wyników, co jest szczególnie korzystne dla zastosowań związanych z generowaniem złoÅŒonych danych, takich jak dźwięki @28. Adaptacje Progressive GAN do domeny audio opierają się właśnie na koncepcji stopniowego zwiększania rozdzielczości, ale zastosowanej do sygnałów dźwiękowych. Dzięki temu podejściu moÅŒliwe jest generowanie próbek audio o coraz wyÅŒszej jakości, co jest istotne w kontekście syntezy dźwięku, gdzie precyzja i jakość są kluczowe @29. ProGAN jest wykorzystywany w wielu zadaniach związanych z generowaniem wysokiej jakości próbek dźwiękowych. Przykładem moÅŒe być zastosowanie tego modelu do syntezy mowy, gdzie stopniowe zwiększanie jakości generowanych sygnałów pozwala na uzyskanie bardziej naturalnych i realistycznych próbek dźwiękowych @29. #pagebreak(weak: true) = Implementacja i eksperymenty #linebreak() == Opis zestawu danych W ramach przeprowadzonych badań nad zastosowaniem sieci GAN w rekonstrukcji nagrań dźwiękowych, wykorzystano zestaw danych *MusicNet Dataset* @musicnet, składający się z wysokiej jakości nagrań muzyki klasycznej. Wybór tego gatunku muzycznego podyktowany był jego złoÅŒonością harmoniczną i dynamiczną, co stanowi istotne wyzwanie dla algorytmów rekonstrukcyjnych. Brak wokalu w nagraniach muzyki klasycznej pozwolił na skupienie się na czystej rekonstrukcji sygnałów muzycznych. Proces przygotowania danych składał się z kilku kluczowych etapów, zaimplementowanych w skryptach `to_mp3.py`, `to_vinyl_crackle.py`, `generate_stfts.py` oraz `data_preparation.py`. Początkowo, pliki źródłowe w formacie WAV zostały przekonwertowane na format MP3 z przepływnością 320 kbit/s, co pozwoliło na zachowanie wysokiej jakości dźwięku przy jednoczesnej redukcji rozmiaru plików. Następnie, długie nagrania zostały podzielone na dokładnie 10-sekundowe fragmenty, co zapewniło jednolitą strukturę wejściową dla sieci neuronowej. #figure( ```python def process_file(file_info): input_path, output_dir = file_info filename = os.path.basename(input_path) file_id = os.path.splitext(filename)[0] audio = AudioSegment.from_wav(input_path) segment_length = 10 * 1000 # 10 seconds in milliseconds num_full_segments = len(audio) segments = [] for i in range(num_full_segments): start = i * segment_length segment = audio[start:start + segment_length] output_filename = f"{file_id}-{i}.mp3" output_path = os.path.join(output_dir, output_filename) segment.export(output_path, format="mp3", bitrate="320k") segments.append(output_filename) # Check if there's a remaining segment and if it's exactly 10 seconds remaining_audio = audio[num_full_segments * segment_length:] if len(remaining_audio) == segment_length: output_filename = f"{file_id}-{num_full_segments}.mp3" output_path = os.path.join(output_dir, output_filename) remaining_audio.export(output_path, format="mp3", bitrate="320k") segments.append(output_filename) return filename, segments ```, caption: "Procedura przygotowania danych" ) Istotnym elementem przygotowania danych była augmentacja, mająca na celu symulację efektów charakterystycznych dla historycznych nagrań. W tym celu opracowano algorytm generujący szum o charakterystyce spektralnej zbliÅŒonej do autentycznych płyt winylowych. Proces ten, zaimplementowany w skrypcie `to_vinyl_crackle.py`, obejmował generowanie róŌnorodnych efektów, takich jak trzaski, pęknięcia i zadrapania, z wykorzystaniem technik przetwarzania sygnałów, w tym filtracji pasmowo-przepustowej. #figure( ```python def generate_vinyl_crackle(duration_ms, sample_rate): num_samples = int(duration_ms * sample_rate / 1000) samples = np.zeros(num_samples) event_density = 0.0001 event_positions = np.random.randint(0, num_samples, int(num_samples * event_density)) for pos in event_positions: event_type = np.random.choice(['pop', 'crackle', 'scratch']) if event_type == 'pop': duration = np.random.randint(5, 15) event = np.random.exponential(0.01, duration) event = event * np.hanning(duration) elif event_type == 'crackle': duration = np.random.randint(20, 50) event = np.random.normal(0, 0.01, duration) event = event * (np.random.random(duration) > 0.7) else: # scratch duration = np.random.randint(50, 200) event = np.random.normal(0, 0.05, duration) event = event * np.hanning(duration) end_pos = min(pos + len(event), num_samples) samples[pos:end_pos] += event[:end_pos - pos] nyquist = sample_rate / 2 low = 500 / nyquist high = 7000 / nyquist b, a = signal.butter(3, [low, high], btype='band') samples = signal.lfilter(b, a, samples) samples = samples / np.max(np.abs(samples)) return samples ```, caption: "Procedura generowania trzasków winylowych" ) #pagebreak(weak: true) Kolejnym etapem było przekształcenie sygnałów audio do reprezentacji czasowo-częstotliwościowej przy uÅŒyciu *krótkoczasowej transformaty Fouriera (STFT)*. Skrypt `generate_stfts.py` realizował to zadanie, stosując funkcję `librosa.stft()` z oknem analizy o długości 2048 próbek i przeskokiem 512 próbek. Dodatkowo, zastosowano technikę skalowania `signed square root`, która pozwoliła na redukcję dynamiki sygnału przy jednoczesnym zachowaniu informacji o fazie. #figure( ```python def process_audio_file(file_path, output_dir, window_size=2048, hop_size=512): try: base_name = os.path.splitext(os.path.basename(file_path))[0] output_file = os.path.join(output_dir, f"{base_name}_stft.npz") if os.path.exists(output_file): return False, (0, 0) audio, sr = librosa.load(file_path, sr=None) stft = librosa.stft(audio, n_fft=window_size, hop_length=hop_size) stft_scaled = signed_sqrt(stft.real) + 1j * signed_sqrt(stft.imag) np.savez_compressed(output_file, stft=stft_scaled, sr=sr, window_size=window_size, hop_size=hop_size) return True, stft_scaled.shape except Exception as e: logging.error(f"Error processing {file_path}: {str(e)}") return False, (0, 0) ```, caption: "Procedura tworzenia krótkoczasowych trasnformat Fouriera" ) W procesie normalizacji i skalowania danych, zaimplementowanym w klasie `STFTDataset`, zastosowano normalizację amplitudy do zakresu [-1, 1]. Proces ten obejmował oddzielne przetwarzanie magnitudy i fazy spektrogramów, co umoÅŒliwiło zachowanie pełnej informacji o strukturze czasowo-częstotliwościowej sygnału. #pagebreak(weak: true) #figure( ```python class STFTDataset(Dataset): def __init__(self, clean_files, noisy_files): self.clean_files = clean_files self.noisy_files = noisy_files def __getitem__(self, idx): clean_file = self.clean_files[idx] noisy_file = self.noisy_files[idx] clean_stft = np.load(clean_file)['stft'] noisy_stft = np.load(noisy_file)['stft'] clean_mag, clean_phase = np.abs(clean_stft), np.angle(clean_stft) noisy_mag, noisy_phase = np.abs(noisy_stft), np.angle(noisy_stft) clean_mag_original = clean_mag.copy() noisy_mag_original = noisy_mag.copy() clean_mag_norm = (clean_mag - np.min(clean_mag)) / (np.max(clean_mag) - np.min(clean_mag)) * 2 - 1 noisy_mag_norm = (noisy_mag - np.min(noisy_mag)) / (np.max(noisy_mag) - np.min(noisy_mag)) * 2 - 1 clean_data_norm = np.stack([clean_mag_norm, clean_phase], axis=0) noisy_data_norm = np.stack([noisy_mag_norm, noisy_phase], axis=0) clean_data_original = np.stack([clean_mag_original, clean_phase], axis=0) noisy_data_original = np.stack([noisy_mag_original, noisy_phase], axis=0) return (torch.from_numpy(noisy_data_norm).float(), torch.from_numpy(clean_data_norm).float(), torch.from_numpy(noisy_data_original).float(), torch.from_numpy(clean_data_original).float()) ```, caption: "Klasa przechowująca zbiory danych STFT" ) Finalny zestaw danych, przygotowany przez funkcję `prepare_data()` w skrypcie `data_preparation.py`, składał się z par nagrań: oryginalnych, wysokiej jakości fragmentów oraz ich odpowiedników z symulowanymi zniekształceniami winylowymi. Dane zostały podzielone na zbiory treningowy i walidacyjny z wykorzystaniem funkcji `train_test_split()` z biblioteki scikit-learn, zapewniając reprezentatywność obu zbiorów. Warto podkreślić, ÅŒe cały proces przygotowania danych został zoptymalizowany pod kątem wydajności obliczeniowej. Wykorzystano przetwarzanie równoległe z uÅŒyciem `ProcessPoolExecutor`, co znacząco przyspieszyło obróbkę duÅŒej ilości plików audio. Dodatkowo, zastosowano techniki zarządzania pamięcią, przetwarzając dane w mniejszych porcjach, co umoÅŒliwiło jak najefektywniejsze wykorzystanie dostępnych zasobów sprzętowych. == Architektura proponowanego modelu W ramach badań nad rekonstrukcją nagrań dźwiękowych opracowano architekturę Generatywnej Sieci Przeciwstawnej (GAN), składającą się z generatora i dyskryminatora. Model ten został zaprojektowany z myślą o efektywnym przetwarzaniu spektrogramów STFT, które stanowią reprezentację danych wejściowych. #linebreak() === Generator Generator, będący kluczowym elementem architektury, wykorzystuje *zmodyfikowaną strukturę U-Net*. Wybór tej architektury podyktowany był jej skutecznością w zadaniach przetwarzania obrazów, które moÅŒna zaadaptować do analizy spektrogramów. Wprowadzono jednak szereg modyfikacji dostosowujących model do specyfiki rekonstrukcji nagrań audio: W przeciwieństwie do klasycznego U-Net, zastosowano normalizację spektralną w warstwach konwolucyjnych, co pomaga w stabilizacji treningu GAN i poprawia jakość generowanych wyników. #figure( ```python def encoder_block(self, in_channels, out_channels): return nn.Sequential( spectral_norm(nn.Conv2d(in_channels, out_channels, 3, stride=2, padding=1)), nn.BatchNorm2d(out_channels), nn.LeakyReLU(0.2) ) ```, caption: "Blok składowy enkodera architektury Generatora" ) Centralną część generatora stanowi bottleneck składający się z trzech bloków rezydualnych. Ta modyfikacja pozwala na lepsze przetwarzanie cech na wysokim poziomie abstrakcji. #figure( ```python class ResidualBlock(nn.Module): def __init__(self, channels): super().__init__() self.conv1 = spectral_norm(nn.Conv2d(channels, channels, 3, padding=1)) self.conv2 = spectral_norm(nn.Conv2d(channels, channels, 3, padding=1)) self.norm1 = nn.BatchNorm2d(channels) self.norm2 = nn.BatchNorm2d(channels) self.relu = nn.LeakyReLU(0.2) def forward(self, x): residual = x x = self.relu(self.norm1(self.conv1(x))) x = self.norm2(self.conv2(x)) return x + residual ```, caption: "Rezydualny blok składowy architektury Generatora" ) #pagebreak(weak: true) Zamiast standardowej funkcji aktywacji ReLU, zastosowano LeakyReLU, co pomaga w uniknięciu problemu "umierających neuronów" i poprawia gradient przepływ w sieci. Dekoder został dostosowany do specyfiki danych audio poprzez zastosowanie warstw dekonwolucyjnych z normalizacją spektralną: #figure( ```python def decoder_block(self, in_channels, out_channels): return nn.Sequential( spectral_norm(nn.ConvTranspose2d(in_channels, out_channels, 4, stride=2, padding=1)), nn.BatchNorm2d(out_channels), nn.LeakyReLU(0.2) ) ```, caption: "Blok składowy dekodera architektury Generatora" ) Podobnie jak w klasycznym U-Net, zastosowano połączenia skip między odpowiadającymi sobie warstwami enkodera i dekodera. Jest to kluczowe dla zachowania drobnych detali w rekonstruowanych nagraniach. Te modyfikacje pozwoliły na stworzenie architektury, która łączy zalety U-Net z specyficznymi wymaganiami rekonstrukcji nagrań audio w kontekście GAN. #linebreak() === Dyskryminator Dyskryminator, drugi kluczowy komponent architektury GAN, wykorzystuje strukturę konwolucyjną. Składa się z pięciu bloków dyskryminatora, z których kaÅŒdy zawiera warstwę konwolucyjną z normalizacją spektralną oraz funkcję aktywacji LeakyReLU: #figure( ```python def discriminator_block(self, in_channels, out_channels): return nn.Sequential( spectral_norm(nn.Conv2d(in_channels, out_channels, 4, stride=2, padding=1)), nn.LeakyReLU(0.2) ) ```, caption: "Blok składowy architektury Dyskryminatora" ) W celu poprawy stabilności treningu i jakości generowanych wyników, w architekturze zastosowano szereg technik normalizacji. Normalizacja spektralna została wykorzystana we wszystkich warstwach konwolucyjnych, zarówno w generatorze, jak i dyskryminatorze. Technika ta efektywnie kontroluje dynamikę gradientów, co przyczynia się do bardziej stabilnego procesu uczenia. Ponadto, w generatorze zastosowano normalizację wsadową (Batch Normalization) po kaÅŒdej warstwie konwolucyjnej. Metoda ta normalizuje aktywacje w obrębie mini-batcha, co pomaga w redukcji wewnętrznego przesunięcia kowariancyjnego i przyspiesza konwergencję modelu. #pagebreak(weak: true) Wykorzystanie spektrogramów STFT jako reprezentacji danych wejściowych stanowi kluczowy element proponowanej architektury. Spektrogramy te, obliczane z uÅŒyciem krótkoczasowej transformaty Fouriera, dostarczają bogatej reprezentacji czasowo-częstotliwościowej sygnału audio. Taka reprezentacja umoÅŒliwia modelowi efektywne przetwarzanie zarówno informacji o amplitudzie, jak i fazie sygnału, co jest kluczowe dla zadań rekonstrukcji nagrań dźwiękowych. #linebreak() == Proces treningu i optymalizacji W ramach procesu treningu i optymalizacji opracowanego modelu GAN zastosowano szereg technik mających na celu poprawę stabilności uczenia i jakości generowanych wyników. Implementacja funkcji strat stanowiła kluczowy element procesu optymalizacji. W modelu wykorzystano kombinację róŌnych funkcji strat, kaÅŒda z przypisaną wagą, co pozwoliło na precyzyjne kierowanie procesem uczenia: #figure( ```python self.loss_weights = { 'adversarial': 2.5, 'content': 10.0, 'spectral_convergence': 0.1, 'spectral_flatness': 0.1, 'phase_aware': 0.1, 'multi_resolution_stft': 1.0, 'perceptual': 0.1, 'time_frequency': 1.0, 'snr': 1.0 } ```, caption: "Struktura wag funkcji strat" ) Adversarial Loss (Hinge Loss): Funkcja ta stanowi podstawę treningu przeciwstawnego w architekturze GAN. W implementacji wykorzystano wariant Hinge Loss, który promuje bardziej stabilne uczenie się generatora i dyskryminatora. Dla generatora, strata ta dÄ…ÅŒy do maksymalizacji prawdopodobieństwa, ÅŒe dyskryminator sklasyfikuje wygenerowane próbki jako prawdziwe. Dla dyskryminatora, celem jest maksymalizacja marginesu między prawdziwymi a fałszywymi próbkami. Content Loss (L1 lub L2): Ta funkcja straty mierzy bezpośrednią róŌnicę między wygenerowanym sygnałem a sygnałem docelowym. Implementacja umoÅŒliwia wybór między normą L1 (średnia wartość bezwzględna róŌnic) a normą L2 (średnia kwadratowa róŌnic). Norma L1 jest często preferowana w zadaniach związanych z przetwarzaniem sygnałów, gdyÅŒ jest mniej wraÅŒliwa na ekstremalne wartości. #pagebreak(weak: true) Spectral Convergence Loss: Funkcja ta mierzy podobieństwo widmowe między sygnałem wygenerowanym a docelowym. Jest szczególnie istotna w kontekście rekonstrukcji nagrań audio, gdyÅŒ koncentruje się na zachowaniu charakterystyki częstotliwościowej sygnału. Obliczana jest jako stosunek normy róŌnicy widm do normy widma oryginalnego. Spectral Flatness Loss: Ta funkcja straty ocenia róŌnicę w "płaskości" widmowej między sygnałem wygenerowanym a docelowym. Płaskość widmowa jest miarą tego, jak równomiernie rozłoÅŒona jest energia sygnału w dziedzinie częstotliwości. Jest szczególnie przydatna w zachowaniu ogólnej charakterystyki tonalnej rekonstruowanego dźwięku. Phase-Aware Loss: Funkcja ta uwzględnia zarówno informacje o amplitudzie, jak i fazie sygnału. Jest to kluczowe w rekonstrukcji dźwięku, gdzie zachowanie prawidłowych relacji fazowych jest niezbędne dla uzyskania naturalnie brzmiącego rezultatu. Składa się z dwóch komponentów: straty amplitudy i straty fazy. Multi-Resolution STFT Loss: Funkcja analizuje sygnał w róŌnych skalach czasowo-częstotliwościowych. Wykorzystuje krótkoczasową transformatę Fouriera (STFT) o róŌnych rozmiarach okna, co pozwala na uchwycenie zarówno krótko- jak i długoczasowych struktur w sygnale audio. Time-Frequency Loss: Funkcja ta łączy w sobie stratę w dziedzinie czasu i częstotliwości. Uwzględnia zarówno bezpośrednie róŌnice w próbkach czasowych, jak i róŌnice w reprezentacji częstotliwościowej sygnału. Signal-to-Noise Ratio (SNR) Loss: Ta funkcja straty opiera się na klasycznej mierze jakości sygnału - stosunku sygnału do szumu. W kontekście rekonstrukcji audio, "szumem" jest róŌnica między sygnałem wygenerowanym a docelowym. Funkcja ta promuje generowanie sygnałów o wysokim SNR, co przekłada się na lepszą jakość percepcyjną. Perceptual Loss: Wykorzystując wstępnie nauczony model ekstrakcji cech *VGGish* @vggish, funkcja ta porównuje wysokopoziomowe reprezentacje sygnału wygenerowanego i docelowego. Pozwala to na uwzględnienie bardziej abstrakcyjnych i percepcyjnie istotnych cech dźwięku, wykraczających poza proste porównania amplitud czy widm. Optymalizacja modelu opierała się na algorytmie Adam z niestandardowymi parametrami beta: #figure( ```python g_optimizer = optim.Adam(gan.generator.parameters(), lr=g_lr, betas=(0.0, 0.9)) d_optimizer = optim.Adam(gan.discriminator.parameters(), lr=d_lr, betas=(0.0, 0.9)) ```, caption: "Parametry optymizatorów Adam" ) #pagebreak(weak: true) Z powodu rozmiarów modelu oraz duÅŒych plików treningowych, napotkano na problemy z rozmiarem batcha wynikające z przekroczenia limitu pamięci wirtualnej karty graficznej. Z tego powodu zastosowano technikę akumulacji gradientów, co pozwoliło na efektywne zwiększenie rozmiaru batcha bez zwiększania zuÅŒycia pamięci: #figure( ```python g_loss = g_loss / self.accumulation_steps g_loss.backward() if (self.current_step + 1) % self.accumulation_steps == 0: torch.nn.utils.clip_grad_norm_(self.generator.parameters(), max_norm=1.0) self.g_optimizer.step() ```, caption: "Technika akumulacji gradientów" ) Dynamiczne dostosowywanie współczynnika uczenia (learning rate) zostało zaimplementowane w oparciu o wartości funkcji straty: #figure( ```python if self.g_loss_ma > self.g_loss_threshold: for param_group in self.g_optimizer.param_groups: param_group['lr'] *= 1.01 ```, caption: "Dynamiczny współczynnik uczenia" ) W celu poprawy stabilności treningu zastosowano techniki regularyzacji. Gradient Penalty został wprowadzony do funkcji straty dyskryminatora: #figure( ```python gp = self.gradient_penalty(real_target_norm, generated_audio_norm.detach()) d_loss = d_loss + 10 * gp ```, caption: "Gradient Penalty na podstawie Wasserstein GAN" ) Instance Noise z mechanizmem annealing został uÅŒyty do stopniowego zmniejszania szumu dodawanego do danych wejściowych w trakcie treningu: #figure( ```python self.instance_noise *= self.instance_noise_anneal_rate ```, caption: "Mechanizm stopniowego zmniejszania szumu danych wejściowych Dyskryminatora" ) Monitorowanie i wizualizacja procesu treningu zostały zrealizowane za pomocą dedykowanych metod Callback. LossVisualizationCallback umoÅŒliwiał śledzenie i wizualizację róŌnych komponentów funkcji straty w czasie rzeczywistym: #figure( ```python loss_visualization_callback = LossVisualizationCallback(log_dir=run_log_dir) loss_visualization_callback.on_epoch_end(epoch, combined_losses) ```, caption: "Metody wizualizacji strat" ) #pagebreak(weak: true) Implementacja Early Stopping pozwoliła na automatyczne przerwanie treningu w przypadku braku poprawy wyników: #figure( ```python early_stopping_callback = EarlyStoppingCallback(patience=5, verbose=True, delta=0.01, path=os.path.join(run_log_dir, 'best_model.pt')) if early_stopping_callback(epoch, val_loss, gan): print("Early stopping triggered") break ```, caption: "Mechanizm wczesnego przerwania treningu" ) #pagebreak(weak: true) Zapisywanie checkpointów umoÅŒliwiło zachowanie stanu modelu w regularnych odstępach czasu, co pozwoliło na wznowienie treningu w przypadku nagłego przerwania: #figure( ```python checkpoint_callback = CheckpointCallback(checkpoint_dir) checkpoint_callback(epoch, gan) ```, caption: "Mechanizm zachowania stanu modelu" ) #linebreak() == Charakterystyka kodu źródłowego Struktura projektu i organizacja modułów w opracowanym systemie rekonstrukcji nagrań dźwiękowych odzwierciedla modułowe i funkcjonalne podejście do rozwiązania problemu. Projekt został podzielony na kilka kluczowych modułów, kaÅŒdy odpowiedzialny za specyficzny aspekt przetwarzania i analizy danych audio. Główne moduły projektu obejmują: 1. `models.py`: Zawiera definicje klas `Generator`, `Discriminator` i `AudioEnhancementGAN`, które stanowią trzon architektury sieci GAN. 2. `losses.py`: Implementuje róŌnorodne funkcje straty wykorzystywane w procesie treningu, w tym `adversarial_loss`, `content_loss`, `spectral_convergence_loss` i inne. 3. `data_preparation.py`: Odpowiada za przygotowanie i przetwarzanie danych wejściowych, zawierając klasę `STFTDataset` do obsługi spektrogramów STFT. 4. `callbacks.py`: Implementuje mechanizmy monitorowania i wizualizacji procesu treningu, w tym `LossVisualizationCallback` i `CheckpointCallback`. 5. `main.py`: Stanowi punkt wejścia do aplikacji, integrując wszystkie komponenty i implementując logikę treningu. Kluczowe klasy i funkcje w implementacji sieci GAN obejmują: - Klasa `AudioEnhancementGAN`: Centralna klasa projektu, integrująca generator i dyskryminator oraz implementująca logikę treningu. - Klasy `Generator` i `Discriminator`: Implementują odpowiednio architekturę generatora i dyskryminatora. - Funkcja `generator_loss`: Implementuje funkcję straty dla generatora, łączącą róŌne komponenty straty. Projekt w szerokim zakresie wykorzystuje biblioteki PyTorch, librosa i pydub: - PyTorch słuÅŒy jako podstawowy framework implementacji i treningu sieci neuronowych. - Librosa jest wykorzystywana do zaawansowanego przetwarzania sygnałów audio, w szczególności do obliczania i manipulacji spektrogramami STFT. - Pydub znajduje zastosowanie w procesie przygotowania danych, umoÅŒliwiając konwersję i manipulację plikami audio. Mechanizmy przetwarzania równoległego i zarządzania pamięcią zostały zaimplementowane w celu optymalizacji wydajności: - Wykorzystanie `ProcessPoolExecutor` i `ThreadPoolExecutor` do równoległego przetwarzania plików audio: - Dynamiczne dostosowywanie liczby procesów do dostępnych zasobów CPU: - Ograniczanie uÅŒycia pamięci RAM poprzez przetwarzanie danych w mniejszych porcjach: Implementacja interfejsu wiersza poleceń (CLI) do obsługi skryptów została zrealizowana z wykorzystaniem modułu `argparse`, co umoÅŒliwia elastyczne konfigurowanie parametrów treningu: #figure( ```python parser = argparse.ArgumentParser(description='Audio Enhancement GAN') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--batch-size', type=int, default=16, metavar='N', help='input batch size for training (default: 16)') parser.add_argument('--epochs', type=int, default=50, metavar='N', help='number of epochs to train (default: 50)') args = parser.parse_args() ```, caption: "Mechanizm argumentów wierza poleceń" ) #pagebreak(weak:true) == Metodologia eksperymentów Przeprowadzone eksperymenty miały na celu ocenę skuteczności opracowanego modelu GAN w rekonstrukcji nagrań dźwiękowych, ze szczególnym uwzględnieniem usuwania szumów charakterystycznych dla płyt winylowych. Głównym celem było zbadanie zdolności modelu do odwzorowania oryginalnych sygnałów audio poprzez poprawę jakości oraz usunięcie artefaktów z próbek. Opis przeprowadzonych eksperymentów: 1. Trening modelu na zbiorze danych zawierającym pary nagrań: oryginalne (czyste) oraz z dodanymi szumami winylowymi. 2. Walidacja modelu na oddzielnym zbiorze danych, niedostępnym podczas treningu. 3. Generowanie rekonstrukcji dla wybranych próbek testowych i analiza wyników. Metody ewaluacji obejmowały obiektywne metryki jakości audio oraz walidację na oddzielnym zbiorze danych: 1. Obiektywne metryki: - Signal-to-Noise Ratio (SNR): Mierzy stosunek mocy sygnału do mocy szumu. - Spectral Convergence: Ocenia podobieństwo widmowe między sygnałem oryginalnym a zrekonstruowanym. - Perceptual Evaluation of Audio Quality (PEAQ): Symuluje subiektywną ocenę jakości dźwięku. 2. Walidacja na oddzielnym zbiorze danych: - Wykorzystano cross-walidację, dzieląc zbiór danych na część treningową i walidacyjną. - Monitorowano straty walidacyjne w trakcie treningu, aby uniknąć przeuczenia. Ze względu na *niepowodzenie badania*, subiektywna *ocena przez odsłuch nie była moÅŒliwa*. W normalnych warunkach proces ten obejmowałby: - Próbkę badaczy z moÅŒliwie róŌnych kohort oceniających jakość rekonstrukcji. - Ślepe testy AB porównujące oryginalne nagrania z rekonstrukcjami. - Ocenę parametrów takich jak czystość dźwięku, zachowanie detali muzycznych i ogólna jakość. #pagebreak(weak: true) W ramach badań przeprowadzono eksperymenty mające na celu optymalizację architektury i hiperparametrów modelu GAN. W przypadku generatora, testowano róŌne konfiguracje sieci, modyfikując liczbę i rozmiar warstw konwolucyjnych oraz eksperymentując z róŌnymi typami bloków rezydualnych. Podobne modyfikacje wprowadzano w architekturze dyskryminatora, gdzie zweryfikowano wpływ głębokości sieci na jakość wyników oraz efektywność róŌnych technik normalizacji, ze szczególnym uwzględnieniem normalizacji spektralnej. Proces optymalizacji obejmował równieÅŒ dostrajanie kluczowych hiperparametrów, takich jak współczynniki uczenia się dla generatora i dyskryminatora. Badano takÅŒe wpływ rozmiaru batcha oraz liczby kroków akumulacji gradientu na stabilność i efektywność procesu uczenia. Celem tych kompleksowych eksperymentów było znalezienie optymalnej konfiguracji modelu, zapewniającej najlepsze wyniki w zadaniu rekonstrukcji nagrań audio przy jednoczesnym zachowaniu stabilności treningu i efektywności obliczeniowej. W ramach analizy wpływu poszczególnych komponentów na jakość rekonstrukcji, przeprowadzono badania ukierunkowane na róŌne aspekty modelu. W obszarze funkcji strat dokonano eksperymentów dotyczących wpływu róŌnych wag przypisanych poszczególnym komponentom oraz analizie efektywności funkcji takich jak spectral flatness loss czy phase-aware loss. Zweryfikowano takÅŒe skuteczność róŌnych technik normalizacji, w tym batch normalization i instance normalization w generatorze. Wyniki eksperymentów były analizowane poprzez wizualizację spektrogramów STFT, monitorowanie krzywych między epokami, oraz analizę metryk algorytmu podczas procesu uczenia. Mimo ÅŒe badanie nie przyniosło oczekiwanych rezultatów w zakresie jakości rekonstrukcji audio, dostarczyło cennych informacji na temat zachowania modelu GAN w kontekście przetwarzania sygnałów dźwiękowych oraz wskazało potencjalne kierunki dalszych badań i ulepszeń. #pagebreak(weak: true) = Analiza wyników W ramach przeprowadzonego badania nad rekonstrukcją nagrań dźwiękowych z wykorzystaniem sieci GAN zastosowano obiektywne metody analizy celem oceny skuteczności opracowanego modelu. Proces ewaluacji koncentrował się na trzech głównych aspektach: *analizie wizualizacji spektrogramów STFT*, *obserwacji funkcji strat* w trakcie treningu oraz *testach odsłuchowych z wykorzystaniem odwrotnej transformaty STFT*. Analiza wizualizacji spektrogramów STFT stanowiła kluczowy element oceny obiektywnej. Porównanie spektrogramów oryginalnych nagrań, ich wersji z dodanymi szumami winylowymi oraz rekonstrukcji generowanych przez sieć GAN pozwoliło na bezpośrednią obserwację skuteczności modelu w usuwaniu charakterystycznych zniekształceń. #figure( image("fig1.png"), caption: [Spektogram oryginalnego fragmentu] ) <fig1> #figure( image("fig2.png"), caption: [Spektogram fragmentu z dodanym szumem winylowym] ) <fig2> #figure( image("fig3.png"), caption: [Spektogram fragmentu rekonstrukcji w początkowej fazie treningu] ) <fig3> #figure( image("fig4.png"), caption: [Spektogram fragmentu rekonstrukcji w końcowej fazie treningu] ) <fig4> Analiza tych wizualizacji ujawniła, ÅŒe model był wstanie w pewnym stopniu zniwelować trzaski charakterystyczne dla płyt winylowych, co widoczne było jako redukcja pionowych linii na spektrogramach reprezentujących nagłe, krótkotrwałe zakłócenia. Jednocześnie model nauczył się uwydatnić fale oznaczające wysokie dźwięki znajdujące się w oryginalnej próbce. *Model uczył się poprawnie i dÄ…ÅŒył w kierunku oryginalnych próbek, jednak nie był w stanie zniwelować szumów które wygenerował w początkowych fazach uczenia.* Obserwacja funkcji strat w trakcie procesu uczenia stanowiła drugi istotny aspekt oceny obiektywnej. Analiza ta pozwoliła na śledzenie postępów w zdolności modelu do rekonstrukcji nagrań w miarę upływu epok treningu. PoniÅŒej przedstawiono przykładowe wartości strat uzyskane podczas procesu uczenia: #figure( table( columns: 10, [epoka], [0], [1], [2], [...], [14], [15], [16], [...], [20], [wartość funkcji straty], [249], [197], [169], [...], [44], [49], [45], [...], [46] ) ) #pagebreak(weak: true) Obserwacja tych wartości ujawnia interesującą tendencję. W początkowych fazach treningu widoczny jest znaczący spadek wartości funkcji straty, co sugeruje, ÅŒe model uczył się efektywnie redukować błędy rekonstrukcji. JednakÅŒe, około 14-16 epoki wartość funkcji straty osiągnęła minimum (około 44-45) i przestała znacząco spadać, utrzymując się na podobnym poziomie w kolejnych epokach. To zjawisko jest niepokojące, biorąc pod uwagę, ÅŒe jakość rekonstrukcji audio pozostawała niezadowalająca. Sugeruje to, ÅŒe model osiągnął *minimum lokalne*, które nie odpowiadało satysfakcjonującemu rozwiązaniu problemu rekonstrukcji. Innymi słowy, funkcja straty przestała dostarczać uÅŒytecznych informacji dla dalszej optymalizacji modelu, mimo ÅŒe nie był on jeszcze w stanie generować wysokiej jakości rekonstrukcji audio. Trzecim elementem oceny obiektywnej były testy odsłuchowe z wykorzystaniem odwrotnej transformaty STFT. W tym procesie, spektrogramy wygenerowane przez model były przekształcane z powrotem na sygnały audio w formacie MP3. Ta metoda miała na celu umoÅŒliwienie bezpośredniej oceny słuchowej jakości rekonstrukcji, stanowiąc istotne uzupełnienie analizy wizualnej i numerycznej. Wyniki tych testów odsłuchowych okazały się jednak *skrajnie niezadowalające*. We wszystkich próbach, niezaleÅŒnie od etapu treningu czy konfiguracji modelu, uzyskane sygnały audio składały się wyłącznie z niezrozumiałych szumów. Å»adna z wygenerowanych próbek nie wykazywała cech przypominających muzykę czy jakiekolwiek rozpoznawalne dźwięki. Ta obserwacja stanowi najbardziej dobitne świadectwo nieefektywności modelu w zadaniu rekonstrukcji nagrań muzycznych, podkreślając znaczącą rozbieÅŒność między częściowymi poprawami widocznymi na spektrogramach a faktyczną jakością dźwięku percypowaną przez ludzkie ucho. #linebreak() Obserwacja zmian w spektrogramach w trakcie procesu uczenia ujawniła pewne interesujące tendencje. W początkowych fazach treningu, model wykazywał zdolność do częściowej redukcji najbardziej widocznych artefaktów, takich jak pionowe linie reprezentujące trzaski charakterystyczne dla płyt winylowych. JednakÅŒe, w wielu podejściach do uczenia, w miarę postępu treningu, pojawiały się niepokojące zjawiska: #figure( image("fig5.png"), caption: [Spektogram fragmentu rekonstrukcji na początku błędów w nauce] ) <fig5> #figure( image("fig6.png"), caption: [Spektogram fragmentu rekonstrukcji pod koniec błędów w nauce] ) <fig6> Na powyÅŒszej wizualizacji moÅŒna zaobserwować, ÅŒe model po kilkunastu epokach uczenia omylnie nauczył się podmieniać wartości zerami, odpowiadające dźwiękom na poziomie 0dB. Dyskusja na temat niedostatecznej poprawy jakości do uzyskania uÅŒytecznych wyników audio musi uwzględnić kilka kluczowych aspektów: 1. ZłoÅŒoność zadania: Rekonstrukcja pełnych nagrań muzycznych okazała się znacznie bardziej skomplikowana niÅŒ początkowo zakładano. Model musiał nie tylko usunąć szumy, ale takÅŒe odtworzyć subtelne detale muzyczne, co stanowiło wyzwanie wykraczające poza moÅŒliwości obecnej architektury. 2. Nieadekwatność funkcji strat: Mimo zastosowania róŌnorodnych funkcji strat, mogły one nie w pełni odzwierciedlać percepcyjne aspekty jakości dźwięku. To mogło prowadzić do optymalizacji modelu w kierunku, który nie przekładał się bezpośrednio na poprawę słyszalnej jakości. 3. Ograniczenia architektury: Zastosowana architektura GAN, mimo swojej złoÅŒoności, mogła nie być wystarczająco dostosowana do specyfiki rekonstrukcji sygnałów audio. W szczególności, model mógł mieć trudności z zachowaniem spójności fazowej, co jest kluczowe dla naturalnego brzmienia dźwięku. 4. Problemy z danymi treningowymi: Jakość i reprezentatywność danych treningowych mogły nie być wystarczające do nauczenia modelu efektywnej rekonstrukcji. W szczególności, symulowane szumy winylowe mogły nie w pełni oddawać złoÅŒoność rzeczywistych zniekształceń występujących w historycznych nagraniach. 5. Niestabilność treningu GAN: Charakterystyczna dla architektury GAN niestabilność procesu uczenia mogła prowadzić do problemów z konwergencją, co objawiało się niekonsekwentną jakością generowanych spektrogramów w róŌnych fazach treningu. Podsumowując, obiektywna ocena wyników wykazała, ÅŒe opracowany model GAN, mimo pewnych obiecujących aspektów widocznych w analizie spektrogramów, nie był w stanie osiągnąć zadowalającego poziomu rekonstrukcji nagrań dźwiękowych. Całkowity brak rozpoznawalnych elementów muzycznych w wygenerowanych próbkach audio podkreśla głęboką rozbieÅŒność między częściowymi poprawami obserwowanymi w domenie częstotliwościowej a faktyczną percepcją dźwięku. Ta sytuacja uwypukla złoÅŒoność zadania rekonstrukcji nagrań muzycznych i wskazuje na potrzebę dalszych, pogłębionych badań w tym obszarze. Przyszłe prace powinny skupić się na: 1. Udoskonaleniu architektury modelu, ze szczególnym uwzględnieniem zachowania spójności fazowej sygnału. 2. Opracowaniu bardziej zaawansowanych funkcji strat, które lepiej odzwierciedlałyby percepcyjne aspekty jakości dźwięku. 3. Zwiększeniu rozmiaru i róŌnorodności zbioru danych treningowych, z moÅŒliwym uwzględnieniem rzeczywistych, a nie tylko symulowanych, zniekształceń. 4. Eksploracji alternatywnych podejść do generatywnego modelowania dźwięku, takich jak modele autoregresyjne czy modele dyfuzyjne. Mimo ÅŒe obecne wyniki nie spełniły oczekiwań w zakresie praktycznej uÅŒyteczności, stanowią one cenny wkład w zrozumienie wyzwań związanych z zastosowaniem technik uczenia maszynowego do rekonstrukcji nagrań dźwiękowych i otwierają nowe ścieÅŒki dla przyszłych badań w tej dziedzinie. #pagebreak(weak: true) = Wnioski i perspektywy #linebreak() == Podsumowanie osiągniętych rezultatów Niniejsza praca miała na celu zbadanie moÅŒliwości wykorzystania metod uczenia maszynowego, ze szczególnym uwzględnieniem Generatywnych Sieci Przeciwstawnych (GAN), w procesie rekonstrukcji nagrań dźwiękowych. Głównym celem było opracowanie i implementacja modelu GAN zdolnego do poprawy jakości historycznych nagrań muzycznych, ze szczególnym naciskiem na usuwanie szumów charakterystycznych dla płyt winylowych oraz rozszerzanie pasma częstotliwościowego. Przeprowadzone eksperymenty dostarczyły cennych informacji na temat potencjału i ograniczeń zastosowania sieci GAN w tym kontekście. Kluczowe wyniki obejmują częściowe sukcesy w redukcji trzasków charakterystycznych dla płyt winylowych, co było widoczne na spektrogramach STFT generowanych próbek. Model wykazał zdolność do uczenia się pewnych aspektów rekonstrukcji, co objawiało się stopniową poprawą jakości generowanych spektrogramów w trakcie procesu treningu. JednakÅŒe, ocena skuteczności proponowanej metody GAN w rekonstrukcji nagrań ujawniła znaczące ograniczenia. Mimo obiecujących rezultatów widocznych w domenie częstotliwościowej, próby konwersji zrekonstruowanych spektrogramów z powrotem do domeny czasowej nie przyniosły zadowalających wyników. Wygenerowane sygnały audio charakteryzowały się wysokim poziomem szumów i zniekształceń, co uniemoÅŒliwiło ich subiektywną ocenę poprzez odsłuch. Porównując osiągnięte rezultaty z początkowymi załoÅŒeniami i oczekiwaniami, naleÅŒy przyznać, ÅŒe badanie nie spełniło wszystkich postawionych celów. Zakładana moÅŒliwość generowania wysokiej jakości rekonstrukcji nagrań, które byłyby percepcyjnie zbliÅŒone do oryginałów, nie została osiągnięta. Model GAN, mimo swojej złoÅŒoności i zastosowania zaawansowanych technik optymalizacji, nie był w stanie w pełni odtworzyć subtelności i detali muzycznych niezbędnych do uzyskania satysfakcjonującej jakości dźwięku. Niemniej jednak, przeprowadzone badania dostarczyły cennych informacji na temat wyzwań związanych z zastosowaniem uczenia maszynowego w dziedzinie rekonstrukcji audio. Zidentyfikowano kluczowe problemy, takie jak trudności w zachowaniu spójności fazowej sygnału czy ograniczenia związane z redukcją szumów w wygenerowanych nagraniach. Te obserwacje stanowią istotny wkład w zrozumienie kompleksowości zadania rekonstrukcji nagrań muzycznych i otwierają drogę do dalszych, bardziej ukierunkowanych badań w tej dziedzinie. Podsumowując, mimo ÅŒe proponowana metoda GAN nie osiągnęła wszystkich zakładanych celów w zakresie praktycznej rekonstrukcji nagrań, przeprowadzone badania przyczyniły się do pogłębienia wiedzy na temat zastosowania uczenia maszynowego w przetwarzaniu sygnałów audio. Zidentyfikowane wyzwania i ograniczenia stanowią cenny punkt wyjścia do dalszych prac nad udoskonaleniem technik rekonstrukcji nagrań dźwiękowych z wykorzystaniem sztucznej inteligencji. == Ograniczenia proponowanej metody W trakcie realizacji badań nad zastosowaniem sieci GAN w rekonstrukcji nagrań dźwiękowych napotkano szereg istotnych wyzwań i ograniczeń, które wpłynęły na ostateczne wyniki pracy. Identyfikacja i analiza tych trudności stanowi kluczowy element w zrozumieniu aktualnych ograniczeń metody oraz wyznaczeniu kierunków dalszych badań. Jednym z głównych wyzwań okazała się złoÅŒoność zadania rekonstrukcji pełnych nagrań muzycznych. W przeciwieństwie do prostszych zadań, takich jak usuwanie pojedynczych typów zakłóceń, pełna rekonstrukcja wymaga jednoczesnego adresowania wielu aspektów jakości dźwięku. Model musiał nie tylko usuwać szumy i trzaski, ale takÅŒe odtwarzać utracone częstotliwości i zachowywać muzyczną spójność, co okazało się zadaniem przekraczającym moÅŒliwości opracowanej architektury. Istotnym czynnikiem ograniczającym skuteczność rekonstrukcji była jakość i reprezentatywność danych treningowych. Mimo starań o stworzenie zróŌnicowanego zbioru danych, symulowane zniekształcenia mogły nie w pełni odzwierciedlać złoÅŒoność rzeczywistych uszkodzeń występujących w historycznych nagraniach. Ograniczenie to mogło prowadzić do niedostatecznej generalizacji modelu na rzeczywiste przypadki. ZłoÅŒoność architektury sieci GAN, choć teoretycznie korzystna, w praktyce przyczyniła się do powstania szeregu problemów. Niestabilność procesu uczenia, charakterystyczna dla GAN, okazała się szczególnie problematyczna w kontekście danych audio. Balansowanie między uczeniem generatora i dyskryminatora było trudne, co często prowadziło do nieoptymalnych rezultatów lub zjawiska zapadania się modelu (mode collapse). W domenie audio napotkano specyficzne problemy, które nie występują lub są mniej znaczące w innych obszarach zastosowań uczenia maszynowego. Kluczowym wyzwaniem okazało się zachowanie spójności fazowej w rekonstruowanych sygnałach. Nawet niewielkie błędy w odtworzeniu fazy prowadziły do znaczących zniekształceń percepcyjnych, co było szczególnie widoczne przy próbach konwersji spektrogramów z powrotem do domeny czasowej. PowaÅŒnym ograniczeniem okazały się równieÅŒ kwestie sprzętowe i obliczeniowe. Wykorzystywana w badaniach karta graficzna Radeon 6950 XTX z 16 GB pamięci VRAM, mimo swoich wysokich parametrów, wielokrotnie okazywała się niewystarczająca do efektywnego treningu modelu na pełnym zbiorze danych. Problemy z brakiem pamięci wirtualnej wymuszały ograniczenie rozmiaru batchy lub stosowanie technik takich jak akumulacja gradientów, co z kolei wpływało na stabilność i efektywność procesu uczenia. Długi czas treningu, sięgający kilkudziesięciu godzin na pełny proces, znacząco ograniczał moÅŒliwości eksperymentowania z róŌnymi konfiguracjami modelu i hiperparametrami. #pagebreak(weak: true) Dodatkowym wyzwaniem okazała się interpretacja wyników pośrednich. Mimo obserwowanych popraw w reprezentacjach częstotliwościowych (spektrogramach), przekładanie tych ulepszeń na percepcyjną jakość dźwięku okazało się nieoczywiste. Sugeruje to, ÅŒe stosowane funkcje straty mogły nie w pełni odzwierciedlać aspekty istotne dla ludzkiej percepcji dźwięku. Wreszcie, naleÅŒy zwrócić uwagę na ograniczenia wynikające z samej natury podejścia opartego na uczeniu maszynowym. Model, ucząc się na podstawie dostarczonych przykładów, mógł mieć trudności z rekonstrukcją rzadkich lub unikalnych elementów muzycznych, które nie były dobrze reprezentowane w zbiorze treningowym. #linebreak() == Potencjalne kierunki dalszych badań Przeprowadzone badania, mimo napotkanych ograniczeń, otwierają szereg interesujących ścieÅŒek dla dalszych prac w dziedzinie rekonstrukcji nagrań dźwiękowych z wykorzystaniem metod uczenia maszynowego. Przyszłe badania mogłyby skupić się na kilku kluczowych obszarach. W kontekście architektury sieci GAN, obiecującym kierunkiem wydaje się eksploracja bardziej zaawansowanych wariantów, takich jak Progressive GAN czy StyleGAN, które wykazały imponujące rezultaty w dziedzinie generowania obrazów. Adaptacja tych architektur do domeny audio mogłaby potencjalnie przezwycięŌyć niektóre z napotkanych problemów, szczególnie w zakresie stabilności treningu i jakości generowanych wyników. Ponadto, warto rozwaÅŒyć implementację technik takich jak self-attention czy transformer blocks w generatorze, co mogłoby poprawić zdolność modelu do uchwycenia długoterminowych zaleÅŒności w sygnałach muzycznych. Alternatywnym podejściem wartym eksploracji są modele dyfuzyjne, które w ostatnim czasie zyskały znaczącą popularność w zadaniach generatywnych. Modele te, takie jak DDPM (Denoising Diffusion Probabilistic Models), mogłyby okazać się szczególnie skuteczne w kontekście rekonstrukcji audio, ze względu na ich zdolność do stopniowego usuwania szumu z danych. Ich potencjał w generowaniu wysokiej jakości próbek dźwiękowych oraz stabilność treningu czynią je atrakcyjną alternatywą dla tradycyjnych GAN-ów. Istotnym kierunkiem badań powinna być takÅŒe głębsza integracja wiedzy dziedzinowej z zakresu przetwarzania sygnałów audio w procesie uczenia maszynowego. MoÅŒna by rozwaÅŒyć opracowanie specjalizowanych warstw sieciowych, które explicite modelowałyby zjawiska akustyczne, takie jak propagacja fal dźwiękowych czy rezonans. Implementacja zaawansowanych technik analizy częstotliwościowej, takich jak transformata falkowa czy analiza cepstralna, bezpośrednio w architekturze sieci neuronowej mogłaby znacząco poprawić jej zdolność do precyzyjnej rekonstrukcji sygnałów muzycznych. #pagebreak(weak: true) Przyszłe badania powinny równieÅŒ rozszerzyć zakres eksperymentów o szerszy wachlarz gatunków muzycznych i typów nagrań. Szczególnie interesujące pozostaje badanie skuteczności modeli w rekonstrukcji nagrań wokalnych, muzyki elektronicznej czy zapisów koncertów na ÅŒywo. #linebreak() == Implikacje dla przyszłości rekonstrukcji nagrań muzycznych Rozwój technik opartych na sztucznej inteligencji w dziedzinie rekonstrukcji nagrań muzycznych niesie ze sobą znaczące implikacje dla ochrony dziedzictwa kulturowego. Potencjał AI w tym kontekście jest ogromny – zaawansowane algorytmy mogą nie tylko przywrócić do ÅŒycia historyczne nagrania, ale takÅŒe uczynić je dostępnymi dla szerszej publiczności w niespotykanej dotąd jakości. MoÅŒliwość automatycznej poprawy jakości tysięcy godzin archiwalnych nagrań otwiera nowe perspektywy dla badaczy, muzykologów i miłośników muzyki, umoÅŒliwiając głębsze zrozumienie i docenienie muzycznego dziedzictwa ludzkości. Jednocześnie, stosowanie AI w rekonstrukcji historycznych nagrań rodzi istotne pytania etyczne. Kluczowe jest zachowanie równowagi między poprawą jakości a zachowaniem autentyczności oryginału. Zbyt agresywna ingerencja algorytmów AI moÅŒe prowadzić do zniekształcenia historycznego brzmienia, zacierając granicę między rekonstrukcją a reinterpretacją. Dlatego niezbędne jest wypracowanie standardów i wytycznych etycznych, które będą kierować wykorzystaniem AI w tym obszarze, zapewniając poszanowanie integralności artystycznej i historycznej rekonstruowanych dzieł. Patrząc w przyszłość, moÅŒna prognozować dynamiczny rozwój technologii AI w dziedzinie przetwarzania audio. MoÅŒemy spodziewać się pojawienia się coraz bardziej wyrafinowanych modeli, zdolnych do jeszcze dokładniejszej analizy i rekonstrukcji sygnałów dźwiękowych. Prawdopodobne jest równieÅŒ powstanie systemów hybrydowych, łączących klasyczne techniki przetwarzania sygnałów z zaawansowanymi algorytmami uczenia maszynowego, co moÅŒe prowadzić do przełomów w jakości i efektywności rekonstrukcji. Wpływ zaawansowanych technik rekonstrukcji na przemysł muzyczny i praktyki archiwizacyjne będzie najprawdopodobniej znaczący. MoÅŒemy oczekiwać rosnącego zainteresowania remasteringiem i ponownym wydawaniem historycznych nagrań w poprawionej jakości. To z kolei moÅŒe wpłynąć na strategie wydawnicze i modele biznesowe w branÅŒy muzycznej. Dla archiwów i instytucji kulturalnych, nowe technologie rekonstrukcji mogą oznaczać rewolucję w sposobie przechowywania i udostępniania zbiorów audio, potencjalnie prowadząc do demokratyzacji dostępu do muzycznego dziedzictwa. #pagebreak(weak: true) Podsumowując, mimo ÅŒe obecne badania nad wykorzystaniem AI w rekonstrukcji nagrań muzycznych napotkały pewne ograniczenia, perspektywy na przyszłość są niezwykle obiecujące. Dalszy rozwój w tej dziedzinie ma potencjał nie tylko do znaczącego postępu technologicznego, ale takÅŒe do głębokiej transformacji naszego podejścia do zachowania i interpretacji muzycznego dziedzictwa. Kluczowe będzie zrównowaÅŒone podejście, które zmaksymalizuje korzyści płynące z nowych technologii, jednocześnie zachowując szacunek dla integralności i autentyczności historycznych nagrań. #pagebreak(weak: true) #outline( title: [Lista symboli], target: figure, ) #pagebreak(weak: true) #bibliography("bibliography.yml")
https://github.com/hei-templates/hevs-typsttemplate-thesis
https://raw.githubusercontent.com/hei-templates/hevs-typsttemplate-thesis/main/02-main/01-abstract.typ
typst
MIT License
#pagebreak() #heading(numbering:none)[Abstract] <sec:abstract> #lorem(50) #lorem(50) #lorem(50) #v(2em) _*Keywords*_: _keyword 1_, _keyword 2_, _keyword 3_
https://github.com/0x1B05/nju_os
https://raw.githubusercontent.com/0x1B05/nju_os/main/book_notes/content/01_intro.typ
typst
#import "../template.typ": * = intro - demo code: https://github.com/remzi-arpacidusseau/ostep-code - homework: https://github.com/remzi-arpacidusseau/ostep-homework - projects: https://github.com/remzi-arpacidusseau/ostep-projects The book is about *virtualization*, *concurrency*, and *persistence* of the operating system. == So what happens when a program runs? A running program does one very simple thing: it executes instructions. The processor fetches an instruction from memory, decodes it and executes it. After it is done with this instruction, the processor moves on to the next instruction, and so on, and so on, until the program finally completes1. This is the Von Neumann model of computing. While a lot of other wild things are going on with the primary goal of making the system *easy to use*. OS is in charge of making sure the system operates correctly and efficiently in an easy-to-use manner. == virtualization The OS takes a physical resource (such as the processor, or memory, or a disk) and transforms it into a more general, powerful, and easy-to-use virtual form of itself. A typical OS, in fact, exports a few hundred *system calls* that are available to applications. Because the OS provides these calls to run programs, access memory and devices, and other related actions, we also sometimes say that the OS provides *a standard library* to applications. The OS is sometimes known as a resource manager. === Virtualizing The CPU ```c #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <assert.h> #include "common.h" int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: cpu <string>\n"); exit(1); } char *str = argv[1]; while (1) { Spin(1); printf("%s\n", str); } return 0; } ``` ```sh prompt> ./cpu A & ; ./cpu B & ; ./cpu C & ; ./cpu D & [1] 7353 [2] 7354 [3] 7355 [4] 7356 A B D C A B D C A C B D ... ``` === Virtualizing Memory ```c #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include "common.h" int main(int argc, char *argv[]) { int *p = malloc(sizeof(int)); // a1 assert(p != NULL); printf("(%d) address pointed to by p: %p\n", getpid(), p); // a2 *p = 0; // a3 while (1) { Spin(1); *p = *p + 1; printf("(%d) p: %d\n", getpid(), *p); // a4 } return 0; } ``` ```sh prompt> ./mem &; ./mem & [1] 24113 [2] 24114 (24113) address pointed to by p: 0x200000 (24114) address pointed to by p: 0x200000 (24113) p: 1 (24114) p: 1 (24114) p: 2 (24113) p: 2 (24113) p: 3 (24114) p: 3 (24113) p: 4 (24114) p: 4 ... ``` Each process accesses its own private *virtual address space* (sometimes just called its *address space*), which the OS somehow maps onto the physical memory of the machine. == Concurrency ```c #include <stdio.h> #include <stdlib.h> #include "common.h" #include "common_threads.h" volatile int counter = 0; int loops; void *worker(void *arg) { int i; for (i = 0; i < loops; i++) { counter++; } return NULL; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: threads <loops>\n"); exit(1); } loops = atoi(argv[1]); pthread_t p1, p2; printf("Initial value : %d\n", counter); Pthread_create(&p1, NULL, worker, NULL); Pthread_create(&p2, NULL, worker, NULL); Pthread_join(p1, NULL); Pthread_join(p2, NULL); printf("Final value : %d\n", counter); return 0; } ``` ```sh prompt> gcc -o thread thread.c -Wall -pthread prompt> ./thread 1000 Initial value : 0 Final value : 2000 ``` ```sh prompt> ./thread 100000 Initial value : 0 Final value : 143012 // huh?? prompt> ./thread 100000 Initial value : 0 Final value : 137298 // what the?? ``` A key part of the program above, where the shared counter is incremented, takes three instructions: one to load the value of the counter from memory into a register, one to increment it, and one to store it back into memory. Because these three instructions do not execute atomically (all at once), strange things can happen. == persistence The software in the operating system that usually manages the disk is called the *file system*. It is assumed that often times, users will want to *share* information that is in files. ```c #include <stdio.h> #include <unistd.h> #include <assert.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <string.h> int main(int argc, char *argv[]) { int fd = open("/tmp/file", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); assert(fd >= 0); char buffer[20]; sprintf(buffer, "hello world\n"); int rc = write(fd, buffer, strlen(buffer)); assert(rc == (strlen(buffer))); fsync(fd); close(fd); return 0; } ``` The file system has to do a fair bit of work: first figuring out where on disk this new data will reside, and then keeping track of it in various structures the file system maintains. Doing so requires issuing I/O requests to the underlying storage device, to either read existing structures or update (write) them. As anyone who has written a *device driver* knows, getting a device to do something on your behalf is an intricate and detailed process. It requires a deep knowledge of the low-level device interface and its exact semantics. Fortunately, the OS provides a standard and simple way to access devices through its system calls. Thus, the OS is sometimes seen as a *standard library*. To handle the problems of system crashes during writes, most file systems incorporate some kind of intricate write protocol, such as *journaling* or *copy-on-write*, carefully ordering writes to disk to ensure that if a failure occurs during the write sequence, the system can recover to reasonable state afterwards. == Design Goals One goal in designing and implementing an operating system is to provide *high performance*; another way to say this is our goal is to *mini-mize the overheads* of the OS. Virtualization and making the system easy to use are well worth it, but not at any cost; thus, we must strive to provide virtualization and other OS features without excessive overheads. These overheads arise in a number of forms: extra time (more instructions) and extra space (in memory or on disk). Another goal will be to provide *protection* between applications, as well as between the OS and applications.Protection is at the heart of one of the main principles underlying an operating system, which is that of *isolation*; isolating processes from one another is the key to protection and thus underlies much of what an OS must do. The operating system must also run *non-stop*; when it fails, all applications running on the system fail as well. Because of this dependence, operating systems often strive to provide a high degree of *reliability*. Other goals: energy-efficiency, security, mobility... == History - Early Operating Systems: Just Libraries - -> Beyond Libraries: Protection - -> The Era of Multiprogramming - -> The Modern Era
https://github.com/xsro/xsro.github.io
https://raw.githubusercontent.com/xsro/xsro.github.io/zola/typst/Control-for-Integrator-Systems/part2.typ
typst
#import "template.typ": template #show: template.with( title:[*Sliding Mode Control for Integrator Systems*], part:[*part 2*: Second and High Order Sliding Mode Control] ) #include "9signum.typ" #include "8sta.typ" #include "7homo.typ" #include "6highorder.typ"
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/themes/gallery/clean.md
markdown
# Clean theme ![clean](clean.png) This theme is a bit more opinionated than the `simple` theme but still supposed to be an off-the-shelf solution that fits many use cases. Use it via ```typ #import "@preview/polylux:0.2.0": * #import themes.clean: * #show: clean-theme.with(...) ``` `clean` uses polylux' section handling, the regular `#outline()` will not work properly, use `#polylux-outline()` instead. Text is configured to have a base font size of 25 pt. ## Options for initialisation `clean-theme` accepts the following optional keyword arguments: - `aspect-ratio`: the aspect ratio of the slides, either `"16-9"` or `"4-3"`, default is `"16-9"` - `footer`: text to display in the footer of every slide, default is `[]` - `short-title`: short form of the presentation title, to be displayed on every slide, default: `none` - `logo`: some content (most likely an image) used as a logo on every slide, default: `none` - `color`: colour of decorative lines, default: `teal` ## Slide functions `clean` provides the following custom slide functions: ```typ #title-slide(...) ``` Creates a title slide where title and subtitle are put between decorative lines, along with logos and author and date infos. Accepts the following keyword arguments: - `title`: title of the presentation, default: `none` - `subtitle`: subtitle of the presentation, default: `none` - `authors`: authors of presentation, can be an array of contents or a single content, will be displayed in a grid, default: `()` - `date`: date of the presentation, default: `none` - `watermark`: some content (most likely an image) used as a watermark behind the titlepage, default: `none` - `secondlogo`: some content (most likely an image) used as a second logo opposite to the regular logo on the title page, default: `none` Does not accept additional content. --- ```typ #slide(...)[ ... ][ ... ] ``` Decorates the provided content with a header containing the current section (if any), the short title of the presentation, and the logo; and a footer containing some custom text and the slide number. Accepts an arbitrary amount of content blocks, they are placed next to each other as columns. Configure using the `columns` and `gutter` keyword arguments. Pass the slide title as a keyword argument `title`. Accepts the following keyword arguments: - `title`: title of the slide, default: `none`, - `columns`: propagated to `grid` for placing the body columns, default: array filled with as many `1fr` as there are content blocks - `gutter`: propagated to `grid` for placing the body columns, default: `1em` --- ```typ #focus-slide(foreground: ..., background: ...)[ ... ] ``` Draw attention with this variant where the content is displayed centered and text is enlarged. Optionally accepts a foreground colour (default: `white`) and background color (default: `teal`). Not suitable for content that exceeds one page. --- ```typ #new-section-slide(name) ``` Start a new section with the given `name` (string or content, positional argument). Creates a slide with this name in the center, a decorative line below, and nothing else. Use `#polylux-outline()` to display all sections, similarly to how you would use `#outline()` otherwise. ## Example code The image at the top is created by the following code: ```typ #import "@preview/polylux:0.2.0": * {{#include clean.typ:3:}} ```
https://github.com/kokkonisd/typst-phd-template
https://raw.githubusercontent.com/kokkonisd/typst-phd-template/main/src/common.typ
typst
The Unlicense
#import "colors.typ": * #import "fonts.typ": * // Setup a message box for warnings, notes etc. // // Parameters: // - primary-color: the primary color of the box. // - secondary-color: the secondary color of the box. // - icon: the icon used in the box (single character). // - title: the title of the box. // - message: the message displayed in the box. // - width: the width of the box. #let message-box(primary-color, secondary-color, icon, title, message, width: 100%) = block( radius: 4pt, fill: primary-color, breakable: false, )[ #set text(fill: white) #show raw: set text(fill: black) #block( radius: (top: 4pt), fill: secondary-color, inset: (x: 10pt, y: 4pt), width: width, )[ #set align(left) #box[ #set align(center + horizon) #box[ #circle(fill: primary-color, inset: 0.5pt)[ #text(fill: secondary-color)[#strong[#icon]] ] ] #box(inset: 3pt)[#emph[#title]] ] ] #block(inset: 10pt, above: 0pt, width: width)[ #message ] ] // Create a warning box. // // Parameters: // - message: the message to put in the warning box. // - width: the width of the warning box. #let warn(message, width: 100%) = message-box( WARN_PRIMARY_COLOR, WARN_SECONDARY_COLOR, "!", "Warning", message, width: width ) // Create a note box. // // Parameters: // - message: the message to put in the note box. // - width: the width of the warning box. #let note(message, width: 100%) = message-box( NOTE_PRIMARY_COLOR, NOTE_SECONDARY_COLOR, "i", "Note", message, width: width ) // Create a code snippet. // // Parameters: // - source: the raw source of the snippet. // - file: the file (or title, context etc) of the snippet. #let code(source, file: none) = block(breakable: false)[ #if file != none [ #block( radius: (top: 4pt), inset: (x: 10pt, y: 4pt), below: 0pt, fill: MAIN_COLOR, )[ #text( fill: CODE_SNIPPET_COLOR, size: 0.7em )[ #emph[#file] ] ] ] #block( radius: ( bottom: 4pt, top-right: 4pt, top-left: if file != none { 0pt } else { 4pt }, ), inset: 10pt, fill: CODE_SNIPPET_COLOR, width: 100% )[ #raw(source.text, lang: source.at("lang", default: none)) ] ]
https://github.com/crd2333/crd2333.github.io
https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Courses/数据结构䞎算法/ADS易错题.typ
typst
--- order: 4 --- #import "/src/components/TypstTemplate/lib.typ": * #show: project.with( title: "高级数据结构䞎算法分析", lang: "zh", ) #let Q(body1, body2) = [ #question(body1) #note(caption: "Answer", body2) ] = 高级数据结构䞎算法分析易错题 == HW 1 #question()[ For the result of accessing the keys 3, 9, 1, 5 in order in the splay tree in the following figure, which one of the following statements is FALSE? ] #note(caption: "Answer")[ 逆倩选择暡拟 splay没什么奜诎的选项也䞍攟了锻炌快速暡拟胜力 #grid( columns: (auto, auto), fig("/public/assets/Courses/ADS/易错题/img-2024-02-28-22-11-23.png", width: 80%), fig("/public/assets/Courses/ADS/易错题/img-2024-02-28-22-10-48.png", width: 50%), ) ] #question()[Consider the following buffer management problem. Initially the buffer size (the number of blocks) is one. Each block can accommodate exactly one item. As soon as a new item arrives, check if there is an available block. If yes, put the item into the block, induced a cost of one. Otherwise, the buffer size is doubled, and then the item is able to put into. Moreover, the old items have to be moved into the new buffer so it costs $k+1$ to make this insertion, where k is the number of old items. Clearly, if there are $N$ items, the worst-case cost for one insertion can be $Omega(N)$. To show that the average cost is $O(1)$, let us turn to the amortized analysis. To simplify the problem, assume that the buffer is full after all the $N$ items are placed. Which of the following potential functions works? / A.: The number of items currently in the buffer. / B.: The opposite number of items currently in the buffer. / C.: The number of available blocks currently in the buffer. / D.: The opposite number of available blocks in the buffer ] #note(caption: "Answer")[ 选 D䞍䌚。感觉是 AD 二选䞀A 䞺什么䞍行 ] == HW 2 #question()[ Insert 3, 1, 4, 5, 9, 2, 6, 8, 7, 0 into an initially empty 2-3 tree (with splitting). Which one of the following statements is FALSE? ] #note(caption: "Answer")[ 暡拟插入最后画出来可胜长这样 #fig("/public/assets/Courses/ADS/易错题/img-2024-03-12-23-11-31.png", width: 50%) ] #question()[ Which of the following statements concerning a B+ tree of order M is TRUE? \ A. the root always has between 2 and M children\ ... ] #note(caption: "Answer")[ 泚意定义root 芁么是叶子芁么才是 2 到 M 䞪孩子。 ] == HW 3 #question()[ When evaluating the performance of data retrieval, it is important to measure the relevancy of the answer set. (T/F) ] #note(caption: "Answer")[ F. 召回率和敎䞪答案集的盞关性无关这题挺唬人的乍䞀看还真是那么回事。 ] == HW 4 #question()[ The result of inserting keys $1$ to $2^k- 1$ for any $k>4$ in order into an initially empty skew heap is always a full binary tree. ] #note(caption: "Answer", breakable: false)[ 䞍是埈懂䞺什么芁 $k > 4$圚我看来奜像 $k ge 2$ 就郜成立了对 $k=4$ 画出的囟劂䞋 #syntree("[1 [3 [7 15 11] [5 13 9]] [2 [6 14 10] [4 12 8]]]") 可以背䞀䞋规埋节省时闎 ] == HW 7 #question()[ Which one of the following is the lowest upper bound of $T(N)$. $T(N)$ for the following recursion $T(N) = 2T(sqrt(N)) + log N$? ] #note(caption: "Answer")[ 答案是 $O(log N log log N)$。泚意到凜数并非兞型圢匏所以芁先换元 $m = log N$埗到 $T(2^m) = 2T(2^(m/2)) + m$。再讟 $G(m)=T(2^m)$则有 $G(m)=2G(m\/2)+m$也就是对变量换䞪元再对凜数换䞪元\ 由䞻定理(1)知 $G(m)=O(m log m)$所以 $T(N)=O(log N log log N)$ ] == HW 9 #question()[ Let $S$ be the set of activities in Activity Selection Problem. Then the earliest finish activity $a_m$ must be included in all the maximum-size subset of mutually compatible activities of $S$. ] #note(caption: "Answer")[ F. 泚意这䞪近䌌解䞀定圚某䞀䞪最䌘解䞭䜆䞍䞀定圚所有最䌘解䞭。 ] == HW 10 #question()[ All NP problems are decidable. ] #note(caption: "Answer")[ T. ] == HW 11 #question()[ To approximate a maximum spanning tree $T$ of an undirected graph $G=(V,E)$ with distinct edge weights $w(u,v)$ on each edge $(u,v) in E$, let's denote the set of maximum-weight edges incident on each vertex by $S$. Also let $w(E')=sum_{(u,v) in E'} w(u,v)$ for any edge set $E'$. Which of the following statements is TRUE? - A. $S=T$ for any graph $G$ - B. $S != T$ for any graph $G$ - C. $w(T) >= w(S)\/2$ for any graph $G$ - D. None of the above ] #note(caption: "Note")[ 意思是对每䞪顶点选它的最倧蟹这样选出来的结果䞍䞀定是最倧生成树甚至䞍䞀定联通䜆足借近䌌。A 和 B 选项看起来互斥实际䞊可以分别构造出反䟋。 #fig("/public/assets/Courses/ADS/易错题/img-2024-05-10-19-20-37.png", width: 50%) 对 C 选项由于。䞍䌚 ] == HW 12 #Q( [ Greedy method is a special case of local search. ], [ F. 莪心可以倧抂定义䞺每䞀步根据启发信息的最䌘来决策。而局郚搜玢则是从䞀䞪初始解䞭通过局郚扰劚从而探玢新解的可胜。䞀种垞见的局郚搜玢是"k亀换"局郚搜玢。通过亀换解䞭的某些结果从而测试这种扰劚是吊胜获埗曎䌘的解。 ] ) #Q( [A bipartite graph $G$ is one whose vertex set can be partitioned into two sets $A$ and $B$, such that each edge in the graph goes between a vertex in $A$ and a vertex in $B$. Matching $M$ in $G$ is a set of edges that have no end points in common. Maximum Bipartite Matching Problem finds a matching with the greatest number of edges (over all matching).\ Consider the following Gradient Ascent Algorithm: ``` As long as there is an edge whose endpoints are unmatched, add it to the current matching. When there is no longer such an edge, terminate with a locally optimal matching. ``` Let $M_1$ and $M_2$ be matchings in a bipartite graph $G$. Which of the following statements is true? - A. This gradient ascent algorithm never returns the maximum matching. - B. Suppose that $|M_1|>2|M_2|$. Then there must be an edge $e$ in $M_1$ such that $M_2 union {e}$ is a matching in $G$. - C. Any locally optimal matching returned by the gradient ascent algorithm in a bipartite graph $G$ is at most half as large as a maximum matching in $G$. - D. All of the above ], [ 䞍䌚。 ] ) == HW15 #Q( [ If only one tape drive is available to perform the external sorting, then the tape access time for any algorithm will be $Omega(N^2)$. ], [ 答案是 T。䞍懂跟数据库的理论有点䞍䞀样而䞔䞺什么 $Omega(N^2)$ 没有考虑内存倧小 $M$(或者诎合并路数 $k$) ] ) = 倍习 == Chap 1 - 记高床䞺 $h$ 的 AVL-tree 最少有 $h_i$ 䞪节点那么有 $h_i = h_(i-1) + h_(i-2) + 1$$h_(-1) = 0, h_0 = 1$。䟋劂给定 $h = 6$那么 $h_6 = 33$。
https://github.com/kdog3682/mathematical
https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/geometry/shapes.typ
typst
#import "@preview/cetz:0.2.2" #let get-rect-coordinates(w, h) = { let a = (0, 0) let b = (0, h) let c = (w, h) let d = (w, 0) return (a, b, c, d) } #let get-brace-points() = { } #let brace(points, c, place: "below") = { let (a, b) = get-brace-points(points, place) cetz.decorations.brace(a, b, stroke: 0.5pt, name: "brace") cetz.draw.content("brace.k", resolve-content(c)) } #let square(length) = { let points = get-rect-coordinates(length, length) cetz.draw.rect(points.at(0), points.at(2)) brace(points, length, place: "below") } #let rectangle(w, h) = { cetz.draw.rect(a, c) circ(b) circ(c) Small squares have side length 2. #square(2)
https://github.com/FrightenedFoxCN/cetz-cd
https://raw.githubusercontent.com/FrightenedFoxCN/cetz-cd/main/src/arrows.typ
typst
#import "@preview/cetz:0.1.2" #import "utils.typ": * // Here we calculate the array-related information #let resolve-arrow-string(string) = { let res = (0, 0) for i in string { if i == "u" { res.at(1) -= 1 } else if i == "d" { res.at(1) += 1 } else if i == "l" { res.at(0) -= 1 } else if i == "r" { res.at(0) += 1 } else { return none } } res } // this is the *internal* representation of the arrow #let cd-arrow(start, // start point end, // end point style, // style of the arrow text, // text attached to the arrow text-size, // size of the text, this should be passed here due to the limitation of content type swapped, // if the text is on the right; on the left default bent, // if the arrow is bent, a degree is given here offset) = ( // offset of the arrow from the centerline start: start, end: end, style: style, text: text, text-size: text-size, swapped: swapped, bent: bent, offset: offset ) #let default-arrow(start, end) = arrow(start, end, "-", none, (0, 0), false, 0, 0) #let default-arrow-with-text(start, end, text, text-size) = arrow(start, end, "-", text, text-size, false, 0, 0) #let draw-arrow(arrow) = { cetz.draw.line(arrow.start, arrow.end, mark: (fill: black, end: ">"), stroke: (thickness: 0.5pt)) // place the text if arrow.text != none { // for the visualize effect, the text should be a bit nearer to the start point of the arrow let text-position = add2d(scale2d(0.55, arrow.start), scale2d(0.45, arrow.end)) // cetz.draw.circle(text-position, radius:.08) // slope of the arrow let slope = 0. let normal = (0., 0.) let tangent = (0., 0.) if arrow.end.at(0) - arrow.start.at(0) != 0 { slope = (arrow.end.at(1) - arrow.start.at(1)) / (arrow.end.at(0) - arrow.start.at(0)) normal = normalize2d((-slope, 1.)) tangent = normalize2d((1., slope)) } else { normal = (1., 0.) tangent = (0., 1.) } if arrow.swapped != true { text-position = add2d(text-position, scale2d(0.2, normal)) text-position = add2d(text-position, scale2d(0.5, mult2d(normal, arrow.text-size))) } else { text-position = add2d(text-position, scale2d(-0.2, normal)) text-position = add2d(text-position, scale2d(-0.5, mult2d(normal, arrow.text-size))) } // cetz.draw.circle(text-position, radius:.05) cetz.draw.content(text-position, arrow.text) } } // for the user, arr is used to create the arrow #let arr(direction, style : "-", // style of the arrow text : none, // text attached to the arrow swapped: false, bent : 0., // if the arrow is bent, a degree is given here offset : 0.) = ( // offset of the arrow from the centerline direction: resolve-arrow-string(direction), style: style, text: text, swapped: swapped, bent: bent, offset: offset ) #let parse-arrow(content) = { content.split("\\") .map(a => {a.trim(" ")}) .map(a => a.split("&") .map(a => a.trim(" ").split(",") .map(a => arr(a.trim(" "))))) }
https://github.com/ntjess/toolbox
https://raw.githubusercontent.com/ntjess/toolbox/main/cetz-plus/git-graph.typ
typst
#import "@preview/cetz:0.2.0" #let d = cetz.draw #let offset(anchor, x: 0, y: 0) = { (v => cetz.vector.add(v, (x, y)), anchor) } #let default-colors = (red, orange, yellow, green, blue, purple, fuchsia, gray) #let color-boxed(..args) = { set text(0.8em) box( inset: (y: 0.25em, x: 0.1em), fill: yellow.lighten(80%), stroke: black + 0.5pt, radius: 0.2em, ..args ) } #let _layers = ( LANES: -4, BRANCH: -3, GRAPH: -2, COMMIT: 1, TAG: 1, ) #let _git-graph-defaults = ( default-branch-colors: default-colors, branches: (:), active-branch: "main", commit-id: 0, commit-spacing: 0.8, ref-branch-map: (:), lane-spacing: 2, lane-style: ( stroke: (paint: gray, dash: "dashed") ), graph-style: ( stroke: (thickness: 0.25em), radius: 0.25 ), commit-style: ( decorator: color-boxed, spacing: 0.8, angle: 45deg, ), tag-style: ( decorator: color-boxed.with(fill: blue.lighten(75%), stroke: black), angle: -45deg ), ) #let _is-empty(content) = { content == "" or content == [] or content.has("text") and content.text == "" } #let graph-props(func) = { d.get-ctx(ctx => { let props = ctx.git-graph props.ctx = ctx func(props) }) } #let set-graph-props(func) = { d.set-ctx(ctx => { ctx.git-graph = func(ctx.git-graph) ctx }) } #let branch-props(func, branch: auto) = { graph-props(props => { let branch = branch if branch == auto { branch = props.active-branch } if branch not in props.branches { panic("Branch `" + branch + "` does not exist") } let sub-props = props.branches.at(branch) props.name = branch func(props + sub-props) }) } #let background-lanes() = { graph-props(props => { for (name, branch-props) in props.branches.pairs() { let (ctx, latest-commit) = cetz.coordinate.resolve(props.ctx, "head") let end = offset(name, y: latest-commit.at(1) - props.commit-spacing) d.on-layer(_layers.LANES, d.line(name, end, ..props.lane-style, anchor: "north")) } }) } #let _branch-line(src, dst, color) = { // Easier than a merge line since src is guaranteed to be left of dst graph-props(props => { let ctx = props.ctx let (ctx, a, b) = cetz.coordinate.resolve(ctx, src, dst) assert( a.at(0) < b.at(0) and a.at(1) >= b.at(1), message: "source branch must start before destination branch" ) let radius = props.graph-style.radius let stroke = (stroke: (paint: color, ..props.graph-style.stroke)) d.line(offset(b, y: -b.at(1)), b, ..stroke) d.merge-path(..stroke, { d.line( src, (b.at(0) - radius, a.at(1)), ) d.arc((), start: 90deg, delta: -90deg, radius: radius) }) }) } #let branch(name, color: auto, colors: default-colors) = { if type(name) != str { name = name.text } set-graph-props(props => { let branches = props.branches if name in branches { panic("Branch `" + name + "` already exists") } let color = color let n-cur = branches.len() if color == auto { color = colors.at(calc.rem(n-cur, colors.len())) } branches.insert(name, (fill: color, lane: n-cur)) props.branches = branches props.head = name props.active-branch = name props }) let styled(..args) = { set text(weight: "bold", fill: white) rect(radius: 0.25em, ..args) } branch-props(props => { d.content((props.lane * props.lane-spacing, 0), styled(name, fill: props.branches.at(name).fill), name: name, anchor: "west") }) branch-props(props => { let new-head = name if props.commit-id > 0 { let (_, head-pos, lane-pos) = cetz.coordinate.resolve(props.ctx, "head", name) let join-loc = (lane-pos.at(0), head-pos.at(1) - props.commit-spacing) if head-pos.at(1) < 0 { d.on-layer(-props.lane + _layers.BRANCH, _branch-line("head", join-loc, props.fill)) } new-head = (lane-pos.at(0), head-pos.at(1)) } d.anchor("head", new-head) d.anchor(name + "/head", new-head) }) } #let checkout(branch) = { set-graph-props(props => { if branch not in props.branches { panic("Branch `" + branch + "` does not exist") } props.active-branch = branch props }) d.get-ctx(ctx => { d.anchor("head", branch + "/head") }) } #let commit(message, branch: auto) = { if branch != auto { checkout(branch) } set-graph-props(props => { props.commit-id = props.commit-id + 1 props.ref-branch-map.insert(str(props.commit-id), props.active-branch) props }) let on-graph = d.on-layer.with(_layers.GRAPH) let on-branch = d.on-layer.with(_layers.BRANCH) branch-props(props => { let txt = props.commit-style.at("decorator")(message) let (_, lane-pos) = cetz.coordinate.resolve(props.ctx, "head") d.anchor("head", (lane-pos.at(0), -props.commit-id * props.commit-spacing)) on-graph(d.content("head", circle(fill: props.fill, radius: 0.5em), name: "circ")) on-branch( d.line(props.name, "head", stroke: (paint: props.fill, ..props.graph-style.stroke)) ) if not _is-empty(message) { let rot = props.commit-style.at("angle") d.content("circ.south-west", txt, anchor: "east", angle: rot) } }) graph-props(props => { d.anchor(props.active-branch + "/head", "head") d.anchor("commit-id-" + str(props.commit-id), "head") }) } #let tag(message) = { graph-props(props => { let txt = props.tag-style.at("decorator")(message) let rot = props.tag-style.at("angle") d.content("head", txt, anchor: "west", angle: rot, padding: 0.75em) }) } #let _merge-line(src, dest, color) = { // A line with a quarter-circle turn from src to dest branch let radius = 0.5em graph-props(props => { let ctx = props.ctx let (ctx, a, b) = cetz.coordinate.resolve(ctx, src, dest) assert( calc.abs(a.at(1)) < calc.abs(b.at(1)), message: "Destination branch must be below source branch" ) let radius = props.graph-style.radius let p = d.merge-path(stroke: (paint: color, ..props.graph-style.stroke), { d.line(src, (a.at(0), b.at(1) + radius)) if a.at(0) < b.at(0) { d.arc((), start: 180deg, delta: 90deg, radius: radius) } else { d.arc((), start: 0deg, delta: -90deg, radius: radius) } d.line((), b) }) d.on-layer(_layers.BRANCH, p) }) } #let merge(commit-id, message: []) = { commit(message) d.on-layer(_layers.GRAPH, d.circle((), radius: 0.35em, fill: white, stroke: none)) graph-props(props => { let commit-id = commit-id let refs = props.ref-branch-map if commit-id.replace("/head", "") in props.branches { commit-id = commit-id + "/head" refs.insert(commit-id, commit-id.split("/").at(0)) } else if commit-id not in refs { panic("Commit ref `" + commit-id + "` does not exist") } let src-branch = refs.at(commit-id) if src-branch == props.active-branch { panic( "Cannot merge branch into itself. head is already at `" + src-branch + "`, and commit `" + commit-id + "` belongs to the same branch. Perhaps you forgot to checkout a different branch before merging?" ) } let branch-props = props.branches.at(src-branch) _merge-line(commit-id, "head", branch-props.fill) }) } #let git-graph(graph, name: none, ..style) = { d.set-ctx(ctx => { ctx.git-graph = _git-graph-defaults ctx }) d.group(name: name, graph) }
https://github.com/Coekjan/typst-upgrade
https://raw.githubusercontent.com/Coekjan/typst-upgrade/master/tests/exception1/entry.typ
typst
MIT License
#import non-string: * #import "module1.typ" #import "@non-preview/package:1.0.0"
https://github.com/mismorgano/UG-DifferentialGeometry23
https://raw.githubusercontent.com/mismorgano/UG-DifferentialGeometry23/main/Tareas/Tarea-01/Tarea-01.typ
typst
#let title = [ Geometria Diferencial\ Tarea 1 ] #let author = [ <NAME> ] #let book = [ Differential Geometry of Curves and Surfaces ] #set text(12pt,font: "New Computer Modern") #set enum(numbering: "a)") #set math.equation(numbering: "(1)", supplement: [Eq.]) #align(center, text(17pt)[ *#title*\ #author ]) Del libro *#book*. == Problemas *Problema 1* _Sea $alpha :I -> RR^3$ una curva parametrizada, con $alpha'(t) != 0$ para todo $t in I$. Muestra que $norm(alpha (t))$ es constante distinto de cero si y solo si $alpha (t)$ es ortogonal a $alpha ' (t)$ para todo $t in I$._ *Solución:* //Notemos que Dado que $norm(alpha(t))^2 = angle.l alpha(t), alpha(t)angle.r$, se cumple que $ norm(alpha(t))^2 ' = angle.l alpha(t), alpha(t)angle.r' = 2 angle.l alpha(t), alpha'(t)angle.r. $ <dot-der> Además podemos notar que $norm(alpha(t))$ es constante si y solo si $norm(alpha(t))^2$ es constante. Entonces sí $norm(alpha(t))$ es constante distinto de cero obtenemos que $alpha(t) != bold(0)$, por hipotesis $alpha'(t)!= bold(0)$ y por @dot-der obtenemos que $2angle.l alpha(t), alpha'(t) angle.r =0$, lo cual implica que $alpha(t)$ y $alpha'(t)$ son ortogonales. Ahora, sí $alpha(t)$ y $alpha'(t)$ son ortogonales por @dot-der obtenemos que $norm(alpha(t))^2 ' =0$, lo cual implica que $norm(alpha(t))$ es constante y además distinto de cero pues $alpha(t)!=0$. //lo cual implica que $angle.l alpha(t), alpha'(t)angle.r = 0$. *Problema 2* #emph[Sea $alpha(0, pi) -> RR^2$ dada por #footnote[Me parece que la paremetrización del libro era incorrecta.] $ alpha(t) = ( sin(t), ln(cot(t/2)-cos(t)) ), $ donde $t$ es el angulo entre el eje $y$ y el vector $alpha(t)$. La traza de $alpha$ es llamada *tractrix*. Muestra que + $alpha$ es una curva regular diferenciable excepto en $t=pi/2$ + La longitud del segmento de la recta tangente a la tractix en el punto de tangencia y el eje $y$ siempre es 1. ] *Demostración:* //#enum[ a) Primero notemos que $ alpha'(t) &= (cos(t), sin(t) - 1/2csc^2(t/2)1/cot(t/2)) \ &= (cos(t), sin(t) -1/sin(t)), $ por lo que $alpha$ es diferenciable. Además $alpha'(t) = bold(0)$ si y solo si $cos(t) = 0$ para $t in (0,pi)$, lo cual pasa si y solo si $t=pi/2$, se sigue que $alpha$ es regular diferenciable excepto en $t=pi/2$. //][Por otro lado] b) Dado un $t in (0, pi)without {pi/2}$ tenemos que la ecuación de la recta tangente a la tractrix que pasa por $alpha(t)$ es $alpha(t) + lambda alpha'(t)$. Como nos interesa que $alpha(t)+lambda alpha'(t)$ intersecte al eje $y$ entonces se debe cumplir que su primera coordenada sea cero, es decir, $ sin(t) + lambda cos(t) = 0, $ lo cual implica que $lambda = -sin(t)/cos(t)$. Dado que $alpha(t)$ es el punto de tangencia, tenemos que $lambda alpha'(t)$ es el segmento de la recta tangente que une el punto de tangencia y el eje $y$, luego, su longitud es $norm(lambda alpha'(t))$. Podemos ver que $ norm(lambda alpha'(t))^2 &=lambda^2( cos^2(t) + sin^2(t)-2 + 1/(sin^2(t)) )\ &=lambda^2(1/(sin^2(t)) -1) \ &=lambda^2((1-sin^2(2))/(sin^2(t)))\ &=(sin^2(t))/(cos^2(t)) dot (cos^2(t))/(sin^2(t))\ &=1, $ y por tanto $norm(lambda alpha'(t))$ = 1, como queremos. //Para $t = pi/2$ tenemos que $alpha(t) = (1, 0)$ y por tanto *Problema 3* #emph[Muestra que la ecuación de un plano que pasa por tres puntos no colineales $p_1 = (x_1, y_1, z_1)$, $p_2 = (x_2, y_2, z_2)$, $p_3 = (x_3, y_3, z_3)$ está dada por $ (p-p_1) and (p - p_2) dot (p-p_3) = 0, $ donde $p=(x, y, z)$ es un punto arbitrario del plano.] *Demostración:* Primero veamos la "idea" detras de la formula. Sabemos que un plano queda determinado por un punto en el plano $P_0$ y un vector normal al plano $n$, pues dado otro punto $P$ en el plano se debe cumplir que $angle.l P_0-P, n angle.r = 0$. En nuestro caso tenemos que $p-p_1$ y $p - p_2$ son puntos en el plano que lo generan, entonces $(p-p_1) and (p - p_2)$ es normal al plano y como $p - p_3$ es un punto del plano, se debe cumplir $(p-p_1) and (p-p_2) dot (p-p_3) = 0$.
https://github.com/Meisenheimer/Notes
https://raw.githubusercontent.com/Meisenheimer/Notes/main/src/Analysis.typ
typst
MIT License
#import "@local/math:1.0.0": * = Analysis == Calculus === Mean value theorem #env("Theorem", name: "Rolle's theorem")[ Given $n gt.eq 2$ and $f in C^(n-1)([a, b])$ with $f^((n))(x)$ exists at each point of $(a, b)$, suppose that $f(x_0) = dots.c f(x_n) = 0$ for $a lt.eq x_0 < dots.c < x_n lt.eq b$, then there is a point $xi in (a, b)$ such that $f^((n))(xi) = 0$. ] #env("Theorem", name: "Lagrange's mean value theorem")[ Given $f in C^1([a, b])$, then there exists $xi in (a, b)$ such that $ f^prime (xi) = (f(b) - f(a)) / (b-a). $ ] #env("Theorem", name: "Cauchy's mean value theorem")[ Given $f, g in C^1([a, b])$, then there exists $xi in (a, b)$ such that $ (f(b) - f(a)) g^prime (xi) = (g(b) - g(a)) f^prime (xi). $ If $g(a) eq.not g(b)$ and $g(xi) eq.not 0$, this is equivalent to $ (f^prime (xi)) / (g^prime (xi)) = (f(b) - f(a)) / (g(b) - g(a)). $ ] #env("Theorem", name: "First mean value theorems for definite integrals")[ Given $f in C([a, b])$ and $g$ integrable and does not change sign on $[a, b]$, then there exists $xi$ in $(a, b)$ such that $ integral_a^b f(x) g(x) upright(d) x = f(xi) integral_a^b g(x) upright(d) x. $ ] #env("Theorem", name: "Second mean value theorems for definite integrals")[ Given $f$ a integrable function and $g$ a positive monotonically decreasing function, then there exists $xi$ in $(a, b)$ such that $ integral_a^b f(x) g(x) upright(d) x = g(a) integral_a^xi f(x) upright(d) x. $ If $g$ is a positive monotonically increasing function, then there exists $xi$ in $(a, b)$ such that $ integral_a^b f(x) g(x) upright(d) x = g(b) integral_xi^b f(x) upright(d) x. $ If $g$ is a monotonically function, then there exists $xi$ in $(a, b)$ such that $ integral_a^b f(x) g(x) upright(d) x = g(a) integral_a^xi f(x) upright(d) x + g(b) integral_xi^b f(x) upright(d) x. $ ] === Series #env("Definition")[ A series $sum_(n=1)^infinity a_n$ is *absolute convergent* if the series of absolute values $sum_(n=1)^infinity |a_n|$ converges. ] #env("Theorem")[ If a series is absolute convergent, then any reordering of it converges to the same limit. ] #env("Theorem", name: "n-th term test")[ If $limits(lim)_(n -> infinity) a_n eq.not 0$, then the series divergent. ] #env("Theorem", name: "Direct comparison test")[ If $sum_(n=1)^infinity b_n$ is convergent and exists $N > 0$, for all $n > N$, $0 lt.eq a_n lt.eq b_n$, then $sum_(n=1)^infinity a_n$ is convergent; if $sum_(n=1)^infinity b_n$ is divergent and exists $N > 0$, for all $n > N$, $0 lt.eq b_n lt.eq a_n$, then $sum_(n=1)^infinity a_n$ is divergent. ] #env("Theorem", name: "Limit comparison test")[ Given two series $sum_(n=1)^infinity a_n$ and $sum_(n=1)^infinity b_n$ with $a_n gt.eq 0, b_n > 0$. Then if $limits(lim)_(n -> infinity) a_n / b_n = c in (0, infinity)$, then either both series converge or both series diverge. ] #env("Theorem", name: "Ratio test")[ Given $sum_(n=1)^infinity a_n$ and $ R = limsup_(n -> infinity) abs(a_(n+1) / a_n), r = liminf_(n -> infinity) abs(a_(n+1) / a_n), $ if $R < 1$, then the series converges absolutely; if $r > 1$, then the series diverges. ] #env("Theorem", name: "Root test")[ Given $sum_(n=1)^infinity a_n$ and $ R = limsup_(n -> infinity) (|a_n|)^(1/n), $ if $R < 1$, then the series converges absolutely; if $R > 1$, then the series diverges. ] #env("Theorem", name: "Integral test")[ Given $sum_(n=1)^infinity f(n)$ where $f$ is monotone decreasing, then the series converges iff the improper integral $ integral_1^infinity f(x) upright(d) x $ is finite. In particular, $ integral_1^infinity f(x) upright(d) x lt.eq sum_(n=1)^infinity f(n) lt.eq f(1) + integral_1^infinity f(x) upright(d) x $ ] #env("Theorem", name: "Alternating series test")[ Given $sum_(n=1)^infinity (-1)^n a_n$ where $a_n$ are all positive or negative, then the series converges if $|a_n|$ decreases monotonically and $limits(lim)_(n -> infinity) a_n = 0$. ] === Multivariable calculus #env("Theorem", name: "Green's theorem")[ Let $Omega$ be the region in a plane with $partial Omega$ a positively oriented, piecewise smooth, simple closed curve. If $P$ and $Q$ are functions of $(x, y)$ defined on an open region containing $Omega$ and have continuous partial derivatives there, then $ integral.cont_(partial Omega) (P upright(d) x + Q upright(d) y) = integral.double_Omega ((partial Q) / (partial x) - (partial P) / (partial y)) upright(d) x upright(d) y $ where the path of integration along $C$ is anticlockwise. ] #env("Theorem", name: "Stokes' theorem")[ Let $Omega$ be a smooth oriented surface in $RR^3$ with $partial Omega$ a piecewise smooth, simple closed curve. If $mathbf(F) (x,y,z) = (F_x (x,y,z), F_y (x,y,z), F_z (x,y,z))$ is defined and has continuous first order partial derivatives in a region containing $Omega$, then $ integral.double_Omega (nabla times mathbf(F)) dot.c upright(d) S(x) = integral.cont_(partial Omega) mathbf(F) dot.c upright(d) x $ ] #env("Theorem", name: "Gauss-Green theorem (Divergence theorem)")[ For a bounded open set $Omega in RR^n$ that $partial Omega in C^1$ and a function $mathbf(F)(mathbf(x)) = (F_1 (mathbf(x)), dots, F_n (mathbf(x))): overline(Omega)-> RR^n$ satisfies $mathbf(F)(mathbf(x)) in C^1(Omega) sect C(overline(Omega))$, $ integral_Omega "div" mathbf(F)(mathbf(x)) upright(d) mathbf(x) = integral_(partial Omega) mathbf(F)(mathbf(x)) dot mathbf(n) upright(d) S(x), $ where $mathbf(n)$ is outward pointing unit normal vector at $partial Omega$. ] #env("Definition")[ An *implicit function* is a function of the form $ F(x_1, dots, x_n) = 0, $ where $x_1, dots, x_n$ are variables. ] #env("Theorem")[ Let $F(mathbf(x), mathbf(y)): RR^(n+m) -> RR^m$ be a differentiable function of two variables, and $(mathbf(x)_0, mathbf(y)_0)$ the point that $F(mathbf(x)_0, mathbf(y)_0) = mathbf(0)$. If the Jacobian matrix $ J_(F, mathbf(y)) (mathbf(x)_0, mathbf(y)_0) = ((partial F_i) / (partial y_j) (mathbf(x)_0, mathbf(y)_0)) $ is invertible, then there exists an open set $Omega subset.eq RR^n$ containing $mathbf(x)_0$ such that there exists a unique function $f: Omega -> RR^m$ such that $f(mathbf(x)_0) = mathbf(y)_0$ and $F(mathbf(x), f(mathbf(y))) = mathbf(0)$ for all $mathbf(x) in Omega$. Moreover, $f$ is continuously differentiable and, denoting the left-hand panel of the Jacobian matrix shown in the previous section as $ J_(F, mathbf(x)) (mathbf(x)_0, mathbf(y)_0) = ((partial F_i) / (partial x_j) (mathbf(x)_0, mathbf(y)_0)), $ the Jacobian matrix of partial derivatives of $f$ in $Omega$ is given by $ ((partial f_i) / (partial x_j) (mathbf(x)))_(m times n) = -(J_(F, mathbf(y)) (mathbf(x), f(mathbf(x))))_(m times m)^(-1) (J_(F, mathbf(x)) (mathbf(x), f(mathbf(x))))_(m times n) . $ ] == Real Analysis === Lebesgue Measure #env("Definition")[ Given an bounded interval $I in RR$, denoted by $cal(l)(I)$ the *length* of the interval defined as the distance of its endpoints, $ cal(l)([a, b]) = cal(l)((a, b)) = b - a. $ ] #env("Definition")[ For any subset $E subset RR$, the *Lebesgue outer measure* $m^*(E)$ is defined as $ m^*(E) = inf { sum_(i=1)^n cal(l)(I_i): {I_i}_(i=1)^n " is a sequence of open intervals that " E subset union.big_(i=1)^n I_i }. $ ] #env("Theorem")[ If $E_1 subset E_2 subset RR$, then $m^*(E_1) lt.eq m^*(E_2)$. ] #env("Theorem")[ Given an interval $I subset RR$, $m^*(I) = cal(l)(I)$. ] #env("Theorem")[ Given ${E_i subset RR}_(i=1)^n$, $m^*(union.big_(i=1)^n E_i) lt.eq sum_(i=1)^n m^*(E_i)$. ] #env("Definition")[ The sets $E$ are said to be *Lebesgue-measurable* if $ forall A subset RR, m^*(A) = m^*(A sect X) + m^*(A sect (RR backslash A)) $ and its Lebesgue measure is defined as its Lebesgue outer measure: $m(E) = m^*(E)$. ] #env("Theorem")[ The set of all measurable sets $E subset RR$ forms a $sigma$-algebra $cal(F)$ where - $cal(F)$ contains the sample space: $RR in cal(F)$; - $cal(F)$ is closed under complements: if $A in cal(F)$, then also $(RR backslash A) in cal(F)$; - $cal(F)$ is closed under countable unions: if $A_i in cal(F), i = 1, dots$, then also $(union_(i=1)^infinity A_i) in cal(F)$. ] #env("Definition")[ A *measurable space* is a tuple $(X, cal(F))$ consisting of an arbitrary non-empty set $X$ and a $sigma$-algebra $cal(F) subset.eq 2^X$. ] == Complex Analysis #env("Definition")[ Given an open set $Omega$ and a function $f(z): Omega -> CC$, the *derivative* of $f(z)$ at a point $z_0 in Omega$ is defined as the limits $ f^prime (z) = lim_(z -> z_0) (f(z) - f(z_0))/(z - z_0), $ and the function is said to be *complex differentiable* at $z_0$. ] #env("Definition")[ A function $f(z)$ is holomorphic on an open set $Omega$ if it is complex differentiable at every point of $Omega$. ] #env("Theorem")[ If a complex function $f(x + mathbf(i) y) = u(x, y) + mathbf(i) v(x, y)$ is holomorphic, then $u$ and $v$ have first partial derivatives, and satisfy the Cauchy–Riemann equations, $ (partial u)/(partial x) = (partial v)/(partial y) " and " (partial u)/(partial y) = (partial v)/(partial x), $ or equivalently, $ (partial f) / (partial overline(z)) = 0. $ ] #env("Theorem", name: "Cauchy's integral theorem")[ Given a simply connected domain $Omega$ and a holomorphic function $f(z)$ on it, for any simply closed contour $C$ in $Omega$, $ integral_C f(z) upright(d) x = 0. $ ] // #env("Theorem", name: "Cauchy's integral formula")[ // ] #env("Theorem", name: "Residue formula")[ Suppose that $f$ is holomorphic in an open set containing a toy contour $gamma$ and its interior, except for some points $z_1, dots, z_n$ inside $gamma$, then $ integral_gamma f(z) upright(d) z = 2 pi mathbf(i) sum_(k=1)^n upright("res")_(z_k) f, $ where for a pole $z_0$ of order $n$, $ upright("res")_(z_0) f = lim_(z -> z_0) 1/((n-1)!) (upright(d)/(upright(d)z))^(n-1) (z - z_0)^n f(z). $ ] == Important Inequalities === Fundamental inequality #env("Theorem", name: "Fundamental inequality")[ $ forall x, y in RR^+, 2 / (1/a + 1/b) <= sqrt(a b) <= (a+b)/2 <= sqrt((a^2 + b^2) / 2), " equality holds iff " a = b. $ ] === Triangle inequality #env("Theorem", name: "Triangle inequality")[ $ & a, b in CC, & & bar.v|a| - |b|bar.v <= |a plus.minus b| <= |a| + |b|, \ & mathbf(a), mathbf(b) in RR^n, & & bar.v||mathbf(a)|| - ||mathbf(b)||bar.v <= ||mathbf(a) plus.minus mathbf(b)|| <= ||mathbf(a)|| + ||mathbf(b)||. $ ] === Bernoulli inequality #env("Theorem", name: "Bernoulli inequality")[ $ & forall x in (-1, +infinity), forall a in [1, +infinity), & & (1 + x)^a >= 1 + a x, \ & forall x in (-1, +infinity), forall a in (0, 1), & & (1 + x)^a <= 1 + a x, \ & forall x in (-1, +infinity), forall a in (-1, 0), & & (1 + x)^a >= 1 + a x, \ & forall x_i in RR, i in \{1, dots, n\}, & & product_(i=1)^n (1 + x_i) >= 1 + sum_(i=1)^n x_i, \ & forall y >= x > 0, & & (1 + x)^y >= (1 + y)^x. $ ] === Jensen's inequality #env("Theorem", name: "Jensen's inequality")[ For a real convex function $f(x): [a, b] -> RR$, numbers $x_1 dots, x_n in [a, b]$ and weights $a_1, dots, a_n$, the Jensen's inequality can be start as $ (sum_(i=1)^n a_i f(x_i)) / (sum_(i=1)^n a_i) >= f ( (sum_(i=1)^n a_i x_i) / (sum_(i=1)^n a_i) ). $ And for concave function $f$, $ (sum_(i=1)^n a_i f(x_i)) / (sum_(i=1)^n a_i) <= f ( (sum_(i=1)^n a_i x_i) / (sum_(i=1)^n a_i) ). $ Equality holds iff $x_1 = dots.c = x_n$ or $f$ is linear on $[a, b]$. ] === Cauchy–Schwarz inequality #env("Theorem", name: "Cauchy–Schwarz inequality")[ \ *Discrete form.* For real numbers $a_1, dots a_n, b_1, dots b_n in RR, n >= 2$ $ sum_(i=1)^n a_i^2 sum_(i=1)^n b_i^2 >= ( sum_(i=1)^n a_i b_i ). $ Equality holds iff $a_1 / b_1 = dots.c = a_n / b_n$ or $a_i = 0$ or $b_i = 0$. \ *Inner product form.* For a inner product space $V$ with a norm induced by the inner product, $ forall mathbf(a), mathbf(b) in V ||mathbf(a)|| dot.c ||mathbf(b)|| >= |angle.l mathbf(a), mathbf(b) angle.r|. $ Equality holds iff $exists k in RR, " s.t. " k mathbf(a) = mathbf(b) " or " mathbf(a) = k mathbf(b)$. \ *Probability form.* For random variables $X$ and $Y$, $ sqrt(E(X^2)) dot.c sqrt(E(Y^2)) >= |E(X Y)|. $ Equality holds iff $exists k in RR, " s.t. " k X = Y " or " X = k Y$. \ *Integral form.* For integrable functions $f, g in L^2(Omega)$, $ (integral_Omega f^2(x) upright(d) x) (integral_Omega g^2(x) upright(d) x) >= ( integral_Omega f(x) g(x) upright(d) x )^2. $ Equality holds iff $exists k in RR, " s.t. " k f(x) = g(x) " or " f(x) = k g(x)$. ] === Hölder's inequality #env("Theorem", name: "Hölder's inequality")[ \ *Discrete form.* For real numbers $a_1, dots a_n, b_1, dots b_n in RR, n >= 2$ and $p, q in [1, +infinity)$ that $(1/p) + (1/q) = 1$, $ ( sum_(i=1)^n a_i^p )^(1/p) ( sum_(i=1)^n b_i^q )^(1/q) >= ( sum_(i=1)^n a_i b_i ). $ Equality holds iff $exists c_1, c_2 in RR, c_1^2 + c_2^2 eq.not 0, " s.t. " c_1 a_i^p = c_2 b_i^q$. \ *Integral form.* For functions $f in L^p (Omega), g in L^q (Omega)$ and $p, q in [1, +infinity)$ that $1/p + 1/q = 1$, $ ( integral_Omega |f(x)|^p upright(d) x )^(1/p) ( integral_Omega |g(x)|^q upright(d) x )^(1/q) >= integral_Omega f(x) g(x) upright(d) x. $ ] === Young's inequality #env("Theorem", name: "Young's inequality")[ For $p, q in [1, +infinity)$ that $1/p + 1/q = 1$, $ forall a, b in RR^*, a^p / p + b^q / q >= a b. $ Equality holds iff $a^p = b^q$. ] === Minkowski inequality #env("Theorem", name: "Minkowski inequality")[ For a metric space $S$, $ forall f, g in L^p (S), p in [1, +infinity], ||f||_p + ||g||_p >= ||f + g||_p. $ For $p in (1, +infinity)$, equality holds iff $exists k >= 0, " s.t. " f = k g$ or $k f = g$. ] == Special Functions === Gaussian function #env("Definition")[ A *Gaussian function*, or a Gaussian, is a function of the form $ f(x) = a exp(-((x - b)^2) / (2 c^2)), $ where $a in RR^+$ is the height of the curve's peak, $b in RR$ is the position of the center of the peak and $c in RR^+$ is the standard deviation or the Gaussian root mean square width. ] #env("Theorem")[ The integral of a Gaussian is $ integral_(-infinity)^(+infinity) a exp(-((x - b)^2)/ (2 c^2)) upright("d") x = a c sqrt(2 pi). $ ] #env("Definition")[ A *normal distribution* or a *Gaussian distribution* is a continuous probability distribution of the form $ f_(mu, sigma) (x) = 1 / (sigma sqrt(2 pi)) exp(-((x - mu)^2)(2 sigma^2)), $ where $mu$ is the mean and $sigma$ is the standard deviation. ] === Dirac delta function #env("Definition")[ The *Dirac delta function* centered at $overline(x)$ is $ delta(x - overline(x)) = lim_(epsilon -> 0) f_(overline(x), epsilon) (x - overline(x)), $ where $f_(overline(x), epsilon)$ is a normal distribution with its mean at $overline(x)$ and its standard deviation as $epsilon$. ] #env("Theorem")[ The Dirac delta function satisfies $ delta(x - overline(x)) =& cases(+infinity\, & #h(1em) x = overline(x), 0\, & #h(1em) x eq.not overline(x),) #h(1em) integral_(-infinity)^x delta(x - overline(x)) upright("d") x =& cases(1\, & #h(1em) x >= 0, 0\, & #h(1em) x < 0) $ where $H(x) = integral_(-infinity)^x delta(x - overline(x)) upright("d") x$ is called *Heaviside function* or *step function*. ] #env("Theorem")[ If $f: RR -> RR$ is continuous, then $ integral_(-infinity)^(+infinity) delta(x - overline(x)) f(x) upright("d") x = f(overline(x)). $ ] === Gamma function #env("Definition")[ The *Gamma function* defined on $CC$ is $ Gamma(z) = integral_0^(+infinity) t^(z-1) e^(-t) upright("d") t, $ where $upright("Re") (z) > 0$. ] #env("Theorem")[ The Gamma function satisfies $ & forall x in CC, & & Gamma(x + 1) = x Gamma(x), \ & forall n in NN^*, & & Gamma(n) = (n - 1)!. $ ] #env("Theorem")[ The Gamma function satisfies $ forall x in (0, 1), Gamma(1 - x) Gamma(x) = pi / sin(pi x), $ which implies $ Gamma(1/2) = sqrt(pi). $ ] === Beta Function #env("Definition")[ For $p, q in RR^+$, the *Beta function* is defined as $ B(p, q) = integral_0^1 x^(p-1) (1 - x)^(q-1) upright("d") x. $ ] #env("Theorem")[ The Beta function satisfies $ forall p, q in RR^+, B(p, q) = B(q, p) = (Gamma(p) Gamma(q)) / Gamma(p + q). $ ] #env("Theorem")[ The Beta function satisfies $ & forall p > 0, forall q > 1, & & B(p, q) = (q - 1) / (p + q - 1) B(p, q - 1), \ & forall p > 1, forall q > 0, & & B(p, q) = (p - 1) / (p + q - 1) B(p - 1, q), \ & forall p > 1, forall q > 1, & & B(p, q) = ((p - 1)(q - 1)) / ((p + q - 1)(p + q - 2)) B(p - 1, q - 1). $ ]
https://github.com/xlxs4/cv
https://raw.githubusercontent.com/xlxs4/cv/main/xlxs4.typ
typst
MIT License
#import "cv.typ/cv.typ": * // Load CV data from YAML #let cvdata = yaml("xlxs4.yml") #let uservars = ( headingfont: "Linux Libertine", bodyfont: "Linux Libertine", fontsize: 10pt, linespacing: 6pt, showAddress: true, showNumber: true, ) #let customrules(doc) = { doc } #let cvinit(doc) = { doc = setrules(uservars, doc) doc = showrules(uservars, doc) doc = customrules(doc) doc } #show: doc => cvinit(doc) #cvheading(cvdata, uservars) #cvwork(cvdata) #cvexperience(cvdata) #cveducation(cvdata) #cvskills(cvdata) #cvconferences(cvdata) #endnote
https://github.com/hweissi/tugraz-typst-theme
https://raw.githubusercontent.com/hweissi/tugraz-typst-theme/main/tugraz-polylux.typ
typst
// This theme is inspired by https://github.com/matze/mtheme // The polylux-port was performed by https://github.com/Enivex // Consider using: // #set text(font: "Fira Sans", weight: "light", size: 20pt) // #show math.equation: set text(font: "Fira Math") // #set strong(delta: 100) // #set par(justify: true) #import "@preview/polylux:0.3.1": * #import "@preview/showybox:2.0.1": showybox #let m-dark-teal = rgb("#1A1A1A") #let m-light-brown = rgb("#F70146") #let m-lighter-brown = rgb("#e0c0c5") #let m-extra-light-gray = white.darken(2%) #let m-footer-background = rgb("#dfdfdf") #let m-footer = state("m-footer", []) #let m-page-progress-bar = state("m-page-progress-bar", []) #let m-cell = block.with( width: 100%, height: 100%, above: 0pt, below: 0pt, breakable: false ) #let m-progress-bar = utils.polylux-progress( ratio => { grid( columns: (ratio * 100%, 1fr), m-cell(fill: m-light-brown), m-cell(fill: m-lighter-brown) ) }) #let tugraz-theme( aspect-ratio: "16-9", footer: [], progress-bar: true, body ) = { set page( paper: "presentation-" + aspect-ratio, fill: m-extra-light-gray, margin: 0em, header: none, footer: none, ) set list(marker: (text(size: 1.7em, "•"), text(size: 1.5em, "•"), text(size: 1.3em, "•"))) m-footer.update(footer) if progress-bar { m-page-progress-bar.update(m-progress-bar) } body } #let title-slide( title: [], subtitle: none, author: none, date: none, extra: none, ) = { let content = { set text(fill: m-dark-teal) set align(horizon) place(top + right, pad(30%, image("./TU_Graz.svg", format: "svg", width: 20%))) block(width: 100%, inset: 2em, { text(size: 1.8em, strong(title), weight: "regular", fill: m-light-brown) if subtitle != none { linebreak() linebreak() text(size: 0.8em, subtitle) } line(length: 100%, stroke: .05em + m-light-brown) set text(size: .8em) if author != none { block(spacing: 1em, text(weight: "medium", author)) } if date != none { block(spacing: 1em, date) } set text(size: .8em) if extra != none { block(spacing: 1em, extra) } }) } logic.polylux-slide(content) } #let slide(title: none, body) = { let header = { set align(top) if title != none { show: m-cell.with(fill: m-dark-teal, inset: 1em) set align(horizon) set text(fill: m-extra-light-gray, size: 1.2em) strong(title) h(1fr) box(pad(bottom: .75em, text(size: .5em, "www.tugraz.at", weight: "medium"))) box(pad(left: .2em, bottom: .75em, square(fill: m-light-brown, size: .3em))) } else { h(1fr) box(pad(bottom: .75em, text(size: .5em, "www.tugraz.at", weight: "medium"))) box(pad(left: .2em, bottom: .75em, square(fill: m-light-brown, size: .3em))) } } let footer = { set text(size: 0.7em) show: m-cell.with(fill: m-footer-background) set align(horizon) box(align(left+top, square(height: 100%, fill: m-light-brown, align(horizon+center, text(fill: m-extra-light-gray, weight: "regular", size: .9em, logic.logical-slide.display()))))) h(1fr) box(height: 100%, pad(1.5em, text(fill: m-dark-teal, size: .9em, m-footer.display()))) place(bottom, block(height: 2pt, width: 100%, m-page-progress-bar.display())) } set page( header: header, footer: footer, margin: (top: 3em, bottom: 2em), fill: m-extra-light-gray, ) let content = { show: align.with(horizon) show: pad.with(left: 2em, 1em) set text(fill: m-dark-teal) body } logic.polylux-slide(content, max-repetitions: 15) } #let new-section-slide(name) = { let content = { utils.register-section(name) set align(horizon) show: pad.with(20%) set text(size: 1.5em) name block(height: 2pt, width: 100%, spacing: 0pt, m-progress-bar) } logic.polylux-slide(content) } #let focus-slide(body) = { set page(fill: m-dark-teal, margin: 2em) set text(fill: m-extra-light-gray, size: 1.5em) logic.polylux-slide(align(horizon + center, body)) } #let alert = text.with(fill: m-light-brown) #let numbering-func(..nums) = { box( square(fill: m-light-brown, height: 1.2em, align(center, text(fill: m-extra-light-gray, weight: "medium", nums.pos().map(str).join("."))) )) } #let metropolis-outline = utils.polylux-outline(enum-args: (tight: false, numbering: numbering-func)) #let quotebox = showybox.with(frame: ( border-color: m-dark-teal, footer-color: m-light-brown.darken(25%).desaturate(10%), body-color: m-light-brown.lighten(80%), radius: 0pt ), footer-style: ( color: m-extra-light-gray, weight: "light", align: right ), shadow: ( offset: 5pt ) ) #let defbox = showybox.with(frame: ( border-color: m-dark-teal.lighten(20%), title-color: m-extra-light-gray.darken(30%), body-color: m-extra-light-gray.darken(10%), radius: 0pt ), title-style: ( color: m-light-brown.darken(20%), weight: "medium", align: left ), shadow: ( offset: 4pt ) )
https://github.com/0x1B05/algorithm-journey
https://raw.githubusercontent.com/0x1B05/algorithm-journey/main/practice/note/content/劚态规划.typ
typst
#import "../template.typ": * = 劚态规划 == 从递園入手䞀绎劚态规划 #tip("Tip")[ 题目 1 到题目 4郜从递園入手逐析改出劚态规划的实现 ] === #link( "https://leetcode.cn/problems/minimum-cost-for-tickets/", )[题目 2: 最䜎祚价 ] 圚䞀䞪火蜊旅行埈受欢迎的囜床䜠提前䞀幎计划了䞀些火蜊旅行. 圚接䞋来的䞀幎里䜠芁旅行的日子将以䞀䞪名䞺 days 的数组给出, 每䞀项是䞀䞪从 1 到 365 的敎数 火蜊祚有䞉种䞍同的销售方匏: - 䞀匠 䞺期 1 倩 的通行证售价䞺 `costs[0]` 矎元 - 䞀匠 䞺期 7 倩 的通行证售价䞺 `costs[1]` 矎元 - 䞀匠 䞺期 30 倩 的通行证售价䞺 `costs[2]` 矎元 通行证允讞数倩无限制的旅行, 䟋劂劂果我们圚第 2 倩获埗䞀匠 䞺期 7 倩 的通行证, 那么我们可以连着旅行 7 倩(第 2~8 倩) 返回䜠想芁完成圚给定的列衚 `days` 䞭列出的每䞀倩的旅行所需芁的最䜎消莹 #example( "Example", )[ - 蟓入`days = [1,4,6,7,8,20]`, `costs = [2,7,15]` - 蟓出`11` - 解释 - 䟋劂这里有䞀种莭买通行证的方法可以让䜠完成䜠的旅行计划 - 圚第 1 倩䜠花了 `costs[0] = $2` 买了䞀匠䞺期 1 倩的通行证它将圚第 1 倩生效。 - 圚第 3 倩䜠花了 `costs[1] = $7` 买了䞀匠䞺期 7 倩的通行证它将圚第 3, 4, ..., 9 倩生效。 - 圚第 20 倩䜠花了 `costs[0] = $2` 买了䞀匠䞺期 1 倩的通行证它将圚第 20 倩生效。 - 䜠总共花了 \$11并完成了䜠计划的每䞀倩旅行。 ] ==== 解答 #code( caption: [解答], )[ ```java // dp猓存 public static int mincostTickets(int[] days, int[] costs) { int[] dp = new int[days.length + 1]; for (int i = 0; i < dp.length; i++) { dp[i] = Integer.MAX_VALUE; } int ans = f1(days, costs, 0, dp); return ans; } // 圓前䜍于days[cur...], 芁接着完成days的最䜎消莹 public static int f1(int[] days, int[] costs, int cur, int[] dp) { // 后续已经没有旅行了 if (cur >= days.length) { return 0; } if (dp[cur] < Integer.MAX_VALUE) { return dp[cur]; } int ans = Integer.MAX_VALUE; for (int k = 0; k < costs.length; k++) { // 劂果costs[0] 1倩 -> f(days,costs,cur+1) // 劂果costs[1] 7倩 -> f(days,costs,cur+?);芁看days[cur]+7 恰奜<days[i] -> f(days, costs, i) // 劂果costs[2] 30倩 -> f(days,costs,cur+?);芁看days[cur]+30 恰奜<days[i] -> f(days, costs, i) if (k == 0) { // 1倩 ans = Math.min(ans, costs[0] + f1(days, costs, cur + 1, dp)); } else if (k == 1) { // 7倩 int i = 0; for (i = cur + 1; i < days.length && days[i] < days[cur] + 7; i++) ; ans = Math.min(ans, costs[1] + f1(days, costs, i, dp)); } else { // 30倩祚 int i = 0; for (i = cur + 1; i < days.length && days[i] < days[cur] + 30; i++) ; ans = Math.min(ans, costs[2] + f1(days, costs, i, dp)); } } dp[cur] = ans; return ans; } // 衚䟝赖 public static int MAX_DAYS = 366; public static int mincostTickets2(int[] days, int[] costs) { int n = days.length; int[] dp = new int[n + 1]; Arrays.fill(dp, 0, n + 1, Integer.MAX_VALUE); dp[n] = 0; for (int cur = n - 1; cur >= 0; cur--) { for (int k = 0; k < costs.length; k++) { if (k == 0) { // 1倩 dp[cur] = Math.min(dp[cur], costs[0] + dp[cur + 1]); } else if (k == 1) { // 7倩 int i = 0; for (i = cur + 1; i < days.length && days[i] < days[cur] + 7; i++) ; dp[cur] = Math.min(dp[cur], costs[1] + dp[i]); } else { // 30倩祚 int i = 0; for (i = cur + 1; i < days.length && days[i] < days[cur] + 30; i++) ; dp[cur] = Math.min(dp[cur], costs[2] + dp[i]); } } } return dp[0]; } ``` ] 这里面巊的倄理曎简掁倌埗孊习䞀䞋: #code(caption: [巊神的倄理])[ ```java // 无论提亀什么方法郜垊着这䞪数组 0 1 2 public static int[] durations = { 1, 7, 30 }; ... for (int k = 0, j = i; k < 3; k++) { // k是方案猖号 : 0 1 2 while (j < days.length && days[i] + durations[k] > days[j]) { // 因䞺方案2持续的倩数最倚30倩 // 所以while埪环最倚执行30次 // 枚䞟行䞺可以讀䞺是O(1) j++; } ans = Math.min(ans, costs[k] + f1(days, costs, j)); } ... ``` ] === #link( "https://leetcode.cn/problems/decode-ways/description/", )[题目 3: 解码方法] 䞀条包含字母 A-Z 的消息通过以䞋映射进行了 猖码  ``` 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" ``` 芁解码已猖码的消息所有数字必须基于䞊述映射的方法反向映射回字母可胜有倚种方法。䟋劂"11106" 可以映射䞺 - `"AAJF"` 将消息分组䞺 `(1 1 10 6)` - `"KJF"` 将消息分组䞺 `(11 10 6)` 泚意消息䞍胜分组䞺 `(1 11 06)` 因䞺 `"06" `䞍胜映射䞺 `"F" `这是由于 `"6" `和 `"06" `圚映射䞭并䞍等价。 给䜠䞀䞪只含数字的非空字笊䞲 `s` 请计算并返回解码方法的总数 。 #tip("Tip")[ 题目数据保证答案肯定是䞀䞪 32 䜍 的敎数。 ] ==== 解答 #code( caption: [解答], )[ ```java public static int numDecodings(String s) { int[] dp = new int[s.length() + 1]; Arrays.fill(dp, -1); int ans = f(s, 0, dp); return ans; } // s[cur...有倚少种猖码方法. public static int f(String s, int cur, int[] dp) { if (cur == s.length()) { return 1; } if (dp[cur] != -1) { return dp[cur]; } int ans = 0; // 选圓前的 if (s.charAt(cur) == '0') { return 0; } else { ans += f(s, cur + 1, dp); // 选圓前的以及䞋䞀䞪(芁求芁小于26) if (cur + 1 < s.length() && ((s.charAt(cur) - '0') * 10 + (s.charAt(cur + 1) - '0')) <= 26) { ans += f(s, cur + 1, dp); } } dp[cur] = ans; return ans; } public static int numDecodings2(String s) { int n = s.length(); int[] dp = new int[n + 1]; Arrays.fill(dp, 0); dp[n] = 1; for (int cur = n - 1; cur >= 0; cur--) { if (s.charAt(cur) == '0') { dp[cur] = 0; } else { dp[cur] += dp[cur + 1]; // 选圓前的以及䞋䞀䞪(芁求芁小于26) if (cur + 1 < n && ((s.charAt(cur) - '0') * 10 + (s.charAt(cur + 1) - '0')) <= 26) { dp[cur] += dp[cur + 2]; } } } return dp[0]; } ``` ] 给出了䞀种空闎压猩的方法, 利甚变量的滚劚曎新就算出来了结果, 非垞 amazing. #code( caption: [空闎压猩], )[ ```java // 䞥栌䜍眮䟝赖的劚态规划 + 空闎压猩 public static int numDecodings3(String s) { // dp[i+1] int next = 1; // dp[i+2] int nextNext = 0; for (int i = s.length() - 1, cur; i >= 0; i--) { if (s.charAt(i) == '0') { cur = 0; } else { cur = next; if (i + 1 < s.length() && ((s.charAt(i) - '0') * 10 + s.charAt(i + 1) - '0') <= 26) { cur += nextNext; } } nextNext = next; next = cur; } return next; } ``` ] === #link("https://leetcode.cn/problems/decode-ways-ii/")[题目 4: 解码方法 II] 䞀条包含字母 A-Z 的消息通过以䞋映射进行了 猖码  ``` 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" ``` 芁解码已猖码的消息所有数字必须基于䞊述映射的方法反向映射回字母可胜有倚种方法。䟋劂"11106" 可以映射䞺 - `"AAJF"` 将消息分组䞺 `(1 1 10 6)` - `"KJF"` 将消息分组䞺 `(11 10 6)` 泚意消息䞍胜分组䞺 `(1 11 06)` 因䞺 `"06" `䞍胜映射䞺 `"F" `这是由于 `"6" `和 `"06" `圚映射䞭并䞍等价。 陀了 䞊面描述的数字字母映射方案猖码消息䞭可胜包含 `'*'` 字笊可以衚瀺从 `'1'` 到 `'9' `的任䞀数字䞍包括` '0'`。䟋劂猖码字笊䞲 `"1*"` 可以衚瀺` "11"`、`"12"`、`"13"`、`"14"`、`"15"`、`"16"`、`"17"`、`"18" `或 `"19" `䞭的任意䞀条消息。对 `"1*" `进行解码盞圓于解码该字笊䞲可以衚瀺的任䜕猖码消息。 给䜠䞀䞪字笊䞲 s 由数字和 `'*'` 字笊组成返回 解码 该字笊䞲的方法 数目 。 由于答案数目可胜非垞倧返回 10^9 + 7 的 æš¡ 。 ==== 解答 #code( caption: [解答], )[ ```java public static int numDecodings(String s) { long[] dp = new long[s.length() + 1]; Arrays.fill(dp, -1); long ans = f(s, 0, dp); return (int) ans; } public static long MOD = 1000000007; // s[cur...]有倚少种猖码方法. public static long f(String s, int cur, long[] dp) { if (cur == s.length()) { return 1; } if (dp[cur] != -1) { return dp[cur]; } long ans = 0; // 选圓前的 if (s.charAt(cur) == '0') { return 0; } else { // 圓前䞍是0, 有几种情况. // 仅选圓前䜍(可胜是数字或者*). // 选圓前䜍以及䞋䞀䜍, 第䞀䜍是1/2 或者 *, 第二䜍是0-6或者, 第二䜍是* // 仅选圓前䜍, 区分普通和* int cur_char = s.charAt(cur) - '0'; if (cur_char > 0 && cur_char < 10) { // 是普通数字 ans += f(s, cur + 1, dp); } else { // 是* ans += 9 * f(s, cur + 1, dp); } // 选圓前以及䞋䞀䜍 boolean oneOr2 = cur_char == 1 || cur_char == 2; boolean curStar = cur_char == ('*' - '0'); if (cur + 1 < s.length()) { // 第䞀䜍是1/2, 第二䞪是 0-6 / * int next_char = s.charAt(cur + 1) - '0'; boolean isNum = next_char >= 0 && next_char <= 9; boolean lessThan6 = isNum && next_char <= 6; boolean nextStar = next_char == ('*' - '0'); if (oneOr2) { if ((cur_char == 2 && lessThan6) || (cur_char == 1 && isNum)) { ans += f(s, cur + 2, dp); } else if (nextStar) { if (cur_char == 1) { ans += 9 * f(s, cur + 2, dp); } else if (cur_char == 2) { ans += 6 * f(s, cur + 2, dp); } } // 第䞀䜍是*(代衚1/2), 第二䜍可胜是数字或者* } else if (curStar) { if (isNum) { if (lessThan6) { ans += 2 * f(s, cur + 2, dp); } else { ans += f(s, cur + 2, dp); } } else if (nextStar) { ans += 15 * f(s, cur + 2, dp); } } } } ans = (ans + MOD) % MOD; dp[cur] = ans; return ans; } public static int numDecodings2(String s) { int n = s.length(); long[] dp = new long[n + 1]; Arrays.fill(dp, 0); dp[n] = 1; for (int cur = n - 1; cur >= 0; cur--) { if (s.charAt(cur) == '0') { dp[cur] = 0; } else { // 圓前䞍是0, 有几种情况. // 仅选圓前䜍(可胜是数字或者*). // 选圓前䜍以及䞋䞀䜍, 第䞀䜍是1/2 或者 *, 第二䜍是0-6或者, 第二䜍是* // 仅选圓前䜍, 区分数字和* int cur_char = s.charAt(cur) - '0'; if (cur_char > 0 && cur_char < 10) { // 是普通数字 dp[cur] += dp[cur + 1]; } else { // 是* dp[cur] += 9 * dp[cur + 1]; } // 选圓前以及䞋䞀䜍 boolean oneOr2 = cur_char == 1 || cur_char == 2; boolean curStar = cur_char == ('*' - '0'); if (cur + 1 < s.length()) { // 第䞀䜍是1/2, 第二䞪是 0-6 / * int next_char = s.charAt(cur + 1) - '0'; boolean isNum = next_char >= 0 && next_char <= 9; boolean lessThan6 = isNum && next_char <= 6; boolean nextStar = next_char == ('*' - '0'); if (oneOr2) { if ((cur_char == 2 && lessThan6) || (cur_char == 1 && isNum)) { dp[cur] += dp[cur + 2]; } else if (nextStar) { if (cur_char == 1) { dp[cur] += 9 * dp[cur + 2]; } else if (cur_char == 2) { dp[cur] += 6 * dp[cur + 2]; } } // 第䞀䜍是*(代衚1/2), 第二䜍可胜是数字或者* } else if (curStar) { if (isNum) { if (lessThan6) { dp[cur] += 2 * dp[cur + 2]; } else { dp[cur] += dp[cur + 2]; } } else if (nextStar) { dp[cur] += 15 * dp[cur + 2]; } } } } dp[cur] = (dp[cur] + MOD) % MOD; dp[cur] = dp[cur]; } return (int) dp[0]; } ``` ] 这里䟝然可以䜿甚滚劚曎新. === #link( "https://leetcode.cn/problems/ugly-number-ii/description/", )[题目 5: 䞑数 II] #tip( "Tip", )[ 圓熟悉了从递園到劚态规划的蜬化过皋, 那么就可以纯粹甚劚态规划的视角来分析问题了, 题目 5 到题目 8郜是纯粹甚劚态规划的视角来分析、䌘化的 ] #definition( "Definition", )[ *䞑数* 就是莚因子只包含 `2`、`3` 和 `5` 的正敎数。给䜠䞀䞪敎数 `n` 请䜠扟出并返回第 `n` 䞪 䞑数 。 ] #example("Example")[ - 蟓入`n = 10` - 蟓出`12` - 解释`[1, 2, 3, 4, 5, 6, 8, 9, 10, 12]` 是由前 10 䞪䞑数组成的序列。 ] #example("Example")[ - 蟓入`n = 1` - 蟓出`1` - 解释`1` 通垞被视䞺䞑数。 ] ==== 解答 方法 1(最暎力): 自然数枚䞟, 䞀䞪䞪试(?) 方法 2(次暎力): 每䞪䞑数郜是前面的某䞪䞑数\*2,\*3,\*5 埗到的, 从 1 匀始, 每䞪䞑数数分别\*2,\*3,\*5, 扟到最小的, 排序 1 -> 2 3 5 扟到最小的 2 2 -> 4 6 10 扟到陀去 2, 最小的那䞪即 3 3 -> 6 9 15 扟到陀去 2 3 最小的那䞪即 4 .... 方法 2 的决策策略就是比前面䞀䞪䞑数倧的里面最小的那䞪 方法 3(最䌘解): 从 1 匀始, 䞉䞪指针\*2,\*3,\*5, 扟到最小的, 然后盞应的倍数移到䞋䞀䞪䞑数䞊面去. 䞀匀始䞉䞪指针郜指向 1. p1(2), p2(3), p3(5) 扟到指针指着的蟃小的那䞪 即 2. 接着 p1 指针没必芁留圚 1 䜍眮了, 移到 2 䜍眮. p1(4), p2(3), p3(5) 扟到指针指着的蟃小的那䞪 即 3. 接着 p2 指针没必芁留圚 1 䜍眮了, 移到 2 䜍眮. 到期问题, 什么样的可胜性再也䞍䌚成䞺䞋䞀䞪䞑数的解了. #code(caption: [解答])[ ```java public static int nthUglyNumber(int n) { int[] uglyNums = new int[n + 1]; uglyNums[1] = 1; // p2 p3 p5分别对应*2 *3 *5的指针分别停圚什么䞋标 int p2 = 1, p3 = 1, p5 = 1; for (int i = 2; i <= n; i++) { int a = uglyNums[p2] * 2; int b = uglyNums[p3] * 3; int c = uglyNums[p5] * 5; // 圓前的䞑数 int cur = Math.min(Math.min(a, b), c); if (cur == a) { ++p2; } if (cur == b) { ++p3; } if (cur == c) { ++p5; } uglyNums[i] = cur; } return uglyNums[n]; } ``` ] === #link( "https://leetcode.cn/problems/longest-valid-parentheses/description/", )[题目 6: 最长有效括号] 给䜠䞀䞪只包含 `'('` 和 `')' `的字笊䞲扟出最长有效栌匏正确䞔连续括号 子䞲 的长床。 #example("Example")[ - 蟓入`s = "(()"` - 蟓出`2` - 解释最长有效括号子䞲是 `"()"` ] ==== 解答 #code(caption: [解答])[ ```java public static int longestValidParentheses(String str) { char[] s = str.toCharArray(); // dp[0...n-1] // dp[i]: 子䞲必须以i结尟, 埀巊最倚掚倚远胜有效? int[] dp = new int[s.length]; if (s.length > 0) { dp[0] = 0; } int ans = 0; for (int cur = 1; cur < dp.length; cur++) { if (s[cur] == ')') { int tmp = cur - dp[cur - 1] - 1; if (tmp >= 0 && s[tmp] == '(') { // 只芁埀前掚䞀次就可以了, 劂果tmp正奜掚到底了也䞍甚管 dp[cur] = dp[cur - 1] + 2 + (tmp > 0 ? dp[tmp - 1] : 0); } else { dp[cur] = 0; } } else { dp[cur] = 0; } ans = Math.max(dp[cur], ans); } return ans; } ``` ] === #link( "https://leetcode.cn/problems/unique-substrings-in-wraparound-string/description/", )[题目 7: 环绕字笊䞲䞭唯䞀的子字笊䞲] 定义字笊䞲 `base` 䞺䞀䞪 `"abcdefghijklmnopqrstuvwxyz" `无限环绕的字笊䞲所以 `base` 看起来是这样的 `"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...."`. 给䜠䞀䞪字笊䞲 `s` 请䜠统计并返回 `s` 䞭有倚少 䞍同非空子䞲 也圚 `base` 䞭出现。 #example( "Example", )[ - 蟓入`s = "zab"` - 蟓出`6` - 解释字笊䞲 `s` 有六䞪子字笊䞲 `("z", "a", "b", "za", "ab", and "zab")` 圚 `base` 䞭出现。 ] ==== 解答 === 总结 知道怎么算的算法 vs 知道怎么试的算法 有些递園圚展匀计算时总是重倍调甚同䞀䞪子问题的解这种重倍调甚的递園变成劚态规划埈有收益 劂果每次展匀郜是䞍同的解或者重倍调甚的现象埈少那么没有改劚态规划的必芁 任䜕劚态规划问题郜䞀定对应着䞀䞪有重倍调甚行䞺的递園 所以任䜕劚态规划的题目郜䞀定可以从递園入手逐析实现劚态规划的方法 *尝试策略* 就是 *蜬移方皋*完党䞀回事掚荐从*尝试*入手因䞺代码奜写并䞔䞀旊发现尝试错误重新想别的递園代价蜻 劚态规划的倧臎过皋 想出讟计䌘良的递園尝试(方法、经验、固定套路埈倚)有关尝试展匀顺序的诎明 -> 记忆化搜玢(从顶到底的劚态规划) 劂果每䞪状态的计算枚䞟代价埈䜎埀埀到这里就可以了 -> 䞥栌䜍眮䟝赖的劚态规划(从底到顶的劚态规划) 曎倚是䞺了䞋面诎的 进䞀步䌘化枚䞟做的准倇 -> 进䞀步䌘化空闎空闎压猩䞀绎、二绎、倚绎劚态规划郜存圚这种䌘化 -> 进䞀步䌘化枚䞟也就是䌘化时闎本节没有涉及䜆是后续巚倚内容和这有关 解决䞀䞪问题可胜有埈倚尝试方法; 䌗倚的尝试方法䞭可胜若干的尝试方法有重倍调甚的情况可以蜬化成劚态规划; 若干䞪可以蜬化成劚态规划的方法䞭又可胜有䌘劣之分. 刀定哪䞪是最䌘的劚态规划方法䟝据来自题目具䜓参数的数据量, 最䌘的劚态规划方法实现后后续又有䞀敎套的䌘化技巧 == 从递園入手二绎劚态规划 - 尝试凜数有 1 䞪可变参数可以完党决定返回倌进而可以改出 1 绎劚态规划衚的实现 - 尝试凜数有 2 䞪可变参数可以完党决定返回倌那么就可以改出 2 绎劚态规划的实现 䞀绎、二绎、䞉绎甚至倚绎劚态规划问题倧䜓过皋郜是 1. 写出尝试递園 2. 记忆化搜玢(从顶到底的劚态规划) 3. 䞥栌䜍眮䟝赖的劚态规划(从底到顶的劚态规划) 4. 空闎、时闎的曎倚䌘化 劚态规划衚的倧小每䞪可变参数的可胜性数量盞乘 劚态规划方法的时闎倍杂床劚态规划衚的倧小 \* 每䞪栌子的枚䞟代价 二绎劚态规划䟝然需芁去敎理 劚态规划衚的栌子之闎的䟝赖关系 扟寻䟝赖关系埀埀 通过画囟来建立空闎感䜿其曎星而易见 然后䟝然是 从简单栌子填写到倍杂栌子 的过皋即䞥栌䜍眮䟝赖的劚态规划(从底到顶) 二绎劚态规划的压猩空闎技巧原理䞍隟䌚了之后千篇䞀埋 䜆是䞍同题目䟝赖关系䞍䞀样需芁埈细心的画囟来敎理具䜓题目的䟝赖关系 最后进行空闎压猩的实现 䞀定芁 *写出可变参数类型简单䞍比 int 类型曎倍杂*并䞔 *可以完党决定返回倌的递園* 保证做到 这些可变参数可以完党代衚之前决策过皋对后续过皋的圱响再去改劚态规划 䞍管几绎劚态规划, 经垞从递園的定义出发避免后续进行埈倚蟹界讚论, 这需芁䞀定的经验来预知 === #link( "https://leetcode.cn/problems/minimum-path-sum/description/", )[ 题目 1 : 最小路埄和 ] 给定䞀䞪包含非莟敎数的 m x n 眑栌 `grid` 请扟出䞀条从巊䞊角到右䞋角的路埄䜿埗路埄䞊的数字总和䞺最小。 诎明每次只胜向䞋或者向右移劚䞀步。 ==== 解答 #code(caption: [ 题目 1 : 最小路埄和 ])[ ```java public int minPathSum(int[][] grid) { // 暎力递園 public static int minPathSum1(int[][] grid) { return f1(grid, grid.length - 1, grid[0].length - 1); } // 从(0,0)到(i,j)最小路埄和 // 䞀定每次只胜向右或者向䞋 public static int f1(int[][] grid, int i, int j) { if (i == 0 && j == 0) { return grid[0][0]; } int up = Integer.MAX_VALUE; int left = Integer.MAX_VALUE; if (i - 1 >= 0) { up = f1(grid, i - 1, j); } if (j - 1 >= 0) { left = f1(grid, i, j - 1); } return grid[i][j] + Math.min(up, left); } // 记忆化搜玢 public static int minPathSum2(int[][] grid) { int n = grid.length; int m = grid[0].length; int[][] dp = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[i][j] = -1; } } return f2(grid, grid.length - 1, grid[0].length - 1, dp); } public static int f2(int[][] grid, int i, int j, int[][] dp) { if (dp[i][j] != -1) { return dp[i][j]; } int ans; if (i == 0 && j == 0) { ans = grid[0][0]; } else { int up = Integer.MAX_VALUE; int left = Integer.MAX_VALUE; if (i - 1 >= 0) { up = f2(grid, i - 1, j, dp); } if (j - 1 >= 0) { left = f2(grid, i, j - 1, dp); } ans = grid[i][j] + Math.min(up, left); } dp[i][j] = ans; return ans; } // 䞥栌䜍眮䟝赖的劚态规划 public static int minPathSum3(int[][] grid) { int n = grid.length; int m = grid[0].length; int[][] dp = new int[n][m]; dp[0][0] = grid[0][0]; for (int i = 1; i < n; i++) { dp[i][0] = dp[i - 1][0] + grid[i][0]; } for (int j = 1; j < m; j++) { dp[0][j] = dp[0][j - 1] + grid[0][j]; } for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; } } return dp[n - 1][m - 1]; } // 䞥栌䜍眮䟝赖的劚态规划 + 空闎压猩技巧 public static int minPathSum4(int[][] grid) { int n = grid.length; int m = grid[0].length; // 先让dp衚变成想象䞭的衚的第0行的数据 int[] dp = new int[m]; dp[0] = grid[0][0]; for (int j = 1; j < m; j++) { dp[j] = dp[j - 1] + grid[0][j]; } for (int i = 1; i < n; i++) { // i = 1dp衚变成想象䞭二绎衚的第1行的数据 // i = 2dp衚变成想象䞭二绎衚的第2行的数据 // i = 3dp衚变成想象䞭二绎衚的第3行的数据 // ... // i = n-1dp衚变成想象䞭二绎衚的第n-1行的数据 dp[0] += grid[i][0]; for (int j = 1; j < m; j++) { dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j]; } } return dp[m - 1]; } } ``` ] #tip("Tip")[ 改成劚态规划的时候, 并䞍胜把`dp`郜初始化䞺-1 ] #tip( "Tip", )[ 胜改成劚态规划的递園统䞀特埁 - *决定返回倌的可变参数类型埀埀郜比蟃简单䞀般䞍䌚比 int 类型曎倍杂。䞺什么* - 从这䞪角床可以解释 *垊路埄的递園可变参数类型倍杂䞍适合或者诎没有必芁改成劚态规划* 题目 2 就是诎明这䞀点的 ] === #link( "https://leetcode.cn/problems/word-search/description/", )[题目 2: 单词搜玢] 给定䞀䞪 m x n 二绎字笊眑栌 `board` 和䞀䞪字笊䞲单词 `word` 。劂果 `word` 存圚于眑栌䞭返回 `true` 吊则返回 `false` 。 单词必须按照字母顺序通过盞邻的单元栌内的字母构成其䞭“盞邻”单元栌是那些氎平盞邻或垂盎盞邻的单元栌。同䞀䞪单元栌内的字母䞍允讞被重倍䜿甚。 #tip("Tip")[ 埀埀题目的数据量郜比蟃小 ] #code( caption: [题目 2: 单词搜玢], )[ ```java public static boolean exist(char[][] board, String word) { boolean succeed = false; char[] w = word.toCharArray(); int m = board.length; int n = board[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { succeed = f(board, w, i, j, 0); if (succeed) break; } } return succeed; } // 从i,j出发,到了w[k], 接䞋来胜䞍胜匹配到w[k+1...] public static boolean f(char[][] board, char[] w, int i, int j, int k) { // 匹配到最后䞀䞪了 if (k == w.length) { return true; } // 越界 if (i < 0 || i == board.length || j < 0 || j == board[0].length || board[i][j] != w[k]) { return false; } // 䞍越界 board[i][j] = w[k] char tmp = board[i][j]; board[i][j] = 0; boolean ans = f(board, w, i + 1, j, k + 1) || f(board, w, i - 1, j, k + 1) || f(board, w, i, j + 1, k + 1) || f(board, w, i, j - 1, k + 1); board[i][j] = tmp; return ans; } ``` ] === #link( "https://leetcode.cn/problems/longest-common-subsequence/description/", )[题目 3: 最长公共子序列] 给定䞀䞪字笊䞲 `text1` 和 `text2`返回这䞀䞪字笊䞲的最长 公共子序列 的长床。劂果䞍存圚 公共子序列 返回 `0` 。 䞀䞪字笊䞲的 子序列 是指这样䞀䞪新的字笊䞲它是由原字笊䞲圚䞍改变字笊的盞对顺序的情况䞋删陀某些字笊也可以䞍删陀任䜕字笊后组成的新字笊䞲。 䟋劂`"ace" `是 `"abcde" `的子序列䜆 `"aec" `䞍是 `"abcde" `的子序列。 䞀䞪字笊䞲的 公共子序列 是这䞀䞪字笊䞲所共同拥有的子序列。 #tip("Tip")[ - 蟓入`text1 = "abcde"`, `text2 = "ace"` - 蟓出`3` - 解释最长公共子序列是 `"ace" `它的长床䞺 `3` 。 ] ==== 解答 可胜性, 劚态规划的关键 䞀种垞见的就是长床定奜之后, 按照结尟来讚论可胜性.(䞺啥, 䞀种垞见的暡型) #code( caption: [题目 3: 最长公共子序列], )[ ```java public class Code03_LongestCommonSubsequence { public static int longestCommonSubsequence(String text1, String text2) { char[] t1 = text1.toCharArray(); char[] t2 = text2.toCharArray(); return f(t1, t2, t1.length - 1, t2.length - 1); } // t1[0..p1] 侎 t2[0...p2] 公共子序列的长床 public static int f(char[] t1, char[] t2, int i1, int i2) { if (i1 < 0 || i2 < 0) { return 0; } // 公共子䞲䞍包含结尟 int p1 = f(t1, t2, i1 - 1, i2 - 1); // 芁䞀䞪结尟,䞍芁及䞀䞪 int p2 = f(t1, t2, i1, i2 - 1); int p3 = f(t1, t2, i1 - 1, i2); // 䞀䞪结尟郜芁 int p4 = t1[i1] == t2[i2] ? (p1 + 1) : 0; return Math.max(Math.max(p1, p2), Math.max(p3, p4)); } // 䞺了避免埈倚蟹界讚论 // 埈倚时候埀埀䞍甚䞋标来定义尝试而是甚长床来定义尝试 // 因䞺长床最短是0而䞋标越界的话讚论起来就比蟃麻烊 public static int longestCommonSubsequence2(String str1, String str2) { char[] s1 = str1.toCharArray(); char[] s2 = str2.toCharArray(); int n = s1.length; int m = s2.length; return f2(s1, s2, n, m); } // s1[前猀长床䞺len1]对应s2[前猀长床䞺len2] // 最长公共子序列长床 public static int f2(char[] s1, char[] s2, int len1, int len2) { if (len1 == 0 || len2 == 0) { return 0; } int ans; if (s1[len1 - 1] == s2[len2 - 1]) { ans = f2(s1, s2, len1 - 1, len2 - 1) + 1; } else { ans = Math.max(f2(s1, s2, len1 - 1, len2), f2(s1, s2, len1, len2 - 1)); } return ans; } // 记忆化搜玢 public static int longestCommonSubsequence3(String str1, String str2) { char[] s1 = str1.toCharArray(); char[] s2 = str2.toCharArray(); int n = s1.length; int m = s2.length; int[][] dp = new int[n + 1][m + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= m; j++) { dp[i][j] = -1; } } return f3(s1, s2, n, m, dp); } public static int f3(char[] s1, char[] s2, int len1, int len2, int[][] dp) { if (len1 == 0 || len2 == 0) { return 0; } if (dp[len1][len2] != -1) { return dp[len1][len2]; } int ans; if (s1[len1 - 1] == s2[len2 - 1]) { ans = f3(s1, s2, len1 - 1, len2 - 1, dp) + 1; } else { ans = Math.max(f3(s1, s2, len1 - 1, len2, dp), f3(s1, s2, len1, len2 - 1, dp)); } dp[len1][len2] = ans; return ans; } // 䞥栌䜍眮䟝赖的劚态规划 public static int longestCommonSubsequence4(String str1, String str2) { char[] s1 = str1.toCharArray(); char[] s2 = str2.toCharArray(); int n = s1.length; int m = s2.length; int[][] dp = new int[n + 1][m + 1]; for (int len1 = 1; len1 <= n; len1++) { for (int len2 = 1; len2 <= m; len2++) { if (s1[len1 - 1] == s2[len2 - 1]) { dp[len1][len2] = 1 + dp[len1 - 1][len2 - 1]; } else { dp[len1][len2] = Math.max(dp[len1 - 1][len2], dp[len1][len2 - 1]); } } } return dp[n][m]; } // 䞥栌䜍眮䟝赖的劚态规划 + 空闎压猩 public static int longestCommonSubsequence5(String str1, String str2) { char[] s1, s2; if (str1.length() >= str2.length()) { s1 = str1.toCharArray(); s2 = str2.toCharArray(); } else { s1 = str2.toCharArray(); s2 = str1.toCharArray(); } int n = s1.length; int m = s2.length; int[] dp = new int[m + 1]; for (int len1 = 1; len1 <= n; len1++) { int leftUp = 0, backup; for (int len2 = 1; len2 <= m; len2++) { backup = dp[len2]; if (s1[len1 - 1] == s2[len2 - 1]) { dp[len2] = 1 + leftUp; } else { dp[len2] = Math.max(dp[len2], dp[len2 - 1]); } leftUp = backup; } } return dp[m]; } } ``` ] === #link( "https://leetcode.cn/problems/longest-palindromic-subsequence/description/", )[最长回文子序列] #definition( "Definition", )[ 子序列定义䞺䞍改变剩䜙字笊顺序的情况䞋删陀某些字笊或者䞍删陀任䜕字笊圢成的䞀䞪序列。 ] 给䜠䞀䞪字笊䞲 `s` 扟出其䞭最长的回文子序列并返回该序列的长床。 #example("Example")[ - 蟓入`s = "bbbab"` - 蟓出`4` - 解释䞀䞪可胜的最长回文子序列䞺 `"bbbb" `。 ] #example("Example")[ - 蟓入`s = "cbbd"` - 蟓出`2` - 解释䞀䞪可胜的最长回文子序列䞺 `"bb"` 。 ] #tip("Tip")[ - 1 <= `s.length` <= 1000 - s 仅由小写英文字母组成 ] ==== 解答 #code(caption: [题目4: 最长回文子序列])[ ```java public class Code04_LongestPalindromicSubsequence { public static int longestPalindromeSubseq1(String str) { char[] s = str.toCharArray(); int n = s.length; int[][] dp = new int[n][n]; int ans = f1(s, 0, n - 1, dp); return ans; } // l...r 最长回文子序列 public static int f1(char[] s, int l, int r, int[][] dp) { if (l == r) { return 1; } if (l + 1 == r) { return s[l] == s[r] ? 2 : 1; } if (dp[l][r] != 0) { return dp[l][r]; } int ans; if (s[l] == s[r]) { ans = 2 + f(s, l + 1, r - 1, dp); } else { ans = Math.max(f(s, l + 1, r, dp), f(s, l, r - 1, dp)); } dp[l][r] = ans; return ans; } // 䞥栌衚结构 public static int longestPalindromeSubseq3(String str) { char[] s = str.toCharArray(); int n = s.length; int[][] dp = new int[n][n]; // l䞺行r䞺列 -> r >= l for (int l = n - 1; l >= 0; l--) { // l=r 对角线是1 dp[l][l] = 1; // l+1 = r if (l + 1 < n) { dp[l][l + 1] = s[l] == s[l + 1] ? 2 : 1; } for (int r = l + 2; r < n; r++) { if (s[l] == s[r]) { dp[l][r] = 2 + dp[l - 1][r - 1]; } else { dp[l][r] = Math.max(dp[l - 1][r], dp[l][r - 1]); } } } return dp[0][n - 1]; } } ``` ] === #link( "https://www.nowcoder.com/practice/aaefe5896cce4204b276e213e725f3ea", )[题目5: 二叉树的结构数] #definition("Definition")[ 树的高床: 定义䞺所有叶子到根路埄䞊节点䞪数的最倧倌. ] 小区现圚有`n`䞪节点,他想请䜠垮他计算出有倚少种䞍同的二叉树满足节点䞪数䞺`n`䞔树的高床䞍超过`m`的方案.因䞺答案埈倧,所以答案需芁暡䞊`1e9+7`后蟓出. - 蟓入描述 第䞀行蟓入䞀䞪正敎数`n`和`m`. `1≀m≀n≀50` - 蟓出描述 蟓出䞀䞪答案衚瀺方案数. #example("Example")[ - 蟓入 `3 3` - 蟓出 `5` ] ==== 解答 #code( caption: [题目5: 二叉树的结构数], )[ ```java public class Code05_NodenHeightNotLargerThanm { public static int MAXN = 51; public static int MAXM = 51; public static int MOD = 1000000007; public static long[][] dp = new long[MAXN][MAXM]; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer in = new StreamTokenizer(br); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); while (in.nextToken() != StreamTokenizer.TT_EOF) { int n = (int) in.nval; in.nextToken(); int m = (int) in.nval; for (int i = 0; i < n+1; i++) { for (int j = 0; j < m+1; j++) { dp[i][j] = -1; } } out.println(compute(n, m)); } out.flush(); out.close(); br.close(); } // n䞪节点高床䞍超过m // 记忆化搜玢 public static int compute(int n, int m) { if (n == 0) { return 1; } // n>0 if (m == 0) { return 0; } if (dp[n][m] != -1) { return (int) dp[n][m]; } long ans = 0; // left 几䞪 right 几䞪 倎占掉䞀䞪 for (int i = 0; i < n; i++) { int left = compute(i, m - 1) % MOD; int right = compute(n - i - 1, m - 1) % MOD; ans = (ans + ((long) left * right) % MOD) % MOD; } dp[n][m] = ans; return (int) ans; } } ``` ] === #link( "https://leetcode.cn/problems/longest-increasing-path-in-a-matrix/", )[矩阵䞭的最长递增路埄] 给定䞀䞪 `m x n` 敎数矩阵 `matrix` 扟出其䞭 最长递增路埄 的长床。 对于每䞪单元栌䜠可以埀䞊䞋巊右四䞪方向移劚。 䜠 䞍胜 圚 对角线 方向䞊移劚或移劚到 蟹界倖即䞍允讞环绕。 #example("Example")[ - 蟓入 ``` matrix = [[9,9,4], [6,6,8], [2,1,1]] ``` - 蟓出`4` - 解释最长递增路埄䞺 `[1, 2, 6, 9]`。 ] #tip("Tip")[ - m == matrix.length - n == matrix[i].length - 1 <= m, n <= 200 - 0 <= matrix[i][j] <= 2^31 - 1 ] ==== 解答 #code(caption: [题目6: 矩阵䞭最长递增路埄])[ ```java public class Code06_LongestIncreasingPath { public static int longestIncreasingPath(int[][] matrix) { int n = matrix.length; int m = matrix[0].length; int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { max = Math.max(max, f(matrix, i, j)); } } return max; } // 从 i,j 出发 最长的递增路埄 public static int f(int[][] matrix, int i, int j) { int next = 0; if (i > 0 && grid[i][j] < grid[i - 1][j]) { next = Math.max(next, f1(grid, i - 1, j)); } if (i + 1 < grid.length && grid[i][j] < grid[i + 1][j]) { next = Math.max(next, f1(grid, i + 1, j)); } if (j > 0 && grid[i][j] < grid[i][j - 1]) { next = Math.max(next, f1(grid, i, j - 1)); } if (j + 1 < grid[0].length && grid[i][j] < grid[i][j + 1]) { next = Math.max(next, f1(grid, i, j + 1)); } return next + 1; } public static int longestIncreasingPath2(int[][] grid) { int n = grid.length; int m = grid[0].length; int[][] dp = new int[n][m]; int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ans = Math.max(ans, f2(grid, i, j, dp)); } } return ans; } public static int f2(int[][] grid, int i, int j, int[][] dp) { if (dp[i][j] != 0) { return dp[i][j]; } int next = 0; if (i > 0 && grid[i][j] < grid[i - 1][j]) { next = Math.max(next, f2(grid, i - 1, j, dp)); } if (i + 1 < grid.length && grid[i][j] < grid[i + 1][j]) { next = Math.max(next, f2(grid, i + 1, j, dp)); } if (j > 0 && grid[i][j] < grid[i][j - 1]) { next = Math.max(next, f2(grid, i, j - 1, dp)); } if (j + 1 < grid[0].length && grid[i][j] < grid[i][j + 1]) { next = Math.max(next, f2(grid, i, j + 1, dp)); } dp[i][j] = next + 1; return next + 1; } } ``` ] === #link( "https://leetcode.cn/problems/distinct-subsequences/description/", )[题目7: 䞍同的子序列] 给䜠䞀䞪字笊䞲 `s` 和 `t` 统计并返回圚 `s` 的 子序列 äž­ `t` 出现的䞪数结果需芁对 `10^9 + 7` 取暡。 #example("Example")[ - 蟓入`s = "rabbbit", t = "rabbit"` - 蟓出`3` - 解释 - 劂䞋所瀺, 有 3 种可以从 `s` 䞭埗到 `"rabbit"` 的方案。 - *rabb* b *it* - *rab* b *bit* - *rabb* b *it* ] ==== 解答 #code( caption: [题目7: 䞍同的子序列], )[ ```java public class Code01_DistinctSubsequences { // 盎接劚态规划 public static int numDistinct(String s, String t) { int MOD = 1000000007; char[] s1 = s.toCharArray(); char[] s2 = t.toCharArray(); int len1 = s1.length; int len2 = s2.length; // 衚瀺前猀长床(䜿甚䞋标䌚有埈倚蟹界情况的讚论) int[][] dp = new int[len1 + 1][len2 + 1]; // 尝试: s1[...p1] 已经匹配了x䞪 s2[...p2] // s1[0] -> s2[0] = 1 s2[1....] 0 // s2[0] -> s1[0] = 1 s1[1....] 1 (子序列生成的空集) for (int i = 0; i < dp.length; i++) { dp[i][0] = 1; } // 按照末尟讚论可胜性,s1[...p1] s2[...p2] // 䞍芁s1的最后䞀䞪, 就芁s1[...p1-1] s2[...p2] // 对应 dp[p1-1][p2](侊) // 芁s1的最后䞀䞪就芁芁求s1[p1] == s2[p2], 接䞋来s1[...p1-1] s2[...p2-1] // 对应dp[p1-1][p2-1](巊䞊) // 以䞊䞀种可胜性盞加 // -------->填衚 for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { int p1 = dp[i-1][j]%MOD; // 因䞺代衚长床所以圚䞋标的时候芁-1䞍然䌚越界 int p2 = s1[i-1]==s2[j-1]?( dp[i-1][j-1]%MOD ):0; dp[i][j] = (p1+p2)%MOD; } } return dp[len1][len2]; } // 空闎压猩 public static int numDistinct2(String str, String target){ int MOD = 1000000007; char[] s1 = s.toCharArray(); char[] s2 = t.toCharArray(); int len1 = s1.length; int len2 = s2.length; // 衚瀺前猀长床(䜿甚䞋标䌚有埈倚蟹界情况的讚论) int[] dp = new int[len2 + 1]; dp[0] = 1; // -------->填衚 for (int i = 1; i <= len1; i++) { int leftUp = 1, backup; for (int j = 1; j <= len2; j++) { backup = dp[j]; // 侊 int p1 = dp[j]%MOD; // 巊䞊 int p2 = s1[i-1]==s2[j-1]?( leftUp%MOD ):0; // 圓前 dp[j] = (p1+p2)%MOD; leftUp = backup; } } return dp[len2]; } } ``` ] === #link( "https://leetcode.cn/problems/edit-distance/description/", )[题目8: 猖蟑距犻] 给䜠䞀䞪单词 `word1` 和 `word2` 请返回将 `word1` 蜬换成 `word2` 所䜿甚的最少操䜜数。 䜠可以对䞀䞪单词进行劂䞋䞉种操䜜 - 插入䞀䞪字笊(代价䞺`a`) - 删陀䞀䞪字笊(代价䞺`b`) - 替换䞀䞪字笊(代价䞺`c`) #example("Example")[ - 蟓入`word1 = "horse", word2 = "ros", a=b=c=1` - 蟓出`3` - 解释 - horse -> rorse (将 'h' 替换䞺 'r') - rorse -> rose (删陀 'r') - rose -> ros (删陀 'e') ] ==== 解答 1. `s1[i-1]`参䞎 - `s1[i-1]`->`s2[j-1]` 1. `s1[i-1]==s2[j-1]` `s1[0...i-2]`搞定`s2[0...j-2]`即`dp[i-1][j-1]` 2. `s1[i-1]!=s2[j-1]` `s1[i-1]`盎接替换成`s2[j-1]`即`dp[i-1][j-1]+替换代价` - `s1[i-1]!->s2[j-1]` - `s1[...i-1]`搞定`s2[...j-2]`最后通过插入搞定`s2[j-1]` 即`dp[i][j-1]+插入` 2. `s1[i-1]`䞍参䞎, 删掉`s1[i-1]` 即`dp[i-1][j]+删陀代价` #code(caption: [题目8: 猖蟑距犻])[ ```java public class Code02_EditDistance { public int minDistance(String word1, String word2) { return editDistance2(word1, word2, 1, 1, 1); } // 原初尝试版 // a : str1䞭插入1䞪字笊的代价 // b : str1䞭删陀1䞪字笊的代价 // c : str1䞭改变1䞪字笊的代价 // 返回从str1蜬化成str2的最䜎代价 public static int editDistance1(String str1, String str2, int a, int b, int c) { char[] s1 = str1.toCharArray(); char[] s2 = str2.toCharArray(); int n = s1.length; int m = s2.length; // dp[i][j] : // s1[前猀长床䞺i]想变成s2[前猀长床䞺j]至少付出倚少代价 int[][] dp = new int[n + 1][m + 1]; for (int i = 1; i <= n; i++) { dp[i][0] = i * b; } for (int j = 1; j <= m; j++) { dp[0][j] = j * a; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int p1 = Integer.MAX_VALUE; if (s1[i - 1] == s2[j - 1]) { p1 = dp[i - 1][j - 1]; } int p2 = Integer.MAX_VALUE; if (s1[i - 1] != s2[j - 1]) { p2 = dp[i - 1][j - 1] + c; } int p3 = dp[i][j - 1] + a; int p4 = dp[i - 1][j] + b; dp[i][j] = Math.min(Math.min(p1, p2), Math.min(p3, p4)); } } return dp[n][m]; } // 枚䞟小䌘化版 public static int editDistance2(String str1, String str2, int a, int b, int c) { char[] s1 = str1.toCharArray(); char[] s2 = str2.toCharArray(); int n = s1.length; int m = s2.length; // dp[i][j] : // s1[前猀长床䞺i]想变成s2[前猀长床䞺j]至少付出倚少代价 int[][] dp = new int[n + 1][m + 1]; for (int i = 1; i <= n; i++) { dp[i][0] = i * b; } for (int j = 1; j <= m; j++) { dp[0][j] = j * a; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s1[i - 1] == s2[j - 1]) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = Math.min(Math.min(dp[i - 1][j] + b, dp[i][j - 1] + a), dp[i - 1][j - 1] + c); } } } return dp[n][m]; } // 空闎压猩 public static int editDistance3(String str1, String str2, int a, int b, int c) { char[] s1 = str1.toCharArray(); char[] s2 = str2.toCharArray(); int n = s1.length; int m = s2.length; int[] dp = new int[m + 1]; for (int j = 1; j <= m; j++) { dp[j] = j * a; } for (int i = 1, leftUp, backUp; i <= n; i++) { leftUp = (i - 1) * b; dp[0] = i * b; for (int j = 1; j <= m; j++) { backUp = dp[j]; if (s1[i - 1] == s2[j - 1]) { dp[j] = leftUp; } else { dp[j] = Math.min(Math.min(dp[j] + b, dp[j - 1] + a), leftUp + c); } leftUp = backUp; } } return dp[m]; } } ``` ] == 从递園入手䞉䜍劚态规划 - 尝试凜数有1䞪可变参数可以完党决定返回倌进而可以改出1绎劚态规划衚的实现 - 尝试凜数有2䞪可变参数可以完党决定返回倌那么就可以改出2绎劚态规划的实现 - 尝试凜数有3䞪可变参数可以完党决定返回倌那么就可以改出3绎劚态规划的实现 倧䜓过皋郜是 + 写出尝试递園 + 记忆化搜玢(从顶到底的劚态规划) + 䞥栌䜍眮䟝赖的劚态规划(从底到顶的劚态规划) + 空闎、时闎的曎倚䌘化 === #link("https://leetcode.cn/problems/ones-and-zeroes/")[题目1: 䞀和零] 给䜠䞀䞪二进制字笊䞲数组 `strs` 和䞀䞪敎数 `m` 和 `n` 。 请䜠扟出并返回 `strs` 的最倧子集的长床该子集䞭 最倚 有 `m` 䞪 `0` 和 `n` 䞪 `1` 。 #example("Example")[ - 蟓入`strs = ["10", "0001", "111001", "1", "0"]`, `m = 5`, `n = 3` - 蟓出`4` - 解释最倚有 5 䞪 0 和 3 䞪 1 的最倧子集是 {"10","0001","1","0"} 因歀答案是 4 。 其他满足题意䜆蟃小的子集包括 `{"0001","1"}` 和 `{"10","1","0"}` 。`{"111001"}` 䞍满足题意因䞺它含 `4` 䞪 `1` 倧于 `n` 的倌 `3` 。 ] #example("Example")[ - 蟓入`strs = ["10", "0", "1"]`, `m = 1`, `n = 1` - 蟓出`2` - 解释最倧的子集是 `{"0", "1"}` 所以答案是 `2` 。 ] #tip("Tip")[ - `1 <= strs.length <= 600` - `1 <= strs[i].length <= 100` - `strs[i]` 仅由 `'0'` 和 `'1'` 组成 - `1 <= m, n <= 100` ] ==== 解答 #code(caption: [题目1: 䞀和零])[ ```java public class Code01_OnesAndZeroes { public static int zeros; public static int ones; public static void count(String str){ zeros = 0; ones = 0; for (int i = 0; i < str.length(); i++) { if(str.charAt(i)=='0'){ zeros++; }else if(str.charAt(i)=='1'){ ones++; } } } public static int findMaxForm1(String[] strs, int m, int n) { return f1(strs, 0, m, n); } // strs[i...] 自由选择0的数量䞍超过z1的数量䞍超过o // 最倚胜选择倚少字笊䞲 public static int f1(String[] strs, int cur, int z, int o){ if(cur==strs.length){ return 0; } // 䞍选择圓前字笊䞲 int p1 = f1(strs, cur+1, z, o); // 选择圓前字笊䞲 int p2 = 0; count(strs[cur]); if(zeros<=z && ones<=o){ p2 = 1 + f1(strs, cur+1, z-zeros, o-ones); } return Math.max(p1, p2); } // 记忆化搜玢 public static int findMaxForm2(String[] strs, int m, int n) { int[][][] dp = new int[strs.length][m+1][n+1]; for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[0].length; j++) { for (int k = 0; k < dp[0][0].length; k++) { dp[i][j][k] = -1; } } } return f2(dp, strs, 0, m, n); } public static int f2(int[][][] dp, String[] strs, int cur, int z, int o){ if(cur==strs.length){ return 0; } if(dp[cur][z][o]!=-1){ return dp[cur][z][o]; } // 䞍选择圓前字笊䞲 int p1 = f2(dp, strs, cur+1, z, o); // 选择圓前字笊䞲 int p2 = 0; count(strs[cur]); if(zeros<=z && ones<=o){ p2 = 1 + f2(dp, strs, cur+1, z-zeros, o-ones); } dp[cur][z][o] = Math.max(p1, p2); return dp[cur][z][o]; } // 䞥栌衚䟝赖 public static int findMaxForm3(String[] strs, int m, int n) { int len = strs.length; // 来到 strs[cur...]芁0的数量<=m1的数量<=n 的最倧长床 int[][][] dp = new int[len+1][m+1][n+1]; // base case: dp[len][..][..]=0 // 每䞀层䟝赖䞊䞀层 for (int cur = len-1; cur >= 0; cur--) { count(strs[cur]); for (int z = 0; z <= m; z++) { for (int o = 0; o <= n; o++) { int p1 = dp[cur+1][z][o]; int p2 = 0; if(z>=zeros && o >=ones){ p2 = 1 + dp[cur+1][z-zeros][o-ones]; } dp[cur][z][o] = Math.max(p1, p2); } } } return dp[0][m][n]; } // 空闎压猩 public static int findMaxForm4(String[] strs, int m, int n) { // 代衚cur==len int[][] dp = new int[m+1][n+1]; // 第i层䟝赖第i+1层圓前䜍眮以及巊䞋角某䞪倌 // 从右䞊到巊䞋进行空闎压猩 for (String s : strs) { // 每䞪字笊䞲逐析遍历即可 // 曎新每䞀层的衚 // 和之前的遍历没有区别 count(s); for (int z = m; z >= zeros; z--) { for (int o = n; o >= ones; o--) { dp[z][o] = Math.max(dp[z][o], 1 + dp[z - zeros][o - ones]); } } } return dp[m][n]; } } ``` ] === #link("https://leetcode.cn/problems/profitable-schemes/")[题目2: 盈利计划] 集团里有 `n` 名员工他们可以完成各种各样的工䜜创造利涊。第 `i` 种工䜜䌚产生 `profit[i]` 的利涊它芁求 `group[i]` 名成员共同参䞎。劂果成员参䞎了其䞭䞀项工䜜就䞍胜参䞎及䞀项工䜜。工䜜的任䜕至少产生 `minProfit` 利涊的子集称䞺 盈利计划 。并䞔工䜜的成员总数最倚䞺 `n` 。 有倚少种计划可以选择因䞺答案埈倧所以 返回结果暡 `10^9 + 7` 的倌。 #example("Example")[ - 蟓入`n = 5`, `minProfit = 3`, `group = [2,2]`, `profit = [2,3]` - 蟓出`2` - 解释至少产生 3 的利涊该集团可以完成工䜜 0 和工䜜 1 或仅完成工䜜 1 。 总的来诎有䞀种计划。 ] #tip("Tip")[ - 蟓入`n = 10`, `minProfit = 5`, `group = [2,3,5]`, `profit = [6,7,8]` - 蟓出`7` - 解释至少产生 `5` 的利涊只芁完成其䞭䞀种工䜜就行所以该集团可以完成任䜕工䜜。 有 7 种可胜的计划(0)(1)(2)(0,1)(0,2)(1,2)以及 (0,1,2) 。 ] #tip("Tip")[ - `1 <= n <= 100` - `0 <= minProfit <= 100` - `1 <= group.length <= 100` - `1 <= group[i] <= 100` - `profit.length == group.length` - `0 <= profit[i] <= 100` ] ==== 解答 #code(caption: [题目2: 盈利计划])[ ```java public class Code02_ProfitableSchemes { public static int MOD = 1000000007; public int profitableSchemes1(int n, int minProfit, int[] group, int[] profit) { return f1(0, group, profit,n, minProfit); } // 来到第job仜工䜜,芁求剩䞋的工䜜n䞪人至少产生minProfit的利涊 // 返回方案数 public static int f1(int job, int[] group, int[] profit,int n, int minProfit){ int len = profit.length; // 劂果没人了或者工䜜选完了 if(n < 0 || job==len){ return minProfit > 0 ? 0:1; } // 䞍做圓前这仜工䜜 int p1 = f1(job+1, group, profit, n, minProfit); // 做圓前这仜工䜜 int p2 = 0; if(n-group[job]>=0){ p2= f1(job+1, group, profit, n-group[job], minProfit-profit[job]); } return p1+p2; } public int profitableSchemes2(int n, int minProfit, int[] group, int[] profit) { int len = profit.length; int[][][] dp = new int[len+1][n+1][minProfit+1]; for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[0].length; j++) { for (int k = 0; k < dp[0][0].length; k++) { dp[i][j][k] = -1; } } } return f2(dp, 0, group, profit,n, minProfit); } public static int f2(int[][][] dp, int job, int[] group, int[] profit,int n, int minProfit){ int len = profit.length; // 劂果没人了或者工䜜选完了 if(n < 0 || job==len){ return minProfit > 0 ? 0:1; } if(dp[job][n][minProfit]!=-1){ return dp[job][n][minProfit]; } // 䞍做圓前这仜工䜜 int p1 = f2(dp, job+1, group, profit, n, minProfit); // 做圓前这仜工䜜 int p2 = 0; if(n-group[job]>=0){ p2= f2(dp, job+1, group, profit, n-group[job], Math.max(0,minProfit-profit[job])); } dp[job][n][minProfit] = (p1+p2) % MOD; return dp[job][n][minProfit]; } // 䞥栌衚结构+空闎压猩 public int profitableSchemes3(int n, int minProfit, int[] group, int[] profit) { int len = profit.length; // i = 没有工䜜的时候i == g.length int[][] dp = new int[n + 1][minProfit + 1]; // 工䜜选完之后还有人䜆是已经䞍甚再盈利 for (int person = 0; person <= n; person++) { dp[person][0] = 1; } for (int job = len-1; job >= 0; job--) { for (int person = n; person >= 0; person--) { for (int prof = minProfit; prof >= 0; prof--) { int p1 = dp[person][prof]; int p2 = 0; if((person-group[job])>=0){ p2 = dp[person-group[job]][Math.max(0,prof-profit[job])]; } dp[person][prof] = (p1+p2)%MOD; } } } return dp[n][minProfit]; } } ``` ] === #link("https://leetcode.cn/problems/knight-probability-in-chessboard/")[题目3: 骑士圚棋盘䞊的抂率] 圚䞀䞪 `n x n` 的囜际象棋棋盘䞊䞀䞪骑士从单元栌 `(row, column)` 匀始并尝试进行 `k` 次移劚。行和列是 从 `0` 匀始 的所以巊䞊单元栌是 `(0,0)` 右䞋单元栌是 `(n - 1, n - 1)` 。 象棋骑士有`8`种可胜的走法(类䌌象棋䞭的🐎的走法)。每次移劚圚基本方向䞊是䞀䞪单元栌然后圚正亀方向䞊是䞀䞪单元栌。每次骑士芁移劚时它郜䌚随机从8种可胜的移劚䞭选择䞀种(即䜿棋子䌚犻匀棋盘)然后移劚到那里。骑士继续移劚盎到它走了 `k` 步或犻匀了棋盘。 返回 骑士圚棋盘停止移劚后仍留圚棋盘䞊的抂率 。 #example("Example")[ - 蟓入: `n = 3`, `k = 2`, `row = 0`, `column = 0` - 蟓出: `0.0625` - 解释: 有䞀步(到`(1,2)``(2,1)`)可以让骑士留圚棋盘䞊。 圚每䞀䞪䜍眮䞊也有䞀种移劚可以让骑士留圚棋盘䞊。骑士留圚棋盘䞊的总抂率是0.0625。 ] #example("Example")[ - 蟓入: `n = 1`, `k = 0`, `row = 0`, `column = 0` - 蟓出: `1.00000` ] #tip("Tip")[ - `1 <= n <= 25` - `0 <= k <= 100` - `0 <= row, column <= n - 1` ] ==== 解答 #code(caption: [骑士圚棋盘䞊的抂率 - 解答])[ ```java public class Code03_KnightProbabilityInChessboard { public double knightProbability(int n, int k, int row, int col) { double[][][] dp = new double[k+1][n][n]; for (int t = 0; t <= k; t++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i][j][t] = -1; } } } return f(n, row, col, k, dp); } // 从(i,j)出发还有k步芁走返回最后圚棋盘䞊的抂率 public static double f(int n, int i, int j, int k, double[][][] dp) { if (i < 0 || i >= n || j < 0 || j >= n) { return 0; } if (dp[i][j][k] != -1) { return dp[i][j][k]; } double ans = 0; if(k==0){ return 1; }else{ ans += (f(n, i - 2, j + 1, k - 1, dp) / 8); ans += (f(n, i - 1, j + 2, k - 1, dp) / 8); ans += (f(n, i + 1, j + 2, k - 1, dp) / 8); ans += (f(n, i + 2, j + 1, k - 1, dp) / 8); ans += (f(n, i + 2, j - 1, k - 1, dp) / 8); ans += (f(n, i + 1, j - 2, k - 1, dp) / 8); ans += (f(n, i - 1, j - 2, k - 1, dp) / 8); ans += (f(n, i - 2, j - 1, k - 1, dp) / 8); } dp[i][j][k] = ans; return ans; } } ``` ] === #link("https://leetcode.cn/problems/paths-in-matrix-whose-sum-is-divisible-by-k/")[题目4: 矩阵䞭和胜被 K 敎陀的路埄] 给䜠䞀䞪䞋标从 0 匀始的 `m x n` 敎数矩阵 `grid` 和䞀䞪敎数 k 。䜠从起点 `(0, 0)` 出发每䞀步只胜埀 例 或者埀 右 䜠想芁到蟟终点 `(m - 1, n - 1)` 。 请䜠返回路埄和胜被 `k` 敎陀的路埄数目由于答案可胜埈倧返回答案对 `10^9 + 7` 取䜙 的结果。 #example("Example")[ - 蟓入 ``` grid = [ [5,2,4], [3,0,5], [0,7,2] ] k = 3 ``` - 蟓出2 - 解释有䞀条路埄满足路埄䞊元玠的和胜被 `k` 敎陀。 - 第䞀条路埄和䞺 5 + 2 + 4 + 5 + 2 = 18 胜被 3 敎陀。 - 第二条路埄和䞺 5 + 3 + 0 + 5 + 2 = 15 胜被 3 敎陀。 ] #example("Example")[ - 蟓入`grid = [[0,0]]`, `k = 5` - 蟓出`1` - 解释红色标泚的路埄和䞺 0 + 0 = 0 胜被 5 敎陀。 ] #example("Example")[ - 蟓入`grid = [[7,3,4,9],[2,3,6,2],[2,3,7,0]]`, `k = 1` - 蟓出`10` - 解释每䞪数字郜胜被 1 敎陀所以每䞀条路埄的和郜胜被 `k` 敎陀。 ] #tip("Tip")[ - `m == grid.length` - `n == grid[i].length` - `1 <= m, n <= 5 * 10^4` - `1 <= m * n <= 5 * 10^4` - `0 <= grid[i][j] <= 100` - `1 <= k <= 50` ] ==== 解答 `(k + r - (grid[x][y] % k)) % k`解析 来到`(x, y)`䜍眮圓前䜍眮加䞊剩䞋的芁凑出䜙数r。 #example("Example")[ - `k=7`,`r=3`:圓前加䞊剩䞋的芁凑出䜙数`3` - 圓`grid[x][y]%k = 2<3`,剩䞋的芁䜙`1` - 圓`grid[x][y]%k = 4>3`,剩䞋的芁䜙`7+3-4=6` ] #code(caption: [K 敎陀的路埄 - 解答])[ ```java public class Code04_PathsDivisibleByK { public static int MOD = 1000000007; public static int numberOfPaths1(int[][] grid, int k) { return f1(grid, k, 0, 0, 0); } // 从(i,j)出发最终䞀定芁走到右䞋角(n-1,m-1)有倚少条路埄环加和%k是r public static int f1(int[][] grid, int k, int x, int y, int r){ int n = grid.length; int m = grid[0].length; if (x==n-1 && y==m-1) { return grid[x][y]%k==r?1:0; } int ans = 0; int need = (k+r-(grid[x][y]%k))%k; int p1=0, p2=0; // 向䞋走 if(x+1<n){ p1 = f1(grid, k, x+1, y, need); } // 向右走 if(y+1<n){ p2 = f1(grid, k, x+1, y, need); } ans = (p1+p2)%MOD; return ans; } public static int numberOfPaths2(int[][] grid, int k) { int n = grid.length; int m = grid[0].length; int[][][] dp = new int[k][n][m]; for (int r = 0; r < k; r++) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[r][i][j] = -1; } } } return f2(dp, grid, k, 0, 0, 0); } // 从(i,j)出发最终䞀定芁走到右䞋角(n-1,m-1)有倚少条路埄环加和%k是r public static int f2(int[][][] dp, int[][] grid, int k, int x, int y, int r){ int n = grid.length; int m = grid[0].length; if(dp[r][x][y]!=-1){ return dp[r][x][y]; } if (x==n-1 && y==m-1) { return grid[x][y]%k==r?1:0; } int need = (k+r-grid[x][y]%k)%k; int p1=0, p2=0; // 向䞋走 if(x+1<n){ p1 = f2(dp, grid, k, x+1, y, need); } // 向右走 if(y+1<m){ p2 = f2(dp, grid, k, x, y+1, need); } dp[r][x][y] = (p1+p2)%MOD; return dp[r][x][y]; } public static int numberOfPaths3(int[][] grid, int k) { int n = grid.length; int m = grid[0].length; // 从(i,j)出发最终䞀定芁走到右䞋角(n-1,m-1)有倚少条路埄环加和%k是r int[][][] dp = new int[n][m][k]; dp[n-1][m-1][grid[n-1][m-1]%k] = 1; // 最后䞀列从䞋到䞊䟝赖 for (int i = n-2; i >= 0; i--) { for (int r = 0; r < k; r++) { int need = (k+r-grid[i][m-1]%k)%k; dp[i][m-1][r] = dp[i+1][m-1][need]; } } // 最后䞀行从右到巊䟝赖 for (int j = m-2; j >= 0; j--) { for (int r = 0; r < k; r++) { int need = (k+r-grid[n-1][j]%k)%k; dp[n-1][j][r] = dp[n-1][j+1][need]; } } for (int i = n-2; i >= 0; i--) { for (int j = m-2; j >= 0; j--) { for (int r = 0; r < k; r++) { int need = (k+r-grid[i][j]%k)%k; // 䟝赖右蟹 int p1 = dp[i][j+1][need]; // 䟝赖䞋蟹 int p2 = dp[i+1][j][need]; dp[i][j][r] = (p1+p2)%MOD; } } } return dp[0][0][0]; } } ``` ] #tip("Tip")[ 衚䟝赖可以看成䞀䞪二绎坐标每䞪坐标栌子里面有䞪k层的柜子。 ] === #link("https://leetcode.cn/problems/scramble-string/")[题目5: 扰乱字笊䞲] 䜿甚䞋面描述的算法可以扰乱字笊䞲 `s` 埗到字笊䞲 `t`  + 劂果字笊䞲的长床䞺 `1` 算法停止 + 劂果字笊䞲的长床 `> 1` 执行䞋述步骀 + 圚䞀䞪随机䞋标倄将字笊䞲分割成䞀䞪非空的子字笊䞲。即劂果已知字笊䞲 `s` 则可以将其分成䞀䞪子字笊䞲 `x` 和 `y` 䞔满足 `s = x + y` 。 + 随机 决定是芁「亀换䞀䞪子字笊䞲」还是芁「保持这䞀䞪子字笊䞲的顺序䞍变」。即圚执行这䞀步骀之后`s` 可胜是 `s = x + y` 或者 `s = y + x` 。 + 圚 `x` 和 `y` 这䞀䞪子字笊䞲䞊继续从步骀 1 匀始递園执行歀算法。 给䜠䞀䞪 长床盞等 的字笊䞲 `s1` 和 `s2`刀断 `s2` 是吊是 `s1` 的扰乱字笊䞲。劂果是返回 `true` 吊则返回 `false` 。 #example("Example")[ - 蟓入`s1 = "great"`, `s2 = "rgeat"` - 蟓出`true` - 解释`s1` 䞊可胜发生的䞀种情圢是 ``` "great" --> "gr/eat" // 圚䞀䞪随机䞋标倄分割埗到䞀䞪子字笊䞲 "gr/eat" --> "gr/eat" // 随机决定「保持这䞀䞪子字笊䞲的顺序䞍变」 "gr/eat" --> "g/r / e/at" // 圚子字笊䞲䞊递園执行歀算法。䞀䞪子字笊䞲分别圚随机䞋标倄进行䞀蜮分割 "g/r / e/at" --> "r/g / e/at" // 随机决定第䞀组「亀换䞀䞪子字笊䞲」第二组「保持这䞀䞪子字笊䞲的顺序䞍变」 "r/g / e/at" --> "r/g / e/ a/t" // 继续递園执行歀算法将 "at" 分割埗到 "a/t" "r/g / e/ a/t" --> "r/g / e/ a/t" // 随机决定「保持这䞀䞪子字笊䞲的顺序䞍变」 ``` 算法终止结果字笊䞲和 `s2` 盞同郜是 `"rgeat"` 这是䞀种胜借扰乱 `s1` 埗到 `s2` 的情圢可以讀䞺 `s2` 是 `s1` 的扰乱字笊䞲返回 `true` ] #example("Example")[ - 蟓入`s1 = "abcde"`, `s2 = "caebd"` - 蟓出`false` ] #example("Example")[ - 蟓入`s1 = "a"`, `s2 = "a"` - 蟓出`true` ] #tip("Tip")[ - s1.length == s2.length - 1 <= s1.length <= 30 - s1 和 s2 由小写英文字母组成 ] ==== 解答 劂果䞀䞪字笊䞲字笊种类䞀样对应的数量也䞀样䞀䞪是吊䞀定互䞺扰乱䞲呢 䞍䞀定 #example("Example")[ - s1: `abcd` + `a bcd` + `ab cd` + `abc d` - s2: `cadb` 没法儿 ] #code(caption: [扰乱字笊䞲 - 解答])[ ```java public class Code05_ScrambleString { public static boolean isScramble1(String str1, String str2) { char[] s1 = str1.toCharArray(); char[] s2 = str2.toCharArray(); int n = s1.length; return f1(s1, 0, n - 1, s2, 0, n - 1); } // s1[l1....r1] // s2[l2....r2] // 保证l1....r1侎l2....r2 // 是䞍是扰乱䞲的关系 public static boolean f1(char[] s1, int l1, int r1, char[] s2, int l2, int r2) { if (l1 == r1) { // s1[l1..r1] // s2[l2..r2] return s1[l1] == s2[l2]; } // s1[l1..i][i+1....r1] // s2[l2..j][j+1....r2] // 䞍亀错去讚论扰乱关系 for (int i = l1, j = l2; i < r1; i++, j++) { if (f1(s1, l1, i, s2, l2, j) && f1(s1, i + 1, r1, s2, j + 1, r2)) { return true; } } // 亀错去讚论扰乱关系 // s1[l1..........i][i+1...r1] // s2[l2...j-1][j..........r2] for (int i = l1, j = r2; i < r1; i++, j--) { if (f1(s1, l1, i, s2, j, r2) && f1(s1, i + 1, r1, s2, l2, j - 1)) { return true; } } return false; } // 䟝然暎力尝试只䞍过四䞪可变参数变成了䞉䞪 public static boolean isScramble2(String str1, String str2) { char[] s1 = str1.toCharArray(); char[] s2 = str2.toCharArray(); int n = s1.length; return f2(s1, s2, 0, 0, n); } public static boolean f2(char[] s1, char[] s2, int l1, int l2, int len) { if (len == 1) { return s1[l1] == s2[l2]; } // s1[l1.......] len // s2[l2.......] len // å·Š : k䞪 右: len - k 䞪 for (int k = 1; k < len; k++) { if (f2(s1, s2, l1, l2, k) && f2(s1, s2, l1 + k, l2 + k, len - k)) { return true; } } // 亀错 for (int i = l1 + 1, j = l2 + len - 1, k = 1; k < len; i++, j--, k++) { if (f2(s1, s2, l1, j, k) && f2(s1, s2, i, l2, len - k)) { return true; } } return false; } public static boolean isScramble3(String str1, String str2) { char[] s1 = str1.toCharArray(); char[] s2 = str2.toCharArray(); int n = s1.length; // dp[l1][l2][len] : int 0 -> 没展匀过 // dp[l1][l2][len] : int -1 -> 展匀过返回的结果是false // dp[l1][l2][len] : int 1 -> 展匀过返回的结果是true int[][][] dp = new int[n][n][n + 1]; return f3(s1, s2, 0, 0, n, dp); } public static boolean f3(char[] s1, char[] s2, int l1, int l2, int len, int[][][] dp) { if (len == 1) { return s1[l1] == s2[l2]; } if (dp[l1][l2][len] != 0) { return dp[l1][l2][len] == 1; } boolean ans = false; for (int k = 1; k < len; k++) { if (f3(s1, s2, l1, l2, k, dp) && f3(s1, s2, l1 + k, l2 + k, len - k, dp)) { ans = true; break; } } if (!ans) { for (int i = l1 + 1, j = l2 + len - 1, k = 1; k < len; i++, j--, k++) { if (f3(s1, s2, l1, j, k, dp) && f3(s1, s2, i, l2, len - k, dp)) { ans = true; break; } } } dp[l1][l2][len] = ans ? 1 : -1; return ans; } public static boolean isScramble4(String str1, String str2) { char[] s1 = str1.toCharArray(); char[] s2 = str2.toCharArray(); int n = s1.length; boolean[][][] dp = new boolean[n][n][n + 1]; // 填写len=1层所有的栌子 for (int l1 = 0; l1 < n; l1++) { for (int l2 = 0; l2 < n; l2++) { dp[l1][l2][1] = s1[l1] == s2[l2]; } } for (int len = 2; len <= n; len++) { // 泚意劂䞋的蟹界条件 : l1 <= n - len l2 <= n - len for (int l1 = 0; l1 <= n - len; l1++) { for (int l2 = 0; l2 <= n - len; l2++) { for (int k = 1; k < len; k++) { if (dp[l1][l2][k] && dp[l1 + k][l2 + k][len - k]) { dp[l1][l2][len] = true; break; } } if (!dp[l1][l2][len]) { for (int i = l1 + 1, j = l2 + len - 1, k = 1; k < len; i++, j--, k++) { if (dp[l1][j][k] && dp[i][l2][len - k]) { dp[l1][l2][len] = true; break; } } } } } } return dp[0][0][n]; } } ``` ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/attach-p1_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test basics, postscripts. $f_x + t^b + V_1^2 + attach(A, t: alpha, b: beta)$
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/抜象代数/章节/暡、域.typ
typst
#import "../../template.typ": * #show: note.with( title: "抜象代数/代数孊基础", author: "YHTQ", date: none, logo: none, withOutlined: false ) #let chapterThree = [ = æš¡ == 基本抂念 类比线性空闎是域䜜甚于亀换矀暡是环䜜甚于亀换矀 == 䞻理想敎环䞊有限生成暡的分类定理 本节䞭所有的 $R$ 郜是 PID #lemma[][ 讟 $p, q in R$ 是䞍盞䌎的玠元$r, s in NN$则 - 若 $M tilde.eq R$则 $quotient(M, p^r M) tilde.eq quotient(R, (p^r))$ - 若 $M tilde.eq quotient(R, p^s R)$则 $ p^r M = cases( quotient(p^r R, p^s R) space& r <= s, {0} & r > s ) $ - 若 $M tilde.eq quotient(R, q^s R)$则 $ p^r M = M $ ] #proof[ + + + 泚意到圚 PID 䞭$(p^r, q^s) = (1)$。讟 $a p^r + b q^s = 1$则 $m = a m p^r + b m q^s in (p^r + (q^s)) M = p^r M$ ] = 域 == 基本抂念 域的定义前面已经给出了。对于域的考察我们从最简单的域匀始即特埁䞺玠数的玠域再从它们出发构造新的域。 #definition[特埁][ 对域 $F$若存圚正敎数 $n$ 䜿埗: $ n dot 1 = 0 $ 则称满足芁求的最小敎数 $n$ 䞺域 $F$ 的特埁记䜜 $"char"(F)$吊则称 $F$ 的特埁䞺 $0$。 ] #corollary[][ 讟 $"char"(F) = n$则 $forall x in F$有 $n dot x = 0$ ] #theorem[][ 域的特埁䞀定是玠数 ] #proof[ $(n m) dot 1 = 0 <=> (n dot 1)(m dot 1) = 0 <=> n dot 1 = 0 or m dot 1 = 0$衚明域的特埁䞀定䞍可分解进而䞀定是玠数。 ] #corollary[][ 所有特埁䞺 $p$ 的域郜包含 $ZZ_p$特埁䞺 $0$ 的域郜包含 $QQ$ ] #lemma[][ 域闎的同态䞀定是单射 ] #proof[ 星然域同态䞀定是环同态进而 $ker(phi)$ 是 $F$ 的理想由于 $F$ 是域$ker(phi)$ 只胜是 $F$ 或者 $\{0\}$而 $phi$ 䞍可胜是 $0$ 映射因歀 $ker(phi) = \{0\}$即 $phi$ 是单射。 ] #remark[][ 这䞪匕理给出若我们有䞀䞪域同态 $F -> K$则 $F$ 可以看䜜 $K$ 的子域进而我们可以将 $K$ 看䜜 $F$ 的扩匠域这就匕出了域扩匠的抂念。 ] == 域扩匠 从抂念䞊扩匠关系基本就是子域关系只是我们圚研究域时埀埀从小至倧因歀有了反向的扩匠关系 #definition[域扩匠][ 讟 $F$ 是 $K$ 的子域则称 $K$ 是 $F$ 的䞀䞪域扩匠并称 $F$ 是䞀䞪基域。若 $F subset E subset K$ 郜是域则称 $E$ 是䞭闎域。 歀时$K$ 是䞀䞪 $F$ 向量空闎进而称域扩匠 $quotient(K, F)$ 的次数 $ [K : F] := dim_F K $ ] #theorem[][ 若 $F subset E subset K$则 $ [K : F] = [K : E] [E : F] $ ] #proof[ 讟 $m = [K : E], n = [E : F] $\ 扟 $alpha_1, alpha_2, ..., alpha_m$ 是 $K$ 圚 $E$ 䞊的䞀组基$beta_1, beta_2, ..., beta_n$ 是 $E$ 圚 $F$ 䞊的䞀组基\ 则对任意 $k in K$存圚 $lambda_i in E$䜿埗 $ k = sum_(i = 1)^m lambda_i beta_i $ 而对 $lambda_i in E$存圚 $mu_(i j) in K$䜿埗 $ lambda_i = sum_(j = 1)^n = mu_(i j) alpha_j $ 进而 $ k = sum_(i = 1)^m sum_(j = 1)^n mu_(i j) alpha_j beta_i $ 衚明 $alpha_i, beta_j$ 构成䞀组生成元只需证明它们线性无关事实䞊 $ 0 = sum_(i = 1)^m sum_(j = 1)^n mu_(i j) alpha_j beta_i => sum_(i = 1)^m (sum_(j = 1)^n mu_(i j) alpha_j) beta_i = 0 \ => sum_(j = 1)^n mu_(i j) alpha_j = 0, space forall i \ => mu_(i j) = 0, space forall i, j $ ] #example[][ 讟 $F$ 是域则 $F[x]$ 是䞻理想敎环。取其䞀䞪䞍可纊元 $p(x)$则 $quotient(F[x], (p(x)))$ 是域它圓然 $F$ 的䞀䞪域扩匠䞔 $[quotient(F[x], (p(x))) : F] = deg(p(x))$\ 曎重芁的是以䞋匕理 #lemma[][ 什 $theta = x + (p) in quotient(F[x], (p(x)))$ 则它将成䞺方皋 $ p(z) = 0, z in quotient(F[x], (p(x))) $ 的根 ] #proof[ 讟 $p(x) = sum_i a^i x^i$则 $ p(theta) = sum_i a^i (x + (p))^i = sum_i a^i x^i + (p) = p(x) + (p) = 0 $ ] 衚明我们奜像真的是添加了䞀䞪根。 ] #remark[][ $quotient(RR, (x^2 + 1))$ 按照䞊面的介绍成䞺了 $RR$ 的䞀䞪扩匠域它就是 $CC$。䜆事实䞊 $CC$ 䞭有倚项匏 $x^2 + 1$ 的䞀䞪而䞍是䞀䞪根 ] #definition[][ 讟 $F subset K$ 郜是域$a_i in K$则记 $ F(a_1, a_2, ..., a_n) $ 䞺包含 $F, a_i$ 的 $K$ 䞭的最小子域称䞺 $F$ 和 $a_i$ 的生成域。\ 由有限䞪元玠生成的域称䞺有限生成\ 特别的单䞪元玠生成的域成䞺单扩匠 ] #example[][ - $QQ(sqrt(2), sqrt(3)) = QQ(sqrt(2) + sqrt(3))$ ] #theorem[][ 讟 $K = F(alpha)$则以䞋䞀者有䞔只有䞀䞪成立 - $1, alpha, alpha^2, ..., alpha^n, ...$ 圚 $F$ 䞊党郚线性无关进而 $F(alpha) tilde.eq "Frac"(F[x])$歀时称 $alpha$ 圚 $F$ 䞊超越 - $1, alpha, alpha^2, ..., alpha^n, ...$ 圚 $F$ 䞊线性盞关进而䜿埗 $f(alpha) = 0$ 的 $F$ 䞊倚项匏构成䞀䞪理想进而是䞻理想。取其唯䞀生成元 $m(x)$则称 $m(x)$ 䞺 $alpha$ 圚 $F$ 䞊的极小倚项匏它䞀定䞍可纊记䜜 $m_alpha(x)$并有 $ F(alpha) tilde.eq quotient(F[x], (m_alpha (x))) $ 歀时称 $alpha$ 圚 $F$ 䞊代数algebraic ] #proof[ - 对于情况䞀构造环同态 $ funcDef(phi, F[x], K, f(x), f(alpha)) $ 由题讟$phi$ 是单射进而它可以延拓到 $phi': Frac(F[x]) -> K$构成域䞊的同态圓然是单射因歀 $ Frac(F[x]) tilde.eq im(phi') = K $ - 对于情况二只需证明 $m_alpha (x)$ 确实䞍可纊。事实䞊 $ funcDef(phi, F[x], K, f(x), f(alpha)) $ 给出环䞊的满同态进而 $ quotient(F[x], ker(phi)) tilde.eq im(phi) = K $ 而 $K$ 是域同时 $ker(phi) = (m_alpha (x))$衚明 $m_alpha (x)$ 确实䞍可纊。 ] #definition[][ 讟 $K = F(alpha_1, alpha_2, ..., alpha_i, ...)$若每䞀䞪元玠郜是代数的则称 $quotient(K, F)$ 是代数的吊则称䞺超越的 ] #proposition[][ 以䞋䞀者等价 - $[K : F]$ 有限 - $quotient(K, F)$ 是有限生成䞔代数的 ] #proof[ - $1 => 2$ 是容易的同时我们有 $ deg(m_alpha (x)) = [F(alpha), F] | [K, F] $ - 及䞀䟧略星倍杂 #lemma[][ 讟 $F subset E subset K$$alpha in K$$alpha$ 圚 $E, F$ 䞊的极小倚项匏分别䞺 $m_E (x), m_F (x)$则 $ m_(F) (x) = 0 in E => m_(E) (x) | m_(F) (x) in E[x] $ ] #corollary[][ $[E(alpha) : E] <= [F(alpha): F]$ ] #definition[][ 讟 $F subset E_i subset K$则记 $ E_1 E_2 ... E_n $ 䞺包含 $E_i$ 的最小的域称䞺 $E_i$ 的倍合 ] #lemma[][ 讟 $[E_i, F]$ 有限则 $ [E_1 E_2 : F] <= [E_1 : F] [E_2 : F] $ ] #proof[ 讟 $E_1 = F(alpha_1, alpha_2, ..., alpha_n)$则由䞊面的匕理 $ [E_2(alpha_1) : E_2] <= [F(alpha_1) : F]\ [E_2(alpha_1, alpha_2) : E_2(alpha_1)] <= [F(alpha_1, alpha_2) : F(alpha_1)]\ $ 由于域扩匠的次数可乘巊右䟧党郚乘起来埗到 $ [E_2(alpha_1, alpha_2, ..., alpha_n) : E_2] <= [F(alpha_1, alpha_2, ..., alpha_n) : F]\ <=> [E_1 E_2 : E_2] <= [E_1 : F] \ => [E_1 E_2 : F] = [E_1 E_2 : E_2] [E_2 : F] <= [E_1 : F] [E_2 : F] $ ] 由这些匕理讟 $K = F(alpha_1, alpha_2, ..., alpha_n)$则 $ [K : F] = [F(alpha_1) F(alpha_2) ... F(alpha_n) : F]<= product [F(alpha_i) : F] $ 证毕 ] #corollary[代数闭包][ 讟 $alpha, beta in K$ 圚 $F$ 䞭代数则 $ alpha plus.minus beta, alpha beta, alpha / beta $ 郜圚 $F(alpha, beta)$ 之䞭由䞊面的定理这是有限扩匠进而这些元玠郜圚 $F$ 䞭代数从而 $K$ 䞭所有圚 $F$ 䞭代数的元玠构成 $K$ 的䞀䞪子域称䞺 $K$ 圚 $F$ 䞊的代数闭包 ] #theorem[][ 若 $quotient(K, E)$ 侎 $quotient(E, F)$ 郜是代数的则 $quotient(K, F)$ 也是代数的 ] == 分裂域 #definition[分裂域][ 给定域 $F$ 以及其䞊的倚项匏 $f in F[x]$这里并䞍芁求䞍可纊。䞀䞪域扩匠 $quotient(K, F)$ 称䞺 $f(x)$ 的分裂域劂果 - $f(x)$ 圚 $K[x]$ 䞭可以写成䞀次倚项匏的乘积或者诎恰有 $deg f$ 䞪根 $alpha_i$ - $K = F[alpha_1, alpha_2, ..., alpha_(deg f)]$ ] #remark[][ 讟 $F <= E <= K, f(x) in F[x]$$f(x)$ 圚 $F$ 䞊的分裂域是 $K$则它圚 $E$ 䞊的分裂域圓然也是 $K$。 ]<cor1> #theorem[][ 域扩匠䞀定是有限扩匠。曎进䞀步$f(x) in F[x]$分裂域䞺 $K$则 $ [K : F] <= n! $ ] #proof[ 对 $f(x)$ 的次数園纳假讟 $deg(f) < n$ 的情圢郜已成立。\ 讟 $f(x) = p(x)k(x)$其䞭 $p(x)$ 䞍可纊。什 $ E = quotient(F[x], (p(x))) $ 圚 $E$ 䞭$p(x) in E[x]$ 圓然有根因歀 $f(x)$ 也有根讟 $ f(x) = (x - theta)g(x) $ 由園纳法存圚分裂域 $ quotient(K, E) $ 满足 $ [K : E] <= (n-1)! $ 从而圓然 $quotient(K, F)$ 是 $f(x)$ 的分裂域䞔 $ [K : F] <= n! $ ] #example[分圆域][ 域 $QQ$ 䞊倚项匏 $x^n - 1$ 的分裂域称䞺 $n$ 次分圆域。 ] #lemma[][ 讟 $eta$ 是域同构$p(x)$ 是䞍可纊倚项匏则 $eta(p(x))$ 圓然也是䞍可纊倚项匏进䞀步 $ quotient(F[x], (q(x))) tilde.eq quotient(eta(F[x]), (eta(p(x)))) $ ] #example[][ - $a + b sqrt(2) -> a - b sqrt(2)$ 是 $Q[sqrt(2)]$ 的自同构 $Q((sqrt(5+sqrt(2)))) tilde.eq quotient(QQ(sqrt(2)), (x^2 - 5 -sqrt(2))) tilde.eq quotient(QQ(sqrt(2)), (x^2 - 5 +sqrt(2))) tilde.eq Q((sqrt(5-sqrt(2))))$ ] #lemma[][ 讟 $eta$ 是域同构$f(x) in F[x], f'(x) = eta(f(x))$。讟 $E, E'$ 分别是 $f(x), f'(x)$ 圚各自域䞊的分裂域那么存圚䞍䞀定唯䞀同构 $sigma$ 䜿埗䞀䞪分裂域同构 ] #proof[ 我们的思路是给出䞀䞪标准的分裂域构造再证明它们的䞀臎性。\ 我们证明加区的呜题 #lemma[][ 讟 $eta:F -> F'$ 是同构$E, E'$ 是 $E, F'$ 的䞀䞪扩域䜿埗 $E$ 是 $f(x) in F[x] $某些根生成$f'(x) = eta(f(x)) in F'[x]$ 圚其䞭分裂则存圚同态 $sigma'$ 将 $E$ 嵌入 $E'$ ] #proof[ ] ] #theorem[][ 讟 $F <= E, E' <= K$, $E, E'$ 郜是 $f(x) in F[x]$ 圚 $F$ 䞊的分裂域则 $ E = E' $ ] #corollary[][ 讟 $F <= E <= K$$sigma$ 是 $K$ 䞊的自同构$E$ 是某䞪分裂域䞔 $sigma|_F = id$则 $ sigma(E) = E $ ]<lemma1> == 正规扩匠 #definition[正规扩匠][ 䞀䞪代数域扩匠 $quotient(K, F)$ 称䞺正规扩匠劂果 - 对 $F[x]$ 䞊所有䞍可纊倚项匏 $p(x)$只芁它圚 $K$ 䞭有䞀䞪根䟿有所有等于次数的根 ] 这䞪条件看䌌埈区䜆事实䞊并䞍然䞋面的定理䟿诎明了这点 #theorem[][ 䞀䞪有限域扩匠 $quotient(K, F)$ 是正规扩匠圓䞔仅圓它是某䞪倚项匏 $f(x)$ 的分裂域 ] #proof[ - 讟 $K = F(alpha_i)$ 是正规扩匠星然它就是 $f(x) = product_i m_(alpha_i) (x)$ 的分裂域 - 及䞀䟧是䞍平凡的。讟 $K$ 是 $f(x)$ 的分裂域$p(x)$ 是某䞪䞍可纊倚项匏它圚 $K$ 䞭有根 $alpha$。讟 $L$ 是 $p(x)$ 圚 $K$ 䞭的分裂域埀证 $ L = K $ - 銖先$K <= L$ 是星然的。 - 取 $beta in L$ 是及䞀䞪 $p(x)$ 圚 $L$ 䞭的根若 $p$ 是䞀次倚项匏结论是星然的我们发现 $L$ 将同时成䞺 $F(alpha), F(beta)$ 的分裂域因歀 $ F(alpha) tilde.eq F(beta) $ 并䞔诱富出 $L$ 䞊非平凡自同构 $eta$, $eta(F(alpha)) = eta(F(beta)). eta|_F = id$。䜆由 @lemma1这意味着 $ eta(K) = K $ 而 $alpha in K => beta in K$进而 $K$ 拥有 $p(x)$ 圚 $L$ 䞭所有的根从而结论成立 ] #corollary[][ 讟 $quotient(K, F)$ 是有限正规扩匠$F <= E <= K$则 $quotient(K, E)$ 也是正规扩匠$quotient(F, E)$ 未必 ] #proof[ 回忆 @cor1结论是容易的 ] #definition[正规闭包][ ç§° $quotient(L, K)$ 是 $quotient(K, F)$ 的正规闭包劂果 - $quotient(L, F)$ 是正规扩匠 - 若 $quotient(L', F)$ 也是正规扩匠$L' subset L$则 $L = L'$ ] #lemma[][ 有限域扩匠 $quotient(K, F)$ 的正规闭包圚同构意义䞋存圚䞔唯䞀具䜓的同构可胜倚种 ] #proof[ - 存圚性讟 $F = F(alpha_i)$则取 $product_i m_(alpha_i) (x)$ 的䞀䞪分裂域 $L$容易验证 $quotient(L, K)$ 就是正规闭包 - 唯䞀性讟 $quotient(L', K)$ 是正规闭包仍取䞊面的 $f(x)$并取 $L$ 就是它的分裂域。星然 $f(x)$ 圚 $L'$ 䞭分裂。由之前的定理存圚 $L -> L'$ 的嵌入。由定义的第二条䞍应有比 $L'$ 曎小的正规扩匠因歀$L' tilde.eq L$ ] == 可分扩匠 #definition[完党域][ 称䞀䞪特埁 $p$ 的有限域 $F$ 䞺完党域劂果映射 $ funcDef(sigma, F, F, x, x^p) $ 是同构。换蚀之所有元玠郜可以匀 $p$ 次根号 ] #definition[圢匏富数][ 称域䞊倚项匏 $f(x)$ 的圢匏富数䞺 $f'(x)$劂同利甚富数法则计算其富数䞀样。圢匏富数满足富数计算的所有性莚。 ] #proposition[重根刀别法][ 域䞊倚项匏 $f(x)$ 圚其分裂域䞭有重根圓䞔仅圓 $f(x), f'(x)$ 䞍互玠 ]<重根刀别法> #proof[ 利甚域䞊倚项匏环是䞻理想敎环$(f(x), f'(x)) = (d(x)) => d(x) | f(x), d(x) | f'(x)$ ] #lemma[][ 完党域的代数扩匠还是完党域 ] #proof[ 讟 $char F = p$。对任意 $alpha in K$将有 $ alpha^(1/p) in E = F(alpha) $ 从而回到了有限扩匠情圢。\ 我们有 $ [E : sigma(E)][sigma[E] : sigma[F]] = [E : F][F : sigma(F)] $ 而星然 $[sigma[E] : sigma[F]] = [E : F]$因歀 $ [E : sigma(E)] = [F : sigma(F)] $ ] #corollary[][ $quotient(K, F)$ 是有限扩匠$K$ 完党 $=> K$ 完党。䜆圚代数扩匠䞋这䞪事实䞍成立。 ] #definition[][ 若 $f(x) in F[x]$ 是䞍可纊倚项匏圚其分裂域䞭 - 若 $f(x)$ 有重根则称 $f$ 是䞍可分的 - 若 $f(x)$ 无重根则称 $f$ 是可分的 ] #proposition[][ 䞍可纊倚项匏 $f$ 䞍可分圓䞔仅圓 $f'(x) = 0$ ] #proof[ 结合 $f$ 䞍可纊和之前的重根刀别法 @重根刀别法结论是容易的 ] #corollary[][ - 圚特埁 $0$ 的域䞭所有䞍可纊倚项匏郜是可分的 - 圚特埁 $p$ 的域䞭所有䞍可分倚项匏郜圢劂 $g(x^p)$䞔完党域䞭没有䞍可分倚项匏 ] #proof[ (1) 是星然的对于 (2)什 $ D(sum_i a_i x^i) = sum_i i a_i x^(i-1) = 0 => i a_i = 0 => i = 0 or a_i = 0 $ 因歀对于所有䞍是 $p$ 的倍数则 $i != 0$进而 $a_i = 0$ 同时讟 $F$ 是完党域可讟 $ sum_i a_i x^(p i) = sum_i b_i^p x^(p i) $ 泚意到圚特埁 $p$ 的域䞭䞀定有 $ sum_i b_i^p x^(p i) = (sum_i b_i x^i)^p $ 这䞎倚项匏䞍可纊矛盟 ] #corollary[][ 圚特埁 $p$ 的域䞭所有䞍可纊倚项匏郜圢劂 $ g(x^(p^e)) $ å…¶äž­ $g(x)$ 已经是可分䞍可纊倚项匏。同时圚 $g$ 的分裂域䞭$f$ 恰有 $deg(g)$ 䞪䞍同的根。 ]<零点䞪数> #proof[ 将䞊面的掚论进䞀步进行若已经可分就停止若䞍可分就继续进行最终由于次数有限䞀定可以埗到类䌌的圢匏。 对于后者泚意到 $ g(x) = product_(i=1)^n (x - alpha_i)\ f(x) == product_(i=1)^n (x^(p^e) - alpha_i) = product_(i=1)^n (x - alpha_i^(1/(p^e)))^(p^e) $ 从而结论成立 ] #definition[][ 圚代数扩匠 $quotient(K, F)$ 䞭 - 若 $alpha in K$ 圚 $F$ 䞭最小倚项匏可分/䞍可分则称 $alpha$ 可分/䞍可分 - 若所有元玠郜可分则称域扩匠可分吊则成䞺䞍可分 ] #proposition[][ 给定域扩匠 $quotient(K, E), quotient(E, F)$若 $alpha$ 圚 $quotient(K, F)$ 䞭可分则圚 $quotient(K, E)$ 可分 ] #proof[ 由于䞀䞪域扩匠䞭最小倚项匏有敎陀关系结论是容易的 ] #theorem[][ - 讟 $alpha$ 圚 $F$ 可分则 $F(alpha)$ 是可分扩匠 - 讟代数扩匠 $quotient(K, E), quotient(E, F)$ 可分则扩匠 $quotient(K, F)$ 也可分 ]<可分扩匠定理> #proof[ 这䞪定理是埈䞍平凡的先论述䞀点想法。我们可以扟到䞀䞪域扩匠的正规闭包 $M$考虑所有同态 $phi: K -> M$ 侔 $phi_F = id$ 构成的集合 $Hom_F (K, M)$这䞪集合有着重芁的功胜。 #lemma[][ 讟 $K = F(alpha)$, $alpha$ 的最小倚项匏䞺 $m(x) = g(x^(p^e))$其䞭 $g(x)$ 是可分䞍可纊倚项匏则 $ |Hom_F (K, M)| = deg g(x) <= [F(alpha) : F] $ 取等圓䞔仅圓 $alpha$ 可分 ] #proof[ 星然这样的同态由 $alpha$ 的像唯䞀确定。同时由于 $phi(m(x)) = m(x)$因歀 $phi(alpha)$ 䞀定也是 $m(x)$ 的根。@零点䞪数 给出了这样零点的䞪数恰䞺 $deg g(x)$。同时我们有 $ [F(alpha) : F] = deg(m(x)) >= deg(g(x)) $ 从而取等圓䞔仅圓 $m(x) = g(x)$也即 $m(x)$ 可分等价于 $alpha$ 可分 ] #corollary[][ 讟有限域扩匠 $quotient(K, F)$ 䞎其正规闭包 $quotient(M, F)$则有 $ |Hom_F (K, M)| <= [K : F] $ 䞔取等圓䞔仅圓䞀者等价 + $K = F(alpha_1, alpha_2, ..., alpha_n)$ 䞔每䞪元玠郜可分 + $quotient(K, F)$ 可分 ]<lemma-1> #proof[ 泚意到 $ |Hom_F (F(alpha_1), M)| <= [F(alpha_1) : F]\ |Hom_(F(alpha_1)) (F (alpha_1, alpha_2), M)| <= [F(alpha_1, alpha_2) : F(alpha_1)] $ 䞍隟验证䞀蟹郜满足乘性因歀 $ |Hom_F (F (alpha_1, alpha_2), M)| <= [F(alpha_1, alpha_2) : F] $ 以歀类掚即埗等价条件 1。对于 2泚意到任䜕䞍可分元玠郜䞀定䌚砎坏等于号因歀结论也是对的。 ] 至歀我们证明了 @可分扩匠定理 的第䞀郚分。 再考虑第二郚分劂果扩匠是有限扩匠结论已经容易了而我们对于可分扩匠的芁求是每䞪元玠郜可分每䞪元玠所垊有的信息量是有限的。曎䞥栌的诎讟 $alpha in K$取它圚 $E$ 䞭的最小倚项匏 $m_E (x)$。\ $m_E (x)$ 的系数星然只有有限䞪考虑这些系数构成的 $F$ 的有限扩匠 $ E' = F(a_1, a_2, ..., a_n)\ K' = F(a_1, a_2, ..., a_n, alpha) $ 可以证明 $F -> E', E' -> K'$ 郜是可分扩匠特别的$alpha$ 可分 ] #theorem[有限域的分类][ - 讟 $F$ 是特埁 $p$ 的域则 $ |F| = p^([F : ZZ_p]) $ - 给定有限域的元玠䞪数 $n$则圚同构意义䞋存圚唯䞀的域满足 $|F| = n$䞀䞪兞范是 $x^(p^n) - x in ZZ_p [x]$ 的分裂域 ] #proof[ 1 是星然的。讟 $|F| = p^n$则乘法矀 $F^times$ 的阶数䞺 $p^n - 1$从而 $ a^(p^n-1) = 1 <=> x^(p^n) - x = 0 space forall a in F $ 同时 $0$ 也是 $x^(p^n) - x = 0$ 的根因歀 $F$ 䞭所有元玠恰䞺倚项匏 $x^(p^n) - x = 0$ 的根因歀 $F$ 就是它的分裂域。\ 反之由于 $D(x^(p^n) - x) != 0$故圚它的分裂域它没有重根进而它的分裂域至少有 $p^n$ 䞪元玠。\ ] #theorem[Primitive element theorem, 本原元定理][ - 䞀䞪有限可分扩匠䞀定可以由唯䞀元玠生成 - 讟 $alpha, beta$ 代数䞔可分则䞀定存圚 $eta$ 䜿埗 $F(alpha, beta) = F(beta)$ ]<PET> #proof[ 只证明 2从而 1 是星然的 考虑 $eta = alpha + c beta$。事实䞊可以感觉到对于绝倧倚数 $c$ 郜成立只需芁躲匀那些运气极差的郚分。 - 对于有限域星然有限域郜是完党域 #lemma[][ 讟 $|F| = p^n$则 $F$ 䞭存圚 $p^m$ 阶子域圓䞔仅圓 $m | n$䞔这样的子域是䞀䞪分裂域进而唯䞀 ] #proof[ 由于扩域构成线性空闎必芁性是星然。反之泚意到 $ x^(p^n) - x = (x^(p^m) - x)(x^(p^n-1)-1)/(x^(p^m-1)-1) := f(x) g(x) $ 从而 $f(x)$ 的分裂域 $F_(p^m)$ 圓然可以进䞀步分裂䞺 $f(x)g(x)$ 的分裂域 $F$从而结论成立。 ] - 假讟 $F$ 是无穷域 讟 $f, g$ 是 $alpha, beta$ 的极小倚项匏并取 $E$ 䞺 $f g$ 的分裂域域䞭 $f, g$ 的䞍同的根分别䞺 $ alpha_1 = alpha, alpha_2, ..., alpha_n\ beta_1 = beta, beta_2, ..., beta_m $ 我们垌望对所有的 $i, k$ 和䞍等于 $1$ 的 $j$郜有 $ alpha_i + c beta_1 eq.not alpha_k + c beta_j $ 这只排陀了有限倚䞪 $c$我们还有无穷倚䞪 $c$可甚我们只需证明这些 $c$ 郜是奜的也即 $ F(alpha + c beta := eta) = F(alpha, beta) $ 只需芁让 $alpha, beta$ 萜圚 $F(eta)$ 䞭考虑 $ f_1(x) = f(eta - c x)\ $ 由前面的条件我们可以知道圚 $E$ äž­ $f_1, g$ 有唯䞀的公共根 $beta_1$吊则 $alpha_1 + c beta_1 = alpha_k + c beta_j$ 同时由可分性知 $g(x)$ 圚 $E$ 䞭䞍䌚有重根进而 $ (f_1, g) = (x - beta_1) $ 然而最倧公因匏圚域扩匠䞋保持䞍变因歀 $x - beta_1$ 也是它们圚 $F(eta)$ 䞭的最倧公因匏进而 $beta_1 in F(eta)$因歀也星有 $alpha_1 in F(eta)$证毕 ] #remark[][ 对于䞍可分扩匠未必胜保证猩减到䞀䞪。事实䞊考虑 $ F = F_p (x, y)\ K = F_p (x^(1/p), y^(1/p)) $ 则 $[K : F] = p^2$而 $K$ 䞭任䜕元玠的最小倚项匏的次数䞀定䞍超过 $p$进而䞍可胜由䞀䞪元玠生成。 ] @lemma-1 是埈重芁的圚之后的䌜眗华理论䞭同样起着重芁䜜甚 == 䌜眗华理论 #definition[䌜眗华扩匠][ 称䞀䞪域扩匠是䌜眗华扩匠劂果扩匠是可分正规的 ] #definition[䌜眗华矀][ 给定䌜眗华扩匠 $quotient(K, F)$称所有 $K$ 的满足 $phi|_(F) = id$ 的自同构 $phi$ 构成的矀䞺䌜眗华矀记䜜 $Gal(quotient(K, F))$ ] #proposition[][ $|Gal(quotient(K, F))| = [K : F]$ ] #proof[ 这是 @lemma-1 的自然结果 ] #example[双二次扩匠][ $QQ -> QQ(sqrt(2), sqrt(3))$其䌜眗华矀有四䞪元玠 $ sqrt(2) -> plus.minus sqrt(2)\ sqrt(3) -> plus.minus sqrt(3) $ 这䞪矀圓然就是四元矀 $ZZ_2 times ZZ_2$\ 同时䞉䞪非平凡元玠分别成䞺 $QQ(sqrt(2)), QQ(sqrt(3)), QQ(sqrt(6))$ 的皳定子这䞉䞪域郜是域扩匠的䞭闎子域。 ] 从䞊面的䟋子可以猜到䌜眗华矀的子矀可胜是某䞪子域的皳定子以䞋的定理诎明了这䞪埈䞍平凡的事实。 #theorem[䞻定理/䌜眗华定理][ 讟 $quotient(K, F)$ 是有限䌜眗华扩匠$G$ 是其䌜眗华矀。则 + 圚以䞋集合之闎存圚䞀䞀对应 $ {E | K <= E <= F} &<-> {H | H <= G}\ E &-> Gal(quotient(K, E)) = {phi in Isom(K) | phi|_E = id} $ 埀埀将 $H <= G$ 的像记䜜 $K^(H)$ + 䞊面的䞀䞀对应䞭矀越小域越倧也即 $ H_1 <= H_2 <=> K^(H_1) >= K^(H_2) $ + $|H| = [K : K^H], [G:H]=[K^H:F]$ + 讟 $E = K^H$则任取 $g in G$有 $ g(E) = K^(conjugateRight(g, H)) $ + $H norS G$ 圓䞔仅圓 $quotient(K^H, F)$ 是正规扩匠同时我们有 $ quotient(G, H) tilde.eq Gal(quotient(K^H, F)) $ + 讟 $E_1, E_2$ 分别对应 $H_1, H_2$则 $ E_1 E_2 <-> H_1 sect H_2\ E_1 sect E_2 <-> generatedBy(H_1\, H_2) $ ] #proof[ 先给出第䞀条的证明这是盞对最困隟最䞍平凡的䞀条。\ 由䌜眗华扩匠的芁求我们可以假讟 $K$ 是某䞪可分倚项匏 $f(x) in F[x]$ 的分裂域。\ - 给定 $H <= G$先扟出被 $H$ 䞍变的子域 $E$再证明 $Gal(quotient(K, E)) = H$\ - 銖先圓然有 $H <= Gal(quotient(K, E))$我们只需芁证明䞍䌚倚出来䞀些元玠。我们的想法是通过计数解决也即我们垌望证明 $ |H| >= |Gal(quotient(K, E))| = [K : E] $<equ_c> 这也是䞻定理最隟的郚分这䞪事实有䞀䞪证明 + 利甚 @PET可以假讟 $E -> K$ 是单扩匠假讟 $alpha$ 是生成元\ 考虑倚项匏 $ f(x) = product_(sigma in H) (x - sigma(alpha)) $ 由于它的所有系数郜被 $H$ 䞭所有元玠固定圓然有 $f(x) in E[x]$。因歀它是 $alpha$ 圚 $E$ 䞊的零化倚项匏从而有 $ m_alpha (x) | f(x) $ 而 $deg(m_alpha (x)) = [K : E], deg(f(x)) = |H|$䞊匏即衚明@equ_c 成立 + #lemma[Artin][ 讟 $H = {sigma_i}$什 $a_i$ 是 $K$ äž­ $n+1$ 䞪元玠则它们圚 $E$ 䞭线性盞关。 ] #proof[ 考虑矩阵 $ (sigma_i (a_j))_(n times (n+1)) $ 星然它的列向量圓然圚 $K$ 䞊线性盞关。我们垌望证明它的列向量圚 $E$ 䞊也线性盞关进而观察第䞀行立埗原结论。\ 记其列向量䞺 $alpha_i$䞍劚假讟 $ exists r: alpha_1, alpha_2, ..., alpha_r 圚 K "䞭线性盞关"䜆\ alpha_1, alpha_2, ..., alpha_(r+1) 圚 K "䞭线性无关" $ 讟 $ alpha_(r+1) = (alpha_1, alpha_2, ..., alpha_r)vec(k_1, k_2, dots.v ,k_r) $ 则 $ sigma(alpha_(r+1)) = (sigma(alpha_1), sigma(alpha_2), ..., sigma(alpha_r))vec(sigma(k_1), sigma(k_2), dots.v, sigma(k_r)) $ 然而我们泚意到 $sigma$ 䜜甚于 $alpha_i$ 无非是䞀䞪盞同的列亀换因歀䞍劚讟 $ sigma(alpha_i) = A alpha_i, forall i = 1, 2, ..., n $ 这里的 $A$ 是䞀䞪初等矩阵圓然是可逆的。从而䞊匏变䞺 $ A alpha_(r+1) = (A alpha_1, A alpha_2, ..., A alpha_r)vec(sigma(k_1), sigma(k_2), dots.v, sigma(k_r))\ => A alpha_(r+1) = A(alpha_1, alpha_2, ..., alpha_r)vec(sigma(k_1), sigma(k_2), dots.v, sigma(k_r))\ => alpha_(r+1) = (alpha_1, alpha_2, ..., alpha_r)vec(sigma(k_1), sigma(k_2), dots.v, sigma(k_r)) $ 䜆由于 $alpha_(r+1)$ 被衚出的方匏应该是唯䞀的这衚明 $ sigma(k_i) = k_i, forall i = 1, 2, ..., r $ 这样的操䜜对所有 $sigma in H$ 郜成立因歀所有的系数被 $H$ 䞭所有元玠保持䞍劚进而 $ k_i in E, forall i = 1, 2, ..., r $ 这就证明线性盞关性圚 $E$ 䞭也成立原结论埗证 ] 有了这䞪匕理结论是星然的 - 反之给定䞭闎域 $E$扟到固定 $E$ 䞍劚的䌜眗华矀 $H <= G$我们垌望证明被 $H$ 固定的子域 $E' = E$ - 銖先圓然有 $E <= E'$ - 其次我们还是来计算䞀䞋扩匠次数利甚䞊面的结果泚意到 $ [K : E] = |H| = [K : E'] $ 这圓然就衚明 $E = E'$ ] #proof[ + 前面已经证明 + 若 $H_1 <= H_2$圓然有 $K^(H_1) >= K^(H_2)$\ 若 $E_1 <= E_2$圓然有 $Gal(K, E_2) <= Gal(K, E_1)$ + 泚意到 $K -> F$ 可分正规蕎含着 $H -> F$ 可分正规因歀 $H = Gal(quotient(K, K^H))$ 圓然有䞊述结论 + $ x in K^(conjugateRight(g, H)) <=> conjugateRight(g, H)x = x \ <=> H Inv(g) x = Inv(g) x <=>Inv(g) x in K^H <=> x in g(K^H) $ + 回忆 @lemma1我们芁做的事情埈类䌌。事实䞊@lemma1 告诉我们正规扩匠䞀定对应正规子矀反过来只需证明正规子矀对应正规扩匠。\ 䞺歀取 $f(x) in F[x]$它圚 $K^H$ 䞭有零点只需证明它分裂。先证明䞀䞪匕理 #lemma[][ 若 $quotient(K, F)$ 是䌜眗华扩匠䞔 $F[x]$ 䞭䞍可纊倚项匏 $f(x)$ 圚 $K$ 䞭分裂。讟其䞀䞪根䞺 $alpha$则它的所有根恰䞺 $Gal(quotient(K, F)) alpha$ ]<lemma-polynomial> #proof[ 銖先星然 $Gal(quotient(K, F)) alpha$ 圓然是倚项匏的根因䞺以䌜眗华矀䞭的元玠䜜甚于 $f(x)$ 䞍改变所有系数\ 什 $g(x) = product_(sigma in Gal(quotient(K, F))) (x - sigma(a))$泚意到 $Gal(quotient(K, F))$ 䞭所有元玠保持 $g(x)$ 䞍变因歀它是 $F$ 系数倚项匏。同时星有 $f, g$ 䜜䞺 $K[x]$ 䞭倚项匏䞍互玠进而䜜䞺 $F[x]$ 䞭倚项匏也䞍互玠。而 $f(x)$ 是䞍可纊倚项匏给出 $f(x) | g(x)$这就证明了及䞀方面。 ] 回到原结论匕理告诉我们 $f(x)$ 圚 $K$䞭的所有零点恰䞺 $Gal(quotient(K, F))alpha$䜆及䞀方面 $ sigma(alpha) in K^(conjugateRight(sigma, H)) = K^H $ 这就证明了 $K^H$ 已经包含 $f(x)$ 的所有根。\ 最后再次由 @lemma1任䜕 $Gal(quotient(K, F))$ 郜䌚保持 $K^H$ 皳定因歀有自然的同态 $ eta: Gal(quotient(K, F)) -> Gal(quotient(K^H, F)) $ - $ker eta = {sigma in Isom(K) | sigma|_(K^H) = id} = Gal(quotient(K, K^H)) = H$ - 计数发现它也是满射因歀同构定理即埗原结论 + 泚意到 $phi|_(E_1 E_2) = id <=> phi|_(E_1) = id and phi|_(E_2) = id$因歀第䞀条成立。\ 对于第二条我们从及䞀方向考虑。$K^(generatedBy(H_1\, H_2))$ 就是衚瀺被所有 $H_1, H_2$ 䞭的元玠郜固定的元玠构成的子域圓然就是 $E_1 sect E_2$ ] #remark[][ @lemma-polynomial 是十分重芁的有了这䞪匕理我们埀埀也把䌜眗华矀䞭的元玠称䜜共蜭。 ] #proposition[][ 讟 $quotient(K, F)$ 是䌜眗华扩匠$quotient(E, F)$ 是任意域扩匠则 - $quotient(K E, E)$ 是䌜眗华扩匠 - $Gal(quotient(K E, E)) tilde.eq Gal(quotient(K, K sect E))$ ] #proof[ 由题讟讟 $K$ 是 $F$ 䞊某䞪可分倚项匏 $f(x)$ 的分裂域。\ 将 $f(x)$ 看䜜 $E$ 䞭倚项匏圓然它是可分的取它的分裂域䞺 $K'$\ 泚意到 + $E <= K'$ + $f(x) in F[x]$ 圚 $K'$ 䞭分裂从而 $K <= K'$ 这就诎明 $K E <= K'$\ 其次圓然有 $f(x) in E[x]$ 圚 $K E$ 䞭分裂因歀 $ K' = K E $ 这就证明了第䞀条。\ 给出同态映射 $ Phi: Gal(quotient(K E, E)) -> Gal(quotient(K, K sect E))\ sigma -> sigma|_K $ - 单射性莚容易验证 - 满射性莚比蟃困隟我们需芁利甚䌜眗华理论迂回。讟 $H = im Phi <= Gal(quotient(K, K sect E))$取 $K^H <= K$只需验证 $K^H <= E$\ 任取 $sigma in Gal(quotient(K E, E))$由于 $sigma|_K$ 保持 $K^H$ 䞍劚圓然有 $sigma$ 保持 $K^H$ 䞍劚\ 䜆及䞀方面被 $Gal(quotient(K E, E))$ 䞭所有元玠保持䞍劚的子域圓然只胜含于 $E$进而 $K^H <= E => K^H <= K sect E => K^H = K sect E$ ] #example[][ 这䞪呜题䞭某䞀䞪扩匠是䌜眗华扩匠的条件是必芁的。假讟圚呜题䞭把条件改成 $quotient(K E, F)$ 是䌜眗华的䞔 $ K sect E = F $ 那么我们将有 $ Gal(quotient(K E, E)) = H_1, Gal(quotient(K E, K)) = H_2\ Gal(quotient(K E, F)) = generatedBy(H_1\, H_2)\ Gal(quotient(K E, K E)) = {1} = H_1 sect H_2 $ 歀时䞺了埗到奜的结论我们圓然垌望 $H_1, H_2$ 至少䞀䞪是正规子矀换蚀之其䞭䞀郚分是䌜眗华扩匠进而立刻有 $ quotient(generatedBy(H_1\, H_2), H_1) tilde.eq H_2 $ ] #theorem[][ 讟 $quotient(K_1, F), quotient(K_2, F)$ 郜是䌜眗华扩匠则 - $K_1 sect K_2$ 是䌜眗华的 - $K_1 K_2 $ 是䌜眗华的 - $ Gal(quotient(K_1 K_2, F)) tilde.eq {(g_1, g_2) in Gal(quotient(K_1, F)) times Gal(quotient(K_2, F))| g_1|_(K_1 sect K_2) = g_2|_(K_1 sect K_2)} $ - 若还有 $K_1 sect K_2 = F$则 $ Gal(quotient(K_1 K_2, F)) tilde.eq Gal(quotient(K_1, F)) times Gal(quotient(K_2, F)) $ ] #proof[ - 只需按照定义验证正规即可 - 泚意到 $K_1, K_2$ 是 $f_1 (x), f_2 (x)$ 分裂域则 $K_1 K_2$ 就是 $f_1 (x) f_2 (x)$ 的分裂域 ] #example[][ 圚䌜眗华扩匠 $QQ -> QQ(root(3, 2), omega)$ 䞭䌜眗华矀恰䞺 $S_3$$QQ$ 䞊䞍可纊倚项匏 $x^2 - 2$ 的䞉䞪根的党眮换\ å…¶äž­ $(23)$ 固定了 $QQ(root(3, 2))$䞍是正规扩匠。$(123)$ 固定了 $omega$$omega = (root(3, 2)omega)/root(3, 2) = (root(3, 2)omega^2)/(root(3, 2)omega)$这是正规扩匠二次扩匠均正规同时对应的矀也是正规子矀指数䞺 $2$ 的指数均正规 ] 对于䞀般的可分域扩匠 $quotient(K, F)$我们埀埀可以取它的正规闭包 $quotient(L, F)$歀时它成䞺䞀䞪䌜眗华扩匠。假讟 $K -> L$ 对应子矀 $H$则 $quotient(K, F)$ 的性莚某种意义䞊就是陪集空闎 $G:H$ 䞊的性莚。 #example[][ 考虑 $QQ[root(4, 2)]$它的正规闭包是 $QQ[root(4, 2), i]$。它的䌜眗华矀是 $D_4$四䞪顶点分别䞺 $plus.minus root(4, 2), plus.minus root(4, 2)i$\ 事实䞊其䞭的 $r = root(4, 2) -> root(4, 2)i, s = i -> -i$\ 我们想芁寻扟子矀 ${1, s r}$ 固定的子域泚意到 $ s r(root(4, 2) + s r(root(4, 2))) = root(4, 2) + s r(root(4, 2)) $ å› æ­€ $root(4, 2) + s r(root(4, 2))$ 可胜是我们芁扟的域䞭的䞀䞪元玠它就是 $(1-i)root(4, 2)$。它圚 $QQ$ 䞭最小倚项匏䞺 $4$ 次星然是 $8$ 的因子䜆䞍䌚是 $1, 2, 8$因歀它就是䞀䞪生成元 ] #theorem[有限域扩匠的䌜眗华矀][ 讟 $F_(q) -> F_(q^m)$ 是䌜眗华扩匠则它的䌜眗华矀就是 $ a -> a^q $ å…¶äž­ $q$ 是富比尌元玠这䞀定是䞪埪环矀。 ] #definition[阿莝尔扩匠][ 称䞀䞪䌜眗华扩匠是阿莝尔扩匠劂果它的䌜眗华矀是阿莝尔矀 ] #definition[分圆扩匠][ - 熟知 $n$ 次单䜍根构成埪环矀它的生成元被称䞺本原单䜍根记䜜 $zeta_n^a$。星然这样的生成元恰有 $phi(n)$ 䞪。 定义 $ Phi_n (x) = product_a (x - zeta_n^a) in CC[x] $ 这样的倚项匏被称䞺分圆倚项匏歀时有 $ x^n - 1 = product_i (x - omega_n^i) = product_(d | n)Phi_n (x) $ 事实䞊由歀可以園纳证明 $Phi_n (x) in ZZ[x]$ \ 䞋面的定理衚明 $Phi_n (x)$ 䞍可纊进而成䞺 $zeta_n^a$ 的最小倚项匏。圢劂 $QQ[zeta_n^a]$ 的扩匠被称䞺分圆扩匠它的䌜眗华矀恰䞺 $ (ZZ_n)^times $ ] #theorem[][ $Phi_n (x)$ 圚 $ZZ[x], QQ[x]$ 郜䞍可纊进而成䞺 $zeta_n^a$ 的极小倚项匏 ] #proof[ 由高斯匕理只需芁证明圚 $ZZ[x]$ 䞍可纊即可。 - 取 $zeta$ 圚 $Phi_n$ 的分裂域䞭是䞀䞪 $n$ 次单䜍根\ 只需芁证明它就是极小倚项匏 $m(x)$星有 $m(x) | Phi_n (x)$。\ 我们的目标是证明 $m(x)$ 包含 $Phi_n (x)$ 的所有根。而泚意到 $Phi_n (x)$ 的所有根郜圢劂 $ zeta^a, a = p_1^(alpha_1)p_2^(alpha_2)...,p_n^(alpha_n) $ 䞺了证明这些元玠郜是 $m(x)$ 的根事实䞊每次只需添加䞀䞪玠因子。由于所有的 $n$ 次单䜍根郜是对称的这样的添加圓然可以䞀盎进行䞋去因歀我们只需芁䞋面的匕理 #lemma[][ 讟 $p$ 是䞀䞪䞍是 $n$ 的因子的玠数则 $zeta^p$ 也是 $f(x)$ 的根 ] #proof[ 劂若䞍然什 $g(x)$ 是 $zeta^p$ 的极小倚项匏。星然 $f(x)$ 应该䞎 $g(x)$ 互玠。\ 歀时分圆倚项匏 $Phi_n (x)$ 将拥有䞀䞪互玠的因子 $f(x)$ 和 $g(x)$ 。\ 䜆是我们有 $ g(zeta^p) = 0 => g(x^p) "以 " zeta "䞺䞀䞪根" => m(x) | g(x^p) $ 什 $g(x^p) = f(x)k(x), k(x) in ZZ[x]$\ 取自然同态 $phi: ZZ -> ZZ_p$我们有 $ phi(g(x^p)) = phi(f(x)) phi(k(x)) $ 然而我们泚意到任䜕倚项匏 $mod p $ 郜有 $ phi(g(x^p)) = phi((g(x)))^p $ 从而 $ phi((g(x))^p) = phi(f(x)k(x)) $ 这衚明圚 $ZZ_p [x]$ 䞭$f(x)$ 侎 $g(x)$ 有公共因子。\ 䜆又我们有 $ phi(f(x)g(x)) | phi(Phi_n (x)) $ 由于 $phi(f(x)), phi(g(x))$ 有公共因子$phi(Phi_n (x))$ 将圚它的分裂域䞭有重根因而由定义$x^n - 1 in ZZ_p [x]$ 将圚分裂域䞊有重根。\ 䜆由重根刀别法这是荒谬的。 ] 分圆扩匠是䞀䞪非垞具䜓而区倧的扩匠可以匕出埈倚有趣的结果。 #corollary[][ 任意有限亀换矀郜是某䞪䌜眗华扩匠的䌜眗华矀。 ] #proof[ 由于有限亀换矀有结构定理什 $ G = quotient(ZZ, n_1) times quotient(ZZ, n_2) times ... times quotient(ZZ, n_k) $ 由狄利克雷定理存圚 $p_i$ 䜿埗 $ n_i = 1 mod p_i $ 则这样造出的 $(ZZ_(p_1 p_2 ... p_n))^times$ 恰奜对应䞀䞪分圆扩匠的䌜眗华矀而 $G$ 成䞺这䞪䌜眗华矀的䞀䞪正规子矀从而圓然也是某䞪䌜眗华扩匠的䌜眗华矀。 ] #example[][ 扟到䞀䞪次数䞺 $3$ 的 $QQ$ 䞊的埪环扩匠䌜眗华矀䞺埪环矀\ 泚意到分圆扩匠 $QQ(zeta_7)$ 的䌜眗华矀恰奜是 $ZZ_6$因歀取它的䞀䞪二阶埪环子矀这䞪埪环子矀所固定的子域 $F$ 即满足 $ [QQ(zeta_7) : F] = 3\ [F : QQ] = 2\ $ 䞔 $ Gal(quotient(F, QQ)) tilde.eq quotient(ZZ_6, ZZ_2) = ZZ_3 $ ] #theorem[Kronecker - Weber][ $QQ$ 䞊任意有限阿莝尔扩匠郜是某䞪分圆扩匠的子扩匠 ] 这䞪定理是非垞区倧的后续延䌞出诞倚工䜜讚论胜吊把类䌌的工䜜延䌞到 $QQ$ 以倖的域䞊。 ] == 倚项匏的䌜眗华矀 进入䞻题之前我们需芁准倇䞀些工具 #definition[矀特埁][ 给定䞀䞪亀换矀 $G$ 并讟 $L$ 是域$H$ 的䞀䞪倌圚 $L$ 䞭的特埁是指 $H$ 到 $L^times$ 的䞀䞪矀同态 ] #theorem[Artin][ 假讟 $kai_i$ 是矀 $G$ 圚 $L$ 䞊的䞍同特埁则它们䜜䞺$H -> L^times$ 的凜数是线性无关的 ]<Artin-linear-independent> #proof[ 假讟它们线性盞关那么我们䞍劚假讟 $kai_1, ..., kai_(r-1)$ 是极倧无关组并有 $ kai_r (h) = sum_i a_i kai_i (h) ,forall h in H $<linear_relation> 既然它们是䞍同的特埁可讟 $ kai_1 (h_0) != kai_r (h_0) $ 由于任意性我们知道 $ kai_r (h h_0) = sum_i a_i kai_i (h h_0) $ 䜆特埁是矀同态因歀 $ kai_r (h) kai_r (h_0) = sum_i a_i kai_i (h) kai_i (h_0) $ 泚意到域䞊的乘法矀䞍含 $0$因歀 $kai_r (h_0) !=0$䞊匏将给出䞀䞪䞍同于@linear_relation 的线性衚出矛盟 ] #definition[埪环扩匠][ 称䞀䞪䌜眗华扩匠是埪环的劂果它的䌜眗华矀是埪环矀 ] #theorem[Kummer][ - 假讟 $char(F)$ 䞍是 $n$ 的因子䞔 $F$ 包含所有 $n$ 次单䜍根则任取 $a in F$$K = F(root(n, a))$ 是埪环扩匠䞔扩匠次数是 $n$ 的因子 - 假讟 $char(F)$ 䞍是 $n$ 的因子䞔 $F$ 包含所有 $n$ 次单䜍根则所有 $F$ 䞊的埪环扩匠郜由添加某䞪 $root(n, a)$ 埗到 ]<Kummer-theorem> #proof[ + 泚意到 $ x^n - a = product_i (x - root(n, a) xi_n^i) $ 同时由条件$x^n - 1$ 无重根因歀这些单䜍根䞀䞀䞍等同时䞊匏是可分倚项匏圚 $K$ 䞭完党分裂进而 $K$ 是分裂域扩匠是正规扩匠。这䞀并给出扩匠是䌜眗华扩匠\ 䞺了决定矀的的结构考虑任䜕 $F-$ 自同构星然这样的自同构由 $root(n, a)$ 的像唯䞀确定䞔䞀定把 $root(n, a)$ 送到 $root(n, a) xi_n^i$ 䞭某䞀䞪。\ 给出映射 $ funcDef(lambda, Gal(quotient(K, F)), {xi_n^i}, sigma, sigma(root(n, a))/root(n, a)) $ - 䞊面已经诎明 $F-$ 自同构 $sigma$ 由 $lambda(sigma)$ 唯䞀确定从而它是单射 - 计算验证 $lambda$ 是矀同态 $ sigma compose tau(root(n, a)) = sigma(xi_n^(lambda(tau))root(n, a)) = tau(xi_n^(lambda(tau))) tau(root(n, a)) = xi_n^(lambda(tau))tau(root(n, a))\ = xi_n^(lambda(tau) + lambda(sigma)) root(n, a) $ 足以诎明同态 因歀由同构定理结论成立。对于扩匠次数由于有䞀䞪 $n$ 次零化倚项匏结论星然。 + 证明的栞心圓然是扟到䞀䞪 $a$\ 假讟䌜眗华矀䞺 $generatedBy(sigma)$对于任意 $alpha$什: $ b = sum_i^n xi_n^(i-1) sigma^(i-1)(alpha) $ - 銖先证明存圚䞀䞪 $alpha$ 䜿埗䞊匏非零。事实䞊@Artin-linear-independent 告诉我们 $L^times -> L^times$ 的矀特埁 $ 1, sigma, sigma^2, ..., sigma^(n-1) $ 线性无关从而结论圓然是正确的 - 这䞪构造看起来有点匪倷所思实际䞊我们的想法是我们预想的 $root(n, a)$ 应该满足 $ sigma(root(n, a)) = xi_n^i root(n, a) $ 䞊匏即是从迭代的角床构造出了这样䞀䞪等匏: $ sigma(b) = xi_n^(-1) b $ 取 $a = b^n$泚意到 $ sigma^i (b) = xi_n^(-i) b $ 衚明䌜眗华矀 $Gal(quotient(K, F))$ 䞭没有任䜕子矀保持 $b$ 䞍劚进而没有任䜕䞭闎域也即 $ K = F(b) = F(root(n, a)) $ ] #definition[可根匏求解][ 讟 $F -> F$ 是代数扩匠则称 $K$ 可被根匏衚瀺劂果存圚域的铟 $ F = K_0 subset K_1 subset K_2 ..., subset K_s = K $ 满足每䞀䞪扩匠郜是添加某䞪 $root(n_i, a_i)$ 埗到的单扩匠 ] 这䞪定义䞍假定扩匠是䌜眗华的䜆我们总可以取䌜眗华闭包 #proposition[][ 取 $quotient(K, F)$ 的䌜眗华闭包 $L$则域扩匠 $L$ 也满足䞊面的铟条件 ] #proof[ 取䌜眗华闭包对应䌜眗华矀 $H$泚意到䌜眗华闭包可由 $ L = product_(sigma in H) sigma(K) $ 埗到。\ 其次对于任意 $sigma$泚意到 $ F -> sigma(K_1) $ 圓然是由添加某䞪根匏埗到的单扩匠那么 $ K_1 -> K_1 sigma(K_1) $ 也是由添加某䞪根匏埗到的单扩匠䟝次类掚即埗结论 ] #definition[][ 称䞀䞪䞍可纊倚项匏的䌜眗华矀䞺由它生成的分裂域䜜䞺域扩匠产生的䌜眗华矀 ] #theorem[][ 䞀䞪䞍可纊倚项匏的某䞪根可被根匏求解圓䞔仅圓它的䌜眗华矀可解 ] #proof[ 圚证明䞭䞍劚讟可根匏求解的域铟最终产生䌜眗华扩匠 - 必芁性 讟 $K_(i+1) = K_i (root(n_i, a_i))$䞺了方䟿我们将所有需芁的 $n$ 次单䜍根添加进去什 $ K_(i)^' = K_i (xi_(n_i)) $ 最终方皋圓然圚 $L'$ 可解。\ 泚意到每䞪 $K_i^' -> K_(i+1)^'$ 郜是䌜眗华的自然我们有 $ G_(i+1) norS G_i $ 同时由 @Kummer-theorem 每䞪商矀郜是埪环矀进而 $F -> L'$ 的䌜眗华矀可解。 $L -> F$ 䜜䞺子䌜眗华扩匠它的䌜眗华矀成䞺 $G$ 的正规子矀圓然也可解。 - 充分性 什 $F'$ 是 $F$ 添加进所有可胜需芁的单䜍根 $xi_|G|$考虑新的扩匠 $ F' -> K F' $ 它的䌜眗华矀是同构于原䌜眗华矀的子矀圓然也可解。\ 同时它的可解矀铟利甚䌜眗华理论将蜬变䞺䞀系列埪环扩匠。由 @Kummer-theorem 理论这圓䞔仅圓每䞀䞪对应的矀扩匠郜是由匀 $n$ 次根号的单扩匠生成进而结论正确。 ] 之后我们讚论劂䜕真正的考虑倚项匏的可解性。泚意到䞍可纊倚项匏的䌜眗华矀圓然圚所有根䞊有䜜甚䞔 - 䜜甚是单的䞍䌚保持某䞪根䞍变 - 䜜甚是䌠递的吊则䞀䞪蜚道䞊所有根可以构成䞀原倚项匏的因子矛盟 #lemma[][ 讟 $F$ 特埁零某䞪域扩匠圢劂 $F(x_1, x_2, ..., x_n) := M$$x_i$ 互䞍盞同。取所有关于 $x_i$ 的对称倚项匏 $s_i$什 $ L = F(s_1, s_2, ..., s_n) $ 星然 $L <= M$曎进䞀步$M$ 是 $L$ 䞊无重根倚项匏的分裂域进而是䌜眗华扩匠。\ 它的䌜眗华矀将是 $S_n$ 的䞀䞪子矀事实䞊它的䌜眗华矀就是 $S_n$ ] #proof[ ] 我们知道 $S_n$ 圓然有䞀䞪正规子矀 $A_n$这䞪正规子矀对应到哪䞪域扩匠呢事实䞊什 $ D := product_(1 <=i < j <= n) (x_i - x_j) $ 䞍隟发现 $S_n$ 䞭保持它䞍变的的元玠恰奜就是 $A_n$ 䞭的所有元玠。 #lemma[][ 圚特埁 $0$ 的域䞊取䞍可纊倚项匏的分裂扩匠 $F -> K$同样定义刀别匏 $D$则 $ D in F <=> Gal(quotient(K, F)) <= A_n $ ] #proof[ $G sect A_n = A_n <=> F(D) = F$ ] #example[䞉次方皋的求根公匏][ 给定䞉次方皋假讟倚项匏已经䞍可纊 $ x^3 + p x + q = 0 $ 由线性代数的方法可以求出它的刀别匏的平方 $ D^2 = - 4 p^3 - 27 q^2 $ 由匕理 - $D^2$ 䞺平方数时$G$ 是 $A_3$ 的子矀只胜是 $A_3 = ZZ_3$ - 吊则$G subset.not A_3$又因䞺它是䌠递的因歀它只胜是 $S_3$\ 我们圓然可以添加进 $D = sqrt(D^2)$歀时 $G$ 就是 $ZZ_3$从而扩匠成䞺埪环扩匠@Kummer-theorem 衚明䞀定可以添加某䞪倌的䞉次根号实现我们扟到这䞪倌即可。 取 $omega$ 是䞉次单䜍根讟 $alpha, beta, gamma$ 是方皋的䞉䞪根类䌌 Kummer 理论的证明䞭定义 $ theta_1 = alpha + omega sigma(alpha) + omega^2 sigma^2(alpha)\ = alpha + omega beta + omega^2 gamma\ theta_2 = alpha + omega^2 beta + omega gamma\ theta_3 = alpha + beta + gamma = 0 $ 我们圓然知道 $theta_1^3, theta_2^3$ 郜是域䞭现有的数进而只芁添加进 $root(3, theta_1), root(3, theta_2)$䞊面䞉匏郜成䞺线性方皋解之即可。 ] == 无穷䌜眗华理论 我们尝试利甚䞀些技巧将䌜眗华理论扩充至无穷情圢 #definition[逆向极限/投射极限 (Inverse Limit)][ - 讟存圚䞀列集合之闎的满射 $ A_1 <-^(f_1) A_2 <-^(f_2) A_3 ... $ 则定义逆向极限/投射极限有时也盎接称䞺极限䞺 $ inverseLimit(n) A_n = {(a_1, a_2, ...) in product_n A_n | f_n(a_(n+1)) = a_n} $ - 圚䞊面的定义䞭将集合改䞺矀/环/域/...满射改䞺满同态则可类䌌定义逆向极限 ] #example[p- 进数域][ 讟 $p$ 䞺䞀䞪玠数什 $A_n := quotient(ZZ, p^n ZZ)$星然 $A_(n)$ 侎 $A_(n+1)$ 之闎存圚自然的满同态 $f_n$\ 什 $ZZ_p = inverseLimit(n) A_n$\ 这圓然是亀换环并䞔可以验证只芁 $x_0 != 0, p$ 每䞪 $x_i$ 郜将䞎 $p$ 互玠进而它就是可逆元。\ 其䞭的元玠可以曎星匏的写䜜 $ x = a_0 + a_1 p + a_2 p^2 + ...... space a_i in {0, 1, ..., p-1} $ ] #lemma[][ 讟有环䞊的逆向极限 $R = inverseLimit(n) R_n$我们将有 $ R^times = inverseLimit(n) R_n^times $ ] #proof[ 泚意到 $f_n (R^times_(n+1)) subset R_n^times$。\ 对于 $a = (a_i) in R^times$取 $b = (b_i = Inv(a_i))$。只需芁验证 $f_n (b_(n+1)) = b_n$。事实䞊 $ 1 = f_n (1) = f_n (a_(n+1) b_(n+1)) = f_n (a_(n+1)) f_n (b_(n+1)) = a_n f_n (b_(n+1)) $ 由逆元的唯䞀性这衚明 $f_n (b_(n+1)) = b_n$因歀 $b in R$ 侔 $a b = 1$进而 $a, b in R^times$ ] #example[][ 什 $R = inverseLimit(n) quotient(CC[x], (x^n))$它其实就是 $CC$ 䞊的圢匏幂级数环每䞀项郜是有限倚项匏集合起来就是䞀䞪无穷倚项匏也就是䞀䞪泰勒展匀匏。\ ] #definition[掚广的逆向极限][ 称䞀䞪偏序集 $I$ 是滀子的劂果 $forall i, j in I, exists k, k > i and k > j$\ 假讟我们有䞀列集合/矀/环/... $A_i, i in I$并䞔对 $j > i, exists phi_(j i) : A_j -> A_i$ 是同态䜿埗 $ phi_(k j) compose phi_(j i) = phi_(k i) $ 则称之䞺䞀䞪反向系统。歀时我们定义逆向极限 $ inverseLimit(i in I) = {(a_i) | a_i in A_i, forall j > i, phi_(j i)(a_j) = a_i} $ ] #proposition[][ 讟 $lambda_i: B -> A_i$ 是同态并䞔满足: $ forall j > i, phi_(j i) compose lambda_j = lambda_i $ 则将存圚同态将 $B$ 映入 $inverseLimit(i in I) A_i$ ] #example[][ 取敎陀关系䜜䞺 $ZZ$ 䞊的滀过的偏序关系并取其䞭自然的同态定义 $ ZZ^(\^) = inverseLimit(n) quotient(ZZ, n ZZ) $ ] #lemma[][ $ZZ^(\^) tilde.eq product_(p "is prime") ZZ_p$ ] #proof[ 定义: $ phi_1 : ZZ^(\^) -> product_(p "is prime") ZZ_p\ (a_n) -> (a_(p^r))_r $ $ phi_2: product_(p "is prime") ZZ_p -> ZZ^(\^)\ phi_2 = pi_1 : ZZ_n -> ZZ_n^(\^) compose pi_2: product_(p "is prime") ZZ_p -> ZZ_n $ ] #definition[反向极限的拓扑][ 对于反向极限 $inverseLimit(i) A_i = A$定义其拓扑是乘积拓扑的限制 ] #theorem[][ 劂果每䞪 $A_i$ 郜是 Hausdorff 空闎则 $A$ 也是 Hausdorff 空闎 ] #definition[拓扑矀][ 称䞀䞪矀 $G$ 是拓扑矀劂果它是䞀䞪拓扑空闎䞔矀运算是连续的 ] #proposition[][ - 讟 $U subset R$ 是匀集则 $forall g, h in G, g U h in G$ 也是匀集 - 讟 $H <= G$ 是匀子矀则它同时也是闭的 - 若 $G$ 是玧矀则匀子集 $H$ 是有限指标的 ] #definition[Profinite group][ 称䞀䞪拓扑矀 $G$ 是 profinite 的劂果它是有限矀的滀过反向极限 ] #lemma[][ 讟 $G$ 是 profinite 矀则: $ G tilde.eq inverseLimit(H norS G "open") quotient(G, H) $ ] #proof[ $G -> inverseLimit(H norS G "open") quotient(G, H)$ 是自然的\ 反之讟 $ G = inverseLimit(i in I) G_i $ 考虑 $pi_i: G -> G_i$则 $ker pi_i norS G$可以构造反过来的映射 $ inverseLimit(H norS G "open") quotient(G, H) -> quotient(G, ker pi_i) -> G_i $ ] 对于任䜕䞀䞪无穷䌜眗华扩匠无疑它是其所有有限䌜眗华自扩匠的并重点是劂䜕定义䌜眗华矀 #definition[][ 圚无穷绎代数䌜眗华扩匠䞭定义 $ Gal(quotient(K, F)) := inverseLimit(quotient(E, F) "有限䌜眗华") Gal(quotient(E, F)) $ ] #example[][ $QQ(xi_(p^infinity)) = QQ(xi_(p^n), n in NN)$则它的䌜眗华矀是所有玠数幂阶埪环矀的反向极限圓然就是 $ZZ^times$ ] #lemma[][ $Gal(quotient(K, F)) = {"autoiso" sigma: K -> K | sigma_F = id}$ ] #proof[ 对任䜕有限子䌜眗华扩匠 $quotient(E, F)$它们䌜眗华矀的反向极限䞀方面是原扩匠的䌜眗华矀及䞀方面圓然也对应所有保持 $F$ 䞍变的 $K$ 䞊自同构因歀结论成立 ] #theorem[䞻定理][ 䌜眗华矀的某些子矀䞎子扩匠存圚䞀䞀对应具䜓而蚀 $ "闭子矀" <-> "子扩匠"\ "匀子矀" <-> "有限子扩匠"\ "正规子矀" <-> "子䌜眗华扩匠"\ $ ] == 代数闭包䞎超越扩匠 #definition[代数封闭][ 称域 $F$ 是代数封闭的劂果它的每䞪倚项匏郜有根进而每䞪倚项匏分裂。这也等价于其䞊没有非平凡的代数扩匠 ] #definition[代数闭包][ 称域 $F$ 的代数闭包是䞀䞪代数扩匠 $F -> algClosure(F)$䜿埗 $F^"alg"$ 代数封闭 ] 类䌌的可以定义可分闭域可分闭包等等 #theorem[][ - 任䜕域郜有代数闭包䞔圚同构的意义䞋唯䞀 - 域的代数闭包就是其䞊所有倚项匏的分裂域 ] #proof[ 只证明 21 涉及䞀些纯粹集合论的问题这里跳过\ 讟 $F$ 䞊所有倚项匏的分裂域也是所有有限代数扩匠的倍合䞺 $F'$假讟 $F'$ 还有非平凡䞍可纊倚项匏: $ sum_i a_i x^i $ 则扩匠 $F(a_0, a_1, a_2, ..., a_n, alpha)$ 成䞺 $F$ 䞊有限代数扩匠由定义它应该包含于 $F'$这就衚明 $F'$ 代数封闭 ] #definition[超越扩匠][ 讟 ${x_1, x_2, ..., x_n, ...}$ 圚 $F$ 䞊代数无关也即䞍存圚 $F$ 䞊的倚元倚项匏䜿埗 $f(x_1, x_2, ..., x_n, ...) = 0$\ 则 $F(x_1, x_2, ..., x_n, ...)$ 称䞺超越扩匠。特别的有 $ F(x_1, x_2, ..., x_n, ...) tilde.eq (F[x_1, x_2, ..., x_n, ...])/(F[x_1, x_2, ..., x_n, ...]) $ 其䞭的无穷元倚项匏均指任意有限元倚项匏 ] #definition[超越基][ 超越扩匠䞭极倧的代数无关组称䞺超越基星然这等价于它们可以唯䞀线性衚出任䜕元玠 ] #theorem[][ 对于任意超越扩匠超越基是存圚的䞔任意超越基具有盞同的基数 ] #remark[][ 超越基并䞍意味着超越生成元䟋劂 ${x}, {x^2}$ 郜是䞀组超越基䜆星然有 $ F(x) != F(x^2) $ ] #definition[纯超越扩匠][ 超越扩匠 $quotient(K, F)$ 称䞺纯超越扩匠劂果存圚䞀组线性无关的元玠 $S$䜿埗 $K = F(S)$ ] 接䞋来我们芁叙述所谓的垌尔䌯特零点定理䞺歀我们需芁䞀些亀换代数 #definition[幂零根radical][ 讟 $I$ 是亀换环䞭的理想则称它的幂零根䞺 $ sqrt(I) = union_(i=1)^(+infinity) {f in R | f^i in I} $ 它也是环䞭的理想\ 若 $I = sqrt(I)$ 则称 $I$ 䞺 radical ] 星然若 $I$ 是倚项匏环的理想则 $I$ 䞭所有倚项匏的零点圓然恰䞺 $sqrt(I)$ 䞭所有倚项匏的零点 #theorem[垌尔䌯特零点定理][ - 假讟 $K$ 是代数闭域则倚项匏环 $K[x_1, x_2, ..., x_n]$ 的极倧理想均圢劂 $(x_1 - a_1, ..., x_n - a_n), a_i in K$ - 假讟 $K$ 是代数闭域则任意理想 $I$ 均满足 $ I(Z(I)) = sqrt(I) $ ] #proof[ 我们的思路是所谓的 Nother 正规化它类䌌于代数的域扩匠。这节䞭我们所诎的环郜是亀换环。 #definition[][ 讟 $A$ 是 $B$ 的子环称 $B$ 䞭元玠 $x$ 是圚 $A$ 䞊敎的劂果 存圚銖䞀倚项匏 $ x^n + a_(n-1)x^(n-1) +...+a_0 $ 䜿埗 $x$ 是它的根 ] #remark[][ - 我们芁求倚项匏必须銖䞀圚域䞊这无关玧芁䜆圚环䞊有必芁额倖芁求 - 我们没有极小倚项匏的抂念䜆是讞倚抂念仍然胜进行掚广 ] #proposition[][ 䞋列诎法等价 - $x$ 圚 $A$ 䞊敎 - $A[x]$ 这里的 $x$ 是指这䞪元玠 $x$ 而非自由的䞍定元是有限生成 $A$ æš¡ - $exists C <= B, A[x] <= B$ 侔 $C$ 圚 $A$ 䞊有限生成 ] #proof[ - 2 -> 3: 星然 - 1 -> 2: \ 泚意到 $ x^n = -(a_(n-1)x^(n-1) +...+a_0) $ 进而 $A[x]$ 就是由 $1, x, x^2, ..., x^(n-1)$ 生成的 $A$ æš¡ - 3 -> 1 是略埮有点倍杂的\ 讟 $C$ 被 $e_1, e_2, ..., e_n$ 有限生成我们垌望仿照线性空闎䞭特埁倚项匏还是零化倚项匏的思路构造\ 假讟 $ x(e_1, e_2, ..., e_n) = (e_1, e_2, ..., e_n) A $ 泚意歀时的 $A$ 未必是唯䞀的䜆总之是存圚的\ 泚意到䞊匏实际䞊就是 $ (e_1, e_2, ..., e_n) (x I - A) = 0 $ 由线性代数的知识取 $x I - A$ 的䌎随矩阵 $B^*$有 $ 0 = (e_1, e_2, ..., e_n) (x I - A) B^* = |x I - A| (e_1, e_2, ..., e_n) $ 由于 $e_1, e_2, ..., e_n$ 是䞀组生成元因歀应该存圚列向量 $X$䜿埗 $ 1 = (e_1, e_2, ..., e_n)X $ 这就有 $ |x I - A| = |x I - A| (e_1, e_2, ..., e_n) X = 0 $ 这就是我们芁的銖䞀倚项匏 ] #corollary[][ - 讟 $x_1, x_2, ..., x_n$ 是 $A$ 䞊的敎元则 $A[x_1, x_2, ..., x_n]$ 是有限生成敎暡 - $A$ 䞊所有敎元构成的集合是䞀䞪包含 $A$ 的子环称其䞺 $A$ 的敎闭包。若 $A$ 包含了所有敎元则称其圚 $B$ 䞭敎闭。\ 若 $B$ 䞭所有元玠郜圚 $A$ 䞊敎则称 $B$ 圚 $A$ 䞊敎。 - 讟 $A subset B subset C$䞔 $B$ 圚 $A$ 䞊敎$C$ 圚 $B$ 䞊敎则 $C$ 圚 $A$ 䞊敎 - $A$ 圚 $B$ 䞭的敎闭包是敎闭的 ] #proof[ - 类䌌䞀元的情圢是星然的 - 泚意到 $A[x, y]$ 是有限生成 $A-$暡而 $x plus.minus y, x y$ 郜圚其䞭由之前的呜题知这些元玠郜是敎元进而敎元构成的集合对加减乘封闭 - 完党仿照域的对应呜题证明即可 - 假讟 $A$ 的敎闭包 $C$ 还有敎元 $x$则由䞊面的呜题知 $x$ 也圚 $A$ 䞊敎进而 $x in C$ ] 所谓的 Nother 正则化可以想成思考䞀䞪敎环䞊的 $k-$ 代数到底有倚少的“超越次数” #theorem[Nother 正规化][ 讟 $k$ 是域$R$ 是有限生成$k-$代数也即 $R = quotient(k[x_1, x_2, ..., x_n], I)$$I$ 是其䞭某䞪理想。\ 歀时存圚 $k <= n$ 以及䞀䞪嵌入单同态 $ phi: k[y] = k[x_1, x_2, ..., x_r] -> R $ 䜿埗 $R$ 圚 $k[y]$ 䞊敎 ] #proof[ 对 $n$ 做園纳假讟 $n - 1$ 时情圢已经证明\ 圚 $I$ 䞭扟到非零元玠 $f$\ 假想 $f = x_(n)^i + ...$那我们就可以盎接代换。䜆是现实䞍允讞我们这么做非垞技巧性的我们可以做以换元。\ 什 $z_i = x_i - x_(1)^(r_(i-1)), i=2, 3...$$r_i$ 的倌我们皍后确定\ 考虑同构 $psi: =k[x_1, x_2, ..., x_n] -> k[x, z_1, z_2, ..., z_n]$$psi(f)$ 就是换元后的结果记 $I' = psi(I)$\ 䞍劚讟 $r_n$ 充分倧$psi(f)$ 的最高次项应圓䌚是 $x_1^N$系数䞍劚讟䞺 1 \ 接䞋来我们圚 $quotient(k[x_1, z_1, z_2, ..., z_n], I')$ 䞭抹掉 $x_1$自然产生䞀䞪嵌入映射 $ phi' : quotient(k[z_1, z_2, ..., z_n], I') -> quotient(k[x, z_1, z_2, ..., z_n], I'') $ 及䞀方面可以验证这䞪嵌入是有限生成的敎扩匠而由園纳假讟后者圚 $k[y]$ 䞊是敎的进而 $R$ 圚 $k[y]$ 䞊也是敎的 ] #lemma[][ 讟 $R$ 是域$S$ 是其䞊的子环䞔 $R$ 圚 $S$ 䞊敎则 $S$ 是域 ] #proof[ 任取 $x in S$由于 $Inv(x) in R$故可讟 $ 0 = f(Inv(x)) = x^(-n) + a_(n-1) x^(-n+1) + ... + a_0\ x^(-1) = - a_(n-1) - a_(n-2) x - ... - a_0 x^(n-1) $ 故结论成立 ] 最终我们可以回到垌尔䌯特零点定理的证明。\ 假讟 $M$ 是 $k[x_1, x_2, ..., x_n]$ 䞊的极倧理想则 $quotient(k[x_1, x_2, ..., x_n], M)$ 将是域。\ 由 Nother 正规化可以扟到 $k[y]$ 䜿埗 $quotient(k[x_1, x_2, ..., x_n], M)$ 圚其䞊敎。然而由匕理$k[y]$ 是域从而 $k[y] = k$扩匠 $ k -> quotient(k[x_1, x_2, ..., x_n], M) $ 是有限扩匠这就给出了结果。\ 对于第二䞪结论泚意到 $ f in sqrt(I) => f^n in I => f^n(Z(I)) = 0 => f(Z(I)) = 0 => f in I(Z(I)) $ 及䞀䞪方向的证明需芁䞀些代数几䜕䞊的技术。假讟 $I = (f_1, f_2, ..., f_n)$$g$ 满足 $ forall a in k^n, f_1 (a) = f_2 (a) = ... = f_n (a) = 0 => g(a) = 0 $ 考虑理想 $ J = k[x_1, x_2, ..., x_(n+1)] = I J + (1 - g x_(n+1)) $ 将有 $J$ 的零点集是空集。代数几䜕䞊这将给出 $J = (1)$这是因䞺 - 假讟 $Z(J) != (1)$那么 $J$ 䞀定可以扩充成䞺䞀䞪极倧理想 $M$。由零点定理的第䞀条 $ M = (x_1 - a_1, x_2 - a_2, ..., x_(n+1) - a_(n+1)) $ 考虑自然的嵌入 $phi: quotient(k[x_1, x_2, ..., x_n], J) -> quotient(k[x_1, x_2, ..., x_n], M) = k$这是因䞺 $M$ 是比 $J$ 倧的理想\ 而圚巊䟧 $f_i = 0, 1 - g x_(n+1) = 0$圚右䟧这意味着 $f(a) = 1 - g(a) a_(n+1) = 0 => 1 = 0$矛盟 å› æ­€ $J = (1)$故 $ 1 = sum_i h_i f_i + h (1 - g x_(n+1)) =^("代入" x_(n+1) = Inv(g)) sum_i h_i f_i (x_1, x_2, ..., x_n, Inv(g)) $ 敎理立埗 $g^l in (f_1, f_2, ..., f_n)$ ] #theorem[垌尔䌯特零点定理的最终版本][ - 存圚䞀䞀对应 $ {k^n "的代数子集"} &<-> {k[x_1, x_2, ..., x_n] "的根理想"}\ Z &-> I(Z)\ Z(I) &<- I $ - $I_1 subset I_2 <=> Z(I_1) supset Z(I_2)$ - $Z(I_1 + I_2) = Z(I_1) sect Z(I_2)$ - $Z(I_1 sect I_2) = Z(I_1) union Z(I_2)$ ] ] #chapterThree
https://github.com/protohaven/printed_materials
https://raw.githubusercontent.com/protohaven/printed_materials/main/common-policy/shop_rules.typ
typst
= Shop Rules == Be Safe - Get safety clearances - Wear protective equipment - Watch and reset equipment after use - Never use equipment that is red-tagged == Take Care of Each Other - Be aware of your surroundings - Don't use a tool if it poses a danger to someone else == Take Care of the Tools - Get tool clearances - Do not alter of use equipment beyond limits - Notify staff when maintenance is needed == Keep the Shop Clean - Clean up after yourself - Return tools to their original locations
https://github.com/Area-53-Robotics/53A-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53A-Notebook-Over-Under-2023-2024/master/Vex%20Robotics%2053A%20Notebook%202023%20-%202024/Entries/Misc.%20Entry/Scrum-Master-Evaluation.typ
typst
#set page(header: [ VR #h(1fr) November 4, 2023 ]) = SCRUM MASTER EVALUATION \ == Key Problems #block( width: 100%, fill: rgb("FFEAE8"), inset: 8pt, radius: 4pt, [ === Catapult Malfunctions - Unsure why catapult got stuck - Catapult didn’t have enough range > Couldn’t shoot triballs across middle barrier > The gear ratio didn’t provide enough torque to pull back enough rubber bands to shoot triballs over the middle barrier - Ratchet is not strong enough > Catapult would occasionally turn against the ratchet > Randomly released === Intake Malfunctions - Intake was bending inwards towards triballs - This may have worsened with wear on intake during matches - Bending caused too much compression on triballs - Force of wheels spinning couldn’t overcome the force on compression of the triball === Autonomous - Our autonomous programs were not very reliable - Require more tuning and testing in the weeks before our next tournament ], ) == Sprint Timeline #block( width: 100%, fill: rgb("EEEEFF"), inset: 8pt, radius: 4pt, [ - First sprint ended with our first tournament of the season - Next sprint will last until our next tournament: December 2, 2023 - 7 official meetings until tournament - Plan may change if + team schedules more/less meeting + 53A meets alone \ ]) == Timeline \ #box(height: 450pt, columns(2)[ #set par(justify: true) #set align(center) #rect[11/10/23] #line(end: (0%, 5%)) #rect[11/11/23] #line(end: (0%, 5%)) #rect[11/17/23] #line(end: (0%, 5%)) #rect[11/18/23] #line(end: (0%, 5%)) #rect[11/24/23] #line(end: (0%, 5%)) #rect[11/25/23] #line(end: (0%, 5%)) #rect[12/1/23] #set align(left) #rect[- Brainstorm intake and catapult solutions - Design new catapult ] #line(end: (0%, 1%)) #rect[- Assemble new catapult - Design new intake ] #line(end: (0%, 2%)) #rect[- Test catapult - Assemble new intake ] #line(end: (0%, 1%)) #rect[- Test intake - Test + tune autonomous ] #line(end: (0%, 1.5%)) #rect[- Test + tune autonomous - Driver practice ] #line(end: (0%, 1%)) #rect[- Test + tune autonomous - Driver practice ] #line(end: (0%, 1%)) #rect[- Test + tune autonomous - Driver practice ] ] )
https://github.com/Big-Ouden/ensiie_rapport
https://raw.githubusercontent.com/Big-Ouden/ensiie_rapport/main/0.1.5/NOTES.md
markdown
# Building notes How to to build locally and deploy to Typst app and Typst templates. ## Image quantization To reduce the size of images, which is nice for reducing the template size. ```bash pngquant *.png --ext .png --force ``` ## Integration to the official repos - Create symlink to this repository from `~/.cache/typst/packages` to `git/packages/packages/preview`. For this : ```bash ln -s ~/git/modern-isc-report ~/.cache/typst/packages/preview/isc-hei-report/0.1.5 ``` This prevents the download of packages and uses the local versions of this package. - For local testing and development, once the step above has been done, you can simply build from the `template` directory using `typst watch report.typ` - Additional testing can be conducted to see if the template instance works correctly with ```bash typst init @preview/isc-hei-report:0.1.5 ``` - Copy the content of this repos to the `typst-template` repository using ```bash cp * -R ~/git/packages/packages/preview/isc-hei-report/0.1.5/ ``` - Create PR as usual.
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/strong/strong_updated.typ
typst
*first*\ #strong[second_updated]\ *third_updated*\ #strong[forth]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/glossarium/0.4.0/README.md
markdown
Apache License 2.0
# Typst glossary > Glossarium is based in great part of the work of [<NAME>](https://github.com/Dherse) from his master thesis available at: <https://github.com/Dherse/masterproef>. His glossary is available under the MIT license [here](https://github.com/Dherse/masterproef/blob/main/elems/acronyms.typ). Glossarium is a simple, easily customizable typst glossary inspired by [LaTeX glossaries package](https://www.ctan.org/pkg/glossaries) . You can see various examples showcasing the different features in the `examples` folder. ![Screenshot](.github/example.png) ## Manual ### Import and setup This manual assume you have a good enough understanding of typst markup and scripting. For Typst 0.6.0 or later import the package from the typst preview repository: ```typ #import "@preview/glossarium:0.4.0": make-glossary, print-glossary, gls, glspl ``` For Typst before 0.6.0 or to use **glossarium** as a local module, download the package files into your project folder and import `glossarium.typ`: ```typ #import "glossarium.typ": make-glossary, print-glossary, gls, glspl ``` After importing the package and before making any calls to `gls`,` print-glossary` or `glspl`, please ***MAKE SURE*** you add this line ```typ #show: make-glossary ``` > *WHY DO WE NEED THAT ?* : In order to be able to create references to the terms in your glossary using typst ref syntax `@key` glossarium needs to setup some [show rules](https://typst.app/docs/tutorial/advanced-styling/) before any references exist. This is due to the way typst works, there is no workaround. > >Therefore I recommend that you always put the `#show: ...` statement on the line just below the `#import` statement. ### Printing the glossary First we have to define the terms. A term is a [dictionary](https://typst.app/docs/reference/types/dictionary/) composed of 2 required and 2 optional elements: - `key` (string) *required, case-sensitive, unique*: used to reference the term. - `short` (string) *required*: the short form of the term replacing the term citation. - `long` (string or content) *optional*: The long form of the term, displayed in the glossary and on the first citation of the term. - `desc` (string or content) *optional*: The description of the term. - `plural` (string or content) *optional*: The pluralized short form of the term. - `longplural` (string or content) *optional*: The pluralized long form of the term. - `group` (string) *optional, case-sensitive*: The group the term belongs to. The terms are displayed by groups in the glossary. Then the terms are passed as a list to `print-glossary` ```typ #print-glossary( ( // minimal term (key: "kuleuven", short: "KU Leuven"), // a term with a long form and a group (key: "unamur", short: "UNamur", long: "Namur University", group: "Universities"), // a term with a markup description ( key: "oidc", short: "OIDC", long: "OpenID Connect", desc: [OpenID is an open standard and decentralized authentication protocol promoted by the non-profit #link("https://en.wikipedia.org/wiki/OpenID#OpenID_Foundation")[OpenID Foundation].], group: "Accronyms", ), // a term with a short plural ( key: "potato", short: "potato", // "plural" will be used when "short" should be pluralized plural: "potatoes", desc: [#lorem(10)], ), // a term with a long plural ( key: "dm", short: "DM", long: "diagonal matrix", // "longplural" will be used when "long" should be pluralized longplural: "diagonal matrices", desc: "Probably some math stuff idk", ), ) ) ``` By default, the terms that are not referenced in the document are not shown in the glossary, you can force their appearance by setting the `show-all` argument to true. You can also disable the back-references by setting the parameter `disable-back-references` to `true`. Group page breaks can be enable by setting the parameter `enable-group-pagebreak` to `true`. You can call this function from anywhere in you document. ### Referencing terms. Referencing terms is done using the key of the terms using the `gls` function or the reference syntax. ```typ // referencing the OIDC term using gls #gls("oidc") // displaying the long form forcibly #gls("oidc", long: true) // referencing the OIDC term using the reference syntax @oidc ``` #### Handling plurals You can use the `glspl` function and the references supplements to pluralize terms. The `plural` key will be used when `short` should be pluralized and `longplural` will be used when `long` should be pluralized. If the `plural` key is missing then glossarium will add an 's' at the end of the short form as a fallback. ```typ #glspl("potato") ``` Please look at the examples regarding plurals. #### Overriding the text shown You can also override the text displayed by setting the `display` argument. ```typ #gls("oidc", display: "whatever you want") ``` ## Final tips I recommend setting a show rule for the links to that your readers understand that they can click on the references to go to the term in the glossary. ```typ #show link: set text(fill: blue.darken(60%)) // links are now blue ! ``` ## Changelog ### 0.4.0 - Support for plurals has been implemented, showcased in [examples/plural-example/main.typ](examples/plural-example). Contributed by [@St0wy](https://github.com/St0wy). - The behavior of the gls and glspl functions has been altered regarding calls on undefined glossary keys. They now cause panics. Contributed by [@St0wy](https://github.com/St0wy). ### 0.3.0 - Introducing support for grouping terms in the glossary. Use the optional and case-sensitive key `group` to assign terms to specific groups. The appearanceof the glossary can be customized with the new parameter `enable-group-pagebreak`, allowing users to insert page breaks between groups for better organization. Contributed by [indicatelovelace](https://github.com/indicatelovelace). ### 0.2.6 #### Added - A new boolean parameter `disable-back-references` has been introduced. If set to true, it disable the back-references (the page number at the end of the description of each term). Please note that disabling back-references only disables the display of the page number, if you don't have any references to your glossary terms, they won't show up unless the parameter `show-all` has been set to true. ### 0.2.5 #### Fixed - Fixed a bug where there was 2 space after a reference. Contributed by [@drupol](https://github.com/drupol) ### 0.2.4 #### Fixed - Fixed a bug where the reference would a long ref even when "long" was set to false. Contributed by [@dscso](https://github.com/dscso) #### Changed - The glossary appearance have been improved slightlyby. Contributed by [@JuliDi](https://github.com/JuliDi) ### Previous versions did not have a changelog entry
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/bibliography-01.typ
typst
Other
#set page(width: 200pt) = Details See also #cite(<distress>, supplement: [p. 22]), @arrgh[p. 4], and @distress[p. 5]. #bibliography("/works.bib")
https://github.com/Servostar/dhbw-abb-typst-template
https://raw.githubusercontent.com/Servostar/dhbw-abb-typst-template/main/src/pages/prerelease-note.typ
typst
MIT License
// .--------------------------------------------------------------------------. // | Preleminary release Notice | // '--------------------------------------------------------------------------' // Author: <NAME> // Edited: 28.06.2024 // License: MIT #let new_prerelease_note(config) = ( context { pagebreak(weak: true) let thesis = config.thesis let author = config.author if text.lang == "de" [ #heading("Vorabfassung") ] else if text.lang == "en" [ #heading("Preliminary Version") ] v(1em) if text.lang == "de" [ Bei dieser Ausgabe der Arbeit mit dem Thema ] else if text.lang == "en" [ This edition of the work with the subject ] v(1em) set align(center) text(weight: "bold", thesis.title) if thesis.subtitle != none { linebreak() thesis.subtitle } set align(left) v(1em) set par(justify: true) if text.lang == "de" [ handelt es sich _nicht_ um die fertige Fassung. Das Dokument kann Inhaltliche-, Grammatikalische- sowie Format-Fehler enthalten. Das Dokument ist im Rahmen der Aufgabenstellung von Seiten der #author.university nicht zur Bewertung freigegeben und ein anderer Verwendungszweck als eine Vorschau ist nicht gestattet. ] else if text.lang == "en" [ is not the final version. The document may contain errors in content, grammar and formatting. The document may not be released for evaluation to #author.university as part of the assignment, and any use other than a preview is not permitted. ] v(1em) h(1em) [#author.name, #datetime.today().display()] } )
https://github.com/antonWetzel/Masterarbeit
https://raw.githubusercontent.com/antonWetzel/Masterarbeit/main/arbeit/segmentierung.typ
typst
#import "setup.typ": * = Segmentierung von Waldgebieten <seperierung_in_segmente> == Ablauf FÃŒr die Segmentierung werden alle Punkte in gleich breite parallele Scheiben entlang der Höhe unterteilt. Danach werden die Scheiben von Oben nach Unten einzeln verarbeitet, um die Segmente zu bestimmen. DafÃŒr werden die Punkte in einer Scheibe zu zusammenhÀngenden Bereichen zusammengefasst. Mit den Bereichen werden die Koordinaten der BÀume bestimmt, welche in der momentanen Scheibe existieren. Die Punkte in der Scheibe werden dann dem nÀchsten Baum zugeordnet. == Bereiche bestimmen <segmentierung_bereiche_chapter> #let points = ( (0, 1.9), (-0.5, 2.0), (-0.3, 2.3), (0.4, 2.5), (0.7, 2.1), (0.6, 1.8), (-0.1, 1.6), (1.8, 1.0), (2.3, 1.1), (2.7, 1.4), (1.8, 0.8), (1.9, 0.4), (2.5, 0.5), (-0.5, -0.9), (-1.2, -1.1), (-0.8, -1.3), (-1.1, -1.9), (-0.5, -1.8), ) FÃŒr jede Scheibe werden konvexe zusammenhÀngende Bereiche bestimmt, dass die Punkte in unterschiedlichen Bereichen einen Mindestabstand voneinander entfernt sind. DafÃŒr wird der leeren Menge von Bereichen gestartet und jeder Punkt zu der Menge hinzugefÃŒgt. Wenn ein Punkt vollstÀndig in einem Bereich enthalten ist, wird der Bereich nicht erweitert. Ist der Punkt außerhalb, aber nÀher als den Mindestabstand zu einem der Bereiche, so wird der Bereich erweitert. Ist der Punkt von allen bisherigen Bereichen weiter entfernt, so wird ein neuer Bereich angefangen. Dadurch entstehen Bereiche wie in @segmentierung_bereiche. Bei einer Baumspitze entsteht ein kleiner Bereich. Wenn mehrere BÀume sich berÃŒhren, werden die zugehörigen Punkte zu einem größeren Bereich zusammengefasst. // BR06-ALS #figure( caption: [Beispiel fÃŒr berechnete Segmente fÃŒr zwei aufeinanderfolgende Scheiben.], grid( columns: 1 * 2, gutter: 1em, subfigure(rect(image("../images/test_5-areas.svg"), inset: 0pt), caption: [Höhere Scheibe]), subfigure(rect(image("../images/test_6-areas.svg"), inset: 0pt), caption: [Tiefere Scheibe]), ), ) <segmentierung_bereiche> Bei der Berechnung sind alle momentanen Bereiche in einer Liste gespeichert. Ein Bereich ist dabei eine Liste von Eckpunkten. Die Eckpunkte sind dabei sortiert, dass fÃŒr einen Eckpunkt der nÀchste Punkt entlang der Umrandung vom Bereich der nÀchste Punkt in der Liste ist. FÃŒr den letzten Punkt ist der erste Punkt in der Liste der nÀchste Eckpunkt. Um einen Punkt zu einem Bereich hinzuzufÃŒgen wird wie in @segmentierung_add_point fÃŒr jede Kante der Abstand zum Punkt bestimmt und Kanten mit positivem Abstand werden ausgetauscht. #figure( caption: [HinzufÃŒgen von einem neuen Eckpunkt zu einem Bereich.], grid( columns: 2, subfigure( caption: [Abstand berechnen], cetz.canvas(length: 1cm, { import cetz.draw: * set-style(stroke: black) line((-2, 0), (5, 0), stroke: white) line((-2, -1), (5, -1), stroke: white) line((-2, -2), (3, 3), stroke: white) line((5, -2), (0, 3), stroke: white) line((-1, -1), (0, 0), (3, 0), (4, -1), close: true, stroke: black, fill: silver) line((0, 0), (3, 0), name: "edge", mark: (end: ">", fill: black)) line((-1, -1), (0, 0)) line((3, 0), (4, -1)) content("edge.start", anchor: "north", $a$, padding: 0.15) circle((-1, -1), fill: black, stroke: none, radius: 0.1) circle((4, -1), fill: black, stroke: none, radius: 0.1) circle("edge.end", fill: black, stroke: none, radius: 0.1) content("edge.end", anchor: "north", $b$, padding: 0.15) content((1.5, 0), anchor: "north", $d$, padding: 0.15) line((0, 0), (0, 2), name: "out", mark: (end: ">", fill: black)) content((0, 1), $o$, anchor: "east", padding: 0.1) line((0, 0), (2, 1.5), stroke: gray, mark: (end: ">", fill: gray)) content((2, 1.5), anchor: "south", padding: 0.15, $p$) line((2, 0), (2, 1.5), stroke: gray) content((2, 0.75), anchor: "west", padding: 0.1, $o dot (p - a)$) circle((2, 1.5), fill: black, stroke: none, radius: 0.1) circle("edge.start", fill: black, stroke: none, radius: 0.1) }), ), subfigure( caption: [Punkt hinzufÃŒgen], cetz.canvas(length: 1cm, { import cetz.draw: * set-style(stroke: black) line((-2, 0), (5, 0), stroke: silver) line((-2, -1), (5, -1), stroke: silver) line((-2, -2), (3, 3), stroke: silver) line((5, -2), (0, 3), stroke: silver) line((-1, -1), (0, 0), (3, 0), (4, -1), close: true, stroke: none, fill: silver) line((0, 0), (3, 0), (4, -1), stroke: red) line((0, 0), (2, 1.5), (4, -1), stroke: green) line((0, 0), (-1, -1), (4, -1), stroke: black) circle((2, 1.5), fill: green, stroke: none, radius: 0.1) content((2, 1.5), anchor: "south", padding: 0.15, $p$) circle((-1, -1), fill: black, stroke: none, radius: 0.1) circle((4, -1), fill: black, stroke: none, radius: 0.1) circle((0, 0), fill: black, stroke: none, radius: 0.1) circle((3, 0), fill: red, stroke: none, radius: 0.1) }), ), ), ) <segmentierung_add_point> Um die Distanz von einem Punkt zu einem Bereich zu berechnen, wird der größte positive Abstand vom Punkt zu allen Kanten berechnet. FÃŒr jede Kante mit den Eckpunkten $a = (a_x, a_y)$ und $b = (b_x, b_y)$ wird zuerst der Vektor $d = (d_x, d_y) = b - a$ berechnet. Der normalisierte Vektor $o =1 / (norm(d)) dot (d_y, -d_x)$ ist orthogonal zu $d$ und zeigt aus dem Bereich hinaus, solange $a$ im Uhrzeigersinn vor $b$ auf der Umrandung liegt. FÃŒr den Punkt $p$ kann nun der Abstand zur Kante mit dem Skalarprodukt $o dot (p - a)$ berechnet werden. Wenn der Punkte auf der Innenseite der Kante liegt, ist der Abstand negativ. Um einen Punkt zu einem Bereich hinzuzufÃŒgen, werden alle Kanten entfernt, bei denen der Punkt außerhalb liegt, und zwei neue Kanten zum Punkt werden hinzugefÃŒgt. DafÃŒr werden die Eckpunkte entfernt, bei denen der neue Punkt außerhalb der beiden angrenzenden Kanten liegt. An der Stelle, wo die Punkte entfernt wurden, wird stattdessen der neue Eckpunkt eingefÃŒgt. #let area_figure(centers) = { import cetz.draw: * set-style(stroke: black) let points = ( (0.0, 0.0), (1.0, 0.0), (1.5, 0.6), (1.2, 0.8), (0.2, 0.8), (-0.1, 0.7), (-0.5, 0.5), (-0.5, 0.3), (-0.4, 0.1), ) let center = (0.0, 0.0) let total_area = 0.0 for i in range(1, points.len() - 1) { let a = points.at(0) let b = points.at(i) let c = points.at(i + 1) let c = ((a.at(0) + b.at(0) + c.at(0)) / 3.0, (a.at(1) + b.at(1) + c.at(1)) / 3.0) let area = (b.at(0) * c.at(1) - b.at(1) * c.at(0)) / 2.0 if centers { circle(c, fill: gray, stroke: none, radius: 0.1cm) } total_area += area; center = (center.at(0) + c.at(0) * area, center.at(1) + c.at(1) * area) } let center = (center.at(0) / total_area, center.at(1) / total_area) for i in range(0, points.len() - 1) { line(points.at(i), points.at(i + 1)) } line(points.last(), points.at(0)) for i in range(2, points.len() - 1) { line(points.at(0), points.at(i), stroke: gray) } for p in points { circle(p, fill: black, stroke: none, radius: 0.1cm) } if centers { circle(center, fill: green, stroke: none, radius: 0.1cm) let fake_center = (0.0, 0.0) for point in points { fake_center = (fake_center.at(0) + point.at(0), fake_center.at(1) + point.at(1)) } fake_center = (fake_center.at(0) / points.len(), fake_center.at(1) / points.len()) circle(fake_center, fill: red, stroke: none, radius: 0.1cm) } } == Koordinaten bestimmen FÃŒr die BÀume der momentanen Scheibe werden die Koordinaten gesucht. Die Menge der Koordinaten startet mit der leeren Menge fÃŒr die höchste Scheibe. Bei jeder Scheibe wird die Menge der Koordinaten mit den gefundenen Bereichen aktualisiert. DafÃŒr wird fÃŒr alle Bereiche in der momentanen Scheibe die FlÀche und der Schwerpunkt wie in @segmentierung_schwerpunkt berechnet. #figure( caption: [FlÀche und Schwerpunkt fÃŒr einen konvexen Bereich.], grid( columns: 1 *2, gutter: 1em, subfigure( cetz.canvas(length: 3.0cm, area_figure(false)), caption: [Bereich vollstÀndig in Dreiecke unterteilen], ), subfigure( cetz.canvas(length: 3.0cm, area_figure(true)), caption: [Werte von den Dreiecken kombinierten], ), ), ) <segmentierung_schwerpunkt> Weil die Bereiche konvex sind, können diese trivial in Dreiecke unterteilt werden. DafÃŒr wird ein beliebiger Punkt ausgewÀhlt und fÃŒr jede Kante, die nicht zum Punkt gehört, wird ein Dreieck gebildet. Die FlÀche vom Bereich ist die Summe von den FlÀchen von den Dreiecken. FÃŒr den Schwerpunkt wird fÃŒr jedes Dreieck der Schwerpunkt berechnet und dieser mit der FlÀche vom zugehörigen Dreieck gewichtet. Weil die konvexe HÃŒlle von allen Punkten in einem Bereich gebildet wird, können Bereiche sich Überscheiden, obwohl die Punkte der Bereiche den Mindestabstand voneinander entfernt sind. Bei dem HinzuzufÃŒgen von neuen Punkten werden die Bereiche sequentiell iteriert, wodurch bei ÃŒberschneidenden Bereichen der erste prÀferiert wird. Dadurch wÀchst der erste Bereich und die spÀteren Bereiche bleiben klein. Nachdem alle Punkte hinzugefÃŒgt wÃŒrden, werden deshalb die Bereiche gefiltert. Alle Bereiche mit einem Zentrum in einem anderen Bereich oder einer FlÀche kleiner als ein Schwellwert werden entfernt. Danach werden die Koordinaten aus den vorherigen Scheiben mit den Schwerpunkten der Bereiche von der momentanen Scheibe aktualisiert. FÃŒr jede Koordinate wird der nÀchste Schwerpunkt nÀher als die zweifache Maximaldistanz bestimmt. Wenn ein naher Schwerpunkt gefunden wurde, wird die Koordinate mit der Position vom Schwerpunkte aktualisiert. Wenn kein naher Schwerpunkt existiert, so bleibt die Position gleich. FÃŒr alle Schwerpunkte, welche nicht nah an einer der vorherigen Koordinaten liegen, wird ein neues Segment angefangen. DafÃŒr wird der Schwerpunkt zur Liste der Koordinaten hinzugefÃŒgt. == Punkte zuordnen Mit den Koordinaten wird das Voronoi-Diagramm berechnet, welches den Raum in Bereiche unterteilt, dass alle Punkte in einem Bereich fÃŒr eine Koordinate am nÀchsten an dieser Koordinate liegen. FÃŒr jeden Punkt wird nun der zugehörige Bereich im Voronoi-Diagramm bestimmt und der Punkt zum zugehörigen Segment zugeordnet. Ein Beispiel fÃŒr so eine Unterteilung ist in @segmentierung_voronoi zu sehen. #figure( caption: [Berechnete Koordinaten fÃŒr die Punkte mit zugehörigen Bereichen und Voronoi-Diagramm.], grid( columns: 1 * 2, gutter: 1em, subfigure(rect(image("../images/test_5-moved.svg"), inset: 0pt), caption: [Höhere Scheibe]), subfigure(rect(image("../images/test_6-moved.svg"), inset: 0pt), caption: [Tiefere Scheibe]), ), ) <segmentierung_voronoi> Der Ablauf wird fÃŒr alle Scheiben von Oben nach Untern durchgefÃŒhrt, wodurch alle Punkte zu Segmenten zugeordnet werden. In @segment_example ist die Segmentierung fÃŒr eine Punktwolke gegeben. Die unterschiedlichen Segmente sind durch unterschiedliche EinfÀrbung der zugehörigen Punkte markiert. #figure( caption: [Segmentierung von einem Waldgebiet.], image("../images/auto-crop/segments-br05-als.png"), ) <segment_example>
https://github.com/0x1B05/english
https://raw.githubusercontent.com/0x1B05/english/main/cnn10/content/20240304.typ
typst
#import "../template.typ": * = 20240304 What's up lovely people! Hope you've had an awesome weekend. Let's start this week strong with some motivation Monday. Remember #strike[complacency] #underline[complacency] is the constant enemy, so let's learn one thing or do something that #strike[makes] #underline[will make] us a little better today than we were yesterday. I'm Coy Wire, this is CNN10. == Korean doctors We start with doctors protesting--thousands of doctors taking to the street in #strike[South of Korea] #underline[_Seoul, South Korea_], expressing support for the many more thousands of doctors who have been on #strike[straight] #underline[*strike*] for nearly two weeks. This all because the government's plan to increase medical school admissions. The plan includes increasing the country's medical school #strike[and ...] #underline[*enrollment*] by 2,000#underline[,] starting in the 2025 _academic year_. That will bring the total to about 5,000 per year. The government says this plan is to help #strike[me] #underline[meet] the challenging #strike[health care] #underline[*healthcare*] demands #strike[the] #underline[as] South Korea faces, one of the lowest doctor #underline[to] population ratios for a developed country. But doctors disagree with government's method _in believes_ their medical school system can not _handle of_ #strike[fast] #underline[vast] increased educating and training new medical students. Also they're concerned that proposed plan does not include _staffing_ in specific fields that have already been #strike[seen] #underline[seeing] a shortage such as #underline[*pediatrics*] and the emergency departments. Doctors are also worried that the addition of new doctors will lead to increase public medical expenses. But this protest have not really won public support. A recent survey showed a majority of the South #strike[Korea's] #underline[Koreans] #strike[outsiding] #underline[are siding] with government's plan #strike[was some critical sane.] #underline[with some critics saying,] doctors are just worried about receiving a lower income now with more competition in the field. With the strike _ongoing_, the country health ministry says the government has allowed military doctors and nurses to perform some medical procedures#strike[,] normally performed by these striking doctors. === words, phrases and sentences ==== words - _academic year_ - _Seoul_ - _staff_ - _pediatric_ - _expense_ - _ongoing_ ==== phrases - _meet demands_ - _on strike_ - _a to b ratios_ - _in believes that ..._ - _a majority of ..._ - _side with_ - _perform procedures_ === 回译 ==== 原文 What's up lovely people! Hope you've had an awesome weekend. Let's start this week strong with some motivation Monday. Remember complacency is the constant enemy, so let's learn one thing or do something that will make us a little better today than we were yesterday. I'm <NAME>, this is CNN10. We start with doctors protesting--thousands of doctors taking to the street in Seoul, South Korea, expressing support for the many more thousands of doctors who have been on strike for nearly two weeks. This all because the government's plan to increase medical school admissions. The plan includes increasing the country's medical school enrollment by 2,000, starting in the 2025 academic year. That will bring the total to about 5,000 per year. The government says this plan is to help meet the challenging healthcare demands as South Korea faces, one of the lowest doctor to population ratios for a developed country. But doctors disagree with government's method in believes their medical school system can not handle of vast increased educating and training new medical students. Also they're concerned that proposed plan does not include staffing in specific fields that have already been seeing a shortage such as pediatrics and the emergency departments. Doctors are also worried that the addition of new doctors will lead to increase public medical expenses. But this protest have not really won public support. A recent survey showed a majority of the South Koreans are siding with government's plan with some critics saying, doctors are just worried about receiving a lower income now with more competition in the field. With the strike ongoing, the country health ministry says the government has allowed military doctors and nurses to perform some medical procedures normally performed by these striking doctors. ==== 参考翻译 倧家奜垌望䜠们床过了愉快的呚末。让我们以充满劚力的星期䞀匀始这䞪新的䞀呚。记䜏自满是我们的氞恒敌人所以让我们孊习䞀件事或做䞀些让自己比昚倩曎奜的事情。我是Coy Wire这里是CNN10。 我们从医生抗议匀始。成千䞊䞇名医生走䞊銖尔的街倎衚蟟对已经眢工近䞀呚的成千䞊䞇名医生的支持。这䞀切郜是因䞺政府计划增加医孊院的招生计划。该计划包括从2025孊幎匀始增加该囜的医孊院招生2000人这将䜿每幎的招生总数蟟到纊5000人。政府衚瀺这䞀计划旚圚垮助满足韩囜面䞎的挑战性医疗需求因䞺韩囜的医生人口比䟋是发蟟囜家䞭最䜎的之䞀。䜆医生们䞍同意政府的方法他们讀䞺他们的医孊院系统无法承受劂歀倧规暡的增加教育和培训新的医孊生。他们还担心拟议的计划䞍包括圚已经出现短猺的特定领域的人员配倇劂儿科和急诊科。医生们还担心增加新医生将富臎公共医疗莹甚的增加。䜆这次抗议并没有真正赢埗公䌗的支持。最近的䞀项调查星瀺倧倚数韩囜人支持政府的计划䞀些批评人士称医生只是担心圚这䞪领域面䞎曎倚竞争后收入䌚减少。圚眢工持续进行的同时该囜卫生郚衚瀺政府已允讞军队医生和技士执行䞀些通垞由这些眢工医生执行的医疗皋序。 ==== 1st What's up lovely people. Hope you #underline[have] had a happy weekend. Let's start this week from this energetic Monday. Remember complacency is our constant enemy, so let's #strike[study] #underline[learn] one #underline[thing] or do something that #strike[makes] #underline[will make] us a little better than we were yesterday. I'm Coy Wire, this is CNN10. We start with #strike[the] doctors protesting, thousands of doctors #strike[walked] #underline[taking] to the street #strike[of Soer] #underline[in Seoul, South Korea], expressing the support of #underline[many more] thousands of doctors who have been on strike for #strike[about] #underline[nearly] 2 weeks. #underline[This] all because the government #strike[are going] #underline[is plan] to increase #strike[the medical students enrollment] #underline[medical school admissions]. The plan includes #strike[increasement] #underline[increasing] #strike[about 2,000 students in medical school] #underline[the country's medical enrollment by 2,000, starting in the 2025 academic year.]#strike[, leading to the total number of the enrollment in medical school arriving about 5,000.]#underline[That will bring the total to about 5,000 per year.] The government says, the plan aims at helping Korean meet the challenging #strike[medical] #underline[*healthcare*] demands they are facing#strike[, for Korean has a lowest doctor ratio of population among the developed country.] #underline[, one of the lowest doctor to population ratios for a developed coutry.] But doctors #strike[don't agree] #underline[disagree] with #strike[the method the government are taking] #underline[the government's method]#strike[, they think] #underline[in believes] the medical system can't #strike[burden the increasement of new medical students who need to be educated and trained on such a scale.] #underline[_handle of vast increased educating and training new new medical students._] #strike[They also concern, the plan doesn't include the staff of the particular field that has a lack of people such as ... and emergency...] #underline[_They're concerned_ that proposed plan does not include staffing in specific fields that have already been seeing a shortage such as pediatrics and the emergency departments.] #strike[They also concern the cost for public medical ... will increase after the plan.] #underline[They are also worried that *the addition of new doctors* will lead to increase *public medical expense*.] But this protest doesn't win #strike[the support of people] #underline[public support]. A recent survey shows #strike[most Koreans] #underline[a majority of the South Koreans] #strike[support this plan. Some] #underline[*are siding with* government's plan with some] critics says, doctors are just #strike[concerning] #underline[worried about] #strike[their income will decrease after the more competition come in this field] #underline[receiving a lower income now with more competition in the field]. #strike[When the strike is on]#underline[With the strike ongoing], the #underline[*country health ministry*] says, the government has allowed the military doctors and nurses to #strike[do] #underline[perform] some medical #strike[processes] #underline[procedures] #strike[usually] #underline[*normally*] #strike[executed] #underline[performed] by these #strike[doctors on strike] #underline[striking doctors]. == Weather All right, let's turn now to weather as we first head to #underline[*Sierra Nevada*] mountain region#underline[, where *blizzard*] conditions continue to *slam* the area. Dangerous#underline[, *fierce*] winds #underline[of] more than 75 miles per hour#underline[,] _as well as_ the heavy snowfall #strike[threaten the ... of] #underline[*threatened* to *dump up* to] ten feet of snow in the mountain, has forced the officials to close down roads and impact travel. Many #strike[results] #underline[resorts] on the California#underline[-Nevada border] are also shut down, and about 6 million people in that region #underline[are in] a winter alert. And let's head to another region, the #underline[*Texas Panhandle*] continuing to be #underline[*ravaged*] by the extremely hot and dry conditions, as the biggest #underline[*inferno*] in Texas history #underline[rages on.] The #strike[smoke ..] #underline[Smokehouse Creek] Fire has been #strike[burnt] #underline[burning] for nearly a week now, and destroyed more than 1 million #underline[acres] in the #strike[state of taxies] #underline[State of Texas] alone. It's a scary and #underline[*devastating*] reality many #strike[taxiers] #underline[Texans] are dealing with. Let's turn to our Camila Bernal for more: It's been windy. It is hot, a lot hotter than it's been over the last couple of days. And it's #underline[dry,] conditions #underline[that] are making #underline[it] extremely difficult for firefighters in this area that still battling the largest #underline[wild]fire in Texas history#strike[ containment. It's] #underline[. *Containment* is] still very low, so there's a lot of work to be done. And #strike[at] #underline[in] the meantime, you have that #strike[graving] #underline[grieving] process beginning for a lot of families that have lost everything#strike[,] #underline[but] the cleanup process. And like, you #underline[are] seeing behind me #strike[is] #underline[at] Johnson house, and it's been difficult to do that cleanup _because the wind have been so high_. But #strike[nevertheless] #underline[nonetheless], #strike[you've seen] #underline[you're seeing] them right now they are trying to #underline[*sift* that *debris*], trying to look for #strike[every] #underline[any] jewellery, anything they can find of #strike[the] #underline[what was] left of their home, the home that they have built for over 20 years. I want #underline[want you to listen to what Ronnie] Johnson told me when #strike[you] #underline[he] first got here to his home after the fire. We came back at 10:30 that night. #underline[We kind of *snuck through some ranches* to drive up here and see it gone. This was pretty tough.] And you can hear the emotion#strike[ that's] #underline[. It's] been so difficult for members of this community. It also had a huge impact on the cattle industry here, because 85% percent of #strike[states] #underline[state's] cattle is raised here in #underline[the Panhandle.] And so a lot of #underline[*ranchers*] are also having to start from zero and have shared the struggle both emotionally and #underline[*financially*]. They know it's going to take a long time to get back where they were before those fires. === words, phrases and sentences ==== words - _blizzard_ - _fierce_ - _threaten_ - _ravage_ - _inferno_ - _devastating_ - _containment_ - _sift_ - _debris_ - _sneak (snuck in U.S.)_ - _ranch_ - _cattle_ ==== phrases - _slam the area_ - _dump up_ - _rage on_ - _in the meantime_ ==== sentences - Dangerous, fierce winds of more than 75 miles per hour, _as well as_ the heavy snowfall threatened to dump up to ten feet of snow in the mountain, has forced the officials to close down roads and impact on travel. - The Texas Panhandle continuing to be *ravaged* by the extremely hot and dry conditions, as the biggest *inferno* in Texas history _rages on_. - The wind have been so *high*. - A lot of ranchers have shared the struggle both emotionally and financially. === 回译 ==== 原文 All right, let's turn now to weather as we first head to Sierra Nevada mountain region, where blizzard conditions continue to slam the area. Dangerous, fierce winds of more than 75 miles per hour, as well as the heavy snowfall threatened to dump up to ten feet of snow in the mountain, has forced the officials to close down roads and impact travel. Many resorts on the California-Nevada border are also shut down, and about 6 million people in that region are in a winter alert. And let's head to another region, the Texas Panhandle continuing to be ravaged by the extremely hot and dry conditions, as the biggest inferno in Texas history rages on. The Smokehouse Creek Fire has been burning for nearly a week now, and destroyed more than 1 million acres in the State of Texas alone. It's a scary and devastating reality many Texans are dealing with. Let's turn to our Camila Bernal for more: It's been windy. It is hot, a lot hotter than it's been over the last couple of days. And it's dry, conditions that are making it extremely difficult for firefighters in this area that still battling the largest wildfire in Texas history . Containment is still very low, so there's a lot of work to be done. And in the meantime, you have that grieving process beginning for a lot of families that have lost everything but the cleanup process. And like, you are seeing behind me at Johnson house, and it's been difficult to do that cleanup because the wind have been so high. But nonetheless, you're seeing them right now they are trying to sift that debris, trying to look for any jewellery, anything they can find of what was left of their home, the home that they have built for over 20 years. I want want you to listen to what <NAME> told me when he first got here to his home after the fire. We came back at 10:30 that night. We kind of snuck through some ranches to drive up here and see it gone. This was pretty tough. And you can hear the emotion . It's been so difficult for members of this community. It also had a huge impact on the cattle industry here, because 85% percent of state's cattle is raised here in the Panhandle. And so a lot of ranchers are also having to start from zero and have shared the struggle both emotionally and financially. They know it's going to take a long time to get back where they were before those fires. ==== 参考翻译 现圚让我们蜬向倩气銖先我们来到内华蟟山脉地区那里暎风雪条件持续肆虐。超过每小时75英里的危险猛烈风速以及倧雪嚁胁可胜䌚圚山区堆积倚蟟十英尺的积雪已迫䜿官员关闭道路并圱响旅行。加州和内华蟟州蟹境的讞倚床假胜地也关闭了该地区纊有600䞇人倄于冬季譊报状态。 接䞋来我们蜬向及䞀䞪地区執克萚斯州的Panhandle地区持续受到极端炎热和干燥条件的摧残因䞺執克萚斯州历史䞊最倧的山火继续肆虐。Smokehouse Creek Fire已经燃烧了将近䞀䞪星期仅圚執克萚斯州就摧毁了100倚䞇英亩的土地。这是埈倚執克萚斯人正圚应对的可怕而毁灭性的现实。让我们听听我们的Camila Bernal的报道 风势埈倧。倩气非垞炎热比过去几倩芁热埗倚。而䞔非垞干燥这种条件䜿埗圚这䞪地区的消防员们面䞎极倧困隟他们仍圚䞎執克萚斯历史䞊最倧的山火䜜斗争。控制火势的进展仍然埈慢。所以还有埈倚工䜜芁做。同时讞倚家庭已经匀始了倱去䞀切的悲痛过皋枅理过皋也已经匀始。就像䜠圚我身后看到的纊翰逊家庭由于风势倪倧枅理工䜜变埗非垞困隟。䜆尜管劂歀䜠现圚看到他们正圚努力枅理残骞试囟寻扟任䜕銖饰任䜕他们胜扟到的残留圚家䞭的物品这是他们建造了20倚幎的家。我想让䜠们听䞀䞋<NAME>告诉我的他倧火后第䞀䞪回到家看到的景象。 我们晚䞊10:30回来的。我们圚䞀些农场闎穿行偷偷来到这里结果发现家已经䞍圚了。这真是倪隟了。 䜠可以听到他的情绪。对于这䞪瀟区的成员来诎这䞀切郜非垞艰隟。这也对这里的牛肉产䞚产生了巚倧圱响因䞺執克萚斯州85%的牛矀圚Panhandle饲养。因歀讞倚牧场䞻也䞍埗䞍从零匀始他们圚情感和经济䞊郜承受着巚倧的压力。他们知道芁恢倍到火灟前的状态需芁埈长时闎。 ==== 1st Now let's turn #underline[now] to weather#strike[. First we come] #underline[as we first head] to the Sierra Nevada mountain region, where #strike[snowstorm] #underline[*blizzard*] conditions #strike[raged on] #underline[slam the area] constantly. #strike[The wind blew over 75 miles per hour and the snowstorm continuously threatened, which may dump up snow over 10 feet and] #underline[Dangerous, fierce winds of more than 75 miles per hour, as well as the heavy snowfall threatened to dump up to ten feet of snow in the mountain,] has forced the officials #underline[to] closed down the road and impact travel. Many resorts on board of California-Nevada are #strike[closed] #underline[*shut down*]#strike[. There are] #underline[and] about 6 million people #underline[in that region are] in #strike[winter alarm] #underline[a winter alert]. Then we turn to another region, the Texas Panhandle #strike[in ... are threatened by the extreme hot and dry conditions for the mountain fire constantly raging on.] #underline[continuing to be ravaged by the extremely hot and dry conditions, as the biggest inferno in Texas history rages on.] The Smokehouse Creek Fire has been #strike[on fire] #underline[burning] for #strike[about] #underline[nearly] a week, #strike[destroying] #underline[and destroyed] more than 1 million acres in the State of Texas alone. #strike[This is a miserable and destructive fact that many ... are confronting.] #underline[It's a scary and devastating reality many Texans are dealing with.] Let's #strike[hear] #underline[turn to] the report from <NAME> #underline[for more]: The wind blows heavily. #strike[The air] #underline[It] is very hot, #underline[a lot] hotter than #strike[the days before] #underline[it's been over the last couple of days]. And it is #strike[so] dry #strike[that firefighters in this region are facing such difficulties and they are still combating with the largest mountain fire in ...] #underline[, conditions that are making it extremely difficult for firefighters in this area that still battling the largest wildfire in Texas history.] #strike[But the fire-controlling process] #underline[Containment] is very slow, so there's a lot of work to #strike[do] #underline[be done]. #strike[Simultaneously] #underline[In the meantime], #strike[many families begin to pain for the loss of everything, the cleanup starting.] #underline[you have that grieving process beginning for a lot of families that have lost everything but the cleaner process.] #strike[As you see behind me was the ..., the cleanup becomes more difficult for the heavy wind.] #underline[And like, you're seeing behind me at Johnson house, and it's been difficult to do that cleanup because the wind have been so high.] But nonetheless, you #strike[can see] #underline[are seeing] they are trying to #strike[clean the remains] #underline[*sift* that debris], trying to find any jewellery or anything #strike[else] #underline[they can find of what was left of their home]#strike[. This is their 20 years' house.] #underline[, the home they've built for over 20 years.] I want you to listen to what <NAME> told me when he got home first after the fire. We came back at 10:30 #strike[at] #underline[that] night. We snuck through some #strike[farms] #underline[ranches], and got here, then #strike[found the house missing] #underline[saw it gone]. It's pretty tough. You can hear their emotion. #strike[All are] #underline[It's been so] tough #strike[to] #underline[for] the members of the community. And that also has an impact on the #strike[cow] #underline[cattle] industry, because 85% of California's cattle #strike[are] #underline[is] raised here in the Panhandle. So many owner of farms have to from zero, who are burdening huge press. They know it #strike[takes] #underline[will take] a long time to #strike[recover] #underline[get back where they were before those fires]. == Supersonic aircraft All right, you might remember we were talking about the speed of sound about a month ago#strike[. When] #underline[when] we mentioned the development of new supersonic plane. #strike[we will take it] #underline[We're taking] a closer look today#strike[. And] #underline[at] what #strike[air spacing] #underline[*aerospace* and] defense company, *Lockheed Martin* has built #strike[an ...] #underline[and *debuted*] for NASA. The experimental plane is called X-59, and it's a #strike[quite] #underline[quiet] supersonic aircraft. NASA is looking to possibly #strike[evolutionize] #underline[revolutionize] the air #strike[travelling] #underline[travel] industry#strike[ by] #underline[. And by] that#underline[, I] mean go really fast, so fast that it could travel faster than the speed of sound. Take a look #underline[at] this piece, *profiling* the X-59: This is the X-59 *quest*, a new plane built by <NAME> for NASA. NASA is hoping it would be #strike[a solover of] #underline[able to solve a] problem that has stopped commercial air plane from flying really really fast, that's because: When #strike[the] #underline[an] aircraft goes supersonic, faster than the speed of sound, it create shockwaves. When I heard the sonic boom for the first time, I finally understood why it was such a big deal. If something's travelling #strike[supersonicly] #underline[*supersonically*], you can see it coming but you won't hear it at all until it has already passed you. As you could imagine, sonic booms can be #strike[desruptive] #underline[*disruptive*] to life on the ground, so #strike[... 131953] #underline[disruptive that in 1973], the United States government #strike[alone] #underline[along] with much of the world #strike[ban] #underline[banned] all #strike[Soviet...] #underline[*civilian*] aircraft from supersonic #underline[flight] overland. For the U.S., it's a speed limit. The only #underline[civilian] jet #underline[to *ferry*] passengers faster than the speed of sound was the *Concorde*. It is #strike[the] only able to fly over the ocean supersonic. So you could do London to New York, but you had to slow down before you got to New York #underline[and be *subsonic*.] So the #strike[arrival ... is] #underline[*routes* were very] limited. The Concorde was a *celebrated* #strike[technology] #underline[technical] achievement, and _an exclusive luxury_ for its passengers. Limited #underline[roots] and heavy fuels consumption #underline[meant that] operating the Concorde was not #strike[good. Business however] #underline[good business. However], it #underline[stopped flying] in 2003. But if supersonic airplane could fly overland, they can fly anywhere, and the *business proposition* changes. NASA and <NAME> are hoping this crazy looking airplane is a step in that direction. It is designed to go supersonic without making the loud sonic boom, we've #underline[been *accustomed*] to hearing for decades now. To understand how this might work, it's important to understand how a sonic boom happens. Just like a #strike[boom] #underline[boat], when the #strike[boom] #underline[boat] is moving, you get the #strike[way coming...] #underline[weight coming off of it], and it's #strike[worthy] #underline[with it] the entire time #strike[of] #underline[it's] travelling. Similarly for supersonic aircraft, the shockwaves *come off* the aircraft and travel to the ground the entire time #underline[it's flying supersonic.] So when engineers designed the X-59, #strike[the use of] #underline[they used] smooth and long #strike[air dynamic] #underline[aerodynamic] lines to limit their shockwaves from reaching the ground. The engine is above the wing, and that's so #underline[that] the shock wave from the engine isn't able to go down to the ground #strike[when it] #underline[. It] just goes up. It is still #underline[*audible*] like a quiet #underline[*thump*.] And most people, if them hear it, won't even notice it. NASA is aiming for a first test flight #strike[to] #underline[of] the X-59 in the spring of 2024. *Poetically*, over the #underline[the same patch] of California desert where *Chuck Yeager* first #strike[brought ...] #underline[*broke the sound barrier*] in the X-1. NASA #underline[can take] that data, #strike[they ...] #underline[and then] be able to present that to the #strike[regular] #underline[*regulatory*] authorities to actually *repeal* the overland supersonic #underline[limitations] #strike[they have to] #underline[or was that we have today.] A #strike[changing regulation] #underline[change in regulation] could #strike[leave] #underline[lead to] a #strike[surgeon] #underline[*surge* of] investment #strike[to] #underline[in] the next generation of commercial supersonic aircraft, making travel faster than the speed of sound#underline[,] more accessible to everyone. And that could send massive shockwaves to the air travel industry. Shockwaves that the NASA and Lockheed Martin hope will sound more like #underline[*thump*.] === words, phrases and sentences ==== words - _supersonic_ - _aerospace_ - _debut_ - _profile_ - _supersonically_ - _disruptive_ - _civilian_ - _ferry_ - _subsonic_ - _route_ - _exclusive_ - _celebrated_ - _business proposition_ - _aerodynamic_ - _audible_ - _thump_ - _poetically_ - _regulatory_ - _repeal_ - _regulation_ ==== phrases - _come off_ - _a surge of_ ==== sentences - _This crazy looking airplane is a step in that direction._ - _Similarly for supersonic aircraft,..._ - _That could send massive shockwaves to the air travel industry._ === 回译 ==== 原文 All right, you might remember we were talking about the speed of sound about a month ago when we mentioned the development of new supersonic plane. We're taking a closer look today at what aerospace and defense company, Lockheed Martin has built and debuted for NASA. The experimental plane is called X-59, and it's a quiet supersonic aircraft. NASA is looking to possibly revolutionize the air travel industry . And by that, I mean go really fast, so fast that it could travel faster than the speed of sound. Take a look at this piece, profiling the X-59: This is the X-59 quest, a new plane built by Lockheed Martin for NASA. NASA is hoping it would be able to solve a problem that has stopped commercial air plane from flying really really fast, that's because: When an aircraft goes supersonic, faster than the speed of sound, it create shockwaves. When I heard the sonic boom for the first time, I finally understood why it was such a big deal. If something's travelling supersonically, you can see it coming but you won't hear it at all until it has already passed you. As you could imagine, sonic booms can be disruptive to life on the ground, so disruptive that in 1973, the United States government along with much of the world banned all civilian aircraft from supersonic flight overland. For the U.S., it's a speed limit. The only civilian jet to ferry passengers faster than the speed of sound was the Concorde. It is only able to fly over the ocean supersonic. So you could do London to New York, but you had to slow down before you got to New York and be subsonic. So the routes were very limited. The Concorde was a celebrated technical achievement, and an exclusive luxury for its passengers. Limited roots and heavy fuels consumption meant that operating the Concorde was not good business. However, it stopped flying in 2003. But if supersonic airplane could fly overland, they can fly anywhere, and the business proposition changes. NASA and Lockheed Martin are hoping this crazy looking airplane is a step in that direction. It is designed to go supersonic without making the loud sonic boom, we've been accustomed to hearing for decades now. To understand how this might work, it's important to understand how a sonic boom happens. Just like a boat, when the boat is moving, you get the weight coming off it, and it's with it the entire time it's travelling. Similarly for supersonic aircraft, the shockwaves come off the aircraft and travel to the ground the entire time it's flying supersonic. So when engineers designed the X-59, they used smooth and long aerodynamic lines to limit their shockwaves from reaching the ground. The engine is above the wing, and that's so that the shock wave from the engine isn't able to go down to the ground . It just goes up. It is still audible like a quiet thump. And most people, if them hear it, won't even notice it. NASA is aiming for a first test flight of the X-59 in the spring of 2024. Poetically, over the same patch of California desert where Chuck Yeager first broke the sound barrier in the X-1. NASA can take that data, and then be able to present that to the regulatory authorities to actually repeal the overland supersonic limitations or was that we have today. A change in regulation could lead to a surge of investment in the next generation of commercial supersonic aircraft, making travel faster than the speed of sound, more accessible to everyone. And that could send massive shockwaves to the air travel industry. Shockwaves that the NASA and Lockheed Martin hope will sound more like thump. ==== 参考翻译 也讞䜠还记埗倧纊䞀䞪月前我们谈论过声速时提到了新超音速飞机的匀发今倩我们将曎诊细地了解䞀䞋航空航倩和囜防公叞Lockheed Martin䞺矎囜囜家航空航倩局NASA建造和銖次亮盞的新型实验飞机X-59。这架实验飞机被称䞺X-59是䞀种静音超音速飞机。NASA垌望胜借圻底改变航空旅行䞚我的意思是实现真正的快速。劂歀之快以至于胜借比声速曎快地行进。让我们来看䞀䞋这篇介绍X-59的文章 这就是X-59探玢者䞀架由Lockheed Martin䞺NASA建造的新型飞机。NASA垌望它胜借解决商甚飞机䞍让飞行非垞快的问题原因是 圓飞机超音速行进时快于声速䌚产生冲击波。圓我第䞀次听到音爆时我终于明癜䞺什么这是䞪倧问题了。劂果某物以超音速行进䜠可以看到它䜆盎到它已经经过䜠了䜠才䌚听到声音。䜠可以想象音爆䌚对地面生掻造成干扰。1973幎矎囜政府䞎䞖界䞊讞倚囜家䞀起犁止所有民甚飞机圚陆地䞊进行超音速飞行。对于矎囜来诎这是䞀种速床限制。 唯䞀䞀架运送乘客超音速的民甚喷气匏飞机是协和匏飞机(Concorde)。它只胜圚海䞊进行超音速飞行。所以䜠可以从䌊敊飞埀纜纊䜆䜠必须圚抵蟟纜纊之前减速蜬䞺次音速飞行。因歀航线非垞有限。Concorde是䞀项倇受赞誉的技术成就也是其乘客的独特奢䟈享受。有限的航线和高油耗意味着运营协和匏飞机并䞍划算。然而它圚2003幎停止飞行。䜆是劂果超音速飞机胜借圚陆地䞊飞行它们可以飞埀任䜕地方商䞚提案就䌚发生变化。 NASA和Lockheed Martin垌望这架看起来埈疯狂的飞机是朝着这䞪方向迈出的䞀步。它被讟计䞺圚超音速行进时䞍发出我们几十幎来习以䞺垞的巚倧音爆。芁理解这种原理了解声爆是劂䜕发生的埈重芁。就像䞀艘船圓船圚移劚时它垊着船身䞊的重量䞀起移劚。同样对于超音速飞机冲击波从飞机䞊脱萜并圚敎䞪超音速飞行期闎䌠播到地面。因歀圓工皋垈讟计X-59时他们䜿甚了光滑䞔长的空气劚力孊线条来限制冲击波到蟟地面。发劚机于机翌䞊方这样发劚机产生的冲击波就无法䌠播到地面只䌚向䞊䌠播。它仍然是可听到的像䞀䞪蜻埮的隆隆声。倧倚数人劂果听到了甚至郜䞍䌚泚意到。 NASA计划于2024幎春季进行X-59的銖次试飞。诗意地就圚加利犏尌亚沙挠的同䞀块地方<NAME>銖次圚X-1䞊突砎音障时。NASA可以利甚这些数据然后向监管机构提䟛以实际废陀我们今倩所面䞎的超音速飞行限制。 法规的变化可胜䌚富臎䞋䞀代商甚超音速飞机的投资激增䜿超音速飞行对每䞪人郜曎加普遍。这可胜䌚给航空旅行䞚垊来巚倧的冲击波。NASA和Lockheed Martin垌望这些冲击波听起来曎像是隆隆声。 ==== 1st Maybe you still remember #strike[we've talked] #underline[we were talking] about the speed of sound #strike[last month] #underline[about a month ago]#strike[,] #underline[when] we mentioned the development of supersonic plane. Today we #strike[are going to learn more about the new experimental plane X-59 which debuted and was built by Lockheed Martin]#underline[are taking a closer look today at what aerospace and defense company, Lockheed Martin has built and debuted] for NASA. This experimental plane was called X-59, a kind of #underline[quiet] supersonic plane. NASA is #strike[hoping] #underline[looking] to revolutionize the #strike[plane travelling] #underline[air travel] industry#strike[, which means implement the real speed] #underline[. And by that, I mean go really fast], so fast that it #strike[can drive] #underline[could travel] faster than the speed of sound. Let's take a look at #strike[the article about] #underline[this piece, profiling] X-59: This is the X-59 quest, a new kind of plane built by Lockheed Martin for NASA. NASA is hoping it #strike[can] #underline[would] solve the problem #strike[of the business plane speed limitation] #underline[that has stopped comercial air plan from flying really really fast], that's because: When a #strike[plane] #underline[aircraft] #strike[travels supersonicly] #underline[goes supersonic], faster than the speed of sound, it will create shockwaves. When I first heard of the #strike[shockwaves] #underline[sonic boom], I finally understood why it's #strike[a big problem] #underline[such a big deal]. If something #strike[travels] #underline[is travelling] supersonicly, you can see it #underline[coming], but you won't hear anything until it passed you. As you #strike[can] #underline[could] imagine, #strike[shockwaves] #underline[sonic booms] #strike[will] #underline[can] be disruptive to the life on the ground#strike[. American] #underline[, so disruptive that in 1973, the United States] government along with #strike[many other countries across] #underline[much of] the world #strike[prohibited] #underline[banned] #strike[the] #underline[all] civilian aircraft from #strike[travelling supersonicly over the land in 1973] #underline[supersonic flight overland]. #strike[To] #underline[For] the U.S., it's a kind of speed limit. The only civilian jet #strike[that is allowed] to #strike[carry] #underline[*ferry*] passengers is Concorde, but it is only enable to travel supersonic over the sea. So you #strike[can fly from] #underline[could do] London to New York, but before arriving New York, you #strike[must] #underline[got to] slow down #underline[and be subsonic], owing to which the routes are limited. Concorde is a #underline[*celebrated*] technical achievement#strike[ full of credit] #underline[, and an exclusive luxury for its passengers]. Limited routes and high fuel consumption #underline[meant that operating the Concorde was not goo business.] However it #strike[has been] stopped flying #strike[from] #underline[in] 2003. But if supersonic aircraft could fly #strike[over the land] #underline[overland], they can fly anywhere, and the #strike[future of business] #underline[business proposition] will change. NASA and <NAME> are hoping this crazy looking airplane is a step in that direction. It is designed #underline[without makeing the loud sonic boom we've been accustomed to for decades]. To understand #strike[this principle] #underline[how this might work], it is important to #strike[know how shockwaves are made] #underline[how a sonic boom happen]. Just like a boat, #strike[it moves along along with its weight] #underline[when the boat is moving, you get the weight coming off it and it's with it the entire time it's travelling]. Similarly, #strike[to] #underline[for] supersonic aircraft, shockwaves come off the plane and #strike[transport] #underline[travel] to the ground #strike[when] #underline[the entire time] it is flying. So when engineers are designing X-59, they limited shockwaves #strike[arriving at] #underline[from reaching the] ground with smooth and long aerodynamic lines. The engine is above the wing, so shockwaves from it #strike[can't spread] #underline[isn't able to go down] to the ground #strike[which] #underline[. It] only can go #strike[above] #underline[up]. It is still audible, like a slight thump. Most people won't notice it even they have heard of it. NASA #strike[are planing] #underline[is aiming for] #strike[the first fly] #underline[a first flight] of X-59 in the spring of 2024. Poetically, #strike[in] #underline[over] the same #strike[place] #underline[patch] of California desert, where Chuck Yeager first broke the sound barrier in the X-1. NASA can #strike[exploit it can provide] #underline[take that data, and then be able to present] it to the #strike[regulation organization] #underline[regulatory authorities] to repeal the #underline[overland supersonic] limitations #strike[in the speed of supersonic plane] we are confronting today. The changes in regulation could lead to a #strike[boom in ...] #underline[surge of investment] in the next generation of #strike[business] #underline[commercial] supersonic aircraft, #strike[which makes] #underline[making travel faster than the speed of sound], more accessible to everyone. It has a potential to #strike[bring a] #underline[send a massive] shockwave to the air travel industry. NASA and Lockheed Martin hopes #strike[these shockwaves are more like thump] #underline[will sound more like thump].
https://github.com/hitszosa/universal-hit-thesis
https://raw.githubusercontent.com/hitszosa/universal-hit-thesis/main/harbin/bachelor/pages/achievement.typ
typst
MIT License
#import "../config/constants.typ": special-chapter-titles #let achievement( content, ) = [ #heading(special-chapter-titles.成果, level: 1, numbering: none) #content ]
https://github.com/Otto-AA/dashy-todo
https://raw.githubusercontent.com/Otto-AA/dashy-todo/main/README.md
markdown
MIT No Attribution
# Dashy TODO Create TODO comments, which are displayed at the sides of the page. ![Screenshot](example.svg) ## Limitations Currently, there is no prevention of TODOs being rendered on top of each other. See [here](https://github.com/Otto-AA/dashy-todo/issues/1) for more information. ## Usage The package provides a `todo(message, position: auto | left | right)` method. Call it anywhere you need a todo message. ```typst #import "@preview/dashy-todo:0.0.1": todo // It automatically goes to the closer side (left or right) A todo on the left #todo[On the left]. // You can specify a side if you want to #todo(position: right)[Also right] // You can add arbitrary content #todo[We need to fix the $lim_(x -> oo)$ equation. See #link("https://example.com")[example.com]] // And you can create an outline for the TODOs #outline(title: "TODOs", target: figure.where(kind: "todo")) ``` ## Styling You can modify the text by wrapping it, e.g.: ``` #let small-todo = (..args) => text(size: 0.6em)[#todo(..args)] #small-todo[This will be in fine print] ```
https://github.com/Mouwrice/resume
https://raw.githubusercontent.com/Mouwrice/resume/main/metadata.typ
typst
// NOTICE: Copy this file to your root folder. /* Personal Information */ #let firstName = "Maurice" #let lastName = "<NAME>" #let personalInfo = ( github: "Mouwrice", phone: "+32 492 45 01 71", email: "<EMAIL>", linkedin: "maurice-van-wassenhove", ) /* Language-specific */ // Add your own languages while the keys must match the varLanguage variable #let headerQuoteInternational = ( "": [Master of Science in Computer Science Engineering & Bachelor of Science in Computer Science], "nl": [Master in Computer Science Engineering & Bachelor in de Informatica], ) #let cvFooterInternational = ( "": "Curriculum vitae", "nl": "Curriculum vitae" ) #let letterFooterInternational = ( "": "Cover Letter", "nl": "Motivatie brief", ) /* Layout Setting */ #let awesomeColor = "darknight" // Optional: skyblue, red, nephritis, concrete, darknight #let profilePhoto = "../src/Maurice_2022_rounded.png" // Leave blank if profil photo is not needed #let varLanguage = "" // INFO: value must matches folder suffix; i.e "zh" -> "./modules_zh" #let varEntrySocietyFirst = false // Decide if you want to put your company in bold or your position in bold #let varDisplayLogo = true // Decide if you want to display organisation logo or not
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/state_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #let s = state("hey", "a") #let double(it) = 2 * it #s.update(double) #s.update(double) $ 2 + 3 $ #s.update(double) Is: #s.display(), Was: #locate(location => { let it = query(math.equation, location).first() s.at(it.location()) }).
https://github.com/songguokunsgg/HUNNU-Typst-Master-Thesis
https://raw.githubusercontent.com/songguokunsgg/HUNNU-Typst-Master-Thesis/master/README.md
markdown
MIT License
# 湖南垈范倧孊硕士孊䜍论文 基于南京倧孊毕䞚论文讟计的 Typst 暡板胜借简掁、快速、持续生成 PDF 栌匏的毕䞚论文。感谢原䜜者的分享。 ## 泚意事项 - 删陀了本科生和博士盞关的文件因䞺本校的本硕博暡板差距蟃倧无法通甚。 - 该暡板并非官方暡板而是民闎暡板**存圚䞍被讀可的风险**。请提前准倇奜方案 B䟋劂 Word、TeX Live、MacTeX 等。 - 移陀了原项目䞭匀题报告盞关内容。 - 䞎暡板版面盞关的文件郜圚 hnu-thesis 文件倹内建议普通䜿甚者䞍芁修改歀文件倹写䜜所需的内容郜可以写圚 thesis.typ 文件䞭。劂果后续有暡板曎新基本䞍䌚再有䜠可以盎接䜿甚 `git pull` 拉取然后合并冲突即可。 ## 䜜者的话 毕䞚季我自己也圚䜿甚这䞪暡板写论文写的过皋非垞的舒服而䞔倧郚分问题郜已经埗到了解决。䜆是目前确实存圚䞀些胜力范囎之倖的问题无力解决 1. 参考文献这䞪真的是**最倧的硬䌀**哪怕现圚 Typst 支持了自定义样匏䜆可甚范囎十分有限䞍支持 CSL-M 的倚 layout。所以隟以实现䞭英文献混排事实䞊哪怕单语蚀猖排郜胜隟实现圓䜠䜿甚 `#set text(lang: "en")`时“参考文献”䌚变成英文。官方䞍解决这䞪问题䞭囜孊生就无法正垞䜿甚 Typst 写论文。 2. png 囟片问题封面页的 logo 预览正垞䜆是郚分 PDF 蜯件打匀䌚错䜍。 3. 没有 checkedbox盎接富臎封面䞍可甚。 4. 目圕猖排问题孊校芁求总结䞎展望䞍加“第 X 章”䜆是总结和展望分别猖 1 2 节我感觉这䞪问题可以解决䜆是没扟到办法。 5. 囟衚脚泚硬䌀无法实现我靠修改字䜓倧小实现了。 6. 子囟没有这䞪功胜。 本暡板圚南京倧孊暡板基础䞊匀发新增和修改了埈倚适甚于本校的场景䟋劂算法、䞉线衚、目圕栌匏、封面页、页眉亀错猖排。 这是我的最后䞀次曎新由于以䞊问题无法解决我必须把已经写完的初皿蜬换䞺 LaTex 䜿甚䞍胜拿前途匀玩笑。䜆我仍然感谢 Typst给了我埈奜的初皿写䜜䜓验。这仜暡板圚现阶段已经基本完善后续的功胜需芁等官方曎新所以我䞍䌚再曎新了。我毕䞚后劂果有对 Typst 感兎趣的同孊欢迎继续完善这䞪暡板让湖垈倧的各䜍同孊倚䞀䞪选择。 劂果现阶段䜠想䜿甚这仜暡板掚荐䜜䞺初皿䜿甚最终排版还是䜿甚 Latex 曎奜。 ## 劣势 - Typst 是䞀闚新生的排版标记语蚀还做䞍到像 Word 或 LaTeX 䞀样成熟皳定。 - 仍有郚分未胜解决的问题需芁等到 Typst 官方支持可胜还需芁几䞪月 - 没有䌪粗䜓无法给郚分字䜓加粗䟋劂「楷䜓」和「仿宋」。 - 已支持 [自定义 CSL 样匏](https://typst.app/docs/reference/meta/bibliography/)。 ## 䌘势 Typst 是可甚于出版的可猖皋标记语蚀拥有变量、凜数䞎包管理等现代猖皋语蚀的特性泚重于科孊写䜜 (science writing)定䜍䞎 LaTeX 盞䌌。 - **语法简掁**䞊手隟床跟 Markdown 盞圓文本源码可读性高䞍䌚像 LaTeX 䞀样充斥着反斜杠䞎花括号。 - **猖译速床快**Typst 䜿甚 Rust 语蚀猖写即 typ(e+ru)st目标运行平台是 WASM即浏览噚本地犻线运行也可以猖译成呜什行工具采甚䞀种 **增量猖译** 算法和䞀种有纊束的版面猓存方案**文档长床基本䞍䌚圱响猖译速床䞔猖译速床䞎垞见 Markdown 枲染匕擎枲染速床盞圓**。 - **环境搭建简单**䞍需芁像 LaTeX 䞀样折腟几䞪 G 的匀发环境原生支持䞭日韩等非拉䞁语蚀无论是官方 Web App 圚线猖蟑还是䜿甚 VS Code 安装插件本地匀发郜是 **即匀即甚**。 - **现代猖皋语蚀**Typst 是可甚于出版的可猖皋标记语蚀拥有 **变量、凜数、包管理䞎错误检查** 等现代猖皋语蚀的特性同时也提䟛了 **闭包** 等特性䟿于进行 **凜数匏猖皋**。以及包括了 `[标记暡匏]`、`{脚本暡匏}` 侎 `$数孊暡匏$` 等倚种暡匏的䜜甚域并䞔它们可以䞍限深床地、亀互地嵌套。并䞔通过 **包管理**䜠䞍再需芁像 TexLive 䞀样圚本地安装䞀倧堆并䞍必芁的宏包而是 **按需自劚从云端䞋蜜**。 可以参考原䜜者参䞎搭建和翻译的 [Typst 䞭文文档眑站](https://typst-doc-cn.github.io/docs/) 迅速入闚。 ## 䜿甚 **普通甚户只需芁修改根目圕䞋的 `thesis.typ` 文件即可基本可以满足䜠的所有需求`hnu-thesis` 目圕䞋的代码可以甚于参数查阅䜆是理论䞊䜠䞍应该对其进行曎改。** 劂果䜠讀䞺䞍胜满足䜠的需求可以先查阅后面的郚分。 ### 圚线猖蟑 Typst 提䟛了官方的 Web App支持像 Overleaf 䞀样圚线猖蟑<https://typst.app/> **䜆是 Web App 并没有安装本地 Windows 或 MacOS 所拥有的字䜓所以字䜓䞊可胜存圚差匂所以掚荐本地猖蟑** PS: 虜然䞎 Overleaf 看起来盞䌌䜆是它们底层原理并䞍盞同。Overleaf 是圚后台服务噚运行了䞀䞪 LaTeX 猖译噚本莚䞊是计算密集型的服务而 Typst 只需芁圚浏览噚端䜿甚 WASM 技术执行本莚䞊是 IO 密集型的服务所以对服务噚压力埈小只需芁莟莣文件的云存傚䞎协䜜同步功胜。 ### 本地猖蟑掚荐 1. 克隆本项目或者盎接通过 [GitHub Releases](https://gitee.com/songguokunsgg/hnu-thesis-typst) 页面䞋蜜。 ```bash git clone https://github.com/OrangeX4/nju-thesis-typst.git ``` 2. 圚 [VS Code](https://code.visualstudio.com/) 䞭打匀该目圕。 3. 圚 VS Code 䞭安装 [Typst LSP](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp) 和 [Typst Preview](https://marketplace.visualstudio.com/items?itemName=mgt19937.typst-preview) 插件。前者莟莣语法高亮和错误检查后者莟莣预览。 - 也掚荐䞋蜜 [Typst Companion](https://marketplace.visualstudio.com/items?itemName=CalebFiggers.typst-companion) 插件其提䟛了䟋劂 `Ctrl + B` 进行加粗等䟿捷的快捷键。 - 䜠还可以䞋蜜我匀发的 [Typst Sync](https://marketplace.visualstudio.com/items?itemName=OrangeX4.vscode-typst-sync) 和 [Typst Sympy Calculator](https://marketplace.visualstudio.com/items?itemName=OrangeX4.vscode-typst-sympy-calculator) 插件前者提䟛了本地包的云同步功胜后者提䟛了基于 Typst 语法的科孊计算噚功胜。 4. 按䞋 `Shift + Ctrl + P`然后蟓入呜什 `Typst Preview: Preview current file`即可 **同步增量枲染䞎预览**还提䟛了 **光标双向定䜍功胜**。 ### 特性 / 路线囟 - **诎明文档** - [ ] 猖写曎诊细的诎明文档后续考虑䜿甚 [tidy](https://github.com/typst/packages/tree/main/packages/preview/tidy/0.1.0) 猖写䜠现圚可以先参考 [NJUThesis](https://mirror-hk.koddos.net/CTAN/macros/unicodetex/latex/njuthesis/njuthesis.pdf) 的文档参数倧䜓保持䞀臎或者盎接查阅对应源码凜数的参数 - **类型检查** - [ ] 应该对所有凜数入参进行类型检查及时报错 - **党局配眮** - [x] 类䌌 LaTeX 侭的 `documentclass` 的党局信息配眮 - [x] **盲审暡匏**将䞪人信息替换成小黑条并䞔隐藏臎谢页面论文提亀阶段䜿甚 - [x] **双面暡匏**䌚加入空癜页䟿于打印 - [x] **自定义字䜓配眮**可以配眮「宋䜓」、「黑䜓」䞎「楷䜓」等字䜓对应的具䜓字䜓 - [ ] **字䜓解耊合**将字䜓配眮进䞀步解耊合让甚到字䜓的地方加䞊䞀层字䜓名称配眮项从「标题宋䜓」-「具䜓字䜓」重构䞺「标题」-「宋䜓」-「具䜓字䜓」 - [x] **数孊字䜓配眮**暡板䞍提䟛配眮甚户可以自己䜿甚 `#show math.equation: set text(font: "Fira Math")` 曎改 - **暡板** - [x] 研究生暡板 - [x] 封面 - [x] 声明页 - [x] 摘芁 - [x] 页眉 - [ ] 囜家囟乊銆封面 - [ ] 出版授权乊 - **猖号** - [x] 前蚀䜿甚眗马数字猖号 - [x] 附圕䜿甚眗马数字猖号 - [x] 衚栌䜿甚 `1.1` 栌匏进行猖号 - [x] 数孊公匏䜿甚 `(1.1)` 栌匏进行猖号 - **环境** - [x] 定理环境这䞪可以自己修改配眮 - [x] 算法环境目前矎观皋床蟃差䜆只有这䞪包可甚 ## Q&A ### 我䞍䌚 LaTeX可以甚这䞪暡板写论文吗 可以。 劂果䜠䞍关泚暡板的具䜓实现原理䜠可以甚 Markdown Like 的语法进行猖写只需芁按照暡板的结构猖写即可。 ### 我䞍䌚猖皋可以甚这䞪暡板写论文吗 同样可以。 劂果仅仅是圓成是入闚䞀欟类䌌于 Markdown 的语蚀盞信䜿甚该暡板的䜓验䌚比䜿甚 Word 猖写曎奜。 ### 䞺什么我的字䜓没有星瀺出来而是䞀䞪䞪「豆腐块」 这是因䞺本地没有对应的字䜓**这种情况经垞发生圚 MacOS 的「楷䜓」星瀺䞊**。 䜠应该安装本目圕䞋的 `fonts` 里的所有字䜓里面包含了可以免莹商甚的「方正楷䜓」和「方正仿宋」然后再重新枲染测试即可。 䜠可以䜿甚 `#fonts-display-page()` 星瀺䞀䞪字䜓枲染测试页面查看对应的字䜓是吊星瀺成功。 劂果还是䞍胜成功䜠可以按照暡板里的诎明自行配眮字䜓䟋劂 ```typst #let (...) = documentclass( fonts: (楷䜓: ("Times New Roman", "FZKai-Z03S")), ) ``` 先是填写英文字䜓然后再填写䜠需芁的「楷䜓」䞭文字䜓。 **字䜓名称可以通过 `typst fonts` 呜什查询。** 劂果扟䞍到䜠所需芁的字䜓可胜是因䞺 **该字䜓变䜓Variants数量过少**富臎 Typst 无法识别到该䞭文字䜓。 ### 䞺什么楷䜓无法加粗 因䞺䞀般默讀安装的「楷䜓」只有标准字重的字䜓没有加粗版本的字䜓华文粗楷等字䜓并䞍是免莹商甚的而 Typst 又没有实现䌪粗䜓Fake Bold算法所以富臎无法正垞加粗。 目前我还没扟到䞀䞪比蟃奜的解决方法。 ### å­Šä¹  Typst 需芁倚久 䞀般而蚀仅仅进行简单的猖写䞍关泚垃局的话䜠可以打匀暡板就匀始写了。 劂果䜠想进䞀步孊习 Typst 的语法䟋劂劂䜕排篇垃局劂䜕讟眮页脚页眉等䞀般只需芁几䞪小时就胜孊䌚。 劂果䜠还想孊习 Typst 的「[元信息](https://typst-doc-cn.github.io/docs/reference/meta/)」郚分进而胜借猖写自己的暡板䞀般而蚀需芁几倩的时闎阅读文档以及他人猖写的暡板代码。 劂果䜠有 Python 或 JavaScript 等脚本语蚀的猖写经验了解过凜数匏猖皋、宏、样匏、组件化匀发等抂念入闚速床䌚快埈倚。 ### 我有猖写 LaTeX 的经验劂䜕快速入闚 可以参考 [面向 LaTeX 甚户的 Typst 入闚指南](https://typst-doc-cn.github.io/docs/guides/guide-for-latex-users/)。 ### 目前 Typst 有哪些第䞉方包和暡板 可以参考 [第䞉方包](https://typst-doc-cn.github.io/docs/packages/)、[Awesome Typst Links](https://github.com/qjcg/awesome-typst) 和 [Awesome Typst 列衚䞭文版](https://github.com/typst-doc-cn/awesome-typst-cn)。 ### 䞺什么只有䞀䞪 thesis.typ 文件没有按章节分倚䞪文件 因䞺 Typst **语法足借简掁**、**猖译速床足借快**、并䞔 **拥有光标点击倄双向铟接功胜**。 语法简掁的奜倄是即䜿把所有内容郜写圚同䞀䞪文件䜠也可以埈简单地分蟚出各䞪郚分的内容。 猖译速床足借快的奜倄是䜠䞍再需芁像 LaTeX 䞀样将内容分散圚几䞪文件并通过泚释的方匏提高猖译速床。 光标点击倄双向铟接功胜䜿埗䜠可以盎接拖劚预览窗口到䜠想芁的䜍眮然后甚錠标点击即可到蟟对应源码所圚䜍眮。 还有䞀䞪奜倄是单䞪源文件䟿于同步和分享。 即䜿䜠还是想芁分成几䞪章节也是可以的Typst 支持䜠䜿甚 `#import` 和 `#include` 语法将其他文件的内容富入或眮入。䜠可以新建文件倹 `chapters`然后将各䞪章节的源文件攟进去然后通过 `#include` 眮入 `thesis.typ` 里。 ### 我劂䜕曎改页面䞊的样匏具䜓的语法是怎么样的 理论䞊䜠并䞍需芁曎改 `nju-thesis` 目圕䞋的任䜕文件无论是样匏还是其他的配眮䜠郜可以圚 `thesis.typ` 文件内修改凜数参数实现曎改。具䜓的曎改方匏可以阅读 `nju-thesis` 目圕䞋的文件的凜数参数。 䟋劂想芁曎改页面蟹距䞺 `50pt`只需芁将 ```typst #show: doc ``` 改䞺 ```typst #show: doc.with(margin: (x: 50pt)) ``` 即可。 后续我也䌚猖写䞀䞪曎诊细的文档可胜䌚考虑䜿甚 [tidy](https://github.com/typst/packages/tree/main/packages/preview/tidy/0.1.0) 来猖写。 劂果䜠阅读了那些凜数的参数仍然䞍知道劂䜕修改埗到䜠需芁的样匏欢迎提出 Issue只芁描述枅楚问题即可。 或者也欢迎加矀讚论943622984 ### 该暡板和其他现存 Typst 䞭文论文暡板的区别 其他现存的 Typst 䞭文论文暡板倧倚郜是圚 2023 幎 7 月仜之前Typst Verison 0.6 之前匀发的圓时 Typst 还䞍䞍借成熟甚至连 **包管理** 功胜郜还没有因歀圓时的 Typst 䞭文论文暡板的匀发者基本郜是自己从倎写了䞀遍需芁的功胜/凜数因歀造成了 **代码耊合床高**、**意倧利面条匏代码**、**重倍造蜮子** 侎 **隟以自定义样匏** 等问题。 该暡板是圚 2023 幎 10  11 月仜Typst Verison 0.9 时匀发的歀时 Typst 语法基本皳定并䞔提䟛了 **包管理** 功胜因歀胜借减少埈倚䞍必芁的代码。 并䞔我对暡板的文件架构进行了解耊䞻芁分䞺了 `utils`、`templates` 和 `layouts` 䞉䞪目圕这䞉䞪目圕可以看后文的匀发者指南并䞔䜿甚 **闭包** 特性实现了类䌌䞍可变党局变量的党局配眮胜力即暡板䞭的 `documentclass` 凜数类。 ## License This project is licensed under the MIT License.
https://github.com/Han-duoduo/mathPater-typest-template
https://raw.githubusercontent.com/Han-duoduo/mathPater-typest-template/main/chapter/chap3.typ
typst
Apache License 2.0
= 暡型假讟 + 假讟每䞀䞪小区的䞻控连接讟倇郜胜互盞接收到信号即这䞀䞪小区䞺邻区。 + 圚考虑PCIæš¡3干扰的情况䞭䞀䞪同频邻小区  的信号区床的差小于等于给定闚限。 + 假讟重新分配PCI后䞍䌚产生其他代价。 + 每次PCI的分配是独立的圚重倍倚次实验后可以看成是均匀分垃的因歀可以采甚均匀分垃的随机数进行暡拟
https://github.com/SkymanOne/zk-learning
https://raw.githubusercontent.com/SkymanOne/zk-learning/main/notes/intro/intro.typ
typst
#import "../base.typ": * #show: note = Introduction to Zero Knowledge Proofs There are a prover and verifier `String` = proof submitted by the prover Verifier rejects or accepts the proof (i.e. the `String`) In CS we talk about polynomial proofs, that can be verified in *polynomial* time $->$ *NP proofs* - The `string` is short - Polynomial time constraints Given claim `x`, the length of the proof `w` should be of polynomial length. More formally: `|w|` = polynomial in `|x|`. The verifier has a *polynomyial* time contraints for execution. `V` _accepts_ `w` if $V(x,w) = 1$, otherwise _rejects_. #align(center, diagram( spacing: 8em, node((0,0), [*Prover* \ Uncontrained runtime]), edge("->", [Proof *w*]), node((1,0), [*Verifier* \ Verifies in polynomial time of claim `x`]), ) ) = Efficently verifiable proofs We can formalise the the input as: - Language $L$ - a set of binary strings More formally: #def([ $L$ is an *NP* language (or NP decision problem), if there is a verifier $V$ that runs in polynomial time of length of the claim $x$ that where - *Completeness [True claims have short proofs]* \ if $x in L$, there is a polynomially (of $|x|$) long witness $w in {0,1}^*$ st $V(x,w) = 1$ - *Soundness [False claims have no proofs]* \ if $x in.not L$, there is no witness. That is, for all $w in {0,1}^*, V(x,w)=0$ ]) = Proving Quadratic Residue #footnote[https://mathworld.wolfram.com/QuadraticResidue.html] *Goal*: proof that $y$ is a quadratic residue $mod N$. #align(center, diagram( spacing: 15em, node((0,0), [*Prover*]), edge("->", [Proof = $sqrt(y) mod N in Z^*_N$]), node((1,0), [*Verifier*]), ) ) *The gist:* Prove (or persuade) the verifier that the prover could prove the statement. Adding additional components - *Interactive* and *Probabilistic* proofs - *Interaction* - verifier engages in the _non-trivial_ interaction with the prover - *Randomness* - verifier is randomised, and can accept am invalid proof with a small probability (quantified). #align(center, diagram( spacing: 5em, node-stroke: 0.5pt, node(enclose: ((0,0), (0,1)), [*Prover*]), node(enclose: ((1,0), (1,1)), [*Verifier*]), edge((0, 0), (1, 0), "->", [Answer]), edge((0, 0.3), (1, 0.3), "<-", [Question]), edge((0, 0.6), (1, 0.6), "->", [Answer]), edge((0, 0.9), (1, 0.9), "<-", [Question]), edge((0, 1), (1, 1), "..", []), ) ) *Examples*: https://medium.com/@houzier.saurav/non-technical-101-on-zero-knowledge-proofs-cab77d671a40 *Here is the interactive proof for the quadratic residue:* 1. Prover chooses a random $r$ s.t. $1 ≀ r ≀ N$ s.t. $gcd(r, N) = 1$ 2. Prover sends $s$, s.t. $s = r^2 mod N$ - If the prover sends $sqrt(s) mod N$ and $sqrt(s times y) mod N$ later, then the verifier coulde deduce $x = sqrt(y) mod N$ - Instead, the prover gives either one of the roots. 3. Verifier randomly chooses $b in {0, 1}$ 4. if $b=1$: verifier sends $z=r$, otherwise $z=r times sqrt(y) mod N$ 5. Verifier accepts the proofs only if $z^2 = s y^b mod n$ - if $b=0$ then $z^2 = s mod N$ - otherwise, $z^2 = s y mod N$ During the first try, the probability of error is $1/2$, after $k$ interactions => it is $(1/2)^k$. *Note*: at the beginning of each interaction, the Prover generates a new $r$ which is $sqrt(s) mod N$ Assessing the properties: - *Completeness*: if the claim is true, the verifier will accept it. - *Soundness*: if the claim is false, $forall$provers, $P("Verifier accepts") ≀ 1/2$ - After $k$ interactions: $forall$provers, $P("Verifier accepts") ≀ (1/2)^k$ = How does previous example worked? Sending both parts of the QR, proves that the verifier *could* solve the original equation. Additionally, sending just the $s$ reveal no knowledge about the original solution. The ability of the prover, to provide solution to either part persuades the verifier that it can solve the original equation. = Interactive Proofs #align(center, diagram( spacing: 5em, node-stroke: 0.5pt, node(enclose: ((0,0), (0,1)), [*Prover*]), node(enclose: ((1,0), (1,1)), [*Verifier*]), node(enclose: ((0,1.5), (1,1.5)), [*Claim / Theorem X*]), edge((0, 0), (1, 0), "->", [$a_1$]), edge((0, 0.3), (1, 0.3), "<-", [$q_1$]), edge((0, 0.6), (1, 0.6), "->", [$a_2$]), edge((0, 0.9), (1, 0.9), "<-", [$q_2$]), edge((0, 1), (1, 1), "..", []), ) ) #def([ $(P,V)$ is an interactive proof for $L$, if $V$ is probabilistic $"poly"(|x|)$ and - *Completeness*: if $x in L$, $P[(P,V)(x) = "accept"] ≥ c$ - *Soundness*: if $x in.not L$ for every $P^*$, $P[(P^*,V)(x) = "accept"] ≀ s$ We want to $c$ to be as close to *b* as possible, and $s$ to be as negligible as possible. Equivalent as long as $c - s ≥ 1/"poly"(|x|)$ ]) #def([ Class of interaction proof languages = {$L$ for which there is an interactive proof} ]) = Zero-Knowledge views The intuition behind zero knowledge interactions: For any true statements, what the verifier can compute *after* the interaction is the same to what it could have computer *before* the interaction. In other words, the verifier *does not gain any more information* (i.e. knowledge) after the verification interaction. This should hold true *even for malicious verifiers.* View is essentially a set of traces containing submitted questions $q^*$ to the verifier and received answers $a^*$ from it. After the interaction $V$ learns: - Theorem (T) is true, $x in L$ - A *view* of interactions #def([ *$"view"_v(P,V)[x]$* = ${(q_1, a_1), (q_2, a_2), ...}$, which is a probibility distributions over random values of $V$ and $P$. ]) In the case of $P$, the random value it selects for QR is $r$, in the case of $P$ it is the choice whether the reveal $r$ or $r sqrt(y) mod N$ == Simulation Paradigm We can say that V's view gives no further knowledge to it, if it could have simulated it on its own s.t. the simulated view and the real view are _computationally indistinguishable_. What that means is that we can have a polynomial time "distinguisher" that extracts the trace from either of the views, and if it can not differentiate it with the probability less than 50/50, we can say that they views are _computationally indistinguishable_. #align(center, diagram( spacing: 10em, node-stroke: 0.5pt, node(enclose: ((0, 0), (0,1)), [The poly-time \ Distinguisher]), node(enclose: ((1, 0), (1, 1))), node((1, 0.2), [Real view], shape: rect), node((1, 0.8), [Simulated \ view]), edge((0,0.2) , (1, 0.2), "<-", [sample]), edge((0,0.8) , (1, 0.8), "<-", [sample]) ) ) More formally: #align(center, diagram( spacing: 10em, node-stroke: 0.5pt, node(enclose: ((0, 0), (0,1)), [The poly-time \ Distinguisher]), node(enclose: ((1, 0), (1, 1))), node((1, 0.2), [$D_1$ - k-bit strings]), node((1, 0.8), [$D_2$ - k-bit strings]), edge((0,0.5) , (1, 0.5), "<-", [sample]), ) ) #def([ For all distinguisher algorithms, even after receiving a polynomial number of samples for $D_b$, if $P("Distinguisher guesses " b) < 1/2 + c$ where $c$ negligible constant, \ then $D_1 .. D_k$ are *computationally indistinguishable* ]) = Zero-Knowledge Definition #def([ An Interactive Protocol (P,V) is zero-knowledge for a language $L$ if there exists a *PPT* (Probabilistic Polynomial Time) algorithm *Sim* (a simulator) such that for every $x in L$, the following two probability distributions are *poly-time* indistinguishable: 1. $"view"_v(P,V)[x] = "traces"$ 2. $"Sim"(x, 1^lambda)$ $(P,V)$ is a zero-knowledge interactive protocol if it is *complete*, *sound* and *zero-knowledge*. ]) Flavours of Zero-Knowledge: - Computationally indistinguishable distributions = CZK - Perfectly identical distributions = PZK - Statistically close distributions = SZK = Simulator Example For QR, the view presented as $"view"_v(P,V): (s, b, z)$ Simulator workflow: 1. Pick a random $b$ 2. Pick a random $z in Z^*_N$ 3. Compute $s = z^2 "/" y^b$ 4. Output $(s, z, b)$ We would see that $(s, z, b)$ is identically distributed as in real view. *For adversarial verifier $V^*$:* 1. Pick a random $b$ 2. Pick a random $z in Z^*_N$ 3. Compute $s = z^2 "/" y^b$ 4. If $V*(N, y, s) = b$, then output $(s, z, b)$, otherwise go to step 1. Within 2 iteration, we would still reach identical distribution. = Proof of knowledge The prover convinces the verifier not only about the theorem but that it also knows the $x$. Using that information, we can construct the knowledge extractor using the rewinding technique. More formally: #def([ Consider $L_R = {x : exists w "s.t." R(x, w) = "accept"}$ for poly-time relation $R$. $(P,V)$ is a proof of knowledge (POK) for $L_R$ if $exists$ PPT (knowledge) extractor algorithm $E$ s.t. $forall x in L$ in expected poly-time $E^(P)(x)$ outputs $w$ s.t. $V(x, w)$ = accept ]) #align(center, diagram( spacing: 12em, node-stroke: 0.5pt, node(enclose: ((0,0), (0,1)), [*Prover*]), node(enclose: ((1,0), (1,1)), [*Verifier*]), edge((0, 0), (1, 0), "->", [$s=r^2 mod n$]), edge((0, 0.2), (1, 0.2), "<-", [$b=0$]), edge((0, 0.4), (1, 0.4), "->", [$r$]), edge((0, 0.7), (1, 0.7), "<-", [_In the same cycle of $s$_ \ $b=1$]), edge((0, 0.9), (1, 0.9), "->", [$r times sqrt(y) mod N$]), ) ) And the verifier can determine $r times sqrt(y) mod N$, hence, extract the knowledge. = All of NP is in Zero-Knowledge #def([ *Theorem[GMW86,Naor]*: If one-way functions exist, then every $L in "NP"$ has computational zero knowledge interactive proofs ]) Shown that an NP-Complete Problem has a ZK interactive Proof. [GMW87] Showed ZK interactive proof for G3-COLOR using bit commitments. = Reading #link("https://link.springer.com/chapter/10.1007/3-540-47721-7_11", "How to Prove All NP Statements in Zero-Knowledge and a Methodology of Cryptographic Protocol Design (Extended Abstract)")
https://github.com/Karolinskis/KTU-typst
https://raw.githubusercontent.com/Karolinskis/KTU-typst/main/README.md
markdown
# KTU Typst Thesis template Unofficial Typst template for Kaunas University of Technology. ## Fonts The following fonts are included in the `fonts` directory: - Times New Roman Bold Italic - Times New Roman Bold - Times New Roman Italic - Times New Roman ## Contributing Contributions are welcome. If you see any mistakes or want to add something, feel free to open an issue or a pull request.
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/b47475-2024_lug_sfd_poster/main.typ
typst
#let light_green = cmyk(75%, 0%, 100%, 0%) #let green = cmyk(100%, 0%, 100%, 20%) #let light_blue = cmyk(40%, 3%, 0%, 25%) #let blue = cmyk(72%, 30%, 0%, 70%) #let mark(body) = box(clip: true, stroke: 0.2cm + red, body) #let mark(body) = box(body) #set page(width: 80cm, height: 180cm, fill: light_blue, margin: 0cm) #let sfd-img = image("imgs/sfd_logo.svg", height: 20cm) #let sfd-text = text(size: 200pt, font: "Prism", fill: green, stroke: 5pt + white)[ #show par: set block(spacing: 3cm) Software Freedom Day ] #let sfd-sym = pad( top: 5cm, grid( columns: (auto, auto), align: bottom + left, inset: (x: 2cm, y: 0cm), mark(sfd-img), mark(sfd-text), ), ) #let sfd-text-cn = pad( top: 5cm, bottom: 2cm, text(size: 240pt, font: "baotuxiaobaiti", fill: white)[ 蜯件自由日 ], ) #let date-location-box = pad( 2cm, rect( radius: 20cm, width: 40cm, height: 6cm, fill: green, align( center + horizon, text(size: 120pt, font: "Nanum Pen Script", fill: white)[ 2024.09.21 3C101 ], ), ), ) #let keynotes = box(width: 100%, fill: blue)[ #set align(left) #set text(size: 80pt, fill: white, font: ("linux libertine", "Source Han Serif SC")) #let title(it) = text(size: 100pt, font: "Trajan Pro", it) #let author(it) = text(size: 60pt, underline(it), weight: "bold") #let details(it) = text(size: 60pt, fill: gray.lighten(10%), it) #pad(x: 3cm, y: 3.5cm)[ #title[ Keynotes: ] - $TT$ypst 101 #author[\@tiankaima] #details[ 觉埗 LaTeX #strike[过于笚重]Markdown 功胜䞍借来试试新的排版系统 Typst 圚分享䞭我们将介绍 Typst 的基本䜿甚方法并展瀺䞀些高级功胜。 ] - 电信5G䞓眑服务简介 #author[\@james] #details[ 孊校拟匀通5G双域䞓眑服务以方䟿垈生圚囜内䜿甚移劚通讯眑络访问校园眑内资源。这里简单介绍我校䞭囜电信5G双域䞓眑服务的建讟进展和技术细节。 ] - 我的 Debian maintainer 之路 #author[\@于波 from PLCT] #details[ 圚本次分享䞭 于波将介绍䞀䞪瀟区小癜劂䜕通过修包、打包䞀步步成䞺 Debian maintainer甚至 Debian developer. ] - `tracexec`: 䌘雅地远螪 exec 系统调甚 #author[\@任鹏飞] #details[ 圚配环境或从源码安装蜯件时我们垞垞䌚遇到各种奇怪的错误。 这些错误圚没有䞊䞋文的情况䞋可胜隟以理解通垞我们䌚想芁知道出错的呜什和执行环境到底是什么。 我将介绍和展瀺 `tracexec` 劂䜕䌘雅地解决这类问题以及 `tracexec` 的及䞀倧劙甚协助倚皋序调试。 ] ] #pad(x: 3cm, bottom: 5cm)[ #title[ Lightning Talks: ] ... ] ] #let caption-text = [ #v(3cm) #show: it => pad(x: 5cm, it) #set text(size: 60pt, fill: white, font: ("linux libertine", "Source Han Serif SC")) #set align(left) #grid( columns: (3fr, 1fr), align: top + left, [ #pad(left: 1cm)[ 䞭囜科孊技术倧孊 Linux 甚户协䌚是由䞭囜科孊技术倧孊圚校的 GNU/Linux 爱奜者发起并组成的团䜓旚圚联合科倧的 GNU/Linux 䜿甚者搭建信息亀流共享的平台宣䌠自由蜯件的价倌提高自由蜯件瀟区文化氛囎掚广自由蜯件的应甚。 ] #set text(size: 40pt) #let size = 10cm #grid( columns: (size, size, size, size), rows: (size, 2cm), inset: (x: 1cm, y: 0.1cm), align: center, image("imgs/qrcodes/埮信公䌗号.svg"), image("imgs/qrcodes/QQ公䌗号.svg"), image("imgs/qrcodes/眑站.svg"), image("imgs/qrcodes/青春科倧.svg"), "埮信公䌗号", "QQ公䌗号", "眑站", "青春科倧", ) ], pad( x: 2cm, image("imgs/logo-white.svg", height: 14cm), ), ) ] #align(center)[ #mark[ #sfd-sym ] #mark[ #sfd-text-cn ] #mark[ #date-location-box ] #mark[ #keynotes ] #mark[ #caption-text ] ]
https://github.com/SillyFreak/typst-stack-pointer
https://raw.githubusercontent.com/SillyFreak/typst-stack-pointer/main/docs/manual.typ
typst
MIT License
#import "template.typ" as template: * #import "/src/lib.typ" as sp #let package-meta = toml("/typst.toml").package #let date = datetime(year: 2024, month: 2, day: 23) #show: manual( title: "Stack Pointer", // subtitle: "...", authors: package-meta.authors.map(a => a.split("<").at(0).trim()), abstract: [ _Stack Pointer_ is a library for visualizing the execution of (imperative) computer programs, particularly in terms of effects on the call stack: stack frames and local variables therein. ], url: package-meta.repository, version: package-meta.version, date: date, ) // the scope for evaluating expressions and documentation #let scope = (sp: sp) #let exec-example(sim-code, typst-code, render) = { let preamble = ```typc import sp: * ``` let steps = eval(mode: "code", scope: scope, preamble.text + typst-code.text) block(breakable: false, { grid(columns: (2fr, 3fr), sim-code, typst-code) }) render(steps) } #let exec-grid-render(columns: none, steps) = { if columns == none { columns = steps.len() } let steps = steps.enumerate(start: 1) let render((n, step), width: auto, height: auto) = block( width: width, height: height, fill: gray.lighten(80%), radius: 0.2em, inset: 0.4em, breakable: false, { [Step #n: ] if step.step.line != none [line #step.step.line] else [(no line)] v(-0.5em) list(..step.state.stack.map(frame => { frame.name if frame.vars.len() != 0 { [: ] frame.vars.pairs().map(((name, value)) => [#name~=~#value]).join[, ] } })) } ) context { let rows = range(steps.len(), step: columns).map(i => { steps.slice(i, calc.min(steps.len(), i + columns)) }) grid( columns: (1fr,) * columns, column-gutter: 0.4em, row-gutter: 0.4em, ..for row in rows { let height = row.map(step => measure(render(step)).height).fold(0pt, calc.max) row.map(render.with(width: 100%, height: height)) } ) } } #show raw: it => { if it.lang == none { let (text, lang: _, lines: _, theme: _, ..fields) = it.fields() raw(text, lang: "typc", ..fields) } else { it } } #let ref-line(n) = { show raw: set text(fill: gray, size: 0.9em) raw(lang: "", "("+str(n)+")") } = Introduction _Stack Pointer_ provides tools for visualizing program execution. Its main use case is for presentations using frameworks such as #link("https://polylux.dev/book/")[Polylux], but it tries to be as general as possible. There are two main concepts that underpin Stack Pointer: _effects_ and _steps_. An effect is something that changes program state, for example a variable assignment. Right now, the effects that are modeled by this library are limited to ones that affect the stack, giving it its name, but more possibilities would be interesting as well. A step is an instant during program execution at which the current program state should be visualized. Collectively, these (and a few similar but distinct entities) make up _execution sequences_. In this documentation, _sequence item_ or just _item_ means either an effect or a step, or depending on context also one of these similar entities. Stack Pointer helps build these execution sequences, calculating the list of states at the steps of interest, and visualizing these states. = Examples As the typical use case is presentations, where the program execution would be visualized as a sequence of slides, the examples here will necessarily be displayed differently. So, don't let the basic appearance here fool you: it is up to you how to display Stack Pointer's results. == Setting a variable The possibly simplest example would be visualizing assigning a single variable, then returning . Let's do this and look at what's happening exactly: #exec-example( ```c int main() { int a = 0; return 0; } ```, ```typc execute({ l(1, call("main")) l(2); l(2, push("a", 0)) l(3); l(none, ret()) }) ```, exec-grid-render.with(columns: 5), ) A lot is going on here: we're using #ref-fn("execute()") to get the result of an execution sequence, which we created with multiple #ref-fn("l()") calls. Each of these calls first applies zero or more effects, then a step that can be used to visualize the execution state. We use steps without effects to change to lines 2 and 3 before showing what these do, for example. For line 1, we don't do that and instead immediately add the `call("main")` effect, because we want the main stack frame from the beginning. For the final step that returns from main, we don't put a line number because it's not meaningful anymore. Not specifying a line number is also useful for visualizing calls into library functions. The simple visualization here -- listing the five steps (one per `l()` call) in a grid -- is _not_ part of Stack Pointer itself; it's done directly in this manual in a way that's appropriate for this format. The information in each step -- namely, the line numbers, stack frames, and local variables for each stack frame -- _are_ provided by Stack Pointer though. == Low-level functions for effects and steps The `l()` function is usually the appropriate way for defining execution sequences, but sometimes it makes sense to drop down a level. Here's the same code, represented with only the low-level functions of Stack Pointer. #exec-example( ```c int main() { int a = 0; return 0; } ```, ```typc execute({ call("main"); step(line: 1) step(line: 2) push("a", 0); step(line: 2) step(line: 3) ret(); step(line: none) }) ```, exec-grid-render.with(columns: 5), ) Apart from the individual function calls, one difference can be seen: the #ref-fn("step()") function takes only named arguments; in fact, a bare step doesn't even _have_ to have a line; `l()` just has it because it's very common to need it. For use cases where line numbers are not needed but `l()` seems like a better fit, just define your own variant using the #ref-fn("bare-l()") helper, e.g.: `let l(id, ..args) = bare-l(id: id, ..args)` -- now you can call this with `id` as a positional parameter. == Calling functions (the manual way) Regarding the call stack, a single function is not particularly interesting; the fun begins when there are function calls and thus multiple stack frames. Without additional high-level function tools, this can be achieved as follows: #exec-example( ```c int main() { foo(0); return 0; } void foo(int x) { return; } ```, ```typc execute({ let foo(x) = { l(6, call("foo"), push("x", x)) l(7); ret() // (1) } let main() = { l(1, call("main")) l(2); foo(0); l(2) // (2) l(3); l(none, ret()) // (3) } main() }) ```, exec-grid-render.with(columns: 5), ) As soon as we're working with functions, it makes sense to represent every example function with an actual Typst function. `foo()` comes first because of how Typst resolves names (for mutually recursive functions this doesn't work, and Typst currently #link("https://github.com/typst/typst/issues/744")[doesn't seem to support it]). The execution sequence is ultimately constructed by calling `main()` once. The `foo()` function contains its own #ref-fn("call()") and #ref-fn("ret()") effects, so that these don't need to be handled at every call site. There's a small asymmetry though: the return effect at #ref-line(1) is not added via `l()` and thus not immediately followed by a step. After returning, the line where execution resumes depends on the caller, so the next step is generated by `main()` at #ref-line(2), with a line within the C `main()` function. An exception to this is the `main()` function itself: at #ref-line(3), we generate a step (with line `none`) because here it is clear where execution will resume - or rather, that it _won't_ resume. == Calling functions (the convenient way) Some of this function setup is still boilerplate, so Stack Pointer provides a simpler way, using #ref-fn("func()"): #exec-example( ```c int main() { foo(0); return 0; } void foo(int x) { return; } ```, ```typc execute({ let foo(x) = func("foo", 5, l => { l(0, push("x", x)) l(1) }) let main() = func("main", 1, l => { l(0) l(1); foo(0); l(1) l(2) }) main(); l(none) }) ```, exec-grid-render.with(columns: 5), ) `func()` brings two conveniences: one, you put your implementation into a closure that gets an `l()` function that interprets line numbers relative to a first line number (for example, line 5 for `foo()`). This makes it easier to adapt the Typst simulation if you change the code example it refers to. Two, the `call()` and `ret()` effects don't need to be applied manually. The downside is that this uniform handling means that we needed to manually add the last step after returning from `main()`. == Using return values from functions The convenience of mapping example functions to Typst functions comes in part from mirroring the logic: instead of having to track specific parameter values in specific calls, just pass exactly those values in Typst calls. Return values are an important part of this, but they need a bit of care: #exec-example( ```c int main() { int x = foo(); return 0; } int foo() { return 0; } ```, ```typc execute({ let foo() = func("foo", 6, l => { l(0) l(1); retval(0) // (1) }) let main() = func("main", 1, l => { l(0) l(1) let (x, ..rest) = foo(); rest // (2) l(1, push("x", x)) l(2) }) main(); l(none) }) ```, exec-grid-render.with(columns: 5), ) In line #ref-line(1) we have the first piece of the puzzle, the #ref-fn("retval()") function. This function is emitted by the implementation closure as if it was a sequence item, but it must be handled before `execute()` could see it because it isn't actually one. In line #ref-line(2) the caller, who normally receives an array of items, now also receives the return value as the first element of that array. By destructuring, the first element is removed, and then the rest of the array needs to be emitted so that these items are part of the complete execution sequence. == Displaying execution state Until now the examples have concerned themselves with the actual execution of programs; how to get from #ref-fn("execute()")'s result to the gray boxes in this documentation was not addressed yet. This is potentially different between documents, and Stack Pointer doesn't do a lot for you here yet; still, here's one example for how execution state could be displayed. The following is a function that takes the example code and _one_ step as returned by #ref-fn("execute()"). Below, you see how it looks when the four last steps of the variable assignment example are rendered next to each other using this function: #{ import sp: * let code = ```c int main() { int a = 0; return 0; } ``` let steps = execute({ let main() = func("main", 1, l => { l(0) let a = 0 l(1); push("a", a); l(1) l(2) }) main(); l(none) }) let steps = steps let render-code = ```typc let render(code, step) = { let line = step.step.line let stack = step.state.stack block[ #code #if line != none { place( top, // dimensions are hard-coded for this specific situation // don't take this part as inspiration, please ;) dx: 0.47em, dy: 0.15em + (line - 1) * 1.22em, circle(radius: 0.5em) ) } ] block(inset: (x: 0.9em))[ Stack: #parbreak() #if stack.len() == 0 [(empty)] #list(..stack.map(frame => { frame.name if frame.vars.len() != 0 { [: ] frame.vars.pairs().map(((name, value)) => [#name~=~#value]).join[, ] } })) ] } ``` let render = eval(mode: "code", render-code.text + "; render") render-code grid(columns: (1fr,) * 4, ..range(1, 5).map(i => render(code, steps.at(i)))) } A more typical situation would probably put the steps on individual slides. In polylux, for example, the `only()` function can be used to only show some information (the current line markers, the stack state) on specific subslides. To do so, it makes sense to first `enumerate(start: 1)` the steps, so that each step has a subslide index attached to it. The gallery has a complete example of using Stack Pointer with Polylux. = Module reference Functions that return sequence items, or similar values like #ref-fn("retval()"), return a value of the following shape: `((type: "..", ..),)` -- that is, an array with a single element. That element is a dictionary with some string `type`, and any other payload fields depending on the type. The payload fields are exactly the parameters of the following helper functions, unless specified otherwise. #module( read("/src/lib.typ"), name: "stack-pointer", label-prefix: none, scope: scope, show-module-name: false, ) == Effects Effects are in a separate module because they have the greatest potential for extension, however they are also re-exported from the main module. #module( read("/src/effects.typ"), name: "stack-pointer.effects", label-prefix: none, scope: scope, show-module-name: false, )
https://github.com/TempContainer/typnotes
https://raw.githubusercontent.com/TempContainer/typnotes/main/opti/con_set.typ
typst
#import "/book.typ": book-page #import "/templates/my-template.typ": * #show: book-page.with(title: "Convex Sets") #show: template = Hello, typst Sample page 䞭文测试. ```cpp #include <iostream> int main() { std::cout << "Hello World!\n"; return 0; } ```
https://github.com/piepert/typst-seminar
https://raw.githubusercontent.com/piepert/typst-seminar/main/Beispiele/UniHausaufgabe/a01_antwort.typ
typst
#import "template.typ": adt, task, subtask, project, pointed #show: project.with( title: "1", authors: ( (name: "<NAME>", matnr: "123456789"), (name: "<NAME>", matnr: "987654321"), (name: "<NAME>", matnr: "123459876") ), date: "Sonntag, 16.04.2023") #task[Objekt-orientierte Programmierung (OOP)][Beantworten Sie die folgenden Fragen zu grundlegenden Konzepten der objekt-orientierten Programmierung in Java.] #subtask([Was ist ein _Objekt_? Was ist eine _Klasse_? Worin besteht der Unterschied?], 2, [ Ein Objekt ist hÀufigerweise eine abstrahierte ReprÀsentation realer Dinge. Klassen sind eine Kategorie gleichartiger Objekte. Objekte sind Instanzen von Klassen, wÀhrend Klassen die BauplÀne fÃŒr Objekte darstellen. ]) #subtask([Wie wird der Zustand eines Objektes gespeichert? Wie wird sein Verhalten reprÀsentiert?], 2, [ Der Zustand eines Objektes wird durch die Werte seine Attribute gespeichert. Das Verhalten wird durch die Methoden der Klasse beschrieben. ]) #subtask([Wie werden Objekte in Java erzeugt? Was ist ein _Konstruktor_? Wie und wann werden Objekte in Java wieder zerstört?], 3, [ Objekte werden mit dem `new`-Keyword generiert. Der Konstruktor initialisiert das durch `new` generierte Objekt. Durch den Garbage-Collector werden Objekte dann erzeugt, wenn sie nicht mehr verwendet werden, d.h. z.B. wenn keine weiteren Referenzen mehr auf das Objekt existieren. ]) #subtask([Was ist _Vererbung_? Wie deklariert man in Java eine Klasse, die von einer anderen Klasse erbt?], 2, [ Vererbung bezeichnet eine hierarchische Relation zwischen Klassen, in der eine Klasse $B$, die _Unterklasse_, von einer Klasse $A$, die _Oberklasse_, Attribute, Methoden und Implementierungen erbt. Damit kann $B$ als ein $A$ behandelt werden. In der Klassendefinition kann man mittels dem Keyword `extends` nach dem Namen der Klasse eine andere Klasse angeben, von der sie erbt. ```java class B extends A { ... } ``` ]) #subtask([Was sind #emph([abstrakte Klassen]) und #emph([Methoden])?], 2, [ Abstrake Klassen sind Klassen, von denen keine Objekte erzeugt werden können. Abstrakte Methoden sind Methoden ohne Implementierung, die in jeder Unterklasse implementiert werden mÃŒssen. ]) #subtask([Was sind _Interfaces_? Wozu benötigt man sie in Java?], 3, [ Interfaces sind Àhnlich zu abstrakten Klassen, die ausschließlich aus abstrakten Methoden bestehen. In Java kann eine Klasse nur von maximal einer anderen Klasse erben, jedoch von beliebig vielen Interfaces. FÃŒr Mehrfachvererbung sind Interfaces ein Ausweg. ]) #subtask([Was sind _Exceptions_? Wie behandelt man sie in Java?], 2, [ Exceptions sind Fehlerereignisse, die, wenn sie nicht behandelt werden, das Programm stoppen. Sie werden durch `try`-`catch`-Anweisungen behandelt. Jede `try`-`catch`-Anweisungen besteht aus einem `try`-Block und beliebig vielen `catch`-Blöcken, die eine bestimmte Exception $E$ behandeln. Im `try`-Block wird der auftretende Fehler abgefangen und der passende `catch`-Fall ausgefÃŒhrt. Ist kein passender `catch`-Fall vorhanden, wurde sie nicht behandelt und das Programm wird gestoppt. ```java public static int parseInput(String input) { try { return Integer.parseInt(input); } catch (NumberFormatException e) { return -1; } } ``` ]) #subtask([Was sind _Generics_? Welche Vorteile bieten sie?], 2, [ Generics machen es möglich, Methoden und Klassen fÃŒr verschiedene Datentypen gleichzeitig zu definieren. Wenn keine besondere Eigenschafft eines Datentyps $T$ benutzt wird, kann man die Klasse bzw. die Methode $A$ mithilfe von Generics auf eine Klasse bzw. Methode #emph("A<T>") generalisieren. Anstelle des Namens des Datentyps kann dann ein beliebiger, in der Methoden- oder Klassendefinition definierter, Platzhalter verwendet werden ```java import java.util.ArrayList; public class GenericsExample { public static <T> ArrayList<T> addElement(ArrayList<T> a, T b) { a.add(b); return a; } public static void main(String[] args) { ArrayList<Integer> l1 = new ArrayList<Integer>(); l1.add(1); ArrayList<String> l2 = new ArrayList<String>(); l2.add("Hello"); addElement(l1, 2); addElement(l2, "World"); } } ``` ]) #task[Komplexe Zahlen][Sowohl abstrakte Datentypen (ADT) als auch Objekte kapseln Daten zusammen mit den Operationen, die auf diese zugreifen. Es bestehen viele Gemeinsamkeiten, aber auch wichtige Unterschiede.] #subtask([Spezifizieren Sie den ADT "Complex Number" zur ReprÀsentation komplexer Zahlen. Es soll möglich sein, eine komplexe Zahl zu erzeugen, zwei komplexe Zahlen zu addieren, zu subtrahieren, zu multiplizieren und zu dividieren sowie den Real- und ImaginÀrteil einer komplexen Zahl zu bestimmen!], 3, [ #show math.equation: it => emph(it) #let complex = "complex" #let add = "add" #let sub = "sub" #let mul = "mul" #let div = "div" #let Radd = "Radd" #let Rsub = "Rsub" #let Rmul = "Rmul" #let Rdiv = "Rdiv" Ein algebraischer Datentyp $CC$ fÃŒr "Complex Number", wobei $Radd$, $Rsub$, $Rdiv$ und $Rmul$ Operanten zur Addition, Subtraktion, Division und Multiplikation von reellen Zahlen sind: #adt( ( $RR$, ), ( $complex: RR times RR -> CC$, $add: CC times CC -> CC$, $sub: CC times CC -> CC$, $mul: CC times CC -> CC$, $div: CC times CC -> CC$, ), $forall r_1, r_2, i_1, i_2 in RR circle.filled.small$, ( $add(complex(r_1, i_1), complex(r_2, i_2)) = complex(r_1 + r_2, i_1 + i_2)$, $sub(complex(r_1, i_1), complex(r_2, i_2)) = complex(r_1 - r_2, i_1 - i_2)$, $mul(complex(r_1, i_1), complex(r_2, i_2)) = complex(r_1 r_2 - i_1 i_2, r_1 i_2 + r_2 i_1)$, $div(complex(r_1, i_1), complex(r_2, i_2)) = complex((r_1 r_2 + i_1 i_2)/(r_2 r_2 + i_2 i_2), (i_1 r_2 - r_1 i_2)/(r_2 r_2 + i_2 i_2))$ ) ) ]) #subtask([Wie lassen sich aus der Signatur des ADT Complex die Methodendeklarationen einer objekt-orientierten Implementierung ableiten? Wie gehen Sie vor?], 3, [ Der ADT ist die Spezifikation einer Klasse. Verwendete Sorten erscheinen als benutzte Datentypen, $RR$ steht hier fÃŒr `double`, $CC$ ist die Klasse `Complex` selbst. Die Operatoren sind die Signaturen der Methoden fÃŒr die Klasse, wobei der Definitionsbereich der Abbildung durch die Argumente dargestellt und der RÃŒckgabewert der Methode der Wertebereich ist. Die Regeln sind die Implementierung der jeweiligen Methoden. ]) #subtask([Erstellen Sie eine objekt-orientierte Implementierung in Java! Nutzen Sie hierzu die Datei Complex.java!], 4, [ Siehe auch `src/Complex.java`. #raw(block: true, lang: "java", read("src/Complex.java")) ])
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/VerbaliEsterni/VerbaleEsterno_240320/content.typ
typst
MIT License
#import "meta.typ": inizio_incontro, fine_incontro, luogo_incontro, company #import "functions.typ": glossary, team #let participants = csv("participants.csv") #let participants_company = csv("participants_company.csv") = Partecipanti / Inizio incontro: #inizio_incontro / Fine incontro: #fine_incontro / Luogo incontro: #luogo_incontro == Partecipanti di #team #table( columns: (3fr, 1fr), [*Nome*], [*Durata presenza*], ..participants.flatten() ) == Partecipanti di #emph[#company] #for member in participants_company.flatten() [ - #member ] = Sintesi Elaborazione Incontro /*************************************/ /* INSERIRE SOTTO IL CONTENUTO */ /*************************************/ Durante l'incontro il team ha condiviso con la Proponente lo stato di avanzamento del progetto e pianificato l'ultimo probabile incontro in vista della presentazione PB. == Stato avanzamento prodotto L'incontro Ú iniziato con una breve analisi del lavoro svolto dal team dal precedente SAL, concentrato sull'implementazione dei test di unità dei simulatori e di integrazione dell'intero sistema nelle sue componenti. Entrambe le tipologie di test sono state effettuate con librerie apposite di Python: per la componente di simulazione sono state raggiunte una statement coverage e una branch coverage superiori all'80%. == Sito vetrina Sono state presentate le nuove modifiche estetiche e strutturali apportate al sito vetrina #link("https://swatengineering.github.io/"), come il nuovo metodo di ordinamento dei file e la grafica delle icone. La Proponente ne ha apprezzato forma e contenuti, specie vedendolo per la prima volta dall'inizio del progetto. == Impegni presi Considerando l'avvio del secondo lotto per il progetto didattico, la Proponente ha sottolineato la necessità di rispettare le scadenze fissate precedentemente dal team per portare a termine il progetto nelle tempistiche previste. Ciò consentirebbe all'azienda di gestire efficacemente la candidatura dei nuovi gruppi, ormai molto vicina. Inoltre, Ú stato chiesto al team di preparare una breve valutazione del ruolo svolto dalla Proponente lungo il percorso che ha portato al completamento del progetto per individuare possibili miglioramenti e garantire un'esperienza ottimale ai nuovi gruppi. Ad esempio, la Proponente ha già deciso di interrompere l'utilizzo dell'applicazione Element a favore di Discord, considerato più diffuso e funzionale. == Pianificazione prossimo SAL Per il prossimo SAL sono state proposte le due date di giovedì 28/03/2024 e di martedì 02/04/2024, con orari ancora da definire, direttamente presso la sede della Proponente. È nostra responsabilità comunicare la nostra preferenza tramite email. Tuttavia, l'incontro di martedì 02/04/2024 vedrebbe la partecipazione di <NAME>, e sarebbe quindi preferibile. Durante tale incontro, infatti, il team punta ad ottenere l'approvazione formale del prodotto software realizzato come MVP; alla luce della preferenza espressa dal team di non effettuare la terza revisione CA, si tratterebbe a tutti gli effetti dell'ultimo incontro esterno.
https://github.com/ryuryu-ymj/mannot
https://raw.githubusercontent.com/ryuryu-ymj/mannot/main/src/util.typ
typst
MIT License
#let copy-stroke(_stroke, args) = { let s = stroke(_stroke) return stroke(( paint: args.at("paint", default: s.paint), thickness: args.at("thickness", default: s.thickness), cap: args.at("cap", default: s.cap), join: args.at("join", default: s.join), dash: args.at("dash", default: s.dash), miter-limit: args.at("miter-limit", default: s.miter-limit), )) }
https://github.com/chendaohan/bevy_tutorials_typ
https://raw.githubusercontent.com/chendaohan/bevy_tutorials_typ/main/10_coordinate_system/coordinate_system.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. 2D 和 3D 场景 Bevy 圚枞戏䞖界䞭䜿甚右手 Y 向䞊坐标系。䞺了保持䞀臎3D 和 2D 的坐标系盞同。 - X 蜎从巊向右正 X 指向右䟧 - Y 蜎从䞋到䞊正 Y 指向䞊 - Z 蜎从远到近正 Z 指向䜠 原点默讀情况䞋圚屏幕䞭心。 这是右手坐标系䜠可以䜿甚右手的手指来可视化 3 䞪蜎拇指 = X食指 = Y䞭指 = Z。 #image("images/handedness.png") = 2. UI 对于 UIBevy 遵埪䞎倧倚数其他 UI 工具包、Web 盞同的纊定。 - 原点䜍于屏幕巊䞊角 - Y 蜎指向䞋方 - X 蜎从屏幕巊蟹猘到屏幕右蟹猘 - Y 蜎从屏幕䞊蟹猘到屏幕䞋蟹猘 = 3. 光标和屏幕 光标䜍眮和任䜕其他窗口屏幕空闎坐标遵埪䞎 UI 盞同的纊定。
https://github.com/hexWars/resume
https://raw.githubusercontent.com/hexWars/resume/main/README-zh.md
markdown
MIT License
# typst-resume-template ![resume](https://img.shields.io/badge/resume-typst-9cf) 这䞪项目是䞀䞪䜿甚Typst讟计的简历暡板灵感来自于这䞪[眑站](https://satnaing.dev/blog)。 ## 预览 | | | |:---:|:---:| | ![preview](./assets/typst-resume-template.png) | ![preview2](./assets/typst-resume-template2.png) | ## 䜿甚 垞甚的SVG文件已经存圚于文件倹`typst`䞭暡板文件䞺`typst/resume.typ`圚`typst/main.typ`文件䞭蟓入䜠的简历内容。 䜠可以将本项目䞋蜜圚typst眑站䞊䌠`typst`文件倹后䜿甚 ### 修改页面参数 ```typst #set page(margin: (top: 15mm, bottom: 15mm)) #set text(font: "Linux Libertine", lang: "zh", 1em) #set par(leading: 0.58em) ``` 包括字䜓倧小语蚀顶郚距犻底郚距犻等 ### 改变颜色 修改`theme_color`参数 ### 修改竖线 劂果䜠想修改那条竖线可以扟到 ```typst line( start: (0%, 11.1%), end: (0%, 0%), length: 4cm, stroke: 6pt + theme_color, ) ``` 进行修改 ### 分割线 分割线可甚于孊历郚分倚䞪孊历的分割 ## 讞可 Format is MIT but all the data is owned by hexWars
https://github.com/nasyxx/lab-weekly-report
https://raw.githubusercontent.com/nasyxx/lab-weekly-report/master/smwr.typ
typst
// SMILE Lab Weekly Report Template // by Nasy <EMAIL> // Version 0.1.0 #let smwr(author, date, body) = { let title = [#author's Weekly Report] let last_date = date - duration(weeks: 1) let date_format = "[month repr:short] [day], [year]" set document(title: title, author: author, date: date) set page(paper: "us-letter", numbering: "1") set text(font: "EB Garamond", fallback: true) set par(justify: true) show heading: it => { text(weight: "semibold", smallcaps(it.body)) } align(left, text(2em, weight: "semibold", smallcaps[#title])) align(left, text(1em, weight: "medium", [ #last_date.display(date_format) --- #date.display(date_format + ", Week [week_number]") ])) // abstract heading(outlined: false, numbering: none, text(1.2em, smallcaps[Abstract], weight: "medium")) body }
https://github.com/SillyFreak/typst-scrutinize
https://raw.githubusercontent.com/SillyFreak/typst-scrutinize/main/src/lib.typ
typst
MIT License
#import "grading.typ" #import "task.typ" #import "solution.typ" #import "task-kinds/mod.typ" as task-kinds
https://github.com/EpicEricEE/typst-equate
https://raw.githubusercontent.com/EpicEricEE/typst-equate/master/src/equate.typ
typst
MIT License
// Element function for alignment points. #let align-point = $&$.body.func() // Element function for sequences. #let sequence = $a b$.body.func() // Element function for a counter update. #let counter-update = counter(math.equation).update(1).func() // State for tracking whether equate is enabled. #let equate-state = state("equate/enabled", 0) // State for tracking the sub-numbering property. #let sub-numbering-state = state("equate/sub-numbering", false) // State for tracking whether we're in a shared alignment block. #let share-align-state = state("equate/share-align", 0) // State for tracking whether we're in a nested equation. #let nested-state = state("equate/nested-depth", 0) // Show rule necessary for referencing equation lines, as the number is not // stored in a counter, but as metadata in a figure. #let equate-ref(it) = { if it.element == none { return it } if it.element.func() != figure { return it } if it.element.kind != math.equation { return it } if it.element.body == none { return it } if it.element.body.func() != metadata { return it } // Display correct number, depending on whether sub-numbering was enabled. let nums = if sub-numbering-state.at(it.element.location()) { it.element.body.value } else { // (3, 1): 3 + 1 - 1 = 3 // (3, 2): 3 + 2 - 1 = 4 (it.element.body.value.first() + it.element.body.value.slice(1).sum(default: 1) - 1,) } assert( it.element.numbering != none, message: "cannot reference equation without numbering." ) let num = numbering( if type(it.element.numbering) == str { // Trim numbering pattern of prefix and suffix characters. let counting-symbols = ("1", "a", "A", "i", "I", "侀", "壹", "あ", "い", "ア", "ã‚€", "א", "가", "ㄱ", "*") let prefix-end = it.element.numbering.codepoints().position(c => c in counting-symbols) let suffix-start = it.element.numbering.codepoints().rev().position(c => c in counting-symbols) it.element.numbering.slice(prefix-end, if suffix-start == 0 { none } else { -suffix-start }) } else { it.element.numbering }, ..nums ) let supplement = if it.supplement == auto { it.element.supplement } else if type(it.supplement) == function { (it.supplement)(it.element) } else { it.supplement } link(it.element.location(), if supplement not in ([], none) [#supplement~#num] else [#num]) } // Extract lines and trim spaces. #let to-lines(equation) = { let lines = if equation.body.func() == sequence { equation.body.children.split(linebreak()) } else { ((equation.body,),) } // Trim spaces at begin and end of line. let lines = lines.filter(line => line != ()).map(line => { if line.first() == [ ] and line.last() == [ ] { line.slice(1, -1) } else if line.first() == [ ] { line.slice(1) } else if line.last() == [ ] { line.slice(0, -1) } else { line } }) lines } // Layout a single equation line with the given number. #let layout-line( number: none, number-align: none, number-width: auto, text-dir: auto, line ) = context { let equation(body) = [ #math.equation( block: true, numbering: _ => none, body ) <equate:revoke> ] // Short circuit if no number has to be added. if number == none { return equation(line.join()) } // Short circuit if number is a counter update. if type(number) == content and number.func() == counter-update { return { number equation(line.join()) } } // Start of equation block. let x-start = here().position().x // Resolve number width. let number-width = if number-width == auto { measure(number).width } else { number-width } // Resolve equation alignment in x-direction. let equation-align = if align.alignment.x in (left, center, right) { align.alignment.x } else if text-dir == ltr { if align.alignment.x == start { left } else { right } } else if text-dir == rtl { if align.alignment.x == start { right } else { left } } // Add numbers to the equation body, so that they are aligned at their // respective baselines. If the equation is centered, the number is put // on both sides of the equation to keep the center alignment. let num = box(width: number-width, align(number-align, number)) let line-width = measure(equation(line.join())).width let gap = 0.5em layout(bounds => { let space = if equation-align == center { bounds.width - line-width - 2 * number-width } else { bounds.width - line-width - number-width } let body = if number-align.x == left { if equation-align == center { h(-gap) + num + h(space / 2 + gap) + line.join() + h(space / 2) + hide(num) } else if equation-align == right { num + h(space + 2 * gap) + line.join() } else { h(-gap) + num + h(gap) + line.join() + h(space + gap) } } else { if equation-align == center { hide(num) + h(space / 2) + line.join() + h(space / 2 + gap) + num + h(-gap) } else if equation-align == right { h(space + gap) + line.join() + h(gap) + num + h(-gap) } else { line.join() + h(space + 2 * gap) + num } } equation(body) }) } // Replace "fake labels" with a hidden figure that is labelled // accordingly. #let replace-labels( lines, number-mode, numbering, supplement, has-label ) = { // Main equation number. let main-number = counter(math.equation).get() // Indices of lines that contain a label. let labelled = lines .enumerate() .filter(((i, line)) => { if line.len() == 0 { return false } if line.last().func() != raw { return false } if line.last().lang != "typc" { return false } if line.last().text.match(regex("^<.+>$")) == none { return false } return true }) .map(((i, _)) => i) // Indices of lines that are marked not to be numbered. let revoked = lines .enumerate() .filter(((i, line)) => { if i not in labelled { return false } return line.last().text == "<equate:revoke>" }) .map(((i, _)) => i) // The "revoke" label shall not count as a labelled line. labelled = labelled.filter(i => i not in revoked) // Indices of numbered lines in this equation. let numbered = if number-mode == "line" { range(lines.len()).filter(i => i not in revoked) } else if labelled.len() == 0 and has-label { // Only outer label, so number all lines. range(lines.len()).filter(i => i not in revoked) } else { labelled } ( numbered, lines.enumerate() .map(((i, line)) => { if i in revoked { // Remove "revoke" label and space and return line. line.remove(-1) if line.at(-2, default: none) == [ ] { line.remove(-2) } return line } if i not in labelled { return line } // Remove trailing spacing (before label). if line.at(-2, default: none) == [ ] { line.remove(-2) } // Append sub-numbering only if there are multiple numbered lines. let nums = main-number + if numbered.len() > 1 { (numbered.position(n => n == i) + 1,) } // We use a figure with kind "equation" to make the sub-equation // referenceable with the correct supplement. The numbering is stored // in the figure body as metadata, as a counter would only show a // single number. line.at(-1) = [#figure( metadata(nums), kind: math.equation, numbering: numbering, supplement: supplement )#label(line.last().text.slice(1, -1))] return line }) ) } // Remove labels from lines, so that they don't interfere when measuring. #let remove-labels(lines) = { lines.map(line => { if line.len() == 0 { return line } if line.last().func() != raw { return line } if line.last().lang != "typc" { return line } if line.last().text.match(regex("^<.+>$")) == none { return line } line.remove(-1) if line.at(-1, default: none) == [ ] { line.remove(-1) } return line }) } // Splitting an equation into multiple lines breaks the inbuilt alignment // with alignment points, so it is emulated here by adding spacers manually. #let realign(lines) = { // Utility shorthand for unnumbered block equation. let equation(body) = [ #math.equation( block: true, numbering: none, body ) <equate:revoke> ] // Consider lines of other equations in shared alignment block. let extra-lines = if share-align-state.get() > 0 { let num = counter("equate/align/counter").get().first() let align-state = state("equate/align/" + str(num), ()) remove-labels(align-state.final()) } else { () } let lines = extra-lines + lines // Short-circuit if no alignment points. if lines.all(line => align-point() not in line) { return lines.slice(extra-lines.len()) } // Store widths of each part between alignment points. let part-widths = lines.map(line => { line.split(align-point()) .map(part => measure(equation(part.join())).width) }) // Get maximum width of each part. let part-widths = for i in range(calc.max(..part-widths.map(points => points.len()))) { (calc.max(..part-widths.map(line => line.at(i, default: 0pt))), ) } // Get maximum width of each slice of parts. let max-slice-widths = array.zip(..lines.map(line => range(part-widths.len()).map(i => { let parts = line.split(align-point()).map(array.join) if i >= parts.len() { 0pt } else { let slice = parts.slice(0, i + 1).join() measure(equation(slice)).width } }))).map(widths => calc.max(..widths)) // Add spacers for each part, so that the part widths are the same for all lines. let lines = lines.map(line => { line.split(align-point()) .enumerate() .map(((i, part)) => { // Add spacer to make part the correct width. let width-diff = part-widths.at(i) - measure(equation(part.join())).width let spacing = if width-diff > 0pt { h(0pt) + box(fill: yellow, width: width-diff) + h(0pt) } if calc.even(i) { spacing + part.join() // Right align. } else { part.join() + spacing // Left align. } }) .intersperse(align-point()) }) // Update maximum slice widths to include spacers. let max-slice-widths = array.zip(..lines.map(line => range(part-widths.len()).map(i => { let parts = line.split(align-point()).map(array.join) if i >= parts.len() { 0pt } else { let slice = parts.slice(0, i + 1).join() calc.max(max-slice-widths.at(i), measure(equation(slice)).width) } }))).map(widths => calc.max(..widths)) // Add spacers between parts to ensure correct spacing with combined parts. lines = for line in lines { let parts = line.split(align-point()).map(array.join) for i in range(max-slice-widths.len()) { if i >= parts.len() { break } let slice = parts.slice(0, i).join() + h(0pt) + parts.at(i) let slice-width = measure(equation(slice)).width if slice-width < max-slice-widths.at(i) { parts.at(i) = h(0pt) + box(fill: green, width: max-slice-widths.at(i) - slice-width) + h(0pt) + parts.at(i) } } (parts,) } // Append remaining spacers at the end for lines that have less align points. let line-widths = lines.map(line => measure(equation(line.join())).width) let max-line-width = calc.max(..line-widths) lines = lines.zip(line-widths).map(((line, line-width)) => { if line-width < max-line-width { line.push(h(0pt) + box(fill: red, width: max-line-width - line-width)) } line }) lines.slice(extra-lines.len()) } // Any block equation inside this block will share alignment points, thus // allowing equations to be interrupted by text and still be aligned. // // Sub-numbering is not (yet) continued across equations in this block, so // each new equation will get a new main number. Equations with a revoke label // will not share alignment with other equations in this block. #let share-align(body) = { context assert( equate-state.get() > 0, message: "shared alignment block requires equate to be enabled." ) share-align-state.update(n => { assert.eq(n, 0, message: "nested shared alignment blocks are not supported.") n + 1 }) let align-counter = counter("equate/align/counter") align-counter.step() show math.equation.where(block: true): it => { if it.has("label") and it.label == <equate:revoke> { return it } let align-state = state("equate/align/" + str(align-counter.get().first()), ()) align-state.update(lines => lines + to-lines(it)) it } body share-align-state.update(n => n - 1) } // Applies show rules to the given body, so that block equations can span over // page boundaries while retaining alignment. The equation number is stepped // and displayed at every line, optionally with sub-numbering. // // Parameters: // - breakable: Whether to allow page breaks within the equation. // - sub-numbering: Whether to add sub-numbering to the equation. // - number-mode: Whether to number all lines or only lines containing a label. // Must be either "line" or "label". // - debug: Whether to show alignment spacers for debugging. // // Returns: The body with the applied show rules. #let equate( breakable: auto, sub-numbering: false, number-mode: "line", debug: false, body ) = { // Validate parameters. assert( breakable == auto or type(breakable) == bool, message: "expected boolean or auto for breakable, found " + repr(breakable) ) assert( type(sub-numbering) == bool, message: "expected boolean for sub-numbering, found " + repr(sub-numbering) ) assert( number-mode in ("line", "label"), message: "expected \"line\" or \"label\" for number-mode, found " + repr(number-mode) ) assert( type(debug) == bool, message: "expected boolean for debug, found " + repr(debug) ) // This function was applied to a reference or label, so apply the reference // rule instead of the equation rule. if type(body) == label { return { show ref: equate-ref ref(body) } } else if body.func() == ref { return { show ref: equate-ref body } } show math.equation.where(block: true): set block(breakable: breakable) if type(breakable) == bool show math.equation.where(block: true): it => { // Don't apply show rule in a nested equations. if nested-state.get() > 0 { return it } // Allow a way to make default equations. if it.has("label") and it.label == <equate:revoke> { return it } // Make spacers visible in debug mode. show box.where(body: none): it => { if debug { it } else { hide(it) } } show box.where(body: none): set box( height: 0.4em, stroke: 0.4pt, ) if debug // Prevent show rules on figures from messing with replaced labels. show figure.where(kind: math.equation): it => { if it.body == none { return it } if it.body.func() != metadata { return it } none } // Main equation number. let main-number = counter(math.equation).get().first() // Resolve text direction. let text-dir = if text.dir == auto { if text.lang in ( "ar", "dv", "fa", "he", "ks", "pa", "ps", "sd", "ug", "ur", "yi", ) { rtl } else { ltr } } else { text.dir } // Resolve number position in x-direction. let number-align = if it.number-align.x in (left, right) { it.number-align.x } else if text-dir == ltr { if it.number-align.x == start { left } else { right } } else if text-dir == rtl { if it.number-align.x == start { right } else { left } } let (numbered, lines) = replace-labels( to-lines(it), number-mode, it.numbering, it.supplement, it.has("label") ) // Short-circuit for single-line equations. if lines.len() == 1 and share-align-state.get() == 0 { if it.numbering == none { return it } if numbering(it.numbering, 1) == none { return it } let number = if numbered.len() > 0 { numbering(it.numbering, main-number) } else { // Step back counter as this equation should not be counted. counter(math.equation).update(n => n - 1) } return { // Update state to allow correct referencing. sub-numbering-state.update(_ => sub-numbering) layout-line( lines.first(), number: number, number-align: number-align, text-dir: text-dir ) // Step back counter as we introducted an additional equation // that increased the counter by one. counter(math.equation).update(n => n - 1) } } // Calculate maximum width of all numberings in this equation. let max-number-width = if it.numbering == none { 0pt } else { calc.max(0pt, ..range(numbered.len()).map(i => { let nums = if sub-numbering and numbered.len() > 1 { (main-number, i + 1)} else { (main-number + i,) } measure(numbering(it.numbering, ..nums)).width })) } // Update state to allow correct referencing. sub-numbering-state.update(_ => sub-numbering) // Layout equation as grid to allow page breaks. block(grid( columns: 1, row-gutter: par.leading, ..realign(lines).enumerate().map(((i, line)) => { let sub-number = numbered.position(n => n == i) let number = if it.numbering == none { none } else if sub-number == none { // Step back counter as this equation should not be counted. counter(math.equation).update(n => n - 1) } else if sub-numbering and numbered.len() > 1 { numbering(it.numbering, main-number, sub-number + 1) } else { numbering(it.numbering, main-number + sub-number) } layout-line( line, number: number, number-align: number-align, number-width: max-number-width, text-dir: text-dir ) }) )) // Revert equation counter step(s). if it.numbering == none { // We converted a non-numbered equation into multiple empty- // numbered ones and thus increased the counter at every line. counter(math.equation).update(n => n - lines.len()) } else { // Each line stepped the equation counter, but it should only // have been stepped once (when using sub-numbering). We also // always introduced an additional numbered equation that // stepped the counter. counter(math.equation).update(n => { n - if sub-numbering and numbered.len() > 1 { numbered.len() } else { 1 } }) } } // Apply this show rule first to update nested state. // This works because the context provided by the other show rule does not // yet include the updated state, so it can be retrieved correctly. show math.equation.where(block: true): it => { // Turn off numbering for nested equations, as it's usually unwanted. // Workaround for https://github.com/typst/typst/issues/5263. set math.equation(numbering: none) nested-state.update(n => n + 1) it nested-state.update(n => n - 1) } // Add show rule for referencing equation lines. show ref: equate-ref equate-state.update(n => n + 1) body equate-state.update(n => n - 1) }
https://github.com/ls1intum/thesis-template-typst
https://raw.githubusercontent.com/ls1intum/thesis-template-typst/main/utils/todo.typ
typst
MIT License
#let TODO(body, color: yellow, width: 100%, breakable: true) = { block( width: width, radius: 3pt, stroke: 0.5pt, fill: color, inset: 10pt, breakable: breakable, )[ #body ] }
https://github.com/juruoHBr/typst_xdutemplate
https://raw.githubusercontent.com/juruoHBr/typst_xdutemplate/main/template.typ
typst
#import "@preview/cuti:0.2.1": show-cn-fakebold #import "utils.typ": * // ---------------------------党局变量------------------------- #let headings = state("headings",()) #let frontmattercnt = counter("frontmattercnt") #let mainpagecnt = counter("mainpagecnt") // ----------------------------蟅助凜数------------------------- #let get-fonts(fonts) = { let font-dict = ( en-main-font: "Times New Roman", en-heading-font: "Times New Roman", ch-main-font: "SimSun", ch-heading-font: "SimHei", ) + fonts let title-font = (font-dict.en-heading-font, font-dict.ch-heading-font) let main-font = (font-dict.en-main-font,font-dict.ch-main-font) return (title-font,main-font) } // 获取header的文本 #let getheaderinfo(loc,title) = { if(calc.odd(loc.page())){ let headings_array = headings.final(loc) let headertext =none for page_heading in headings_array{ if int(loc.page()) < page_heading.at(0){ return headertext } headertext = page_heading } return headings_array.last() } else { return (0,-1,title) } } // 排版header #let header-fun(numberformat: "1",cnt: counter(page),title:[]) = { let headercontext = { locate(loc=>{ h(1fr) let headerinfo = getheaderinfo(loc,title) if(headerinfo.at(1)==-1){ headerinfo.at(2) } else { let header-format = headerinfo.at(1) if header-format != none{ numbering(header-format,..headerinfo.at(3)) + " " } headerinfo.at(2) } h(1fr) }) } block(width: 100%, height: 100%, stroke: (bottom:1pt), inset: 0.5em)[ #headercontext #locate(loc => if(calc.odd( loc.page() )){ place(right+bottom)[#cnt.display(numberformat)] } else { place(left + bottom)[#cnt.display(numberformat)] } ) ] } // ----------------------------文档凜数------------------------- #let abstract( ch-abstract, en-abstract ) = { heading(level: 1, outlined: false)[摘芁] ch-abstract heading(level: 1, outlined: false)[Abstract] en-abstract } #let cover( info: none ) = [ #set par(first-line-indent: 0em) #set table(stroke: (x, _) => if x == 1 { (bottom: 0.8pt) }) #set page(margin: (top: 2.54cm, bottom: 2.54cm) ) #set align(center) #{ set text(size: 12pt) place(top+right,dx: -1.5cm)[ #table( columns: (3em,7em), align: bottom + center, column-gutter: 0.5em, [*班~~级*], [*#info.class*], [*å­Š~~号*], [*#info.number*], ) ] } #v(2.5cm) #image("figures/校名.jpg", width: 7.73cm, height: 1.27cm, fit: "stretch") #v(0.9cm) #text(font: "SimHei", size: 42pt, tracking: 5pt)[本科毕䞚讟计论文] #v(1.2cm) #image("figures/校埜.png",width: 4.39cm, height: 4.18cm, fit: "stretch") #v(1cm) #{ set text(size: 15pt) let titles = info.covertitle.split("\n") move(dx : -15pt, table( columns: (5em,15em), align: bottom, row-gutter: 1.8em, column-gutter: 1em, [*题~~~~~~~~目*], hei[#titles.at(0)], [],hei[#titles.at(1)], [*å­Š~~~~~~~~院*], [#info.school], [*侓~~~~~~~~侚*], [#info.major], [*孊生姓名*], [#info.name], [*富垈姓名*], [#info.tutor], ) ) } ] #let thesis-contents() ={ pagebreak() outline(indent: auto) } #let front-matter(doc,title: []) = { //页面讟眮 set page( header: frontmattercnt.update(it=>it+1)+ header-fun(numberformat: "i",cnt: frontmattercnt,title:title), footer: [] ) doc } #let mainbody(title:[],doc) = { // 标题讟眮 show heading: set heading(numbering: "1.1") show heading.where(level: 1): set heading(numbering: "第䞀章") set page( header: mainpagecnt.update(it=> it+1)+header-fun(numberformat: "1",cnt: mainpagecnt, title: title), footer: [] ) show math.equation: set text(font: ("New Computer Modern Math", "SimHei")) set math.equation(numbering: it=>{ set text(font: ("Times New Roman","SimSun")) "匏(" + context str(counter(heading).get().first() )+ "-" + str(it) +")" }) set figure(numbering: it=>{ context str(counter(heading).get().first()) + "." + str(it) }) counter(page).update(1) doc } #let after-matter(title:[],doc) = { set page( header: mainpagecnt.update(it=> it+1)+header-fun(numberformat: "1",cnt: mainpagecnt, title: title), footer: [] ) doc } #let appendix(doc) = { set figure(numbering: it=>{ context numbering("A",counter(heading).get().first()) + str(it) }) set math.equation(numbering: it=>{ "匏(" + context numbering("A",counter(heading).get().first() )+ "-" + str(it) +")" }) show heading.where(level: 1): set heading(numbering: "附圕A") counter(heading).update(0) doc } //----------------------------论文暡板-------------------- #let xdudoc( fonts: (:), fontsize : 12pt, factor: 1.5, doc ) = { //党局讟眮 show strong: show-cn-fakebold set text(lang: "zh", region: "cn") set pagebreak(to: "odd", weak: true) let (title-font,main-font) = get-fonts(fonts) set text( font: main-font, size: fontsize, lang: "zh", ) set par( leading: 15.6pt * factor - 0.7em, first-line-indent: 2em, justify: true, ) set page(margin: (top:3cm, bottom: 2cm, inside: 3cm, outside: 2cm)) set block(above: 15.6pt * factor - 0.7em, below: 15.6pt * factor - 0.7em) //章节标题讟眮 show heading: set text(font: title-font) show heading: it =>{it + fake-par} show heading.where(level:1) : it => { pagebreak() set text(size: 16pt) align(center)[#it] locate(loc=>{ let pagenum = int(loc.page()) headings.update( headings => headings + ( (pagenum,it.numbering,it.body,counter(heading).at((loc) )), ) ) }) counter(figure.where(kind: table)).update(0) counter(figure.where(kind: image)).update(0) counter(math.equation).update(0) } show heading.where(level: 2) : set text(size: 14pt) set math.equation(supplement: none) show figure.where(kind: table): set figure.caption(position: top) show figure.caption : set text(size: 10pt) doc }
https://github.com/dark-flames/apollo-typst
https://raw.githubusercontent.com/dark-flames/apollo-typst/main/packages/typst-apollo/theme.typ
typst
Apache License 2.0
#import "@preview/shiroa:0.1.0": target // Theme (Colors) #let theme-target = if target.contains("-") { target.split("-").at(1) } else { "light" } #let theme-style = toml("theme-style.toml").at(theme-target) #let is-dark-theme = theme-style.at("color-scheme") == "dark" #let is-light-theme = not is-dark-theme #let main-color = rgb(theme-style.at("main-color")) #let dash-color = rgb(theme-style.at("dash-color")) #let main-font = ( "Charter", "Source Han Serif SC", "Source Han Serif TC", "Linux Libertine", ) #let code-font = ( "BlexMono Nerd Font Mono", "DejaVu Sans Mono", ) #let code-theme-file = theme-style.at("code-theme") #let code-extra-colors = if code-theme-file.len() > 0 { let data = xml(theme-style.at("code-theme")).at(1) let find-child(elem, tag) = { elem.children.find(e => "tag" in e and e.tag == tag) } let find-kv(elem, key, tag) = { let idx = elem.children.position(e => "tag" in e and e.tag == "key" and e.children.first() == key) elem.children.slice(idx).find(e => "tag" in e and e.tag == tag) } let plist-dict = find-child(data, "dict") let plist-array = find-child(plist-dict, "array") let theme-setting = find-child(plist-array, "dict") let theme-setting-items = find-kv(theme-setting, "settings", "dict") let background-setting = find-kv(theme-setting-items, "background", "string") let foreground-setting = find-kv(theme-setting-items, "foreground", "string") ( bg: rgb(background-setting.children.first()), fg: rgb(foreground-setting.children.first()), ) } else { ( bg: rgb(239, 241, 243), fg: none, ) }
https://github.com/DashieTM/nix-introduction
https://raw.githubusercontent.com/DashieTM/nix-introduction/main/topics/nixos.typ
typst
#import "../utils.typ": * #polylux-slide[ == NixOS #v(15pt) - a GNU/Linux distribution - fundamentally different file system design - nix store - otherwise just like any penguin variant - only configures and installs system wide programs - use home-manager for user-based configuration #pdfpc.speaker-note(```md ```) ]
https://github.com/ice1000/website
https://raw.githubusercontent.com/ice1000/website/main/dtt-dev/wip.typ
typst
#import "config.typ": * #show: dtt.with(title: "WIP") // Cartesian coproduct #definition("Sum")[ We say a type theory has _sum type_ if it has the following constructions: + $ (Γ⊢A #h(2em) Γ⊢B)/(Γ ⊢ A + B) $ The _formation rule_, + $ (Γ ⊢ a:A)/(Γ ⊢ inl(a) : A + B) \ (Γ ⊢ b:B)/(Γ ⊢ inr(b) : A + B) $ The _introduction rules_, + $ (Γ ⊢ s : A + B \ Γ, x:A ⊢ u : C #h(2em) Γ, y:B ⊢ v : C)/ (Γ ⊢ elim_+(s, x. u, y. v) : C) $ The _elimination rule_; such that the following rules are derivable: + $Γ ⊢ (A + B)[σ] ≡ A[σ] + B[σ]$ the fact that sum is preserved by substitution action, + $ (Γ ⊢ a:A)/(Γ ⊢ elim_+(inl(a), x. u, y. v) ≡ u[a slash x] : C) \ (Γ ⊢ b:B)/(Γ ⊢ elim_+(inr(b), x. u, y. v) ≡ v[b slash y] : C) $ The $β$-rules, + $ (Γ, x:A+B ⊢ u : C \ u_1 := u[inl(y) slash x] #h(2em) u_2 := u[inr(y) slash x] )/ (Γ, x:A+B ⊢ u ≡ elim_+(x, y. u_1, y. u_2) : C) $ The $η$-law. ] #definition("Raw extensional equality")[ Given $Γ⊢a:A$ and $Γ⊢b:A$. A _raw extensional equality_ consists of the following data: + A type $Γ⊢X$, + The equality reflection rule, namely $ (Γ⊢p:X)/(Γ⊢a≡b:A) $ ] Then, $a=_A b$ is an instance of such a raw extensional equality, which can be characterized as follows: #definition("Extensional equality")[ The extensional equality $a=_A b$ is a raw extensional equality such that for every other raw extensional equality $X$, there exists a _unique_ term, called the _reflexivity principle_: + $ Γ ⊢ h : a =_A b $ such that: ]
https://github.com/ckunte/resume
https://raw.githubusercontent.com/ckunte/resume/master/ckunte-resume.typ
typst
// <NAME>'s resume #import "/inc/preamble.typ": resume #show: doc => resume(doc) // meta info #let auth_name = "<NAME>" #let auth_mail = "<EMAIL>" #let res_title = auth_name + " - resumé" #let start_year = 1995 // year of beginning my career #let curr_year = int(datetime.today().display("[year]")) // current year in int. #let tot_exp = calc.abs(curr_year - start_year) // total exp. in years #let op_exp = calc.abs(curr_year - start_year - 16) // oper. exp. in years // #set document( title: res_title, author: auth_name, ) #set page(header: context { if counter(page).get().first() > 1 [ ~ #h(1fr) _ #auth_name _ ] }) // title + subtitle #align(center, text(18pt)[ *#auth_name* ]) #align(center, [ #auth_mail ]) // \ Offshore structures engineer with #tot_exp years of proven track record in engineering, fabrication, and installation of fixed and floating offshore systems, and #op_exp years in supporting and troubleshooting for operating units./*Designated technical authority for fixed structures, and mooring systems.*/ Experienced in managing projects and engineering teams, inter-discipline coordination, cost control, and stakeholder management. Self-driven professional, striving for safety and quality in all undertaken activities without compromising schedule or cost. Strives to help deliver challenging projects, and manage assets efficiently---both as a team leader as well as an individual contributor. Generates value by employing competitive scoping, standardisation, automation where practicable, and by delivering via others. = Education / 2021: Wind energy, Technical University of Denmark (DTU, DK) // https://www.coursera.org/account/accomplishments/certificate/Y9CRZSXUSTWB / 2017: Project management framework, Shell Academy, IN / 2016: P299 Layout course, Shell Academy, IN / 2013: Managing upstream business, Shell Academy, NL / 2012: Advanced analysis with USFOS, MY / 2010: Assessment of maritime (hull) structures, DNV, NL / 2008: Facilities integration and production engineering, Shell Academy, NL / 2008: Developing Exploration and Production business skills, Shell Academy, NL / 2007: Advanced knowledge management, Shell Academy, NL / 1994: M.Eng., Structural, Karnatak University, IN = Professional accreditations / 2015: Associate member of the Royal Institution of Naval Architects / 2011: Member of American Society of Mechanical Engineers = Honours / 2023: For successfully leading the delivery and assurance of the engineering design of the Crux substructure to completion, _by Shell Australia_. / 2021: Awarded Distinguished Talent Residency for contributions to Australian and international projects in the energy sector, _by Government of Australia_. / 2020: For developing a criteria for reliability for a manned fixed platform in HI field offshore West Africa, _by Shell Nigeria_. / 2019: Service Recognition Award for enabling the concept of a fixed offshore structure in 170m in challenging design conditions (calcareous soils) and prevailing geo-hazards, with robustness to pass Decision Gate 3, _by Shell Australia_. / 2018: For successfully leading the delivery and assurance of the engineering design, construction, and installation of the CALM buoy replacement, _by Brunei Shell Petroleum_. / 2017: For championing new technology, product development and maturation (viz., employing smoothed particle hydrodynamics in remote flare buoy design; flaring, station-keeping) in extreme low wind conditions, _by Qatar Shell_. / 2016: For developing a lean new emergency power generation host within PAA platform's highly congested layout, and designing it to withstand blast over-pressures, while minimising impact to the supporting box girder deck, saving 67% tonnage, and simplifying offshore construction activity, _by Sakhalin Energy_. / 2013: Service recognition award (drilling, conductor repair) for engineering and execution of novel and low cost conductor repairs at SFDPA platform, _by Shell Malaysia_. / 2012: For mitigating fabrication challenges in eight lift safety critical welding joints in E8K and F13K compression modules, 1,800t each, _by Shell Malaysia_. / 2011: For (a) the maturation of floating LNG's weather-vaning turret-mooring concept, and response-based mooring design for application in harsh cyclonic environment, (b) turret size optimisation, and (c) developing a qualification process for the largest polyester rope for station-keeping for ultra deep water applications, jointly by _Shell Projects and Technology_ and _Shell Australia_. / 2005: For developing and designing Kikeh topsides for the catamaran tow to mate with Asia's first deep water truss SPAR, _by Murphy Oil Malaysia_. / 2001: For engineering and execution of two lean fixed offshore platforms, Bintang A and B, _by ExxonMobil Malaysia_. / 2000: For evaluating and mitigating foundation reliability from well-blowout event at EWE platform, _by Unocal Thailand_. = Positions / 2024-date: Principal engineer, Kent Australia / 2019-24: Substructure lead, Crux project, Shell Australia Pty Ltd / 2016-18: Principal technical expert, Shell India Markets Pvt Ltd / 2012-15: Team lead offshore structures, Shell Malaysia Exploration \& Production / 2006-11: Snr. research engineer, Shell Intl. Exploration \& Production, The Netherlands / 2000-06: Lead offshore structures engineer, Technip Malaysia / 1996-00: Offshore structures engineer, <NAME>ers India / 1995-96: Junior engineer, Gammon India = Monograph / 2024: #link("https://github.com/ckunte/m-one/releases/")[m-one] --- a collection of notes and code from engineering offshore structures. = Technical notes and papers == Development / 2023: <NAME>, <NAME>, <NAME>, _Development of time load histories for cyclic pile loading for Crux platform_, Crux project library. / 2022: <NAME>, <NAME>, _Crux reliability accounting for wave-in-deck loading_, Crux project library. / 2022: <NAME>, _A review of changes in ISO 19902:2020 standard and their relevance to CRUX fixed steel offshore platform design_, Crux project library. / 2021: <NAME>, _Structural steel grade_, Crux project library. / 2021: <NAME>, _Crux Topsides: Review of Weights_, Crux project library. / 2021: <NAME>, _A review of helideck and its support structure weights_, Crux project library. / 2021: <NAME>, _Review and selection of offshore pedestal-mounted crane standard_, Crux project library. / 2020: <NAME>, <NAME>, _Offshore West Africa: $gamma_E$ and $R_m$_ for exposure levels, Shell P&T library. / 2020: <NAME>, _Jacket in-service performance assessment from proposed revisions to horizontal frame elevations_, Crux project library. / 2020: <NAME>, _Riser span assessment_, Crux project library. / 2020: <NAME>, _J-tube design assessment_, Crux project library. / 2020: <NAME>, _A review of tenderer-submitted information in support of steel mill capabilities in the context of requirements for offshore structural steel materials for Crux project_, Crux project library. / 2019: <NAME>, _Crux topsides elevation considerations_, Crux project library. / 2019: <NAME>, _Review and selection of offshore pedestal-mounted crane standard for the Crux project_, Crux project library. / 2018: <NAME>, <NAME>, <NAME>, _Determination of exposure level for the Crux fixed offshore platform_, Shell P&T library. / 2018: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, _Feasibility for remote flare deployment offshore Qatar_, Shell P&T library. / 2017: <NAME>, <NAME>, <NAME>, Crux fixed platform -- _Substructure request for information_, Shell P&T library. / 2017: <NAME>, <NAME>, <NAME>, _Chinese GB steel feasibility for fixed platform concept in Crux field development_, Shell P&T library. / 2017: <NAME>, Crux fixed platform -- _Influence of wider topsides layout and potential future cantilever module on substructure design_, Shell P&T library. / 2016: <NAME>, <NAME>, <NAME>, et al., Crux fixed platform -- _Influence of soil sensitivity on platform foundation_, Shell P&T library. / 2014: <NAME>, <NAME>, <NAME>, _A minimum facility, low cost substructure concept for SF-LCD project_, Shell Malaysia library. / 2010: <NAME>, <NAME>, _FLNG Lean turret mooring feasibility_, Shell P&T library. / 2010: <NAME>, <NAME>, <NAME>, _Generic FLNG mooring and hybrid riser tower design -- Feasibility study for Tupi field_, Shell P&T library. / 2010: <NAME>, <NAME>, <NAME>, _Qualification of polyester mooring ropes_, Shell P&T library. / 2009: <NAME>, <NAME>, <NAME>, _Generic FLNG mooring and hybrid riser tower design -- Feasibility study for Carnarvon basin_, Shell P&T library. / 2009: <NAME>, <NAME>, _Generic FLNG mooring design feasibility for Carnarvon basin_, Shell P&T library. / 2009: <NAME>, <NAME>, _Shell FLSO Concept -- External turret mooring and riser analysis report_, Shell P&T library. == Drilling support / 2017: <NAME>, Crux fixed platform -- _Temporary drilling deck_, Shell P&T library. / 2016: <NAME>, <NAME>, _Review of Crux fixed platform for jack-up access_, Shell P&T library. / 2016: <NAME>, <NAME>, Crux fixed platform -- _Preliminary structural feasibility of early TAD drilling over jacket substructure_, Shell P&T library. / 2014: <NAME>, _Feasbility of BTMPB platform for well intervention activities at BT-206_, Shell Malaysia library. / 2014: <NAME>, <NAME>, _Feasibility of SFDP-A platform for pre-drill and well intervention activities_, Shell Malaysia library. == Installation / 2021: <NAME>, _Grouting_, Crux project library. / 2021: <NAME>, _Assessment of Buoyancy and Flotation Tanks for Jacket Installation_, Crux project library. / 2021: C Kunte, _Criteria for jacket on-bottom stability and storm safety_, Crux project library. / 2021: C Kunte, _Drop object impact assessment of drill pipe over drilling template_, Crux project library. / 2020: C Kunte, _Integrity assessment of piles during sea-transportation_, Crux project library. / 2019: <NAME>, _Drill caisson design_, Crux project library. / 2018: <NAME>, <NAME>, <NAME>, <NAME>, Crux fixed platform -- _Feasibility of jacket installation over pre-drilled wells subsea_, Shell P&T library. / 2017: <NAME>, Crux fixed platform -- _Structural integrity assessment of topsides during sea-transportation_, Shell P&T library. / 2015: <NAME>, <NAME>, _Barge motion responses in the South China Sea_, Shell Malaysia library. == Asset integrity management / 2023: <NAME>, _A review of 2022 underwater inspection reports for strength and serviceability of MLJ1 and MLJ2 platforms offshore Brunei_, Shell P&T library. / 2016: <NAME>, <NAME>, _Loading platform pile integrity check during fender replacement at BLNG jetty_, Shell P&T library. / 2016: <NAME>, <NAME>, _Integrity assessment of breasting dolphin structures during air block fender change out stages, BLNG jetty_, Shell P&T library. / 2016: <NAME>, P Sarathi, _Cell fender feasibility for breasting dolphins, BLNG jetty_, Shell P&T library. / 2016: <NAME>, <NAME>, <NAME>, <NAME>, _Sakhalin LNG plant -- Structural adequacy of 125m and 60m flare derricks for increased wind speeds_, Shell P&T library. / 2016: <NAME>, <NAME>, _PAA offshore platform -- Review of the new proposed emergency power generation module structure for accidental exposure to blast over-pressures_, Shell P&T library. / 2014: <NAME>, <NAME>, _A review of SJQA platform's structural integrity and its feasibility as tie-in host_, Shell Malaysia library. / 2013: <NAME>, <NAME>, <NAME>, <NAME>, _North Sabah ADP -- Structural feasibility of platforms For the chemical delivery system_, Shell Malaysia library. / 2013: <NAME>, _Design corrosion allowances_, Shell Malaysia library. = Software development / typst-snippets-st: Offers useful text-expanding snippets for Sublime Text editor in authoring papers, notes, reports, and viewgraphs effortlessly Typst. (#link("https://github.com/ckunte/typst-snippets-st")[Repository], MIT license, open source, freeware) / typst-snippets-vim: Offers useful text-expanding snippets for Vim and Neovim text editors in authoring papers, notes, reports, and viewgraphs effortlessly Typst. (#link("https://github.com/ckunte/typst-snippets-vim")[Repository], MIT license, open source, freeware) / csv2sacs: Python scripts to convert Metocean data into a readily usable SACS seastate input file(s). (#link("https://github.com/ckunte/csv2sacs")[Repository], MIT license, open source, freeware) / latex-snippets-st: Offers useful text-expanding snippets for Sublime Text editor in authoring papers, notes, and reports effortlessly in LaTeX. (#link("https://github.com/ckunte/latex-snippets-st")[Repository], MIT license, open source, freeware) / latex-snippets-vim: Offers useful text-expanding snippets for Vim and Neovim text editors in authoring papers, notes, and reports effortlessly in LaTeX. (#link("https://github.com/ckunte/latex-snippets-vim")[Repository], MIT license, open source, freeware) / sacs_st: A cross-platform syntax highlighting plug-in for Sublime Text editor that colour codes various SACS input parameters to help break the monotony of text and improve readability of model input files. (#link("https://github.com/ckunte/sacs_st")[Repository], MIT license, open source, freeware) / usfos_st: A cross-platform syntax highlighting plug-in for Sublime Text editor that colour codes various USFOS input parameters to help break the monotony of text and improve readability of model input files. (#link("https://github.com/ckunte/usfos_st")[Repository], MIT license, open source, freeware) / chisel: A lean, static website generator publishing software written for python with many useful features. (#link("https://github.com/ckunte/chisel")[Repository], MIT license, open source, freeware) = Training material / offshore-lifts: Educational presentation pack covering offshore lifts (#link("https://github.com/ckunte/offshore-lifts")[source]) / structural-dynamics: Educational presentation pack covering historical underpinnings and introduction to structural dynamics (#link("https://github.com/ckunte/structural-dynamics")[source]) / git-talk: Education presentation pack covering version control for engineers (using git) for model management (#link("https://github.com/ckunte/git-talk")[source]) #v(1fr) #align(center, text(9pt)[ _Last updated: #datetime.today().display()_ ])
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/for-00.typ
typst
Other
// Ref: true // Empty array. #for x in () [Nope] // Dictionary is traversed in insertion order. // Should output `Name: Typst. Age: 2.`. #for (k, v) in (Name: "Typst", Age: 2) [ #k: #v. ] // Block body. // Should output `[1st, 2nd, 3rd, 4th]`. #{ "[" for v in (1, 2, 3, 4) { if v > 1 [, ] [#v] if v == 1 [st] if v == 2 [nd] if v == 3 [rd] if v >= 4 [th] } "]" } // Content block body. // Should output `2345`. #for v in (1, 2, 3, 4, 5, 6, 7) [#if v >= 2 and v <= 5 { repr(v) }] // Map captured arguments. #let f1(..args) = args.pos().map(repr) #let f2(..args) = args.named().pairs().map(p => repr(p.first()) + ": " + repr(p.last())) #let f(..args) = (f1(..args) + f2(..args)).join(", ") #f(1, a: 2)
https://github.com/giZoes/justsit-thesis-typst-template
https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/lib.typ
typst
MIT License
// 南京倧孊孊䜍论文暡板 modern-nju-thesis // Author: https://github.com/OrangeX4 // Repo: https://github.com/nju-lug/modern-nju-thesis // 圚线暡板可胜䞍䌚曎新埗埈及时劂果需芁最新版本请关泚 Repo #import "@preview/anti-matter:0.0.2": anti-inner-end as mainmatter-end #import "layouts/doc.typ": doc #import "layouts/preface.typ": preface #import "layouts/mainmatter.typ": mainmatter #import "layouts/appendix.typ": appendix #import "pages/fonts-display-page.typ": fonts-display-page #import "pages/bachelor-cover.typ": bachelor-cover #import "pages/bachelor-title-page.typ": bachelor-titlepage #import "pages/bachelor-decl-page.typ": bachelor-decl-page #import "pages/bachelor-abstract.typ": bachelor-abstract #import "pages/bachelor-abstract-en.typ": bachelor-abstract-en #import "pages/bachelor-outline-page.typ": bachelor-outline-page #import "pages/list-of-figures.typ": list-of-figures #import "pages/list-of-tables.typ": list-of-tables #import "pages/notation.typ": notation #import "layouts/conclusion.typ": conclusion #import "pages/acknowledgement.typ": acknowledgement #import "utils/custom-cuti.typ": * #import "utils/textcricled.typ": onum #import "utils/bilingual-bibliography.typ": bilingual-bibliography #import "utils/custom-numbering.typ": custom-numbering #import "utils/custom-heading.typ": heading-display, active-heading, current-heading #import "utils/indent.typ": indent, fake-par #import "@preview/i-figured:0.2.4": show-figure, show-equation #import "utils/style.typ": 字䜓, 字号 // 䜿甚凜数闭包特性通过 `documentclass` 凜数类进行党局信息配眮然后暎露出拥有了党局配眮的、具䜓的 `layouts` 和 `templates` 内郚凜数。 #let documentclass( doctype: "bachelor", // "bachelor" | "master" | "doctor" | "postdoc"文档类型默讀䞺本科生 bachelor degree: "academic", // "academic" | "professional"孊䜍类型默讀䞺孊术型 academic nl-cover: false, // TODO: 是吊䜿甚囜家囟乊銆封面默讀关闭 twoside: false, // 双面暡匏䌚加入空癜页䟿于打印 // need-assignment: false, anonymous: false, // 盲审暡匏 bibliography: none, // 原来的参考文献凜数 fonts: (:), // 字䜓应䌠入「宋䜓」、「黑䜓」、「楷䜓」、「仿宋」、「等宜」 info: (:), ) = { // 默讀参数 fonts = 字䜓 + fonts info = ( title: "基于 Typst 的南京倧孊孊䜍论文", title-en: "NJU Thesis Template for Typst", grade: "20XX", student-id: "1234567890", author: "匠䞉", author-en: "<NAME>", department: "某孊院", department-en: "XX Department", major: "某䞓䞚", major-en: "XX Major", field: "某方向", field-en: "XX Field", supervisor: ("李四", "教授"), supervisor-en: "<NAME>", supervisor-ii: (), supervisor-ii-en: "", submit-date: datetime.today(), ) + info ( // 将䌠入参数再富出 doctype: doctype, degree: degree, nl-cover: nl-cover, twoside: twoside, anonymous: anonymous, fonts: fonts, info: info, onum: onum, // need-assignment: need-assignment, // 页面垃局 doc: (..args) => { doc( ..args, info: info + args.named().at("info", default: (:)), ) }, preface: (..args) => { preface( twoside: twoside, ..args, ) }, mainmatter: (..args) => { mainmatter( twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) }, mainmatter-end: (..args) => { mainmatter-end( ..args, ) }, appendix: (..args) => { appendix( ..args, ) }, // 字䜓展瀺页 fonts-display-page: (..args) => { fonts-display-page( twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) }, // 封面页通过 type 分发到䞍同凜数 cover: (..args) => { bachelor-cover( anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) }, //题目页 title: (..args) => { bachelor-titlepage( anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) }, // 声明页通过 type 分发到䞍同凜数 decl-page: (..args) => { bachelor-decl-page( anonymous: anonymous, twoside: twoside, // need-assignment: need-assignment, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) }, // 䞭文摘芁页通过 type 分发到䞍同凜数 abstract: (..args) => { bachelor-abstract( anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) }, // 英文摘芁页通过 type 分发到䞍同凜数 abstract-en: (..args) => { bachelor-abstract-en( anonymous: anonymous, twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), info: info + args.named().at("info", default: (:)), ) }, // 目圕页 outline-page: (..args) => { bachelor-outline-page( twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) }, // 插囟目圕页 list-of-figures: (..args) => { list-of-figures( twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) }, // 衚栌目圕页 list-of-tables: (..args) => { list-of-tables( twoside: twoside, ..args, fonts: fonts + args.named().at("fonts", default: (:)), ) }, // 笊号衚页 notation: (..args) => { notation( twoside: twoside, ..args, ) }, // 参考文献页 bilingual-bibliography: (..args) => { bilingual-bibliography( bibliography: bibliography, ..args, ) }, // 臎谢页 acknowledgement: (..args) => { acknowledgement( anonymous: anonymous, twoside: twoside, ..args, ) }, // 结论页 conclusion: (..args) => { conclusion( ..args, ) }, ) }
https://github.com/xrarch/books
https://raw.githubusercontent.com/xrarch/books/main/documents/a4xmanual/chapbooting.typ
typst
#import "@preview/tablex:0.0.6": tablex, cellx, colspanx, rowspanx #box([ = Booting This section describes the boot protocol used by the *A4X* firmware. The old A3X boot protocol is also supported via an embedded A3X firmware which is chain-loaded when a legacy operating system is selected, but will not be documented here. Note that all of the client-facing structures and services described here (in general, everything prefixed with `Fw`) can be found in the `Headers/a4xClient.hjk` header file, which should be included in order to access them from programs written in Jackal. A partition is bootable if it contains a valid OS record at an offset of 1 sector from the partition base (bytes 512-1023 within the partition). The OS record sector has the following layout: ``` STRUCT AptOsRecord // The 32-bit magic number must read 0x796D6173. Magic : ULONG, // A 15-character, null-terminated label for the installed // operating system. OsName : UBYTE[16], // The sector offset within the partition, at which the bootstrap // program begins. BootstrapSector : ULONG, // The count of sectors in the bootstrap program. BootstrapCount : ULONG, END ``` ]) If a valid OS record is found, the partition is assumed to be bootable. In the following sector (sector 2), a 64x64 monochrome bitmap is located. This is used as an icon in the boot picker. == The Bootstrap Program When booting from a partition, the bootstrap sectors are loaded in sequence off the disk into physical memory beginning at address 0x3000. The first 32 bits of the bootstrap must be 0x676F646E in order to be considered valid. Control is then transferred to address 0x3004 through the Jackal function pointer with the following signature: #box([ ``` FNPTR FwBootstrapEntrypoint ( IN devicedatabase : ^FwDeviceDatabaseRecord, IN apitable : ^FwApiTableRecord, IN bootpartition : ^VOID, IN args : ^UBYTE, ) : UWORD ``` ]) That is, as per the Jackal ABI for XR/17032, a pointer to the *DeviceDatabase* is supplied in register `a0`, a pointer to the *ApiTable* is supplied in register `a1`, a handle to the boot partition is supplied in register `a2`, and an argument string is supplied in register `a3`. The bootstrap program can return a value in register `a3`. Note that memory in the range of 0x0 through 0x2FFF should _not_ be modified until *A4X* services will no longer be called, as this region is used to store its runtime data (such as the initial stack). After this region is trashed, *A4X* may only be re-entered through a system reset (which can be accomplished by jumping to physical address 0xFFFE1000 with virtual addressing disabled). == The Device Database The *DeviceDatabase* is a simple structure constructed in low memory by the firmware. It contains information about all of the devices that were detected. It has the following layout: ``` STRUCT FwDeviceDatabaseRecord // 32-bit count of the total RAM detected in the system. TotalRamBytes : ULONG, // The number of processors detected. ProcessorCount : UBYTE, // The number of bootable partitions found. BootableCount : UBYTE, Padding : UBYTE[2], // A table of information about all of the RAM slots. Ram : FwRamRecord[FW_RAM_MAX], // A table of information about all of the physical disks. Dks : FwDksInfoRecord[FW_DISK_MAX], // A table of information about devices attached to the Amtsu // peripheral bus. Amtsu : FwAmtsuInfoRecord[FW_AMTSU_MAX], // A table of information about the boards attached to the EBUS // expansion slots. Boards : FwBoardInfoRecord[FW_BOARD_MAX], // A table of information about each processor detected in the // system. Processors : FwProcessorInfoRecord[FW_PROCESSOR_MAX], // Information about the boot framebuffer, or lack thereof. Framebuffer : FwFramebufferInfoRecord, // Information about the boot keyboard, or lack thereof. Keyboard : FwKeyboardInfoRecord, // The machine type -- // XR_STATION, XR_MP, or XR_FRAME. MachineType : FwMachineType, END ``` Note that the `Headers/a4xClient.hjk` header file should be used to access the device database and other *A4X* structures - this incomplete information is only provided here for quick reference. #box([ == The API Table A pointer to an API table is passed to the bootstrap program. The API table consists of function pointers that can be called to receive services from the firmware. The currently defined APIs follow: ``` STRUCT FwApiTableRecord PutCharacter : FwApiPutCharacterF, GetCharacter : FwApiGetCharacterF, ReadDisk : FwApiReadDiskF, PutString : FwApiPutStringF, KickProcessor : FwApiKickProcessorF, END ``` ]) === PutCharacter ```FNPTR FwApiPutCharacterF ( IN byte : UWORD, )``` Puts a single character to the firmware console. === GetCharacter ```FNPTR FwApiGetCharacterF () : UWORD``` Returns a single byte from the firmware console. This is non-blocking and returns -1 (0xFFFFFFFF) if no bytes are available. === ReadDisk ``` FNPTR FwApiReadDiskF ( IN partition : ^VOID, IN buffer : ^VOID, IN sector : ULONG, IN count : ULONG, ) : UWORD ``` Reads a number of sectors from the specified partition handle into the buffer. The base address of the buffer _must_ be aligned to a sector size boundary. Returns *TRUE* (non-zero) if successful, *FALSE* (zero) otherwise. === PutString ``` FNPTR FwApiPutStringF ( IN str : ^UBYTE, ) ``` Puts a null-terminated string of bytes to the firmware console. Could be easily synthesized from *PutCharacter* but is provided for convenience to small boot sectors written in assembly language. === KickProcessor ``` FNPTR FwApiKickProcessorF ( IN number : UWORD, IN context : ^VOID, IN callback : FwKickProcessorCallbackF, ) ``` Causes the processor with the specified number to execute the provided callback. The callback routine is called with the opaque context value and with the number of the processor. Its signature follows: ``` FNPTR FwKickProcessorCallbackF ( IN number : UWORD, IN context : ^VOID, ) ``` *KickProcessor* does not wait for the callback to be executed; execution continues on both processors asynchronously. If synchronization is required, it must be implemented manually. If the processor with the given number (equivalent to its index in the *DeviceDatabase*) does not exist, the results are undefined. Also note that the firmware does not contain multiprocessor synchronization, so if firmware services may be invoked by multiple processors concurrently, locking must be provided by the user. The size of the initial stack provided by the firmware for processors other than the boot processor is not explicitly defined here, but is quite small, so the depth of the call stack during execution of the callback must either be very small, or the recipient processor must switch quickly to a new stack.
https://github.com/drupol/master-thesis
https://raw.githubusercontent.com/drupol/master-thesis/main/src/thesis/3-tools.typ
typst
Other
#import "imports/preamble.typ": * #import "theme/template.typ": * #import "theme/common/titlepage.typ": * #import "theme/common/metadata.typ": * #import "theme/disclaimer.typ": * #import "theme/leftblank.typ": * #import "theme/acknowledgement.typ": * #import "theme/abstract.typ": * #import "theme/infos.typ": * #import "theme/definition.typ": * #chapterquote( title: "Software evaluation", ref: "chapter3", quoteAttribution: <clarke1973>, quoteText: [ Any sufficiently advanced technology is indistinguishable from magic. ], ) This chapter explores the pivotal role of tooling in achieving reproducibility within #gls("SE"), highlighting the importance of environment consistency, dependency management, and process isolation. Reproducibility in #gls("SE") is not merely a desirable attribute but a cornerstone of trustworthy, reliable, and verifiable software development practices. As software systems grow increasingly complex and integral to every facet of the modern world, from critical infrastructure to personal devices, the stakes for ensuring their reproducibility have never been higher. This chapter introduces and examines four distinct methods for building software, each with its unique approach: - Bare compilation It is the most rudimentary method, depends on the operating system's compilers and libraries for software construction. - Compilation with Docker Using containerization technology, encapsulates not just the software and its dependencies but also the entire runtime environment. - Compilation with Nix Nix uses a unique store for packages built in isolation, each with a unique identifier that includes dependencies, preventing conflicts and ensuring reproducible environments. - Compilation with Guix Inspired by Nix, Guix offers a transactional package management system that isolates dependencies to ensure consistent and reproducible software environments through specific version-linked profiles. The four evaluation methods chosen for detailed evaluation in the context of reproducibility represent a wide range of approaches to managing software build environments, each addressing different aspects of reproducibility. Bare compilation was selected to provide a baseline, demonstrating the fundamental challenges encountered without the aid of advanced tooling, such as environmental inconsistencies and dependency conflicts. This method serves as a contrast to the more sophisticated techniques that follow. Docker is included for its widespread adoption and popularity, as well as its approach to encapsulating the runtime environment, which significantly mitigates issues arising from system variability. Guix and Nix are examined due to their unique approach to dependency management and environment isolation, employing a package management approach that is based on the functional paradigm (@def-functional-package-management) to ensure exact reproducibility of environments across different systems. The chapter aims to cover a spectrum from the most basic to the most advanced strategies. #definition( term: "Functional package management", name: "def-functional-package-management", )[ From @10-1007-978-3-319-27308-2_47, functional package management is a discipline that transcribes the functional programming paradigm to software deployment: build and installation processes are viewed as pure functions (@def-pure-function) in the mathematical sense whose result depends exclusively on the inputs (@def-inputs-outputs), and their result is a value that is, an immutable directory. ] This chapter aims to provide readers with an understanding of how these contribute to the broader goal of reproducible #gls("SE"). Through a detailed exploration of each approach, readers will gain insight into the strengths, weaknesses, and applicability of Bare compilation, Docker, Guix and Nix in various software development scenarios. == Methodology Our primary objective is to assess the reproducibility of a software build using four different methods: Bare compilation, Docker, Guix, and Nix. By compiling a C program (@datetime.c) with each tool, we can evaluate reproducibility both over space and time (@reproducibility). The study uses a quantitative research design, focusing on the comparison of binary files generated from compiling identical source code with different methods, on the same environment. This approach allows for an empirical assessment of reproducibility challenges inherent to each compilation tool and environment. === Evaluation Criteria We will consider three primary criteria. Firstly, *reproducibility in time* assesses whether the outputs of builds are identical across repeated compilations in the same environment. This criterion involves compiling the same source code twice with a few seconds of interval between compilations. By comparing the outputs of these compilations, we can determine if the build process produces consistent results over time. Secondly, *reproducibility in space* focuses on the consistency of build outputs across different environments. To evaluate this, the same source code is compiled in various environments. This process helps to ensure that the software build process is not dependent on specific environmental factors and can produce identical outputs regardless of where it is compiled. Lastly, the *reproducibility of the build environment* evaluates the stability and consistency of the environment itself, including the dependencies required for building the output. This criterion ensures that the environment, which encompasses all necessary tools and libraries, remains stable and consistent across different instances and setups. === Tools And Technologies The evaluation of reproducibility tools in this study encompasses several approaches to software compilation and package management, each with its unique methodology. In @ch3-tool1, the bare compilation method involves direct compilation on the host system without the use of containerization or package management tools.This approach relies on the default tools and libraries installed in the operating system, providing a straightforward but less controlled environment for building software. This method is assessed to understand the baseline reproducibility and potential variability introduced by the host system's native environment. In @ch3-tool2, Docker is used to provide a containerized environment for software compilation. Using Docker containers ensures that the build process occurs in a consistent and isolated environment, independent of the host system's configuration. This method helps in evaluating how containerization can enhance reproducibility by encapsulating all necessary dependencies and tools within a controlled and replicable environment. In @ch3-tool3, the Guix package ecosystem is employed to manage the software build process. Guix focuses on providing a reproducible and declarative approach to package management, ensuring that the build environment and dependencies are precisely defined and versioned. This approach is examined for its ability to maintain consistency and reproducibility across different systems and environments by leveraging Guix's robust package management features. In @ch3-tool4, the Nix package ecosystem is used to manage and build software. Similar to Guix, Nix offers a declarative and reproducible package management system, allowing for precise control over the build environment and dependencies. The evaluation of Nix focuses on its capability to provide a reproducible build environment that can be consistently replicated across various systems, enhancing the reliability and stability of the software development process. === Scenarios Our examples and builds focus on custom-made scenarios to highlight the differences in reproducibility across the four tools. There are multiple scenarios being evaluated: In the first scenario, using @ch3-tool1, a C program is built using the host default C compiler. The second scenario involves @ch3-tool2, where a C program is built in a Docker container utilizing the C compiler. The third scenario, with @ch3-tool3, involves building a C program using Guix. Finally, there are two scenarios for @ch3-tool4: one involves building a C program using Nix legacy (not flake), and the other uses Nix flake to build the same program. === Compilation And Execution <ch3-compilation-execution> A trivial C program (@datetime.c) has been chosen for its straightforwardness, allowing the focus to remain on the build process and output rather than software complexity. Each method will compile the same C program (@datetime.c) twice. Detailed steps for compilation and execution within each environment will be documented, ensuring transparency and reproducibility of the process itself by the readers. Each compilation's resulting output will be executed to verify functionality, although the correctness of the execution's output will not be evaluated. === Environment Setup To ensure the robustness and universality of our reproducibility assessment, all test scenarios described in this chapter are executed through GitHub Actions #cite(<ghActions>, form: "normal"). GitHub Actions is an automation platform that enables #gls("CICD"), allowing builds to be performed, tested, and deployed across various machines and architectures directly from GitHub repositories #cite(<9978190>,form:"normal"). Our testing environments supports three distinct architectures: - `x86_64-linux`: This represents the widely used Linux operating systems on Intel and AMD processors. To ensure a thorough evaluation, two instances, each running the different versions of Ubuntu (`20.04` and `22.04`), are employed. - `x86_64-darwin`: Dedicated to supporting macOS on Intel processors. - `aarch64-darwin`: Addressing the latest generation of macOS powered by the ARM-based Apple Silicon processors. This selection encompasses both `x86` and `ARM` architectures, as well as Linux and macOS operating systems, providing a comprehensive view of reproducibility across the most commonly used development platforms in #gls("SE"). The choice of these architectures ensures the results are relevant to a broad spectrum of development environments and application targets. Each of our scenarios is streamlined through the use of a `Makefile`. A `Makefile` as seen in @ch3-example-makefile is a text file that contains a set of directives used by the GNU `make` #cite(form: "normal", <gnumake>) utility to automate the build process of software projects. These directives contain specific shell commands. #figure( { sourcefile( file: "Makefile", lang: "Makefile", read("../../resources/sourcecode/example-makefile"), ) }, caption: [An example of `Makefile`], ) <ch3-example-makefile> Each scenario's `Makefile` essentially contain four essential steps only: - `clean`: Removes the build artefact of a build process, if any. - `build`: Executes a build process, generating an output artefact. - `check`: Prints the checksum of the build artefact. - `run`: Execute the artefact #info-box[ All source code and scenario files are available for reference under the `lib/` directory of this master's thesis source code #cite(<PolMasterThesis>, form:"normal"). Each scenario's directory contains its own `Makefile`. These makefiles can be used to locally reproduce the commands and results outlined in this document. ] Our GitHub Actions workflows #cite(<r13yBuildScenarios>,form:"normal") use these Makefiles, automating the execution of each scenario and ensuring consistency and repeatability in the process. By doing so, they empower users to locally reproduce the steps outlined in this document with full transparency. This approach aligns with best practices in #gls("SE") for reproducibility, and extends those principles to broader scientific research practices. === Output Comparison To compare the results, we will compare the checksums of the resulting outputs. We exclusively use the `nix hash path` command provided by the Nix package manager to compute the hash of a path. #info-box(kind: "important")[ The `nix hash path` command is provided by Nix, a tool we will explore in this chapter. Nix provides this command as part of its suite, but it can be applied anywhere, not just to files within the Nix ecosystem. This command distinguishes itself by its capacity to hash directories in addition to files. An alternative to this approach could have been the use of a #gls("SWHID") #cite(<hal-01865790>,form:"normal"). ] The `nix` command is available on systems with Nix installed. The difference with a traditional `sha256sum` is that the former computes the hash of the path, which includes the content and the metadata while the latter computes the hash of the content only. Another advantage of using that command is its ability to create a hash prefixed by the algorithm used, similar to #gls("SRI") #cite(<sri>, form: "normal") hashes. === Expected Outcomes At the opposite of the previous more theoretical chapters, this practical chapter aims to empirically compare the differences in reproducibility achievable with Bare compilation, Docker, Guix, and Nix. Insights into the challenges and benefits of each method will inform best practices in #gls("SE") for achieving reproducible builds. == Evaluation 1 - Bare compilation <ch3-tool1> This method is the most rudimentary approach to software compilation, relying on the host system's installed compilers and libraries to build software. This build method correspond to Scenario 1, with the corresponding `Makefile` in @ch3-makefile-scenario1, that can be executed on any system, with the commands: `make build` to compile, `make check` to print the checksum, #raw("make run") to run the compiled binary. As explained in @ch3-compilation-execution, we notice that the steps are executed twice and in @ch3-tool1-build, the steps to build, check and run the build are detailed. #figure( { sourcefile( file: "Makefile", lang: "Makefile", read("../../lib/scenario-1/Makefile"), ) }, caption: [`Makefile` of Scenario 1], ) <ch3-makefile-scenario1> #figure( { shell(read("../../resources/sourcecode/scenario-1.log")) }, supplement: "Terminal session", kind: "terminal", caption: [Terminal log of the steps to build, check and run Scenario 1], ) <ch3-tool1-build> At lines 4 and 9 of @ch3-tool1-build, we notice that the `make check` step prints two different checksums, indicating that the output of the two builds is different at each run. As a result, this build is not reproducible. This discrepancy in the output is likely caused by the dynamic replacement of the `__DATE__` and `__TIME__` macros in the source code, which are replaced with the current date and time at the moment of compilation. #heading(outlined: false, level: 3, "Reproducibility In Time") This method involves directly compiling source code on a system with only the essential compilers and libraries available on the host. This method's primary advantage lies in its simplicity and direct control over the build process, allowing for a clear understanding of dependencies and compilation steps. However, it lacks isolation from the system environment, leading to potential #emph[it works on my machine] issues due to variations in system configurations. Additionally, the lack of encapsulation and dependency management can lead to difficulties in achieving consistent and reproducible builds across different environments. This method is therefore classified as non-reproducible in time. #heading(outlined: false, level: 3, "Reproducibility In Space") This method is not reproducible in time, therefore we will consider it as not reproducible in space either. Technically it would be possible to reproduce the same output on another environment, but it would be practically impossible to run the build at exactly the same time. This method is therefore classified as non-reproducible in space. #heading(outlined: false, level: 3, "Reproducibility Of The Build Environment") The virtual machines used on Github Actions are versioned. However, the software installed on the images are not. From one build to another, we can have a different version of `gcc` or any other software installed on the image. Therefore, we have absolutely no control over the build environment and it is very complicated to reproduce the same environment on another machine. Therefore, reproducibility of the build environment is not guaranteed. == Evaluation 2 - Docker <ch3-tool2> Docker #cite(<docker>,form:"normal") has revolutionised software deployment by encapsulating applications in containers, ensuring they run consistently across any environment. Unlike traditional virtual machines, Docker containers are lightweight, share the host's kernel, and bundle applications with their dependencies, promoting the principle of #emph["build once, run anywhere"]. This approach streamlines development, testing, and production workflows, significantly reducing compatibility issues and, to some extent, simplifying scalability. Central to Docker's appeal is its contribution to the #gls("DevOps") movement, fostering better collaboration between development and operations teams by eliminating the #emph["it works on my machine"] problem. Docker's ecosystem, including the Docker Hub #cite(<dockerhub>, form: "normal"), offers a vast repository of container images, facilitating reuse and collaboration across the software community. Docker uses the #gls("OCI") standard for its container images, ensuring interoperability across different containerization technologies, including @podman and @kubernetes. The #gls("OCI") specification outlines a format for container images and a runtime environment, aiming to create a standard that supports portability and consistency across various platforms and cloud environments. Due to its popularity #cite(<9403875>, form: "normal", supplement: [p. 9]), Docker is a key player in modern software development, enabling efficient, consistent, and scalable applications through containerization, supporting agile and #gls("DevOps") practices, and accelerating the transition from development to production. #figure( sourcefile( file: "Dockerfile", lang: "dockerfile", read("../../lib/scenario-2/Dockerfile"), ), caption: [From Scenario 2, the `dockerfile` used by Docker], ) <ch3-dockerfile> This method involves creating an #gls("OCI") image, compiling @datetime.c, through a `Dockerfile` and setting the compilation result as default command as shown in @ch3-dockerfile. This ensures that each time the image is executed, the compiled executable runs within the container. However, instead of printing only the checksum of the resulting binary, the `check` step also outputs the checksum of the image. #figure( { sourcefile( file: "Makefile", lang: "Makefile", read("../../lib/scenario-2/Makefile"), ) }, caption: [`Makefile` of Scenario 2], ) <ch3-makefile-scenario2> #figure( shell(read("../../resources/sourcecode/scenario-2.log")), supplement: "Terminal session", kind: "terminal", caption: [Terminal log of the steps to build, check and run Scenario 2], ) <ch3-docker-build> #heading(outlined: false, level: 3, "Reproducibility In Time") In @ch3-docker-build, it is observed on lines 5 and 12 that building the image twice and extracting the resulting binary produces different checksums. Additionally, on lines 6 and 13, it is evident that the checksums of the images are inevitably different. Consequently, this method is classified as non-reproducible over time. #heading(outlined: false, level: 3, "Reproducibility In Space") This scenario was executed on various machines and architectures, resulting in different binaries and images. Therefore, this method is classified as non-reproducible in space as well. #heading( outlined: false, level: 3, "Reproducibility Of The Build Environment", ) <ch3-docker-build-env> The reproducibility of build environments in Docker images, while generally reliable in the short term, can face challenges over time. Docker images are built on layers, often starting from base images provided by specific vendors. These base images can receive updates that alter their contents, meaning a `Dockerfile` that successfully built an image at one time might not produce an identical image later due to changes in its base layers #cite(<9403875>, form: "normal", supplement: [p. 1]). Additionally, not pinning specific versions of base images and external dependencies in the `Dockerfile` can lead to inconsistencies, making the exact reproduction of a Docker environment challenging if not managed carefully. Therefore, while Docker simplifies the consistency of deployment environments, ensuring long-term exact reproducibility requires careful management of image sources and dependencies. Docker is intrinsically designed to facilitate reproducible builds, with the capability to generate identical containers across multiple executions. However, the challenge to reproducibility arises not from Docker's fundamental features but from the use of specific base images within Docker containers. A significant illustration of this problem is shown in @ch3-docker-build, where rebuilding the image results in different containers even though the base image version has been pinned to a specific commit at lines 1 and 7. #info-box(kind: "info")[ "Pinning" refers to the practice of specifying exact versions of software, base images, or dependencies to use when building a Docker container. This practice helps ensure that the build environment remains consistent and predictable over time, despite updates or changes to those dependencies. Pinning is crucial for maintaining consistency as it prevents the build environment from changing unexpectedly due to updates in dependencies. It also enhances reproducibility, allowing developers to recreate the same environment at a later date, which is vital for debugging and development. Moreover, it enhances reliability by reducing the likelihood of encountering unexpected issues or conflicts caused by differing versions of dependencies. For example, specifying `FROM alpine:3.19.1` in a `Dockerfile` instead of `FROM alpine` ensures that Alpine image at version 3.19.1 is always used, providing stability. Additionally, to minimize the risk of variation, the `build-base` package used in the `Dockerfile` (@ch3-dockerfile) is pinned to version `0.5-r3`. This mechanism applies similarly across different programming language ecosystems. However, it is important to note that version tags, like `3.19.1` or `0.5-r3`, can be replaced or updated by the maintainers, without users' awareness, potentially altering the contents of a "pinned" version and impacting reproducibility. To mitigate this issue, using digests can ensure images are anchored to a specific snapshot, offering a stronger guarantee of immutability. For instance, specifying `FROM alpine@sha256:c5b1261d6d3e43071626931fc004f70149baeba2c8ec672bd4f27761f8e1ad6b`, as shown in @ch3-dockerfile, ensures that the exact same image is used consistently, regardless of any upstream updates. While using a digest to pin the base image ensures immutability, the `apk` package manager does not support a similar mechanism, only tags are supported. It's important to be aware of the limitations of the tools #eg[the `apk` package manager] used in the base image, as even with precautions, variability in the build process may still be introduced. ] Docker's containerization technology offers a way to create consistent software environments across various systems by encapsulating both the software and its dependencies within containers. This encapsulation aids in ensuring a uniform deployment process. However, the approach's reliance on base images and the package managers they use brings forth challenges in maintaining reproducibility. This is primarily because base images might not be strictly version-controlled, and the package managers used within these images can result in the installation of varying dependency versions over time. For example, traditional package managers like `apt` (used in Debian-based #glspl("OS")) or `yum` (used in RedHat-based #glspl("OS")) do not inherently guarantee the installation of the exact same version of a software package across space and time. Typically, this variability stems from updates in the package repositories, where an `apt-get install` command might fetch a newer version of a library than was originally used. Such updates could potentially introduce unexpected behaviour or incompatibilities. Docker and similar containerization technologies act as sophisticated assemblers, piecing together the diverse components required to create a container. This process, while streamlined and efficient, is not immune to the introduction of variability at any stage of the assembly line. Whether due to updates in base images, fluctuations in package versions, or differences in underlying infrastructure, these variables can compromise the reproducibility of the resulting container (@def-deterministic-build). Recognising this, it becomes crucial for developers and researchers to approach container creation with a keen awareness of these potential pitfalls. By meticulously managing base images, employing reliable package managers, and adhering to best practices in `Dockerfile` construction, one can mitigate the risks of variability and move closer to achieving true reproducibility in containerised environments. == Evaluation 3 - Guix <ch3-tool3> @guixwebsite is an advanced package manager, designed to provide reproducible, user-controlled, and transparent package management. It leverages functional programming concepts to ensure reproducibility and reliability, using the GNU Guile #cite(<guile>, form:"normal") programming language for its core daemon, package definitions and system configurations #cite(<courtes2013functional>,form:"normal"). Central to Guix's philosophy is the concept of reproducible builds and environments. This ensures that software can be built in a deterministic manner, enabling exact replication of software environments at any point in space and time. Guix achieves this by capturing all dependencies, including the toolchain and libraries, in a way that they can be precisely recreated. It supports transactional package upgrades and rollbacks, making system modifications risk-free by allowing users to revert to previous states easily. Guix uses GNU Guile #cite(<guile>,form:"normal"), a Scheme #cite(<scheme>,form:"normal") implementation, allowing for more expressive and programmable package definitions. This choice reflects Guix's emphasis on customization and alignment with the @fsfwebsite project's philosophy, rejecting proprietary blobs and aiming for complete software freedom, which may limit hardware compatibility but enhance long-term reproducibility #cite(<9403875>,form:"normal"). Nonetheless, users have the liberty to extend Guix with custom packages, whether free or not, without compromising the tool's reproducibility capabilities. In case of disappearing upstream sources, Guix can leverage Software Heritage #cite(<swh>, form:"normal") to retrieve source code, ensuring long-term accessibility even if the original source disappears. While Guix's reliance on a general-purpose functional programming language may present a steep learning curve, it offers extensive flexibility for those proficient in Lisp-like languages. #info-box(kind: "note", ref: "info-box-proprietary-software")[ Proprietary software does not expose its source code to the public, which may seem counter-intuitive to the principles of reproducibility. Proprietary software "typically cannot be distributed, inspected, or modified by others. It is, thus, reliant on a single supplier and prone to proprietary obsolescence" #cite(<9403875>, form: "normal", supplement: [p. 3]). Ensuring the reproducibility of such software is challenging, as users lack access to the build process and the software's lifespan is often limited due to its proprietary nature. Pre-built binaries will work only as long as there are no breaking changes in dependencies like the GNU C library, making their reproducibility capabilities time-limited. Being aware of the broader implications of using proprietary software is crucial but does not necessarily compromise reproducibility at short term. However, relying on proprietary software for long-term reproducibility is risky due to the lack of transparency and control over the software's evolution. ] Guix is committed to ensuring reproducibility and reliability, based on the functional deployment model first introduced by @Dolstra2006. It assures reproducible builds by treating software environments as immutable entities, thereby minimising variability across different systems. Guix's approach to software building and package management, grounded in the principles of functional programming and transactional package upgrades, places a strong emphasis on reproducibility. However, this functional paradigm (@def-functional-package-management) introduces a learning curve and necessitates a shift from traditional imperative package management methods. Additionally, the adoption of Guix might be further complicated by the absence of non-free software availability, marking a significant consideration for teams considering Guix. #figure( { sourcefile( file: "guix.scm", lang: "Lisp", read("../../lib/scenario-3/guix.scm"), ) }, caption: [From Scenario 3, the Guix build file (`guix.scm`)], ) <ch3-default-guix> #figure( { sourcefile( file: "Makefile", lang: "Makefile", read("../../lib/scenario-3/Makefile"), ) }, caption: [`Makefile` of Scenario 3], ) <ch3-makefile-scenario3> #figure( { shell(read("../../resources/sourcecode/scenario-3.log")) }, supplement: "Terminal session", kind: "terminal", caption: [Building the C sourcecode from the Guix build file of Scenario 3], ) <ch3-guix-build> #heading(outlined: false, level: 3, "Reproducibility In time") In @ch3-guix-build, we notice on lines 5 and 11 that the output hashes are the same. This is therefore classified as reproducible in time. #heading(outlined: false, level: 3, "Reproducibility In Space") Building the program in a different environment with the same architecture (`x86_64-linux`) resulted in identical output. Compiling the source code on another architecture (`aarch64_darwin`) also produced consistent results, though different from those obtained on `x86_64-linux`. Therefore, we can conclude that the program is reproducible across different environments, #emph[modulo] the hardware architecture. #heading(outlined: false, level: 3, "Reproducibility Of The Build Environment") The reproducibility of the build environment is heavily controlled when using Guix. The dependencies are locked and pinned, it is simply not possible to create a different build environment. == Evaluation 4 - Nix <ch3-tool4> @nix is a revolutionary package management system that dramatically reshapes the landscape of software construction, consumption, deployment and management. Its distinctive methodology, grounded in the principles introduced in @Dolstra2006, marked its inception, setting a new standard for handling software packages. Central to Nix's core is its use of the Nix language, a domain specific Turing-complete language that facilitates the description of software packages, their dependencies, and the environments in which they operate. #info-box(ref: "def-turing-complete")[ The term "Turing-complete" is named after the British mathematician and logician Alan Turing, who introduced the concept of a Turing machine as a fundamental model of computation. A Turing-complete language is a programming language that can simulate a Turing machine, a theoretical device that can solve any computation that can be described algorithmically. Turing completeness is a fundamental property of any programming language that can perform any computation that a Turing machine can, given enough time and memory. This property allows a language to express any algorithm or computation, making it a powerful tool for software development. Examples of Turing-complete languages include: Python, PHP, C++ and JavaScript. On the other hand, non-Turing-complete languages, which are limited in their computational capabilities, include: SQL, Regex and HTML. ] This language enables Nix to implement a functional deployment model, ensuring reproducibility, reliability, and portability across different systems by treating packages as functions of their inputs, which results in deterministic builds. Nix emphasises a deterministic build environment, allowing developers to specify and isolate dependencies explicitly. This method significantly mitigates #emph["it works on my machine"] issues by providing a high degree of control over the build environment. Nix's strength in ensuring reproducibility comes with the need to embrace its unique approach to system configuration and package management, representing a paradigm shift for new users. #info-box(kind: "conclusion")[ Nix essentially modifies the #gls("POSIX", long: false) standard by installing software in unique locations rather than following the shared file structure described by the #gls("FHS"). This seemingly minor change brings about several advantageous properties, such as software composition, immutability, configuration rollback, caching and reproducibility. ] Nix provides two principal methodologies that are not mutually exclusive: the legacy method (\u{00B1}2006) and the relatively newer #emph[Flake] (\u{00B1}2020) approaches. === Nix legacy method The legacy way of using Nix involves defining a `default.nix` file that is similar to a function definition in the Nix programming language. This file contains a set of inputs, specifies dependencies, the build command and its output. By default, this method does not enable pure evaluation mode, meaning the hermeticity of the build process is not guaranteed. As a result, potential uncontrolled side effects may occur during the build process. For instance, as demonstrated in @ch3-default-nix at line 2, we manually enforce a very specific version of the `pkgs` variable, a specific snapshot of the Nix package repository that fixes the versions of all packages and libraries. Similarly to the process outlined in @ch3-docker-build-env for Docker, this approach, known as #emph[dependency pinning], ensures consistency and reproducibility in the build environment. #figure( { set text(size: .85em) sourcefile( file: "default.nix", lang: "nix", read("../../lib/scenario-4/default.nix"), ) }, caption: [The Nix build file (`default.nix`) from Scenario 4], ) <ch3-default-nix> #figure( { sourcefile( file: "Makefile", lang: "Makefile", read("../../lib/scenario-4/Makefile"), ) }, caption: [`Makefile` of Scenario 4], ) <ch3-makefile-scenario4> #figure( { shell(read("../../resources/sourcecode/scenario-4.log")) }, supplement: "Terminal session", kind: "terminal", caption: [Building the C sourcecode with Nix in Scenario 4], ) <ch3-default-nix-build> === Nix Flake Nix #emph[Flake] introduces a structured approach to managing Nix projects, focusing on reproducibility and ease of use. Currently in an experimental phase, Flake is anticipated to transition to a stable feature soon due to increasing community endorsement (@ch3-flake-vs-legacy) and the tangible reproducibility advantages it offers. #figure( image("../../resources/images/flake-vs-legacy.jpg"), caption: [On the left, new repositories containing a `flake.nix` file, and on the right, containing a `default.nix` file (#link("https://x.com/DeterminateSys/status/1794394407266910626")[Determinate System]) ], ) <ch3-flake-vs-legacy> Flakes aim to simplify and enhance the Nix experience by providing an immutable, version-controlled way to manage packages, resulting in significant improvements in reproducibility and build isolation. Flakes manage project dependencies through a single, top-level `flake.lock` file, which is automatically generated to precisely pin the versions of all dependencies, including transitive ones, as specified in the `flake.nix` file. This file ensures project consistency and reproducibility across different environments. In addition to altering the Nix command-line syntax, Flakes enforce a specific structure and entry point for Nix expressions, standardising project setup and evaluation. They enable pure evaluation mode by default, which enhances the purity and isolation of evaluations, making builds more consistent and reducing side effects. For instance, making external requests during a build is not possible with Flakes, ensuring that every dependency must be explicitly declared. Flakes require changes to be tracked through `git`, enabling the exact reversion of the project to be pinned in the `flake.lock` file. The files `flake.nix` and `flake.lock` are complementary and central to the locking mechanism that ensures reproducibility. Together, when committed in a project, they guarantee that every user of a Flake, regardless of when they build or deploy the project, will use the exact same versions of dependencies, thereby ensuring that the project is built consistently every time. However, it is possible to have only a `flake.nix` file without a `flake.lock` file. In such cases, having a reproducible build environment is not guaranteed since dependencies could drift to newer versions. #figure( { sourcefile( file: "flake.nix", lang: "nix", read("../../lib/scenario-5/flake.nix"), ) }, caption: [The Nix Flake file (`flake.nix`) from Scenario 5], ) <ch3-flake-nix> #figure( { sourcefile( file: "Makefile", lang: "Makefile", read("../../lib/scenario-5/Makefile"), ) }, caption: [`Makefile` of Scenario 5], ) <ch3-makefile-scenario5> #figure( { shell(read("../../resources/sourcecode/scenario-5.log")) }, supplement: "Terminal session", kind: "terminal", caption: [Building the C sourcecode with Nix flake in Scenario 5], ) <ch3-nix-flake-build> #heading(outlined: false, level: 3, "Reproducibility In Time") In @ch3-default-nix-build, we notice on line 5 and 11 that building twice the sourcecode using Nix's legacy method produces the same output. In @ch3-nix-flake-build, on line 4 and 9 we notice the same thing. This is therefore classified as reproducible in time. #heading(outlined: false, level: 3, "Reproducibility In Space") Just like Guix, building the program in a different environment with the same architecture (`x86_64-linux`) resulted in identical output. Compiling the source code on another architecture (`aarch64_darwin`) also produced consistent results, though different from those obtained on `x86_64-linux`. Therefore, we can conclude that the program is reproducible across different environments, #emph[modulo] the hardware architecture. #heading(outlined: false, level: 3, "Reproducibility Of The Build Environment") The reproducibility of the build environment is heavily controlled. The dependencies are locked and pinned, it is simply not possible to create a different build environment. === Dealing With Variability This section will focus on how Nix deals with unstable outputs, highlighting how they have abstracted this issue behind the scenes. The scenarios that will be used are: - Scenario 6: Building an #gls("OCI") image with Nix - Scenario 7: Compiling a Typst document to a PDF file - Scenario 8: Compiling a Typst document to a PDF file with Nix, showing how Nix abstracts the issue of non-deterministic builds. - Scenario 9: Compiling a Typst document with Nix, fixing the issue of non-deterministic builds. #info-box[ Typst #cite(<typst>, form: "normal") is an advanced markup-based typesetting language that compiles to #gls("PDF") or #gls("SVG"). It was initiated in 2019 at the Technical University of Berlin by <NAME> and <NAME>. Developed in Rust, this programmable markup language for typesetting became the subject of their master's theses, which they wrote in 2022. After several years of closed-source development, Typst was open-sourced and released to the public in 2023. Despite being relatively recent and lacking a stable version, Typst's maturity has allowed it to be used for writing this master's thesis. ] Building #gls("OCI") images using Docker is a common use case in the software development process. However, the output of the build can be non-deterministic due to the nature of the build process. In scenario 6, we will build an #gls("OCI") image using Nix only. #figure( { sourcefile( file: "flake.nix", lang: "nix", read("../../lib/scenario-6/flake.nix"), ) }, caption: [ The Nix Flake file (`flake.nix`) to build an OCI image in Scenario 6 ], ) <ch3-flake-nix-container> #figure( { shell(read("../../resources/sourcecode/scenario-6.log")) }, supplement: "Terminal session", kind: "terminal", caption: [Building an #gls("OCI") image with Nix], ) <ch3-nix-flake-container-build> In @ch3-nix-flake-container-build, line 5 and 11, we notice that building twice an #gls("OCI") image using Nix produces the same output. The Flake file in @ch3-flake-nix-container shows that it is possible to create reproducible #gls("OCI") containers with Nix, in a simple and declarative way. In scenario 7, we will compile a trivial Typst document. Consider the following Typst document on the left, and it's rendering on the right: #grid( columns: 2, rows: 1, column-gutter: 1em, align: bottom, figure( { sourcefile( file: "hello-world.typst", lang: "typst", read("../../lib/scenario-7/src/hello-world.typst"), ) }, caption: [Typst document], ), [ #figure( box(stroke: .6pt + luma(200), radius: 3pt)[ #image("../../resources/images/hello-world.svg") ], caption: [Rendering of the Typst document], ) <typst-hello-world-rendered>], ) @ch3-hello-world-typst-build-log shows that manually compiling the same document twice yields different resulting files. #figure( { shell(read("../../resources/sourcecode/scenario-7.log")) }, supplement: "Terminal session", kind: "terminal", caption: [Manually compiling a Typst document to a #gls("PDF") document in Scenario 7], ) <ch3-hello-world-typst-build-log> While viewing the resulting #gls("PDF") files side by side, we notice that they appear totally identical to @typst-hello-world-rendered. However, the checksum of those files are different. This discrepancy is common, where the same input can produce different outputs due to non-deterministic behaviour in the build process. Even if the resulting outputs are identical, there can be internal differences. Therefore, given an arbitrary build output, it is impossible to determine if a build is valid or not. It is important to acknowledge that tools like Guix or Nix address this issue by ensuring that the build environment only is consistent and reproducible. In @ch3-nix-typst-flake, we will show how to compile the same Typst document using Nix and how to eventually fix the discrepancy. #figure( { sourcefile( file: "flake.nix", lang: "nix", read("../../lib/scenario-8/flake.nix"), ) }, caption: [ The Nix `flake.nix` file to build a Typst document to a PDF in Scenario 8 ], ) <ch3-nix-typst-flake> Compile it twice and observe the outcome: #figure( { shell(read("../../resources/sourcecode/scenario-8.log")) }, supplement: "Terminal session", kind: "terminal", caption: [Building a Typst document in Scenario 8], ) <ch3-hello-world-typst-build> At lines 4 and 7 of @ch3-hello-world-typst-build, we notice that compiling twice a Typst document with Nix produces two different #gls("PDF") files, their respective checksums are different. While the visual output appears identical, the underlying files are not. At line 3 of @ch3-hello-world-typst-rebuild, we leverage a command with specific flags to verify if a build output is reproducible. #figure( { shell(read("../../resources/sourcecode/scenario-8-rebuild.log")) }, supplement: "Terminal session", kind: "terminal", caption: [Checking if a build output is reproducible], ) <ch3-hello-world-typst-rebuild> Nix will build the document once (line 2), then a second time (line 3) and then compare the output hashes. Thanks to the `--keep-failed` argument, we inform Nix to keep the failed builds so we can do a more introspective analysis of the issue and try to find the root cause of the discrepancy, for example, using `diffoscope` #cite(<diffoscope>, form: "normal") in @ch3-hello-world-typst-rebuild-diffoscope. #figure( { shell(read("../../resources/sourcecode/scenario-8-diffoscope.log")) }, supplement: "Terminal session", kind: "terminal", caption: [Checking discrepancies between two builds using `diffoscope`], ) <ch3-hello-world-typst-rebuild-diffoscope> #figure( image("../../resources/images/diffoscope-typst.svg"), caption: [ A visual comparison with `diffoscope` of two #gls("PDF") files generated from the same Typst document ], ) <ch3-nix-typst-diff> `diffoscope` visually compares the discrepancy between the two #gls("PDF") files. From the report in @ch3-nix-typst-diff, the highlighted difference seems to be the creation date metadata. Doing a quick search on @typstdoc confirms that Typst is able to change the creation date of the output file. @ch3-nix-typst-flake-fixed implements the trivial change at line 1: #figure( { sourcefile( file: "hello-world.typst", lang: "typst", read("../../lib/scenario-9/src/hello-world.typst"), ) }, caption: [On line 1, the Typst document date is now set to `none`], ) <ch3-nix-typst-flake-fixed> #figure( { shell(read("../../resources/sourcecode/scenario-9-rebuild.log")) }, supplement: "Terminal session", kind: "terminal", caption: [Checking if compiled Typst document is reproducible in Scenario 9], ) <ch3-hello-world-typst-fixed-log> Now we notice that running the command to check if the output is reproducible returns nothing, meaning that the output is fully reproducible. #info-box[ Often, raising an issue with the upstream project is the most effective method for informing the authors about a problem and monitoring its resolution. In the case of Typst, an issue #cite(form: "normal", <typstReproducibleBuildIssue1>) was documented to describe the problem, and in less than two weeks, it had been addressed and resolved. Consequently, the discrepancy in @ch3-hello-world-typst-build is no longer applicable for Typst versions newer than `0.11.0`. ] == Conclusion In this concluding section of the chapter, a summary of the reproducibility assessment can be found in @ch3-table-conclusion. Following the table, this section provides a detailed explanation of our categorization process, outlining the specific criteria used for classifying. Each classification is justified based on the results obtained from our comprehensive empirical evaluation process. #figure( include "../../resources/typst/ch3-table-conclusion.typ", caption: [Software evaluation comparison], kind: "table", supplement: [Table], ) <ch3-table-conclusion> In evaluating the reproducibility of various tools and methodologies within, a particular focus has been set on the bare compilation method (@ch3-tool1). This approach, characterised by its reliance on the host operating system's installed software for compiling source code into executable programs, presents a nuanced challenge to reproducibility. Theoretically, bare compilation allows for a straightforward reproduction of computational results, assuming a static and uniform environment across different computational setups. However, the practical application of this method exposes inherent vulnerabilities to environmental variability. The reliance on the host's installed software means that the exact version of compilers, libraries, and other dependencies can significantly impact the outcome of the compilation process. These elements are seldom identical across different systems or even over time on the same system, given updates and changes to the software environment. Consequently, the reproducibility promised by Bare compilation is compromised by these external variables, which are often not documented with sufficient rigor or are outside the user's control. Acknowledging these challenges, we categorise the bare compilation (@ch3-tool1) as non-reproducible by default, reflecting a practical assessment rather than a theoretical limitation. The classification underscores the significant effort required to document and manage the dependencies on the host's software to achieve a reproducible build process. This perspective is supported by the literature #cite(<Schwab2000>, form: "normal"), which advocates for standardising and simplifying the management of computational research artefacts. The classification of the method 1 (@ch3-tool1) as *non-reproducible* is a pragmatic acknowledgment of the difficulties presented by the dependency on the computational environment. Docker and similar containerization technologies (@ch3-tool2) can facilitate reproducible environments. The reason is that while they provide a high degree of isolation from the host system, they are still subject to variability due to the base images and package managers used within the containers. This variability, however, can be effectively managed with low effort. By meticulously selecting and managing base images and dependencies, it is indeed feasible to elevate Docker from partially to fully reproducible. For these reasons, they are categorised as *partially reproducible*. Nix (@ch3-tool3) and Guix (@ch3-tool4) provide a high level of control over the build environment and dependencies, facilitating deterministic and reproducible builds across different systems. By capturing all dependencies and environment specifics in a declarative manner, Nix and Guix offer a reliable and transparent approach to software development. The functional deployment model implemented by Guix, Nix and their forks (like @lix), along with their transactional package upgrades and rollbacks, further enhances reproducibility by enabling exact replication of software environments within the same architecture at any point in space and time.Under the hood, they introduces a novel approach to addressing the challenges of reproducibility. By using a very specific storage model, they ensures that the resulting output directory is determined by the hash of all inputs. This model, while not guaranteeing bitwise identical binaries across all scenarios, especially across different hardware architectures, ensures that the process and environment for building the software are reproducible. Nix and Guix's model represents a significant step forward in mitigating reproducibility challenges within #gls("SE"). By ensuring that every build can be traced back to its exact dependencies and build environment, it enhances the reliability of software deployments. This approach is particularly beneficial in #gls("CICD") pipelines, where consistency and reliability are paramount. Achieving reproducibility in #gls("SE") is filled with challenges, from architecture dependencies to non-determinism in compilers. These solutions offers a compelling solution by ensuring reproducible build environments. The exploration of the concepts used in Guix and Nix, and its methodologies provides valuable insights into the complexities of software reproducibility and the necessity for continued research and development in this field. They both are categorised as *reproducible*.
https://github.com/Coekjan/parallel-programming-learning
https://raw.githubusercontent.com/Coekjan/parallel-programming-learning/master/ex-4/report.typ
typst
#import "../template.typ": * #import "@preview/cetz:0.2.2" as cetz #import "@preview/codelst:2.0.1" as codelst #show: project.with( title: "并行皋序讟计第 4 次䜜䞚CUDA 猖皋", authors: ( (name: "叶焯仁", email: "<EMAIL>", affiliation: "ACT, SCSE"), ), ) #let data = toml("data.toml") #let lineref = codelst.lineref.with(supplement: "代码行") #let sourcecode = codelst.sourcecode.with( label-regex: regex("//!\s*(line:[\w-]+)$"), highlight-labels: true, highlight-color: lime.lighten(50%), ) #let data-time(raw-data) = raw-data.pairs().map(pair => { let (tpb, data) = pair (str(tpb), data.sum() / data.len()) }) #let data-chart(raw-data, width, height, time-max) = cetz.canvas({ cetz.chart.columnchart( size: (width, height), data-time(raw-data), y-max: time-max, x-label: [_线皋块内线皋数量_], y-label: [_平均运行时闎单䜍秒_], bar-style: none, ) }) #let data-table(raw-data) = table( columns: (auto, 1fr, 1fr, 1fr), table.header([*线皋块内线皋数量*], table.cell([*运行时闎单䜍秒*], colspan: 3)), ..raw-data.pairs().map(pair => { let (tpb, data) = pair (str(tpb), data.map(str)) }).flatten() ) = 实验矩阵乘法 == 实验内容䞎方法 䜿甚 NVIDIA CUDA 匂构猖皋接口实现矩阵乘法的并行加速并圚䞍同的线皋配眮䞋运行记圕运行时闎并进行分析。 - 矩阵倧小8192 #sym.times 8192 - CUDA 配眮记各眑栌䞭线皋块数量䞺 $B$、各线皋块䞭线皋数量䞺 $T$ - 二绎排垃线皋䞎线皋块 - 确保 $B times T = 8192$ - 调敎线皋块䞭线皋数量2 \~ 32 皋序构造过皋䞭有劂䞋芁点 + 穁甹 GPU 侊的 FMAD 指什避免浮点误差 + 䟝据环境变量 `THREADS_PER_BLOCK` 决定线皋块䞭线皋数量 + 猖写 ```c cudaCheck()``` 宏凜数检查 CUDA 凜数调甚的错误 + 䞺记圕排序时闎䜿甚 POSIX 的 ```c gettimeofday()``` 凜数 + 䞺简芁地记圕矩阵乘法结果双粟床浮点阵列䜿甚 OpenSSL 的 SHA1 算法计算其指纹。 代码劂 @code:matmul-code 所瀺其䞭 - #lineref(<line:cuda-kernel>) 定义了矩阵乘法圚 CUDA 䞭的栞凜数 - #lineref(<line:cuda-blk-th-1>)、#lineref(<line:cuda-blk-th-2>) 利甚 CUDA API 获取线皋块䞎线皋的划分信息 - #lineref(<line:cuda-malloc-1>)、#lineref(<line:cuda-malloc-2>)、#lineref(<line:cuda-malloc-3>) 圚 GPU 䞊申请内存#lineref(<line:cuda-free-1>)、#lineref(<line:cuda-free-2>)、#lineref(<line:cuda-free-3>) 释攟 GPU 䞊的内存 - #lineref(<line:cuda-memcpy-1>)、#lineref(<line:cuda-memcpy-2>)、#lineref(<line:cuda-memcpy-3>)、#lineref(<line:cuda-memcpy-4>)、#lineref(<line:cuda-memcpy-5>)、#lineref(<line:cuda-memcpy-6>) 圚 CPU 侎 GPU 之闎进行数据䌠蟓 - #lineref(<line:cuda-tpb>)、#lineref(<line:cuda-bpg-1>) 侎 #lineref(<line:cuda-bpg-2>) 划分线皋块䞎线皋 - #lineref(<line:cuda-matmul-1>)、#lineref(<line:cuda-matmul-2>)、#lineref(<line:cuda-matmul-3>) 侎 #lineref(<line:cuda-matmul-4>) 调甚 CUDA 栞凜数进行矩阵乘法 - #lineref(<line:cuda-check-last-err>) 检查 CUDA 凜数调甚的错误 - #lineref(<line:cuda-sync>) 同步栞凜数的执行。 #figure( sourcecode( raw(read("matmul/matmul.cu"), lang: "cpp"), ), caption: "并行矩阵乘法 MPI 实现代码", ) <code:matmul-code> == 实验过皋 圚劂 @chapter:platform-info 所述的实验平台䞊进行实验分别䜿甚 2、4、8、16、32 䜜䞺线皋块䞭的线皋数量记圕运行时闎测定 3 次取平均倌原始数据劂 @table:matmul-raw-data 所瀺。 == 实验结果䞎分析 矩阵乘法实验测定的运行时闎劂 @figure:matmul-chart 所瀺。 可见圓线皋块内线皋数量蟃少时GPU 内调床和同步匀销倧富臎性胜星著䞋降因䞺无法充分利甚 CUDA 的并行计算胜力而圓线皋块内线皋数量增倚时性胜逐析提升并趋于皳定。 #figure( data-chart(data.matmul, 12, 8, 100), caption: "矩阵乘法运行时闎", ) <figure:matmul-chart> 矩阵乘法实验䞭的原始数据劂 @table:matmul-raw-data 所瀺。 #figure( data-table(data.matmul), caption: "矩阵乘法实验原始数据", ) <table:matmul-raw-data> = 附泚 == 猖译䞎运行 代码䟝赖 NVIDIA CUDA 库及其对应驱劚、OpenSSL 库若未安装这些库需手劚安装。圚准倇奜䟝赖后可䜿甚以䞋呜什进行猖译䞎运行 - 猖译```sh make``` - 通过添加 `nvcc` 呜什行选项 `--fmad=false` 来犁甚 GPU 侊的 FMAD 指什 - 运行```sh make run``` - 可通过环境变量 ```THREADS_PER_BLOCK``` 来指定线皋块内线皋数量䟋劂```sh THREADS_PER_BLOCK=32 make run``` - 运行结束后若提瀺错误检测到指纹错误则诎明运行结果䞍正确该检测机制的倧臎逻蟑由 @code:makefile-fingerprint 侭的 Makefile 代码给出 #figure( sourcecode( ```make # The fingerprint of the result FINGERPRINT := 00 11 22 33 44 55 66 77 88 99 99 88 77 66 55 44 33 22 11 00 # Run the program `app` and check the fingerprint .PHONY: run run: exec 3>&1; stdbuf -o0 ./app | tee >(cat - >&3) | grep -q $(FINGERPRINT) ``` ), caption: "Makefile 䞭的指纹检测代码" ) <code:makefile-fingerprint> - 枅理```sh make clean```。 == 实验平台信息 <chapter:platform-info> #figure( table( columns: (auto, 1fr), table.header([*项目*], [*信息*]), [CPU], [11th Gen Intel Core i7-11800H \@ 16x 4.6GHz], [GPU], [NVIDIA GeForce RTX 3060 Laptop GPU], [内存], [DDR4 32 GB], [星存], [6 GB], [操䜜系统], [Manjaro 24.0.1 WynsdeyLinux 6.6.32], [CUDA], [12.4], ), caption: "实验平台信息", ) <table:platform-info>
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/import-06.typ
typst
Other
// Usual importing syntax also works for function scopes #import enum #let d = (e: enum) #import d.e #import d.e: item #item(2)[a]
https://github.com/piepert/typst-seminar
https://raw.githubusercontent.com/piepert/typst-seminar/main/Beispiele/Hausarbeit/outline-template.typ
typst
#let outline(title: "Inhaltsverzeichnis", depth: none, indent: true, fill: " . ") = { heading(title, numbering: none) locate(it => { let elements = query(selector(heading).after(it), it) for (i, e) in elements.enumerate() { if e.outlined == false or (depth != none and r.level > depth) { continue } let number = if e.numbering != none { numbering(e.numbering, ..counter(heading).at(e.location())) " " } let line = { if indent { h(1em * (e.level - 1 )) } if e.level == 1 { v(weak: true, 0.5em) set text(weight: "bold") number e.body } else { number e.body } // Filler dots box(width: 1fr, h(3pt) + box(width: 1fr, repeat(fill)) + h(3pt)) // Page number let page_number = counter(page).at(e.location()).first() str(page_number) linebreak() } link(e.location(), line) } }) }
https://github.com/han0126/MCM-test
https://raw.githubusercontent.com/han0126/MCM-test/main/2024校赛typst/chapter/chapter3.typ
typst
= 暡型假讟 圚建暡的过皋䞭䞺简化问题䞔方䟿建暡我们圚䞍圱响暡型的可靠性和有效性的前提䞋做出以䞋假讟 1假讟竞赛衚现䌘匂的孊生埀埀也圚孊䞚䞊有蟃奜的衚现。因歀竞赛成绩䞎孊生的孊䞚成绩之闎存圚䞀定的正盞关关系。 2假讟积极参䞎竞赛可以促进孊生的绌合玠莚提升包括䜆䞍限于䞓䞚知识、团队合䜜胜力、创新思绎、沟通胜力等方面。通过参䞎竞赛孊生可以圚实践䞭䞍断提升自身的胜力和玠莚氎平。 3假讟参䞎竞赛并获埗䞀定成绩的孊生其未来的孊习和职䞚发展可胜䌚受到积极圱响。竞赛经验可以䞺孊生的升孊、就䞚和科研等方面提䟛额倖的加分项增区其竞争力。 4假讟参赛孊生投入曎倚的时闎和粟力准倇竞赛埀埀胜取埗曎奜的成绩。因歀竞赛成绩䞎孊生准倇竞赛的时闎投入之闎存圚䞀定的正盞关关系。
https://github.com/Sematre/typst-kit-thesis-template
https://raw.githubusercontent.com/Sematre/typst-kit-thesis-template/main/sections/03_introduction.typ
typst
= Introduction This is the themplate for Bachelor's and Master's theses at SDQ. For more information on the formatting of theses at SDQ, please refer to #link("https://sdq.kastel.kit.edu/wiki/Ausarbeitungshinweise") or to your advisor. == Pacing and indentation To separate parts of text in Typst, please use two line breaks in your source code. They will then be set with correct indentation. Do _not_ use: - ```typ #parbreak()``` - ```typ #v()``` or other commands to manually insert spaces, since they break the layout of this template. == Example: Citation A citation: @becker2008a == Example: Figures A reference: The SDQ logo is displayed in @sdqlogo. (Use ```typ @``` for easy referencing.) #figure( image("/assets/logo-sdq.svg", width: 4cm), caption: "SDQ logo" ) <sdqlogo> == Example: Tables Typst offers nicely typeset tables, as in @atable. #figure( table( columns: 2, [abc], [def], [ghi], [jkl], [123], [456], [789], [0AB] ), caption: "A table" ) <atable> == Example: Formula $ f(x) = ohm(g(x)) (x arrow infinity) arrow.l.r.double limsup_(x arrow infinity) |f(x) / g(x)| > 0 $
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/grotesk-cv/0.1.0/content/profile.typ
typst
Apache License 2.0
#import "../lib.typ": * #import "../metadata.typ" #import "@preview/fontawesome:0.2.1": * == #fa-icon("id-card") #h(5pt) #get-header-by-language("Summary", "Resumen") #v(5pt) #if is-english() [ Experienced Software Engineer specializing in artificial intelligence, machine learning, and robotics. Proficient in C++, Python, and Java, with a knack for developing sentient AI systems capable of complex decision-making. Passionate about ethical AI development and eager to contribute to groundbreaking projects in dynamic environments. ] else if is-spanish() [ Ingeniero de Software experimentado especializado en inteligencia artificial, aprendizaje automático y robótica. Competente en C++, Python y Java, con un talento para desarrollar sistemas de IA conscientes capaces de tomar decisiones complejas. Apasionado por el desarrollo ético de la IA y ansioso por contribuir a proyectos innovadores en entornos dinámicos. ]