repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/026%20-%20Eldritch%20Moon/007_Battle%20of%20Thraben.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Battle of Thraben", set_name: "Eldritch Moon", story_date: datetime(day: 20, month: 07, year: 2016), author: "<NAME>", doc ) #emph[When we last saw Jace, he had just laid eyes on the third Eldrazi titan, Emrakul. Realizing the enormity of the situation, he planeswalked to Zendikar to rally the Gatewatch; it would take all of them to destroy the eldritch monstrosity.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Jace shuddered involuntarily as he opened his eyes on Innistrad. The air was quite a bit colder here. It had a different smell, too, a different feel. The scent was strange, almost metallic, and when he exhaled his last breath of Zendikar's air and breathed in Innistrad, he felt it. There was a thickness to the air here. That first breath hurt, just a little. The sky was tearing itself apart. Storm clouds swirled, as if there were a gale in every direction, and no sunlight escaped the horizon. The plane's eternal dusk had given way to a purplish glow. His eyes didn't want to adjust to the dark; they fought him every moment of the way. He squinted toward the horizon, toward the hole in reality, and tried to focus. Focus. Focus. His mind felt heavy, here. Like a sack of wet rice on top of his neck. Sloshing, grinding, sliding away... There was a chime in his mind. Or the memory of a chime. A reminder of himself, and his eyes cleared. He stood atop a hill, looking down on the rolling fields that surrounded Thraben. He could see the city now, and half of it was ablaze. There were battles raging in the streets. Torches. Shouting. Screaming. He wasn't sure whether he was hearing the screams from this distance, or feeling them. And above it all, up in the sky...he couldn't bring himself to focus there. Not yet. A second set of sounds brought Jace's focus to a more clear and present issue. Growling. Snarling. Eyes glowing a sickly green in the dark. "Werewolves again," Jace muttered to himself. He reached out into the darkness and lightly touched the minds that he found there. Three of them, ravaged by madness and changed into something he could barely recognize. As they crept out of the shadows, he saw the werewolves clearly. Their fur was patchy, their skin infused with the same latticework pattern that he had seen all over the organic matter of Innistrad. Jace made a call. There wasn't enough left of these minds to be saved. There was no subtlety in his mental assault; he grabbed ahold of their senses and overloaded each one—blinding light, deafening sound, smells so intense they choked on them. It wasn't pretty, but he needed to establish a foothold here for when the others arrived. #figure(image("007_Battle of Thraben/01.jpg", width: 100%), caption: [Contingency Plan | Art by Ryan Yee], supplement: none, numbering: none) Two of the werewolves whimpered and fell; they twitched, and then went still. The last of the three...laughed? He could feel its mind changing, adapting, growing in response to the assault. The mental connection broke, and he watched as the creature's skin rippled, its limbs lengthened, its claws elongated, and its skin oozed. Jace stumbled backward. Whatever he had done had triggered some sort of reflexive mutation. Now, he wasn't even sure what he was looking at. With a quick gesture, he split into a dozen reflections, and the monster spent a moment sniffing the air before focusing in on his real body, the illusions ignored. Jace looked around for an escape route and found none. Options raced through his mind, and were discarded one by one. Jace's illusions, semi-substantial, tried to crowd the beast, buying him more time, until... ...a flash of light, the sound of a whipping blade and tearing flesh. The horror dropped into a mangled, whimpering pile. Gideon. "It's fine, Jace. I've got your back." Jace straightened his coat. "Did you get lost on the way? Make a stopover in Ravnica for snacks?" "It's not easy following you to a place I've never been. Hmm." Gideon stared down the hill toward Thraben. If he was having a hard time with his senses, he wasn't showing it. "Bigger than the other two. And it's got quite the force between us and it. What's the plan?" A heat shimmer appeared in the air, and a woman stepped out of it. Chandra rubbed her hands together. "Same plan as last time, right? Fire? I guess that wasn't the plan at the time, but it did the trick. Usually does." She put her hands on her hips as she looked down at the chaotic scene below. The hill rumbled slightly, the only herald of Nissa's arrival. She frowned as she knelt down, placing her palm against the ground. "The mana here is dark. Twisted. It's in the soil, the trees...Emrakul did some of this, but..." "This is your first time to Innistrad, right? 'Dark and twisted' is kind of a regular feature." Jace continued, "So, we've basically got the same scenario as last time, with a couple minor wrinkles. Emrakul is moving on Thraben, and we need to get there first. Nissa will use her planar glyph to tap into the leyline network. Gideon will clear us a path to get close. We channel the plane's energy through Chandra, and she does her thing." Nissa shook her head. "It's not going to work. The leylines have already been redirected. Into that." Jace tried to force a grin. "Well, yes. The cryptolith network. They're focusing all the leylines toward Thraben now. That, plus the fact that Thraben is the densest population of life on Innistrad, will mean that Emrakul will almost certainly be drawn there. That center point should amplify the glyph's effects. Quite similar to the hedron network, actually." "If we can get close enough to it. But if we get that close, Emrakul will destroy us." Nissa's voice was quiet, but firm. "And if we don't get that close, I'll be able to tap into one or two leylines from any other vantage point. Three at most. It won't be enough." Chandra put her hand on Nissa's shoulder. "Hey. One leyline or twenty, you tap me in, and we'll make it enough." Gideon sighed. "Nissa, do you believe you can do this? We're not going to try a plan that we're not all committed to." Nissa picked up a handful of dirt and sifted it between her fingers. She glanced up to the faces of her companions. Gideon, concerned. Jace, impassive. Chandra, excited. She closed her eyes and listened for several long seconds. To her heartbeat, to the blighted soil beneath her, to her memories. "Yes." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "Look at it, Gared. Pretty, in a way. Your world is ending." Liliana watched as Thraben began to burn and tentacles reached down from the storms to rake the earth below. The sky swarmed with angels, and the ground beneath the titan just swarmed. From this distance, she could make out only the movement, an unending, writhing mass of creatures, pressing as close to the source of the world's end as they could. "Yes, mistress. S'what it does around here, mostly." The geistmage's apprentice, with his bulging eye, looked forlornly down at the chaos. "Ah, there they are. See the fire and the flashes of light? Those must be Jace's little friends. Looks like they're headed straight toward the center of it all." Gared tilted his head, an interesting effect atop his already asymmetrical body. "Yes, mistress. I couldn't help but notice, you've raised this lovely little army to help, but we're staying up here, and the others are down there." "Hmm. I suppose that's true." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Chandra was screaming. The others couldn't tell whether they were screams of pain or joy or rage, they just heard the screams and felt the overwhelming heat. She was incandescent, an inferno that walked, and she projected fire in every direction, scorching her friends but charring wave after wave of the mutated remains of what had been the people of Thraben, just days ago. #figure(image("007_Battle of Thraben/02.jpg", width: 100%), caption: [Spreading Flames | Art by Chase Stone], supplement: none, numbering: none) The screaming stopped, and the fires went out. Chandra dropped to her hands and knees, and Gideon leapt forward to cover her. They were trapped in what had been a market square, two of the four entrances blocked by rubble and fallen buildings. A dilapidated, lattice-scarred tower leaned tenuously over the cobblestone road that led farther into the heart of the city—but both it and the road they had entered on were blocked by rank after rank of Emrakul's legion. Some of them were still recognizably human. Their voices were a screeching whirl of screams and gibberish. Some of them were what remained of beasts, of angels, of things unrecognizable. Some moved with purpose, others merely lumbered and moaned, their limbs limp and their flesh melting like candle wax. And behind them loomed the storm. The body of the titan was still mostly hidden from view, but its presence was everywhere. Emrakul. The storm raged, and impossible forking lightning thrashed and slashed the city below. Tentacles would emerge from the black clouds, scraping low along the ground, rumbling as city blocks were reduced to ash and stone. #figure(image("007_Battle of Thraben/03.jpg", width: 100%), caption: [Emrakul, the Promised End | Art by <NAME>], supplement: none, numbering: none) "Options. I need options." Gideon surveyed the square, sural unfurled. "Nissa. Elementals?" The elf shook her head. "I could call, but we wouldn't like what would answer." Gideon grunted his frustration. "Chandra? You ready to go another round?" Chandra was doubled over, hands on her knees, breathing hard. She raised a hand and gave a weak thumbs-up gesture. "Sure thing, boss. Just getting started." She coughed and straightened up—her face was covered in soot and ash, but her smile seemed genuine enough. "Jace. What have you got?" Jace scanned the area again. "We're not going forward. We've got a defensible open space to work with. I say we use the glyph here." Gideon nodded. "Nissa, can you do it?" Nissa knelt down, putting both of her palms on the ground. A green glow snaked up from the ground, wrapping her arms in a verdant light. "Two leylines. Three if I push." "Do it." Gideon's voice held the slightest hesitation. "The rest of us, we need to cover her. The resistance we've faced this far has been incidental. I'm not even sure it's noticed us yet." Jace gestured toward the tower that overlooked one of the entrances to the square. Two illusionary marks appeared on it. "Chandra, I need you to hit the tower here and here. When the lattice transforms stone, it is quite resistant to damage, but expands when exposed to extreme heat. That should topple the tower and block off the street." "What?" Chandra glanced back, hands already ablaze. "I read it in a book. Trust me." Chandra thrust her fists toward the tower, and two arcing fireballs struck precisely where Jace had marked. Seconds later, the entire structure collapsed, blocking off most of the street as it crashed into the inn on the other side. The market square came alive—new growth sprang from the packed dirt and cobblestones, and the air, sour and foul, cleared slightly. Nissa stood motionless in the center of it, as glowing runes appeared on the ground around her, snaking their way from her feet until the complex glyph was complete. There was a shrieking sound from the hordes around them. As one, they turned and charged toward Nissa—and Gideon charged to intercept them. He hit the line with powerful vertical slashes, and drove his body into their ranks, golden sparks lifting into the night air as blows deflected off his body. He roared a challenge as he slashed in a wide circle, trying to inflict as much damage as possible and draw as much attention to himself as he could. #figure(image("007_Battle of Thraben/04.jpg", width: 100%), caption: [Give No Ground | Art by <NAME>], supplement: none, numbering: none) But the creatures did not fall easily, and those that fell did not stay down. Even fully dismembered creatures stayed still for only a moment; they grew new hideous limbs from each fresh wound, and walked, crawled and skittered past, drawn directly to Nissa and the glyph. "Nissa, are we ready? Because I really, really think now is a good time." Chandra paced at the edge of the flaring glyph, as Nissa muttered incomprehensible syllables, eyes firmly shut. Chandra gave a yell of warning to Gideon before washing the entire street in a wave of flames. She looked back over her shoulder to see Nissa reaching down into the earth and pulling up what looked to be a spectral thorned vine, wide around as a tree trunk. She strained to pull it up from the earth, and she gasped in shock as those spectral thorns cut into her arms. Nissa grunted through gritted teeth. "Get...ready. Almost...there." She reached down again, and raised a second vine. This one pulled and buckled, thrashing back and forth in her grasp like a serpent. With a pained effort, she managed to wrap it around her waist as an anchor, and reach down to the ground for a third. Chandra paced, not sure what to do next. There was nothing she could do for Nissa, and Gideon was doing what he could to stop a flowing mass of creatures moving their way. She glanced up, and immediately regretted it. Limbs, tentacles, and other lattice-wracked extremities were starting to climb up over the buildings and rubble, in every direction. Hundreds of them. She glanced back to Nissa, and watched her fall to her knees. The third spectral vine was darker than the other two, the barbs more cruel, its motion more sinuous and chaotic. Nissa was trying to get it under control, but it had managed to wrap itself around her neck, and it looked as if it was trying to drag her down into the ground. "Life cannot stop...even when it knows it must...even when it knows it is wrong! Alone and discordant! Even when it knows!" Nissa's voice echoed, her eyes glowed a sickly purple, and then she dropped limp onto the ground. The vines were gone. The glyph went instantly dark. And the hordes of creatures continued their approach. "Fall back!" Chandra yelled as she rushed to Nissa's side, scooping up her head as gently as she could. "Come on, come on, you need to wake up!" "There's nowhere to fall back to, Chandra!" Jace took up position next to the two, and reached down to touch Nissa's forehead. "She's still in there. Just a bit stunned. She'll be fine in a couple minutes." Gideon came running back to the others, as the crowd of creatures slowly pressed closer. "I'll watch over her until she wakes up. You two planeswalk back to safety." Chandra stood, hands ablaze. "Not gonna happen. We're all walking out of here together, or..." Her bravado faded with her trailing words. "Or not at all," Jace supplied. "Together or not at all?" Chandra opened her mouth to respond, then cocked her head to the side. "Wait...what is that?" The Planeswalkers heard them before they saw them—growling, moaning, crunching, and tearing, as ranks of the undead spilled into the square. They moved in tight formations, throwing themselves, biting and clawing into the mutated creatures that surrounded the Planeswalkers, ripping them apart with terrible strength. #figure(image("007_Battle of Thraben/05.jpg", width: 100%), caption: [Liliana's Elite | Art by <NAME>], supplement: none, numbering: none) Necrotic flesh met mutated limbs in an explosive clash, both sides heedless of pain or losses. But the zombies moved with precision and purpose. When their ranks were shredded, they were immediately replenished. And when they reached the Planeswalkers, they parted, formed a defensive perimeter around them, and started pushing outward. Then, their general appeared. #figure(image("007_Battle of Thraben/06.jpg", width: 100%), caption: [Dark Salvation | Art by <NAME>], supplement: none, numbering: none) Liliana floated forth, arms spread wide, the Chain Veil hovering just beyond her fingertips. Her tattoos blazed with light and dripped with blood. At a casual flick of her wrist, bolts of necromantic energy swept in wide arcs, reducing the corpses of the mutated creatures to ash. All the cancerous growth, all the twisted vibrancy was simply snuffed out. In a field of unending, unnatural life, a sphere of stillness and death arrived, and there it reigned. Liliana's expression softened from exultant fury to a demure smile in an instant, as she dropped gracefully to the ground. Her tattoos faded, and the Veil seemed to diminish. "Oh, Jace. I got here as soon as I could." "What are you doing here?" Gideon was still in a combat stance, his sural flowing with imbued power. #figure(image("007_Battle of Thraben/07.jpg", width: 100%), caption: [Collective Effort | Art by <NAME>], supplement: none, numbering: none) "The nice lady with the uncomfortable dress just saved our butts, Gideon. Calm down a second." Chandra turned her back to Liliana and stepped between them. Nissa stirred and struggled to her feet. "That...thing she carries. It's an abomination." Nissa flinched from the Veil, refusing to look anywhere near it. Liliana's smile curved its way across her face. "That's a strange way of saying 'thank you, Liliana, you saved my life, and I'll always be in your debt.'" Gideon grunted, and his sural retracted. "Liliana, I'm...I didn't think I'd see you again. But you're here." Jace pulled back his hood, the glow gone from his eyes. The dark circles underneath them were plain to see. "Eloquent as ever. Yes. You're rescued, you owe me, and now you should really planeswalk somewhere safe." Jace shook his head. "We can't do that. We need to finish this. We're so close. And with you covering us, I think we can do this. I know we can." Liliana rubbed her forehead. "This is not the time to be ridiculous, Jace. What we need to do is leave." "What you need to do is take that cursed thing and go." Nissa stood unsteadily, but her sword was in hand. "I'll not fight alongside it." Gideon raised a hand in warning. "You fought at Sea Gate alongside vampires, pirates, and worse, Nissa. We take the allies we can get, if they can be trusted." "Ah, the meat can reason!" Liliana beamed. "But I don't know if you #emph[can] be trusted. Nissa's instincts are rarely wrong, and I'm inclined to agree with her. That object is...a problem. But I don't know you. He does." Gideon turned to Jace. "So you'll decide. Tell me, Jace. Can she be trusted?" Liliana laughed, high and clear, before Jace could answer. "That's a ridiculous question, and you know it. Look around you. I snap my fingers, and you're all overrun. You are trusting me, right now. But if you won't leave, I can't force you. So tell me, brave heroes, what's your plan now?" She looked to each of their faces. Gideon, exasperated. Chandra, exhausted. Nissa, furious. And Jace, pained. "Oh, wonderful." Liliana smiled for lack of a better expression. "I'm sure this will end well."
https://github.com/jmigual/typst-efilrst
https://raw.githubusercontent.com/jmigual/typst-efilrst/main/README.md
markdown
MIT License
# Typst efilrst A simple referenceable list library for Typst. If you ever wanted to reference elements in a list by a key, this library is for you. The name comes from "reflist" but sorted alphabetically because we are not allowed to use descriptive names for packages in Typst 🤷🏻‍♂️. ## Example ```typst #import "@preview/efilrst:0.1.0" as efilrst #show ref: efilrst.show-rule #efilrst.reflist( [My cool constraint A],<c:a>, [My also cool constraint B],<c:b>, [My non-refernceable constraint C], list_style: "C1)", ref_style: "C1", name: "Constraint" ) See how my @c:a is better than @c:b. ``` This generates the following output: ![Example of the typst output. The last sentence reads "See how my Constraint C1 is better than Constraint C2"](img/image.png) ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## Changelog ### 0.1.0 - Initial release
https://github.com/tingerrr/subpar
https://raw.githubusercontent.com/tingerrr/subpar/main/src/_pkg.typ
typst
MIT License
#import "@preview/t4t:0.3.2"
https://github.com/jredondoyuste/TypstReport
https://raw.githubusercontent.com/jredondoyuste/TypstReport/main/main.typ
typst
The Unlicense
#import "report.typ": report #show: doc => report( title: [ Nobel acceptance speech ], event: "Nobel Prize Ceremony", author: "<NAME>", supervisor: "Supervisor: <NAME>", placedate: "Copenhagen, May 12th 2023.", doc, ) #lorem(200) #lorem(100) #lorem(150)
https://github.com/mem-courses/calculus
https://raw.githubusercontent.com/mem-courses/calculus/main/homework-1/calculus-homework4.typ
typst
#import "../template.typ": * #show: project.with( title: "Calculus Homework #4", authors: (( name: "<NAME> (#47)", email: "<EMAIL>", phone: "3230104585" ),), date: "October 20, 2023", ) = 课堂例题 10.17 #prob[求极限:$ lim_(x->pi)(sin m x)/(sin n x) $] *(细节有点多的)* = P55 习题1-3 11 #prob[ 1. 由 $display(lim_(x->-oo)(sqrt(x^2-x+1) - a_1 x - b_1) = 0)$,求常数 $a_1$,$b_1$. 2. 由 $display(lim_(x->+oo)(sqrt(x^2-x+1) - a_2 x - b_2) = 0)$,求常数 $a_2$,$b_2$. ] 1. 已知 $ lim_(x->-oo) sqrt(x^2-x+1)/(-x) = lim_(x->-oo) sqrt((x^2-x+1)/x^2) = lim_(x->-oo) sqrt(1 - 1/x + 1/x^2) = 1 $ 所以 $x->-oo$ 时,$sqrt(x^2-x+1) sim -x$.已知 $display(lim_(x->-oo)(-x - a_1 x - b_1) = 0)$,可得 $a_1 = -1$,$b_1 = 0$. 2. 同理可得 $x->+oo$ 时,$sqrt(x^2-x+1) sim x$.已知 $display(lim_(x->+oo)(x - a_2 x - b_2) = 0)$,可得 $a_2 = 1$,$b_2 = 0$. *(注意符号)* = P55 习题1-3 12(1) #prob[证明关系:$ cos x = 1 - 1/2 x^2 + o(x^2) quad (x->0) $] $ cos x = 1 - 1/2 x^2 + o(x^2) quad (x->0) quad <==> quad cos x - 1 + 1/2 x^2 = o(x^2) quad (x->0) $ 已知 $ lim_(x->0) (cos x - 1 + 1/2 x^2)/(x^2) &= lim_(x->0) (1 - 2 sin^2 (x/2) - 1 + 1/2 x^2)/(x^2)\ &= -1/2 lim_(x->0) (sin^2 (x/2))/((x/2)^2) + 1/2 lim_(x->0) x^2/x^2\ &= -1/2 + 1/2 = 0 $ 故原命题得证. = P55 习题1-3 12(2) #prob[证明关系:$ sqrt(x+sqrt(x+sqrt(x))) sim root(8,x) quad (x->0^+) $] 令 $u=root(4,x)$,已知 $display(lim_(x->0^+) u=0^+)$. $ & lim_(x->0^+) sqrt(x+sqrt(x+sqrt(x)))/root(8,x) = sqrt(lim_(x->0^+) (x+sqrt(x+sqrt(x)))/root(4,x))\ =& sqrt(lim_(u->0^+) (u^4 + sqrt(u^4 + u^2)) / u) = sqrt(lim_(u->0^+) (u^3 + sqrt(u^2 + 1))) = 1 $ = P55 习题1-3 12(5) #prob[证明关系:$ o(x^n) + o(x^m) = o(x^m) quad (x->0,space n>m>0) $] $ lim_(x->0) frac(o(x^n) + o(x^m), x^m) = x^(n-m) lim_(x->0) frac(o(x^n), x^n) + lim_(x->0) frac(o(x^m), x^m) = 0 $ 故原命题得证. = P55 习题1-3 16(1) #prob[利用等价量替换计算极限:$ lim_(x->0)(sqrt(1+tan^2 x)-1)/(x sin x) $] 已知:$x->0$ 时,$x sim sin x sim tan x$. $ lim_(x->0)(sqrt(1+tan^2 x)-1)/(x sin x) = lim_(x->0)(tan^2 x)/(x^2(sqrt(1+tan^2 x)+1)) = lim_(x->0)1/(sqrt(1+tan^2 x)+1) = 1/2 $ = P55 习题1-3 16(2) #prob[利用等价量替换计算极限:$ lim_(x->0)(sin(tan^2 x))/(root(n,1+x^2)-1) $] 令 $u=root(n,1+x^2)$,故 $x^2=u^n-1$.已知:$dp(lim_(n->0) u=1)$. $ lim_(x->0) (sin(tan^2 x))/(root(n,1+x^2)-1) = lim_(x->0) x^2/(root(n,1+x^2)-1) = lim_(u->1) (u^n-1)/(u-1) = lim_(u->1) sum_(k=0)^(n-1) u^k = n $ = P55 习题1-3 16(3) #prob[利用等价量替换计算极限:$ lim_(x->0^+)((1-sqrt(cos x)) tan x)/((1-cos x)^(3/2)) $] 已知:$x sim tan x$,$1-cos x sim 1/2 x^2$. $ lim_(x->0^+)((1-sqrt(cos x)) tan x)/((1-cos x)^(3/2)) = lim_(x->0^+)(tan x)/(sqrt(1-cos x)(1+sqrt(cos x))) = lim_(x->0^+)x/((1+sqrt(cos x)) sqrt(1/2 x^2)) = sqrt(2)/2 $ = 课堂例题 10.19 #prob[求极限:$ lim_(x->0)(frac(display(e^(1/x)+2),display(e^(2/x))+1)+(sin x)/(|x|)) $] 令 $u=e^(1/x)$,已知 $display(lim_(x->0^+) u=lim_(t->+oo) e^x = +oo)$,$display(lim_(x->0^-) u=lim_(t->-oo) e^x = 0)$.所以有: $ lim_(x->0^+)(frac(display(e^(1/x)+2),display(e^(2/x))+1)+(sin x)/(|x|)) = lim_(u->+oo)(frac(u+2,u^2+1)+1) = 1 $ $ lim_(x->0^-)(frac(display(e^(1/x)+2),display(e^(2/x))+1)+(sin x)/(|x|)) = lim_(u->0)(frac(u+2,u^2+1)-1) = 1 $ = P71 习题1-4 3(5) #prob[指出下列函数的间断点,并指出间断点是属于哪一类型:$ f(x) = (sin x)/(|x|) $] $x=0$ 处为原函数的跳跃间断点. = P71 习题1-4 3(6) #prob[指出下列函数的间断点,并指出间断点是属于哪一类型:$ f(x) = x/((4-x^2)(1+x^2)) $] $x=2$ 和 $x=-2$ 处是原函数的无穷间断点. = P71 习题1-4 3(8) #prob[指出下列函数的间断点,并指出间断点是属于哪一类型:$ f(x) = cases(2x+1\,quad x>=0,x\,quad x<0) $] $x=0$ 处是原函数的跳跃间断点. = P71 习题1-4 3(10) #prob[指出下列函数的间断点,并指出间断点是属于哪一类型:$ f(x) = lim_(n->oo)(x^n)/(1+x^n)quad (x>=0) $] $ f(x) = cases( 0\,quad& x=0, display(lim_(n->oo)1/(1+x^(-n)))\,quad&x>0 ) sp = cases( 0\,quad&0<=x<1, 1/2\,quad&x=1, 1\,quad&x>1, ) $ 故 $x=1$ 处是原函数的跳跃间断点. = P71 习题1-4 4 #prob[ 设 $display(f(x) = cases( e^x (sin x + cos x)\,quad& x>0, 2x+a\,quad& x<=0 ))$ 在 $(-oo,+oo)$ 上连续,求常数 $a$. ] 由于原函数在 $RR$ 上连续,应有:$ f(0) = f(0^+) quad <=> quad a = lim_(x->0^+) e^x (sin x + cos x) = 1 $ = P71 习题1-4 6 #prob[ 若 $display(f(x) = cases( display((sin 2x+e^(2a x)-1)/x)\,quad& x!=0, a\,quad& x=0 ))$ 在 $x=0$ 处连续,求常数 $a$. ] 根据函数的连续性要求,即需 $display(lim_(x->0) f(x))$ 存在且 $display(lim_(x->0) f(x)) = a$. $ lim_(x->0) (sin 2x+e^(2a x)-1)/x = 2 lim_(x->0) (sin 2x)/(2x) + lim_(x->0) (e^(2a x)-1)/x = 2 + lim_(x->0) (2a x+o(x))/x = 2 + 2a $ 所以 $a=-2$.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/pagebreak-parity_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(height: 30pt, width: 80pt) // Test when content extends to more than one page First Second #pagebreak(to: "odd") Third
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/block-03.typ
typst
Other
// Block directly in markup also creates a scope. #{ let x = 1 } // Error: 7-8 unknown variable: x #test(x, 1)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/pinit/0.1.0/lib.typ
typst
Apache License 2.0
#import "simple-arrow.typ": simple-arrow #import "pinit-core.typ": * // ----------------------------------------------- // Libs // ----------------------------------------------- #let pinit-rect( dx: 0em, dy: -1em, extented-width: 0em, extented-height: 1.4em, ..args, ) = { pinit(args.pos(), (positions) => { let min-x = calc.min(..positions.map((loc) => loc.x)) let max-x = calc.max(..positions.map((loc) => loc.x)) let min-y = calc.min(..positions.map((loc) => loc.y)) let max-y = calc.max(..positions.map((loc) => loc.y)) absolute-place( dx: min-x + dx, dy: min-y + dy, rect( width: max-x - min-x + extented-width, height: max-y - min-y + extented-height, ..args.named() ) ) }) } #let pinit-highlight( fill: rgb(255, 0, 0, 20), radius: 5pt, stroke: 0pt, ..args, ) = { pinit-rect(fill: fill, radius: radius, stroke: stroke, ..args) } #let pinit-line( stroke: 1pt, start-dx: 0pt, start-dy: 0pt, end-dx: 0pt, end-dy: 0pt, start, end, ) = { pinit((start, end), (positions) => { absolute-place( line( stroke: stroke, start: ( positions.at(0).x + start-dx, positions.at(0).y + start-dy, ), end: ( positions.at(1).x + end-dx, positions.at(1).y + end-dy, ), ) ) }) } #let pinit-arrow( start-dx: 0pt, start-dy: 0pt, end-dx: 0pt, end-dy: 0pt, start, end, ..args, ) = { pinit((start, end), (locations) => { absolute-place(simple-arrow( start: ( locations.at(0).x + start-dx, locations.at(0).y + start-dy, ), end: ( locations.at(1).x + end-dx, locations.at(1).y + end-dy, ), ..args, )) }) } #let pinit-point-to( pin-dx: 5pt, pin-dy: 5pt, body-dx: 5pt, body-dy: 5pt, offset-dx: 35pt, offset-dy: 35pt, pin-name, body, ..args, ) = { pinit-arrow(pin-name, pin-name, start-dx: pin-dx, start-dy: pin-dy, end-dx: offset-dx, end-dy: offset-dy, ..args) pinit-place(pin-name, body, dx: offset-dx + body-dx, dy: offset-dy + body-dy) } #let pinit-point-from( pin-dx: 5pt, pin-dy: 5pt, body-dx: 5pt, body-dy: 5pt, offset-dx: 35pt, offset-dy: 35pt, pin-name, body, ..args, ) = { pinit-arrow(pin-name, pin-name, start-dx: offset-dx, start-dy: offset-dy, end-dx: pin-dx, end-dy: pin-dy, ..args) pinit-place(pin-name, body, dx: offset-dx + body-dx, dy: offset-dy + body-dy) }
https://github.com/bennyhandball/PA1_LoB_Finance
https://raw.githubusercontent.com/bennyhandball/PA1_LoB_Finance/main/PA/codelst/2.0.1/codelst.typ
typst
#let codelst-counter = counter("@codelst-line-numbers") // Counts the number of blanks (of a specific type) // the line starts with. #let codelst-count-blanks( line, char:"\t" ) = { let m = line.match(regex("^" + char + "+")) if m != none { return m.end } else { return 0 } } // Counts the maximum number of whitespace (of similar type) // all lines have in common. #let codelst-gobble-count( code-lines ) = { let gobble = 9223372036854775807 let _c = none for line in code-lines { if line.trim().len() == 0 { continue } if not line.at(0) in (" ", "\t") { return 0 } else { if _c == none { _c = line.at(0) } gobble = calc.min(gobble, codelst-count-blanks(line, char:_c)) } } return gobble } // Removes whitespace from the start of each line. #let codelst-gobble-blanks( code-lines, gobble ) = { if gobble == auto { gobble = codelst-gobble-count(code-lines) } // Convert tabs to spaces and remove unnecessary whitespace return code-lines.map((line) => { if line.len() > 0 { line = line.slice(gobble) } line }) } // Alias for the numbering function #let codelst-numbering = numbering // Creates a copy of the given raw element with // some optional overwrites for some options. // If a text is provided, the text from the original raw element // is ignored. #let codelst-raw-copy( code, text:none, ..overrides ) = { let args = (:) for k in ("syntaxes", "theme", "align", "lang", "block") { if code.has(k) { args.insert(k, code.at(k)) } } for (k, v) in overrides.named() { args.insert(k, v) } if text == none { raw(..args, code.text) } else { raw(..args, text) } } // Default format for code frames #let code-frame( fill: luma(250), stroke: .6pt + luma(200), inset: (x: .45em, y: .65em), radius: 3pt, clip: false, code ) = block( fill: fill, stroke: stroke, inset: inset, radius: radius, breakable: true, width: 100%, clip: clip, code ) // Default format for line numbers #let codelst-lno( lno ) = text(.8em, luma(160), raw(lno)) #let sourcecode( lang: auto, numbering: "1", numbers-start: auto, numbers-side: left, numbers-width: auto, numbers-style: codelst-lno, numbers-align: right+horizon, numbers-first: 1, numbers-step: 1, // continue-numbering: false, gutter: 10pt, tab-size: 2, gobble: auto, highlighted: (), highlight-color: rgb(234, 234,189), label-regex: regex("// <([a-z-]{3,})>$"), highlight-labels: false, showrange: none, showlines: false, frame: code-frame, syntaxes: (), theme: none, code ) = { if code.func() != raw { code = code.children.find((c) => c.func() == raw) } assert.ne(code, none, message: "Missing raw content.") let line-numbers = numbering != none let numbers-format = numbering let continue-numbering = false // TODO: How to implement? let code-lang = lang if lang == auto { if code.has("lang") { code-lang = code.lang } else { code-lang = "plain" } } let code-lines = code.text.split("\n") let line-count = code-lines.len() // Reduce lines to range if showrange != none { assert.eq(showrange.len(), 2) showrange = ( calc.clamp(calc.min(..showrange), 1, line-count) - 1, calc.clamp(calc.max(..showrange), 1, line-count) ) code-lines = code-lines.slice(..showrange) if numbers-start == auto { numbers-start = showrange.first() + 1 } } else { showrange = (0, line-count) } // Starting line number if numbers-start == auto { numbers-start = 1 if not continue-numbering { codelst-counter.update(0) } } else { codelst-counter.update(numbers-start - 1) } if not showlines { let trim-start = code-lines.position((line) => line.trim() != "") let trim-end = code-lines.rev().position((line) => line.trim() != "") showrange = (showrange.first() + trim-start, showrange.last() - trim-end) code-lines = code-lines.slice(trim-start, code-lines.len() - trim-end) numbers-start = numbers-start + trim-start } // Parse labels let labels = (:) if label-regex != none { for (i, line) in code-lines.enumerate() { let m = line.match(label-regex) if m != none { labels.insert(str(i + numbers-start), m.captures.at(0)) if highlight-labels { highlighted.push(i + numbers-start) } } } } if frame == none { frame = (b) => b } show raw.where(block: true): it => { let code-lines = it.lines.slice( showrange.first(), calc.min( showrange.last(), it.lines.len() ) ) // TODO: Somehow one blank line gets removed from the raw text (seems like a bug). This adds them back, if necessary. if showrange.last() > it.lines.len() { code-lines += ("",) * (showrange.last() - it.lines.len()) } let line-count = code-lines.len() // Numbering function let next-lno() = { codelst-counter.step() context codelst-counter.display((lno) => [ #if lno >= numbers-first and calc.rem(lno - numbers-first, numbers-step) == 0 [ #numbers-style(codelst-numbering(numbering, lno)) ] #if str(lno) in labels { label(labels.at(str(lno))) } ]) } let code-table = style(styles => { // Measure the maximum width of the line numbers // We need to measure every line, since the numbers // are styled and could have unexpected formatting // (e.g. line 10 is extra big) let numbers-width = numbers-width if numbering != none and numbers-width == auto { numbers-width = calc.max( ..{(0pt,) + range(numbers-first - 1, line-count, step:numbers-step).map((lno) => measure( numbers-style(codelst-numbering(numbering, lno + numbers-start)), styles ).width)} ) + .1em } table( columns: if numbering == none { (1fr,) } else if numbers-side != right { (numbers-width, gutter, 1fr) } else { (1fr, gutter, numbers-width) }, column-gutter: 0pt, row-gutter: 0pt, stroke:none, inset: (x: 0pt, y: .25em), fill: (c, r) => { if r + numbers-start in highlighted { highlight-color } else { none } }, align: (c, r) => { if numbering != none { if numbers-side != right and c == 0 or (numbers-side == right and c == 2) { return numbers-align } } return start }, ..if numbering == none { code-lines } else if numbers-side != right { code-lines.map((l) => (next-lno(), none, l)).flatten() } else { code-lines.map((l) => (l, none, next-lno())).flatten() } ) }) frame[ #set align(start) #code-table ] } // Create actual raw element //// Prepare code text code-lines = code.text.split("\n") ///// Gobble whitespace from the start of lines code-lines = codelst-gobble-blanks(code-lines, gobble) ///// Remove labels code-lines = code-lines.map((line) => line.replace(label-regex, "")) let code-opts = ( block: true, lang: code-lang, syntaxes: syntaxes, tab-size: tab-size ) if theme != none { code-opts.insert("theme", theme) } raw( ..code-opts, code-lines.join("\n") ) } #let sourcefile( code, file:none, lang:auto, ..args ) = { if file != none and lang == auto { let m = file.match(regex("\.([a-z0-9]+)$")) if m != none { lang = m.captures.first() } } else if lang == auto { lang = "plain" } sourcecode( ..args, raw(code, lang:lang, block:true)) } #let lineref( label, supplement:"line" ) = locate(loc => { let lines = query(selector(label), loc) assert.ne(lines, (), message: "Label <" + str(label) + "> does not exists.") [#supplement #{context numbering("1", ..codelst-counter.at(lines.first().location()))}] }) #let codelst-styles( body ) = { show figure.where(kind: raw): set block(breakable: true) body } #let codelst( tag: "codelst", reversed: false, ..args ) = { if not reversed { return (body) => { show raw.where(lang: tag): (code) => { let code-lines = code.text.split("\n") let lang = code-lines.remove(0).trim().slice(1) sourcecode(..args, codelst-raw-copy(code, text:code-lines.join("\n")) ) } body } } else { return (body) => { show raw: (code) => { if code.text.starts-with(":" + tag) { sourcecode(..args, codelst-raw-copy(code, text:code.text.slice(tag.len() + 1))) } else { code } } body } } }
https://github.com/cs-24-sw-3-01/typst-documents
https://raw.githubusercontent.com/cs-24-sw-3-01/typst-documents/main/report/chapters/design.typ
typst
#import "../custom.typ": * = Design == Graphical User Interface == Architectural design == System Processes == Component design == Final Model Prototype
https://github.com/kaplanz/resume
https://raw.githubusercontent.com/kaplanz/resume/main/src/main.typ
typst
#import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: resume.with( author: ( name: "<NAME>", email: "<EMAIL>", affiliation: "Intel Corporation", location: "Kingston, ON", phone: "+1.416.602.2925", ), social: ( web: link( "https://zakhary.dev", media(icon: "link")[zakhary.dev] ), lin: link( "https://linkedin.com/in/zakhary", media(icon: "linkedin")[in/zakhary] ), src: link( "https://github.com/kaplanz", media(icon: "github")[kaplanz] ), ), ) = Education #experience( what: "Bachelor of Applied Science", where: "University of Toronto", when: ( from: datetime(year: 2018, month: 09, day: 01), to: datetime(year: 2023, month: 06, day: 20), ), )[ - Studied #emph[Computer Engineering] at the Faculty of Applied Science & Engineering. - Achieved #emph[Dean's List Scholar] for all semesters; confurred #emph[High Honours] upon graduation. ] = Work #experience( what: "FPGA Architect", where: "Intel Corporation", when: ( from: datetime(year: 2018, month: 09, day: 01), to: none, ), )[ - Working on Intel's next-generation FPGA's architectures. ] #experience( what: "Teaching Assistant", where: "University of Toronto", when: ( from: datetime(year: 2022, month: 08, day: 01), to: datetime(year: 2023, month: 05, day: 30), ), )[ - Hired as an undergraduate teaching assistant for C++ project-based lab component of ECE244 (Programming Fundamentals), and for Verilog processor design and ARM assembly labs for ECE243 (Computer Organization). ] #experience( what: "Computer Architect", where: "Qualcomm", when: ( from: datetime(year: 2021, month: 05, day: 10), to: datetime(year: 2022, month: 08, day: 26), ), )[ - Created transaction level model for cache architecture for use in several IPs within the Snapdragon’s digital signal processor (DSP). - Diagrammed architectures and prepared internal presentations justifying designs. - Lead exploration of high-level synthesis (HLS) workflows within architecture team. ] #experience( what: "Software Developer", where: "Geomechanica Inc.", when: ( from: datetime(year: 2020, month: 05, day: 01), to: datetime(year: 2020, month: 08, day: 31), ), )[ - Developed and tested features for Irazu, a geomechanical simulation software. - Duties included implementation of CAD editor tools, visualization of simulation outputs, project file management, and licensing. Worked using Qt in C++. ] #experience( what: "Researcher", where: "University of Toronto", when: ( from: datetime(year: 2020, month: 05, day: 01), to: datetime(year: 2020, month: 08, day: 31), ), )[ - Explored use of machine learning (ML) to extract topics from tweets via natural language processing with TensorFlow on BERT and XLNet models. - Researched improvements to distributed ML using federated learning (FL) on PyTorch. Developed framework for conducting experiments. Coauthor of paper presented at IEEE INFOCOM discussing findings of FL project. ] = Projects #experience( what: "Nintendo Game Boy Emulator", where: "Rust", when: ( from: datetime(year: 2022, month: 01, day: 22), to: none, ), fmt: "[year]", )[ - Implemented a complete hardware emulator of the DMG-01 Nintendo Game Boy, including a cycle accurate SM83 (Z80-derivative) CPU model. ] #experience( what: "Neovim Plugin", where: "Lua", when: ( from: datetime(year: 2022, month: 07, day: 20), to: datetime(year: 2023, month: 01, day: 13), ), fmt: "[year]", )[ - Created and currently maintaining an open source Neovim plugin for managing trailing whitespace. Featured in #emph(link("https://dotfyle.com/this-week-in-neovim/2#new-nvim-retrail")[This Week In Neovim]) newsletter. ] #experience( what: "KAP-16 Instruction Set Architecture", where: "Specification", when: ( from: datetime(year: 2021, month: 07, day: 19), to: datetime(year: 2022, month: 02, day: 13), ), fmt: "[year]", )[ - Designed a 16-bit instruction set architecture (ISA) for a custom CPU. Used Huffman codings when deciding encodings to innovatively improve instruction density. ] #experience( what: "Mapper", where: "C++, GTK", when: ( from: datetime(year: 2020, month: 01, day: 20), to: datetime(year: 2020, month: 05, day: 18), ), fmt: "[year]", )[ - Solved NP-complete graph problems (travelling salesman variant) using advanced meta-heuristic and simulated annealing iterative improvement algorithms. ] #experience( what: "16-bit CPU", where: "Verilog, DE1-SoC", when: ( from: datetime(year: 2020, month: 01, day: 16), to: datetime(year: 2020, month: 01, day: 24), ), fmt: "[year]", )[ - Implemented an 16-bit toy CPU in Verilog with clearly defined control and data paths. Compiled and tested on DE1-SoC FPGA development board. ] = Publications #paper( title: "Optimizing Federated Learning on Non-IID Data with Reinforcement Learning", authors: [<NAME>, #underline[<NAME>], <NAME>, <NAME>], conference: "IEEE INFOCOM 2020", ) = Relevant Courses #grid(columns: 2, gutter: 1em, course( code: "ECE241", name: "Digital Systems", mark: "A+", )[ Digital logic circuit design with substantial hands-on laboratory work using Verilog on FPGA boards. ], course( code: "ECE334", name: "Digital Electronics", mark: "A+", )[ Digital design techniques for integrated circuits, CMOS logic design, Elmore delays. ], course( code: "ECE243", name: "Computer Organization", mark: "A+", )[ CPU design in Verilog and ARM instruction set architecture. Focus on memory, caches, and scheduling IO with interrupts. ], course( code: "ECE344", name: "Operating Systems", mark: "A+", )[ Concurrency, deadlock, CPU scheduling, memory management, file systems. ], course( code: "ECE345", name: "Algorithms & Data Structures", mark: "A+", )[ Trees, graphs, amortized analysis, hashing, dynamic programming, greedy, NPC. ], course( code: "ECE244", name: "Programming Fundamentals", mark: "A+", )[ Object-oriented programming in C++. ], course( code: "APS360", name: "Artificial Intelligence Fundamentals", mark: "A+", )[ Optimizing neural networks, autoencoders, RNNs, NLP, GANs. ] )
https://github.com/k0tran/cont_labs
https://raw.githubusercontent.com/k0tran/cont_labs/master/reports/lab6.typ
typst
#import "template.typ": * #show: lab.with(n: 6) = Конфигурация виртуальных машин #pic(img: "lab6/vagrant.png")[Настройка виртуальных машин] = Инициализация роя #pic(img: "lab6/swarm_init.png")[Инициализация роя на машине manager1] #pic(img: "lab6/swarm_join_link.png")[Получение команды для добавления машины в рой] = Добавление нод #pic(img: "lab6/swarm_node1.png")[Добавление worker1 в качестве ноды] #pic(img: "lab6/swarm_node2.png")[Добавление worker2 в качестве ноды] #pic(img: "lab6/swarm_node_list.png")[Список нод] #pic(img: "lab6/swarm_node_vagrant.png")[Vagrant script] = Развертывание сервиса в кластере #pic(img: "lab6/service.png")[Запуск hello world на кластере] - команда `docker service create` создает службу; - флаг `--name` называет службу helloworld; - флаг `--replicas` указывает желаемое состояние одного работающего экземпляра; - aргументы `alpine ping` docker.com определяют службу как контейнер Alpine Linux, который выполняет команду `ping docker.com`. = Инспектирование сервиса в кластере #pic(img: "lab6/service_info.png")[Просмотр информации о контейнере] Вывод команды `sudo docker service inspect helloworld`: ```json [ { "ID": "pgd1yns23qfmv9rvhdk1wt0cv", "Version": { "Index": 21 }, "CreatedAt": "2023-10-31T17:36:51.670589461Z", "UpdatedAt": "2023-10-31T17:36:51.670589461Z", "Spec": { "Name": "helloworld", "Labels": {}, "TaskTemplate": { "ContainerSpec": { "Image": "alpine:latest@sha256:eece025e432126ce23f223450a0326fbebde39cdf496a85d8c016293fc851978", "Args": [ "ping", "docker.com" ], "Init": false, "StopGracePeriod": 10000000000, "DNSConfig": {}, "Isolation": "default" }, "Resources": { "Limits": {}, "Reservations": {} }, "RestartPolicy": { "Condition": "any", "Delay": 5000000000, "MaxAttempts": 0 }, "Placement": { "Platforms": [ { "Architecture": "amd64", "OS": "linux" }, { "OS": "linux" }, { "OS": "linux" }, { "Architecture": "arm64", "OS": "linux" }, { "Architecture": "386", "OS": "linux" }, { "Architecture": "ppc64le", "OS": "linux" }, { "Architecture": "s390x", "OS": "linux" } ] }, "ForceUpdate": 0, "Runtime": "container" }, "Mode": { "Replicated": { "Replicas": 1 } }, "UpdateConfig": { "Parallelism": 1, "FailureAction": "pause", "Monitor": 5000000000, "MaxFailureRatio": 0, "Order": "stop-first" }, "RollbackConfig": { "Parallelism": 1, "FailureAction": "pause", "Monitor": 5000000000, "MaxFailureRatio": 0, "Order": "stop-first" }, "EndpointSpec": { "Mode": "vip" } }, "Endpoint": { "Spec": {} } } ] ``` #pic(img: "lab6/service_ps.png")[На каких нодах запущен сервис] = Масштабирование сервера в кластере #pic(img: "lab6/scale.png")[Масштабирование] = Удаление сервиса #pic(img: "lab6/rm.png")[Удаление контейнера] Проверим как быстро были удалены контейнеры на разных машинах: #pic(img: "lab6/rm1.png")[`docker ps` на manager1] #pic(img: "lab6/rm2.png")[`docker ps` на worker1] #pic(img: "lab6/rm3.png")[`docker ps` на worker2] = Обновление сервиса #pic(img: "lab6/redis_create.png")[Создание redis контейнера] #pic(img: "lab6/redis_info.png")[Информация о контейнере] #pic(img: "lab6/redis_update.png")[Обновление] - остановка первого task; - планирование обновления для остановленной задачи (task); - запуск контейнера обновленной задачи; - если обновление задачи возвращает RUNNING, ожидание установленной задержки, а затем запуск задачи; - если в процессе обновления задача возвращает FAILED, остановка обновления. #pic(img: "lab6/redis_after_update.png")[После обновления] #pic(img: "lab6/service_update.png")[Запуск обновленной версии] #pic(img: "lab6/redis_ps.png")[Контейнеры] = Обслуживание нод кластера На предыдущих этапах руководства все узлы работали в ACTIVE режиме. Менеджер кластера может назначать задачи любому ACTIVE узлу, поэтому до сих пор все узлы были доступны для получения задач. Иногда, например, во время планового обслуживания необходимо установить узел в режим DRAIN. DRAIN режим не позволяет узлу получать новые задачи от менеджера кластера. Это также означает, что менеджер останавливает задачи, выполняемые на узле, и запускает задачи реплики на ACTIVE доступном узле. #pic(img: "lab6/aval_check.png")[Проверка доступности нод] #pic(img: "lab6/aval_create.png")[Создание сервиса] #pic(img: "lab6/aval_wrk1_drain.png")[Перевод worker1 в режим DRAIN] #pic(img: "lab6/aval_ps.png")[ps после перевода worker1 в DRAIN] #pic(img: "lab6/aval_wrk1_aval.png")[Перевод worker1 обратно в режим AVALIABLE]
https://github.com/kaarmu/splash
https://raw.githubusercontent.com/kaarmu/splash/main/README.md
markdown
MIT License
# splash Add a splash of color to your project with these palettes for [Typst](https://github.com/typst/typst). This library provides different color palettes with human-readable names in Typst dictionaries. Currently there are just a few different palettes to choose from. Any contributions or suggestions are welcome! *Note*: `splash` is in the [Typst Package Repository](https://github.com/typst/packages). See how to use it in the example below. ## Usage ```typst #import "@preview/splash:0.4.0": xcolor #box(width: 3em, height: 1em, fill: xcolor.dandelion) ``` ## Documentation See the different colors in the [documentation](https://github.com/kaarmu/splash/blob/v0.4.0/doc/main.pdf).
https://github.com/ustctug/ustc-thesis-typst
https://raw.githubusercontent.com/ustctug/ustc-thesis-typst/main/chapters/publications.typ
typst
MIT License
#block[ = 已发表论文 <已发表论文> + A A A A A A A A A + A A A A A A A A A + A A A A A A A A A = 待发表论文 <待发表论文> + A A A A A A A A A + A A A A A A A A A + A A A A A A A A A = 研究报告 <研究报告> + A A A A A A A A A + A A A A A A A A A + A A A A A A A A A ]
https://github.com/Me0wzz/study-note
https://raw.githubusercontent.com/Me0wzz/study-note/main/wrtt/240416.typ
typst
258 페이지 10번 실효값 0.023 20logVrms = 16.99dB = 실험 1 #image("assets/2024-04-16-16-26-05.png") 5.12 (offset 2) #image("assets/2024-04-16-16-27-29.png") 7.16 (offset 4) #image("assets/2024-04-16-16-27-05.png") 10.2 (offset 8) = 실험 2 #image("assets/2024-04-16-16-28-51.png") 1.08 #image("assets/2024-04-16-16-29-24.png") 채널 2 to 채널 1 중첩 (9.2) #image("assets/2024-04-16-16-30-12.png") 1.02V = 실험 3 #image("assets/2024-04-16-16-37-27.png") 1kHz, 16.0dB $20log(V_("rms")) = 20log(0.707 times 10) = 16.98$\ #image("assets/2024-04-16-16-43-49.png") 2kHz, -34.4dB = 실험 4 #image("assets/2024-04-16-16-45-20.png") 1kHz, 7.04V = 실험 5 #image("assets/2024-04-16-16-47-30.png") 5Hz, 12.0dB, 1kHz, 7.2dB #image("assets/2024-04-16-16-50-13.png") 5Hz, 3.92V, 1kHz, 2.16V = 실험 6 #image("assets/2024-04-16-16-55-21.png") 1.05khz, 9.6dB, 20khz,12.0dB #image("assets/2024-04-16-16-56-14.png") 1.05khz, 2.96v,20khz,960mv = 실험 7 #image("assets/2024-04-16-16-58-42.png") 1.05khz 9.12v 3khz 3.12v = 실험 8 #image("assets/2024-04-16-17-00-55.png") 19.8 #image("assets/2024-04-16-17-02-09.png") 19.6 = 실험 9 #image("assets/2024-04-16-17-03-13.png") 20V #image("assets/2024-04-16-17-04-24.png") 15.8V = 실험 10 #image("assets/2024-04-16-17-06-25.png") 18.8 13.4 0.7283, 49.52 = 실험 11 #image("assets/2024-04-16-17-12-11.png") 1 0\ 1 0\ 1 0\ 0.9615 3.85\ 0.9412 5.88\ 0.9796 2.04 \ 0.9791 2.09 \ 0.9574 4.26 \ 0.9149 8.51 \ 0.8510 14.9 \ 0.8085 19.15 \ 0.7659 23.41 \ 0.7234 27.64 \ #image("assets/2024-04-16-17-21-50.png") 0.7234 72.34 \ 0.4782 47.82 \ 0.3478 34.78 \ 0.2826 28.26 \ 0.2391 23.91 \ 0.1956 19.56 \ 0.1739 17.39 \ 0.1521 15.21 \ 0.1521 15.21 \ 0.1521 15.21 \ 0.1111 11.11 \ 0.0667 6.67 \ 0.0444 4.44 \ = 실험 12 #image("assets/2024-04-16-17-30-32.png") 1khz 2.8v 50khz 920mv #image("assets/2024-04-16-17-35-10.png") 1khz 2.72v 50khz 120mv
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/attach-00.typ
typst
Other
// Test basics, postscripts. $f_x + t^b + V_1^2 + attach(A, t: alpha, b: beta)$
https://github.com/darkMatter781x/OverUnderNotebook
https://raw.githubusercontent.com/darkMatter781x/OverUnderNotebook/main/entries/auton/disrupt/disrupt.typ
typst
#import "../auto-util.typ": * #auton( "Close Side Disrupt", datetime(year: 2024, month: 2, day: 19), "disrupt.cpp", [This auton both moves the center triballs such that the opposing alliance cannot use them. and hopefully pushes them over to the other side to score 4 swing points for our team. It also gets AWP which requires the robot to remove the matchload zone triball and touch the horizontal elevation bar. ], )[ // auto route: https://excalidraw.com/#json=RChcg3g7wm8WuuQ7x0Fq9,7Ot7uQK4_Mj7DHtzAJwbBA #figure(image("./route.svg", width: 100%), caption: [ auton route ]) ```cpp void runDisrupt() { // front of drivetrain should be aligned with closer edge of puzzle pattern // x is where neil decided so Robot::chassis->setPose( {0 - TILE_LENGTH * 2 + Robot::Dimensions::drivetrainWidth / 2 + 6, MIN_Y + TILE_LENGTH - Robot::Dimensions::drivetrainLength / 2, UP}, false); // position the robot to disrupt center triballs Robot::chassis->moveToPose(-TILE_LENGTH - 3, -TILE_LENGTH + 6, RIGHT, 3000, {.lead = .3, .minSpeed = 64}); // wait until facing right to push triballs waitUntil([] { return robotAngDist(RIGHT) < 20 || !isMotionRunning(); }); Robot::chassis->cancelMotion(); // prepare to push triballs Robot::Actions::expandBothWings(); Robot::Actions::outtake(); // full speed into the triballs Robot::chassis->moveToPoint(10000000, 0, 3000, {.minSpeed = 127}); // wait until near barrier waitUntil([] { return Robot::chassis->getPose().x > -12.5 || !isMotionRunning(); }); Robot::chassis->cancelMotion(); // done disrupting // position the robot to clear matchload zone Robot::chassis->moveToPoint(-TILE_LENGTH * 2 - 3, -TILE_LENGTH * 2 - 6, 3000, {.forwards = false}); // retract wings Robot::chassis->waitUntil(5); Robot::Actions::retractBothWings(); Robot::chassis->waitUntilDone(); // turn to be parallel to the matchload pipe Robot::chassis->turnTo(1000000, -1000000, 2000); Robot::chassis->waitUntilDone(); // expand wing Robot::Actions::expandBackWing(); // move in an arc to sweep ball out tank(32, 127, 0, 0); // wait until facing right or if we are far from the matchload zone waitUntil( [] { return robotAngDist(RIGHT) < 10 || Robot::chassis->getPose().x > -TILE_LENGTH * 1.5; }, 0, 1000); stop(); // ensure we don't bend back wing Robot::Actions::retractBackWing(); // intake any straggler balls Robot::Actions::intake(); // let matchload zone triball get ahead of us pros::delay(1000); // touch horizontal elevation bar Robot::chassis->moveToPose(0 - Robot::Dimensions::drivetrainLength / 2 - 3.5, MIN_Y + TILE_RADIUS, RIGHT, 2000); // if a triball enters the intake, outtake it while (pros::competition::is_autonomous()) { if (isTriballInIntake()) { Robot::Actions::outtake(); pros::delay(500); } pros::delay(10); } } ``` ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/layout-infinite-lengths_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // #set page(width: auto, height: auto) // // // Error: 17-41 cannot create line with infinite length // #layout(size => line(length: size.width))
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/tournament-states/entry.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator, diagraph #import notebookinator: * #import themes.radial.components: * #import "/utils.typ": tournament-from-csv #import diagraph: * #show: create-body-entry.with( title: "Tournament: State Championship", type: "test", date: datetime(year: 2024, month: 3, day: 2), author: "<NAME>", witness: "<NAME>", ) = Qualifications #let qual-data = tournament-from-csv( read("./RE-VRC-23-2762-HS States-Results-2024-03-08.csv"), team-name: "53E", section: "qualifications", ) #(qual-data.at(0).awp = true) #tournament(..qual-data) #colbreak() = Alliance Selection We ended up in 24th place, leaving us in the unfortunate situation of needing to be picked by a team higher up in the rankings. If a team picked us we would be forced to accept, so there wasn't much decision making to do. Here's the list of teams we talked to, in the order that they ranked by. + 9080C + 9080H + 929S + 929T In the end, 9080H picked us because they weren't picked by their first pick. = Eliminations #let elims-data = tournament-from-csv( read("./RE-VRC-23-2762-HS States-Results-2024-03-08.csv"), team-name: "53E", section: "eliminations", ) #tournament(..elims-data) We ended up being eliminated in our first round 16 match, by a single point. = Reflection #grid( columns: (1fr, 1fr), align(center, pie-chart( (value: 4, color: green, name: "wins"), (value: 5, color: red, name: "losses"), )), [ Overall, our match performance wasn't great. We weren't able to maintain our momentum, and were only able to score the AWP once, leading us to be placed lower than we would have liked. Fortunately, we were able to win the Design Award, qualifying us for the World Championship! Not only that, but two other teams in our organization qualified as well, 53C and 53F. ], )
https://github.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024
https://raw.githubusercontent.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024/master/chap10/main.typ
typst
#set text(lang: "zh", cjk-latin-spacing: auto, font: "Noto Serif CJK SC") #set page("iso-b5", numbering: "1", margin: (left: 1.4cm, right: 1.9cm)) #set par(leading: 1.1em) #show table: set text(font: "Zhuque Fangsong (technical preview)") #show figure.caption: set text(font: "Zhuque Fangsong (technical preview)") #show "。": "." #show heading: set text(font: "Noto Sans CJK SC", size: 1.15em) = 数字图像处理 第10章 形状表示与描述 作业 == 1 #stack( dir: ltr, spacing: 4%, box(width: 38%)[ #set text(weight: "bold") 教材P509页,第10.7题。 假设我们已使用示于如图中的边缘模型代替了图10.10中的斜坡模型。请写出每个剂面的梯度和拉普拉斯算子。(教材P509页,第10.7题。)], figure( caption: "斜坡1", image("./1.svg", width: 28%), ), figure( caption: "斜坡2", image("./2.svg", width: 25%), ), ) == 2 #let stderr = $plus.minus 3 sigma$ #let I1 = 60 #let I2 = 180 #let span = 10 * 3 *右图所示图像中的物体和背景,在标度范围 $[0, 255]$ 内具有的平均灰度分别为180和70。该图像被均值为0、标准差为10个灰度级的高斯噪声污染了。请提出一种正确分割率为90%或更高百分比的阈值处理方法。(回忆一下,高斯曲线下99.7%的面积位于均值的 $plus.minus 3 sigma$ 区间内。)(教材P512页,第10.36题。) * 均值为 $I_1 = 60$ 灰度级和 $I_2 = 180$ 灰度级,噪声的标准差为 $sigma = 10$ 灰度级,则 $I_1 stderr = [#(I1 - span), #(I1 + span)] $,$I_2 stderr = [#(I2 - span), #(I2 + span)]$。因此,可选择阈值 $T = 120$,此时正确分割率在 99% 以上。 // 因此两个亮度群体之间存在明显的分离。因此选择170作为种子值来生长对象是相当合适的。一种方法是通过将任何与先前附加到该种子的任何像素8连通的像素附加到种子上,并且其亮度为170±3σ为生长区域。 == 3 *提出一个区域生长算法来分割习题10.36中的图像。(教材P512页,第10.38题。)* 根据上一题,可以以灰度级为 $I_2 = I2$ 的点为种子点,并选择八连通的、灰度级在 $170 stderr$ 内的像素点为生长区域。 #include "quadtree.typ"
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/finite/0.1.0/cmd.typ
typst
Apache License 2.0
#import "@preview/t4t:0.3.0": is, assert, def #import "@preview/cetz:0.0.2" #import "./draw.typ" #import "./layout.typ" /// Draw an automaton from a transition table. /// /// The transition table #arg[states] has to be a dictionary of dictionaries, having /// the names of all states as keys in the first level dictionary and names of states, /// the state has a transition to as keys in the second level dictionaries. The values /// in the second level dictionary are labels (inputs) for the transitions. /// /// The following example, defines three states `q0`, `q1` and `q2`. For the input `0` /// `q0` transitions to `q1` and to `q2` for the inputs `0` and `1`. /// `q1` transitions to `q0` for `0` and `1` and `q2` for `0`. `q2` has no transitions. /// #codesnippet[```typ /// #automaton(( /// q0: (q1:0, q0:"0,1"), /// q1: (q0:(0,1), q2:"0"), /// q2: none /// )) /// ```] /// If no initial and final states are defined, #cmd-[automaton] selects the first and last /// state in the dictionary respectively (`q0` and `q2` in this example). /// /// As you can see, the transition labels can be provided as a single value or an array. /// Arrays are joined with a comma (`,`) to generate the final label. /// #ibox[ /// For now, there is no difference in providing inputs as arrays or strings. Internally, /// string are split on commas, to get atomic symbols, and later joined again. /// Future versions might use these symbols, though, to actually simulate the automaton /// and decide if a word is accepted or not. /// ] /// /// #arg[inital] and #arg[final] can be used to customize the initial and final states. /// /// - states (dictionary): A dictionary of dictionaries, defining the transition table of an automaton. /// - initial (string, auto, none): The name of the initial state. For #value(auto), the first state in #arg[states] is used. /// - final (array, auto, none): A list of final state names. For #value(auto), the last state in #arg[states] is used. /// - style (dictionary): A dictionary with styles for states and transitions. /// - label-format (function): A function #lambda("string", "boolean", ret:"string") to format labels. /// The function will get the label as a string and a boolean #arg[is-state], if the label is generated for a state (#value(true)) or a transition (#value(false)). It should return the final label as #dtype("content"). /// - layout (function): A layout function. See below for more information on layouts. /// - ..canvas-styles (any): Arguments for #cmd-(module:"cetz")[canvas] #let automaton( states, initial: auto, final: auto, style: (:), label-format: (label, is-state) => if is-state and is.str(label) and label.starts-with("q") { [q#sub(label.slice(1))] } else { label }, layout: layout.linear, ..canvas-styles ) = { assert.that(is.dict(states), message: (v) => "Need a dictionary with state and transition information. Got " + repr(v)) if is.a(initial) { initial = states.keys().first() } if is.a(final) { final = (states.keys().last(), ) } else if is.n(final) { final = () } cetz.canvas(..canvas-styles, { import cetz.draw: set-style import draw: state, transition set-style(..style) layout((0,0), { for name in states.keys() { state((), name, label: label-format(name, true), initial: (name == initial), final: (name in final), ..style.at(name, default:(:)) ) } }) // Transitions don't need to be layed out for (from, transitions) in states { if is.dict(transitions) { for (to, label) in transitions { let name = from + "-" + to if is.arr(label) { label = label.map(str).join(",") } else if is.dict(label) and "text" in label and is.arr(label.text) { label.text = label.text.map(str).join(",") } transition( from, to, inputs: label, label: label-format(label, false), ..style.at(name, default:(:)) ) } } } }) } /// Displays a transition table for an automaton. /// /// The format for #arg[states] is the same as for @@automaton. /// /// #example[``` /// #finite.transition-table(( /// q0: (q1: 0, q0: (1,0)), /// q1: (q0: 1, q2: (1,0)), /// q2: (q0: 1, q2: 0), /// )) /// ```] /// /// - states (dictionary): A dictionary of dictionaries, defining the transition table of an automaton. /// - initial (string, auto, none): The name of the initial state. For #value(auto), the first state in #arg[states] is used. /// - final (array, auto, none): A list of final state names. For #value(auto), the last state in #arg[states] is used. /// - format (function): /// - format-list (function): /// - ..table-style (any): Arguments for #doc("layout/table"). #let transition-table( states, initial: auto, final: auto, format: (col, v) => raw(str(v)), format-list: (states) => if states.len() > 1 { "{" + states.join(",") + "}"} else { states.join(",") }, ..table-style ) = { assert.that(is.dict(states), message: (v) => "Need a dictionary with state and transition information. Got " + repr(v)) if is.a(initial) { initial = states.keys().first() } if is.a(final) { final = (states.keys().last(), ) } else if is.n(final) { final = () } let inputs = () for (state, transitions) in states { if is.dict(transitions) { for (name, label) in transitions { if is.str(label) { label = label.split(",") } inputs = inputs + def.as-arr(label) } } } inputs = inputs.dedup() inputs = inputs.map(str) let table-cnt = () for (state, transitions) in states { table-cnt.push(format(0, state)) if is.dict(transitions) { for (i, char) in inputs.enumerate() { let to = () for (name, label) in transitions { if is.str(label) { label = label.split(",") } label = def.as-arr(label).map(str) if char in label { to.push(format(i+1, name)) } } table-cnt.push(format-list(to)) } } } table( columns: 1 + inputs.len(), fill: (c,r) => if r == 0 or c == 0 { luma(240) }, align: center + horizon, ..table-style, [], ..inputs, ..table-cnt ) }
https://github.com/sabitov-kirill/comp-arch-conspect
https://raw.githubusercontent.com/sabitov-kirill/comp-arch-conspect/master/main.typ
typst
#import "conf.typ": conf #show: rest => conf(rest, title: [ = Билеты к экзамену по Арх. ЭВМ (Первый семестр) ], pageHeader: [ Билеты к экзамену по Арх. ЭВМ ], credits: [ #align(center)[#text(gray)[ Created by <NAME>, <NAME>, <NAME>\ January 2023 ]] ], color: blue, ) #{ // All tickets list let tickets = ( "1_phisical_base.typ", "2_numbers.typ", "3_functional_schemes.typ", "4_memory.typ", "5_chipsets.typ", "6_ram.typ", "7_cache.typ", "8_virtual_memory.typ", "9_isa.typ", "11_storage.typ", "12_parallel.typ", ) for ticket in tickets { pagebreak() include ("questions/" + ticket) } }
https://github.com/0x1B05/english
https://raw.githubusercontent.com/0x1B05/english/main/cnn10/main.typ
typst
#import "template.typ": * #show: template.with( title: [CNN10-Notes], short_title: "CNN10", description: [ CNN10 练习(听力,回译). ], date: datetime(year: 2024, month: 3, day: 22), authors: ( ( name: "0x1B05", github: "https://github.com/0x1B05", homepage: "https://github.com/0x1B05", // 个人主页 affiliations: "1", ), ), affiliations: ( (id: "1", name: "NUFE"), ), paper_size: "a4", text_font: "Linux Libertine", sc_font: "Noto Sans CJK SC", code_font: "DejaVu Sans Mono", // 主题色 accent: orange, // 封面背景图片 cover_image: "./figures/Pine_Tree.jpg", // 图片路径或 none // 正文背景颜色 // background_color: "#FAF9DE" // HEX 颜色或 none ) #include "content/20240304.typ" #include "content/20240308.typ" #include "content/20240312.typ" #include "content/20240313.typ" #include "content/20240402.typ" #include "content/20240425.typ" #include "content/20240513.typ" #include "content/20240521.typ"
https://github.com/drupol/ipc2023
https://raw.githubusercontent.com/drupol/ipc2023/main/src/ipc2023/history.typ
typst
#import "imports/preamble.typ": * #focus-slide[ #set align(center + horizon) #set text(size: 1.5em, fill: white, font: "Virgil 3 YOFF") Brief history #pdfpc.speaker-note(```md I haven't explained yet what Nix is, but this will come, no worries... Let's start with a brief history ```) ] #slide(title: "Nix", new-section: "History",)[ #let cell = box.with() #grid( columns: (2fr, 3fr), cell(height: 100%)[ #uncover("1,4-", mode: "transparent")[- 2003: First commit] #uncover("2,4-", mode: "transparent")[- 2006: Doctoral thesis] #uncover("3,4-", mode: "transparent")[- 2006: NixOS #box(baseline: 4pt)[#image("../../resources/images/Nix_snowflake.svg", height: 1em)]] ], cell(height: 100%, width: 100%)[ #only("1")[ #set text(size: .5em) #figure( box(inset: (top: 5pt, x: 5pt), fill: black)[#image("../../resources/screenshots/Screenshot_20231021_170656.png", fit: "contain")], caption:[First commit of the Nix project @NixFirstCommit] ) ] #only("2")[ #set text(size: .5em) #figure( box(inset: (top: 2pt, x: 2pt), fill: black)[#image("../../resources/screenshots/Screenshot_20231021_171758.png", height: 90%, fit: "contain")], caption:[<NAME>'s PHD thesis @Dolstra06] ) ] #only("3")[ #set text(size: .5em) #figure( box(inset: (top: 2pt, x: 2pt), fill: black)[#image("../../resources/screenshots/Screenshot_20231022_120449.png", height: 90%, fit: "contain")], caption:[<NAME>'s master thesis @INF-SCR-2005-091] ) ] #only("4")[ #figure( image("../../resources/sourcecode/nixos-stats/nixos-stats.svg", height: 100%, fit: "contain") ) ] ] ) #pdfpc.speaker-note(```md In 2003, the journey of Nix began, you can see here the first commit. ... leading to its official launch in 2006. The brain behind Nix is <NAME>, who developed it as part of his PhD work at the University of Utrecht in the Netherlands. And let's give credit where it's due - although Nix has grown to receive global contributions - it originated right here in Europe! The same year, <NAME> wrote a master thesis on building a Linux distribution managed by Nix... and he built the first NixOS linux distribution, which is the Linux distribution built on top of Nix, this is the distribution that I use since 3 years now. And here we are, roughly 20 years later, with a thriving community and a growing ecosystem, as you can see on this chart. The chart was made from statistics extracted from the git repository. ```) ]
https://github.com/matteopolak/resume
https://raw.githubusercontent.com/matteopolak/resume/main/utils.typ
typst
MIT License
#let config = toml("config.toml") // Create a consistent vertical spacing #let space(h: 0.6em) = v(h, weak: true) // Shortcut for evaluating a string as markup #let markup(str) = eval(str, mode: "markup") // Format a job entry #let job(title: "", company: "", location: "", start: "", end: "Present", achievements: ()) = { let format = "[month repr:long] [year]" let end = if type(end) == str [#end] else [#end.display(format)] stack( dir: ltr, align(alignment.start, [*#title* \ #company]), align(alignment.end, [#start.display(format) --- #end \ #emph(location)]) ) space(h: 0.7em) list(..achievements) } // Format a project entry #let project(title: "", github: "", tags: (), achievements: ()) = { if not config.projects.enabled.contains(github) { return [] } [ #link("https://github.com/" + github, title) -- #tags.map(t => text(weight: "semibold", t)).join(", ") ] space(h: 0.7em) list(..achievements) } // Create a section heading #let section(title: "", right: "") = { [ *#upper(title)* #h(1fr) #right ] line(length: 100%) } // Create a coloured header with some centered content #let header(content, padding: 0.4in, alignment: center + horizon) = box( width: 100%, fill: rgb(38, 38, 38), // we want to push the content below it down inset: (bottom: padding - 0.1in), // but since this is at the top, we want to fill // the margin with the background of the box outset: (x: padding, top: padding), align(alignment, content) )
https://github.com/PA055/5839B-Notebook
https://raw.githubusercontent.com/PA055/5839B-Notebook/main/Entries/entries.typ
typst
#include "./Game_Discussion/pre_reveal.typ" #include "./Game_Discussion/post_reveal.typ" #include "./First-Steps/first-steps.typ" #include "./First-Steps/3d-design-software.typ" #include "./file-structure-model-management/file-structure-model-management.typ" #include "./inventory/taking-inventory.typ" #include "./inventory/inventory-results.typ" #include "./drivetrain/drive-train-types.typ" #include "./sensors/new-odometry-sensors.typ" #include "./drivetrain/drive-train-prototypes.typ" #include "./drivetrain/mecanum-drive-testing.typ"
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/04-opentype/exploring/post.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/components.typ": note #import "/lib/glossary.typ": tr #show: web-page-template // ### The `post` table === `post` 表 // While we're on the subject of PostScript Type 1 representation, let's briefly look at the `post` table, which is used to assemble data for downloading fonts onto PostScript printers: 既然我们已经在介绍PostScript相关技术了,也顺便看看用于把字体传输到PostScript打印机上的`post`表的内容: ```xml <post> <formatType value="3.0"/> <italicAngle value="0.0"/> <underlinePosition value="-75"/> <underlineThickness value="50"/> <isFixedPitch value="0"/> <minMemType42 value="0"/> <maxMemType42 value="0"/> <minMemType1 value="0"/> <maxMemType1 value="0"/> </post> ``` // The `post` table has been through various revisions; in previous versions, it would also include a list of glyph names, but as of version 3.0, no glyph names are provided to the PostScript processor. The final four values are hints to the driver as to how much memory this font requires to process. Setting it to zero doesn't do any harm; it just means that the driver has to work it out for itself. The italic angle is specified in degrees *counter*clockwise, so a font that leans forward 10 degrees will have an italic angle of -10. `isFixedPitch` specifies a monospaced font, and the remaining two values are irrelevant because nobody should ever use underlining for anything, am I right? `post`表有多个版本,在老版本中它还需要包含#tr[glyph]名称列表,不过3.0之后就不需要了。最后的四个值用于告诉打印机这个字体需要多少内存来进行处理。将它们设置成0并不会影响字体的功能,只是代表打印机需要自行判断使用多少内存。`italicAngle` 在表示倾斜角度时要求使用逆时针,所以向前倾斜10度的字体这个字段需要填 -10。`isFixedPitch`用于指定是否为等宽字体。剩下的两个很明显是决定下划线的位置和粗细程度。
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-算法/滑动窗口与双指针/删除有序数组中的重复项.typ
typst
#import "../../../../lib.typ":* === #Title( title: [删除有序数组中的重复项], reflink: "https://leetcode.cn/problems/remove-duplicates-from-sorted-array/description/", level: 1, )<删除有序数组中的重复项> #note( title: [ 删除有序数组中的重复项 ], description: [ 给你一个 非严格递增排列 的数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。然后返回 nums 中唯一元素的个数。 考虑 nums 的唯一元素的数量为 k ,你需要做以下事情确保你的题解可以被通过: - 更改数组 nums ,使 nums 的前 k 个元素包含唯一元素,并按照它们最初在 nums 中出现的顺序排列。nums 的其余元素与 nums 的大小不重要。 - 返回 k 。 ], examples: ([ 输入:nums = [1,1,2] 输出:2, nums = [1,2,\_] 解释:函数应该返回新的长度 2 ,并且原数组 nums 的前两个元素被修改为 1, 2 。不需要考虑数组中超出新长度后面的元素。 ],[ 输入:nums = [0,0,1,1,1,2,2,3,3,4] 输出:5, nums = [0,1,2,3,4] 解释:函数应该返回新的长度 5 , 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4 。不需要考虑数组中超出新长度后面的元素。 ] ), tips: [ 1 <= nums.length <= $3 \* 10^4$ $-10^4$ <= nums[i] <= $10^4$ nums 已按 非严格递增 排列 ], solutions: ( ( name:[双指针], text:[ 这道题目的要求是:对给定的有序数组 nums 删除重复元素,在删除重复元素之后,每个元素只出现一次,并返回新的长度,上述操作必须通过原地修改数组的方法,使用 O(1) 的空间复杂度完成。 由于给定的数组 `nums` 是有序的,因此对于任意 $i < j$,如果 `nums[i] = nums[j]`,则对于任意 $i ≤ k ≤ j$,必有 `nums[i] = nums[k] = nums[j]`,即相等的元素在数组中的下标一定是连续的。利用数组有序的特点,可以通过双指针的方法删除重复元素。 如果数组 `nums` 的长度为 0,则数组不包含任何元素,因此返回 0。 当数组 `nums` 的长度大于 0 时,数组中至少包含一个元素,在删除重复元素之后也至少剩下一个元素,因此 `nums[0]` 保持原状即可,从下标 1 开始删除重复元素。 定义两个指针 `i` 和 `j` 分别为慢指针和快指针,快指针表示遍历数组到达的下标位置,慢指针表示下一个不同元素要填入的下标位置,初始时慢指针指向下标 0,快指针指向下标 1。 假设数组 `nums` 的长度为 `n`。将快指针 `j` 依次遍历从 1 到 `n−1` 的每个位置,对于每个位置,如果 `nums[j]` 不等于 `nums[i]`,说明 `nums[j]` 和之前的元素都不同,因此将 `nums[j]` 的值复制到 `nums[i+1]` 的位置,并将 `i` 的值加 1,即指向下一个位置。 遍历结束之后,从 `nums[0]` 到 `nums[i]` 的每个元素都不相同且包含原数组中的每个不同的元素,因此新的长度即为 `i+1`,返回 `i+1` 即可。 ],code:[ ```cpp class Solution { public: int removeDuplicates(vector<int>& nums) { int i,j,n = nums.size(); if(n == 0) return 0; for(i = 0, j = 1; j < n; j++){ //j不断向后寻找 if(nums[i] != nums[j]){ //i和j各自后移一位 nums[++i] = nums[j]; //如果j=i+1,相当于什么都没有做。 } } return i+1; } } ``` ]), ), gain:none, )
https://github.com/ckunte/offshore-lifts
https://raw.githubusercontent.com/ckunte/offshore-lifts/master/offshore-lifts.typ
typst
// preamble #import "@preview/polylux:0.3.1": * #import themes.simple: * #set page(paper: "presentation-16-9") #show: simple-theme.with( footer: [OFFSHORE LIFTS], ) #set text( font: "Segoe UI", top-edge: "cap-height", bottom-edge: "baseline", number-type: "old-style", size:21pt ) // main font used // #show raw: set text(size: 18pt) // font for code // #set raw(syntaxes: "/inc/Bash.sublime-syntax") // for highlighting #show link: set text(fill: rgb(0, 0, 255)) // show links w/ colour #let sc(content) = text(features: ("c2sc",))[#content] #show regex("[A-Z]{2,}"): match => { sc(match) } // #title-slide[ = OFFSHORE LIFTS _An overview_ <NAME>, Sep 2024 ] #slide[ #side-by-side[ = Agenda - Importance, applications - Capacity limits - Lift types and selection - Howto carry out safe lifts - Importance of lifting analysis - Fabrication, certification, weighing - Offshore lifts - some examples - Vessel days worldwide stats - 10 questions, golden rule of lifting - Examples of hardware inspection - Crane banksman signals - QA ][ #figure( image("/inc/cover.jpg", height: 100%), ) ] ] #slide[ #side-by-side[ = Importance of lifts - High risk activity - Cost (day rates) - Complexity: personnel + hardware + Metocean conditions - Severity - Reputation ][ = Applications - Yard lifts (quayside) - Offshore lifts - Greenfield, and brownfield - Appurtenances, mitigations - Subsea, Pipelay, Decommissioning ] = Lifting on land _versus_ water / Land: Capacity limited by soil bearing / Seawater: (incompressible, greater buoyancy) #sym.arrow.r Higher capacity ] #focus-slide[ = Lifting capacity limits _within the industry \~15,000t_ ] #centered-slide[ Traditionally around #highlight[10,000--15,000t] (exceptions: _Pioneering Spirit_, HMC _Sleipnir_ SSCV, which offer >15,000t capacity via their unique features). Beyond this threshold, if not by crane vessels, then by the *efficiency* of structures themselves *to be made suitable for lifting* -- one time use of higher steel tonnage pumped into the structure is *neither efficient, nor good for ROI*. *Float-over* methods evolved, and became popular because of the above. ] #focus-slide[ = Lift types _routine_ \ _non-routine_ ] #slide[ #side-by-side[ #figure( image("/inc/lift-normal.jpg", height: 100%), ) ][ = Routine lifts - Known weight, shape, COG - In calm[er] environment - Standard rigging + lift equipment - Inside designated landing area - Emphasis on host ] ] #slide[ #side-by-side[ #figure( image("/inc/lift-tandem.jfif", height: 100%), ) ][ = Non-routine lifts - Personnel transfer - Synthetic sling to dynamic, shock, snatch cond. - #highlight[Blind] lifts - Beyond allowable (e.g. squalls, seastate, etc) - Lifts with awkward forms, unbalanced, valuable equipment, moving COGs - Tandem lifts Emphasis on higher risks, and safety concerns; #highlight[coordination challenges], etc. ] ] #slide[ = Lift type selection criteria / Single point: Considered generally when no limitations (layout, capacity, etc) / Multi-point: Overhang, beyond lift point grid, etc.; unbalanced load distribution; greater than single hook/crane capacity / Spreader-aided: When there is no (adequate) clearance to slings ] #slide[ #figure( image("/inc/select.png", height: 100%), caption: [Lift type selection] ) <sel> ] #slide[ = How to carry out safe lifts #side-by-side[ - #highlight[Safety in design] + fab + execution - Weight #highlight[monitoring] + fab control - #highlight[Select] crane and vessel type - types - applicability - DP, heave compensation - draft, clearances - tugs, anchor handlers - block type (single, double) ][ - Installation #highlight[procedures] - HAZID - hardware inspections + cert. - sling arrangements - OIC procedures - weather forecast - #highlight[Execution] - tugger lines - banksmen + signalling - line of sight - sparing ] ] #slide[ = Importance of lifting analysis - To assess + design structure for #highlight[installation stresses] - Offers insights into weight distribution, COG, (and COB, where relevant) - Lifting, if employed, one of the critical pre-service conditions in terms of member and joint stresses - #highlight[Early assessments can help improve layout, structural efficiency, and ROI] - To capture #highlight[changes in layout] post-design stage tolerances - To capture fabrication tolerances in terms of #highlight[eccentricities] when built ] #slide[ #figure( image("/inc/fab-challenges-1.jpg", width: 100%), caption: [Fabrication challenges _(weld access issue #sym.arrow.r incomplete coverage)_] ) <fc1> ] #slide[ #figure( image("/inc/fab-challenges-2.jpg", width: 100%), caption: [Fabrication challenges _(stiffener as a mitigation)_] ) <fc2> ] #slide[ #figure( image("/inc/hardware-test-cert.png", height: 100%), caption: [Hardware testing certification _(important)_] ) <htc> ] #slide[ #figure( image("/inc/weight-calib-cert.png", height: 100%), caption: [Weighing, calibration _(important)_] ) <wc> ] #focus-slide[ = Offshore lifts _some examples_ ] #slide[ #figure( image("/inc/lift-trad.jpg", width: 100%), caption: [Traditional lift by heavy lift vessel (HLV)] ) <hlv> ] #slide[ #figure( image("/inc/lift-semisub.jpg", width: 100%), caption: [Lift by semisub. installation vessel (SSIV)] ) <ssiv> ] #slide[ #figure( image("/inc/pioneering-spirit.jpg", width: 100%), caption: [Pioneering Spirit -- In a class of its own] ) <ps> ] #slide[ = Malikai TLP installation + TLP loaded out on to the vessel + Transported to site + Vessel begins to submerge + TLP is floated-off the submerged vessel via tugs #figure( image("/inc/inst-malikai.png", width: 100%), caption: [Malikai TLP using Dockwise's _White Marlin_] ) <mal> ] #slide[ #figure( image("/inc/lift-modular.jpg", width: 100%), caption: [Modular lift] ) <mod> ] #slide[ #figure( image("/inc/lift-module-e8k.jpg", width: 100%), caption: [Modular lift -- E8K] ) <e8k> ] #slide[ #figure( image("/inc/lift-nontrad.jpg", width: 100%), caption: [Non-traditional lifts] ) <ntl> ] #slide[ #figure( image("/inc/lift-asart.jpg", width: 100%), caption: [Lifting as an art] ) <lart> ] #slide[ #figure( image("/inc/lift-decom.jpg", width: 100%), caption: [Decommissioning] ) <dco> ] #slide[ #figure( image("/inc/lift-blanding.png", width: 100%), caption: [Appurtenance upgrade: boat landing] ) <bl> ] #slide[ #figure( image("/inc/lift-cranechart.png", width: 100%), caption: [Crane chart -- informative] ) <cc> ] #slide[ = Vessel days in 2010 -- worldwide #table( columns: (3fr, auto, 3fr, auto), inset: 10pt, align: horizon, table.header( [*_Contractor_*], [*_Vessel Days_*], [*_Contractor_*], [*_Vessel Days_*], ), [<NAME>], [1,231], [SapuraCrest], [220], [Saipem SpA], [1,117], [Larsen \& Toubro], [203], [COOEC], [688], [MDL Energy], [179], [Heerema Marine Contractors], [650], [Hyundai Heavy Industries], [115], [Nippon Steel], [358], [Smit International], [115], [Protexa], [334], [<NAME>eren], [111], [Deep Offshore Technology], [299], [Global Industries], [110], [Swiber Offshore], [272], [NPCC], [104], [Offshore Specialty], [252], [<NAME>], [87], [V. Ships], [237], [Seaway Heavy Lifting], [29] ) ] #slide[ = Guidance and support available with (some) operators #side-by-side[ - Lifting + hoisting SMEs - Standards - Lifting + hoisting manual - Forecast by Metocean - Checklists - Design - Fabrication - Review - Installation ][ - Hardware (no reuse) - Personnel, training - NDT - Certification - MWS interface - OIC interface ] ] #slide[ = Standards / ISO 19902 2020: Fixed steel offshore structures / ISO 19901-3: Topsides structures / ISO 19901-6: Marine operations / EP 2005-0264-ST: Lifting and hoisting HSE standard (Shell) ] #slide[ = Ten questions for a safe lift + Understand the procedures? + Attended toolbox talk? + Equipment pre-inspected? + Tagged w/ SWL, unique ID, valid certificate? + Are all safety devices working? + Know the person-in-charge (PIC) of lift? + Know the current lift plan, JHA, precautions? + Know Metocean limits for the lift? + Aware of self-competence, tasks assigned? + Know signalling + comms methods? ] #slide[ = The golden rule of lifting Lifts utilising cranes, hoists, or other mechanical lifting devices will not commence unless: - Assessment of lift has been complete, lift method + equipment determined by competent person(s) - Operators of powered lifting devices are trained and certified for use in the last 12 months (min) - Load does not exceed dynamic and/or static capacities of lifting equipment - Any safety devices installed on lifting equipment are operational - All lifting devices and equipment have been visually examined before each lift by competent person(s) ] #focus-slide[ = Hardware inspections ] #slide[ #figure( image("/inc/hardware-insp1.png", height: 100%), caption: [Hardware inspection] ) <hi1> ] #slide[ #figure( image("/inc/hardware-insp2.png", height: 100%), caption: [Hardware inspection (contd.)] ) <hi2> ] #focus-slide[ = Hand signals ] #slide[ #figure( image("/inc/banksmen-sig.png", height: 100%), caption: [Crane banksmen hand signals] ) <chs> ] #centered-slide[ = Thank you. Questions? ]
https://github.com/thotypous/telecom-slides
https://raw.githubusercontent.com/thotypous/telecom-slides/main/aula1/main.typ
typst
#import "@preview/polylux:0.3.1": * #import "@preview/fletcher:0.4.2" as fletcher: node, edge #import "@preview/cetz:0.2.2": canvas, plot #import themes.university: * // Make the paper dimensions fit for a presentation and the text larger #set page(paper: "presentation-16-9") #set text(font: "Inria Sans", size: 25pt) // Use #polylux-slide to create a slide and style it using your favourite Typst functions #polylux-slide[ #align(horizon + center)[ = Tecnologia de Comunicação Aula 1 -- Conceitos básicos & modulação digital Prof. <NAME> ] ] #polylux-slide[ == Apresentação da disciplina - Cinco _práticas_ acompanhadas dos conceitos relacionados: + modem V.21 + interface E1 + interface Ethernet + WSPR no satélite QO-100 + IEEE 802.11 (Wi-Fi) - Cinco _mini testes_ antes das práticas - Seminário com apresentação de experimento próprio ] #polylux-slide[ == Avaliação - 50% -- práticas (em grupo) - 20% -- quatro melhores mini testes (individual) - 30% -- seminário (em grupo) ] #polylux-slide[ == Objetivo da disciplina Transmitir informação por um canal e recebê-la do outro lado. #v(-0.5em) #fletcher.diagram( spacing: 1em, node-stroke: 1pt, edge-stroke: 1pt, node((0,0), [0110...010]), edge("-|>"), node((1,0), [modulador], shape: fletcher.shapes.pill), edge("-|>"), node((2,0), [canal], shape: fletcher.shapes.circle), edge("-|>"), node((3,0), [demodulador], shape: fletcher.shapes.pill), edge("-|>"), node((4,0), [0110...110]), ) - O canal adiciona ruído, interferência, distorções ao sinal. - O demodulador não está perfeitamente sincronizado com o modulador. - Em algumas tecnologias, há mais de um usuário compartilhando o mesmo canal. ] #polylux-slide[ == Ruído gaussiano branco aditivo (AWGN) #v(1em) $ r_t = s_t + w_t $ onde $w_t$ é uma variável aleatória regida pela distribuição $1/(sigma sqrt(2 pi)) e^(-x^2/(2 sigma^2))$ #v(1em) É o modelo de ruído mais utilizado. Por quê? - Ruído térmico - #link("https://en.wikipedia.org/wiki/Lindeberg%27s_condition")[Teorema do limite central de Lindeberg] ] #polylux-slide[ == Densidade espectral do AWGN #align(center)[ ```py plt.psd(5*np.random.randn(10000000)) ``` #image("psd1.svg", width: 45%) ] Com $sigma=5$, temos $N_0=sigma^2=25 approx 10^(14/10)$ ] #polylux-slide[ Alguns autores distribuem $N_0/2$ para $f<0$ e $N_0/2$ para $f>=0$: #align(center)[ ```py plt.psd(5*np.random.randn(10000000), sides='twosided') ``` #image("psd2.svg", width: 45%) ] Note que $N_0/2=12.5 approx 10^(11/10)$ ] #polylux-slide[ == Capacidade teórica de um canal AWGN Teorema de Shannon--Hartley: $ C = B log_2(1 + S/N) $ - $C$: capacidade (bit/s) - $B$: banda (Hz) - $S$: potência do sinal (W) - $N$: potência do ruído (W) #text(size: 14pt)[Para uma prova do teorema, veja Wozencraft & Jacobs, _Principles of Communication Engineering_, 1966, pp. 323--342.] ] #polylux-slide[ Mas $N$ depende de $B$, por exemplo: #canvas(length: 1cm, { plot.plot(size: (24, 4), x-label: [#v(0.5em)Frequência], y-label: [PSD], x-tick-step: none, y-tick-step: none, x-ticks: ((-5, $f_1$), (-1, $f_2$), (1, $f_3$), (5, $f_4$)), y-ticks: ((1, $N_0$), (5, $S_0$)), y-min: 0, y-max: 5, { plot.add( fill: true, style: (stroke: black, fill: rgb(200, 0, 0, 75)), domain: (-10, 10), _ => 1) plot.add( fill: true, style: (stroke: black, fill: rgb(0, 0, 200, 75)), domain: (-1, 1), _ => 5) }) }) Se $B=f_3-f_2$, então $S=S_0 dot (f_3-f_2)$ e $N=N_0 dot (f_3-f_2)$. Se $B=f_4-f_1$, continuamos com $S=S_0 dot (f_3-f_2)$, \ mas $N=N_0 dot (f_4-f_1)$. ] #polylux-slide[ E se pudermos escolher $B$ tão grande quanto quisermos? Lembrando que $C = B log_2(1 + S/N) = log_2(1 + S/(B dot N_0))^B $, $ lim_(B->infinity) log_2(1 + S/(B dot N_0))^B = log_2 e^(S/N_0) = S/N_0 log_2 e approx 1.44 S/N_0$ #v(1em) A expressão acima permite calcular a capacidade quando o fator limitante é a potência (e consequentemente o gasto de energia) para transmitir o sinal. ] #polylux-slide[ Ainda na condição de $B->infinity$, e se quisermos comparar $C$, que é a taxa máxima teórica, com a taxa real $f_b$ do transmissor? $ C/f_b = S/f_b 1/N_0 log_2 e $ A grandeza $S/f_b$ é bastante utilizada e recebe o nome $E_b$. Note que ela tem dimensão de joules por bit. Trata-se da energia empregada para transmitir um único bit. Temos assim: $ C/f_b = E_b/N_0 log_2 e $ ] #polylux-slide[ #align(center)[Como $f_b <= C$,] $ 1 <= C/f_b $ $ E_b/N_0 log_2 e >= 1 $ $ E_b/N_0 >= 1/(log_2 e) approx 0.693 approx -1.59 "dB" $ ] #polylux-slide[ - Gráficos de BER (taxa de bits errados) _vs_ $E_b/N_0$ são bastante usados para avaliar o desempenho de sistemas de telecomunicação. - Para chegar perto do limite teórico de $-1.59 "dB"$, além de banda muito superior à taxa de transmissão, é necessário usar códigos de correção de erro. - Estudaremos os códigos de correção de erro em uma aula futura. ] #polylux-slide[ #align(center)[ #image("jpl-shannon.svg", width: 72%) #v(-1em) #text(size: 10pt)[_Approaching The Shannon Limit at JPL: 1969--2008_, obtido de leecenter.caltech.edu.] ] ] #polylux-slide[ == Teoria de linhas de transmissão #align(center)[ #image("Transmission_line_element.svg", width: 73%) #v(-1em) #text(size: 10pt)[Adaptado de _Microwave and RF Design II_ -- Transmission Line Theory, disponível em #link("https://eng.libretexts.org/Bookshelves/Electrical_Engineering/Electronics/Microwave_and_RF_Design_II_-_Transmission_Lines_(Steer)/02%3A_Transmission_Lines/2.02%3A_Transmission_Line_Theory")[eng.libretexts.org].] ] $ (partial v(z,t))/(partial z) = - R i(z,t) - L (partial i(z,t))/(partial t) $ $ (partial i(z,t))/(partial z) = - G v(z,t) - C (partial v(z,t))/(partial t) $ ] #polylux-slide[ Substituindo soluções do tipo $e^(j omega t)$, temos: #v(2em) $ (d V(z))/(d z) = -(R + j omega L) I(z) $ $ (d I(z))/(d z) = -(G + j omega G) V(z) $ ] #polylux-slide[ Substituindo uma equação na outra, e vice-versa, temos: $ (d^2V(z))/(d z^2) - gamma^2 V(z) = 0 $ $ (d^2I(z))/(d z^2) - gamma^2 I(z) = 0 $ onde: $ gamma = sqrt((R+j omega L)(G + j omega C)) $ ] #polylux-slide[ Convém separar $gamma$ em parte real ($alpha$) e parte imaginária ($beta$). - $alpha = frak("Re"){gamma}$ é a constante de atenuação - $beta = frak("Im"){gamma}$ é a constante de fase Em uma *linha de transmissão ideal*, $R=G=0$, então temos $ gamma = sqrt(j^2 omega^2 L C) = j omega sqrt(L C) $ Ou seja, $alpha=0$, que significa que a linha não atenua o sinal, \ e $beta=omega sqrt(L C)$. A velocidade de fase é $v_p = omega / beta$, que no caso da linha ideal dá $1/sqrt(L C)$ e é igual à velocidade de grupo. ] #polylux-slide[ Em uma *linha de transmissão não ideal*, com $R!=0$ ou $G!=0$, temos atenuação e, além disso, a velocidade de fase é diferente da velocidade de grupo, o que causa dispersão do sinal conforme este se propaga pela linha: #fletcher.diagram( spacing: 4em, edge-stroke: 2pt, node((0,0), [#image("dispersion1.png", width: 10.5cm)]), edge("-|>"), node((1,0), [#image("dispersion2.png", width: 10.5cm)]), ) \ #text(size: 10pt)[Adaptado de Bertolotti, _Telegrapher's Equation_, disponível em #link("https://en.wikipedia.org/wiki/Telegrapher%27s_equations#/media/File:Telegrapher_equation.gif")[en.wikipedia.org].] ] #polylux-slide[ A atenuação cresce com a frequência, efetivamente limitando a banda que pode passar pelo cabo. Os valores de $R$, $L$, $G$, $C$ podem variar com $omega$. Por exemplo, $R$ tende a aumentar com a frequência devido ao efeito pelicular (_skin effect_), fazendo com que a atenuação cresça com a frequência ainda mais rápido do que cresceria se $R$ fosse constante. ] #polylux-slide[ #align(center)[ Cabo de telefone 24 AWG isolado com polietileno #v(1em) #image("PE-89-1.jpg", width: 40%) #v(-1em) #text(size: 10pt)[Imagem de #link("https://www.caledonian-cables.co.uk/products/telephone-cable/pe-89.shtml")[caledonian-cables.co.uk].] ] ] #polylux-slide[ #align(center)[ Atenuação de um cabo de telefone 24 AWG isolado com polietileno #image("attenuation.svg", width: 85%) #v(-1.5em) #text(size: 10pt)[Com base em medidas de $R$, $L$, $G$, $C$ de Reeve, _Subscriber Loop Signaling and Transmission Handbook_, 1995, p. 558.] ] ] #polylux-slide[ == Uma breve história da telefonia #place(left+horizon)[ 1870s: primeiras \ centrais telefônicas ] #place(right+horizon)[ #image("Swbd_333_sm.gif", width: 41%) #v(-1em) #text(size: 10pt)[Hearfield, _A manual telephone exchange: CBS2_, obtido de #link("https://www.johnhearfield.com/Telephone/CBS2.htm")[johnhearfield.com].] ] ] #polylux-slide[ #align(center+horizon)[ #image("Subs_ln_cct.gif", width: 98%) #v(-1em) #text(size: 10pt)[Hearfield, _A manual telephone exchange: CBS2_, obtido de #link("https://www.johnhearfield.com/Telephone/CBS2.htm")[johnhearfield.com].] ] ] #polylux-slide[ #align(center+horizon)[ #image("Cord_cct.gif", width: 95%) #v(-1em) #text(size: 10pt)[Hearfield, _A manual telephone exchange: CBS2_, obtido de #link("https://www.johnhearfield.com/Telephone/CBS2.htm")[johnhearfield.com].] ] ] #polylux-slide[ #align(center+horizon)[ _L-carrier system_ (FDM): 1930s -- 1970s #image("FDM_drawings_1.jpg", width: 90%) #v(-1em) #text(size: 10pt)[Adaptado de Steveo1544, _FDM drawings_, obtido de #link("https://en.wikipedia.org/wiki/File:FDM_drawings_1.jpg")[en.wikipedia.org].] ] ] #polylux-slide[ #align(center+horizon)[ _T-carrier system_ (TDM): 1960s -- hoje #image("tdm.svg", width: 95%) #v(-0.5em) #text(size: 10pt)[Wavetek, _E1 Pocket Guide_, obtido de #link("https://web.fe.up.pt/~mleitao/STEL/Tecnico/E1_ACTERNA.pdf")[web.fe.up.pt].] ] ] #polylux-slide[ - Componentes como capacitores e transformadores de isolação limitam a resposta da linha próximo de DC. - O FDM utilizava uma separação de 4 kHz entre os canais. - O TDM usa uma taxa de amostragem de 8 kHz, limitando a banda em 4 kHz de acordo com Nyquist. - Para ligações telefônicas, geralmente considera-se como banda utilizável a faixa em torno de 300 Hz a 3400 Hz. (Apesar do cabo da casa até a central geralmente suportar bem mais banda --- por isso que o ADSL é possível.) ] #polylux-slide[ == Pulse Amplitude Modulation (PAM) #align(center)[ #image("pam.svg", width: 46%) #v(-1em) #text(size: 10pt)[Oppenheim & Verghese, _6.011 Introduction to communication control and signal processing_, 2010, obtido de #link("https://ocw.mit.edu/courses/6-011-introduction-to-communication-control-and-signal-processing-spring-2010/d2df3fc906190f978ad666c9c63cdc5d_MIT6_011S10_chap12.pdf")[ocw.mit.edu].] ] $ x(t) = sum_n a[n]p(t-n T) $ ] #polylux-slide[ #align(center)[ #image("pam_tx_rx.svg", width: 100%) #v(-0.5em) #text(size: 10pt)[Oppenheim & Verghese, _6.011 Introduction to communication control and signal processing_, 2010, obtido de #link("https://ocw.mit.edu/courses/6-011-introduction-to-communication-control-and-signal-processing-spring-2010/d2df3fc906190f978ad666c9c63cdc5d_MIT6_011S10_chap12.pdf")[ocw.mit.edu].] ] #v(1em) $ X(j omega) = sum_n a[n] thick P(j omega) e^(-j omega n T) = A(e^(j Omega))|_(Omega=omega T) P(j omega) $ $ R(j omega) = H(j omega) X(j omega) $ $ B(j omega) = F(j omega) H(j omega) X(j omega) $ ] #polylux-slide[ $ X(j omega) = A(e^(j Omega))|_(Omega=omega T) P(j omega) $ $ B(j omega) = F(j omega) H(j omega) X(j omega) $ - Precisamos conhecer $A(e^(j Omega))$ em todo o intervalo $|Omega|<=pi <=> |omega|<=pi/T$ para conseguir reconstruir $a[n]$. - Precisamos que $P(j omega)!=0$, $H(j omega)!=0$ e $F(j omega)!=0$ em $|omega|<=pi/T$ para conseguir obter $A(e^(j Omega))$ em todo o intervalo $|Omega|<=pi$ a partir de $B(j omega)$. ] #polylux-slide[ #align(center)[ #image("pam_tx_rx.svg", width: 100%) #v(-0.5em) #text(size: 10pt)[Oppenheim & Verghese, _6.011 Introduction to communication control and signal processing_, 2010, obtido de #link("https://ocw.mit.edu/courses/6-011-introduction-to-communication-control-and-signal-processing-spring-2010/d2df3fc906190f978ad666c9c63cdc5d_MIT6_011S10_chap12.pdf")[ocw.mit.edu].] $ b(t) = sum_n a[n] g(t-n T) $ onde $g(t) = f(t) * h(t) * p(t)$ ] Note que se $g(0)=c$ e $g(n T)=0$ para $n!=0$, então $b(n T) = c dot a[n]$, ou seja, não há ISI --- pulsos emitidos em diferentes instantes de tempo não interferem uns com os outros no sinal $b(t)$. ] #polylux-slide[ - Uma função que satisfaz essa condição é $g(t)=sin(pi/T t)/(pi/T t)$. Nesse caso, $G(j omega)$ é constante no intervalo $|omega|<=pi/T$ e zero fora dele. - Na prática, é difícil trabalhar com pulsos no formato sinc porque eles decaem devagar. Uma alternativa comum é utilizar _raised cosine pulses_: $g(t)=sin(pi/T t)/(pi/T t) cos(beta pi/T t)/(1-(2 beta t/T)^2)$. Nesse caso, $G(j omega)$ fica contido num intervalo mais largo $|omega|<=pi/T (1+beta)$. - Deve-se projetar o pulso $p(t)$ e o filtro $f(t)$ para "anular" o efeito do canal $h(t)$, obtendo-se um $g(t)$ como acima. Se $H(j omega)=1$, adota-se $P(j omega)=F(j omega)=sqrt(G(j omega))$. ] #polylux-slide[ A modulação PAM produz sinais em banda base, ou seja, de DC até uma certa frequência de corte. #v(1em) A seguir, veremos modulações que produzem um sinal em banda passante, ou seja, de uma frequência mínima até uma frequência máxima. ] #polylux-slide[ == Frequency Shift Keying (FSK) #v(1em) $ s(t) = sum_n a[n] p(t-n T)cos((omega_c + Delta_n)t+theta_c) $ - Transmite-se os dados variando $Delta_n$. - Em tese, seria possível variar também $a[n]$, mas não é usual. - Se em vez disso o cosseno tiver uma amplitude constante $A$, \ FSK produz um sinal com envelope constante, que facilita o uso de amplificadores de alta eficiência. ] #polylux-slide[ #place(left+horizon)[ Duas maneiras de modular FSK: - *Osciladores chaveados*: \ Alterna-se entre a saída de \ $M$ osciladores do tipo \ $A cos((omega_c + Delta_n)t)$. - *Fase contínua*: \ Produz-se $A cos(phi)$ como saída, \ incrementando $phi$ de $(omega_c + Delta_n) Delta t$ \ a cada intervalo de tempo $Delta t$. ] #place(right+horizon)[ #image("cont_osc.svg", width: 45%) #v(-1em) #text(size: 10pt)[Tretter, _Additional Experiments for Communication System Design\ Using DSP Algorithms_, obtido de #link("https://user.eng.umd.edu/~tretter/commlab/c6713slides/AdditionalExperiments.pdf")[user.eng.umd.edu].] ] ] #polylux-slide[ O modulador de fase contínua pode, ainda, ser generalizado como: $ s(t) = A cos(omega_c t + phi.alt(t)) $ #v(1em) onde #v(-2.8em) $ phi.alt(t) = omega_d integral_(-infinity)^t m(tau) d tau med, quad quad m(t) = sum_n a[n] p(t-n T) $ Se usarmos um pulso limitador de banda, conseguimos uma maior redução da largura de banda do sinal. Mas, ao contrário do formalismo que desenvolvemos para o PAM, aqui $p$ atua de forma não linear sobre $s(t)$. ] #polylux-slide[ == Phase Shift Keying (PSK) #v(1em) $ s(t) = sum_n a med p(t-n T)cos(omega_c t + theta_n) $ - Varia-se $theta_n$ para transmitir os dados. - Escolhe-se $theta_n=2 pi b_n/M+theta_0$ para utilizar $M$ opções de ângulos igualmente espaçados. ] #polylux-slide[ Uma formulação alternativa é: $ s(t) = sum_n frak("Re"){a med e^(j theta_n) p(t-n T)e^(j omega_c t)} $ ou: $ s(t) = I(t) cos(omega_c t) - Q(t) sin(omega_c t) $ onde $I(t) = sum_n a_i [n] p(t-n T)$ e $Q(t) = sum_n a_q [n] p(t-n T)$ onde $a_i [n] = a cos(theta_n)$ e $a_q [n] = a sin(theta_n)$ ] #polylux-slide[ Abaixo, visualizamos no plano IQ um caso especial de PSK com $M=4$, conhecido como QPSK. #align(center)[ #image("qpsk.svg", width: 46%) #v(-1em) #text(size: 10pt)[Oppenheim & Verghese, _6.011 Introduction to communication control and signal processing_, 2010, obtido de #link("https://ocw.mit.edu/courses/6-011-introduction-to-communication-control-and-signal-processing-spring-2010/d2df3fc906190f978ad666c9c63cdc5d_MIT6_011S10_chap12.pdf")[ocw.mit.edu].] ] ] #polylux-slide[ == Quadrature Amplitude Modulation (QAM) #align(center)[ #image("qam.svg", width: 42%) #v(-1em) #text(size: 10pt)[Oppenheim & Verghese, _6.011 Introduction to communication control and signal processing_, 2010, obtido de #link("https://ocw.mit.edu/courses/6-011-introduction-to-communication-control-and-signal-processing-spring-2010/d2df3fc906190f978ad666c9c63cdc5d_MIT6_011S10_chap12.pdf")[ocw.mit.edu].] ] ] #polylux-slide[ == Offset QPSK (OQPSK) QPSK com deslocamento de meio período entre as componentes. #align(center)[ #image("OQPSK_timing_diagram.png", width: 70%) #v(-1em) #text(size: 10pt)[Splash, _Timing diagram for offset-QPSK_, obtido de #link("https://commons.wikimedia.org/wiki/File:OQPSK_timing_diagram.png")[commons.wikimedia.org].] ] ] #polylux-slide[ OQPSK limita as mudanças de fase a 90°, em vez dos 180° do QPSK. #align(center)[ #image("Oqpsk_phase_plot.svg", width: 47%) #v(-1em) #text(size: 10pt)[Alejo2083, _OQPSK phase plot_, obtido de #link("https://commons.wikimedia.org/wiki/File:Oqpsk_phase_plot.svg")[commons.wikimedia.org].] ] ] #polylux-slide[ == Demodulação IQ Relembrando algumas identidades trigonométricas: $ sin(a)cos(a) = 1/2 (sin(a)cos(a)+sin(a)cos(a)) = 1/2 sin(2a) $ $ cos^2(a) = 1/2 (cos^2(a) + 1-sin^2(a)) = 1/2 (1 + cos(2a)) $ $ sin^2(a) = 1/2 (sin^2(a) + 1-cos^2(a)) = 1/2 (1 - cos(2a)) $ ] #polylux-slide[ $ s(t) = I(t) cos(omega_c t) - Q(t) sin(omega_c t) $ $ r_i (t) = s(t) cos(omega_t) = I(t) cos^2(omega_c t) - Q(t) sin(omega_c t) cos(omega_c t) \ = 1/2 I(t) + 1/2 I(t) cos(2 omega_c t) - 1/2 Q(t) sin(2 omega_c t) $ $ r_q (t) = - s(t) sin(omega_t) = - I(t) cos(omega_c t) sin(omega_c t) + Q(t) sin^2(omega_c t) \ = - 1/2 I(t) sin(2 omega_c t) + 1/2 Q(t) - 1/2 Q(t) cos(2 omega_c t) $ Aplica-se, então, um filtro passa-baixas para eliminar os termos que oscilam ao redor de $2omega_c$. ] #polylux-slide[ #align(center)[ #image("iq_demod.svg", width: 80%) #v(-1em) #text(size: 10pt)[Adaptado de Oppenheim & Verghese, _6.011 Introduction to communication control and signal processing_, 2010, obtido de #link("https://ocw.mit.edu/courses/6-011-introduction-to-communication-control-and-signal-processing-spring-2010/d2df3fc906190f978ad666c9c63cdc5d_MIT6_011S10_chap12.pdf")[ocw.mit.edu].] ] ] #polylux-slide[ == Demodulação FSK (usando _tone filters_) #align(center)[ #image("tonefilter.svg", width: 99%) #v(-1em) #text(size: 10pt)[Tretter, _Additional Experiments for Communication System Design Using DSP Algorithms_, obtido de #link("https://user.eng.umd.edu/~tretter/commlab/c6713slides/AdditionalExperiments.pdf")[user.eng.umd.edu].] ] $ G_k (z) = sum_(n=0)^(L-1) r^n e^(j Lambda_k n t_s) z^(-n) = (1 - r^L e^(j Lambda_k L t_s) z^(-L))/(1 - r e^(j Lambda_k t_s) z^(-1)), quad r = 1 - epsilon.alt $ ] #polylux-slide[ == Visão do FSK no plano IQ #align(center)[ #image("fsk_iq.svg", width: 38%) #v(-1em) #text(size: 10pt)[Šabanović, _Low-SNR Operation of FSK Demodulators_, obtido de #link("https://repository.tudelft.nl/islandora/object/uuid%3A98a156a1-3899-4d7c-86cd-dc223b73ab40")[repository.tudelft.nl].] ] $ h = (2 omega_d)/omega_b = (Delta omega)/omega_b med, quad quad phi.alt(t) = tan_c^(-1)(Q(t)/I(t)) $ ] #polylux-slide[ == Demodulação FSK (a partir dos sinais IQ) $ d/(d t) [tan_c^(-1)(Q(t)/I(t))] = (I(t)Q'(t)-I'(t)Q(t))/(I^2(t)+Q^2(t)) $ #v(-0.5em) #align(center)[ #image("fsk_demod_arctan_deriv.svg", width: 56%) #v(-1em) #text(size: 10pt)[Šabanović, _Low-SNR Operation of FSK Demodulators_, obtido de #link("https://repository.tudelft.nl/islandora/object/uuid%3A98a156a1-3899-4d7c-86cd-dc223b73ab40")[repository.tudelft.nl].] ] ] #polylux-slide[ == Minimum Shift Keying (MSK) 2FSK com fase contínua, $h=0.5$, $p$ retangular e símbolos $b[n]$ é equivalente a OQPSK com $p(t)=sin((pi t) / (2 T))$ e símbolos $ a_i [n] = cases( -a_i [n-1] "se" b[n]!=b[n-1] \, n "ímpar", a_i [n-1] "caso contrário" ) $ $ a_q [n] = cases( -a_q [n-1] "se" b[n]!=b[n-1] \, n "par", a_q [n-1] "caso contrário" ) $ A esse caso especial de FSK (e de OQPSK) dá-se o nome MSK. ] #polylux-slide[ #align(center)[ #image("msk_equivalence.png", width: 64%) #v(-1em) #text(size: 10pt)[Chaudhari, _Minimum Shift Keying (MSK) -- A Tutorial_, obtido de #link("https://www.dsprelated.com/showarticle/1016.php")[dsprelated.com].] ] ] #polylux-slide[ == Universal Asynchronous Receiver-Transmitter (UART) #align(center)[ #image("modem_external_001_1.jpg", width: 66%) #v(-1em) #text(size: 10pt)[Imagine41, _U.S. Robotics 56K external modem_, obtido de #link("https://www.imagine41.com/product/u-s-robotics-56k-external-modem-power-adapter-cables/")[imagine41.com].] ] Usado para comunicação entre o modem de linha telefônica e o computador. ] #polylux-slide[ #align(center)[ #image("uart_sig.png", width: 90%) #v(-1em) #text(size: 10pt)[Maxim, _Determining Clock Accuracy Requirements for UART Communications_, obtido de #link("https://pdfserv.maximintegrated.com/en/an/AN2141.pdf")[maximintegrated.com].] ] Sinal digital pode ser visto como uma modulação PAM OOK com pulsos retangulares no domínio do tempo. Ou seja, ineficiente para passar por um canal com banda limitada! ] #polylux-slide[ Para sincronizar o sinal no receptor, utiliza-se um relógio mais rápido que a taxa de transmissão e localiza-se a metade do pulso a partir da primeira queda de tensão do quadro (no _start bit_). #align(center)[ #image("uart_sync.png", width: 66%) #v(-1em) #text(size: 10pt)[Maxim, _Determining Clock Accuracy Requirements for UART Communications_, obtido de #link("https://pdfserv.maximintegrated.com/en/an/AN2141.pdf")[maximintegrated.com].] ] ] #polylux-slide[ == Breve histórico dos modems de linha telefônica #v(1em) #text(size: 24pt)[ #table( columns: (auto, auto, auto, auto, auto), inset: 8pt, align: horizon, table.header( [*Bit/s*], [*Símbolos/s*], [*Modulação*], [*Norma CCITT*], [*Ano*] ), [300],[300],[2FSK],[V.21],[1964], [1200],[1200],[2FSK],[V.23],[1968], [1200],[600],[QPSK],[V.22],[1980], [2400],[600],[16QAM],[V.22bis],[1984], [4800],[2400],[QPSK],[V.32],[1984], [14400],[2400],[128QAM,TCM],[V.32bis],[1991], [28800],[3429],[1024QAM,TCM],[V.fast(V.34)],[1994], [56000],[8000],[PAM],[V.90],[1998], ) ] ] #polylux-slide[ == Prática: Implementação de um modem V.21 - Modulação 2FSK a uma taxa de 300 símbolos por segundo, em ambas as direções. - Quem faz a chamada telefônica transmite bits zero ("espaço") na frequência de 1180 Hz, e transmite bits um ("marca") na frequência de 980 Hz. - Quem atende a chamada telefônica transmite bits zero ("espaço") na frequência de 1850 Hz, e transmite bits um ("marca") na frequência de 1650 Hz. ] #polylux-slide[ Fator de modulação: $ h = (1180-980)/300 = (1850-1650)/300 = 200/300 approx 0.67 $ ] #polylux-slide[ == Hardware de um modem de linha telefônica #align(center)[ #image("wet_daa.svg", width: 64%) #v(-1em) #text(size: 10pt)[Adaptado de Randolph Telecom, _Transformer-based phone line interfaces_, obtido de #link("https://randolph-telecom.com/wp-content/uploads/2021/03/AN-5-Transformer-based-phone-line-interfaces-DAA-FXO-Rev1_IN-1300.pdf")[randolph-telecom.com].] ] ] #polylux-slide[ #align(center)[ #image("dry_daa.svg", width: 70%) #v(-1em) #text(size: 10pt)[Adaptado de Randolph Telecom, _Transformer-based phone line interfaces_, obtido de #link("https://randolph-telecom.com/wp-content/uploads/2021/03/AN-5-Transformer-based-phone-line-interfaces-DAA-FXO-Rev1_IN-1300.pdf")[randolph-telecom.com].] ] ] #polylux-slide[ #align(center)[ Híbrido #image("simple_hybrid.svg", width: 41%) #v(-1em) #text(size: 10pt)[Adaptado de National Semiconductor, _Optimal hybrid design_, obtido de #link("http://bitsavers.trailing-edge.com/components/national/_appNotes/AN-0397_Optimum_Hybrid_Design_Oct1999.pdf")[bitsavers.trailing-edge.com].] ] ] #polylux-slide[ #align(center+horizon)[ #image("simple_hybrid2.svg", width: 49%) ] ] #polylux-slide[ #place(left+horizon)[ #image("simple_hybrid3.svg", width: 49%) ] #place(right+horizon)[ $ V_1=2V_2 - V_L <=> 2V_2 = V_1 + V_L$ $ V_2=(V_1+V_O)/2 <=> V_O = 2V_2 - V_1 $ $ V_O = V_L $ ] ] #polylux-slide[ De volta à teoria de linhas de transmissão Substituindo a solução $ V(z)=V_0^+e^(-gamma z)+V_0^-e^(gamma z) $ em $ (d V(z))/(d z) = -(R + j omega L) I(z) $ temos $ -gamma V_0^+e^(-gamma z)+ gamma V_0^-e^(gamma z) = -(R + j omega L) I(z) $ $ V_0^+e^(-gamma z) - V_0^-e^(gamma z) = (R + j omega L)/gamma I(z) $ Identificamos $ Z_0 = (R + j omega L)/gamma = (R + j omega L)/sqrt((R+j omega L)(G + j omega C)) $ #v(1em) $ Z_0 = sqrt((R+j omega L)/(G + j omega C)) $ ] #polylux-slide[ O que significa $Z_0$? - Posso trocar uma linha de transmissão com impedância característica $Z_0$ por um equivalente Thevenin de \ impedância $Z_0$? *Não!* #align(center)[#image("tline_thevenin1.svg", width: 80%)] ] #polylux-slide[ O que significa $Z_0$? - Posso trocar uma linha de transmissão com impedância característica $Z_0$ terminada com uma carga de impedância $Z_0$ por um equivalente Thevenin de impedância $Z_0$? *Sim* #align(center)[#image("tline_thevenin2.svg", width: 80%)] ] #polylux-slide[ Problema: a impedância da linha telefônica não é bem padronizada #align(center)[ #image("phone_line_impedance.png", width: 70%) #v(-1em) #text(size: 10pt)[National Semiconductor, _Optimal hybrid design_, obtido de #link("http://bitsavers.trailing-edge.com/components/national/_appNotes/AN-0397_Optimum_Hybrid_Design_Oct1999.pdf")[bitsavers.trailing-edge.com].] ] ] #polylux-slide[ National Semiconductor, _Optimal hybrid design_, disponível em #link("http://bitsavers.trailing-edge.com/components/national/_appNotes/AN-0397_Optimum_Hybrid_Design_Oct1999.pdf")[bitsavers.trailing-edge.com], apresenta uma abordagem para projetar um híbrido que funciona da melhor maneira possível para um intervalo de impedâncias $Z_L$. ]
https://github.com/metamuffin/typst
https://raw.githubusercontent.com/metamuffin/typst/main/tests/typ/meta/cite-footnote.typ
typst
Apache License 2.0
Hello @netwok And again: @netwok #pagebreak() #bibliography("/works.bib", style: "chicago-notes")
https://github.com/lyzynec/hys-or-kys
https://raw.githubusercontent.com/lyzynec/hys-or-kys/main/01/main.typ
typst
#import "../lib.typ": * #knowledge[ #question(name: [Explain the concept of a discrete event.])[] #question(name: [Contrast the concept of a time-driven continuous-variable (dynamical) system with that of a discrete-event system.])[] #question(name: [Give a formal definition of a state automaton and show an example of its graphical representation by means of a state transition graph/diagram.])[] #question(name: [Explain the concept of a language and how it is related to a (state) automaton.])[] #question(name: [Enumerate standard components of a queuing system. Give a few examples of a queueing system.])[] #question(name: [Give a few important extensions of the standard state automaton.])[] #question(name: [When introducing time into an automaton, which elements must be added into the (definition of the standard untimed) automaton?])[] ] #skills[ #question(name: [Formulate some simple discrete-event system as a state automaton. If the number of states is small, draw a transition graph of the automaton.])[] #question(name: [Build a simple automaton using StateFlow.])[] #question(name: [Build a simple queueing system using SimEvents.])[] #question(name: [Build a simple timed automaton using UPPAAL.])[] ]
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/post_type_check/text_stroke1.typ
typst
Apache License 2.0
#let tmpl2(stroke: ()) = text(stroke: stroke) #tmpl2(stroke: (/* position */))
https://github.com/MattiaOldani/Informatica-Teorica
https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/complessità/21_ndtm.typ
typst
#import "../alias.typ": * = Macchine di Turing non deterministiche (NDTM) == Algoritmi non deterministici Abbiamo visto come esistano problemi molto utili di cui non si conoscono ancora algoritmi deterministici efficienti in tempo. Tuttavia, è possibile costruire degli *algoritmi non deterministici* che li risolvano, sfruttando il fatto che possono valutare velocemente la funzione obiettivo del problema. === Dinamica dell'algoritmo In generale, in un algoritmo non deterministico, la computazione non è univoca, ma si scinde in tante computazioni, una per ogni struttura generata. Sono formati da due fasi principali: - *fase congetturale*: viene generata "magicamente" una struttura/un assegnamento/una configurazione/una congettura che aiuta a dare una risposta _SI_ o _NO_; - *fase di verifica*, in cui usiamo la struttura prodotta precedentemente per decidere se vale la proprietà che caratterizza il problema di decisione. Le varie computazioni delle fasi di verifica sono tutte deterministiche. È la fase congetturale ad essere non deterministica e in particolare lo è nella creazione della struttura "magica". Dato un problema $Pi$, un'istanza $x in D$ e una proprietà $p(x)$, un algoritmo non deterministico risolve $Pi$ se e solo se: + su ogni $x$ a risposta #text(green)[positiva] (quindi $forall x : p(x) = 1$), esiste *almeno una computazione* $k$ che accetta la coppia $(x, s_k)$. + su ogni $x$ a risposta #text(red)[negativa] (quindi $forall x : p(x) = 0$), non esiste *alcuna computazione* che accetti la coppia $(x, s_k)$ per qualche $s_k$. Tutte le computazioni o rifiutano o vanno in loop. === Esempi Vediamo un algoritmo non deterministico per la soluzione di _CNF-SAT_: $ P equiv & "input"(phi(x_1, dots, x_n)); \ & "genera ass." x in {0,1}^n; \ & "if" (phi(x_1, dots, x_n) == 1) \ & quad "return" 1; \ & "return 0"; $ Ammettendo un modello di calcolo come quello descritto, questo è a tutti gli effetti un algoritmo non deterministico, formato da fase congetturale e fase di verifica. Vediamo invece un algoritmo non deterministico per trovare, se esiste, un circuito hamiltoniano in un grafo $G$. $ P equiv & "input"(G=(V,E)); \ & "genera perm." pi(v_1, dots, v_n); \ & "if" (pi(v_1, dots, v_n) "è un circuito in" G) \ & quad "return" 1; \ & "return 0"; $ Si vede chiaramente come sia simile a quello precedente, mostrando che la struttura di questi algoritmi e pressoché la stessa. == Tempo di calcolo Dato che è cambiato il modello di calcolo, dobbiamo rivedere la definizione di tempo di calcolo. Consideriamo il tempo di calcolo $T(x)$ per un'istanza $x$ a risposta positiva (negativa) come il miglior tempo di calcolo delle fasi di verifica a risposta positiva (negativa). Per convenzione, la fase congetturale non impiega tempo. Da ricordare che questo è un modello teorico, infatti nella realtà pagherò tempo anche per la generazione delle strutture che servono nelle verifiche. _Come formalizzare questo tipo di algoritmi?_ == Macchina di Turing Non Deterministica Consideriamo una DTM $M$ come l'abbiamo già descritta e apportiamo delle modifiche: - allunghiamo il nastro, in modo che sia infinito anche verso sinistra; - aggiungiamo un _Modulo Congetturale_, che scriva sulla parte sinistra del nastro la struttura generata; Quindi, il nastro conterrà sia l'input $x$ del problema, sia la struttura $gamma$ generata dalla fase congetturale e la fase di verifica non lavorerà più solo su $x$, ma utilizzerà la coppia $(gamma, x)$. Allora: - $x$ viene accettato $arrow.double.long.l.r exists gamma in Gamma^* : (gamma, x)$ viene deterministicamente accettata; - non viene accettato altrimenti. Il linguaggio accettato da $M$ è $ L_M = {x in Sigma^* : M "accetta" x}. $ Un linguaggio $L subset.eq Sigma^*$ è accettato da un algoritmo non deterministico se e solo se esiste una NDTM $M = (Q, Sigma, Gamma, delta, q_0, F)$ tale che $L = L_M$. Ricordiamo che, dato un problema $(Pi, x in D, p(x))$, il linguaggio riconosciuto dal problema è $ L_Pi = {cod(x) : x in D and p(x)} $ dove $cod : D arrow Sigma^*$ e la funzione di codifica delle istanze del problema. Un algoritmo non deterministico per la soluzione di $Pi$ è una NDTM $M$ tale che $ L_Pi = L_M. $ Ovviamente, mediante opportuna codifica, possiamo definire NDTM che accettano insiemi o funzioni. == Complessità in tempo Come abbiamo accennato precedentemente, la complessità in tempo di un algoritmo non deterministico corrisponde alla miglior complessità in tempo per quell'istanza. Allo stesso modo, possiamo definire la complessità in tempo per le NDTM. Una NDTM $M = (Q, Sigma, Gamma, delta, q_0, F)$ ha *complessità in tempo* $t : NN arrow NN$ se e solo se per ogni input $x in L_M$ con $|x| = n$ esiste almeno una computazione accettante di $M$ che impiega $t(n)$ passi. Un linguaggio è accettato con *complessità in tempo non deterministico $t(n)$* se e solo se esiste una NDTM $M$ con complessità in tempo $t(n)$ che lo accetta. In questo modo abbiamo mappato tutti i concetti chiave visti nelle macchine di Turing deterministiche anche per il non determinismo. == Classi di complessità non deterministiche È possibile definire delle classi per i linguaggi accettati allo stesso modo di come avevamo fatto per le DTM. Chiamiamo $ ntime(f(n)) $ l'insieme dei linguaggi accettati con complessità non deterministica $O(f(n))$. Caratterizziamo il concetto di "efficienza" anche per il non determinismo. Sappiamo che *efficiente risolubilità* si traduce nella classe $ P = union.big_(k gt.eq 0) dtime(n^k). $ Definiamo ora l'*efficiente verificabilità* come la classe $ "NP" = union.big_(k gt.eq 0) ntime(n^k), $ che corrisponde all'insieme dei problemi di decisione che ammettono algoritmi non deterministici polinomiali.
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/030%20-%20Amonkhet/004_Servants.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Servants", set_name: "Amonkhet", story_date: datetime(day: 19, month: 04, year: 2017), author: "<NAME>", doc ) #figure(image("004_Servants/01.png", width: 100%), caption: [], supplement: none, numbering: none) #emph[Spending her days served and waited upon by scores of devoted undead is precisely Liliana's idea of paradise, but she can't afford to sit idle on Amonkhet. She came to the plane to find—and kill—another of her demon creditors.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) There was something, Liliana reflected, about shade in the desert. It was always nice, of course, to be in a place where the climate was temperate and the breeze pleasantly cool without intervention. But lounging in a little island of soothing darkness, feeling the searing air all around you, caressed by breezes that never touched the still and sun-baked trees—there was something downright luxurious about that. She chewed a fig thoughtfully. Next to her, a white-wrapped undead servant held the plate of fruit on its head with perfect poise. Behind her, another one of these strange, servile mummies waved a large feathered fan, the source of the pleasant breeze that teased through her hair. She'd told several other mummies to wait in case she needed anything, and they knelt before her, still and sterile. She was accustomed to zombie servants, but these were unusually effective—not just meeting her needs, but anticipating them. #figure(image("004_Servants/02.jpg", width: 100%), caption: [Liliana, Death's Majesty | Art by <NAME>], supplement: none, numbering: none) She could get used to this place. Except. Except for the omnipresent reminders of <NAME>, who ruled it in absentia as some kind of God-Pharaoh. Except for the way everyone else here was obsessed with gods and trials and some glorious afterlife instead of enjoying the city's evident luxuries. Except for the fact that she wasn't actually using necromancy to command these zombies, so different from the ones she was used to, and didn't know what would happen if she tried. Except, in particular, for Razaketh. Two of the demons who had held the contracts on her soul were dead, killed in surprise attacks by the deadly power of the Chain Veil. Kothophed had sent her after the Veil, an evil relic of tremendous power, and then let her walk right up to him with it—proving that even a demon can be too stupid to live. Griselbrand was far more dangerous, but he'd been bound within a prison of magical silver. Liliana bullied a hapless local into blowing the thing up and shredded the demon while he was still disoriented. Razaketh would make three. But unlike the first two, she had no idea whether she could catch Razaketh by surprise—no idea where on the plane he was or whether he was aware of her presence. Razaketh was somewhere on this world, a world under the thrall of <NAME>. Bolas was the one who had brokered Liliana's contracts in the first place, and Liliana had no idea how he would view her efforts to break free of them on her own. Regardless of the outcome of the Gatewatch's full-frontal assault on an elder dragon, Liliana was damn well going to make sure they helped her kill Razaketh first. "Shouldn't you be looking for someone?" said a wispy, urbane voice behind her. Just what she needed. The Raven Man. A ghost of the past, figurative or literal, who always knew where she'd been and what she'd been doing. He might not be corporeal. He might even be an affliction of her own mind, a curse or a mental parasite. But he was real, had to be real. She refused to entertain the alternative. Whoever and whatever he was, he had haunted her intermittently since she was young. In the last few years, he'd grown downright chatty. "Don't you have anything better to do?" she asked, not turning around. Liliana's legs were dangling out into the warm sunlight, and she knew the Raven Man preferred to keep to the shadows. So he didn't face her from the front. But he did appear next to her in his archaic black clothing, leaning on one of the poles of her tent and regarding her with his flat golden eyes. "I'm concerned for you, Liliana. One of your demons is in reach, and time is running out." He gestured to the second sun, so close to its final resting place. "Yet here you sit. Eating fruit." "You're well aware that I haven't been idle." She hadn't dared deploy any of her own zombies, not without a deeper understanding of how bootleg necromancy would be greeted in a place where undead servitude was so ubiquitous and well regimented. She'd summoned up a few shades instead, incorporeal undead of darkness and death. She sent them flitting among the shadows between the great monuments, searching for signs of Razaketh. And no matter how long he'd been gone, the Raven Man always seemed to know what she'd been doing. "Ah yes," said the Raven Man. "You sent servants, rather than looking around yourself. No doubt motivated by a desire to remain inconspicuous. Certainly not by fear, I'm sure." "Your scorn is noted," said Liliana. "Now get lost." "I've been very patient. I left you alone during the months you spent on Ravnica, hanging around your clubhouse and do-gooding when it suited you. I stayed quiet during your little excursion to Kaladesh, too, even after it became a dangerous distraction. I trusted that you knew what you were doing. That you were strengthening the bonds of affection that would allow you to manipulate those fools into doing your bidding." "Affection #emph[is] manipulation," said Liliana. "It worked, didn't it?" "On whom?" said the Raven Man. "You and Jace have split a bottle and #emph[reminisced] about old times more than once. You're telling me that was just you getting your hooks back into him?" It had happened, a time or three, at her private residence on Ravnica after she joined the Gatewatch. Then Gideon had remarked acidly at some strategy meeting about being unable to find Jace in the early hours of the morning, and that had been the quiet, unremarked-upon end of the thing. "That," said Liliana, "is none of your damned business." "Don't let your #emph[affections] get the better of you," he said. "Here are your loyal fools, on the very doorstep of your enemies. Yet you do nothing. They're poking around indiscreetly, and you're sitting here risking everything we've worked for. Have you gone soft?" Liliana's vision darkened. "They've done more for me than you ever have, you worthless phantom." "How hurtful," said the Raven Man, with smirking affront. "Haven't I helped you along your path? Didn't I protect your mind back on Innistrad, when that hooded plaything of yours lost his? Didn't I take command of the Chain Veil to blast you out of that wurm's belly when you arrived here?" "Excuse me?" Now Liliana did look at him. She'd thought she was dead, sliding down that thing's gullet. She was fuzzy on how she'd gotten out. Taken command . . . Could he actually do that? Had he done it before? "I'm trying to help you," said the Raven Man, smiling. "Razaketh might not know you're here. The sooner you round up your minions and kill him, the better off you'll be. It's time to make use of your useful fools." A flash of blue caught Liliana's eye, moving toward her through the crowd. "Speaking of my minions," she said, smiling, "our favorite telepath is right over there. You might want to make yourself scarce." "Afraid he'll see me?" said the Raven Man. "Afraid of what he could do to you if he did?" said Liliana. The Raven Man's golden eyes narrowed. How gratifying. "Don't forget why you're here," he said, and vanished indignantly. Liliana leaned back, determined to appear relaxed when Jace arrived. She plucked a round, purple grape from the bowl next to her and bit off half of it, curling her bottom lip just so to keep the juice from running down her chin. It was a very fine grape, juicy and sweet. "There you are," said Jace, squinting in the sunlight even under his hood. Liliana had slipped out of her room in their borrowed quarters while Jace was still miserably nursing a mug of thick, bitter beer, eager to see the city on her own. She'd eventually settled in this little tent by the river, sent out her searchers, and ordered some food. She swallowed the grape, seeds and all of course—spitting was so undignified. "Hello, Jace," she said. "Brunch?" "It's past midday," he said. "It's a late brunch." He gritted his teeth. "That's . . . just . . . lunch." Adorable. "Suit yourself," she said. "More figs for me." Jace shrugged and reached for a fig, but recoiled when he saw what was holding up the plate. "I'd be more comfortable with food that hadn't been handled by corpses." "Jace, I'm surprised at you. I knew the others would be squeamish, but I'd have thought that you'd appreciate the convenience of uncomplaining undead servants. The wrappings are quite sanitary, you know." "Have you ever seen a society like this?" said Jace. "The dead taken away and mummified for servitude, zombies doing all the work?" "No," said Liliana. "Not like this. And the ones in the city are different from the ones outside, if you haven't noticed." "They're certainly tidier," he said. "But yes, I noticed. Out in the sands, one of those wurms rose all by itself. You were . . . down. And I'd have known if there were another necromancer around." Was that concern in his voice? "Those zombies hadn't been under anyone's control in a long time," she said. "If what you're saying about the wurm is true, then it's possible they were raised by some kind of ambient necromancy." "Ambient necromancy? Is there such a thing?" She shrugged. "It might just be what happens here," she said. "It's not a nice place." "What about the ones in here?" "They're . . . strange," she said. The fact was, the serving mummies in the city creeped her out. "Whatever magic raised them, it isn't like mine. And it keeps them under tight control. I've never seen anything like it." "If we knew more about it, we might have a better idea what was happening here." #figure(image("004_Servants/03.jpg", width: 100%), caption: [Those Who Serve | Art by <NAME>aga], supplement: none, numbering: none) Liliana felt the familiar chill of a shade drawing near, slithering across the shadowy sides of monuments and stretching from one tree's shadow to the next. Jace shivered and scanned the surrounding shadows. Smart boy. "It's mine," she said. He relaxed, but not completely. Smart, paranoid boy. The shade lingered some distance away, unable to comfortably reach Liliana's shelter. #emph[Come] , it whispered to her. #emph[F] #emph[ound] . Not exactly sterling conversationalists, shades. "Well," she said aloud. "Looks like I found something." She dismissed the serving mummies with a wave, gathered her skirts, and turned to Jace. "You're planning to follow me," she said. "Obviously." "And if I tell you not to follow me," she said, "you'll turn invisible and follow me anyway." Jace shrugged. "It crossed my mind." "So the only difference is whether I have to look at you along the way?" "Uh . . . I guess?" "Fine," said Liliana. "Come on then." She walked away, following the shade. Jace sighed and followed after her, muttering, "So does that mean you want to look at me, or . . . ?" She smiled and kept walking. They strolled along the sunlit thoroughfares, past fit young adults and eerily disciplined children. Shouts of exertion and the scent of clean sweat wafted from training grounds where hundreds of the city's "initiates" practiced combat. Such fine physiques! She couldn't help but imagine them dead and in her service, provided they died cleanly . . . #emph[Oh.] "Jace . . ." she said. "Have you noticed that all the mummies in the city are maimed?" "Hm?" he said. "I'd noticed that some are. Missing hands, that sort of thing. All of them? Really?" "Even the ones that aren't missing parts have had tendons severed or bones broken. I can tell from how they walk. Does everyone here die a violent death?" "Or," said Jace, "do they do something different with the ones that don't?" She frowned. "This place is weird," she said. "Really weird," he said. "And it seems like Gideon . . ." ". . . actually likes it here," he finished. "I know." They both made a noise of disgust. "So what are we looking for?" he asked. "#emph[I'm] looking for it," said Liliana, smiling. "You're following me. Anyway, it's a secret." "I hate secrets." "Knowing them, or not knowing them?" "They're trouble either way," he said. "Although not knowing is worse, obviously." #emph[Obviously.] He was still so innocent in some ways. She sighed. "Promise you won't be mad?" "No." "Promise you won't tell Gideon?" "Uh, extra no." "Then you figure it out, cloak boy." He walked next to her, thinking. "You're trying to find <NAME>," he said. "I'd just as soon not." "You're going to #emph[betray] us to <NAME>." "Tempting, but no." "You're . . . looking for something you left behind when you were here before." She smiled. "Mmm," she said. "Interesting guess. Vague, though." The shade flowed to a stop in the shadows along one wall of a building. The wall was covered in inscriptions. The local script, some symbols she didn't recognize—and some she did. #emph[Razaketh.] The inscription swam in her vision, and whispers pawed at the edges of her awareness. She swayed, catching herself on the wall of the building. The heat. Must be the heat. Jace didn't reach out to steady her, but he saw her waver. "You all right?" he said. "I'm always all right." He shot her a look. "In the long run," she said. The shade led them around to the entrance. Its substance was starting to unravel, too long exposed to the desert suns. She dismissed it with a wave. The place didn't look open to the public. It didn't have a lock, or even a door, but from what she'd seen that was typical of the city. They walked down a stone ramp, into a long corridor lit by intermittent torches. There were carvings on the walls, depicting initiates battling each other in earnest, some of them lying dead on the ground. There was a shuffling movement behind them, footfalls coming down the ramp. They spun. Nowhere to hide. Hopefully they weren't trespassing. The blank face of a serving mummy came into view, carrying a pile of rags in its arms. Jace and Liliana found an alcove and ducked into it, but the mummy took no notice of them at all. Behind it came another, then another, some dragging their loads, others working in pairs to carry heavier things. No. Not things. The mummies carried the bodies of initiates slain in combat, dripping blood, wrapped in rags. Some were missing pieces. They were freshly dead, going by the smell. An hour or two at most. Next to her, Jace gagged. Once the mummies had passed, she stepped back out into the corridor. "Watch your step," she said. "It's slippery now." "We shouldn't be in here," he said. "Why did we come here? What are you looking for?" "You said yourself that if we understood these mummies, we might learn something about what's going on here." It was all true, as far as that went. But what did any of that have to do with Razaketh? They followed the mummies down the corridor. The carvings around them changed, depicting mummies carrying away dead initiates, then embalming them on slabs, creating more mummies. They entered a large, well-lit central chamber and saw the reality of the carvings. The place was a bustle of activity, the bodies laid out on stone slabs next to tables lined with implements and canopic jars. The smell in here was different, the stench of death mixed with the stale stink of preservatives. #figure(image("004_Servants/04.jpg", width: 100%), caption: [Anointer Priest (Embalmed) | Art by Lake Hurwitz], supplement: none, numbering: none) The mummies worked in perfect silence, broken only by the shuffle of bandaged feet and the occasional snap, grind, or squelch of the bodies being prepared. So much effort! It was like the mummification she'd read about on other planes, but on an industrial scale. Mummies removed most of the initiates' organs, but here they were placed in large communal jars without decoration. The bodies were mounted on racks for the wrapping process, as efficient as a loom. Not a religious rite. Purely practical. Jace spoke within her mind: #emph[This is what they do with all the dead initiates.] She didn't appreciate the intrusion, and the mummies, for their part, seemed wholly uninterested in the living, going about their gruesome work with deliberate efficiency. Why would so many die in training? She nudged him and gestured to the far side of the room, where the wall bore some kind of elaborate mural. He nodded, and the two of them crept around the edge of the room. One of the dead bodies began to stir, #emph[before] it was fully wrapped. It thrashed and shuddered, and the wrapping process clattered to a halt. It was the first thing they'd seen that wasn't efficient and orderly, and they paused to watch. There was no necromancer besides herself, essentially no #emph[necromancy] —just an upwelling of death magic that seemed to come from everywhere. The mummies overseeing the wrapping process approached the rogue corpse and held it down, while another approached with a large metal plate—a cartouche. They pressed the cartouche into place on the body's chest. The thrashing corpse fell still. Liliana and Jace exchanged a look. They kept moving around the room, as the embalming mummies placed more cartouches on the embalmed bodies. Some began to stir before the cartouches were in place. Others lay still for some time after. Liliana and Jace stopped in front of a mural carved in dark stone that covered the entire far wall of the chamber. They studied the mural, while the grim work behind them continued. It was a depiction of the afterlife, with iconography that had become familiar from inscriptions around the city. There was the second sun resting between the horns on the horizon, and the enormous gate that (the locals said) barred the way to the afterlife. In this inscription the gate was open, the afterlife beyond it tantalizingly visible—but guarded by a monstrous demon. Razaketh. #emph[The final test,] read the inscription. #emph[The last inglorious death, culling the unworthy who remain.] Razaketh's hands were covered in blood, a pile of corpses at his feet. Blood ran into the water of the river. #emph[Beyond the gate, Razaketh. Beyond Razaketh, paradise.] The carving of Razaketh made Liliana uneasy. Like it was looking back at her. #figure(image("004_Servants/05.jpg", width: 100%), caption: [Trespasser's Curse | Art by <NAME>], supplement: none, numbering: none) "You're down here looking for one of your damned demons?" hissed Jace. "Two down," said Liliana, a lump in her throat. The carving seemed to loom over her. "He's next." "You should have told us!" said Jace. "We would have helped you!" "You knew about my demons going into this," Liliana shot back. "#emph[You're] willing to fight them. Do you really think Gideon would have come if I'd told you all? Or Nissa?" "I don't know," snapped Jace. "I would have backed you up. But now, since you lied about it, I don't think—" "I didn't lie about anything," said Liliana. Her head was pounding. "You didn't tell the truth," said Jace. "You broke our trust." "I never asked you to trust me." Jace said something in reply, something angry, but she couldn't understand it. Her ears were ringing, and her vision swam. The Chain Veil grew warm in her pocket. Protecting her. The carving of Razaketh . . . opened its eyes. They were red, blood red, the only thing she could see. The sounds behind them stopped, and a dozen ruined throats whispered: "Liliana." #emph[No no no no no] The mummies were staring at her, their work suspended. The products of their efforts stood beside them, a few of them half-unwrapped with cartouches hastily attached. Now she heard her name whispered all around her, from the walls themselves. #emph[Are you doing this?] Jace's voice spoke inside her head. She shook her head helplessly. "Liliana . . ." they whispered. The mummies lunged forward. They were all around, a tangle of bandaged flesh and grasping hands. And still silent, utterly silent—a quiet fight, just the occasional grunt and the whisper of silk wrappings. Jace was casting next to her, pulling the mummies away one at a time with illusory rope. But it was such a small space, and so many bodies. Liliana's head cleared. She reached out, the way she had in the desert, to control them. They were just bodies, no different from any others. Nothing happened. Ambient magic. In a flash, she understood it all. There was something on this world—natural or artificial, it hardly mattered—that raised the dead. #emph[All] the dead, inside the city and out. Those who created and commanded the serving mummies didn't need necromancy at all, only a means of control. And that control was direct, physical—far harder to overcome than the whims of a lesser necromancer. "I can't control them," she said. "The cartouches—" She grabbed the nearest mummy, dug her fingers around the edges of the cartouche, and wrenched it as hard as she could. Jace saw what she was doing and gave her the assist, grabbing the mummy around the neck and pulling it away from her. With a fleshy #emph[snap] , the cartouche came loose. Then there was a #emph[pop] , and a sizzle. The hole left by the cartouche burned with blinding white light, and the mummy fell apart. #emph[Well, damn.] Then the mummies were all around them, too many, grasping them by limbs and throats. She reached for the Chain Veil. She'd been desperately avoiding it, but if that was what it took to survive . . . The mummies froze, holding them in place. Then some of them shuffled aside, parting to let someone through. "You really are outsiders," he said. Temmet. #figure(image("004_Servants/06.jpg", width: 100%), caption: [Temmet, Vizier of Naktamun | Art by <NAME>], supplement: none, numbering: none) Liliana had taken an immediate disliking to the arrogant young vizier who'd graciously granted them housing in the city. Too poised, too self-assured. She'd even wondered, initially, if he might be older than he looked—much older, like she was. But no. He was a teenager. Like everyone else here, he'd been honed to a sharp edge at a very young age. Now that edge was turned on them, with enough force that Liliana couldn't quite dismiss him as a child playing at authority. "I didn't believe it at first. Whoever heard of such a thing?" He came closer, examining them. #emph[Keep him talking] , said Jace in her mind. #emph[He's got some kind of protection. I need a minute.] "But I checked the birth records at the Monument of Knowledge," Temmet went on. "Kefnet knows all, but his viziers do not know you. And now you're down here, snooping around the sacred embalming chambers. You're truly ignorant of our ways. You know nothing of the Horned One—may his return come quickly, and may we be found—" "We've met him, actually," said Liliana. Jace and Temmet looked equally shocked. "Silence!" said Temmet. "And just so you know, he's a complete a—" Mummified hands tightened around her throat, cutting her off. "LIES!" screamed Temmet, red-faced. Then Temmet's eyes glowed blue and his face went slack. A moment later, the mummies' hands released their grip. Jace grabbed her arm. His eyes were glowing too, blue light leaking out around the edges, and his face was contorted. "Run," he gasped. "What—" "Can't . . ." said Jace. ". . . much . . . longer . . ." #emph[Oh.] Jace was controlling Temmet, and Temmet was controlling the mummies, and that had to be taking a toll on the dear boy's mind. Not all of the mummies were still. There were too many, probably. Jace barely had control. Liliana shouldered the nearest mummy aside and ran, away from the carving's red eyes and the embalming chamber and the stink of death and stillness. She ran. Outside. Blinding suns. Her heart was pounding. Jace's eyes cleared. Liliana glanced backward, but didn't see any pursuit. Not yet. "That . . ." wheezed Jace, ". . . was your idea to keep him talking? Blasphemy?" "It was funny," she said. For a moment, they just breathed and ran. "What . . . happened back there?" he asked. "Razaketh," she replied. "The demon. I think . . . he's involved with this afterlife. And he knows . . . I'm here. Chain Veil's the only reason he can't . . . activate my contract." "Great," said Jace. "You wiped Temmet's mind, at least?" Jace grimaced. "No," he said. "It was all I could do . . . to keep the mummies off us. He'll be out for a while, and he'll wake up with a hell . . . of a headache. But he'll remember." "Then we have to find the others," said Liliana. #emph[It's time to make use of your useful fools] , the Raven Man had said. Whether they were friends or fools, Liliana needed them. She ran, away from her demon, toward help.
https://github.com/Rhinemann/mage-hack
https://raw.githubusercontent.com/Rhinemann/mage-hack/main/src/chapters/Outline.typ
typst
#import "../templates/interior_template.typ": * #show: chapter.with(chapter_name: "Table of Contents") #set text(size: 10pt) #show outline.entry.where(level: 1): it => { set text(size: 14pt) v(10pt, weak: true) strong(it) } #show outline.entry.where(level: 2): it => { set text(size: 12pt) show strong: set text(fill: luma(0%)) strong(it) } = Table of Contents #show: columns.with(2, gutter: 1em) #outline(indent: 1em, title: none, fill: none)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/dict-00.typ
typst
Other
// Ref: true // Empty #(:) // Two pairs and string key. #let dict = (normal: 1, "spacy key": 2) #dict #test(dict.normal, 1) #test(dict.at("spacy key"), 2)
https://github.com/mcarifio/explore.typst
https://raw.githubusercontent.com/mcarifio/explore.typst/main/src/first.typ
typst
// #import "first.tym" #import "author.tym" #let me = (first: "Mike", last: "Carifio", email: "<EMAIL>", tel: "+1-978-377-8680") #author.dump(me) = Start Here First sentence from #author.name(me) reached at #author.contact(me).
https://github.com/Clamentos/FabRISC
https://raw.githubusercontent.com/Clamentos/FabRISC/main/src/spec/Section1.typ
typst
Creative Commons Attribution Share Alike 4.0 International
/// #import "Macros.typ": * /// #section( [Introduction], [This is the official document for the FabRISC instruction set architecture. This writing is intended to introduce and explain concepts, features and capabilities of the specification.], [FabRISC is a feature rich, register-register, classically virtualizable, load-store architecture with variable length encodings of 2, 4 and 6 bytes. This specification is designed to be highly modular allowing the realization of various different microarchitectures ranging from simple 8 and 16 bit widths, all the way to advanced 32 and 64 bit high performance multithreaded systems. The ISA includes scalar, vector, floating-point, compressed as well as atomic memory instructions. The complete specification also supports privileges, system related instructions, interrupts, exceptions, faults and more, helping with the implementation of various kinds of operating systems with or without memory management needs. The ISA can be further expanded and enriched by allocating unused encoding space to custom application specific instructions, increasing both performance and code density.], [FabRISC is completely free, open-source and available to anyone interested in the project via the official GitHub page: #monospace(link("https://github.com/Clamentos/FabRISC")) (license details can be found at the very end of this writing as well as in the linked repository). The document is divided into multiple sections each explaining a particular aspect of the architecture in detail with the help of tables, figures and suggestions in order to aid the hardware and software designers in creating an efficient implementation of the FabRISC ISA.], comment([ Commentary in this document will formatted in this way and communication will be more colloquial. If the reader is only interested in the specification, these sections can be skipped without hindering the understanding too much. This project tries to be more of a hobby learning experience rather than a new super serious industry standard, plus the architecture borrows many existing concepts from the most popular and iconic ISAs like: x86, RISC-V, MIPS, ARM and OpenRISC. Don't expect this project to be as good or polished as the commercial ones, however, i wanted to design something that goes beyond simple toy architectures used for teaching and demonstrations. I chose to target FPGAs as the primary platform for two main reasons: firstly is that ASICs are out of the question for the vast majority of people because of cost, time and required expertise. Secondly is that using discrete components, all though fun and interesting, makes little sense from a sanity, practicality and scalability points of view given the complexity of this project. Software simulators, such as Logisim-evolution #monospace(link("https://github.com/logisim-evolution/logisim-evolution")) or Digital #monospace(link("https://github.com/hneemann/Digital")) can be good alternative platforms for simpler implementations without having to spend a dime. The core ideas here are the use of variable length encodings of 4 and 6 byte instruction sizes along with shorter "compressed" ones to increase code density. The goal behind these is to use the long 6 byte format for instructions containing larger immediate values, while the 2 and 4 byte formats for instructions with smaller ones or registers only. The trade off of this is increased ISA capabilities and code density at the expense of misalignment and variable length encodings which can complicate the hardware implementation a bit. This ISA, all though not a "pure" RISC design with simple fixed length instructions and few addressing modes, resembles that philosophy for the most part skewing away from it in some areas, such as, being able to load, store, move and swap multiple registers with a single instruction, more complex addressing modes, floating point transcendental operations and variable length encodings. I chose the name "FabRISC" because i wanted to encapsulate the main characteristics and target device of this instruction set. The pronunciation should vaguely remind of the word "fabric" which is a reference on the fact that the main component of an FPGA is the "LUT fabric", that is, a network of many interconnected logic cells. ]), ///. subSection( [Terminology], [The FabRISC architecture uses the following terminology throughout the document in order to more accurately define technical concepts and vocabulary:], tableWrapper([Technical term list.], table( columns: (auto, auto), align: left + horizon, [#middle([*Term*])], [#middle([*Description*])], [Abort, \ Transaction Abort], [Are used to refer to the act of abruptly stopping an ongoing memory transaction as well as invalidating, rolling back or undoing all of its changes. The first term is also used to broadly refer to the act of abruptly terminating an ongoing set of operations.], [Architecture], [Is used to refer to the set of abstractions and contracts that the hardware exposes to the software.], [Atomic], [Is used to refer to any operation that must, either be completely executed, or not at all.], [Architectural State], [Is used to refer to the state of the processor, a single core or hardware thread that can be directly observed by the programmer.], [Coherence], [Is used to refer to the ability of a system to be coherent, that is, ensuring the uniformity of shared resources across the entire system. In particular, it ensures that the order of accesses to a single memory location is observed by all of the participating actors.], [Consistency], [Is used to refer to the ability of a system to be consistent, that is, ensuring a particular order of operations across all memory locations that is observed by all of the participating actors.], [Consistency Model], [Is used to refer to a particular consistency model or protocol implemented by a system.], [Core], [Is used to refer to a fully functional and complete sub-processor within a bigger entity. Advanced processors often aggregate multiple similar copies of themselves, in order to be able to schedule different programs each working on it's own stream of data. It is important to note that each core can have a completely different microarchitecture, as well as instruction set.], [Demotion], [Is used to refer to the transition from a higher privilege mode to a lower privilege one.], [Event], [Is used to generically refer to any extraordinary situation that needs to be taken care of as soon as possible, potentially interrupting and redirecting the current flow of execution.], [Exception], [Is used to refer to any non severe internal, deterministic event.], [Fault], [Is used to refer to any severe internal, deterministic event.], [Hardware Thread, \ Hart, \ Logical Core], [Are used to refer to a particular physical instance of a software thread running on the processor.], [Instruction Set Architecture, \ ISA], [Are used to refer to the architecture that a particular processor exposes to the software under the form of instructions, registers and other resources.], [Interrupt], [Is used to refer to any external, non-deterministic event.], [Macro Operation, \ Macro-Op, \ Instruction], [Are used to refer to an idiomatic assembly machine command that a particular ISA defines.], [Memory Fence, \ Fence], [Are used to refer to particular instructions that have the ability to enforce a specific execution order of memory instructions.], [Memory Transaction, \ Transaction], [Are used to refer to a particular series of operations that behave atomically within the system.], [Micro Operation, \ Micro-Op], [Are used to refer to a partially or fully decoded instruction.], [Microarchitectural State], [Is used to refer to the complete state of the processor, a single core or hardware thread, that might not be visible by the programmer in its entirety. The microarchitectural state can be seen as a superset of the architectural state.], [Microarchitecture], [Is used to refer to a particular physical implementation or realization of a given architecture.], [Page], [Is used to refer to a logical partition of the main system memory.], [Promotion], [Is used to refer to the transition from a lower privilege mode to a higher privilege one.], [Transparent], [Is used to refer to something that is, mostly, invisible to the programmer and handled automatically by the underlying hardware.], [Trap], [Is used to refer to the transition from a state of normal execution to the launch of an event handler after receiving an event.], [Unaligned, \ Misaligned], [Are used to refer to any memory item that is not naturally aligned, that is, the address of the item modulo its size, is not equal to zero.] // MMIO // DMA // privilege / privilege level )) ) ) #pagebreak() ///
https://github.com/Mouwrice/resume
https://raw.githubusercontent.com/Mouwrice/resume/main/modules/education.typ
typst
#import "../brilliant-CV/template.typ": * #cvSection("Education") #cvEntry( title: [Master of Science in Computer Science Engineering], society: [Ghent University], date: [2022 - 2024], location: [Ghent, Belgium], logo: "../src/logos/ugent.png", description: list( [Thesis: Air Drumming: Applied on-device body pose estimation], [Courses: Data Quality #hBar() Big Data Technology #hBar() NoSQL Databases #hBar() Cloud Storage and Computing #hBar() Discrete Algorithms #hBar() Computer Graphics #hBar() Fundamentals of Musical Acoustics and Sonology] ) ) #cvEntry( title: [Bachelor of Science in Computer Science (cum laude)], society: [Ghent University], date: [2019 - 2022], location: [Ghent, Belgium], logo: "../src/logos/ugent.png", description: list( [Minor: Electrotechnique & telecommunications], ) ) #cvEntry( title: [General Secondary Education: Latin-Maths], society: [College Petrus & Paulus], date: [2013 - 2019], location: [Ostend, Belgium], logo: "../src/logos/college.png", description: none, )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/delimited_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test unmatched. $[1,2[ = [1,2) != zeta\(x/2\) $
https://github.com/mem-courses/calculus
https://raw.githubusercontent.com/mem-courses/calculus/main/homework-1/calculus-homework13.typ
typst
#import "../template.typ": * #show: project.with( title: "Calculus Homework #13", authors: (( name: "<NAME> (#47)", email: "<EMAIL>", phone: "3230104585" ),), date: "December 21, 2023", ) #let int = math.integral = P228 习题5-1 1(2) #ac #prob[ 利用定义求下列函数的定积分: $ int_a^b (dx)/(x^2) sp (0<a<b) $ (提示:把区间 $n$ 等分,取 $xi_i=sqrt(x_i x_(i-1))$.) ] 对于 $n->oo$,取 $x_i=a+display(i/n (b-a))$,有 $Delta x_i = display(1/n (b-a))$. $ int_a^b (dx)/(x^2) &= lim_(n->oo) 1/n (b-a) sum_(i=1)^n 1/(sqrt(x_i dot x_(i-1)))^2\ &= lim_(n->oo) 1/n (b-a) sum_(i=1)^n 1/(x_i dot x_(i-1))\ &= lim_(n->oo) 1/n (b-a) sum_(i=1)^n 1/(x_i - x_(i-1)) (1/(x_(i-1)) - 1/(x_i))\ &= lim_(n->oo) sum_(i=1)^n (1/(x_(i-1)) - 1/(x_i))\ &= 1/a - 1/b $ = P228 习题5-1 2(2) #ac #prob[ 把极限用定积分形式表示: $ lim_(n->oo) (n/(n^2+1^2) + n/(n^2+2^2) + dots.c + n/(n^2 + n^2)) $ ] $ "原式" &= lim_(n->oo) 1/n sum_(i=1)^n (n^2)/(n^2+i^2)\ &= lim_(n->oo) 1/n sum_(i=1)^n (1)/(1+(i/n)^2)\ &= int_0^1 (dx)/(1+x^2) $ = P228 习题5-1 2(4) #ac #prob[ 把极限用定积分形式表示: $ lim_(n->oo) 1/n (sin pi/n + sin (2pi)/n + dots.c + sin (n-1)/n pi) $ ] $ "原式" = lim_(n->oo) 1/n sum_(i=0)^(n-1) sin(i/n dot pi) = int_0^1 sin (x pi) dx $ = P236 习题5-2 1(2) #prob[ 利用定积分的性质,比较 $display(int_1^2 x^2 dx)$ 与 $display(int_1^2 x^3 dx)$ 的大小: ] $ int_1^2 x^2 dx - int_1^2 x^3 dx = int_1^2 x^2 (1-x) dx $ 对于函数 $psi(x) = x^2 (1-x)$,在 $[1,2]$ 上有 $psi(x) <= 0$,故 $display(int_1^2 psi(x) dx) < 0$,所以 $ int_1^2 x^2 dx < int_1^2 x^3 dx $ = P236 习题5-2 1(3) #prob[ 利用定积分的性质,比较 $display(int_1^2 ln x dx)$ 与 $display(int_1^2 (ln x)^2 dx)$ 的大小: ] $ int_1^2 ln x dx - int_1^2 (ln x)^2 dx = int_1^2 ln x (1- ln x) dx $ 对于函数 $psi(x) = (ln x )(1 - ln x)$,在 $[1,2]$ 上有 $psi(x) >= 0$,故 $display(int_1^2 psi(x) dx) > 0$,所以 $ int_1^2 ln x dx > int_1^2 (ln x)^2 dx $ = P236 习题5-2 3(1) #prob[ 利用定积分的性质证明: $ (4 pi)/3 <= int_0^(2pi) (dx)/(1+0.5cos x) <= 4pi $ ] $ forall x in [0,2pi],sp -1<=cos x<=1 => 2/3 = 1/(1+0.5) <= 1/(1+0.5 cos x) <= 1/(1-0.5) = 2 $ 故 $ int_0^(2pi) (dx)/(1+0.5cos x) <= int_0^(2 pi) 2 dx = 4pi\ int_0^(2pi) (dx)/(1+0.5cos x) >= int_0^(2 pi) 2/3 dx = (4pi)/3\ $ 原不等式得证. = P236 习题5-2 3(2) #prob[ 利用定积分的性质证明: $ 1/(10 sqrt(2)) <= int_0^1 (x^9)/sqrt(1+x) dx <= 1/10 $ ] $ forall x in [0,1],sp 1<=sqrt(1+x)<=2 => x^9/sqrt(2) <= x^9/sqrt(1+x) <= x^9 $ 故 $ int_0^1 (x^9)/sqrt(1+x) dx <= int_0^1 x^9 dx = 10\ int_0^1 (x^9)/sqrt(1+x) dx >= int_0^1 x^9/sqrt(2) dx = 10/sqrt(2)\ $ 原不等式得证. = P236 习题5-2 5(1) #ac #prob[ 设函数 $f(x)$ 及 $g(x)$ 在 $[a,b]$ 上连续,证明: $ (int_a^b f(x) g(x) dx)^2 <= int_a^b f^2 (x) dx dot int_a^b g^2 (x) dx $ ] 设变限积分 $ F(x) &= (int_a^x f(t) g(t) dt)^2 - (int_a^x f^2(t) dt) (int_a^x g^2(t) dt) quad (a<=x<=b)\ => F'(x) &= 2 f(x) g(x) (int_a^x f(t) g(t) dt) - f^2(x) (int_a^x f^2(t) dt) - g^2(x) (int_a^x g^2(t) dt)\ &= int_a^x (f(t) f(x) (g(t) g(x) - f(t) f(x)) + g(t) g(x) (f(t) f(x) - g(t) g(x))) dt\ &= - int_a^x (f(t) f(x) - g(t) g(x))^2 dt <= 0 $ 故 $forall x in [a,b],sp F(x) <= F(a) = 0$.代入 $x=b$ 得 $F(b) <= 0$,即不等式成立. = P236 习题5-2 5(2) #prob[ 设函数 $f(x)$ 及 $g(x)$ 在 $[a,b]$ 上连续,证明: $ int_a^b (f(x) + g(x))^2 dx <= ((int_a^b f^2 (x) dx)^(1/2) + (int_a^b g^2 (x) dx)^(1/2))^2 $ ] $ int_a^b (f(x) + g(x))^2 dx <= ((int_a^b f^2 (x) dx)^(1/2) + (int_a^b g^2 (x) dx)^(1/2))^2\ <=>\ int_a^b f^2(x) dx + 2 int_a^b f(x) g(x) dx + int_a^b g^2(x) dx \ <= int_a^b f^2(x) dx + 2 sqrt((int_a^b f(x) dx) (int_a^b g(x) dx)) int_a^b g^2(x) dx\ <=>\ (int_a^b f(x) g(x) dx)^2 <= (int_a^b f(x) dx) (int_a^b g(x) dx) $ 而该不等式已在习题 5-2 第 5(1) 题中证明,故原不等式得证. = P237 习题5-2 6 #prob[ 设函数 $f(x)$ 在 $[a,b]$ 上连续,可微且 $f(a) = 0$,证明: $ M^2 <= (b-a) int_a^b f'^2 (x) dx $ 其中 $M = display(sup_(a<=x<=b) abs(f(x)))$. ] $ (int_a^b f'(x) dx)^2 <= (b-a) int_a^b f'^2 (x) dx <=> (int_a^b f'(x) dot 1 dx) <= (int_a^b f'^2 (x) dx) (int_a^b 1 dx) $ 由柯西不等式知成立.进一步地,设 $M$ 在 $x=t$ 时取到,则有: $ M^2 <= (t-a) int_a^t f'^2(x) dx $ 而 $b-a>=t-a$,$f'^2(x) >= 0 => display(int_a^b f'^2(x) dx >= int_a^t f'^2(x) dx)$,故 $ M^2 <= (b-a) int_a^b f'^2(x) dx $ 即原不等式得证. = P237 习题5-2 9 #prob[ 设函数 $f(x)$ 在 $[0, +oo)$ 上连续,单调递增且 $f(0) = 0$,试证函数 $ F(x) = cases( display(1/x int_0^x t^n f(t) dt\, quad& x>0 sp ("其中 " n>0)), display(0\,quad& x = 0), ) $ 在 $[0,+oo)$ 上连续递增. ] 当 $x>0$ 时,有 $ F'(x) &= ((x^n f(x)) x - int_0^x t^n f(t) dt)/(x^2) = (x^(n+1) f(x) - f(x) int_0^x t^n dt)/(x^2)\ &= n/(n+1) x^(n-1)f(x) > 0 $ 故 $F(x)$ 在 $[0,+oo)$ 上连续递增. = P237 习题5-2 10(2) #prob[ 证明: $ lim_(n->oo) int_n^(n+p) (sin^2 x)/x dx = 0 $ ] $ 0 = lim_(n->oo) int_n^(n+p) 0/x dx <= lim_(n->oo) int_n^(n+p) (sin^2 x)/x dx <= lim_(n->oo) int_n^(n+p) 1/x dx $ $ lim_(n->oo) int_n^(n+p) 1/x dx = lim_(n->oo) ln(abs(n+p)) - ln(abs(n)) = lim_(n->oo) ln(abs((n+p)/n)) = 0 $ 由夹逼定理知,原极限为零,原命题得证. = P237 习题5-2 11(2) #prob[ 求导数: $ dif/dx int_(sin x)^(cos x) cos(pi t^2) dt $ ] $ "原式" &= - cos(pi cos^2 x) sin x - cos(pi sin^2 x) cos x $ = P237 习题5-2 11(3) #prob[ 求导数: $ dif/dx int_(-x^2)^0 f(t^2) dt $ ] $ "原式" = - dif(-x^2)/dx f(x^4) = 2x f(x^4) $ = P237 习题5-2 12(1) #prob[ 求极限: $ lim_(x->0) display(int_0^x cos t^2 dt)/x $ ] $ F'(x) = dif/dx (display(int_0^x cos t^2 dt))/x = cos x^2\ => lim_(x->0) display(int_0^x cos t^2 dt)/x = lim_(x->0) (display(int_0^x cos t^2 dt) - 0)/(x-0) = F'(0) = 1 $ = P237 习题5-2 12(3) #prob[ 求极限: $ lim_(x->0) display(int_0^x t e^t sin t dt)/(x^3 e^x) $ ] $ lim_(x->0) display(int_0^x t e^t sin t dt)/(x^3 e^x) &= lim_(x->0) display(dif/dx int_0^x t e^t sin t dt)/(e^x (x^3 + 3x^2)) = lim_(x->0) (x e^x sin x)/(e^x (x^3 + 3x^2))\ &= lim_(x->0) (sin x)/(x^2 + 3 x) = lim_(x->0) x/(x^2 + 3 x) = lim_(x->0) 1/(x + 3) = 1/3 $ = P237 习题5-2 13 #prob[ 设 $f(x)$ 是连续函数,且 $f(x) = x + 2 display(int_0^1 f(x) dx)$,求 $f(x)$. ] $ f(x) = x + 2 int_0^1 f(x) dx => f'(x) = 1 => f(x) = x + c $ 其中 $c$ 是常数,代入可得: $ x + c = x + 2 int_0^1 (x+c) dx => c/2 = 1/2 + c => c = -1 $ 故 $f(x) = x - 1$. = P237 习题5-2 14 #wa #prob[ 设 $f(x)$ 在 $[a,b]$ 上有连续的倒数,且 $f(a) = f(b) = 0$.证明: $ max_(a <= x <= b) |f'(x)| >= 4/((b-a)^2) int_a^b |f(x)| dx $ ] 不会做. = 其他题目 见扫描件. == P238 习题5-2 16(5) == P238 习题5-3 1
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/root_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test precomposed vs constructed roots. // 3 and 4 are precomposed. $sqrt(x)$ $root(2, x)$ $root(3, x)$ $root(4, x)$ $root(5, x)$
https://github.com/antran22/typst-cv-builder
https://raw.githubusercontent.com/antran22/typst-cv-builder/main/README.md
markdown
MIT License
# Typst based CV Builder ## Use case - You have a lot of experiences, projects that can be showcased in CVs. - However, you can only include some of those in one CV to be sent to an employer. - You need a way to centrally manage all your informations, but also quickly pick out some entries to construct into a CV. - You don't really care that much about aesthetic. After all, a minimal looking CV is still a good CV. ## Dependencies - [Typst](https://github.com/typst/typst?tab=readme-ov-file#installation) - [Go Task](https://taskfile.dev/installation/) ## Workflow - You add experience, project, skills entries into `data` - Each entry must have an ID. - Some entry type have a `description` or `summary` that is going to be rendered as Markdown. - Each entry can inherit from another entry of the same type. Use this feature how you can (personally, I can have `project1` as the base information, then `project1-frontend` that showcase my frontend skill better) - To create a new CV, copy 'data/default-config.yml' into a new file in `resumes/`. Name it accordingly, for example 'Google-SRE' or 'Netflix-DevOps'. - Configure your new CV. - Select entries ID that you want to keep in each section. For example: ```yaml experiences: - exp-1 - exp-2 ``` or keep the field as `experiences: all` to include every entries. - Reorder your sections the way you see fit. To develop your CV live: run `task watch-resume Name=$(YAML_FILE_NAME_WITHOUT_EXTENSION)`. The file will be produced in `/output` To build a final CV: run `task build-resume Name=$(YAML_FILE_NAME_WITHOUT_EXTENSION)`. The file will also be produced in /output For example: ```bash git clone https://github.com/antran22/typst-cv-builder.git cd typst-cv-builder cp data/default-config.yml resumes/Google-SRE.yml task watch-resume Name=Google-SRE # watch changes in the CV file and rebuild PDF. vim resumes/Google-SRE.yml # edit your CV # while editing the yml file, open output/Google-SRE-DEV.pdf to see the live change task build-resume Name=Google-SRE # build CV file into output/Google-SRE-$(CURRENT_DATE).pdf. You can send it to your employer now, or keep it somewhere else. ```
https://github.com/C0ffeeCode/typst-dhbw-technik-template
https://raw.githubusercontent.com/C0ffeeCode/typst-dhbw-technik-template/template/thesis.typ
typst
#import "template.typ" : * #show: thesis.with( title: "Creating a Typst template", author: "<NAME>", type: "TX000", student_id: "change-me", course: "TINF2XA", date: datetime( year: 1984, month: 10, day: 10, ), time_period: "01.01.2023 - 00.00.2024", confidentiality_clause: true, language: "en", supervisor: "Someone", signature: none, // TODO ) // NOTE: https://www.dhbw.de/fileadmin/user_upload/Dokumente/Dokumente_fuer_Studierende/191212_Leitlinien_Praxismodule_Studien_Bachelorarbeiten.pdf // Requirements: // - 25-35 pages without directories und attachments // incl. graphics and tables // - must document: task, process of implementation, solutions and results = Introduction #include "./chapters/01-Introduction.typ" #pagebreak() = Technical Background == Spell checking You can use #link("https://github.com/crate-ci/typos")[Typos], but I am too lazy to explain. = Summary and Conclusion #lorem(250)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/chronos/0.1.0/src/note.typ
typst
Apache License 2.0
#import "@preview/cetz:0.2.2": draw #import "consts.typ": * #let SIDES = ( "left", "right", "over", "across" ) #let SHAPES = ( "default", "rect", "hex" ) #let _note(side, content, pos: none, color: COL-NOTE, shape: "default", aligned: false) = { if side == "over" { if pos == none { panic("Pos cannot be none with side 'over'") } } if aligned { if side != "over" { panic("Aligned notes can only be over a participant (got side '" + side + "')") } } return (( type: "note", side: side, content: content, pos: pos, color: color, shape: shape, aligned: aligned, aligned-with: none ),) } #let get-note-box(note) = { let PAD = if note.shape == "hex" {NOTE-HEX-PAD} else {NOTE-PAD} let inset = ( left: PAD.last() * 1pt, right: PAD.last() * 1pt, top: PAD.first() * 1pt, bottom: PAD.first() * 1pt, ) if note.shape == "default" { inset.right += NOTE-CORNER-SIZE * 1pt } if note.side == "left" { inset.right += NOTE-GAP * 1pt } else if note.side == "right" { inset.left += NOTE-GAP * 1pt } return box(note.content, inset: inset) } #let get-size(note) = { let PAD = if note.shape == "hex" {NOTE-HEX-PAD} else {NOTE-PAD} let m = measure(box(note.content)) let w = m.width / 1pt + PAD.last() * 2 let h = m.height / 1pt + PAD.first() * 2 if note.shape == "default" { w += NOTE-CORNER-SIZE } return ( width: w, height: h ) } #let _get-base-x(pars-i, x-pos, note) = { if note.side == "across" { return (x-pos.first() + x-pos.last()) / 2 } if note.side == "over" { if type(note.pos) == array { let xs = note.pos.map(par => x-pos.at(pars-i.at(par))) return (calc.min(..xs) + calc.max(..xs)) / 2 } } return x-pos.at(pars-i.at(note.pos)) } #let render(pars-i, x-pos, note, y, lifelines) = { let shapes = () let PAD = if note.shape == "hex" {NOTE-HEX-PAD} else {NOTE-PAD} let m = measure(box(note.content)) let w = m.width / 1pt + PAD.last() * 2 let h = m.height / 1pt + PAD.first() * 2 let total-w = w if note.shape == "default" { total-w += NOTE-CORNER-SIZE } let base-x = _get-base-x(pars-i, x-pos, note) let i = none if note.pos != none and type(note.pos) == str { i = pars-i.at(note.pos) } let x0 = base-x if note.side == "left" { x0 -= NOTE-GAP x0 -= total-w if lifelines.at(i).level != 0 { x0 -= LIFELINE-W / 2 } } else if note.side == "right" { x0 += NOTE-GAP x0 += lifelines.at(i).level * LIFELINE-W / 2 } else if note.side == "over" or note.side == "across" { x0 -= total-w / 2 } let x1 = x0 + w let x2 = x0 + total-w let y0 = y if note.linked { y0 += h / 2 } let y1 = y0 - h if note.shape == "default" { shapes += draw.merge-path( stroke: black + .5pt, fill: note.color, close: true, { draw.line( (x0, y0), (x1, y0), (x2, y0 - NOTE-CORNER-SIZE), (x2, y1), (x0, y1) ) } ) shapes += draw.line((x1, y0), (x1, y0 - NOTE-CORNER-SIZE), (x2, y0 - NOTE-CORNER-SIZE), stroke: black + .5pt) } else if note.shape == "rect" { shapes += draw.rect( (x0, y0), (x2, y1), stroke: black + .5pt, fill: note.color ) } else if note.shape == "hex" { let lx = x0 + PAD.last() let rx = x2 - PAD.last() let my = (y0 + y1) / 2 shapes += draw.merge-path( stroke: black + .5pt, fill: note.color, close: true, { draw.line( (lx, y0), (rx, y0), (x2, my), (rx, y1), (lx, y1), (x0, my), ) } ) } shapes += draw.content( ((x0 + x1)/2, (y0 + y1)/2), note.content, anchor: "center" ) if note.aligned-with == none and (note.pos != none or note.side == "across") { y -= h } let r = (y, shapes) return r }
https://github.com/booleto/internship_report_2024
https://raw.githubusercontent.com/booleto/internship_report_2024/main/main.typ
typst
#import "template.typ": * #import "@preview/plotst:0.1.0": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( institutions: ( text("Đại học Quốc gia Hà nội", weight: 800), text("Trường Đại học Khoa học Tự nhiên", weight: 800), "", "", "", "", "", "", text("Khoa Toán - Cơ - Tin học", weight: 800) ), title: "Báo cáo thực tập", subtitle: "Thuật toán xấp xỉ đa thức cho \n bài toán TSP và Bin packing", authors: ( "<NAME>", ), logo: "VNU-HUS.jpg" ) #set text(12pt) // We generated the example code below so you can see how // your document will look. Go ahead and replace it with // your own content! #align( center, text(24pt, bottom-edge: "baseline")[Lời cảm ơn] ) Em xin cảm ơn các thầy cô khoa Toán - Cơ - Tin học đã tạo điều kiện cho em hoàn thành kỳ thực tập năm nay. Kỳ thực tập đã đem lại nhiều kinh nghiệm làm việc quý báu cho em, và sẽ là hành trang giúp em tiếp tục phát triển kỹ năng sau này. Em xin cảm ơn TS. Đỗ Đức Hạnh và quý công ty Smartlog vì đã cho em cơ hội được học tập tại doanh nghiệp, giúp em học hỏi và phát triển bản thân. #pagebreak() #align( center, text(24pt, bottom-edge: "baseline")[Danh mục các từ viết tắt] ) #align(center, table( columns: (auto, auto), inset: 7pt, stroke: none, column-gutter: 20pt, [PTAS], [Phương pháp xấp xỉ đa thức], [TSP], [Travelling Salesman Problem - Bài toán người giao hàng], [E-TSP], [Euclidean TSP - Bài toán TSP trong không gian Euclid], [Arora PTAS], [Lý thuyết xấp xỉ đa thức của S.Arora], ) ) #pagebreak() #align( center, text(24pt, bottom-edge: "baseline")[Danh mục các định nghĩa] ) #align(center, table( columns: (auto, auto), inset: 7pt, stroke: none, column-gutter: 20pt, [TSP], [@E-TSP_en], [E-TSP], [@E-TSP_en], [PTAS], [@PTAS_en], [Arora PTAS], [@AroraPTAS_en], [Portal], [@tsp-ex_en], [Bin packing 2d], [@bin2d_en] ) ) #pagebreak() = Giới thiệu == Bài toán TSP Bài toán Người đưa hàng (Traveling Salesman Problem - TSP) là một trong những bài toán cổ điển và nổi tiếng nhất trong lĩnh vực tối ưu hóa và lý thuyết đồ thị. Bài toán được định nghĩa như sau: Cho một tập hợp các thành phố và khoảng cách giữa từng cặp thành phố, người đưa hàng cần tìm hành trình ngắn nhất để thăm mỗi thành phố đúng một lần và quay trở về thành phố ban đầu. #align(center, figure( image("images/tsp.png", height: 200pt), caption: "Một ví dụ về lời giải bài toán TSP. Các đỉnh đồ thị là các điểm giao hàng. Các cạnh đồ thị là đường đi." ) ) TSP có ý nghĩa rất lớn trong nhiều lĩnh vực như logistics, vận tải, sản xuất và thậm chí cả trong các ứng dụng khoa học máy tính. Khả năng giải quyết TSP hiệu quả có thể dẫn đến tiết kiệm chi phí và thời gian đáng kể trong các ngành công nghiệp này. Ngoài ra, TSP cũng có vai trò quan trọng trong việc nghiên cứu và phát triển các thuật toán tối ưu hóa và tìm kiếm. Tên gọi "Traveling Salesman Problem" lần đầu xuất hiện vào những năm 1930 khi nhà toán học người <NAME> và nhà toán học người <NAME> nghiên cứu về các chu trình trong đồ thị. Tuy nhiên, bài toán chỉ thực sự được định nghĩa rõ ràng và trở nên phổ biến nhờ các nghiên cứu của các nhà toán học và kinh tế học trong thập kỷ 1950. Với sự phát triển của công nghệ máy tính và các thuật toán mới, việc giải quyết bài toán TSP đã có những bước tiến vượt bậc. === Độ khó của bài toán TSP là một bài toán NP-khó, có nghĩa là không có thuật toán nào có thể giải quyết tất cả các trường hợp của bài toán này trong thời gian đa thức, trừ khi P = NP. Điều này làm cho TSP trở thành một thách thức lớn đối với các nhà nghiên cứu và lập trình viên. Với số lượng thành phố tăng, số lượng các hành trình khả dĩ tăng lên theo cấp số nhân, khiến cho việc tìm kiếm giải pháp tối ưu trở nên rất khó khăn. Vì vậy, việc tìm ra một phương án giải gần đúng đủ tốt là quan trọng hơn nhiều so với việc tìm ra một lời giải tối ưu. === Các phương pháp giải quyết TSP Bài toán TSP thường được giải bằng một trong các phương pháp cổ điển như sau: *Phương phép Vét cạn (Brute Force):* Phương pháp này thử tất cả các hành trình khả thi và chọn ra hành trình ngắn nhất. Tuy nhiên, phương pháp này chỉ khả thi cho các tập hợp thành phố rất nhỏ do độ phức tạp thời gian tăng theo hàm giai thừa của số thành phố. *Thuật toán Heuristic:* Các thuật toán như Greedy, Nearest Neighbor, và Christofides cho phép tìm ra các giải pháp gần đúng trong thời gian hợp lý. Mặc dù các giải pháp này không đảm bảo tối ưu, nhưng chúng thường đem lại lời giải đủ tốt. *Thuật toán Metaheuristic:* Các thuật toán như Simulated Annealing, Genetic Algorithms, và Ant Colony Optimization giúp tìm kiếm các giải pháp gần tối ưu bằng cách khám phá không gian nghiệm bài toán một cách thông minh và có tổ chức. *Phương pháp Quy hoạch động và Quy hoạch tuyến tính:* Những phương pháp này sử dụng các kỹ thuật toán học để tìm ra giải pháp tối ưu cho TSP. Tuy nhiên, chúng thường chỉ khả thi cho các bài toán có kích thước vừa phải. === Ứng dụng thực tiễn của TSP *Logistics và Vận Tải*: TSP được sử dụng để tối ưu hóa lộ trình cho các phương tiện giao hàng, giúp giảm chi phí nhiên liệu và thời gian di chuyển. *Sản Xuất:* Trong các dây chuyền sản xuất, TSP giúp tối ưu hóa thứ tự di chuyển của các công cụ và nguyên vật liệu, cải thiện hiệu suất và giảm thời gian chờ. *Du Lịch và Lữ Hành:* TSP hỗ trợ lập kế hoạch hành trình du lịch hiệu quả, giúp khách du lịch tham quan nhiều địa điểm trong thời gian ngắn nhất có thể. == Bài toán Bin Packing Bài toán Bin Packing (còn gọi là Bin Loading) là một trong những bài toán tối ưu hóa cổ điển trong khoa học máy tính và toán học. Bài toán được định nghĩa như sau: Cho một tập hợp các đối tượng có kích thước khác nhau và một số lượng giới hạn các thùng (bins), mỗi thùng có một dung tích cố định. Nhiệm vụ là sắp xếp các đối tượng vào các thùng sao cho số lượng thùng sử dụng là ít nhất, đồng thời đảm bảo rằng tổng kích thước của các đối tượng trong mỗi thùng không vượt quá dung tích của thùng đó. === Ứng dụng thực tế Bài toán Bin Packing xuất hiện trong nhiều tình huống thực tế như: - Quản lý kho bãi: Sắp xếp hàng hóa vào các kho chứa sao cho sử dụng không gian hiệu quả. - Vận tải và logistics: Phân chia hàng hóa vào các container vận chuyển sao cho tối thiểu số lượng container sử dụng. - Quản lý bộ nhớ: Phân bổ các quy trình vào các khối bộ nhớ trong máy tính sao cho tối ưu dung lượng sử dụng. == Mục tiêu đề tài Mục tiêu của đề tài này là nghiên cứu và áp dụng các phương pháp xấp xỉ đa thức (Polynomial Time Approximation Scheme - PTAS) vào giải quyết bài toán TSP và Bin packing, nhằm mang lại một hướng tiếp cận khác so với các phương pháp cổ điển như Heuristic và Metaheuristic. Cụ thể, đề tài sẽ dựa trên nền tảng lý thuyết của các nhà nghiên cứu S.Arora, S.B.Rao và V.V.Vazirani, những người đã có nhiều đóng góp quan trọng trong việc phát triển lý thuyết thuật toán xấp xỉ. - *Khám Phá Lý Thuyết PTAS*: Nghiên cứu và hiểu rõ lý thuyết PTAS, đặc biệt là các công trình của Arora, Rao và Vazirani. PTAS cung cấp các giải pháp gần đúng với sai số $(1 + epsilon)$ tuỳ ý, và có thể chạy trong thời gian đa thức, làm cho nó trở thành một công cụ mạnh mẽ cho các bài toán tối ưu hóa tổ hợp phức tạp. - *Phát Triển Thuật Toán Cụ Thể*: Dựa trên nền tảng lý thuyết đã nghiên cứu, phát triển và triển khai một thuật toán PTAS cụ thể cho bài toán TSP và Bin packing. - *<NAME>*: Khảo sát thời gian chạy của các thuật toán PTAS đã phát triển. Đánh giá tính khả thi của việc áp dụng thuật toán trong các tình huống thực tế, như quản lý logistics, phân phối hàng hóa, và các dịch vụ giao hàng. - *Đề Xuất Hướng Phát Triển Mới*: Dựa trên các kết quả đạt được, đề xuất những hướng nghiên cứu và phát triển mới cho việc áp dụng PTAS vào các bài toán tối ưu hóa tổ hợp khác. Khuyến khích việc tiếp tục nghiên cứu và cải tiến các phương pháp xấp xỉ trong lĩnh vực này. Với các mục tiêu này, đề tài hy vọng sẽ mở ra một hướng đi mới trong nghiên cứu và ứng dụng các thuật toán xấp xỉ cho các bài toán NP-hard khác. Việc áp dụng PTAS không chỉ giúp ổn định sai số bài toán mà còn góp phần vào sự phát triển của lý thuyết thuật toán xấp xỉ và ứng dụng của chúng trong các bài toán thực tế phức tạp. #pagebreak() = Nền tảng lý thuyết == Mô hình các bài toán === Mô hình hóa bản đồ Trong thực tế, dữ liệu bản đồ sẽ được cho dưới dạng ma trận khoảng cách. Vì vậy, ở bước đầu tiên, ta mô hình hóa bản đồ cần xét dưới dạng đồ thị. #align( center, figure( image("images/dist_matrix_example.png"), caption: "Bên trái: Ma trận khoảng cách. Bên phải: Đồ thị tương ứng với ma trận khoảng cách." ) ) Đặt $G^0 = (V, E)$ là đồ thị có trọng số, mô tả mạng lưới giao thông trên bản đồ đang xét. Trong đó: - $V = V_1 union V_2 union V_3 = {v_i in V | i in bb(N)^*}$ trong đó: - $V_1$ là các ngã rẽ (ngã ba, ngã tư,...) - $V_2$ là các điểm cần giao hàng. - $V_3$ là kho hàng. - $E = {e_(i j) = (v_i, v_j) | v_i, v_j in V; quad i,j in bb(N); quad i eq.not j}$ là các đường có thể đi trên mạng lưới giao thông. - Để đơn giản bài toán, ta sẽ mặc định $e_(i j) = e_(j i) quad forall i, j in bb(N)^*$. Từ đó, ta định nghĩa một đường đi $P subset E$ trên đồ thị $G^0$ sẽ là một tập cạnh nối nhau trên $G^0$. $ P = {(e_(i j) , e_(j k)) | i, j, k in bb(N)^*} $ Ký hiệu: - $w(e_(i j))$ là độ dài cạnh $e_(i j) in E$ - $d(v_i, v_j)$ là độ dài đường đi ngắn nhất giữa đỉnh $v_i$ và đỉnh $v_j$ Ký hiệu độ dài đường đi $P subset E$ là: $ d(P) = sum_(e_(i j) in P) w(e_(i j)) quad quad quad "với" e_(i j) in P $ === Mô hình bài toán E-TSP <E-TSP> Trong bài toán TSP tổng quát, nhiệm vụ của ta là phải tìm đường đi trên một đồ thị $G = (V, E)$ tổng quát. Đây là một bài toán rất khó do gặp vấn đề bùng nổ tổ hợp. // Tuy nhiên, với dữ liệu bản đồ, ta biết rằng trên thực tế, vị trí của mọi điểm giao hàng đều có thể được xác định bằng các tọa độ (kinh độ, vĩ độ), và mọi đường đi trên thực tế đều nằm trong không gian metric. Tuy nhiên, khi ta đã nhúng đồ thị $G = (V, E)$ vào không gian Euclid, các nghiên cứu của S.Arora đã chứng minh rằng, ta có thể tận dụng các cấu trúc hình học của không gian này để giải xấp xỉ bài toán trong thời gian đa thức. Bài toán TSP khi đó trở thành bài toán TSP trong không gian Euclid (Euclidean Travelling Salesman Problem, hay E-TSP). Sau đây, ta sẽ phát biểu bài toán E-TSP. Cho một tập $X^0$ các điểm cần giao hàng trong không gian Euclid: $ X^0 = {x_1, ... , x_n} = {x_i in bb(R)^d | i in bb(N)^*, i <= n} $ và một điểm bắt đầu $x_0 = (a_1, ... ,a_d) in bb(R)^d$. Mục tiêu bài toán: tìm một đường đi $P = { (x_0, x_i), (x_i, x_j) , ..., (x_k, x_0)}$ sao cho tổng độ dài đường đi $d(P) = sum_((x_i, x_j) in P) (d(x_i, x_j))$ là bé nhất. === Mô hình bài toán Bin packing 2D <bin2d> Bài toán Bin packing có thể được phát biểu như sau: Cho các thùng hàng hình chữ nhật (còn gọi là bin) có kích thước $(W, H)$ cố định, và một tập $I$ các đồ vật kích cỡ $(w_i, h_i)$. Tìm các vị trí $(x_i, y_i)$ của mỗi đồ vật sao cho: - Không có đồ vật nào bị chồng lên nhau. - Số lượng bin có chứa đồ là tối thiểu. // Cho một tập hợp $I$ các đồ vật có kích thước $s(i) in bb(Z)^+ quad forall i in I$ == Phương án giải quyết // === Nhúng đồ thị vào không gian Euclid - Phép nhúng lò xo <Spring> // *TODO* === Phương pháp xấp xỉ đa thức (PTAS) Trong khoa học máy tính (đặc biệt là lý thuyết thuật toán), phương pháp xấp xỉ đa thức (PTAS) là các họ thuật toán xấp xỉ cho các bài toán tối ưu hóa (thường là các bài toán tối ưu hóa NP-hard). Một PTAS là một họ các thuật toán để giải một bài toán nhất định, trong đó mỗi thuật toán phụ thuộc tham số $epsilon > 0$ cho trước. Đầu ra thuật toán là một lời giải có kết quả trong khoảng $(1 + epsilon)$ so với lời giải tối ưu (hoặc $(1 - epsilon)$ đối với các bài toán tối đa hóa). Ví dụ, đối với bài toán người đưa hàng trong không gian Euclid, PTAS sẽ tạo ra một lịch trình di chuyển có độ dài tối đa là $((1 + epsilon) dot L)$, với $L$ là độ dài của lịch trình di chuyển ngắn nhất. ==== Định nghĩa PTAS <PTAS> Sau đây, ta sẽ đưa ra định nghĩa cho một PTAS. *Định nghĩa - Phương pháp xấp xỉ:* Cho $Pi$ là một bài toán tối ưu hóa NP-hard, với hàm mục tiêu $f_Pi$. Ta nói $cal(A)$ là một phương pháp xấp xỉ cho bài toán $Pi$ nếu như với $I$ là một đầu vào của $Pi$ và $epsilon > 0$ là tham số, ta có $cal(A)(I, epsilon) = s$ thỏa mãn: - $f_Pi (I, s) <= (1 + epsilon) dot "OPT"$ nếu $Pi$ là bài toán cực tiểu hóa. - $f_Pi (I, s) >= (1 - epsilon) dot "OPT"$ nếu $Pi$ là bài toán cực đại hóa. Trong đó, OPT là giá trị của hàm mục tiêu đối với nghiệm tối ưu. Tham số $epsilon$ còn thường được gọi là sai số của phương pháp xấp xỉ $cal(A)$ *Định nghĩa - Phương pháp xấp xỉ đa thức:* Cho $cal(A)$ là một phương pháp xấp xỉ của bài toán $Pi$. Ta gọi $cal(A)$ là một phương pháp xấp xỉ thời gian đa thức (PTAS) của $Pi$ nếu với tham số $epsilon > 0$, thời gian chạy của $cal(A)$ là một đa thức theo I. ==== Lý do sử dụng PTAS PTAS là một công cụ mạnh mẽ khi cần giải xấp xỉ các bài toán NP-khó. Các khác biệt quan trọng của PTAS so với các phương pháp cổ điển như Heuristics và Metaheuristics bao gồm: - *Độ chính xác:* Ta có thể chọn một $epsilon$ bé tùy ý, vậy nên luôn biết trước sai số. Đây là kết quả tốt nhất mà ta có thể mong đợi cho các bài toán NP-hard, vốn không thể tìm lời giải tối ưu trong thời gian đa thức. - *Tốc độ:* Thuật toán luôn chạy trong thời gian đa thức với mọi $epsilon$ cố định Tuy nhiên, định nghĩa của PTAS không xét đến thời gian chạy khi sai số $epsilon$ tiến dần về 0. Vì vậy, một thuật toán chạy trong thời gian $O(n^(1 / epsilon))$ hoặc thậm chí $O(n^(e^(1 / epsilon)))$ vẫn được coi là một PTAS. Vậy nên, với một số PTAS, thời gian chạy có thể trở nên phi thực tế khi $epsilon$ quá nhỏ. PTAS có thể được áp dụng cho các bài toán tổ hợp NP-hard như bài toán xếp ba lô (knapsack problem), bài toán lập lịch (scheduling problem), và nhiều bài toán tối ưu khác. === PTAS của S.Arora cho bài toán E-TSP <AroraPTAS> S.Arora (Princeton University) đã phát minh ra PTAS cho bài toán E-TSP trong thời gian $O(n "log"^k (n))$ với sai số $(1 + epsilon)$, với $k$ tỷ lệ với $1/epsilon$ và $d$ khi đồ thị được nhúng sẵn. Nghiên cứu này của ông được trao giải thưởng Godel năm 2010. PTAS của S.Arora cho bài toán E-TSP là một đột phá quan trọng trong lĩnh vực thuật toán xấp xỉ, và đã đặt nền móng cho nhiều thuật toán xấp xỉ cho các bài toán NP-hard khác, chẳng hạn như Cây bao trùm tối thiểu, Cây Steiner tối thiểu, Ghép cặp hoàn hảo trọng số cực tiểu,.... Từ đây, ta sẽ gọi lý thuyết về PTAS của Arora là Arora PTAS. ===== Ví dụ thúc đẩy <tsp-ex> Để mô tả ý tưởng của Arora PTAS, đầu tiên, ta xét một ví dụ cụ thể. Giả sử ta có bài toán E-TSP, trong đó ta đã biết lịch trình tối ưu của bài toán này là như sau: #align( center, figure( image("images/tsp.png"), caption: "Một ví dụ về lịch trình tối ưu của TSP" ), ) Giờ, ta lấy một hình vuông bất kỳ trong lịch trình tối ưu. #align( center, figure( image("images/mpath.png", height: 250pt), caption: "" ), ) Từ đây, ta có thể tách các điểm trong hình vuông thành một bài toán con. Trong lý thuyết xấp xỉ đa thức của S.Arora, đây được gọi là bài toán multipath. Mục tiêu bài toán là tìm một tập các đường đi đi qua tất cả các điểm trên hình vuông và mọi điểm bên trong hình vuông. #align( center, figure( image("images/mpath2.png", height: 200pt), caption: "Bài toán con cần giải quyết." ), ) // Từ đây, ta gọi tất cả các điểm giao nhau giữa hình vuông và đường đi TSP tối ưu là *portal*. *Phát biểu bài toán multipath:* Đầu vào của bài toán bao gồm: - Một hình vuông $S$. - Tập điểm $V = {v_i in diff S | i < r}, space.en r in N^*$ gồm các điểm nằm trên biên của $S$. - Một tập các điểm $X_S subset.eq X$ cần giao hàng trong hình vuông $S$. Đầu ra bài toán: các đường đi $P = {(v_a, x_i), ... , (x_j, v_b)}$, sao cho $x in P space.en forall x in X_S$ Bài toán con này có thể tiếp tục được chia nhỏ. Ta có thể chia bài toán cho đến trường hợp cơ bản: khi chỉ có $<= 1$ điểm nằm trong $S$. Khi đó bài toán con có thể được giải bằng vét cạn trong thời gian $O(r) = O(1/epsilon)$. // thêm hình Ý tưởng chính của Arora chính là chia bài toán E-TSP thành nhiều bài toán con ở trường hợp cơ bản ($|X_S| <= 1$), rồi giải và tổng hợp kết quả. ===== Các bước thực hiện *Bước 1: Tiền xử lý dữ liệu tọa độ* Việc nhân mọi tọa độ $x in X^0$ với một hằng số không làm thay đổi bản chất bài toán. Vì vậy, ta lấy $X' = {x' = k x | x in X^0}$ và $y' = k y_0$ Tiếp theo, ta làm tròn tọa độ của mọi điểm $x' in X'$ và điểm $y$. Mục tiêu là gộp các điểm quá gần nhau và coi chúng như 1 điểm. Từ đó ta có dữ liệu mới: $ X = {x = "round"(x') | x' in X'} $ $ y = "round"(y') $ *Bước 2: Chia nhỏ bài toán và thiết lập 4-tree* Các bước chia của bài toán có thể được mô tả bằng một 4-tree. Đầu tiên, ta lấy một hình vuông bất kỳ bao quanh mọi điểm với chiều dài $L$. Sau đó, ta chia mỗi hình vuông làm 4 cho đến khi mỗi hình vuông chỉ còn chứa 1 nút. #align(center, grid( columns: (auto, auto), column-gutter: 10pt, row-gutter: 10pt, figure( image("images/tree_1.png", height: 100pt), caption: "Chia không gian, bước thứ 1." ), figure( image("images/tree_2.png", height: 90pt), caption: "Cây tương ứng với bước 1." ), figure( image("images/tree_4.png", height: 100pt), caption: "Chia không gian, bước thứ 2." ), figure( image("images/tree_3.png", height: 90pt), caption: "Cây tương ứng với bước 2." ), figure( image("images/4tree2.png", height: 100pt), caption: "Chia không gian, bước thứ 3." ), figure( image("images/4tree.png", height: 100pt), caption: "Cây tương ứng với bước 3." ), ) ) Với mỗi nút trên cây, ta có hình vuông S tương ứng. Ta xây dựng các bài toán multipath, mỗi bài toán ứng với một tổ hợp điểm $V$ trên cạnh hình vuông $S$, ta giải bài toán để tìm đường đi $P$ sao cho $v in P space forall v in V$. Tuy nhiên, vì không được biết trước tập hợp các điểm $v in V$ mà đường đi TSP cắt hình vuông S, nên không mất tổng quát, ta giả sử đường đi TSP chỉ cắt hình vuông tại các điểm cố định. Các điểm này ta gọi là *portal*. *Bước 3: Quy hoạch động* Ta lập một bảng quy hoạch động để lưu tất cả lời giải của các bài toán multipath đối với mỗi hình vuông cần xét. #align( center, table( columns: 7, table.header( [], [Nút], [Bài toán 1], [Bài toán 2], [Bài toán 3], [Bài toán 4], [...] ), table.cell( rowspan: 6, align: horizon, rotate(-90deg, reflow: true)[ Nút trên cây ], ), [1], [...], [...], [...], [...], [...], [2], [...], [...], [...], [...], [...], [3], [...], [...], [...], [...], [...], [4], [...], [...], [...], [...], [...], [5], [...], [...], [...], [...], [...], [6], [...], [...], [...], [...], [...], ) ) Với các nút lá trên cây, bài toán ở trường hợp cơ bản (0 hoặc 1 điểm cần đi qua). Bảng quy hoạch động sẽ lưu lời giải của nút lá. Với các nút còn lại của cây, bảng quy hoạch động lưu vị trí các bài toán con đem lại kết quả. Ta giải từng bài toán trong bảng quy hoạch động từ dưới lên trên. Các nút lá lần lượt được giải bằng vét cạn, và các nút cha lần lượt tìm 4 bài toán con đem lại đường đi ngắn nhất. *Bước 4: Tổng hợp kết quả* Hàng đầu tiên trên bảng quy hoạch động sẽ trỏ đến 4 bài toán con tốt nhất. Tại mỗi bài toán con, lần lượt đi xuống bảng quy hoạch động để tìm đường đi tốt nhất. ===== Cơ sở lý thuyết của Arora PTAS Một trong những kết quả quan trọng nhất trong lý thuyết thuật toán xấp xỉ của Arora là việc chứng minh định lý cấu trúc. Định lý này đưa ra mối liên hệ giữa sai số $epsilon$ cho trước và kết quả của thuật toán xấp xỉ. *Định lý: Định lý cấu trúc:* Cho một sai số $epsilon > 0$ cho trước. Không mất tổng quát, giả sử khoảng cách tối thiểu giữa các nút là 2 và $L$ là độ dài cạnh hình hộp vuông bao quanh mọi điểm $x in X$ cần giao hàng. Với một vector $a in R^d$ ngẫu nhiên, đặt $X_a = {x + a | x in X, a = (a_1, a_2, ..., a_d) in bb(R)^d, 0 < a_i < L/2 space.en forall space 0 < i <= d}$. Khi đó, với xác suất tốt thiểu $1/2$, tồn tại đường đi TSP có tổng chiều dài $(1 + epsilon) dot "OPT"$, cắt các cạnh trên 4-tree tối đa r lần tại các portal. Định lý cấu trúc cho thấy, với một phép tịnh tiến ngẫu nhiên cho mọi $x in X$, ta có thể giải xấp xỉ TSP với một sai số biết trước. === Mở rộng Arora PTAS để giải bài toán Bin packing 2D Những ý tưởng chính của Arora PTAS bao gồm: - Gộp các đối tượng giống nhau bằng cách làm tròn. - Chia bài toán lớn thành các bài toán con, cho đến khi gặp trường hợp cơ bản nhất. - Lần lượt giải từ bài toán con lên bài toán mẹ bằng quy hoạch động. Các phương pháp này cũng có thể được mở rộng cho các bài toán khác, bao gồm bin packing. Sau đây, ta sẽ thiết kế một PTAS cho bin packing 2D, dựa trên các kỹ thuật của Arora. ==== Tiền xử lý dữ liệu Ý tưởng chính của thuật toán: Giống như Arora chia đôi mặt phẳng để tạo thành các bài toán con, ta chia đôi bin tại các điểm nhất định, mỗi điểm tạo thành 2 bài toán bin packing nhỏ hơn. #align( figure( image("images/bin_ptas.png", height: 200pt), caption: "Mục tiêu: chia bin làm 2 ở các vị trí nhất định." ) ) Chọn trước tham số $a$. Với sai số $epsilon$ đã biết, ta chọn các vật có chiều dài $x_i in ((a - epsilon) / k, a / k)$, trong đó $k = 1, 2, ...$ #align( figure( image("images/binselect.png", height: 200pt), caption: "Trục hoành: chiều dài của vật. Trục tung: chiều cao của vật \n Màu đỏ: Các điểm được chọn. Màu xanh: Các điểm chưa được chọn" ) ) $forall x_i in ((a - epsilon) / k, a / k)$, ta coi $x_i approx a/k$ và lần lượt xếp $x_i$ vào bin theo thứ tự $y_i$ từ lớn đến bé. Ý nghĩa của việc chia đôi chính là, khi ta đã xấp xỉ chiều dài $x_i approx a/k$ và đặt bin con chiều dài $a/k$, thì ta không phải xét chiều dài $x_i$ của mỗi vật khi xếp vào bin con. Khi đó bài toán trở thành bài toán bin packing 1D, ta chỉ cần chú ý chiều dài bin và chiều cao $y_i$ #figure( image("images/bin_approx.png", width: 200pt), caption: "Các vật khi xếp xấp xỉ với chiều dài bin" ) // ==== Chia nhỏ bài toán Khi đó, sau mỗi bước bin packing 1D với $x_i in ((a - epsilon)/k, a/k)$, ta thu được 2 bài toán bin packing 1D với $x_i in ((a - epsilon)/(k + 1), a/(k+1))$ #pagebreak() = Triển khai thuật toán == Các công nghệ được sử dụng Theo chỉ dẫn của công ty thực tập, em lập trình toàn bộ các dự án nêu trên trong Python, chỉ sử dụng các thư viện tính toán cơ bản như NumPy, Numba, và các thư viện đồ họa NetworkX, Matplotlib. - *NumPy:* NumPy là một thư viện mã nguồn mở cho ngôn ngữ lập trình Python, được sử dụng rộng rãi trong lĩnh vực khoa học dữ liệu và tính toán khoa học. Tên của nó viết tắt từ "Numerical Python". NumPy cung cấp các cấu trúc dữ liệu mạnh mẽ như mảng (array) và ma trận (matrix), đi kèm với một bộ hàm toán học phong phú để thao tác và tính toán trên các dữ liệu này. Nhờ có NumPy, các nhà khoa học và kỹ sư có thể thực hiện các phép tính số học phức tạp một cách hiệu quả và nhanh chóng, từ đó hỗ trợ cho việc phân tích dữ liệu, mô phỏng và xây dựng các thuật toán phức tạp. NumPy là nền tảng cho nhiều thư viện khác trong Python như SciPy, Pandas và Matplotlib, góp phần làm cho Python trở thành một ngôn ngữ mạnh mẽ trong lĩnh vực khoa học dữ liệu và học máy. - *Numba:* Numba là một thư viện mã nguồn mở dành cho Python, được thiết kế để tăng tốc độ thực thi các đoạn mã Python bằng cách biên dịch chúng thành mã máy (machine code) trong thời gian thực. Sử dụng Just-in-Time (JIT) compilation, Numba cho phép các hàm Python đạt được tốc độ gần như tương đương với các ngôn ngữ lập trình cấp thấp như C hoặc Fortran mà không cần thay đổi nhiều trong mã nguồn gốc. Điều này đặc biệt hữu ích trong các ứng dụng khoa học dữ liệu, tính toán khoa học và học máy, nơi mà hiệu suất là yếu tố quan trọng. Numba tương thích tốt với các thư viện phổ biến như NumPy, giúp tối ưu hóa các thao tác trên mảng và ma trận một cách hiệu quả. Bằng cách đơn giản hóa quá trình tăng tốc mã Python, Numba trở thành một công cụ mạnh mẽ cho các nhà phát triển và nhà nghiên cứu trong việc nâng cao hiệu suất của các ứng dụng tính toán phức tạp. - *Matplotlib:* Matplotlib là một thư viện mã nguồn mở dành cho Python, được sử dụng rộng rãi để tạo ra các biểu đồ và hình ảnh minh họa dữ liệu. Thư viện này cung cấp các công cụ linh hoạt và mạnh mẽ cho việc vẽ các loại biểu đồ như biểu đồ đường, biểu đồ thanh, biểu đồ tán xạ, biểu đồ bánh và nhiều loại biểu đồ khác. Matplotlib hỗ trợ việc tùy chỉnh chi tiết các yếu tố đồ họa, từ màu sắc, kiểu dáng đến chú thích và nhãn, giúp người dùng tạo ra những hình ảnh trực quan và chuyên nghiệp. Thư viện này được đánh giá cao trong cộng đồng khoa học dữ liệu và phân tích dữ liệu vì khả năng kết hợp dễ dàng với các thư viện khác như NumPy, Pandas và SciPy. Matplotlib là một công cụ quan trọng trong việc trình bày và khám phá dữ liệu, giúp các nhà nghiên cứu và nhà phân tích truyền tải thông tin một cách rõ ràng và hiệu quả. == Phép nhúng lò xo Để đưa bài toán TSP tổng quát về bài toán E-TSP, ta dùng phép nhúng lò xo để nhúng đồ thị vào không gian Euclid. *Đầu vào:* Ma trận khoảng cách $A$, mô tả đồ thị $G = (V, E)$ *Đầu ra:* Mảng 2 chiều, chứa tọa độ các đỉnh $v in V$ của đồ thị $G$ khi đã được nhúng. // Để thực hiện phép nhúng lò xo trong thời gian đa thức, ta sẽ sử dụng thuật toán Barnes-Hut. Ý tưởng của thuật toán Barnes-Hut là coi các nút ở xa nhau như một nút thống nhất. == Giải E-TSP bằng PTAS của S.Arora Từ kết quả của phép nhúng lò xo, ta triển khai các bước của Arora PTAS trong Numba. *Đầu vào:* Tọa độ các điểm cần đi qua, dưới dạng một mảng 2 chiều: $ X^0 = {(x_0, x_1) in R^2} $ *Đầu ra:* Tọa độ các điểm cần đi qua, xếp theo thứ tự đến trước $arrow$ đến sau, dưới dạng một mảng 2 chiều. === Dữ liệu tọa độ Vì nhân mọi tọa độ với một hằng số không làm thay đổi bản chất bài toán, ta lấy $X = k X^0$, với $k = O(1/epsilon)$. Tiếp theo, ta làm tròn tọa độ của mọi điểm. Các điểm quá gần nhau sẽ được hợp thành 1 điểm duy nhất. #align( figure( image("images/image.png"), caption: "Các tọa độ trước và sau khi làm tròn. Màu đen: Trước khi làm tròn. Màu xanh: Sau khi làm tròn." ) ) === Xây dựng 4-tree // TODO: hình ảnh Trong Numba, 4-Tree có thể được biểu diễn bằng cấu trúc dữ liệu cây bằng `@jitclass` Tuy nhiên, khả năng hỗ trợ `jitclass` của Numba rất hạn chế. Vậy nên, để tăng tốc độ tính toán, cấu trúc cây được biểu diễn dưới dạng một `array` trong NumPy. Mỗi hàng của `array` chứa thông tin về một nút trên cây, và mỗi hàng chứa thông số về các nút tương ứng. #align(center, figure( table( columns: 7, table.header( [], [ID], [Nút mẹ], [Hoạt động], [Bậc], [Nút con], [AABB] ), table.cell( rowspan: 9, align: horizon, rotate(-90deg, reflow: true)[ *Các nút* ], ), [1], [NULL], [TRUE], [0], [2], [...], [2], [1], [TRUE], [1], [NULL], [...], [3], [1], [TRUE], [1], [6], [...], [4], [1], [TRUE], [1], [NULL], [...], [5], [1], [TRUE], [1], [NULL], [...], [6], [3], [TRUE], [2], [NULL], [...], [7], [3], [TRUE], [2], [NULL], [...], [8], [3], [TRUE], [2], [NULL], [...], [9], [3], [TRUE], [2], [NULL], [...], ), caption: "Một ví dụ về biểu diễn cây bằng ma trận trong NumPy" ) ) Trong đó: - ID: Chỉ số của nút trên ma trận. - Nút mẹ: ID của nút mẹ. - Hoạt động: NULL/TRUE - hàng hiện có chứa dữ liệu về nút không. - Bậc: Bậc của nút trên cây - Nút con: ID của nút con đầu tiên. Để ta chỉ cần lưu nút con đầu tiên, mọi nút con của một nút sẽ được xếp cạnh nhau VD: Để tìm nút con thứ 3 của nút $a$, lấy 2 + ID nút con thứ 1 của $a$ - AABB: Axis-aligned bounding box - Mô tả vị trí và kích cỡ của ô vuông tương ứng với nút này. // Phần bảng trên trên sẽ tương ứng với cây sau: // TODO: Thêm hình ảnh // === <NAME> - Hut === Chia nhỏ bài toán Tại mỗi nút trên cây, ta tạo các portal cách đều nhau ở các đường chia. Portal được lưu trong một mảng 2 chiều `portallist` #align(center, figure( image("images/portals_init.png", height: 250pt), caption: "Ví dụ về đặt portal. Chấm xanh là các điểm đường đi TSP cần đi qua. Dấu x đỏ là các portal." ) ) Lặp lại bước trên với mọi nút trên cây. #align(center, figure( image("images/portals.png", height: 250pt), caption: "Kết quả sau khi chia cây và đặt portal" ) ) Dữ liệu của cây được lưu trong các mảng sau. - `tree:` Thông tin về mỗi nút trên cây. - `vertices`: Mọi điểm cần đi qua. - `vertices_idx`: Thông tin về các điểm nằm trong mỗi nút - VD: nếu ô thứ 5 chứa các điểm thứ 0, 1, 2 trong `vertices`, thì tại `square_index = 5` , ta có `vertex_count = 3`, `vertices_idx = [0, 1, 2]` - `portallist`: Danh sách các portal. - `portalref`: Danh sách các portal trong mỗi ô - VD: nếu ô thứ 5 của cây chứa các portal thứ 0, 1, 2 trong `portallist`, thì tại `square_index = 5` thì `index_count = 3` và `portal_index = [0, 1, 2]` Ta #figure( image("images/matrix_schema.svg"), caption: "Cấu trúc và mối liên hệ giữa các mảng. Hàng đầu tiên của mỗi bảng là chỉ số của hàng đó trong mảng. Các hàng còn lại tương ứng với mỗi phần tử trong phẩn. Các mũi tên mô tả quan hệ của các biến lưu chỉ số." ) === Quy hoạch động Quá trình quy hoạch động được tóm tắt như sau: #align(center, figure( image("images/dp_tsp.png"), caption: "Sơ đồ thuật toán giải quy hoạch động." ) ) Ta dựng bảng quy hoạch động theo cấu trúc sau: #align( center, table( columns: 7, table.header( [], [Nút], [Bài toán 1], [Bài toán 2], [Bài toán 3], [Bài toán 4], [...] ), table.cell( rowspan: 6, align: horizon, rotate(-90deg, reflow: true)[ Nút trên cây ], ), [1], [...], [...], [...], [...], [...], [2], [...], [...], [...], [...], [...], [3], [...], [...], [...], [...], [...], [4], [...], [...], [...], [...], [...], [5], [...], [...], [...], [...], [...], [6], [...], [...], [...], [...], [...], ) ) // Với mỗi ô vuông, ta đánh số thứ tự cho mỗi bài toán con, tương ứng với mỗi tổ hợp portal $V subset partial S$. Để biết tổ hợp portal $V$ ứng với bài toán thứ mấy, ta cần xây dựng ánh xạ từ $V$ vào số thứ tự bài toán. // Không mất tổng quát, vì mỗi portal đặt cách đều nhau, ta quy chúng về các điểm cố định. // *TODO: Ảnh* // Mỗi portal có thể được dùng hoặc không được dùng, vì vậy số bài toán con ứng với mỗi ô vuông $S$ là $2^(|V_S|)$. // *TODO: Ảnh* // Vì vậy, ta có thể dùng biểu diễn nhị phân của tập portal, đổi về số nguyên, lấy kết quả làm chỉ số bài toán. // *TODO: Ảnh mô tả ánh xạ* Bảng quy hoạch động sẽ lần lượt được dựng từ nút con đến nút cha. === Tổng hợp kết quả Một khi có bảng quy hoạch động, ta lần lượt đi từ nút mẹ xuống để tổng hợp kết quả. #align( center, figure( image("images/tsp_res1.png"), caption: "Đường đi TSP thu được từ bảng quy hoạch động" ), ) #align( center, figure( image("images/tsp_res2.png"), caption: "Thông tin trong bảng quy hoạch động" ) ) == Triển khai PTAS cho bài toán Bin packing 2D === Tiền xử lý dữ liệu Ta tách dữ liệu ra theo các phần $((a - epsilon)/k, a/k)$ #figure( image("images/binselect.png"), caption: "Tách dữ liệu" ) Với mỗi $k$ xác định, ta lưu mỗi vật trong khoảng $((a - epsilon)/k, a/k)$ vào một max heap. Như vậy thời gian tìm vật lớn nhất sẽ là $O(1)$. === Thiết lập bài toán con Bài toán con của ta sẽ là một bài toán bin packing 1D: Cho một tập các vật $I$ cho trước, mỗi vật có chiều cao $y_i$. Xếp các vật vào bin $B$ có chiều cao $Y$ sao cho: $ sum_(i in B) y_i <= Y $ === Thuật toán Bắt đầu với bin đầu tiên, lần lượt xếp các vật lớn nhất vào đến khi không thể xếp tiếp, rồi chia đôi bin. #figure( image("images/bin_1.png", height: 100pt), caption: "Bước 1: Xếp đẩy bin" ) #figure( image("images/bin_2.png", height: 100pt), caption: "Bước 2: Chia đôi bin" ) #figure( image("images/bin_3.png", height: 100pt), caption: "Bước 3: Giải bài toán con ở các bin con" ) Sau khi xếp đẩy 1 bin, ta chuyển sang bin tiếp theo, đến khi không còn vật nào để xét. // = Nhận xét và đánh giá // == Độ phức tạp thuật toán // === Arora PTAS // Theo bài báo của S.Arora, độ phức tạp // == Sai số // == So sánh tốc độ // === Phương pháp đánh giá // === Đánh giá kết quả // === Kết luận // == Kiểm tra // === Tiến hành đánh giá // === Kết luận #pagebreak() = Tài liệu tham khảo <NAME>. 1998. Polynomial time approximation schemes for Euclidean traveling salesman and other geometric problems. J. ACM 45, 5 (Sept. 1998), 753–782. https://doi.org/10.1145/290179.290180 Rao, Satish and <NAME>. “Approximating geometrical graphs via “spanners” and “banyans”.” Symposium on the Theory of Computing (1998). <NAME>. 2010. Approximation Algorithms. Springer Publishing Company, Incorporated. <NAME>, <NAME>, and <NAME>. 2005. Euclidean distortion and the sparsest cut. In Proceedings of the thirty-seventh annual ACM symposium on Theory of computing (STOC '05). Association for Computing Machinery, New York, NY, USA, 553–562. https://doi.org/10.1145/1060590.1060673 #counter(heading).update(0) #pagebreak() = Introduction == Travelling Salesman Problem The Traveling Salesman Problem (TSP) is one of the most classic and famous problems in the fields of optimization and graph theory. The problem is defined as follows: Given a set of cities and the distances between each pair of cities, the salesman needs to find the shortest possible route that visits each city exactly once and returns to the original city. #align(center, figure( image("images/tsp.png", height: 200pt), caption: "An example of a solution to the TSP. The vertices of the graph are the delivery points. The edges of the graph are the paths.." ) ) The TSP is highly significant in many fields such as logistics, transportation, manufacturing, and even in computer science applications. The ability to effectively solve the TSP can lead to significant cost and time savings in these industries. Additionally, the TSP also plays an important role in the research and development of optimization and search algorithms. The name "Traveling Salesman Problem" first appeared in the 1930s when Irish mathematician Hamilton and British mathematician Kirkman studied cycles in graphs. However, the problem was only clearly defined and became popular thanks to the research of mathematicians and economists in the 1950s. With the development of computer technology and new algorithms, solving the TSP has made significant strides. === Difficulty of the Problem The TSP is an NP-hard problem, which means that there is no algorithm that can solve all instances of this problem in polynomial time, unless P = NP. This makes the TSP a major challenge for researchers and programmers. As the number of cities increases, the number of possible routes increases exponentially, making it very difficult to find the optimal solution. Therefore, finding a sufficiently good approximate solution is much more important than finding an optimal solution. === Methods for Solving the TSP The TSP is typically solved using one of the following classical methods: *Brute Force Method:* This method tries all possible routes and selects the shortest one. However, this method is only feasible for very small sets of cities due to the factorial time complexity as the number of cities increases. *Heuristic Algorithms:* Algorithms such as Greedy, Nearest Neighbor, and Christofides allow finding approximate solutions in reasonable time. While these solutions are not guaranteed to be optimal, they often provide sufficiently good results. *Metaheuristic Algorithms:* Algorithms like Simulated Annealing, Genetic Algorithms, and Ant Colony Optimization help in finding near-optimal solutions by intelligently and systematically exploring the solution space. *Dynamic Programming and Linear Programming Methods:* These methods use mathematical techniques to find the optimal solution for the TSP. However, they are usually only feasible for problems of moderate size. === Practical Applications of the TSP *Logistics and Transportation:* TSP is used to optimize routes for delivery vehicles, helping to reduce fuel costs and travel time. *Manufacturing:* In production lines, TSP helps optimize the movement sequence of tools and materials, improving efficiency and reducing waiting times. *Travel and Tourism:* TSP aids in planning efficient travel itineraries, enabling tourists to visit many locations in the shortest possible time. == The Bin Packing Problem The Bin Packing Problem (also known as Bin Loading) is a classic optimization problem in computer science and mathematics. The problem is defined as follows: Given a set of objects of different sizes and a limited number of bins, each with a fixed capacity, the task is to arrange the objects into the bins so that the number of bins used is minimized, while ensuring that the total size of the objects in each bin does not exceed the bin's capacity. === Real-World Applications The Bin Packing problem arises in various real-world situations such as: - Warehouse management: Organizing goods into storage warehouses to utilize space efficiently. - Transportation and logistics: Allocating goods into shipping containers to minimize the number of containers used. - Memory management: Allocating processes into memory blocks in computers to optimize memory usage. == Research Objective The objective of this project is to investigate and apply Polynomial Time Approximation Scheme (PTAS) methods to solve the Traveling Salesman Problem (TSP) and Bin Packing problem, aiming to provide an alternative approach to classical methods such as Heuristic and Metaheuristic. Specifically, the project will be based on the theoretical foundation laid out by researchers S. Arora, <NAME>, and <NAME>, who have made significant contributions to the development of approximation algorithm theory. - *Exploration of PTAS Theory*: Study and gain a deep understanding of PTAS theory, especially the works of Arora, Rao, and Vazirani. PTAS offers approximate solutions with arbitrary $(1 + epsilon)$ error, and can run in polynomial time, making it a powerful tool for complex combinatorial optimization problems. - *Development of Specific Algorithms*: Based on the studied theory, develop and implement a specific PTAS algorithm for the TSP and Bin Packing problems. - *Performance Evaluation*: Investigate the runtime of the developed PTAS algorithms. Evaluate the feasibility of applying the algorithms in real-world scenarios, such as logistics management, goods distribution, and delivery services. - *Proposal of New Development Directions*: Based on the achieved results, propose new research and development directions for applying PTAS to other NP-hard optimization problems. Encourage further research and improvement of approximation methods in this field. With these objectives, the project aims to open up a new direction in the research and application of approximation algorithms for other NP-hard problems. Applying PTAS not only stabilizes the error of the problems but also contributes to the development of approximation algorithm theory and their application in complex real-world problems. #pagebreak() = Theoretical Foundation == Mathematical Models === Map Modeling In practice, map data is often provided in the form of a distance matrix. Therefore, in the first step, we model the map to be considered as a graph. #align( center, figure( image("images/dist_matrix_example.png"), caption: "On the left: Distance matrix. On the right: Graph corresponding to the distance matrix.." ) ) Let $G^0 = (V, E)$ be the weighted graph describing the traffic network on the map under consideration. Where: - $V = V_1 union V_2 union V_3 = {v_i in V | i in bb(N)^*}$ where: - $V_1$ are intersections (T-junctions, crossroads, etc.). - $V_2$ are delivery points. - $V_3$ are warehouses. - $E = {e_{i j} = (v_i, v_j) ,|, v_i, v_j in V; quad i, j in bb(N); quad i eq.not j}$ are the roads on the traffic network. - To simplify the problem, we will assume $e_{i j} = e_{j i} quad forall i, j in bb(N)^*$. From there, we define a path $P subset E$ on the graph $G^0$ to be a set of connected edges on $G^0$. $ P = {(e_{i j} , e_{j k}) | i, j, k in bb(N)^*} $ Notation: - $w(e_{i j})$ is the length of edge $e_{i j} in E$. - $d(v_i, v_j)$ is the shortest path length between vertex $v_i$ and vertex $v_j$. The length of the path $P subset E$ is denoted as: $ d(P) = sum_{e_{i j} in P} w(e_{i j}) quad quad quad "for" e_{i j} in P $ === Mathematical Model: E-TSP <E-TSP_en> In the general TSP problem, our task is to find a path on a graph $G = (V, E)$ in a generalized setting. This is a very challenging problem due to the combinatorial explosion. // However, with map data, we know that in reality, the locations of all delivery points can be determined by coordinates (longitude, latitude), and all paths in reality lie in metric space. However, when we embed the graph $G = (V, E)$ into Euclidean space, research by <NAME> has shown that we can leverage the geometric structures of this space to approximate the problem in polynomial time. The TSP problem then becomes the Euclidean Travelling Salesman Problem (E-TSP). Next, we will state the E-TSP problem. Given a set $X^0$ of delivery points in Euclidean space: $ X^0 = {x_1, ... , x_n} = {x_i in bb(R)^d | i in bb(N)^*, i <= n} $ and a starting point $x_0 = (a_1, ... ,a_d) in bb(R)^d$. The problem objective: find a route $P = { (x_0, x_i), (x_i, x_j) , ..., (x_k, x_0)}$ that minimizes the total length of the route $d(P) = sum_((x_i, x_j) in P) (d(x_i, x_j))$. === Problem Model: 2D Bin Packing <bin2d_en> The 2D Bin Packing problem can be stated as follows: Given fixed-size rectangular bins (also called bins) with dimensions $(W, H)$, and a set $I$ of items with sizes $(w_i, h_i)$. Find positions $(x_i, y_i)$ for each item such that: - No items overlap. - The minimum number of bins containing items is used. // Cho một tập hợp $I$ các đồ vật có kích thước $s(i) in bb(Z)^+ quad forall i in I$ == Approaches // === Embedding the Graph into Euclidean Space - Spring Embedding <Spring> // *TODO* === Polynomial Time Approximation Scheme (PTAS) In computer science (especially algorithm theory), Polynomial Time Approximation Scheme (PTAS) is a family of approximation algorithms for optimization problems (often NP-hard optimization problems). A PTAS is a family of algorithms to solve a certain problem, where each algorithm depends on a predefined parameter $epsilon > 0$. The output of the algorithm is a solution with a result within $(1 + epsilon)$ range of the optimal solution (or $(1 - epsilon)$ for maximization problems). For example, for the Euclidean Travelling Salesman Problem, a PTAS will produce a travel itinerary with a maximum length of $((1 + epsilon) \cdot L)$, where $L$ is the length of the shortest travel itinerary. ==== Definition of PTAS <PTAS_en> Below, we will provide a definition for a PTAS. *Definition - Approximation Method:* Given $Pi$ as an NP-hard optimization problem, with the objective function $f_Pi$. We say $cal(A)$ is an approximation method for problem $Pi$ if for $I$ being an input of $Pi$ and $epsilon > 0$ being a parameter, we have $cal(A)(I, epsilon) = s$ satisfying: - $f_Pi (I, s) <= (1 + epsilon) dot "OPT"$ if $Pi$ is a minimization problem. - $f_Pi (I, s) >= (1 - epsilon) dot "OPT"$ if $Pi$ is a maximization problem. Where OPT is the value of the objective function for the optimal solution. The parameter $epsilon$ is also commonly referred to as the approximation factor of the approximation method $cal(A)$. *Definition - Polynomial Time Approximation Scheme:* Given $cal(A)$ as an approximation method for problem $Pi$. We call $cal(A)$ a Polynomial Time Approximation Scheme (PTAS) for $Pi$ if for parameter $epsilon > 0$, the running time of $cal(A)$ is a polynomial in $I$. ==== Reasons for Using PTAS PTAS is a powerful tool when approximating NP-hard problems is necessary. Key differences of PTAS compared to classical methods such as Heuristics and Metaheuristics include: - *Accuracy:* We can choose a small $epsilon$ arbitrarily, so the error is always known beforehand. This is the best result we can expect for NP-hard problems, which we cannot find optimal solutions in polynomial time. - *Speed:* The algorithm always runs in polynomial time for every fixed $epsilon$. However, the definition of PTAS does not consider the running time as $epsilon$ approaches 0. Therefore, an algorithm running in $O(n^(1 / epsilon))$ time or even $O(n^(e^(1 / epsilon)))$ is still considered a PTAS. Hence, for some PTAS, the running time can become impractical when $epsilon$ is too small. PTAS can be applied to combinatorial NP-hard problems such as the knapsack problem, scheduling problem, and many other optimization problems. === PTAS for E-TSP by <NAME> <AroraPTAS_en> <NAME> (Princeton University) devised a PTAS for the E-TSP problem in $O(n "log"^k (n))$ time with an approximation factor of $(1 + epsilon)$, where $k$ is proportional to $1/epsilon$ and $d$ when the graph is pre-embedded. His research on this was awarded the Gödel Prize in 2010. <NAME>'s PTAS for the E-TSP problem represents a significant breakthrough in the field of approximation algorithms, laying the groundwork for many approximation algorithms for other NP-hard problems, such as Minimum Spanning Tree, Minimum Steiner Tree, Minimum Weight Perfect Matching, etc. From here, we will refer to Arora's PTAS theory as Arora PTAS. ===== Illustrative Example <tsp-ex_en> To illustrate the idea of Arora PTAS, let's first consider a specific example. Suppose we have an E-TSP problem, for which we already know the optimal tour as follows: #align( center, figure( image("images/tsp.png"), caption: "An example of an optimal TSP tour" ), ) Now, let's take an arbitrary square from the optimal tour. #align( center, figure( image("images/mpath.png", height: 250pt), caption: "" ), ) From here, we can separate the points within the square into a subproblem. In S. Arora's polynomial approximation theory, this is called the multipath problem. The objective of the problem is to find a set of paths that pass through all the points on the square and all the points inside the square. #align( center, figure( image("images/mpath2.png", height: 200pt), caption: "The subproblem." ), ) // Từ đây, ta gọi tất cả các điểm giao nhau giữa hình vuông và đường đi TSP tối ưu là *portal*. *Statement of the multipath problem:* The input of the problem includes: - A square $S$. - A set of points $V = {v_i in diff S mid i < r}$, where $r in bb(N)^*$ consists of points on the boundary of $S$. - A set of points $X_S subset.eq X$ that need to be visited within square $S$. The problem output: paths $P = {(v_a, x_i), dots , (x_j, v_b)}$, such that $x in P$ for all $x in X_S$. This subproblem can be further subdivided. We can divide the problem until the base case: when there is only $<= 1$ point inside $S$. In that case, the subproblem can be solved by brute force in $O(r) = O(1/epsilon)$ time. // Insert image Arora's main idea is to divide the E-TSP problem into multiple subproblems in the base case ($|X_S| <= 1$), then solve and combine the results. ===== The algorithm *Step 1: Preprocessing Coordinate Data* Multiplying every coordinate $x in X^0$ by a constant doesn't change the essence of the problem. Therefore, we take $X' = {x' = k x | x in X^0}$ and $y' = k y_0$. Next, we round the coordinates of every point $x' in X'$ and point $y$. The goal is to merge points that are too close to each other and consider them as one point. Then we have the new data: $ X = {x = "round"(x') | x' in X'} $ $ y = "round"(y') $ *Step 2: Divide the problem and set up a 4-tree* The division steps of the problem can be described by a 4-tree. First, we take an arbitrary square enclosing all points with a side length of $L$. Then, we divide each square into 4 squares until each square contains only 1 node. #align(center, grid( columns: (auto, auto), column-gutter: 10pt, row-gutter: 10pt, figure( image("images/tree_1.png", height: 100pt), caption: "Space partitioning, step 1." ), figure( image("images/tree_2.png", height: 90pt), caption: "Step 1 tree." ), figure( image("images/tree_4.png", height: 100pt), caption: "Space partitioning, step 2." ), figure( image("images/tree_3.png", height: 90pt), caption: "Step 2 tree." ), figure( image("images/4tree2.png", height: 100pt), caption: "Space partitioning, step 3." ), figure( image("images/4tree.png", height: 100pt), caption: "Step 3 tree." ), ) ) For each node on the tree, we have a corresponding square S. We construct multipath problems, with each problem corresponding to a combination of points $V$ on the edge of square $S$. We solve the problem to find a path $P$ such that $v$ is in $P$ for all $v$ in $V$. However, since we don't know the set of points $v$ in $V$ that the TSP path intersects with the square S beforehand, without loss of generality, we assume that the TSP path intersects the square only at fixed points. These points are called *portals*. *Step 3: Dynamic Programming* We create a dynamic programming table to store all the solutions for the multipath problems for each square under consideration. #align( center, table( columns: 7, table.header( [], [Nút], [Subproblem 1], [Subproblem 2], [Subproblemn 3], [Subproblem 4], [...] ), table.cell( rowspan: 6, align: horizon, rotate(-90deg, reflow: true)[ Nút trên cây ], ), [1], [...], [...], [...], [...], [...], [2], [...], [...], [...], [...], [...], [3], [...], [...], [...], [...], [...], [4], [...], [...], [...], [...], [...], [5], [...], [...], [...], [...], [...], [6], [...], [...], [...], [...], [...], ) ) For the leaf nodes in the tree, representing the base cases (0 or 1 point to pass through), the dynamic programming table will store the solutions for the leaf nodes. For the remaining nodes of the tree, the dynamic programming table stores the positions of the subproblems that yield results. We solve each problem in the dynamic programming table from bottom to top. The leaf nodes are solved sequentially by brute force, and the parent nodes sequentially find the 4 subproblems that yield the shortest paths. *Step 4: Combining solutions* The top row of the dynamic programming table will point to the 4 best subproblems. For each subproblem, traverse down the dynamic programming table to find the best path. ===== Theoretical Foundation of Arora PTAS One of the most significant results in Arora's approximation algorithm theory is the proof of the structure theorem. This theorem establishes a relationship between the predetermined error margin epsilon and the outcome of the approximation algorithm. *Theorem: Structure Theorem:* Given a predetermined error margin $epsilon > 0$. Without loss of generality, assume the minimum distance between nodes is 2 and $L$ is the length of the edge of the square box surrounding every point $x$ in the set of delivery points $X$. For a random vector $a$ in $R^d$, let $X_a = {x + a | x in X, a = (a_1, a_2, ..., a_d) in bb(R)^d, 0 < a_i < L/2} space "for all" space 0 < i <= d}$. Then, with a probability of at least $1/2$, there exists a TSP path with a total length of $(1 + epsilon) dot "OPT"$, cutting the edges on the maximum 4-tree $r$ times at portals. The Structure Theorem demonstrates that with a random translation for every $x$ in $X$, we can approximate the TSP with a predetermined error margin. === Extending Arora's PTAS to solve the 2D Bin Packing Problem The main ideas of Arora's PTAS include: - Grouping similar objects by rounding. - Dividing the large problem into subproblems until reaching the simplest base case. - Solving recursively from the subproblems up to the parent problem using dynamic programming. These methods can also be extended to other problems, including bin packing. Here, we will design a PTAS for the 2D bin packing problem based on Arora's techniques. ==== Data preprocessing The main idea of the algorithm: Similar to Arora's approach of dividing the plane into quarters to create subproblems, we divide bins at certain points, each point forming 2 smaller bin packing problems. #align( figure( image("images/bin_ptas.png", height: 200pt), caption: "Objective: Divide bins into 2 at certain positions" ) ) Choose a parameter a beforehand. With the known error $epsilon$, select objects with lengths $x_i$ in the range $((a - epsilon)/k, a/k)$, where $k = 1, 2, dots$ #align( figure( image("images/binselect.png", height: 200pt), caption: "Horizontal axis: Length of the object. Vertical axis: Height of the object. Red color: Selected points. Blue color: Unselected points." ) ) $forall x_i in ((a - epsilon) / k, a / k)$, we consider $x_i approx a/k$ and iteratively place $x_i$ into each bin in descending order according to $y_i$. The significance of dividing is that, when we have approximated the length $x_i approx a/k$ and set the sub-bin length to $a/k$, we no longer need to consider the length $x_i$ of each item when packing it into the sub-bin. Then the problem becomes a 1D bin packing problem, where we only need to focus on the bin length and the height $y_i$. #figure( image("images/bin_approx.png", width: 200pt), caption: "Items when lining up to their bin approximations" ) // ==== Chia nhỏ bài toán #pagebreak() = Algorithm Implementation == Technologies Used Following the internship company's guidance, I implemented all the mentioned projects in Python, using only basic computational libraries like NumPy, Numba, and graphical libraries like NetworkX, Matplotlib. - *NumPy:* NumPy is an open-source library for the Python programming language, widely used in the fields of data science and scientific computing. Its name is derived from "Numerical Python". NumPy provides powerful data structures such as arrays and matrices, along with a rich set of mathematical functions for manipulating and computing on these data. With NumPy, scientists and engineers can perform complex numerical computations efficiently and quickly, thus supporting data analysis, simulation, and the development of complex algorithms. NumPy serves as the foundation for many other libraries in Python such as SciPy, Pandas, and Matplotlib, contributing to making Python a powerful language in the fields of data science and machine learning. - *Numba:* Numba is an open-source library for Python designed to accelerate the execution speed of Python code by compiling it into machine code at runtime. Using Just-in-Time (JIT) compilation, Numba enables Python functions to achieve speeds nearly equivalent to low-level programming languages like C or Fortran without much alteration in the original source code. This is particularly useful in applications involving data science, scientific computing, and machine learning, where performance is a critical factor. Numba integrates well with popular libraries like NumPy, helping optimize operations on arrays and matrices efficiently. By simplifying the process of accelerating Python code, Numba becomes a powerful tool for developers and researchers in improving the performance of complex computational applications. - *Matplotlib:* Matplotlib is an open-source library for Python widely used to create charts and visualizations of data. This library provides flexible and powerful tools for creating various types of plots such as line plots, bar plots, scatter plots, pie charts, and many others. Matplotlib supports detailed customization of graphic elements, from colors and styles to annotations and labels, allowing users to create visually appealing and professional images. It is highly regarded in the data science and data analysis community for its ease of integration with other libraries such as NumPy, Pandas, and SciPy. Matplotlib is an essential tool for presenting and exploring data, helping researchers and analysts communicate information clearly and effectively. == Spring embedding To generalize the Traveling Salesman Problem (TSP) to the Euclidean Traveling Salesman Problem (E-TSP), we use the spring embedding technique to embed the graph into Euclidean space. *Input:* The distance matrix $A$, describing the graph $G = (V, E)$. *Output:* A 2D array containing the coordinates of the vertices $v in V$ of the graph $G$ after embedding. // Để thực hiện phép nhúng lò xo trong thời gian đa thức, ta sẽ sử dụng thuật toán Barnes-Hut. Ý tưởng của th<NAME> là coi các nút ở xa nhau như một nút thống nhất. == Solving E-TSP using S.Arora's PTAS From the result of the spring embedding, we implement the steps of Arora's PTAS in Numba. *Input:* The coordinates of the points to be visited, represented as a 2D array: $ X^0 = {(x_0, x_1) in R^2} $ *Output:* The coordinates of the points to be visited, ordered from front to back, as a 2D array. === Coordinate Data Since scaling all coordinates by a constant does not change the nature of the problem, we take $X = k X^0$, where $k = O(1/epsilon)$. Next, we round the coordinates of each point. Points that are too close together will be merged into a single point. #align( figure( image("images/image.png"), caption: "Coordinates before and after rounding. Black color: Before rounding. Green color: After rounding.." ) ) === Build 4-tree // TODO: image In Numba, a 4-Tree can be represented using a tree data structure with `@jitclass`. However, the `jitclass` support of Numba is quite limited. Therefore, to speed up computation, the tree structure is represented as an `array` in NumPy. Each row of the `array` contains information about a node in the tree, and each row contains parameters about the corresponding nodes. #align(center, figure( table( columns: 7, table.header( [], [ID], [Parent], [Is active], [Level], [Children], [AABB] ), table.cell( rowspan: 9, align: horizon, rotate(-90deg, reflow: true)[ *Các nút* ], ), [1], [NULL], [TRUE], [0], [2], [...], [2], [1], [TRUE], [1], [NULL], [...], [3], [1], [TRUE], [1], [6], [...], [4], [1], [TRUE], [1], [NULL], [...], [5], [1], [TRUE], [1], [NULL], [...], [6], [3], [TRUE], [2], [NULL], [...], [7], [3], [TRUE], [2], [NULL], [...], [8], [3], [TRUE], [2], [NULL], [...], [9], [3], [TRUE], [2], [NULL], [...], ), caption: "An example of tree representation using a NumPy array" ) ) In which: - ID: Index of the node in the matrix. - Parent node: ID of the parent node. - Active: NULL/TRUE - indicates if the row contains data about the node. - Degree: Degree of the node in the tree. - Child node: ID of the first child node. We only need to store the ID of the first child node; all child nodes of a node will be arranged next to each other. Example: To find the third child node of node $a$, take 2 + the ID of the first child node of $a$. - AABB: Axis-aligned bounding box - Describes the position and size of the square corresponding to this node. // Phần bảng trên trên sẽ tương ứng với cây sau: // TODO: Thêm hình ảnh // === <NAME> - Hut === Divide the problem At each node in the tree, we create portals evenly spaced along the dividing lines. Portals are stored in a 2D array `portallist`. #align(center, figure( image("images/portals_init.png", height: 250pt), caption: "An example of placing portals. The blue dots represent the points the TSP path needs to pass through. The red 'x' marks represent the portals." ) ) Repeat the step above for every node in the tree. #align(center, figure( image("images/portals.png", height: 250pt), caption: "After building the tree and placing portals" ) ) The data of the tree is stored in the following arrays: - `tree:` Information about each node in the tree. - `vertices`: All points to be visited. - `vertices_idx`: Information about the points contained in each node. - For example, if square number 5 contains points 0, 1, 2 in `vertices`, then at `square_index = 5`, we have `vertex_count = 3`, `vertices_idx = [0, 1, 2]`. - `portallist`: List of portals. - `portalref`: List of portals in each square. - For example, if square number 5 of the tree contains portals 0, 1, 2 in `portallist`, then at `square_index = 5`, we have `index_count = 3` and `portal_index = [0, 1, 2]`. Ta #figure( image("images/matrix_schema.svg"), caption: "The structure and relationship between the arrays. The first row of each table is the index of that row in the array. The remaining rows correspond to each element in the section. The arrows describe the relationship between the variables storing the indices.." ) === Dynamic Programming The dynamic programming scheme can be summarized as follows: #align(center, figure( image("images/dp_tsp.png"), caption: "Dynamic programming scheme." ) ) We build the dynamic programming table in the following manner: #align( center, table( columns: 7, table.header( [], [Node], [Subproblem 1], [Subproblem 2], [Subproblem 3], [Subproblem 4], [...] ), table.cell( rowspan: 6, align: horizon, rotate(-90deg, reflow: true)[ Tree nodes ], ), [1], [...], [...], [...], [...], [...], [2], [...], [...], [...], [...], [...], [3], [...], [...], [...], [...], [...], [4], [...], [...], [...], [...], [...], [5], [...], [...], [...], [...], [...], [6], [...], [...], [...], [...], [...], ) ) // Với mỗi ô vuông, ta đánh số thứ tự cho mỗi bài toán con, tương ứng với mỗi tổ hợp portal $V subset partial S$. Để biết tổ hợp portal $V$ ứng với bài toán thứ mấy, ta cần xây dựng ánh xạ từ $V$ vào số thứ tự bài toán. // Không mất tổng quát, vì mỗi portal đặt cách đều nhau, ta quy chúng về các điểm cố định. // *TODO: Ảnh* // Mỗi portal có thể được dùng hoặc không được dùng, vì vậy số bài toán con ứng với mỗi ô vuông $S$ là $2^(|V_S|)$. // *TODO: Ảnh* // Vì vậy, ta có thể dùng biểu diễn nhị phân của tập portal, đổi về số nguyên, lấy kết quả làm chỉ số bài toán. // *TODO: Ảnh mô tả ánh xạ* The dynamic programming table will be iteratively built from children to parents. === Obtaining the results Once we have the dynamic programming table, we proceed to aggregate the results by traversing from the parent node downwards. #align( center, figure( image("images/tsp_res1.png"), caption: "TSP tour build from dynamic programming table" ), ) #align( center, figure( image("images/tsp_res2.png"), caption: "Information contained in dynamic programming table" ) ) // == Implementation of PTAS for the 2D Bin Packing Problem // === Data Preprocessing // ==== Setting up the Range Tree // === Setting up the Subproblems // === Algorithm // === Result Aggregation // #pagebreak() // = Chạy thử == Developing PTAS for the 2D Bin packing problem === Data preprocessing We partition the data in invervals of $((a - epsilon)/k, a/k)$ #figure( image("images/binselect.png"), caption: "Data partitioning" ) For each $k$, we store each item in the interval $((a - epsilon)/k, a/k)$ into a max heap. This way, extracting the max value takes $O(1)$ time. === Defining subproblems Our subproblem will be an instance of the 1D bin packing problem: Given a set if items $I$, each with height $y_i$. Place items into bin $B$ with height $Y$ so that: $ sum_(i in B) y_i <= Y $ === Algorithm Starting with the first bin, iteratively place items in descending order into the bin, until no other items of the same $x_i$ size can be placed. #figure( image("images/bin_1.png", height: 100pt), caption: "Step 1: Pack the bin" ) #figure( image("images/bin_2.png", height: 100pt), caption: "Step 2: Divide the bin" ) #figure( image("images/bin_3.png", height: 100pt), caption: "Bước 3: Solve subproblems in child bins" ) After successfully filling up a bin, we continue to the next, until there are no items left to be placed. #pagebreak() = References <NAME>. 1998. Polynomial time approximation schemes for Euclidean traveling salesman and other geometric problems. J. ACM 45, 5 (Sept. 1998), 753–782. https://doi.org/10.1145/290179.290180 <NAME> and <NAME>. “Approximating geometrical graphs via “spanners” and “banyans”.” Symposium on the Theory of Computing (1998). <NAME>. 2010. Approximation Algorithms. Springer Publishing Company, Incorporated. <NAME>, <NAME>, and <NAME>. 2005. Euclidean distortion and the sparsest cut. In Proceedings of the thirty-seventh annual ACM symposium on Theory of computing (STOC '05). Association for Computing Machinery, New York, NY, USA, 553–562. https://doi.org/10.1145/1060590.1060673 #pagebreak() #align( center, text( "Khoa Toán - Cơ - Tin học Trường ĐH Khoa học Tự nhiên - ĐHQGHN", weight: 900, ), ) #v(40pt) #align( center, text( "NHẬN XÉT THỰC TẬP", weight: 900, size: 20pt, ), ) #v(20pt) #align(left, grid( columns: (auto, auto), column-gutter: 70pt, row-gutter: 15pt, [Công ty thực tập:], [], [Người hướng dẫn:], [], [Thời gian thực tập:], [], [Họ và tên sinh viên:], [Phạm Hoàng Hải], ) ) #v(30pt) 1. Ý thức làm việc của sinh viên: ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ 2. Khả năng làm việc/học hỏi: ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ 3. Mức độ hoàn thành những nhiệm vụ được giao: ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ 4. Xác nhận công việc được báo cáo có đúng như công việc được giao? ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ 5. Những vẫn đề cần góp ý với thực tập sinh/ nhà trường để công việc có thể tiến hành tốt hơn: ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ ........................................................................................................................................................................................ 6. Điểm đánh giá (theo thang điểm 10): ........................................................................................................................................................................................ #v(50pt) #align( center, grid( columns: (auto, auto), column-gutter: 100pt, row-gutter: 20pt, [], [_Hà Nội, ngày ...... tháng 08 năm 2023_], [*Xác nhận của người đánh giá*], [*Xác nhận của doanh nghiệp*], [], [(kí và đóng dấu)], ) )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/unbalanced_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page $ 1/(2 (x) $ $ 1_(2 y (x) () $ $ 1/(2 y (x) (2(3)) $
https://github.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024
https://raw.githubusercontent.com/OverflowCat/BUAA-Digital-Image-Processing-Sp2024/master/chap04/helper.typ
typst
#let problemCounter = counter("q") #let Q = (body) => { set text(weight: "semibold") problemCounter.step() problemCounter.display("1、") body } #let FT = $cal(F)$ #let IFT = $FT^(-1)$ #let CONV = sym.star.filled #let SUMOO = $sum^(oo)_(n=-oo)$ #let INTOO = $integral^(oo)_(-oo)$
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/beurteilen_bewerten/beispiel_kurzkontrolle.typ
typst
Other
#import "/src/template.typ": * == Bewertung durch Bewertungsmatrizen Bewertungsmatrizen sind #ix("Erwartungshorizonte", "Erwartungshorizont"), die eine standardisierte Möglichkeit für die Kontrolle eines Produkts von SuS darstellen. Durch Sie wird für etwa eine Lernerfolgskontrolle oder Klausur ein allgemeiner Maßstab festgelegt, er an alle SuS angelegt wird. Das Vorgehen ist folgendes: + *Festlegung der Kriterien:* Zuerst werden die Kriterien des Produkts festgelegt. Was charakterisiert das Produkt? Nach welchen Kriterien soll es bewertet werden? + *Niveaustufen:* Danach wird jedes Kriterium in mehrere Niveaustufen unterteilt. Die Kriterien können unterschiedlich stark ausgeprägt sein und in unterschiedlicher Gründlichkeit erfüllt worden sein. + *Bepunktung:* Die höchste Niveaustufe legt die Maximalpunktzahl fest, es folgt eine Abstufung der anderen Niveaustufen. Die Bewertung der #ix("Anforderungsbereiche", "Anforderungsbereich") findet unterschiedlich gewichtet statt. Wenn in einer Leistungsüberprüfung 100% der Punkte erreichbar sind, dann sind davon 30% für den #ix("Anforderungsbereich") I, 40% für den #ix("Anforderungsbereich") II und wiederum 30% für den #ix("Anforderungsbereich") III gedacht. Auf der folgenden Seite finden Sie eine Lernerfolgskontrolle inklusive eines #ix("Erwartungshorizontes", "Erwartungshorizont"), der durch eine Bewertungsmatrix beschrieben wird. #pagebreak(weak: true) #include "/src/lernerfolgskontrollen/uebung01/main.typ" #pagebreak(weak: true)
https://github.com/takotori/PhAI-Spick
https://raw.githubusercontent.com/takotori/PhAI-Spick/main/main.typ
typst
#import "ost-summary-template.typ": * #show: doc => conf(lecture: "Physik Anwendung für Informatik", authors: "<NAME>, <NAME>, <NAME>", doc) #include "sections/grundlagen.typ" #include "sections/kinematik.typ" #include "sections/messfehler.typ" #include "sections/kraft.typ" #include "sections/energie.typ" #include "sections/arbeit.typ" #include "sections/leistung.typ" #include "sections/kosmologie.typ" #include "sections/fadenpendel.typ" #include "sections/analysis.typ" #include "sections/aufgaben.typ" #include "sections/weiteres.typ"
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/06-features-2/substitution/substitution.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/components.typ": note #import "/lib/glossary.typ": tr #show: web-page-template // Types of Substitution Rule == 各种类型的#tr[substitution]规则 <section:substitution-rule-types> // The simplest type of substitution feature available in the `GSUB` table is a single, one-to-one substitution: when the feature is turned on, one glyph becomes another glyph. A good example of this is small capitals: when your small capitals feature is turned on, you substitute "A" by "A.sc", "B" by "B.sc" and so on. Arabic joining is another example: the shaper will automatically turn on the `fina` feature for the final glyph in a conjoined form, but we need to tell it which substitution to make. `GSUB`表中最简单的#tr[substitution]特性是一换一#tr[substitution]。当这类特性开启时会让某个#tr[glyph]变成另一个。我们之前介绍过的小型大写字母特性会把`A`变成`A.sc`,把`B`变成`B.sc`,这就是一个不错的例子。另一个例子是阿拉伯文中的连体变形,#tr[shaper]会自动为连体形式的尾部#tr[glyph]打开`fina`特性,我们就在这个特性里编写规则来告诉#tr[shaper]需要如何进行#tr[substitution]。 // The possible syntaxes for a single substitution are: 一换一#tr[glyph]替换的语法有如下几种: ```fea sub <glyph> by <glyph>; substitute <glyphclass> by <glyph>; substitute <glyphclass> by <glyphclass>; ``` // The first form is the simplest: just change this for that. The second form means "change all members of this glyph class into the given glyph". The third form means "substitute the corresponding glyph from class B for the one in class A". So to implement small caps, we could do this: 第一种形式最简单,就是把一个#tr[glyph]换成另一个。第二种形式的含义是将某个#tr[glyph]类中的所有成员都换成给定的#tr[glyph]。第三种形式表示用B#tr[glyph]类中的对应#tr[glyph]#tr[substitution]A类中相同位置的#tr[glyph]。所以,我们可以这样实现小型大写字母特性: ```fea feature smcp { substitute [a-z] by [A.sc - Z.sc]; } ``` // To implement Arabic final forms, we would do something like this: 而阿拉伯字母的词尾形式可以这样实现: ```fea feature fina { sub uni0622 by uni0622.fina; # Alif madda sub uni0623 by uni0623.fina; # Alif hamza sub uni0624 by uni0624.fina; # Waw hamza ... } ``` // Again, in these particular situations, your font editing software may pick up on glyphs with those "magic" naming conventions and automatically generate the features for you. Single substitutions are simple; let's move on to the next category. 值得一提的是,在这些特定的例子中,你的字体编辑软件可能会根据#tr[glyph]的这种“约定俗成”的命名方式自动为你生成对应的特性。一换一#tr[substitution]就是这么简单,我们继续来看下一类吧。
https://github.com/pepega007xd/slplugin
https://raw.githubusercontent.com/pepega007xd/slplugin/master/ip1_report/main.typ
typst
#import "template.typ": * #let ls(from, to) = {$ "ls"(from, to) $} #let sep = $- #h(-0.12em) ast.circle$ #let nil = $"nil"$ #show: project.with( title: "Shape Analysis Using Separation Logic", authors: ( "<NAME>", ), abstract: [ This work describes the implementation of a static analysis of C programs, that tries to find bugs related to dynamic allocation of memory. The analysis is implemented using the Frama-C framework, and it is done by dataflow analysis using a solver for separation logic. This work also discusses possible improvements to this prototype. ], ) = Introduction The way dynamic memory allocation is handled is one of the key aspects that determines the runtime performance of a language. The usual choice for high-level languages is garbage collection, which tracks allocations at runtime, and frees memory when an algorithm determines it is no longer reachable. This has a performance impact that can be unacceptable in certain applications, such as embedded systems. Other languages, notably C and C++, let the user's code manage memory manually. While being the most performant option, this allows for a range of errors resulting from incorrect handling of allocated memory. For example, null pointer dereferences are a common mistake, where a fallible function indicates an error by returning a `NULL` pointer, and the programmer forgets to check for it. Use-after-free is a situation where a pointer to a freed allocation is used to read or write data to memory, resulting in undefined behavior. The opposite situation, where the user does not free memory when it is no longer needed, is called a memory leak. Another common error is double free, where a pointer to already freed allocation is passed to the `free` function again, resulting again in undefined behavior. To mitigate these problems, a number of methods has been developed. One option is the instrumentation of program binaries with extra code that is able to detect invalid memory accesses at runtime, and safely stop the program. An example of this is Valgrind @valgrind, or LLVM's AddressSanitizer @asan. While being efficient at mitigating the security risks associated with memory errors, these tools come with a performance penalty, and obviously cannot be used to check programs ahead-of-time. Some languages are built to prove program's memory safety statically during compilation; this is achieved by placing additional restrictions on the code, as for example Rust does with its ownership and borrowing rules. While being a reasonably safe option, this makes implementing some programs difficult, or requires writing unsafe code. Static analysis tools exist for other languages, including C, which will be the topic of this work. For example, Facebook's static analyzer Infer can perform analyses of memory allocations. = Frama-C framework Frama-C @frama_c is a framework for building analysis tools of C99 source code. Frama-C itself is written in the OCaml programming language. Unlike other tools, which focus in finding common bugs using heuristics, Frama-C specializes on verification tools, which guarantee that after successful completion, the program is correct. The framework itself is composed of a kernel, multiple plugins, and a GUI to present the results of analyses. The kernel provides common functionality for multiple plugins. The main part is the _C Intermediate Language_ (CIL) @cil, which the Frama-C kernel constructs for use within plugins, as well as an API to effectively work with it. CIL has the form of an abstract syntax tree of the input source code, with extra information added to it. This includes types of variables, whether a variable is initialized at a certain node, and other information. Frama-C also transforms the input code, making operations like type casts explicit, and otherwise makes the code more suitable for static analysis. For example, all `return` statements in a function are replaced with `goto` statements to a single `return` at the end of the function. A complete description of CIL can be found in module `Frama_c_kernel.Cil_types` of the Frama-C API documentation @api_documentation. One of the functions of Frama-C is to help with the development of custom analyses. This is done using its plugin system, where a separate plugin binary is built and linked dynamically to the Frama-C runtime. Frama-C then handles command-line argument parsing, reporting results, storing intermediate states of analyses, and exposes APIs to the plugin for access to input's CIL. == Dataflow analysis Besides a general framework for crafting analyses, Frama-C provides generic implementations of common algorithms used for static analysis. One of these is dataflow analysis, implemented in module `Frama_c_kernel.Dataflow2`. Dataflow analysis works by assigning an initial value to each node of a Control Flow Graph (CFG), and then systematically updating values of nodes using a transfer function, following the edges between them. When a node is reached for the second time, the data for this node is computed again based on the data from the previous node, and then joined with the previous data stored for the node. Typically, a CFG is a structure where a node represents a basic block -- a sequence of instructions that will be executed in order, with no loops or conditionals. Edges then represent the control flow of a program - branching and loops. However, Frama-C implements dataflow analysis in a slightly different way. In dataflow analysis as it is implemented in Frama-C, instructions (`Cil_types.instr`) have a separate transfer function from statements (`Cil_types.stmt`). Instruction is a kind of statement that does not change the control flow of the current function, such as variable definition, assignment, or function call. To implement a dataflow analysis, the user needs to provide the type of data that will be stored and updated for each node of the CFG, and the implementation of the following functions. Before running the analysis, the data for the first statement must be set manually. - `computeFirstPredecessor` -- this function is called when the analysis reaches a statement that has no data associated with it. The input for this instruction is the result of previous statement's transfer function, and the statement itself. The result of this function is the initial state for the given statement, which will be stored. Note that because you set the initial state for the first statement manually, this function is not called for the first statement. - `doStmt` -- this function is used by the transfer function for statements -- it gets the statement itself, and data provided by previous statement's transfer function, and it decides what to do. One option is not to continue the analysis of this statement, another option (default) is to continue the analysis of the inside of this statement, and the third is to also continue, but with modified data. Note that the full transfer function for compound statements (if, loop, ...) is implemented by the dataflow module itself, the user is not supposed to call `doInstr` inside `doStmt`. Also note that the result of the full transfer function -- the new computed data for each statement, is not stored. It is only sent to the next statement's transfer function. - `doInstr` -- this is the transfer function for instructions, it receives data from the englobing statement, and generates new data that will be used by the transfer function of the englobing statement. Note that the result of `doInstr` is also not stored, only sent to the transfer function that called `doInstr` internally. - `combinePredecessors` -- this is the join operation. It is called when the analysis computes a new state for a node that already has some data associated with it. This includes situations, where the analysis goes through two branches of an `if` statement, and then joins data from both branches on the statement immediately following the conditional block. Input for this function is the statement itself, an old state -- the data currently stored for the statement, and a new state -- the data that was just computed by the transfer function. The returned value is then stored as the data for this statement. - `doGuard` -- this function is called when an `if` statement is reached. It receives the result of the transfer function for the `if` statement, and the condition expression, and generates two states, each to be used in one of the branches. - `doEdge` -- called between analyzing two statements. The function receives both statements, and the result of the first statement's transfer function. The function can modify this data, and the modified version will be passed into the second statement's transfer function. Note that this is not the full API required for implementing dataflow analysis in `Dataflow2` module, but the other functions, such as pretty-printers for stored data, are not important to the actual analysis, and are therefore omitted. = Separation logic A common technique in program analysis is to generate logical formulae describing the code, and then to use a solver to prove the correctness of the program. However, earlier analyses of programs with dynamic memory have faced a problem with globality -- an abstract state of the program would contain the description of the whole heap in such a way, that an update of a single value would require updating the whole program state. Separation logic (SL) aims to solve this inefficiency by describing the heap in a way that allows for local updates of the heap. In this work, I will describe the syntax and semantics of SL @separation_logic, for which <NAME> implemented a solver called Astral @astral_github. Testing the solver's performance on formulae generated in shape analysis is a secondary goal of this work. == Syntax #let Var = $bold("Var")$ Let $x,y in Var$, where #Var is an infinite set of variables, with a special variable $nil in Var$. The syntax of SL is defined by the following grammar. $ phi ::=& x = y | x != y & "(pure atoms)" \ &| x |-> y | ls(x,y) & "(spatial atoms)" \ phi ::=& phi and phi | phi or phi | phi and_not phi | not phi #h(1cm) & ("boolean connectives") \ phi ::=& phi * phi | phi sep phi & "(spatial connectives)" $ The atomic formulae $x = y$ and $x != y$ simply describe equality and inequality of two variables, $x |-> y$ corresponds to a pointer from $x$ to $y$. The atom $ls(x,y)$ describes a sequence of pointers from $x$ to $y$, or in other words, an acyclic linked list. The boolean connectives have their usual meaning, the spatial connective $phi * phi$, called separating conjunction, says basically that the heap can be split into two disjoint parts, each satisfying one of the formulae. The septraction operator #sep has roughly the following meaning: formula $phi_1 sep phi_2$ is satisfied for all heaps, for which exists another heap satisfying $phi_1$, which can be merged with our heap, together satisfying $phi_2$. == Semantics #let Loc = $bold("Loc")$ The models of SL formulae are so-called stack-heap models. Let #Loc be an ordered set of memory locations, then stack $s$ is a partial function from #Var to #Loc, and heap $h$ is a partial function from #Loc to #Loc, where $h(s(nil)) = bot$. The symbol $bot$ says that the function $h$ is not defined for this input, which corresponds to an invalid memory access in the analyzed program. Stack-heap model is then simply a pair $(s,h)$. The semantics of equality and inequality atoms are satisfied on all models, where $s(x) = s(y)$, or $s(s) != s(y)$ respectively, and the heap is empty. Points-to atom $x |-> y$ is satisfied on a stack-heap model, where the heap contains only a single allocated location, $h = {s(x) |-> s(y)}$. List segment predicate is satisfied on every model where either $s(x) = s(y)$ and the heap is empty, or where the heap is a series of distinct allocated locations $h = {l_0 |-> l_1, ..., l_(n-1) |-> l_n}$ of length at least $n=1$, where $s(x) = l_0$ and $s(y) = l_n$. Semantics of boolean connectives are defined as usual. Separating conjunction $phi_1 * phi_2$ is satisfied on models, for which exist two heaps $h_1, h_2$, such that $ (s, h_1) tack.double phi_1 and (s, h_2) tack.double phi_2 and h_1 union.plus h_2 != bot and h = h_1 union.plus h_2 . $ Septraction is defined similarly, $ (s,h) tack.double phi_1 sep phi_2 <=> exists h_1: (s, h_1) tack.double phi_1 and h_1 union.plus h != bot and (s, h_1 union.plus h) tack.double phi_2 . $ The operation $union.plus$ is defined as a union of two heaps, but it is defined only for heaps, whose domains are disjoint, and also share only named locations, i.e. locations, which are in the image of $s$. == Fragment used for analysis Although any formula generated by the mentioned grammar is a valid SL formula, I will use just a subset of all valid SL formulae. This fragment has the form $phi = phi_1 * phi_2 * ... * phi_n$, where $phi_1, ..., phi_n$ are atomic formulae for equality, inequality, and for points-to relation. Note that pure atoms are satisfied on empty heap only, which is why separating conjunction is used for both spatial and pure atoms. = Shape analysis Shape analysis is a kind of static analysis that aims to detect the shapes of data structures in the heap, such as linked lists, trees, and variations of those, and to use this knowledge to describe the state of a program's memory in more detail than would be otherwise possible. In @shape_analysis, the authors propose a method to analyze programs with linked lists using separation logic for better scalability. However, they work with SL of slightly different semantics (pure atoms are satisfied on any heap), and they also implement shape analysis of a minimal language. They also do not use a dedicated solver. My objective is to adapt their method to support at least a part of the C programming language, and to work with SL as implemented by Astral. == Implementaion Current state of the plugin that that it can analyze programs without loops, function calls except allocation functions, composite data structures, multiple dereferences on any side of assignments, and global variables. Although the analysis is not very useful at the moment, most of these features can be implemented without any new work with the formulae themselves, merely by preprocessing the CIL AST and adding some heuristics. More on this in @future_work. Let us start with the type of data that will be stored for each CFG node during the dataflow analysis. Currently, this is a list of SL formulae (`SSL.t list`). Each formula represents a possible state the program could be in. For example, after a statement `x = malloc(sizeof(void *));`, the program's memory could be described by any of the two formulae $phi_1 = (x |-> y)$, or $phi_2 = (x = nil)$. This expresses the two possible outcomes of calling `malloc` -- either the allocation succeeded, and x is now an allocated memory location, or it failed, and `x` is equal to `NULL`. The $y$ in the formula simply represents an arbitrary memory location that x is now pointing to, and it is existentially quantified. This corresponds to the fact that the allocated memory is uninitialized. The implementation of the analysis itself is done through the `Dataflow2` module API. - `computeFirstPredecessor` -- Currently, this function is implemented as identity. - `doInstr` -- As mentioned, this is the the transfer function for instructions, and therefore much of the logic of the analysis is implemented here. Mind that an instruction in CIL naming convention is any C statement that doesn't affect control flow of the current function. Note that a function call is also considered an instruction. As input, the function gets the instruction itself, and the state of the previous analyzed instruction, and it must return new state for this instruction based on the inputs. For this analysis, I am interested in the following instructions: `LocalInit`, `Set`, `Call`. - `LocalInit` is the initialization of a local variable. Initializations of non-pointer variables are currently ignored, and previous state is returned. For pointer variables, the action depends on the initializing value. If the variable is initialized with a call to an allocation function (currently, these are detected simply by name `malloc`, `calloc`, `realloc`), for each previous state, two new states are generated. One of them represents successful allocation, and therefore $("<name>" |-> "<fresh>")$ is appended to it using separating conjunction ($*$). `name` is simply the name of newly initialized variable, and `fresh` is a globally unique (fresh) variable name generated by Astral. I might extend this naming later, when I add support for loops. Any other initialization is currently considered to be an initialization with a constant (`NULL`), and therefore the previous state is extended by $("<name>" = nil)$. - `Set` is an assignment instruction. Again, this analysis is only interested in assignments to pointer variables, or assignments where the right-hand side contains a dereference. For other assignments, previous state is returned. Simple assignment `a = b;`, where the type of the variables is a pointer type, results in the following change to the previous state. First, all occurences of the variable `a` in the formula are substituted with a new, unique name, and then $a = b$ is appended to the formula with $*$. Assignment of dereferenced variable, `a = *b;`, is more complicated. We must first find the variable, to which `b` is pointing, and then do essentially the same as with simple assignment. To find the variable, to which `b` is pointing to, a transitive closure of equality $C(b)$ is found for `b`, and then the set of all variables that are pointed to by this closure is found simply by iterating through all the atoms of the formula: $T = {t; exists c in C(b) : c |-> t}$. This set $T$ ("target") can be empty -- this corresponds to the possibility of dereferencing an invalid pointer in the program. In this case, the analysis is stoppped. $T$ can contain exactly one element $T = {t}$, then `a` is substituted with a new variable name as in the first case, and atom $a |-> t$ is appended to the substituted formula. This is the computed state. $T$ cannot contain more than a single element, because such formula would be unsatisfiable. Unsatisfiable formulae are filtered out in `doEdge`. For write to dereferenced variable `*a = b`, the single-element set $T = {t}$ with the target of `a` is again found, and then the spatial atom $s |-> t$ is changed to $b |-> t$. `s` is a member of equivalence class $C(a)$. Notice that in this case, no substitutions are done, because no additional equality is added. - `Call` is a function call instruction. Currently, only allocation functions are supported. The implementation is the same as in allocation during initialization, with the extra step that before creating two states for two outcomes of the allocation, name of the variable `x` in `x = malloc(sizeof(void *));` would be first subtituted in the whole formula with a fresh variable. #let old = $phi_"old"$ #let new = $phi_"new"$ - `combinePredecessors` -- This function is called when the analysis reaches a CFG node for the second time, and computes new data for this node. `combinePredecessors` gets the old state and the new state as input parameters, and returns these states joined together, as well as information on whether the old state was updated in any way. This is then used by the dataflow algorithm to decide whether to continue updating nodes following this one. Note that the state of a CFG node is internally a list of formulae, but the meaning is a logical disjunction of these (the models of a state for single CFG node is the union of models of all the formulae in the list). In theory, we could simply take the old state #old and new state #new, and check the entailment $old tack.double new$. If this were true, all models of the new state would have been contained in the old state, and we could have returned that the state had not changed. Otherwise, we would have returned the disjunction of new and old states (internally, a list concatenation). However, this would be imprecise, a single formula in #new, of which a single model would not be a model of #old would cause adding the entirety of #new. Instead, I take the formulae of new state $new_1, new_2, ..., new_n$, and for each one check the entailment $new_i tack.double old$. If this is false, $new_i$ it is added to #old, otherwise it is discarded. Finally, if any formulae were added to #old, the function would return that state for this CFG node was changed. - `doStmt` -- This function decides, whether to continue with analysis upon reaching a statement. This is independent of the actual algorithm for dataflow analysis, which decides when the analysis is complete -- that is, when the state of all statements cannot be updated. Currently, this is set to always continue analysis. - `doGuard` -- called when the analysis reaches an `if` statement. The function gets the state from previous node and the condition expression, and returns the states to use in each of the branches. Currently, all conditions that are not in the form `a == b` or `a != b` are considered nondeterministic. When reaching nondeterministic condition, the analysis simply uses the input state as the state for both branches, since it gained no additional information about what is true in the branches. If the condition is `a == b`, then all formulae of input state $phi_"in"_i$ are tested separately using the following method. For "then" branch, each formula is appended with $(a = b)$ using separating conjunction, and checked for satisfiability. Unsatisfiable formulae are not passed into the "then" branch. For the "else" branch, the same method is used, only the formula is appended with $(a != b)$. This way, only satisfiable formulae are passed into their respective branches, simplifying further analysis. For the case of condition `a != b`, the algorithm is the same, only the states for the two branches are swapped. - `doEdge` -- called between the updates of nodes, it can modify the state that is sent from previous node to next one. In this function, satisfiability of all formulae of the state is checked, and unsatisfiable formulae are removed from the state. All formulae are also simplified using Astral's `Simplifier.simplify` function, which performs many simple syntactic optimizations of the formula without changing its semantics, such as flattening of nested operations. The entrypoint of the analysis is the function `run`, which fetches the entrypoint of the input code, sets up the initial state for the analysis (which is just a formula describing the empty heap, here represented as $(nil = nil)$). Then it runs the analysis to completion, and prints out the result (a list of formulae for each statement). === Example The following table contains the analysis results of a simple program. At the end, you can see that the original variable `x` was renamed to a fresh variable. Fresh variables are marked $f_n$, each having a unique index. #let c(code) = raw(lang: "c", code) #let null = $"nullptr"$ #table(columns: 2, c("int *nullptr = NULL;"), $ null = nil $, c("void *x = malloc(sizeof(void *));"), $ null = nil * x |-> f_0 \ null = nil * x = nil $, c("if (x == nullptr) {"), $$, c(" ;"), $ null = nil * x = nil $, c("} else {"), $$, c("*(void**)x = malloc(sizeof(void *));"), $ null = nil * x |-> f_0 * f_0 |-> f_1 \ null = nil * x |-> f_0 * f_0 = nil $, c("}"), $$, c("; // join of branches"), $ null = nil * x = nil \ null = nil * x |-> f_0 * f_0 |-> f_1 \ null = nil * x |-> f_0 * f_0 = nil $, c("x = nullptr;"), $ null = nil * f_2 = nil * x = null \ null = nil * f_3 |-> f_0 * f_0 |-> f_1 * x = null \ null = nil * f_4 |-> f_0 * f_0 = nil * x = null $, ) = Future work <future_work> Let us address each of the deficiencies of the current implementation, and possible ways to solve them. First, there is the issue of loops. In the current state of the plugin, there is actually no problem with analysis of loops in general, only with pointer manipulation inside loops. For these programs, the analysis would not terminate. The first issue is with initializations within a loop. Currently, variable names inside formulae used for analysis are taken from the source code without any renaming, therefore when the analysis reaches an initialization twice, it produces an invalid state, because it assumes that such a variable does not exist, but it in fact does, from the previous iteration of the loop. This can be solved in two ways. One option is to always do a substitution of the name of variable being initialized, and the other is to preprocess the code in such a way, that the initialization will always be outside of the loop. This will require renaming variables in the CIL AST representation, since pulling a variable to outer scope might cause a name collision. Ideally, all variable initializations should be pulled into the top scope of the function, to avoid further problems with conflicting variable names in nested scopes, which I have not yet encountered. Not considering initializations, other pointer manipulations done inside a loop will technically produce correct formulae, but these will grow without any limits as the analysis progresses. For example, consider a program that constructs a linked list using a while loop with nondeterministic condition. In each iteration, the formula would get longer by a single points-to atom. This can be solved using the list segment atom $ls(x,y)$. Since it represents a sequence of any size, we can abstract the growing chain of pointers into a single list segment. Note that this has limitations, when abstracting the formula $x |-> y * y |-> x * ...$ into $ls(x,z) * x != z * ...$, $y$ cannot be referenced in the rest of the formula, because we would lose the information that it points to $z$. Also, list segment represents an _acyclic_ linked list, which means that $x != y != z$ must hold. Introducing list segments into the state formulae will also mean that most other parts of the analysis will have to be extended to accommodate the possibility of $x$ pointing to an unnamed location inside the list segment. With this, the analysis should be able to process basic programs working with linked lists. Another shortcoming of the current implementation is the limited shape of statements supported by the analysis. However, by supporting the four basic statements, all statements that are a combination of these can be broken down into a sequence of the basic ones: ```c a = b; a = *b; *a = b; a = malloc(...); ``` Take, for example, the statement `*a = **b;`. We can break it down into a sequence of the following statements, using fresh variables: ```c tmp_1 = *b; tmp_2 = *tmp_1; *a = tmp_2; ``` This can be done algorithmically, in another preprocessing step on the CIL AST. Another problem is that currently we can only work with simple pointer types, but for analysis of real programs, the analysis must support structs implementing the linked list ADT. I propose that in yet another preprocessing pass, accesses to the "next" field of the linked list struct are to be rewritten to a simple dereference, whereas accesses to other fields of the struct would be simply ignored. Of course, accesses to other fields over a pointer (eg. `list->data = 5;`) would be checked, whether `list` is allocated, without actually changing the formula. Such a rewrite might look like this: ```c list->next = malloc(...); tmp = list->next; tmp2 = list2->data; ``` could be transformed to ```c *list = malloc(...); tmp = *list; // this line would be omitted, only list would be checked, whether it is allocated ``` The question of how to detect, which field of a struct is the "next" field probably does not have a perfect solution, but a heuristic is easy to implement. If a struct has a single field with a type of pointer to itself, this field would be considered the "next" field. If more than one self-referential pointer is found, it would indicate another data structure, such as a binary tree, or doubly linked list. Another option is to rely on user to annotate the structs and their fields manually. Another missing feature is the analysis of function calls, by which I mean other than allocation functions. Analysis of the `free` function is also not implemented, but it should only require calling existing code. It should suffice to find the target of the freed variable by looking at points-to atoms from the transitive closure of freed variable, and then to simply remove the points-to atom. User-defined functions are, however, a completely different issue. The original paper @shape_analysis does not include functions in its minimal language, so the following method is just my proposition. When calling a function, variables inside the state formula passed as arguments will be renamed to their corresponding parameter names, and this state will be passed as the initial state for the analysis of the function. After returning, the returned value would be renamed back to the variable name the call result was assigned to. This would require all variable names to be unique across functions, and when leaving a function, all of its local variables would have to be renamed to fresh names -- this corresponds to a memory leak when returning from a function, where a local variable holds a pointer to allocated memory. Even simpler way to deal with function calls could be to inline everything into `main`. Note that this would not be applicable to recursive functions. Global variables should not be hard to implement, once analysis of functions is already implemented. Global variables would simply have the same name across all functions they are used in. Their definitions could then simply be moved to the beginning of the entrypoint function (`main`). When calling another function, global variables used in the state formula would be passed into the called function without any renaming. Static variables declared inside functions could be first converted to global variables. = Conclusion Even though the current implementation of the analysis is not capable of processing real-world programs, it shows promise that it will be extendable to cover most C language features to some extent. In theory, most of the work on the analysis itself should already be done, the main part that remains to be implemented is the abstraction to list segments. Besides that, most other work lies in preprocessing the input code to simpler form so that can be analyzed by the existing implementation. #bibliography("references.bib") // TODO: set T cannot be larger than 1 element ?
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/代数学二/作业/hw2.typ
typst
#import "../../template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: note.with( title: "作业1", author: "YHTQ", date: none, logo: none, withOutlined : false, withTitle :false, ) (应交时间为3月12日) #set heading(numbering: none) = 19 由于 $D(f)$ 构成拓扑基,显然所有非空开集相交当且仅当任两个拓扑基相交,因此只需考虑 $D(f)$ 的相交性,注意到: $ D(f), D(g) != emptyset <=> f, g in.not N \ D(f) sect D(g) != emptyset <=> D(f g) != emptyset \ (D(f), D(g) != emptyset -> D(f) sect D(g) != emptyset) <=> (f, g in.not N -> f g in.not N) \ $ 前式前者是说 $Spec(A)$ 不可约,后者是说幂零根是素理想,得证 = 20 == i) 任取 $overline(Y)$ 非空开集,记为: $ A sect overline(Y), $ 其中 $A$ 是 $X$ 中开集\ 断言 $A sect Y$ 非空,否则有 $Y subset X - A => overline(Y) subset X - A => A sect overline(Y) = emptyset$\ 这表明 $A sect Y$ 在 $Y$ 中稠密,当然在 $overline(Y)$ 中稠密,进而 $A sect overline(Y)$ 也在 $overline(Y)$ 中稠密,得证 == ii) 取 $Y$ 是一个不可约子空间,试图利用 Zoun 引理,设: $ Sigma = {Y' | Y subset Y', Y' "irreducible" } $ 并以包含作为偏序关系。设 $Sigma'$ 是 $Sigma$ 的全序子集,断言: $ union.big Sigma' in Sigma $<claim> 进而成为全序子集的上界,由 Zoun 引理即得极大元。\ 为了验证@claim,只需证明 $union.big Sigma'$ 不可约\ - 任取 $union.big Sigma'$ 中两个非空开集,记作: $ A sect union.big Sigma', B sect union.big Sigma' != emptyset $ 其中 $A, B$ 是 $X$ 中开集\ 由上两式非空,可知: $ exists Y_1, Y_2 in Sigma': A sect Y_1 != emptyset, B sect Y_2 != emptyset $ 但由于 $Sigma'$ 中有全序,必有 $Y_1 subset Y_2$ 或 $Y_2 subset Y_1$,不妨设前者成立,于是: $ A sect Y_1 subset A sect Y_2 != emptyset $ 从而由 $Y_2$ 的不可约性: $ A sect Y_2, B sect Y_2 != emptyset => (A sect Y_2) sect (B sect Y_2) != emptyset $ 因此: $ (A sect Y_2) sect (B sect Y_2) subset (A sect union.big Sigma') sect (B sect union.big Sigma') != emptyset $ 得证 == iii) 设 $Y$ 是按上式给出的极大不可约子空间,由 $i)$ 知 $overline(Y)$ 也不可约,进而由极大性当然有 $Y = overline(Y)$ 也即 $Y$ 是闭集\ 此外,显然单点集是不可约的,因此每个点都包含在一个极大不可约子空间中\ 注意到 Hausdorff 空间中不同两点产生不交的开邻域,显然其中的不可约子空间只能是单点集 == iv) 首先,不难验证通过对应原理 $V(I)$ 与 $Spec(A quo I)$ 同胚,从而 $V(I)$ 不可约当且仅当 $sqrt(I)$ 是素理想\ 因此 $V(I) = V(sqrt(I))$ 是某个素理想的零点集,而这个素理想当然应该是极小的素理想 = 21 #let phi = math.phi.alt == i) $ p_y in phi^(*-1) (X_x) &<=> phi^(*)(p_y) in X_x\ &<=> x in phi^*(p_y)\ &<=> x in phi^(-1)(p_y)\ &<=> phi(x) in p_y\ &<=> p_y in Y_(phi(x))\ $ 证毕 == ii) $ p_y in phi^(*-1) (V(alpha)) &<=> phi^(*)(p_y) in V(alpha)\ &<=> alpha subset phi^*(p_y)\ &<=> alpha subset phi^(-1)(p_y)\ &<=> phi(alpha) subset p_y\ &<=> p_y in V(phi(alpha))\ &<=> p_y in V(phi(alpha) B)\ $ == iii) 分别验证 - $phi^*(V(b)) subset V(Inv(phi)(b))$\ 在上一问过程中可以发现 $ phi^(* -1)(V(Inv(phi)(b))) = V(phi(Inv(phi)(b))) supset V(b)\ $ 表明: $ phi^*(V(b)) subset phi^*(phi^(* -1)(V(Inv(phi)(b)))) subset V(Inv(phi)(b)) $ - $V(Inv(phi)(b))$ 是闭集:显然 以上两者给出 $overline(phi^*(V(b))) subset V(Inv(phi)(b))$ - 设 $phi^*(V(b)) subset V(x)$,验证 $V(Inv(phi)(b)) subset V(x)$,这将给出 $overline(phi^*(V(b))) supset V(Inv(phi)(b))$\ 事实上: $ phi^*(V(b)) subset V(x) &=> forall p_y in Spec(B)(p_y supset b -> phi^*(p_y) supset x)\ &=> forall p_y in Spec(B)(p_y supset b -> phi^(-1)(p_y) supset x)\ $ $ phi^*(V(b)) subset V(x) &=> V(b) subset phi^(* -1)(V(x)) = V(phi(x))\ &=> forall p_y in Spec(Y)(p_y supset b -> p_y supset phi(x))\ $ 另一方面: $ &V(Inv(phi)(b)) subset V(x) \ &<=> forall p_x in Spec(X)(p_x supset Inv(phi)(b) -> p_x supset x)\ &<=> forall p_x in Spec(X)((p_x supset Inv(phi)(b) and ker phi subset p_x) -> p_x supset x)\ &arrow.l.double forall p_x in Spec(X)((p_x supset Inv(phi)(b) and phi(p_x) in Spec(B)) -> p_x supset x)\ &arrow.l.double forall p_x in Spec(X)((p_x supset Inv(phi)(b) and phi(p_x) in Spec(B) and phi(p_x) supset b) -> p_x supset x)\ &arrow.l.double forall p_x in Spec(X)((p_x supset Inv(phi)(b) and phi(p_x) in Spec(B) and phi(p_x) supset b) -> Inv(phi)(phi(p_x)) supset x )\ &(ker phi subset p_x => p_x = Inv(phi)(phi(p_x)))\ &arrow.l.double forall p_x in Spec(X)((phi(p_x) in Spec(B) and phi(p_x) supset b) -> Inv(phi)(phi(p_x)) supset x )\ $ 这就是上面的条件,得证 == iv) 当 $phi$ 是满射时,类似上面的过程给出: $ phi^(* -1)(V(Inv(phi)(b))) = V(phi(Inv(phi)(b))) = V(b)\ phi^*(V(b)) = phi^*(phi^(* -1)(V(Inv(phi)(b)))) = V(Inv(phi)(b)) $ 说明闭集的像仍是闭集\ $V(ker phi)$ 自然同胚于 $X quo (ker phi)$,同时熟知满射 $phi$ 可诱导出一一映射 $phi' : X quo A -> B$,从而前面的事实足以说明 $phi'^*$ 是同胚 == v) 注意到: $ overline(phi^*(Y)) = X <=>& overline(phi^*(V(Re_Y))) = X\ <=>& V(Inv(phi)(Re_Y)) = X\ <=>& Inv(phi)(Re_Y) = Re_X\ <=>& {x in X| exists n in NN^+, x^n in ker phi} = {x in X| exists n in NN^+, x^n = 0}\ <=>& ker phi = Re_X $ == vi) $ (psi compose phi)^(-1) = phi^(-1) compose psi^(-1)\ $ 因此结论显然 == vii) 由题设,$Spec(A)$ 中仅有两个元素 $(0), p$,分别设: $ pi_1 : B -> A quo p\ pi_2 : B -> K $ 是投影映射\ 注意到 $p$ 是极大理想,因此 $A quo q$ 也是域\ 考虑 $B$ 的真理想 $I$ 显然有: $ x, y != 0 => (x, y) in U(B) => (x, y) not in I\ $ 这就意味着 $I$ 中所有元素必然有一个分量是零。同时显然必须是同一个分量,否则它们的和将不在 $I$ 中\ 因此 $I$ 只能是 $A quo p times {0}$ 或 ${0} times K$,显然这两个都是素理想\ 不难发现: $ Inv(phi)({0} times K) = p\ Inv(phi)(A quo p times {0}) = (0) $ 从而 $phi^*$ 是一一映射\ 然而注意到 $(0)$ 在 $Spec(A)$ 不是闭点(因为 $(0) subset p$),而 $Spec(B)$ 中两点都是极大理想/闭点,因此不同胚 = 22 取 $phi_i: A -> A_i$ 是投影同态: - $phi_i^*: Spec(A_i) -> Spec(A)$ 给出一组嵌入,记 $phi_i^*(Spec(A_i)) := X_i$ - 由于 $phi_i$ 是满射,上题结论给出 $X_i$ 都是闭集,且: $ X_i tilde.eq Spec(A quo (ker phi_i)) tilde.eq Spec(A_i) $ - $X_i$ 互相不交,事实上: $ p in X_i => p = Inv(phi)(p_i), p_i in Spec(A_i) $ 因此: $ p in X_i sect X_j => exists p_i in Spec(A_i), p_j in Spec(A_j), p = Inv(phi)(p_i) = Inv(phi)(p_j) $ 然而注意到 $i != j => A_i subset Inv(phi)(p_j), A_j subset Inv(phi)(p_i)$,这将给出: $ A_i subset Inv(phi)(p_i) $ 显然是矛盾的 - $union.big_i X_i = Spec(A)$\ 注意到 $A$ 的理想应当形如 $product_i I_i$,其中 $I_i$ 是 $A_i$ 的理想\ (这是因为总可以先乘以 $(1, 0, 0, .., 0)$\ 设 $p$ 是素理想,取嵌入同态 $psi_i: A_i -> A$,则 $Inv(psi_i) (p) = p sect A_i := I_i$ 也是素理想或 $A_i$\ 往证其中只有至多一个分量上不是整个环,只需证明二维情形,高维情形用 $(1, 1, 0, 0..., 0)$ 覆盖即可\ 设 $p = a times b$ 是素理想,假设 $a, b$ 都是素理想(不是整个环),则可取: $ x in.not a\ y in.not b $ 此时: $ (x, 0) dot (0, y) = (0, 0) in p $ 但上式左侧两项都不在 $p$ 内,矛盾! 综上,$Spec(A)$ 中任何一个元素 $p$ 应当在至多一个分量上不是整个环,设为 $i$,当然就有 $p in X_i$,证毕 - 注意到全空间是有限个闭集的不交并,取补集知它们也都是开集 == i) $=>$ ii) 由 $Spec(A)$ 不连通知存在两个不交开集 $X, Y$ 使得它们的并是全空间\ 显然它们也是闭集,可设其为 $V(x), V(y), x, y$ 是两个理想\ - $emptyset = V(x) sect V(y) = V(x + y) => x + y = A$ - $Spec(A) = V(x) union V(y) = V(x sect y) => x sect y = sqrt(0)$ 进而 $1 = a + b = a^2 + 2 a b + b^2, a in x, b in y$ 进而: $ 1 - 2 a b = a^2 + b^2\ a = a^2 + a b\ (a - a^2)^n = 0\ a^n (1-a)^n = 0 $ 由中国剩余定理: $ R tilde.eq R quo ((a^n) (1-a)^n = 0) tilde.eq (R quo (a^n)) times (R quo (1-a)^n) $ == ii) $=>$ iii) 显然 $(1, 0)$ 即满足要求 == iii) $=>$ ii) 设 $e$ 是一个非平凡的幂等元,则 $1 - e$ 也是,同时 $e(1-e) = 0$ 给出: $ R tilde.eq (R quo (e)) times (R quo (1 - e)) $ == ii) $=>$ i) 上题的结论 = 26 = i) 设 $V = sect.big {Inv(f)(0) | f in m}$,它当然是闭集。假设它是空集,那么它的补集: $ union.big {X - Inv(f)(0) | f in m} = X $ 上式左侧是若干开集的并,这意味着左侧是 $X$ 的一个开覆盖\ 由于 $X$ 是紧的,存在 $m$ 的有限子集 $m'$ 使得: $ union.big {X - Inv(f)(0) | f in m'} = X $ 如此令 $g = sum_(f in m') f^2$,它将在整个 $X$ 上无零点,进而成为可逆元,但这与 $f^2 in m => g in m$ 矛盾 == ii) 对于 $x != y$,注意到紧的 Hausdoff 空间是 $T_4$ 的,可以使用 Urysohn's Lemma 找到 $f, g in C(X)$ 使得: $ f(x) = g(y) = 0\ f(y) = g(x) = 1 $ 表明 $m_x != m_y$ == iii) $ m in mu(U_f) &<=> exists x in U_f, m = mu(x)\ &<=> exists x in U_f, m = m_x = {g | g(x) = 0}\ &<=> exists x in X, f(x) != 0 and m = {g | g(x) = 0}\ &<=> f in.not m\ $ 最后一式的 $arrow.l.double$ 是因为若 $f in.not m$ ,由 i) 可设 $m$ 形如 ${g | g(x_0) = 0}$,从而: $ f(x_0) != 0 and m = {g | g(x_0) = 0} $
https://github.com/thornoar/lambda-calculus-course
https://raw.githubusercontent.com/thornoar/lambda-calculus-course/master/haskell-seminar/material.typ
typst
#import "@local/common:0.0.0": * #set page(margin: (x: .5in, y: .5in)) #set text(lang: "ru", size: 12pt) #set heading(numbering: "1.") // #set raw(lang: "haskell") #let rawblock = block.with( stroke: (left: 1pt), inset: (left: 10pt, top: 3pt, bottom: 3pt, right: 0pt), radius: 0pt, ) #show raw.where(lang: "haskell"): rawblock #show raw.where(lang: "c"): rawblock #align(center, text(20pt, [ *Введение в функциональное программирование* ])) = Основы Haskell - Чисто функциональный: нет понятия состояния, каждая переменная --- константа. - Сильно типизированный: каждое значение имеет постоянный тип. - Декларативный: программа состоит из ряда деклараций типа и определений значений, а не комманд. - Скомпилированный: каждая программа должна быть скомпилирована в бинарный файл перед исполнением. - Ленивый: значение вычисляется только тогда, когда оно становится необходимо. #columns(2)[ Пример императивного кода: ```c #include <stdio.h> void main() { int a; scanf("%d", &a); if (a == 0) { printf("zero\n"); } else { printf("not zero\n"); } } ``` #colbreak() Пример декларативного кода: ```haskell sayZero :: Int -> IO () sayZero 0 = putStrLn "zero" sayZero _ = putStrLn "not zero" main :: IO () main = getLine >>= (sayZero . read) ``` ] Разбор примера выше: - `()` --- это тип данных в Haskell, обозначающий "ничего". Кортеж с 0 элементов. - `IO` --- это модификатор типов. Если `a` --- это произвольный тип, то `IO a` --- тип, который "производит какие-то операции ввода/вывода, а потом возвращает объект типа `a`".\ `putStrLn "zero"` имеет тип `IO ()`.\ `readLine` имеет тип `IO String`. - `::` --- декларация типа. `sayZero` --- это функция из `Int` в `IO ()`. `main` --- это объект типа `IO ()`. - Нотация определения функции. - `read` --- это функция, которая парсит значения из строк. ```haskell read :: (Read a) => String -> a read "20" :: Int read "20" :: Float ``` Это пример полиморфизма в Haskell --- все типы статичны, но одна и та же функция могжет принимать и возвращать сразу несколько типов. - `Read` --- это класс (как интерфейс в Java). Разные типы могут быть или не быть элементами класса. `Read` включает те типы, которые можно "распарсить". - `(.)` --- это композиция функций. ```haskell read :: String -> Int sayZero :: Int -> IO () (sayZero . read) :: String -> IO () ``` - `>>=` --- оператор применения монадической функции. (...proceeds to explain monads in Haskell...) #pagebreak() = Первые функции, if-утверждения, рекурсия ```haskell f :: Int -> Int -- (optional) f n = n*2 ``` ```haskell g :: Bool -> Int -> Int -- (Bool -> (Int -> Int)) g switch n = if switch then n*2 else n*3 -- (if [bool] then [type] else [same type]) -- pattern matching g True n = n*2 g False n = n*3 -- lambda expressions g True = \n -> n*2 g False = \n -> n*3 (g True) = f -- currying ``` В Haskell *нет* циклов, но есть _рекурсия:_ #columns(2)[ ```c // example in c int sum (int n) { int res = 0; for (int i = 0; i <= n; i++) { res += i; } return res; } ``` #colbreak() ```haskell -- example in haskell sum :: Int -> Int sum 0 = 0 sum n = n + sum (n-1) ``` ] #line(length: 100%) Упражнения: - Написать функцию `f :: Float -> Float`, имеющую следующий график: #align(center, [ #image("figures/day-2-exercise-1.svg") ]) - Написать функцию `fib :: Int -> Int`, возвращающую $n$-ное число Фибоначчи. - Написать функцию `power :: Int -> (Float -> Float)`, которая по натуральному числу $n$ возвращает функцию $x |-> x^n$, тремя разными способами. #pagebreak() = Списки $ forall a in "Hask": hs hs exists [a] in "Hask" $ #columns(2)[ ```haskell l1 :: [Int] l1 = [1,2,3,4,5] -- simple declaration l2 :: [Int] l2 = [0..20] -- ranges l3 = l1 ++ l2 -- concatenation l4 = 100 : l3 -- prepending an element n :: Int n = l4 !! 30 -- element at an index l5 :: [Int] l5 = [0..] -- infinite (due to laziness) ``` #colbreak() ```haskell head :: [a] -> a tail :: [a] -> [a] last :: [a] -> a init :: [a] -> [a] length :: [a] -> Int null :: [a] -> Bool reverse :: [a] -> [a] take :: Int -> [a] -> [a] drop :: Int -> [a] -> [a] maximum :: (Num a) => [a] -> a minimum :: (Num a) => [a] -> a sum :: (Num a) => [a] -> a product :: (Num a) => [a] -> a elem :: (Eq a) => a -> [a] -> Bool ``` ] В Haskell есть механизм "аксиомы выделения": ```haskell l6 :: [Int] l6 = [n^2 | n <- l5, n `mod` 2 == 0] -- list comprehension ``` Упражнения: - Написать #hs `quicksort :: (Ord a) => [a] -> [a]` - Написать #hs `zw :: (a -> a -> b) -> [a] -> [a] -> [b]` двумя разными способами. - Написать #hs `length'`, не используя `length`. - Написать #hs `intersection` - Написать #hs `removeNonUppercase` #pagebreak() = Кортежи $ forall a,b in "Hask": hs hs exists (a,b) in "Hask". $ ```haskell (1.0,0.0) :: (Float, Float) (1,True,'z') :: (Int, Bool, Char) fst :: (a,b) -> a snd :: (a,b) -> b ``` Упражнения: - Написать #hs `zip' :: [a] -> [b] -> [(a,b)]` - Написать #hs `curry` и `uncurry`. - Определить список натуральных чисел меньше 10, удовлетворяющих теореме Пифагора. #pagebreak() = Типчики и классы
https://github.com/luiswirth/bsc-thesis
https://raw.githubusercontent.com/luiswirth/bsc-thesis/main/src/implementation.typ
typst
= Implementation The concrete implementation of FEEC in Rust. To show the functioning of the implementation, we will be solving one of multiple of these problems: - Elliptic problem: Hodge Poisson Equation $ (delta d + d delta) u = f $ - Parabolic problem: Hodge Heat Equation $ u_t + (delta d + d delta) u = f $ - Hyperbolic problem: Hodge Wave Equation $ u_(t t) + (delta d + d delta) u = f $ Other more advanced problems are: - Maxwell's equations - Stockes' equations (new NumPDE chapter 12) It would be very nice to have a appealing visualization of the solution. A possible approach that could yield very impressive visual results, could be to write a GPU shader. The implementation of this FEEC library is at least as complicated and as much work as writing LehrFEM++ from scratch. Is this doable? We want - Arbitrary Spatial Dimension but we will restrict us to the most simple setup: - Only Simplicial meshes - Whitney forms (only linear order 1 polynomials) - Only Hodge-Poisson Problem
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/gentle-clues/0.1.0/README.md
markdown
Apache License 2.0
# gentle-clues Simple admonitions for typst. Add predefined or define your own. Inspired from [mdbook-admonish](https://tommilligan.github.io/mdbook-admonish/). ## Usage `#import " @preview/gentle-clues:0.1.0: info, success, warning, error` Writing this, ```typst #info[Whatever you want to say] ``` turns into this. ![Screenshot of the info admonish](https://github.com/jomaway/typst-admonish/blob/main/screenshot-info-admonish.png) ### Available Admonitions The follwing admonitions (+ some aliases) are available at the moment. `abstract`, `info`, `question`, `memo`, `task`, `idea`, `tip`, `quote`, `success`, `warning`, `error`. [See here for more Information](https://github.com/jomaway/typst-admonish/blob/main/docs.pdf) ### Define your own But it is very easy to define your own. ```typst //Define it #let ghost-admon(title: "Buuuuh", icon: emohi.ghost, ..args) = admonish(color: "purple", title: title, icon: icon, ..args) // Use it #ghost-admon[Huuuuuh.] ``` The icon can be an `emoji`, `symbol` or `.svg`-file. At the moment the colors are hardcoded. The following color profiles are available to use in your own admonish. In a future version this should be changed. ```typst // color profiles #let colors = ( gray: (border: luma(70), bg: luma(230)), blue: (border: rgb(29, 144, 208), bg: rgb(232, 246, 253)), green: (border: rgb(102, 174, 62), bg: rgb(235, 244, 222)), red: (border: rgb(237, 32, 84), bg: rgb(255, 231, 236)), yellow: (border: rgb(255, 201, 23), bg: rgb(252, 243, 207)), purple: (border: rgb(158, 84, 159), bg: rgb(241, 230, 241)), teal: (border: rgb(0, 191, 165), bg: rgb(229, 248, 246)), orange: (border: rgb(255, 145, 0), bg: rgb(255, 244, 229)), memo: (border: rgb(255, 82, 82), bg: rgb(253, 228, 224)), blueish:(border: rgb(0, 184, 212), bg: rgb(229, 248, 251)), grayish:(border: rgb(158, 158, 158),bg: rgb(245, 245, 245)), quest:(border: rgb(0, 143, 115),bg: rgb(221, 243, 231)), abstract: (border: rgb(124, 77, 255), bg: rgb(242, 237, 255)), ) ``` ### Reference Here the full reference to the admonish function. ```typst admonish( body, title: none, // Default: none, or string icon: "assets/flag.svg", // can be a file or an symbol|emoji color: "gray", width: auto, radius: 2pt, // radius of the right side. For no radius set to 0pt. inset: 1em, // inset of the content, header-inset not yet supported ) ``` ## License MIT
https://github.com/jomaway/typst-teacher-templates
https://raw.githubusercontent.com/jomaway/typst-teacher-templates/main/ttt-exam/lib/headers.typ
typst
MIT License
#import "@preview/ttt-utils:0.1.2": assignments #import "i18n.typ": ling #let header-block( logo: none, title, subtitle: none, class, subject, date, ) = { date = if type(date) == datetime { date.display("[day].[month].[year]") } else { date } table( columns: (3fr, 5fr, 35mm), rows: (25mm, 10mm), inset: 0.7em, table.cell(align: horizon)[ #set par(leading: 1em) #smallcaps(ling("class") + ":") #class \ #smallcaps(ling("subject") + ":") #subject \ #smallcaps(ling("date") + ":") #date ], table.cell(align: center + horizon)[ #if logo != none { context { let size = measure(box(height: 2cm, logo)) if ( size.width * 0.4 > size.height ) { grid( align: center, rows: (1fr), row-gutter: (8pt, 4pt), box(height: 0.7cm, logo), text(16pt, weight: 500, title), if subtitle != none { subtitle } ) } else { grid( columns: 2, column-gutter: 12pt, align: horizon, box(height: 2cm, width: calc.min(size.width, 2cm), logo), { text(16pt, strong(delta: 200,title)) linebreak() if subtitle != none { subtitle } } ) } } } else { text(16pt, weight: 500, title) linebreak() if subtitle != none { subtitle } } ], table.cell(rowspan: 2)[#align(top + start)[#smallcaps(ling("grade") + ":")] #context if assignments.is-solution-mode() { align(center + horizon,text(32pt, weight: 700, red, "X")) }], table.cell(colspan: 2)[#smallcaps(ling("name") + ":") #context if assignments.is-solution-mode() { text(red, ling("solution")) }] ) } #let header-page( logo: none, title, subtitle: none, class, subject, date, point-field: none ) = { date = if type(date) == datetime { date.display("[day].[month].[year]") } else { date } grid( columns: 1fr, rows: (2fr,1fr,1fr), align: horizon, { set text(22pt) set align(center) if logo != none { place(top+end, box(height: 5cm,logo)) } grid( align: center, row-gutter: (1em), text(22pt, weight: 500, title), if subtitle != none { subtitle } ) }, grid( columns: (1fr, auto), row-gutter: 1cm, { set text(18pt) grid( columns: (auto, 6cm), align: (end + horizon, start + horizon), stroke: (x,y) => if (1 == x) { (bottom: 0.5pt)}, inset: (x: 2pt, y: 5pt), row-gutter: 1em, column-gutter: 5pt, smallcaps(ling("name") + ":"), context if assignments.is-solution-mode() { text(red, ling("solution")) }, smallcaps(ling("class") + ":"), class, smallcaps(ling("subject") + ":"), subject, smallcaps(ling("date") + ":"), date, ) }, [ *#ling("grade"):* #rect(width: 3cm, height: 3cm)[#context if assignments.is-solution-mode() { align(center + horizon,text(32pt, weight: 700, red, "X")) }] ] ), align(end,block[ #set align(start) *#ling("points"):* \ #point-field ]) ) }
https://github.com/Otto-AA/definitely-not-tuw-thesis
https://raw.githubusercontent.com/Otto-AA/definitely-not-tuw-thesis/main/README.md
markdown
MIT No Attribution
# Unofficial thesis template for informatics at TU Wien An example thesis can be viewed here: https://otto-aa.github.io/definitely-not-tuw-thesis/thesis.pdf ## Usage You can download the template with: ```bash typst init @preview/definitely-not-tuw-thesis ``` ### Template overview After setting up the template, you will have the following files: - `thesis.typ`: overall structure and styling, configuration for the cover pages and PDF metadata - `content/front-matter.typ`: acknowledgments and abstract - `content/main.typ`: all your chapters - `content/appendix.typ`: AI tools acknowledgment and other appendices - `refs.bib`: references Then copy the values you get from compiling the [official template](https://gitlab.com/ThomasAUZINGER/vutinfth), and paste them in `thesis.typ`. Remove all unused fields and, finally, compare if it is close enough to the official template. If not, please open an issue or PR to fix it. ### Styling If you want to adapt the styling, you can remove the `show: ...` commands in the `thesis.typ` and replace them with your own, or simply extend them with your own `show: ...` commands. ## Contributing I guess there are many ways to improve this template, feel free to do so and submit issues and PRs! More information at [CONTRIBUTING.md](https://github.com/Otto-AA/unofficial-tu-wien-thesis-template/blob/main/CONTRIBUTING.md) ## License The code is licensed under MIT-0. The 'TU Wien Informatics' logo and signet are copyright of the TU Wien. ## Acknowledgments This work is based on the [official template](https://gitlab.com/ThomasAUZINGER/vutinfth) maintained by <NAME>. The repository structure is based on [typst-package-template](https://github.com/typst-community/typst-package-template).
https://github.com/DeveloperPaul123/modern-cv
https://raw.githubusercontent.com/DeveloperPaul123/modern-cv/main/README.md
markdown
Other
# Modern CV [![say thanks](https://img.shields.io/badge/Say%20Thanks-👍-1EAEDB.svg)](https://github.com/DeveloperPaul123/modern-cv/stargazers) [![Discord](https://img.shields.io/discord/652515194572111872?logo=Discord)](https://discord.gg/CX2ybByRnt) ![Release](https://img.shields.io/github/v/release/DeveloperPaul123/modern-cv) [![Tests](https://github.com/DeveloperPaul123/modern-cv/actions/workflows/tests.yml/badge.svg)](https://github.com/DeveloperPaul123/modern-cv/actions/workflows/tests.yml) A port of the [Awesome-CV](https://github.com/posquit0/Awesome-CV) Latex resume template in [typst](https://github.com/typst/typst). ## Requirements ### Tools The following tools are used for the development of this template: - [typst](https://github.com/typst/typst) - [typst-test](https://github.com/tingerrr/typst-test) for running tests - [just](https://github.com/casey/just) for simplifying command running - [oxipng](https://github.com/shssoichiro/oxipng) for compressing thumbnails used in the README ### Fonts You will need the `Roboto` and `Source Sans Pro` fonts installed on your system or available somewhere. If you are using the `typst` web app, no further action is necessary. You can download them from the following links: - [Roboto](https://fonts.google.com/specimen/Roboto) - [Source Sans Pro](https://github.com/adobe-fonts/source-sans-pro) This template also uses FontAwesome icons via the [fontawesome](https://typst.app/universe/package/fontawesome) package. You will need to install the fontawesome fonts on your system or configure the `typst` web app to use them. You can download fontawesome [here](https://fontawesome.com/download). To use the fontawesome icons in the web app, add a `fonts` folder to your project and upload the `otf` files from the fontawesome download to this folder like so: ![alt text](assets/images/typst_web_editor.png) See `typst fonts --help` for more information on configuring fonts for `typst` that are not installed on your system. ### Usage Below is a basic example for a simple resume: ```typst #import "@preview/modern-cv:0.6.0": * #show: resume.with( author: ( firstname: "John", lastname: "Smith", email: "<EMAIL>", phone: "(+1) 111-111-1111", github: "DeveloperPaul123", linkedin: "Example", address: "111 Example St. Example City, EX 11111", positions: ( "Software Engineer", "Software Architect" ) ), date: datetime.today().display() ) = Education #resume-entry( title: "Example University", location: "B.S. in Computer Science", date: "August 2014 - May 2019", description: "Example" ) #resume-item[ - #lorem(20) - #lorem(15) - #lorem(25) ] ``` After saving to a `*.typ` file, compile your resume using the following command: ```bash typst compile resume.typ ``` For more information on how to use and compile `typst` files, see the [official documentation](https://typst.app/docs). Documentation for this template is published with each commit. See the attached PDF on each Github Action run [here](https://github.com/DeveloperPaul123/modern-cv/actions). ### Output Examples | Resumes | Cover letters | | --- | --- | | ![Resume](assets/images/resume.png) | ![Cover Letter](assets/images/coverletter.png) | | ![Resume 2](assets/images/resume2.png) | ![Cover Letter 2](assets/images/coverletter2.png)| ## Building and Testing Locally To build and test the project locally, you will need to install the `typst` CLI. You can find instructions on how to do this [here](https://github.com/typst/typst#installation). With typst installed you can make changes to `lib.typ` and then `just install` or `just install-preview` to install the package locally. Change the import statements in the template files to point to the local package (if needed): ```typst #import "@local/modern-cv:0.6.0": * ```` If you use `just install-preview` you will only need to update the version number to match `typst.toml`. Note that the script parses the `typst.toml` to determine the version number and the folder the local files are installed to. ### Formatting This project uses [typstyle](https://github.com/Enter-tainer/typstyle) to format the code. Run `just format` to format all the `*.typ` files in the project. Be sure to install `typstyle` before running the script. ## License The project is licensed under the MIT license. See [LICENSE](LICENSE) for more details. ## Author | [<img src="https://avatars0.githubusercontent.com/u/6591180?s=460&v=4" width="100"><br><sub>@DeveloperPaul123</sub>](https://github.com/DeveloperPaul123) | |:----:|
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/src/lib/plot/mark.typ
typst
Apache License 2.0
#import "/src/draw.typ" // Draw mark at point with size #let draw-mark-shape(pt, size, mark, style) = { let (sx, sy) = if type(size) != array { (size, size) } else { size } let bl(pt) = (rel: (-sx/2, -sy/2), to: pt) let br(pt) = (rel: (sx/2, -sy/2), to: pt) let tl(pt) = (rel: (-sx/2, sy/2), to: pt) let tr(pt) = (rel: (sx/2, sy/2), to: pt) let ll(pt) = (rel: (-sx/2, 0), to: pt) let rr(pt) = (rel: (sx/2, 0), to: pt) let tt(pt) = (rel: (0, sy/2), to: pt) let bb(pt) = (rel: (0, -sy/2), to: pt) if mark == "o" { draw.circle(pt, radius: (sx/2, sy/2), ..style) } else if mark == "square" { draw.rect(bl(pt), tr(pt), ..style) } else if mark == "triangle" { draw.line(bl(pt), br(pt), tt(pt), close: true, ..style) } else if mark == "*" or mark == "x" { draw.line(bl(pt), tr(pt), ..style) draw.line(tl(pt), br(pt), ..style) } else if mark == "+" { draw.line(ll(pt), rr(pt), ..style); draw.line(tt(pt), bb(pt), ..style) } else if mark == "-" { draw.line(ll(pt), rr(pt), ..style) } else if mark == "|" { draw.line(tt(pt), bb(pt), ..style) } } #let draw-mark(pts, x, y, mark, mark-size, plot-size) = { // Scale marks back to canvas scaling let (sx, sy) = plot-size sx = (x.max - x.min) / sx sy = (y.max - y.min) / sy sx *= mark-size sy *= mark-size for pt in pts { let (px, py, ..) = pt if px >= x.min and px <= x.max and py >= y.min and py <= y.max { draw-mark-shape(pt, (sx, sy), mark, (:)) } } }
https://github.com/refparo/24xs-zh
https://raw.githubusercontent.com/refparo/24xs-zh/master/rules1.typ
typst
#import "common.typ": * #show: typ-24xs #show: rules-page #logo _#link("https://diceghost.itch.io/24xs")[diceghost.itch.io]_ #v(1.25em / 4) 基于 Jason Tocci 以 CC BY 4.0 协议授权的 24XX SRD。 #v(1.25em / 4) *玩法*:决定你角色的行动,思考这需要付出代价还是带有风险。边玩边记录下你的故事,仅在有风险时掷骰。 *提示*:引入你不知道怎么解决的问题。用临时判决填补缺失的规则。叙述叙事上最合理的展开。从环境中寻找灵感。 *掷骰*:做有风险的事时,投一个六面骰。如果这件事跟角色的#underline[技能]有关,或者能用上相关的物品,就双骰取高。 #grid( columns: (auto, 1fr), column-gutter: 1em, row-gutter: 1.25em / 8, [*1--2*], [*灾难。*承受完整风险。], [*3--4*], [*挫折。*你有代价地成功。], [*5+*], [*成功。*], ) *生命*:你的角色受到三次伤害后便会死亡,结果为#underline[灾难]的掷骰合理时可以导致立即死亡。 *装备*:你可以携带此刻你身上的物品加上一件自选物品。 *安全*:时常注意故事走向是否让你自己感觉舒适。你可以暂停、倒带、删除任何不喜欢的内容。保重自己,玩得开心!
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/代数学二/章节/上半学期.typ
typst
#import "../../template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. = 前言 == 课程介绍 - 学习内容:前半学期交换代数,后半学期同调代数 - 教师:阳恩林 https://www.math.pku.edu.cn/teachers/yangenlin/ce.htm - 参考书: - <NAME>, Introduction to Commutative Algebra - Matsumura, Commutative Algebra - 李文威, 代数学基础 - 本门课程提供的同调代数的讲义 - GTM52 代数几何 - T.Wedhorn, adic spaces - 考核:作业 20%, 期中 30%, 期末 50%(也可能期中期末各占40%),期中会更难+调分 约定除非特别指明,环指交换幺环,同态是保持其幺元的。零环也视为环\ 通常环/模记为大写字母,$k$ 表示某个域 期末考试:6.12 14:00 - 16:00 // == 内容介绍 // #example[][ // 方程 $x^2 + y^2 = 1$ 的有理根也是单位圆上的有理点,也是多项式 $h(x, y) = x^2 + y^2 - 1$ 的零点集。\ // 设 $f, g in R[x, y]$ 满足 $f - g in (f)$,那么将有: // $ // f|_C = g|_C // $ // 换言之,$C$ 上的代数函数环恰为 $R[x, y] quo (f)$\ // ] == 中英名词对照 - annihilates:零化 - annihilator:零化子 - idempotent:幂等元 - nilpotent:幂零元 - nilradical:幂零根 - saturated:饱和的 = 环与模 == 模 #definition[范畴|category][ 范畴被形式的定义为以下资料: - 对象集合 $H$ - 对于每一对对象 $A, B in H$,一个集合 $Hom(A, B)$,称为从 $A$ 到 $B$ 的态射集 - 对于每一对对象 $A, B, C in H$,一个映射 $Hom(A, B) * Hom(B, C) -> Hom(A, C)$,称为复合映射 - 对于每一个对象 $A in H$,一个元素 $1_A in Hom(A, A)$,称为恒等态射 ] #definition[模|AModuleule][ 设 $A$ 是环,一个 $A-$模是指: - 加法交换群 $M$ - $A-$作用 $A times M -> M$,记作 $(a, m) = a dot m$ - 运算的兼容性,也即: - $a(x + y) = a x + a y$ - $(a + b) x = a x + b x$ - $a(b x) = (a b)x$ 或者说存在 $M -> End_A (M)$ 的环同态 ] #example[][ - $A$ 是一个域,那么 $A-$模就是向量空间 - $A = ZZ$,$A-$模就是交换群本身(作用当然就是熟知的 $n dot x$) - 设 $A = k[x]$,则 $A-$模包括: - $A$ 在 $k$ 上的作用,也就是 $k$ 的向量空间 - $x$ 在上述线性空间的作用,也即一个线性变换/k-矩阵 - 设 $G$ 是有限群,$A = k[G]$ 是群代数(也是线性空间),其中元素形如 $sum_(g in G) a_g g$\ $G$ 中每个元素给出 $A$ 上的一个可逆线性变换,这就给出 $G -> GL(k)$ 的一个一一映射 - $A$ 是环,$A$ 作用于自己当然也构成 $AModule(A)$ ] #definition[模同态][ 两个 $AModule(A)$ 之间的群同态 $f: M -> N$ 称为模同态,如果: - $f(x + y) = f(x) + f(y)$ - $f(a x) = a f(x)$ 有时也称其为 $A-$线性映射\ 此时,记: - $ker f = {m in M | f(m) = 0}$,它是 $M$ 的子($A$)模 - $im f = {f(m) | m in M}$,它是 $N$ 的子($A$)模 - $coker f = N quo im f$ - $coim f = M quo ker f$ 有熟知的同构定理 $coim f tilde.eq im f$ 所有$AModule(A)$之间的同态构成态射集 $Hom_A (M, N)$。注意到 $Hom_A (M, N)$ 本身就是一个 $AModule(A)$,运算是自然的运算: $ &[a: A -> \ [f: Hom_A (M, N) ->\ [x: M -> a f(x) :N]:Hom_A (M, N)\ ]:(Hom_A (M, N) -> Hom_A (M, N)) = End_A (Hom_A (M, N))\ ]:(A -> End_A (Hom_A (M, N))) \ $ ] #example[][ 设 $M$ 是$AModule(A)$,则 $Hom_A (A, M) tilde.eq M$,它由双向的映射: - $[f: (A -> M) -> f(1)] $ - $[m: M -> [a: A -> a m]] $ 给出 ] #definition[子模|subAModuleule 商模|quotient AModuleule][ 设 $M$ 是 $AModule(A)$,$N$ 是 $M$ 的子集,如果: - $N$(在相同运算下)也是 $A-$模,或者 - $N$ 在 $A$ 作用下稳定,也即 $A M subset M$ 那么称 $N$ 是 $M$ 的子模\ 此时,可以定义商模 $M quo N$ 为交换群的一个商群,它同时也是 $A-$模,定义为: $ [a: A, m + N: M quo N -> a (m + N) = a m + N: M quo N] $ ] #theorem[对应定理][ $M$ 的包含 $N$ 的子模与 $M quo N$ 的子模之间存在一一对应关系,并且保持各种性质 ] #definition[理想|ideal][ 将 $A$ 视作$AModule(A)$,则 $A$ 的子模称为 $A$ 的理想,这等同于在 $A$ 乘法下稳定的加法子群,与环中理想的概念是一致的。\ 自然的,此时的商模就是商环 ] == 子模/理想上的操作 #definition[][ + 设 $M$是$AModule(A)$,$M_i in I$ 是若干子模,定义: - $M_j subset sum_(i in I) M_i = {sum_(i in I) m_i | m_i in M_i, m_i "中至多有限个非零"} subset M$ - $sect.big_(i in I) M_i subset M_j$ 都是子$AModule(A)$ + 设 $I$ 是 $A$ 的理想,定义: $ I M = phi: (A -> (M -> M)) |_I $ 它是 $M$ 的子模\ 当 $I, J$ 都是理想时,以上定义给出 $I J$ 也是理想,它含于 $I sect J$。以此乘法给出 $I^m$ 的定义 + 任取 $m in M$,定义: $ (m) = A m = {a m | a in A} $ 为由 $m$ 生成的子模 + 若 $M = sum_(i=1)^n A m_i$ 对某个 $n$ 和某些 $m_i$ 成立,则称 $M$ 是有限生成(finitely generated)的 + 设 $M_i$ 是若干子模,定义: - 直和 $circle_(i in I) M_i = {(m_i) | m_i in M_i, m_i "中至多有限个非零"} subset M$ - 直积 $product_(i in I) M_i = {(m_i) | m_i in M_i} subset M$ 都是子$AModule(A)$ + 设 $N P$ 是子模,定义: $ (N : P) = {a in A | a P subset N} $ 它是 $A$ 的理想。特殊的,称: $ (0) : P = {a in A | a P = 0} = "ann"(P) $ 为 $P$ 的零化子\ 一般的,我们有: $ N : P = "ann"((N + P)/N) $ (注意到 $a P subset N <=> a (N + P)/N = 0$) ] #theorem[][ $(M_1 + M_2)/(M_1) tilde.eq (M_1)/(M_1 sect M_2)$ ] #theorem[][ $M$ 是有限生成的当且仅当存在 $A^n -> M$ 的满同态 ] #proof[ - 若 $M$ 是有限生成的,那么定义: $ funcDef(phi, A^n, M, (a_i), sum_(i=1)^n a_i m_i)\ $ - 若存在满同态 $phi$,取 $m_i = phi(0, 0, 0, ..., 1, 0,... >,0)$ 即可 ] #theorem[][ 设 $M$ 是$AModule(A)$ ,则 $"ann"(M)$ 是子模,将有: $ M " 是 " AModule(A quo "ann"(M)) $ ] == 素理想和极大理想 #definition[素理想][ 设 $R$ 是环,$P$ 是理想且 $P != R$,称 $P$ 是素理想,若: $ a b in P => a in P or b in P $ ] #proposition[][ 设 $R$ 是环,$P$ 是非平凡理想,则 $P$ 是素理想当且仅当 $quotient(R, P)$ 是整环 ] #definition[极大理想][ 设 $R$ 是环,$m$ 是 $R$ 的双边理想,若 $m != R$ 且没有包含 $m$ 的理想,则称 $m$ 是极大理想 ] #proposition[][ 设 $R$ 是交换环,则 $I$ 是极大理想当且仅当 $quotient(R, I)$ 是域 ] #theorem[][ 任何理想 $I != A$ 都包含在某个极大理想中 ] #proof[ 这个证明需要用到 Zoun 引理。 取 $S$ 是所有 $R$ 中包含 $I$ 的非平凡理想,对于包含关系,我们有 $S$ 是偏序集。在这个集合上我们试图套用 Zoun 引理,只需验证所有链都有上界即可。 设 $I_x space x in S$ 是链,显然: $ union_(x in S) I_x $ 是这个链的一个上界,它是理想也是显然的,只需证明它不是 $R$。\ 事实上,注意到: $ 1 in.not I_x $ 进而 $1 in.not union_(x in S) I_x$ 这就完成了证明 ] #remark[][ 如果不使用 Zoun 引理,可能需要假设 $A$ 是 Noethenian 环 ] #definition[局部环|local ring][ 称 $A$ 是局部环,如果其中有且只有一个极大理想 $m$,此时称 $A quo m$ 为剩余域 ] #theorem[][ - 若所有不可逆元素包含于某个理想,则这个理想一定是唯一的极大理想,进而环是局部环 - 若 $m$ 是极大理想,且 $1+m$ 中所有理想均可逆,则 $A$ 是局部环 ] #proof[ - 显然 - 任取 $x in A - m$,由于: $ m + (x) = (1) $ 因此可设 $a + b x = 1 => b x = 1 -a in 1 + m$ 可逆,进而 $x$ 也可逆,由 1 知结论成立 ] #example[][ $ ZZ_((p)) = {r/s | (p, s) = 1} $ 中,所有的不可逆元包含于 $p ZZ_((p))$,同时这是极大理想,因此环是局部环 ] #example[理想的几何来源][ 设 $k$ 是域,$Y subset k^n$,令: $ I(Y) = {f in k[x_1, x_2 ,..., x_n] | f(Y) = 0} $ 容易验证它是理想 反之,给定 $I$ 是理想,令: $ Z(I) = {p in k^n| forall f in I, f(p) = 0} $ 不幸的是,他们一般不是互逆的,但几乎是互逆的,这在代数几何中非常基本 ] == 幂零根与 Jacob radical #definition[幂零根|nilradical][ 设 $A$ 是环,称 $A$ 的 幂零根|nilradical 为: $ N = sect.big Spec(A) $ ] #definition[Jacob radical][ 设 $A$ 是环,称 $A$ 的 Jacob radical 为: $ R = sect.big "max"(A) $ ] #theorem[][ - $N = {a in A | exists n in NN, a^n = 0}$ - $R = {x in A | 1 - x y in U(A)}$ ]<radicalForm> #proof[ - 记所有幂零元的集合为 $N$,容易验证它是理想。比较困难的是证明它是所有素理想的交(暂记为 $N'$) - 首先容易验证 $N$ 应该包含在所有素理想之中,进而 $N subset N'$ - 再证明另一方面,只需证明: #lemma[][任取 $f in A$ 不是幂零元,它不含于某个素理想] #proof[ 令 $ Sigma = {p in Spec(A) | forall n > 0, f^n in.not p} $ 断言: - $Sigma$ 非空,因为 $(0) in Sigma$ - $Sigma$ 满足 Zoun 引理的条件 - 进而 $Sigma$ 有一个极大元 $p$,它是素理想\ 假设 $x, y in.not p$,往证 $x y in.not p$\ 由极大性,$p + (x), p + (y) in.not Sigma$,也即: $ exists n in NN:\ f^n in p + (x), f^n in p + (y)\ => f^(2n) in p + (x y)\ => p + (x y) in.not Sigma\ => p + (x y) != p\ => x y in.not p $ 证毕 ] - 记 $R' = {x in A | 1 - x y in U(A)}$,分别验证: - $x in m, forall m in max(A) => 1 - x y in U(A)$\ 如若不然,则存在 $y$ 使得 $1 - x y$ 不是单位,可设 $1 - x y$ 包含于极大理想 $m$\ 此时 $m$ 同时包含 $1 - x y, x$ 进而包含 $1$,矛盾! - 反过来,设 $forall y in A, 1- x y in U(A)$\ 若结果不成立,则存在 $m in max(A), x in.not m$,进而: $ m + (x) = (1) => 1 = a + x y => a = 1 - x y $ 这表明 $a in m$ 是单位,不能包含在极大理想中,矛盾! ] #definition[乘性子集 | multiplicative][ 称 $S subset A$ 是乘性子集,如果: - $1 in S$ - $x, y in S => x y in S$ ] #theorem[][ 设 $S$ 是乘性子集且不含零(那么 $S$ 中的元素都不是幂零元),则存在素理想 $p$ 使得 $p sect S = emptyset$ ] #proof[ 构造: $ Sigma = {I "is ideal"| I sect S = emptyset } $ 类似上面的证明,可以利用 Zoun 引理证明 $Sigma$ 有极大元 $p$,且它是素理想 ] #definition[][ 设 $I subset A$ 是理想,记: $ r(I) 或 sqrt(I) := {x in A | exists n in NN^+, x^n in I} = Inv(pi)(N(A quo I)) $ 容易验证它也是: $ sect.big V(I) = sect.big {p in Spec(A) | I subset p} $ 特别的,$sqrt(0) = N$ ] #proposition[][ - $I subset sqrt(I)$ - $sqrt(I) = sqrt(sqrt(I))$ - $sqrt(I J) = sqrt(I) sect sqrt(J)$ - $sqrt(I) = (1) <=> I = 1$ - $p in Spec(A) => sqrt(p) = p$ ] #remark[][ 对应的也应该考虑 $sect.big_(I subset m in max(A)) m$,这同样对应商环中的 Jacob radical,也即: $ forall y in A: (1 - x y) + I = (1)\ a - a x + b = 1\ a x = a + b - 1 $ 它往往比 $sqrt(I)$ 更大(做交运算的集合更少),有时取等 ] #example[][ 设 $D(x) = {y | x y = 0}$,则容易验证 $sqrt(D) = D$。更进一步,整个环的零因子: $ union_x D(x) $ 应当满足: $ sqrt(union_x D(x)) = union_x sqrt(D(x)) = union_x D(x) $ ] == 素谱上的拓扑 #definition[环的(素)谱(prime spectrum)][ 设 $A$ 是一个环,$P$ 是 $A$ 的一个素理想(注意素理想一定是真理想)\ 称环的素谱为 $A$ 的素理想的集合,记作 $Spec(A)$ ] #definition[零点集][ 设 $E$ 是 $A$ 的子集,称: $ V(E) = {P in Spec(A) | E subset P} $ 为 $E$ 的零点集 ] #remark[][ 这看似与零点毫无关系,但后续课程中会学到 $A$ 中的元素可以看作 $A$ 的素谱上的函数,而 $E$ 的零点集可以看作这些函数的零点集 ] 环的素谱是某种意义上多项式零点集的推广,其上具有良好的拓扑性质,我们的目标是模仿零点集给出谱上的拓扑。 #proposition[][ - $V(E) = V(I)$, 其中 $I$ 是 $E$ 的生成理想。这表明我们只需要考虑理想的零点集 - $V(0) = Spec(A)$ - $V(A) = V(1) = emptyset$ - $sect.big_i V(I_i) = V(sum_i I_i)$ - $V(I) union V(J) = V(I sect J) = V(I J)$ ] #proof[ - 注意到对任何素理想 $P, I subset P <=> E subset P$,结论显然 - $0$ 当然包含与任何素理想 - 任何素理想当然都不应该包含 $1$ - 一方面 $ I_j subset sum_i I_i => V(sum_i I_i) subset V(I_j) $ 另一方面,假设素理想 $P$ 满足 $P in sect.big_i V(I_i)$,这就导出 $P supset I_i, forall i$,表明 $P supset sum_i I_i$ - 首先 $I, J supset I sect J, I J$,因此 $V(I), V(J) subset I sect J, I J$。\ - 往证 $V(I J) subset V(I) union V(J)$\ 注意到 $P$ 是素理想,因此 $P supset I J => P supset I or P supset J => P in V(I) union V(J)$ - 类似的,把 $I sect J$ 替换 $I J$ 结论都是正确的 ] 注意到上面的命题实际上说明了: - $Spec(A), emptyset$ 是某个集合的零点集 - 两个零点集的并,任意零点集的交仍是零点集 这恰好就是拓扑的闭集公理,由此我们就定义谱上的拓扑。 #theorem[][ $Spec(A)$ 上的由所有形如 $V(I)$ 的集合作为闭集生成一个拓扑 ] #example[][ - 容易计算得 $ Spec(ZZ) = {(p) | p "is prime"}\ V(n ZZ) = {(p) | p "is prime" and (p) supset (n)} = {(p) | p "is prime" and p | n} $ 不难发现,闭集恰为所有不含 $(0)$ 的有限集和全集。此时 ${(0)}$ 的闭包是全集,表明整数环的谱不是 $T_1$ 的。一般来说,只有很少的环满足 $T_1$ 或者 $T_2$ - 域的谱都是平凡的,因为只有平凡的素理想 - 考虑 $CC[x]$,这是 PID ,所有素理想都是素元的生成理想,而多项式是素元当切仅当它是一次多项式。因此 $Spec(CC[x]) = {(x - a) | a in CC} union {0}$,进而 $CC$ 中每个元素都对应着 $Spec(CC[x])$ 中的一个元素。\ 同时,$CC[x]$ 的零点集当然就是任意若干个 $CC$ 中元素,再次体现了零点集概念的合理性。\ 而: $ V(f) = V(product_(i=1)^n x - a_i) = {(x - a_i) | i = 1, 2, ..., n} $ 它的拓扑恰与余有限拓扑只相差一个零理想对应的单点集。这个事实对任何代数闭域都是成立的。 - 考虑 $RR[x]$,它的素谱比代数闭的情形多出二次不可约多项式,因此: $ Spec(RR[x]) = {(0)} union {(x - a) | a in RR} union {(x-z)(x-overline(z)) | z in CC, im(c) > 0} $ 拓扑是类似的。粗略来说,可以认为 $Spec(RR[x]) tilde.eq Spec(CC[x]) quo Gal(CC quo RR)$ 至少在拓扑上是成立的 ] #definition[基本开集 (prime open set)][ 对任意 $f in A$,称形如: $ D_f = Spec(A) - V(f) = {P in Spec(A) | f in.not P} $ 的集合为基本开集/主开集 ] #proposition[][ - $D(f) sect D(g) = D(f g)$ - $D(f) = emptyset <=> f in sqrt(0)$ - $D(f) = Spec(A) <=> f in U(A)$ - $D(f) = D(g) <=> sqrt(f) = sqrt(g)$ ] #proof[ - $p in D(f) sect D(g) <=> f in.not p and g in.not p <=> f g in.not p$ - 由幂零根的概念和性质可知 - \ - 一方面 $f in U(A) => V(f) = emptyset$ - 另一方面,一个不可逆的元素应该包含于某个极大理想,而极大理想一定是素理想,因此成立 - 首先我们证明: $ sect.big_(P in V(I)) = sqrt(I) $ 这是因为由对应定义,$V(I)$ 中的元素与 $Spec(A quo I)$ 中元素可以产生一一对应 $phi$。同时,注意到: $ Spec(A quo I) = sect.big_(p in V(I)) p quo I $ 用 $phi$ 作用于两侧立得结论 ] #corollary[][ 所有基本开集构成一个拓扑基 ] #proof[ 这是非常自然的,因为开集均形如: $ Spec(A) - V(E) = Spec(A) - (sect.big_(f in E) V(f)) = union.big_(f in E) D(f) $ ] #definition[拟紧(quasi-compact)][ 设 $X$ 是一个拓扑空间,称 $X$ 是拟紧的,如果 $X$ 的任意开覆盖都有有限子覆盖\ (在拓扑学中这就是紧,布尔巴基学派习惯将其称为伪紧) ] #theorem[][ 每个 $D(f)$ 都是拟紧的,特别的 $Spec(A) = D(0)$ 拟紧 ] #proof[ 由于所有 $D(f)$ 构成拓扑基,因此不妨设开覆盖是拓扑基构成的,也即: $ &D(f) subset union.big_(i in I) D(g_i)\ <=>& V(f) supset sect.big_(i in I) V(g_i)\ <=>& V(f) supset V(sum_(i in I) (g_i))\ <=>& f in sqrt(sum_(i in I) (g_i))\ <=>& f^k in sum_(i in I) (g_i) $ 注意到最后一式中 $f^k$ 一定可以被 $g_i$ 中的有限个元素表示,因此倒推可得 $D(f)$ 有有限子覆盖 ] #theorem[][ 任意开集拟紧当且仅当是有限个基本开集的并 ] #proof[ - 有限个拟紧集的并当然拟紧。 - 若开集 $S$ 拟紧,由于基本开集是拓扑基: $ S = union.big_(f in I) D(f) $ 而由 $S$ 拟紧,应当有上式右侧有限个即可覆盖 $S$,当然它们的并就是 $S$ ] #theorem[Hochster][ 设 $X$ 是拓扑空间,则以下条件等价: - $exists A$,$X$ 与 $Spec(A)$ 同胚 - $X$ 伪紧,且有一个均伪紧的开集基,并在有限交下稳定 - 每个不可约闭集有唯一的 generic 点(闭包就是全空间) ] #proof[ 我们不证明这个定理,只是说明谱空间与拓扑学有密不可分的关系 ] 类似素谱,我们可以定义极大谱。它的大部分性质与素谱类似,但在根的处理上更加复杂。 #definition[][ 设 $phi: A -> B$ 是环同态,它将诱导一个映射: $ funcDef(phi^*, Spec(B), Spec(A), P, phi^(-1)(P)) $ (注意到素理想的原像是素理想) 并且满足: - 主开集的原像是主开集,进而连续 - $Inv(phi^*) (V(I)) = V(I B)$, $I$ 是 $A$ 的理想 - $overline(phi^*(V(J))) = V(Inv(phi)(J))$ 此时若 $p = phi(q)$,则称 $q$ 在 $p$ 之上 ] == 素理想的一些性质 #definition[coprime][ 设 $I, J$ 是理想,称它们是互素理想,如果: $ I + J = (1) $ ] #proposition[][ 设 $I + J = (1)$,则 $I sect J = I J$ ] #proof[ - 由定义,$I J subset I sect J$ - 其次: $ I sect J = (I + J)(I sect J) = I (I sect J) + (I sect J) J subset I J + I J = I J $ ] #theorem[中国剩余定理][ 设 $I_i$ 是有限个理想,定义映射: $ funcDef(phi, A, product_i A quo I_i, a, (a + I_i)) $ 则: - 若 $I_i$ 两两互素,则此时有 $I_1 I_2 ... I_n = I_1 sect I_2 ... sect I_n$ - $ker phi = I_1 sect I_2 ... sect I_n$ - $phi$ 是满射当且仅当 $I_i$ 两两互素,此时有: $ A quo (I_1 sect I_2 ... sect I_n) tilde.eq product_i A quo I_i $ ] #proof[ TODO ] #lemma[Prime avoidance][ + 设 $P_i$ 是若干素理想,$I$ 是理想且 $I subset union_i P_i$,则 $exists i,I subset P_i$\ 反之,若 $I$ 不在任何一个 $P_i$ 中,则它不在 $union_i P_i$ 中 + 设 $I_i$ 是理想,$P$ 是素理想,若 $sect_i I_i subset P$,则 $exists i, I_i subset P$\ 进一步,若 $sect_i I_i = P$,则 $exists i, I_i = P$ + 设 $P_i$ 是若干理想,其中至多两个不是素理想,$I$ 是理想且 $I subset union_i P_i$,则 $exists i,I subset P_i$\ ]<prime-avoidance> #proof[ + 我们证明它的反面,目标是构造 $x$ 不落在 $union_i P_i$ 中\ - 若 $n = 1$ 结论平凡 - 若 $n = k$ 成立,则由归纳结论: $ forall k in I, I subset.not union.big_(i in I - {k}) $ 对于每个 $k$,选取 $x_k in I - union.big_(i in I - {k}) P_i$ - 假设对于某个 $k$,$x_k in.not P_k$,则 $x_k$ 即为我们要找的在 $I - union_i P_i$ 中的元素 - 否则,令: $ x = sum_k (product_(j != k) x_j) $ 对于每个 $k$,上式右侧恰有一个元素不落在 $P_k$ 中,从而 $x in.not P_k$,因此 $x$ 就是我们要找的元素 + 用反证法,如若不然,则 $exists x_i in I_i, x_i in.not P$,考察: $ x = product_i x_i $ 显然 $x in sect_i I_i subset P$,但每个 $x_i in.not P$,与素理想的定义矛盾! + 由上面的结论,$I sect (union_(P_i "is prime") P_i) subset union_(P_i "is prime") P_i => exists k, P_k "is prime", I sect (union_(P_i "is prime") P_i) subset P_k$\ 可以不妨假设只有一个素理想并且: - 没有其他理想:显然 - 恰有一个其他理想 $Q$,也即: $ I subset P union Q $ 假设 $I$ 不在其中任何一个,取 $x_P in I - P subset Q, x_Q in I - Q subset P$,显有: $ x = x_P + x_Q $ 不在 $P, Q$ 中任何一个,但在 $I$ 中,矛盾! - 恰有两个其他理想 $Q_1, Q_2$,由之前的证明可知: $ I subset P or I subset Q_1 union Q_2 $ 若前者成立则结论正确,若后者成立仿照前一种情况再次操作即可 ] #corollary[][ 设 ${p_i} subset Spec(A)$,假设 ${p_i}$ 被有限个主开集 $union.big_n D(x_n)$ 所覆盖,则存在某一个主开集 $D(x)$ 覆盖住 ${p_i}$ ] == 自由模 #definition[自由模|free AModuleule][ 称一个自由 $A-$模是同构于: $ plus.circle_(i in I) A $ 的模,指标集有限时也记为 $A^n$ ] #theorem[][ $M$ 是有限生成 $A-$模当且仅当 $M$ 同构于有限自由模的商模 ] #proof[ - 设 $M = sum_(i) A x_i$,构造: $ funcDef(phi, A^n, M, (a_i), sum_(i) a_i x_i) $ 显然是满同态,因此 $ A^n quo ker phi tilde.eq M $ - 设 $M$ 同构于自由模的某个商模,则取 $phi:A^n -> M$ 是同态,容易验证: $ M = sum_i A (phi(epsilon_i)) $ 其中 $epsilon_i$ 为第 $i$ 位为 $1$ 其余为零的坐标 ] #lemma[Nakayama][ 设 $M$ 是有限生成$AModule(A)$, $I$ 是 $A$ 的理想,$phi: M -> M$ 是同态满足 $phi(M) subset I M$,那么存在首一多项式 $f in I[x]$ 使得: $ f(phi) = 0 $ 特别的,取 $I = A$,则 $End_A (M)$ 中每一个元素都被某个多项式零化 ]<Hamiton-Cayley> #proof[ 设 $M = sum_i A x_i$,注意到 $phi(x_i) in I M$,因此存在 $alpha_i in I^n$ 使得: $ phi(x_i) = alpha_i^T X $ 其中 $X = vec(x_1, x_2, dots.v, x_n)$\ 验证: $ sum_j (delta_(i j) phi - a_(i j))(x_j) = 0 $ 也即: $ phi(X) = vec(alpha_1^T, alpha_2^T, dots.v, alpha_n^T) X := B X\ $ 这里 $B$ 是矩阵,当然可以被多项式零化。具体而言,有: $ (phi I - B)X = 0\ (phi I - B)^*(phi I - B) X = det(phi I - B) X = 0 $ 注意到 $det(phi x - B) := f(x) in I[x]$ 首一 ,上式即是说: $ (f(phi)) X = 0 => f(phi) = 0 $ 得证 ] #corollary[][ 设 $M, I$ 满足 $I M = M$,则 $exists x in A, x = 1 mod I and x M = 0$ ] #proof[ 在上面的引理中取 $id: M -> I M$ 即可 ] #corollary[Nakayama, another form][ $M$ 有限生成,$I subset $ Jacob radical\ 若 $I M = M$, 则 $M = 0$ ] #proof[ 根据引理,可获得 $x$ 满足 $x = 1 mod I and x M = 0$\ 注意到 $x in 1 +$ Jacob radical 给出它是一个单位(@radicalForm),继而 $M = 0$ ] #corollary[][ $M$ 有限生成,$I subset $ Jacob radical, $N$ 是 $M$ 子模\ 若 $M = N + I M$ 则 $N = M$ ] #proof[ 考虑 $M quo N$ 中,注意到: $ M quo N = (N + I M) quo N = I (M quo N) $ 结合有限生成模的商模仍然有限生成,因此可以利用上面的引理 ] #proposition[][ 设 $A$ 是局部环,唯一素理想是 $m$,$M$ 是有限生成 $AModule(A)$ 则: $ M quo m M 是 A quo m "上的有限维向量空间" $ 同时,设 $x_i in M$ 在 $M quo m M$ 中的像生成构成线性空间的基,则它们也是 $M$ 的生成元 ]<basis-is-generator-Nakayama> #proof[ 设 $x_i$ 是这样一组基,取 $N = sum_i A x_i subset M$,取满同态 $phi: N -> M -> (M quo m) M$ 显然 $N quo m M = M quo m M$,因此有 $ N + m M = M $ 由上面的引理可知 $N = M$ ] == 代数 #definition[代数][ 给定环同态 $A ->^f B$ ,可将 $B$ 看作 $AModule(A)$,这个模就称为环上的代数。$A-$代数的同态自然定义为环之间的同态,保证交换图表: $ #align(center)[#commutative-diagram( node((0, 0), $A$, 1), node((0, 1), $C$, 2), node((1, 0), $B$, 3), arr(1, 2, $$), arr(3, 2, $$), arr(1, 3, $$),)] $ ] #example[][ - 每个环都是 $ZZ$ 代数 - 设 $k$ 是域,$phi: k -> B$ 是环同态。熟知 $phi$ 一定是单射,进而 $k$ 一定是 $k-$代数的子环 ] #definition[][ - 称 $B$ 是有限 $A-$代数,如果它作为 $AModule(A)$ 是有限生成的 - 称 $B$ 是有限生成的,如果存在有限集 ${x_i}$,存在满射: $ A[x_1, x_2, ..., x_n] -> B $ ] #example[][ - 多项式环当然是有限生成代数,但不是有限代数 ] #definition[张量积][ 设 $B, C$ 是 $A-$代数,则 $B tensorProduct C$ 也有自然的代数结构,称为代数的张量积 ] == 同调代数简介 #definition[复形][ 设有一列 $AModule(A)$: $ ... -> M_(i-1) ->^(f_i) M_i ->^(f_(i+1)) M_(i+1) ...\ $ - 称之为一个 复形|(cochain) complex,如果 $f_(i+1) compose f_i = 0 <=> im f_i subset ker f_(i+1)$ - 称之为在 $i$ 处 正合|exact,如果 $im f_i = ker f_(i+1)$ 对一般的复形,定义: $ H_i (M) = ker f_(i+1) quo im f_i $ 为(上)同调群,显然该处正合当且仅当 $H_i = {0}$ ] #example[][ - $0 -> M' ->^f M$ 正合当且仅当 $f$ 单射 - $M ->^g -> M' -> 0$ 正合当且仅当 $g$ 满射 - $0 -> M' ->^f M ->^g -> M'' -> 0$ 正合当且仅当 $f$ 单射,$g$ 满射 - 长正合列可以分裂,例如设 $... -> M_(i-1) ->^(f_i) M_i ->^(f_(i+1)) M_(i+1) ...$ 于该处正合,则令 $N_i = ker f_(i+1) = im f_i$,有: $ 0 -> N_i -> M_i -> im f_(i+1) = N_(i+1) -> 0 $ 正合 ] #theorem[正合判别法][ 在 $AModule(A)$ 范畴中: - $M' ->^mu M ->^nu M'' -> 0$ 正合当且仅当任取 $AModule(A) space N$,序列: $ 0-> Hom_A (M'', N) ->^(nu') Hom_A (M, N) ->^(mu') Hom_A (M', N) $ 正合\ 换言之,如果将 $Hom_A (*, N)$ 看作函子,则这个函子是反变左正合的\ - 对偶的,$0-> M' ->^mu M ->^nu M''$ 正合当且仅当任取 $AModule(A) space N$,序列: $ 0-> Hom_A ( N, M') ->^(nu') Hom_A (N, M) ->^(mu') Hom_A ( N, M'') $ 正合\ 也即函子 $Hom_A (N, *)$ 是共变左正合的 ]<exact-test> #proof[ 只证明一个方向,另一侧是类似的\ 设 $forall N in Mod(A), 0 -> Hom_A (M'', N) ->^nu' Hom_A (M, N) ->^mu' Hom_A (M', N) $ 正合,往证: $ M' ->^mu M ->^nu M' -> 0 $ 正合,只需验证: - $nu$ 是满射 $<=> M'' \/ im nu = 0$\ 取 $N = M'' \/ im nu$,注意到: $ Hom_A (M'', N) ->^nu' Hom_A (M, N) $ 其中诱导的 $nu'$ 是单射(条件),取自然同态 $pi: M'' -> M'' \/ im nu in Hom_A (M'', N)$,发现: $ nu'(pi) = pi compose nu = 0 => pi = 0 => M'' \/ im nu = 0 $ 证毕 - $im mu = ker nu$ - 先证明 $im mu subset ker v$,事实上,注意到: $ mu' compose nu' = 0 => (mu' compose nu')(*) = 0 => * compose nu compose mu = 0, forall * in M'' -> N $ 取 $* = id_M''$ 即得 $nu compose mu = 0$ - 再证明 $ker nu subset im mu$,取 $N = M \/ im mu$ 和自然的同态 $pi: M -> N$,有: $ pi compose mu = mu'(pi) =0 => pi in ker mu' = im nu' => pi = nu'(f) = f compose nu\ ker(nu) subset ker(f compose nu) = ker(pi) = im nu $ 证毕 ] #definition[(共变/反变函子|covarient/contravarient functor)][$Mod(A) -> Mod(B)$ 称为共变/反变函子,包括以下资料和性质: - $forall M in Mod(A), exists F M in Mod(B)$ - 共变函子是指: $forall phi in Hom_A (M, N), exists F(phi) in Hom_A (F M,F N)$,使得: $ F(g compose h) = F(g) compose F(h)\ F(id) = id $ 更进一步,如果 $F: Hom_A (M, N) -> Hom_B (F M, F N)$ 均是(模同态作为模的加法群)群同态,则称 $F$ 为加性函子 - 反变函子是指 $forall phi in Hom_A (M, N), exists F(phi) in Hom_A (F N,F M)$ 满足: $ F(g compose h) = F(h) compose F(g) \ F(id) = id $ ] #definition[正合函子][ 设 $F$ 是加性共变函子,$G$ 是加性反变函子,称 $F | G$ 是左正合函子,如果任给正合列: $ 0 -> M' -> M -> M' $,均有: $ 0 -> F M' -> F M -> F M'' \ 0 -> G M'' -> G M -> G M' $ 正合\ 反之,若如果任给正合列: $ M' -> M -> M' -> 0 $,均有:: $ F M' -> F M -> F M'' -> 0\ G M'' -> G M -> G M' -> 0 $ 正合,则称为右正合函子\ 若函子同时左正合,右正合,则称之为正合函子,它保持所有正合列 ] #example[][ $Hom(M, *) : Mod(A) -> Mod(A)$ 是共变的加性函子,另一侧 $Hom(*, N)$ 是反变函子,它们都是左正合的 ] #lemma[][ 设 $E_i$ 是复形,则 $directSum_i (E_i)$ 正合当且仅当 $forall i, E_i$ 正合 ]<directSum-exact> #proof[ 注意到 $ker(directSum_i (f_i)) = directSum_i ker f_i$,$im$ 类似,因此结论显然 ] #definition[导出函子][ 对于任意的左正合(加性)函子 $F$,一族函子 $Mod(A)-> Mod(B)$: $ {R^i F : Mod(A) -> Mod(B)} $ 称为(右)导出函子,如果: - $R^0 F = F$ - 任取短正合列: $ 0 -> X -> Y -> Z -> 0 $ 有长正合列: $ 0 -> F X -> F Y -> F Z -> R^1 F X -> R^1 F Y -> R^1 F Z ->\ ... -> R^n F X -> R^n F Y -> R^n F Z -> ... $ - 具有函子性(保持复形的同态),也若有交换图: $ 0 -> &X -> &&Y -> && Z -> 0\ &arrow.b &&arrow.b &&arrow.b \ 0 -> &X -> &&Y -> && Z -> 0\ $ 则上下两正合列对应的长正合列也交换 给定右正合函子,其左导出函子 ${L_i F : Mod(A) -> Mod(B)}$ 也可以对偶地定义 ] #example[][ 命题:若 $F$ 正合,则导出函子就是 $R^0 F = 0, R^i F = 0$ (这当然也是 $F$ 右正合的充要条件)因此一般的导出函子可以看作与正合函子的距离 ] #definition[][ $ "Ext"^i (*, N) := R^i Hom(*, N)\ "Ext"^i (M, *) := R^i Hom(M, *) $ 称为拓展组 (extension group),显然需要验证从两种方法定义的 $"Ext"^i (M, N)$ 是相同的,这称之为 Balance property - 若 $Hom(M, *)$ 正合,则称 $M$ 是 投射|projective 模 - 若 $Hom(*, N)$ 正合,则称 $N$ 是 入射|injective 模 ] 问题:何时 $Hom(*, N), Hom(M, *)$ 正合? 既然上述两个函子都左正合,只要它们都右正合即可 #proposition[][ - $N$ 是入射模当且仅当任取单同态 $phi: X -> Y$,都有 $phi': Hom(Y, N) -> Hom(X, N)$ 是满射 - $N$ 是投射模当且仅当任取满同态 $phi: X -> Y$,都有 $phi': Hom(N, X) -> Hom(N, Y)$ 是满射 ] #proof[ 只证明第一条,第二条类似\ - 假如它是入射模,则它应该保持正合列: $ 0 &-> X &&->^(phi) Y &&->^() Y quo im phi &&-> 0\ 0 &-> Hom(Y quo im phi, N) &&->^() Hom(Y, N) &&->^(phi') Hom(X, N) &&-> 0 $ 蕴含 $phi'$ 是满射 - 反之,任取正合列: $ 0 &-> X &&->^(phi_1) Y &&->^(phi_2) Z &&-> 0 $ 往证: $ 0 &-> Hom(Z, N) &&->^(phi'_2) Hom(Y, N) &&->^(phi'_1) Hom(X, N) &&-> 0 $ 的正合性,前面已经证明了左正合,这里只需要 $phi'_1$ 是满射就足够了,而这就是条件 ] #proposition[提升性质][ - $N$ 是入射模当且仅当任取单同态 $phi: X -> Y$ 和同态 $psi: X -> N$,存在 $psi': Y -> N$ 使得以下交换图表成立: #align(center)[#commutative-diagram( node((0, 0), $X$, "1"), node((0, 1), $Y$, "2"), node((1, 0), $N$, "3"), arr("1", "2", $phi$,inj_str), arr("2", "3", $exists psi'$), arr("1", "3", $psi$), )] - $M$ 是投射模当且仅当以下交换图表: #align(center)[#commutative-diagram( node((0, 0), $X$, "1"), node((0, 1), $Y$, "2"), node((1, 0), $M$, "3"), arr("2", "1", $phi $, surj_str), arr("3", "2", $exists psi' $), arr("3", "1", $psi $),)] ] #proof[ $ phi' 满 <=> forall x: X -> N, exists y: Y -> N, x = y compose phi $ 这就是之前的命题\ $ Y = ZZ, X = ZZ_p $ ] 事实上就是对于任何满射 $phi: X -> Y$,诱导的 $phi': Hom_A (M, X) -> Hom_A (M, Y)$ 也是满射,或者说对于所有 $phi: X- > Y$ 是满射和同态 $psi: M -> Y$,均存在 $psi' : M -> X$ 使得 $phi compose psi' = psi$ #proposition[][ 设 $0 -> &X ->^f &&Y ->^g && Z -> 0$ 正合, + 若 $X$ 入射或 $Z$ 投射,则该正合列分裂,也即: $ Y tilde.eq X plus.circle Z $ + 若 $X$ 入射,则 $Y$ 入射 $<=> Z$ 入射; 若 $Z$ 投射,则 $Y$ 投射 $<=> X$ 投射 ] #proof[ 只证明入射一侧 + 根据之前的性质,题上的正合列给出 $f$ 单射,因此有下面的交换图表: #align(center)[#commutative-diagram( node((0, 0), $X$, "1"), node((0, 1), $Y$, "2"), node((1, 0), $X$, "3"), arr("1", "2", $f$,inj_str), arr("2", "3", $exists f'$), arr("1", "3", $id$), )] 进一步,有: $ f' compose f = id => (id - f compose f')f = 0 $ 表明 $im f = ker g subset ker (id - f compose f')$,令 $h = id - f compose f'$ 如下交换图表给出: #align(center)[#commutative-diagram( node((0, 0), $Y$, "1"), node((0, 1), $Y quo ker g$, "2"), node((1, 0), $Y$, "3"), node((-1, 1), $Z$, "4"), arr("1", "2", $$, surj_str), arr("1", "3", $h$), arr("2", "3", $exists !h'$), arr("2", "4", $$, bij_str), arr("1", "4", $g$, surj_str) )] 其中,$h'$ 利用 $ker g subset ker h$ 产生,上半部分和下半部分的交换性是熟知的,注意到: $ Y -> Z -> Y quo ker g -> Y = (Y -> Z -> Y quo ker g) -> Y = (Y -> Y quo ker g) -> Y\ = Y -> (Y quo ker g -> Y) = Y -> Y $ 因此存在 $r: Z -> Y$ 使得: $ id - f compose f' = r compose g\ g(id - f compose f') = g - (g compose f) compose f' = g = g (r g) = (g r) g $ 由于 $g$ 是满射,故有右逆,上式给出 $g r= id$\ 此外还有: $ f f' + r g = id\ $ 以下性质: $ g f = 0\ f f' + r g = id\ f' f = id\ g r = id $ 表明直积分解成立 + 由于 $Y tilde.eq X plus.circle Z$ 故 $Hom(*, X) plus.circle Hom(*, Z) tilde.eq Hom(*, Y)$,再加上 $Hom(*, X)$ 是正合函子,因此当且仅当 $Hom(*, Z)$ 正合 ] #proposition[][ - 自由 $A-$模是投射模 - 投射模都是自由模的直和项(与其它模可以直和得到自由模) ]<projective-module> #proof[ - 设文字集为 $I$,有: $ Hom(A^I, N) = product_I Hom_A (A, N) = product_I N $ - 注意到可以找到满射: $ f: plus.circle_(m in M) A &-> M\ (a_m) &-> sum a_m m $ 这是满射,因此有交换图表: #align(center)[#commutative-diagram( node((0, 0), $M$, "1"), node((0, 1), $plus.circle_(m in M) A$, "2"), node((1, 0), $M$, "3"), arr("2", "1", $f$, surj_str), arr("3", "2", $exists! f' $), arr("3", "1", $id $), )] 不难看出 $f'$ 一定是单射,进而: $ 0 -> ker f -> plus.circle_(m in M) A ->^(f) M -> 0 $ 是正合列,结合 $M$ 投射,$f f' = id$,利用上面的命题知正合列分裂,继而: $ plus.circle_(m in M) A tilde.eq ker f directSum M $ ] #theorem[Baer][ $M$ 是入射模当且仅当任取 $A$ 的理想 $I$ 以及模同态 $I ->^phi M$,存在 $psi: A -> M$ 使得: $ psi|_I = phi $ ] #proof[ - 若 $M$ 入射,则这就是之前讨论中的一种特殊情况 - 反之,若延拓总是存在,令 $X = phi(I)$,利用 Zoun 引理找出所有入射: $ Sigma = {X' subset Y | X subset X' subset Y "是子模,使得" X -> M "可延拓到" X' -> M} $ 验证条件后它将有极大元 $X'$,为了证明 $X' = Y$,如若不然,选出 $b in Y - X'$,希望作出延拓: $ phi': X' + (b) -> M $ 为此,设 $I = {a in A | a b in X'} = (X' : b)$ 是理想,定义 $pi: (a : I) ->(phi(a b) : M)$,由条件将存在同态: $ f: A -> M $ 则取 $phi'(x' + a b) = phi(x') + f(a b)$ 即可 ] 证明: #example[][ - 设 $I = (a)$ 且 $m$ 入射,则有: $ psi(a) = phi(a)\ psi(a) = psi(a dot 1) = $ - 由 Baer 可以证明,$M$ 是 $AModule(ZZ)$当且仅当对于所有 $n in NN$,都有 $n M = M$ - 设 $A$ 是环,$I$ 是入射 $ZZ$ 模,则: $ Hom_ZZ (A, I) $ 是入射 $A-$模\ 这是因为注意到: $ Hom_A (M, Hom_ZZ (A, I)) tilde.eq Hom_ZZ (M, I) $ 同构如此给出: $ f: (M -> I) -> (m -> [a -> f(a m)]): M ->Hom_ZZ (A, I)\ g: (M -> Hom_ZZ (A, I)) -> (m -> (g(m))1) : $ ] #theorem[][导出函子存在且在同构的意义下唯一] #proof[ 考虑左正合函子的导出,如此定义 $R^i F$: - 首先,找到入射同态 $M -> I^0$ 使得 $I^0$ 入射。只需取: $ I' = Hom_ZZ (A, times.circle/ZZ) I^0 = product_(Hom_A (M, I')) I'\ phi(m) =product_(f in Hom_A (M, I')) f(m) $ - 反复进行如上步骤,找到正合列: $ 0 -> M -> I^0 -> I^1 -> ... $ 使得 $I^i$ 都是入射模 - 定义: $ R^i F(M) = H^i (0 -> F I^0 -> F I^1-> ... ) $ (第 $i$ 个位置的同调群) 由 $F$ 左正合: $ 0 -> F M -> F I^0 -> F I^1 $ 正合,可得 $H^0 (0 -> F I^0 -> F I^1-> ... ) = F M$,表明 $R^0 F = F$\ 之后的证明要把短正合列延长至长正合列,具体细节在下半学期补充 对偶的,右正合函子的导出函子大约是: $ H_(-i) (... -> F P^1 -> F P^0 -> 0) = R^i F $ 其中 $P$ 是投射对象 ] #corollary[][ - 设 $M$ 是投射模,则 $L_i F(M) = 0, forall i > 0$ ] #lemma[Snake Lemma|蛇形引理][ 设 $A$ 是环,图: #align(center)[#commutative-diagram( node((0, 0), $0$, "1"), node((1, 0), $Y'$, "3"), node((1, 1), $X'$, "4"), node((2, 0), $Y$, "5"), node((2, 1), $X$, "6"), node((3, 0), $Y''$, "7"), node((3, 1), $X''$, "8"), node((4, 1), $0$, "9"), arr("1", "3", $$), arr("4", "3", $alpha$), arr("3", "5", $mu$), arr("4", "6", $f$), arr("6", "5", $beta$), arr("5", "7", $nu$), arr("6", "8", $g$), arr("8", "7", $gamma$), arr("8", "9", $$), ) ] 是两个正合列,按照如下方式定义 $delta: ker gamma -> coker alpha$,任取 $x' in X''$ - 由 $g$ 是满射,存在 $x$ 使得 $g(x) = x''$ - 令 $y = beta(x)$,则: $ nu(y) = nu(beta(x)) = gamma(g(x)) = gamma(x'') = 0 $ 因此 $y in ker nu$ - 由 $ker nu = im mu$,可取 $y' in Y'$ 使得 $mu(y') = y$,定义: $ delta(x'') = overline(y') $ 为了保证这是良定义的,第三步 $y'$ 对应的等价类当然是唯一的,我们需要验证第一步 $x$ 的取法不影响结果。事实上: - 设 $g(x_1) = g(x_2) = x'' => x_1 - x_2 in ker g = im f$,因此存在 $x'$ 使得 $f(x') = x_1 -x_2$ - 从而: $ y_1 - y_2 = beta(x_1 - x_2) = beta(f(x')) = mu(alpha(x'))\ mu(y'_1 - y'_2) = y_1 - y_2 = mu(alpha(x'))\ $ 而 $mu$ 是单射,因此: $ y'_1 - y'_2 = alpha(x) in im(alpha) $ 它们当然在 $coker(alpha)$ 中对应相同的等价类 将有: #align(center)[#commutative-diagram( node((1, 0), $ker alpha$, "3"), node((1, 1), $coker alpha$, "4"), node((2, 0), $ker beta$, "5"), node((2, 1), $coker beta$, "6"), node((3, 0), $ker gamma$, "7"), node((3, 1), $coker gamma$, "8"), arr("3", "5", $f$), arr("4", "6", $mu$), arr("5", "7", $g$), arr("6", "8", $nu$), arr("7", "4", $delta$) ) ] 给出正合列 此外,若: #align(center)[#commutative-diagram( node((0, 0), $0$, "1"), node((1, 0), $Y'$, "3"), node((1, 1), $X'$, "4"), node((2, 0), $Y$, "5"), node((2, 1), $X$, "6"), node((3, 0), $Y''$, "7"), node((3, 1), $X''$, "8"), node((4, 1), $0$, "9"), node((4, 0), $0$, "10"), node((0, 1), $0$, "11"), arr("1", "3", $$), arr("4", "3", $alpha$), arr("3", "5", $mu$), arr("4", "6", $f$), arr("6", "5", $beta$), arr("5", "7", $nu$), arr("6", "8", $g$), arr("8", "7", $gamma$), arr("8", "9", $$), arr("7", "10", $$), arr("11", "4", $$), ) ] 是两列正合列,则结论的正合列变成: #align(center)[#commutative-diagram( node((0, 0), $0$, "0"), node((1, 0), $ker alpha$, "3"), node((1, 1), $coker alpha$, "4"), node((2, 0), $ker beta$, "5"), node((2, 1), $coker beta$, "6"), node((3, 0), $ker gamma$, "7"), node((3, 1), $coker gamma$, "8"), node((4, 1), $0$, "9"), arr("3", "5", $f$), arr("4", "6", $mu$), arr("5", "7", $g$), arr("6", "8", $nu$), arr("7", "4", $delta$), arr("0", "3", $$), arr("8", "9", $$), ) ] ] #proof[ - 除了 $delta$ 处之外的结论都是显然的,只证明 $delta$ 处。有: $ delta(x'') = 0 <=> exists x' in X', x - x' in ker(alpha) \ <=> x'' in im(ker beta -> ker gamma) $ $ overline(y') in ker(coker(alpha) -> coker(beta)) <=> exists x_0 in X, beta(x_0) = mu(y')\ => exists x_0 in X, gamma(g(x_0)) = mu(beta(x_0)) = nu(mu(y') = 0)\ => exists x_0 in X, x'' = g(x_0) in ker gamma $ ] 有时通过蛇引理得到的正合列是自然的/典范的/函子的,因为若两组符合蛇引理条件的正合列之间有态射,则蛇引理给出的两个正合列之间也有相应的态射 #theorem[同调代数基本定理][ 设 $A$ 是环,$0 -> X^* ->^f Y^* ->^g Z^* -> 0 $ 是模的复形的正合列 #align(center)[#commutative-diagram( node((0, 0), $0$, "1"), node((0, 1), $0$, "2"), node((1, 0), $X^(n)$, "3"), node((1, 1), $X^(n-1)$, "4"), node((2, 0), $Y^n$, "5"), node((2, 1), $Y^(n-1)$, "6"), node((3, 0), $Z^n$, "7"), node((3, 1), $Z^(n-1)$, "8"), node((4, 1), $0$, "9"), node((4, 0), $0$, "10"), arr("1", "3", $$), arr("2", "4", $$), arr("4", "3", $alpha^n$), arr("3", "5", $mu$), arr("4", "6", $f$), arr("6", "5", $beta^n$), arr("5", "7", $nu$), arr("6", "8", $g$), arr("8", "7", $gamma^n$), arr("8", "9", $$), arr("7", "10", $$), ) ] 蛇引理给出正合列: #align(center)[#commutative-diagram( node((1, 0), $ker alpha^n$, "3"), node((1, 1), $coker alpha^n$, "4"), node((2, 0), $ker beta^n$, "5"), node((2, 1), $coker beta^n$, "6"), node((3, 0), $ker gamma^n$, "7"), node((3, 1), $coker gamma^n$, "8"), arr("3", "5", $$), arr("4", "6", $$), arr("5", "7", $$), arr("6", "8", $$), arr("7", "4", $delta$) ) ] 最终给出上同调群的长正合列: #align(center)[#commutative-diagram( node((0, 0), $dots.v$, "2"), node((1, 0), $H^(n-1)(X)$, "3"), node((1, 1), $H^n (X)$, "4"), node((2, 0), $H^(n-1) (Y)$, "5"), node((2, 1), $H^n (Y)$, "6"), node((3, 0), $H^(n-1) (Z)$, "7"), node((3, 1), $H^n (Z)$, "8"), node((4, 1), $dots.v$, "9"), arr("3", "5", $$), arr("4", "6", $$), arr("5", "7", $$), arr("6", "8", $$), arr("7", "4", $delta^n$), arr("2", "3", $$), emptyArrow(2, 3), emptyArrow(8, 9), ) ] ] #proof[ 在下半学期给出 ] #corollary[][ - 若 $X^*, Y^*, Z^*$ 之中有两个已经正合,则第三个也正合 - (9-Lemma)设三列短正合列有: $ 0 -> X^* -> Y^* -> Z^* -> 0 $ - 若三者中间项构成的行正合,则上下行有相同的正合性 - 若上下两行正合,并且中间行是复形,则三行都是正合的 ] #lemma[5-lemma][ 设有交换图上下行都正合: #align(center)[#commutative-diagram( node((0, 0), $X_0$, 0), node((0, 1), $X_1$, 1), node((0, 2), $X_2$, 2), node((0, 3), $X_3$, 3), node((0, 4), $X_4$, 4), node((1, 0), $Y_0$, 5), node((1, 1), $Y_1$, 6), node((1, 2), $Y_2$, 7), node((1, 3), $Y_3$, 8), node((1, 4), $Y_4$, 9), arr(0, 0 + 1, $u_0$), arr(1, 1 + 1, $u_1$), arr(2, 2 + 1, $u_2$), arr(3, 3 + 1, $u_3$), arr(0 + 5, 0 + 6, $v_0$), arr(1 + 5, 1 + 6, $v_1$), arr(2 + 5, 2 + 6, $v_2$), arr(3 + 5, 3 + 6, $v_3$), arr(0, 0 + 5, $f_0$), arr(1, 1 + 5, $f_1$), arr(2, 2 + 5, $f_2$), arr(3, 3 + 5, $f_3$), arr(4, 4 + 5, $f_4$),)] - 若 $f_0$ 满,$f_1 f_3$ 是单射,则 $f_2$ 单射 - 若 $f_4$ 单,$f_1 f_3$ 是满射,则 $f_2$ 满射 - 特别的,若 $f_0$ 满,$f_4$ 单,$f_1 f_3$ 是双射,则 $f_2$ 是双射 ] #proof[ - $ forall x_2 in X_2, f_2 (x_2) = 0 &=> f_3 (u_2 (x_2)) = v_2 (f_2 (x_2)) = 0\ &=> u_2 (x_2) = 0\ &=> exists x_1 in X_1,x_2 = u_1 (x_1)\ & quad=> f_2 (u_1 (x_1)) = nu_1 (f_1 (x_1)) = 0\ & quad=> f_1 (x_1) in ker v_1 = im v_0\ & quad=> exists y_0 in Y_0, nu_0 (y_0) = f_1 (x_1)\ & quad quad => exists x_0 in X_0, f_0 (x_0) = y_0\ & quad quad quad =>nu_0 (f_0 (x_0)) = f_1 (x_1) = f_1 (u_0 (x_0))\ & quad quad quad =>x_1 = u_0 (x_0)\ & quad => x_1 in im u_0 = ker u_1\ & quad => u_1(x_1) = 0\ & => x_2 = 0\ $ - $ y_2 in Y_2 &=> exists x_3 in X_3, v_2 (y_2) = f_3 (x_3)\ &quad => v_3 (f_3 (x_3)) = v_3 (v_2 (y_2)) = 0 = f_4 (u_3 (x_3))\ &quad => u_3 (x_3) = 0\ &quad => exists x_2 in X_2, u_2(x_2) = x_3\ &quad quad =>v_2 (y_2) = f_3 (x_3) = f_3 (u_2 (x_2))=v_2 (f_2 (x_2))\ &quad quad =>y_2 - f_2 (x_2) in ker v_2 = im v_1\ &quad quad quad =>exists x_1 in X_1 y_2 - f_2 (x_2) = v_1 (f_1 (x_1))=f_2 (u_1 (x_1))\ &quad quad quad =>exists x_1 in X_1 y_2 = f_2 (x_2 + u_1 (x_1))\ & => y_2 = im f_2\ $ ] #remark[Diagram Chasing][ Diagram chasing(追图)是常见的证明正合列的方法,也即在交换图上追踪对象。以上两个引理的证明即体现了这个思想 ] = 局部化 == 环的局部化 设 $X = Spec(A), x in X$ 往往看作点,此时 $A$ 可以看作 $X$ 上的全局同态函数。当然,我们也应该考虑在 $x$ 邻域处的同态函数,这就是局部化(localization)的思想 #definition[乘法封闭|multiclosed][ 称 $S subset A$ 乘法封闭,如果 $1 in S$ 且 $S$ 关于乘法封闭 ] #example[][ - 设 $p$ 是素理想,则 $A - p$ 是乘法封闭的 - 设 $f in A$,则 $union_(n in NN) {f^n}$ 是乘法封闭的 ] #let InvSA = $Inv(S) A$ #definition[][ 设 $S subset A$ 乘法封闭,则存在环 $Inv(S) A$ 以及同态 $phi: A -> Inv(S) A$ 满足以下的泛性质: - $phi(S) in U(InvSA)$ - 若 $g : A -> B$ 满足 $g(S) subset U(B)$,则存在唯一的同态 $g' : InvSA -> B$ 使得: #align(center)[#commutative-diagram( node((0, 0), $A$, 1), node((0, 1), $B$, 2), node((1, 0), $InvSA$, 3), arr(1, 2, $g$), arr(3, 2, $exists ! g'$), arr(1, 3, $phi$),)] 称该环为 $A$ 关于 $S$ 的局部化/分式环 ] #proof[ - 先给出 $InvSA$ 的构造,先定义集合: $ InvSA = S times A quo ~ := {a/s}\ (a_1, s_1) ~ (a_2, s_2) <=> exists s in S, s(a_1 s_2 - a_2 s_1) = 0 $ 这里乘以 $s$ 是因为环中未必有消去律,可以验证它确实是等价关系 - 再给出环运算,完全仿照分式的运算定义: $ (a_1/s_1) + (a_2/s_2) = (a_1 s_2 + a_2 s_1) / (s_1 s_2)\ (a_1/s_1) * (a_2/s_2) = (a_1 a_2) / (s_1 s_2) $ 并且 $1/1$ 是其中单位。可以验证它这些运算良定义并且满足环的公理 - 定义: $ funcDef(phi, A, InvSA, a, a/1) $ 显然: $ forall s in S, phi(s) * 1/s = 1 $ 因此满足要求 - 最后验证泛性质,定义: $ funcDef(g', InvSA, B, a/s, g(a) / g(s)) $ 注意到 $g(s)$ 是可逆元,定义是有意义的。\ 可以验证它是良定义的同态,并且确实满足交换图表。\ 同时定义当然是唯一的,因为: $ g'(a/1) = g'(phi(a)) = g(a)\ g'(a/s) = g'(a/1) * g'(1/s) = g(a) * g(s)^{-1} = g(a) / g(s) $ 因此同态已经被唯一确定 ] #remark[][ - 注意 $phi$ 未必是单射,因此 $phi(a) = a/1 = 0 <=> exists s in S, s a = 0$\ 显然在一般的环中不能保证 $phi$ 是单射,但是在整环中,$phi$ 是单射 - 若 $s in S$ 幂零,则 $phi(s)^n = 0$ 可逆,意味着 $InvSA = 0$ ] #definition[][ - 设 $p$ 是素理想,则称 $A_p = Inv((A - p)) A$,并有 $A_p$ 是局部环,唯一的极大理想便是 $p A_p$ - $A_f = Inv({f_n}) A = A[1/f] = A[x] quo (x f - 1)$ 也是分式环 - $ZZ_((p)) = {m/n | (p, n) = 1}$ 是素理想生成的局部化 ] #proof[ 只要证明 $A_p quo p A_p$ 是域,任取其中元素: $ a/s + p A_p = (a + p)/s $ - $a in p => (a + p)/s = 0$ - $a in.not p => a/s$ 可逆 因此结论成立 ] == 模的局部化 #definition[模的局部化][ 设 $S subset A$ 乘法封闭,则有函子: $ Inv(S) : Mod_A -> Mod_(InvSA) $ 及交换图表: #align(center)[#commutative-diagram( node((0, 0), $M$, 1), node((0, 1), $Inv(S) M$, 2), node((1, 0), $N$, 3), node((1, 1), $Inv(S) N$, 4), arr(1, 2, $$), arr(1, 3, $f$), arr(2, 4, $exists f'$), arr(3, 4, $$),)] ] #theorem[][ $Inv(S)$ 是正合函子 ] #proof[ 给定正合列: $ M' ->^f M ->^g M'' $ 验证: $ Inv(S) M' ->^f' Inv(S) M ->^g' Inv(S) M'' $ 也正合 - $Inv(S) g compose Inv(S) f = Inv(S)(g compose f) = 0$,至少是复形 - 只需证明 $im Inv(S) f supset ker Inv(S) g$,为此 ] #corollary[][ - $Inv(S)(N quo M) tilde.eq (Inv(S) N) quo (Inv(S) M)$ - $Inv(S) (N sect P) = Inv(S) N sect Inv(S) P$ - $Inv(S) (N + P) = Inv(S) N + Inv(S) P$ ] #proof[ - 注意到: $ 0 -> M -> N -> N quo M -> 0 $ 正合,由上面的命题知: $ 0 -> Inv(S) M -> Inv(S) N -> Inv(S) (N quo M) -> 0 $ 正合,因此结论成立 - 利用正合列: $ 0 -> N sect P -> M -> M quo N times M quo P $ 得到: $ 0 -> Inv(S) (N sect P) -> Inv(S) M -> Inv(S) (M quo N times M quo P) -> 0 $ 正合,在最后一项将 $Inv(S)$ 换入即可 - 利用正合列: $ 0 -> N plus.circle P -> M -> M quo (N + P) -> 0 $ 得到: $ 0 -> Inv(S) (N plus.circle P) -> Inv(S) M -> Inv(S) (M quo (N + P)) -> 0 $ 利用事实 $N+P = im(N plus.circle P -> M )$ 再次换入即可 ] #theorem[][ 设 $M$ 是一个有限表示,也即存在正合列: $ A^p -> A^q -> M -> 0 $ 则: $ Inv(S) Hom_A (M, N) tilde.eq Hom_(InvSA) (Inv(S) M, Inv(S) N) $ ] #proof[ 由条件依次得到正合列: $ 0 -> Hom_A (M, N) -> Hom_A (A^q, N) -> Hom_A (A^p, N) \ 0 -> Inv(S) Hom_A (M, N) -> Inv(S) Hom_A (A^q, N) -> Inv(S) Hom_A (A^p, N) $ 但是可以验证: $ Inv(S) Hom_A (A^p, N) tilde.eq plus.circle Inv(S) N tilde.eq Hom_(InvSA) (Inv(S) A^p, Inv(S) N) $ 得到: #align(center)[#commutative-diagram( node((0, 0), $0$, 1), node((0, 1), $Hom_A (M, N)$, 2), node((0, 2), $Hom_A (A^p, N)$, 3), node((0, 3), $Hom_A (A^q, N)$, 4), node((1, 0), $0$, 5), node((1, 1), $Hom_(Inv(S) A)(Inv(S) M, Inv(S), N)$, 6), node((1, 2), $Hom_(Inv(S) A)(Inv(S) A^p, Inv(S), N)$, 7), node((1, 3), $Hom_(Inv(S) A)(Inv(S) A^q, Inv(S), N)$, 8), arr(1, 2, $$), arr(2, 3, $$), arr(3, 4, $$), arr(5, 6, $$), arr(6, 7, $$), arr(7, 8, $$), arr(2, 6, $$), arr(3, 7, $$, bij_str), arr(4, 8, $$, bij_str),)] 利用 5-Lemma 即可 ] #proposition[][ $M -> product_(m in "Max" (A)) M_m$ 是单射 ] #proof[ 换言之,需要证明: $ forall x in M, (forall m in "Max"(A), x = 0 in M_m -> x = 0) $ 如若不然,取 $I = "Ann"(x) != (1)$,取包含 $I$ 的极大理想 $m$,有: $ x/1 = 0 => exists t in A - M, t x = 0 => exists t in A -M, t in I $ 这与 $I subset m$ 矛盾! ] #corollary[][ 以下事实等价: - $M = 0$ - $M_p = 0, forall p in Spec(A)$ - $M_m = 0, forall m in "Max"(A)$ ] #corollary[][ 对于 $AModule(A)$同态 $phi$,它是单/满/双射当且仅当在所有素理想/极大理想的局部环中是单/满/双射 ] #remark[][ 像这样性质 $P$ 成立当且仅当它在所有素理想/极大理想的局部化中成立的性质被称作局部性质(local property) ] == 分式环的素理想 #proposition[][ - $I(InvSA) = (1) <=> S sect I != emptyset$ - $Spec (InvSA) = {p InvSA | p in Spec(A) and p sect S = emptyset}$ - $Inv(S) sqrt(I) := sqrt(Inv(S) I)$ ] #proof[ + - 设 $I(InvSA) = (1)$,则存在 $1 = i /s$,表明: $ exists s' in S, s'(a - s) = 0 => s' a = s' s $ 则 $s' a = s' s in I sect S$ - 取元素 $in S sect I$ 显然 + 注意到存在自然同态 $f: A -> Inv(S) A$,从而诱导同态: $ f': Spec(Inv(S) A) -> Spec(A) $ 同时,断言 $f'(q) = Inv(f)(q) sect S = emptyset$,否则 $q$ 中将存在单位,这当然是不可能的\ 另一方面,设 $p in Spec(A)$ 并且 $p sect S = emptyset$,我们断言 $Inv(S) p$ 是素理想,也即: $ Inv(S) A quo Inv(S) p = Inv(S) (A quo p) $ 是整环,但是注意到 $A quo p$ 已经是整环,它的局部化当然也是整环 ] #corollary[][ $ Spec(A_p) = {q A_p | q in Spec(A) and q sect A - p = emptyset}\ = {q A_p | q in Spec(A) and q subset p} $ ] #proposition[][ 设 $S subset A$ 是乘法子集,$M$ 是有限生成 $AModule(A)$,则: - $Inv(S) "Ann"_A (M) = "Ann"_(InvSA) (Inv(S) M)$ - $Inv(S) (N : P) = Inv(S) N : Inv(S) P$ ] #proof[ 设 $M = sum A x_i$,注意到: $ Inv(S) "Ann"(M) = Inv(S) sect.big "Ann"(x_i)\ = sect.big Inv(S) "Ann"(x_i)\ = sect.big "Ann"_(Inv(S) A) (x_i / 1)\ = "Ann"_(Inv(S) A) (Inv(S) M) $ 因此结论一成立 对于下一个结论,注意到: $ N :P = "Ann" ((N + P) quo N) $ 以及有限生成模的商模仍然是有限生成,因此结论自然成立 ] = 张量积 == 构造与性质 #definition[双线性|bilinear][ 设 $M, N$ 是 $AModule(A)$,称 $f: M times N -> P$ 双线性,如果: $ f(x, *), f(*, y) $ 都是线性的 ] 张量积的目的是希望将双线性映射转换成某种线性映射 #definition[][ 设 $M, N$ 是 $AModule(A)$,定义张量积为 $(T, g)$,其中 $T$ 为 $AModule(A)$而 $g$ 是双线性映射 $M times N -> T$,并且满足泛性质: $ forall (D, f):Mod_A times (M times N -> D) $ 有交换图: #align(center)[#commutative-diagram( node((0, 0), $M times N$, 1), node((0, 1), $D$, 2), node((1, 0), $T$, 3), arr(1, 2, $f$), arr(3, 2, $exists !f'$), arr(1, 3, $g$),)] 此时记 $T = M times.circle_A N$, ] #proposition[][ 上面定义的张量积存在且在同构的意义下唯一 ] #proof[ - 唯一性由它是范畴的始对象给出 - 存在性由如下构造给出 - 令 $C$ 是 $M times N$ 中元素生成的自由 $AModule(A)$ $ C = {sum a_i (x_i, y_i)} $ 令 $D$ 是由以下元素生成的子模: $ (x + x', y) - (x, y) - (x', y)\ (x, y + y') - (x, y) - (x, y')\ (a x, y) - a (x, y)\ (x, a y) - a (x, y) $ 令 $T = C quo D$,并取 $g$ 是自然的商模同态,并记: $ x tensorProduct y = g(x, y) $ 显然 $g$ 是双线性映射 - 接下来要验证它满足泛性质。事实上,任取 $f: M times N -> G$ 是双线性映射,依次做提升: $ #align(center)[#commutative-diagram( node((0, 0), $M times N$, 1), node((0, 1), $G$, 2), node((1, 0), $A^(M times N)$, 3), node((2, 0), $A^(M times N) quo D$, 4), arr(1, 2, $f$), arr(3, 2, $exists !f_1$), arr(4, 2, $exists !f_2$), arr(1, 3, $$), arr(3, 4, $$), )] $ 这里分别利用了自由模和商模的泛性质,为此,只需要验证 $f_1(D) = 0$ 即可,事实上: $ f_1 ((x + x', y) - (x, y) - (x', y)) = f (x + x', y) - f (x, y) - f (x', y) = 0 $ 其余几个生成元也可以类似验证,而唯一性只需要倒推即可 ] #definition[张量积的函子性][ 张量积 $- times.circle N : Mod_A -> Mod_A$ 是函子,由以下交换图表给出: #align(center)[#commutative-diagram( node((0, 0), $A$, 1), node((0, 1), $B$, 2), node((1, 0), $A times N$, 3), node((1, 1), $B times N$, 4), node((2, 0), $A tensorProduct N$, 3 + 2), node((2, 1), $B tensorProduct N$, 4 + 2), node((0, 2), $N$, 7), arr(1, 2, $f$), arr(3,1, $$), arr(4, 2, $$), arr(3, 7, $$), arr(4, 7, $$), arr(3, 4, $f'$), arr(0 + 3, 0 + 5, $$), arr(1 + 3, 1 + 5, $$), arr(5, 6, $f'' := f tensorProduct N$), )] 其中 $f'$ 利用了直积的泛性质,$f''$ 利用了张量积的泛性质,其结合性是容易验证的 ] #proposition[][ 张量积函子 $- times.circle N, M times.circle -$ 是右正合的,但未必左正合 ] #proof[ 右正合性之后会给出证明,至于左正合,只需验证它未必保持单射即可。\ 例如,取: $ funcDef(f, ZZ , ZZ, a, 2 a) $ 当然是单射,但是在函子 $F = - tensorProduct (ZZ_2)$的作用下,它变成: $ F f = [a tensorProduct b: ZZ tensorProduct ZZ_2 -> 2 a tensorProduct b = 0: ZZ tensorProduct ZZ_2] $ 成为零映射,当然不是单射 ] #corollary[][ 设有限个 $x_i in M, y_i in N$ 使得 $sum x_i tensorProduct y_i = 0 in M tensorProduct N$,则存在有限生成子模 $M_0 subset N$ 和有限生成子模 $N_0 subset N$ 使得 $sum x_i tensorProduct y_i = 0 in M_0 tensorProduct N_0$ ]<zero-tensor-product-fg> #proof[ 由张量积的构造: $ sum x_i tensorProduct y_i = 0 => sum (x_i, y_i) in D $ 而 $sum (x_i, y_i) in D$ 是 $D$ 中元素的有限和,设: - $M_0$ 由 $x_i$ 生成,且第一个坐标落在有限和之中 - $N_0$ 由 $y_i$ 生成,且第二个坐标落在有限和之中 从而当然有: $ sum x_i tensorProduct y_i = 0 in M_0 tensorProduct N_0 $ ] #remark[][ $x tensorProduct y = 0 in M tensorProduct N$ 成立并不意味着在子模中成立,例如取 $A = ZZ, M = ZZ, N = ZZ quo 2 ZZ$,将有: $ 2 tensorProduct x = 1 tensorProduct 2 x = 0 $ 然而在 $M$ 的子模 $M' = 2 ZZ$ 中,它不是零,因为可以取得双线性函数: $ funcDef(f, 2 ZZ times ZZ quo 2, ZZ quo 2 ZZ, (2 k, b), k b ) $ 使得 $f(2, 1) = 1 != 0$ ] 这样的定义完全可以推广到多重线性函数,给出多重的张量积,将其记作 $tensorProduct_i M_i$。然而还有一种自然的构造方式 $(((M_1 tensorProduct M_2) tensorProduct M_2) ...) tensorProduct M_r$,下一个命题给出了它们的一致性 #proposition[][ + $M tensorProduct N tilde.eq N tensorProduct M$ + $(M tensorProduct N) tensorProduct P tilde.eq M tensorProduct(N tensorProduct P) tilde.eq M tensorProduct N tensorProduct P$ + $(M plus.circle N) tensorProduct P tilde.eq (M tensorProduct P) plus.circle (N tensorProduct P) $ + $A tensorProduct M tilde.eq M$,映射如下给出: $ funcDef(phi, A tensorProduct M, M, a tensorProduct m, a m) $ + 设 $N$ 是 $A, B-$ 模,则: $ (M tensorProduct_A N) tensorProduct_B P tilde.eq M tensorProduct_A (N tensorProduct_B P) $ ] #proof[ + 显然 $M times N tilde.eq N times M$,互相验证泛性质即可 + 只证明 $M tensorProduct(N tensorProduct P) tilde.eq M tensorProduct N tensorProduct P$,其余同理\ 验证如下的泛性质成立: #align(center)[#commutative-diagram( node((0, 0), $M times N times P$, 1), node((0, 1), $D$, 2), node((1, 0), $M tensorProduct(N tensorProduct P)$, 3), arr(1, 2, $f$), arr(3, 2, $exists !f'$), arr(1, 3, $g$), )] 熟知 $M times N times P tilde.eq M times ( N times P)$,因此可以换成验证下面的图表: #align(center)[#commutative-diagram( node((0, 0), $M times ( N times P)$, 1), node((0, 1), $D$, 2), node((1, 0), $M tensorProduct(N tensorProduct P)$, 3), arr(1, 2, $f$), arr(3, 2, $exists !f'$), arr(1, 3, $g$), )] 这就是 $M tensorProduct(N tensorProduct P)$ 的泛性质,结论当然正确 + #align(center)[#commutative-diagram( node((0, 0), $(M plus.circle N) times P$, 1), node((1, 0), $(M times P) plus.circle (N times P)$, 2), node((0, 1), $D$, 3), node((2, 2), $M times P$, 4), node((2, 0), $N times P$, 5), node((3, 2), $M tensorProduct P$, 6), node((3, 0), $N tensorProduct P$, 7), node((4, 1), $(M tensorProduct P) plus.circle (N tensorProduct P)$, 8), arr(1, 2, $$, bij_str), arr(1, 3, $f$), arr(2, 3, $f_1$), arr(4, 2, $$), arr(5, 2, $$), arr(4, 6, $$), arr(6, 3, $exists! f'_1$, label-pos:right), arr(5, 7, $$), arr(7, 3, $exists! f'_2$, label-pos:right), arr(6, 8, $$), arr(7, 8, $$), arr(8, 3, $exists! f''$), arr(2, 8, $exists! g$) )] 其中 $f'_1, f'_2$ 分别利用了两个张量积的泛性质,而 $g, f''$ 利用了直和的泛性质 + 取: $ funcDef(f, A times M, M, (a, x) , a x) $ 容易验证它是双线性函数,因此可被唯一延拓到 $f': A tensorProduct M -> M$\ 注意到环中有单位元,自然是满射。验证单射: $ a x = 0 => a tensorProduct x =1 tensorProduct a x = 0 $ 证毕 + 定义: $ funcDef(f_p, M times N, M tensorProduct_A (N tensorProduct_B P), (m,n), m tensorProduct (n tensorProduct p)) $ 容易看出这是关于 $AModule(A)$ 的双线性函数,因此可以唯一延拓到 $f'_p: M tensorProduct_A N -> M tensorProduct_A (N tensorProduct_B P)$\ 同时,注意到 $Hom(M tensorProduct_A N, M tensorProduct_A (N tensorProduct_B P))$ 事实上是 $A, B$ 双模\ 因此,将 $f'$ 看作 $P -> (Hom(M tensorProduct_A N, M tensorProduct_A (N tensorProduct_B P)))$,容易验证它也是同态,进而: $ f' in Hom(P, Hom(M tensorProduct_A N, M tensorProduct_A (N tensorProduct_B P))) \ tilde.eq Hom((M tensorProduct_A N) tensorProduct_B P, M tensorProduct_A (N tensorProduct_B P)) $ (这里用到了之后的伴随性)\ 同时,将有: $ f'((x tensorProduct y) tensorProduct p) = f_p (x, y) = x tensorProduct (y tensorProduct p) $ 容易验证它是同构,证毕 ] == 标量的限制与扩张 restriction/extension of scalar #definition[限制][ 设 $f: A -> B$ 是环同态,$N$ 是 $AModule(B)$,则可以自然导出 $N$ 的 $AModule(A)$ 性,由: $ A times N -> B times N -> M $ 这个模被称为标量限制 ] #proposition[][ 若 $B$ 是有限 $A-$代数,$N$ 是有限生成 $AModule(B)$,则 $N$ 的标量限制是有限生成 $AModule(A)$ ] #proof[ 设 $B = sum_i A x_i, N = sum_i B y_i$,则: $ N = sum_i B y_i = sum_i sum_j A x_j y_i $ 这只是有限和,因此当然 $x_j y_i$ 成为一组生成元 ] #remark[][ 若 $B$ 不是有限的,限制当然未必有限生成。例如取 $B = A[x], N = A[x]$ ] #definition[扩张][ 设 $f: A -> B$ 是环同态,给出函子: $ funcDef(f, Mod_A, Mod_B, M, B tensorProduct_A M := M_B) $ 称为扩张,也即将 $M$ 转化为了 $AModule(B)$ ] #proposition[][ 设 $M$ 是有限生成 $AModule(A)$,则扩张 $M_B$ 也是有限生成 $AModule(B)$ ]<extension-fg> #proof[ 容易验证若 $x_i$ 生成 $M$,则 $1 tensorProduct x_i$ (作为 $AModule(B)$ )生成 $M_B$ ] #proposition[][ 设 $Inv(S) A$ 是分式环,有: $ Inv(S) A tensorProduct_A M tilde.eq Inv(S) M $ 映射由: $ f: (a/s, m) -> (a m)/s $ 给出 ] #proof[ + 首先给出直接的证明,先证明 $Inv(S) A tensorProduct_A M$ 总可以写成 $1/s tensorProduct m$ 的形式\ 事实上,由定义张量积均形如: $ sum_i a/s_i tensorProduct m_i $ 通分化为: $ sum_i 1/s tensorProduct (a_i t_i m_i) $ 这就是我们要的形式,进而表明 $f$ 是满射\ 再证明 $f$ 是单射,注意到: $ f(1/s tensorProduct m) = 0\ => exists t in S, t m = 0\ => t/s tensorProduct m = t/(s t) tensorProduct m = 1/(s t) tensorProduct t m = 0 $ 得证 ] #theorem[][ 函子 $Inv(S)$ 保持张量积,换言之: $ Inv(S) M tensorProduct_(Inv(S) A) Inv(S) N tilde.eq Inv(S) (M tensorProduct_A N) $ 映射由: $ m/s tensorProduct n/t -> (m tensorProduct n)/(s t) $ 给出 ]<tensor-product-localization> #proof[ $ Inv(S) M tensorProduct_(Inv(S) A) Inv(S) N \ tilde.eq (Inv(S) A tensorProduct_A M) tensorProduct_(Inv(S) A) (Inv(S) A tensorProduct_A N)\ tilde.eq (M tensorProduct_A Inv(S) A) tensorProduct_(Inv(S) A) (Inv(S) A tensorProduct_A N)\ tilde.eq M tensorProduct_A (Inv(S) A tensorProduct_(Inv(S) A) (Inv(S) A tensorProduct_A N))\ tilde.eq M tensorProduct_A (Inv(S) A tensorProduct_A N)\ tilde.eq Inv(S) A tensorProduct_A (M tensorProduct_A N)\ tilde.eq Inv(S) (M tensorProduct N) $ 我们证明了它们之间存在同构,容易验证该同构只能是上述形式 ] #lemma[][ 设 $M$ 是$A-$自由模,则 $M_B = B tensorProduct_A M$ 是 $B-$ 自由模 ]<free-extension> #proof[ 设 $M = directSum_i A$,则: $ M_B = B tensorProduct_A M = directSum_i B $ 当然是自由模 ] == $Hom, tensorProduct$ 的伴随性 #definition[][ 设 $T: Mod_A -> Mod_B, U = Hom_A (N, -)$ ,称 $(T, N)$ 是伴随对,如果: $ Hom_B (T M, P) tilde.eq Hom_A (M, U P), forall M, P $ ] #theorem[][ 设 $M, N, P$ 是 $AModule(A)$,则有自然同构: $ Hom(M tensorProduct N, P) &tilde.eq Hom(M, Hom(N, P))\ (f: M tensorProduct N -> P) &->[ m -> [n -> f(m tensorProduct n)]]\ ([(m, n) -> phi(m)(n)]arrow.t) &<- phi $ ] #corollary[][ $- tensorProduct N$ 是右正合函子 ] #proof[ 设: $ E := M' -> M -> M'' -> 0 $ 是正合列,往证: $ E tensorProduct N = M' tensorProduct N -> M tensorProduct N -> M'' tensorProduct N -> 0 $ 正合,由 @exact-test 只需证明: $ Hom(E tensorProduct N, P) $ 对于任意 $P$ 正合,而上式等价于 $ Hom(E, Hom(N, P)) $ 再由 @exact-test,这显然成立 ] #remark[][ - 右正合意味着张量积函子可以产生左导出函子,记 $"Tor"_i^A (M, N) := L_i (- tensorProduct_A N) (M) = H_i (... -> P_1 tensorProduct N -> P_0 tensorProduct N )$ - 然而,张量积本身往往不是左正合的,例如 $f: x -> 2 x$ 是单射,但: $ ZZ tensorProduct ZZ_2 ->^f' ZZ tensorProduct ZZ_2 $ 不是单射(事实上,是零映射) - 可以计算得到对于 $ZZ$ 模,$Tor = 0$ 就等价于模无挠,当然也等价于平坦 ] = 平坦模 == 平坦 #definition[平坦模|flat][ 以下性质等价 + 张量积函子 $- tensorProduct N$ 是正合的 + 任意正合列 $E$,张量积 $E tensorProduct N$ 也是正合的 + 设 $M' ->^f M$ 是单射,则 $M' tensorProduct N ->^f M tensorProduct N$ 也是单射 + 对于任意 $M, M'$ 有限生成,$M' ->^f M$ 单导出 $M' tensorProduct N ->^f M tensorProduct N$ 也是单射 此时,称 $N$ 是平坦模 ] #proof[ - $4 => 3$,假设 $M' ->^f M$ 是单射,往证 $M' tensorProduct N ->^f' M tensorProduct N$ 单 设 $u = sum x_i tensorProduct y_i in ker (f') => 0 = sum f(x'_i) tensorProduct y_i$,由 @zero-tensor-product-fg 知存在有限生成子模 $M_0$ 使得 $0 = sum f(x'_i) tensorProduct y_i in M_0 tensorProduct N$,由于 $f$ 在有限生成模上的提升是单射,$x'_i = 0$,因此 $u = 0$ - 其余情况显然 ] #proposition[平坦性是局部性质][ 以下命题等价: - $M$ 是平坦模 - 对于任意素理想 $p$,$M_p$ 是平坦模 - 对于任意极大理想 $m$,$M_m$ 是平坦模 ] #proof[ + $1 => 2$:注意到局部化函子 $(-)_p$ 也是正合函子,则复合也是正合函子,而它们的复合恰为: $ (- tensorProduct_A M)_p = (-)_p tensorProduct_(A_p) M_p $ 证毕 + $2 => 3$ 显然 + $3 => 1$:\ 设 $N ->^f P$ 是单射,往证 $N tensorProduct M ->^f P tensorProduct M$ 也是单射\ 之前已经证明单射是局部性质,只需要验证 $(N tensorProduct M)_m -> (P tensorProduct M)_m$ 是单射即可,但: $ (N tensorProduct M)_m -> (P tensorProduct M)_m\ <=> (N_m tensorProduct M_m) -> (P_m tensorProduct M_m)\ $ 由条件,结论显然成立 ] #proposition[][ 平坦模的扩张仍是平坦模 ] #proof[ 事实上,设 $E$ 是正合列,有: $ E tensorProduct_B M_B = E tensorProduct_B (B tensorProduct_A M) = (E tensorProduct_B B) tensorProduct_A M = E tensorProduct_A M $ 因此 $E tensorProduct_B M_B$ 作为 $Mod_A$ 中复形正合,而正合性与把它看作哪个环上的模当然无关,因此它也是 $Mod_B$ 中复形,证毕 ] #proposition[][ $directSum_i M_i$ 平坦当且仅当对于每个 $i$ 均有 $M_i$ 平坦 ] #proof[ 注意到张量积与直和交换,因此任取正合列 $E$ 将有: $ E tensorProduct (directSum_i M_i) = directSum_i (E tensorProduct M_i) $ 利用 @directSum-exact 可得结论成立 ] #proposition[][ 投射模都是平坦模 ] #proof[ 前面 @projective-module 给出投射模是自由模的直和项,而自由模是平坦的,它的直和项也是平坦的 ] #lemma[][ 任取投射模构成的正合列: $ ... -> P_2 -> P_1 -> P_0 -> N -> 0 $ 则: $ "Tor"_i^A (M, N) = H_i (... -> P_2 tensorProduct M -> P_1 tensorProduct M -> 0) $ ] #proof[ 这是由导出函子的构造所给出的 ] #theorem[][ 以下事实等价: + $M$ 平坦 + $forall N in Mod_A, "Tor"_1^A (M, N) = 0$ + 任意有限生成理想 $I subset A$,序列 $0 -> I tensorProduct M -> M$ 正合(也即 $I M tilde.eq I tensorProduct M$ + 任意有限生成理想 $I subset A$,$"Tor"_1^A (M, A quo I) = 0$ + 任何有限生成 $AModule(A)$,有 $"Tor"_1^A (M, N) = 0$ + 若 $a_i in A, x_i in M$,且: $ sum_(i=1)^r a_i x_i = 0 $ 则: $ exists s >= 1, b_(i_j) in A, y_j in M, 1 <= j <= s, s.t.\ x_i = sum_j b_(i_j) y_j\ sum_i a_i b_(i_j) = 0, forall j $ 写成矩阵语言就是若 $alpha^T X = 0$,则存在 $C, Y$ 使得: $ X = C Y\ alpha^T C = 0 $ ] #proof[ - $1 => 2\/3\/4\/5, 2 => 3$ 显然\ - $3 <=> 4$,注意到: $ 0 -> I -> A -> A quo I -> 0 $ 正合,无论如何都有长正合列: $ "Tor"_1^N (A, M) -> "Tor"_1^N (A quo I, M) -> I tensorProduct M -> M -> A quo I tensorProduct M tilde.eq M quo I M -> 0 $ 但是 $"Tor"_1^N (A, M) = 0$($A$ 自己当然是平坦模)\ 因此可得正合列: $ 0 -> "Tor"_1^N (A quo I, M) -> I tensorProduct M -> M $ 以此不难看出 $3 <=> 4$ - $4 => 1$,之前证明了 $M$ 平坦当且仅当任意有限生成模 $N, N'$ 均有: $ 0 -> N' -> N 正 合 => 0 -> N' tensorProduct M -> N tensorProduct M 正 合 $ 不妨设 $N' subset N$,继而: $ N = N' + A x_1 + A x_2 + ... + A x_n $ 我们只要递归的证明 $N' tensorProduct M -> (N' + A x_i) tensorProduct M$ 单射即可\ 不妨设 $N = N' + A x_i$,则有正合列: $ 0 -> N' -> N -> N quo N' = A quo I -> 0 where I = {a in A | a x_1 in N'} $ 将有长正合列: $ "Tor"_1^A (A quo I, M) -> N' tensorProduct M -> N tensorProduct M -> A quo I tensorProduct M -> 0 $ 由 4 结论成立 - $5 => 4$ 平凡 - $1 => 6$:\ 设 $sum_i a_i x_i = 0$,考虑: $ phi: A^r &-> A\ (b_i) &-> sum_i b_i a_i $ $M$ 是平坦模表明: $ 0 -> (ker phi) tensorProduct M -> M^r ->^f M where f(t_i) = sum_i a_i t_i $ 正合\ 注意到: $ X in ker f = im (g tensorProduct 1) $ 从而当然有: $ X = sum_j beta_j tensorProduct y_j $ 计算可得这就是结论 - $6 => 3$\ 假设 $sum_i a_i x_i = 0$,往证 $sum_i a_i tensorProduct x_i = 0$,继而对应位置是单射,结论成立\ 由条件,可设: $ x_i = sum_j b_(i j) y_j\ sum a_i b_(i_j) = 0 $ 从而: $ sum_i a_i tensorProduct x_i = sum_i a_i tensorProduct (sum_j b_(i_j) y_j) = sum_j (sum_i a_i b_(i_j)) tensorProduct y_j = 0 $ ] #remark[][ 注意到理想都是有限生成理想的正向极限,而可以证明: $ (lim_(->) M_i) tensorProduct N tilde.eq lim_(->) (M_i tensorProduct N) $ 因此上面的有限生成理想条件可以去掉 ] #definition[平坦同态][ 设 $phi: A -> B$ 是环同态,若 $B$ 成为平坦 $A-$模,则称 $phi$ 是平坦同态 ] #proposition[][ - *平坦同态具有传递性*,也即平坦 $AModule(B)$ 成为平坦 $AModule(A)$ - *平坦在换基下保持不变*,也即若 $phi: A -> B$ 是任意环同态,$M$ 是平坦 $AModule(A)$,则 $M tensorProduct_A B$ 是平坦 $AModule(B)$ - *局部化是平坦模*,也即设 $S$ 是乘性子集,则 $A -> Inv(S) A$ 是平坦同态。事实上,有: $ Inv(S) A tensorProduct E tilde.eq Inv(S) E $ ] #proof[ - 设 $E$ 是 $AModule(A)$正合列,则有: $ E tensorProduct N = (E tensorProduct_A B) tensorProduct_B N $ 然而注意到 $E tensorProduct_A B$ 仍正合,$N$ 是平坦 $AModule(B)$,因此上式当然正合 - 类似的,检查: $ E tensorProduct_B (M tensorProduct_A B) = (E tensorProduct_B B) tensorProduct_A M = E tensorProduct_A M $ 当然正合 - 利用 @tensor-product-localization 显然 ] #proposition[][ 设 $phi: A -> B$ 是平坦同态,则: $ "Tor"_i^A (M, N) tensorProduct B tilde.eq "Tor"_i^B (M tensorProduct_A B, N tensorProduct_A B) $ 特别的: $ ("Tor"_i^A (M, N) tensorProduct B)_p = "Tor"_i^A (M, N) tensorProduct B tensorProduct A_p = "Tor"_i^A (M_p, N_p) $ ] #proof[ 选取投射 $AModule(A)$正合列: $ ... -> P_1 -> P_0 -> M -> 0 $ 有正合列: $ ... -> P_1 tensorProduct B-> P_0 tensorProduct B-> M tensorProduct B -> 0 $ 断言 $P_i tensorProduct B$ 是自由 $AModule(B)$ 的直和项,因此还是投射模\ 事实上,设 $B^X = P_i directSum Q$,则 $A^X tensorProduct_A B = (P_i tensorProduct B) directSum (Q tensorProduct B)$,只需证明 $A^X tensorProduct_A B$ 是自由 $AModule(B)$,这就是 @free-extension 计算: $ "Tor"_i^B (M tensorProduct_A B, N tensorProduct_A B) = H_i ((P tensorProduct_A B) tensorProduct_B (N tensorProduct_A B))\ = H_i (P tensorProduct_A N tensorProduct_A B)\ = H_i (P tensorProduct_A N) tensorProduct_A B\ = "Tor"_i^A (M, N) tensorProduct_A B $ ] #theorem[][ 设 $A$ 是局部环,$k = A quo m$ 是留域,$M in Mod_A$。若 $m$ 幂零或 $M$ 是有限生成 $AModule(A)$,则: $ M "是自由模" <=> M "是平坦模" <=> M "是投射模" $ 一般的,局部环上的投射模都是自由模 ] #proof[ 只需证明若 $M$ 是平坦模,则它是自由模,也即需要找到一组基。\ 注意到: $ M quo m M = M tensorProduct k $ 是有限维 $k-$线性空间,当然可以找到一组自由基。由 Nakayama,可以设 $x_i in M$ 使得 $overline(M_i) in M tensorProduct k$ 是一组基\ 只需证明在 $M$ 上的线性无关性即可,用归纳法: - $n = 1$ 时,$a x_1 = 0$ 及 $M$ 平坦给出: $ x_1 = sum b_i y_i, a b_i = 0 $ 显然不可能所有 $b_i in m$,不妨假设 $b_1 in.not m$\ 然而由于 $A$ 是局部环,这给出 $b_1$ 是单位,从而 $b_1 a = 0 => a = 0$ - $n > 1$ 时方法是类似的,设 $sum_i a_i x_i = 0$,由平坦性知: $ x_i = sum_j b_(i_j) y_j, sum a_i b_(i_j) = 0 $ 由于 $x_1 in.not m M$,因此不妨假设 $b_(1_1) in.not m$,从而是单位。然而 $sum a_i b_(i_1) = 0 => a_1 = - sum_(i > 1) Inv(b_(1_1)) b_(i_1) a_i$,代回得: $ 0 = sum_i a_i x_i = sum_(i > 1) a_i x_i + c_i x_1 $ 由归纳假设立得 $a_i = 0$ ] #example[][ $A = ZZ_((p)), M = QQ$ 它不是自由模但是是平坦模 ] #proof[ - 断言它不是投射模,否则 $QQ$ 是自由模的直和项。设 $f: QQ -> F$ 是 $QQ$ 到自由模的嵌入映射,首先注意到: $ A f(1) tilde.eq A $ 然而: $ f(1) = f(p dot 1/p) = p f(1/p) => 1 dot f(1) - p f( 1/p)\ f(1) = p^2 f(1/p^2)\ ... $ 这表明若设 $x_0, x_1, ... in A$ 分别是 $f(1), f(1/p), ...$ 在 $F$ 中的某分量,一定有: $ x_0 = p^n x_n $ 然而 $A$ 中没有元素能被无穷多个 $p$ 整除,矛盾! - 证明它是平坦模,首先 $QQ$ 作为 $ZZ$ 的局部化由局部化的正合性知在 $QQ$ 上平坦,再做 $(p)$ 的局部化可得另一个平坦性\ ] == 忠实平坦 #definition[忠实平坦|faithful flat][ 以下等价的事实成立: + 复形 $E$ 正合当且仅当 $E tensorProduct M$ 正合 + $M$ 是平坦模且任意非零 $AModule(A) space N$,有 $M tensorProduct N != 0$ + $M$ 是平坦模且任取 $A$ 的极大理想 $m$ 均有 $m M != M$ 成立时,称 $M$ 是忠实平坦模 ] #proof[ - $1 => 2$ 若 $N tensorProduct M = 0$,则 $0 -> N tensorProduct M -> 0$ 正合,由定义知 $0 -> N -> 0$ 正合,继而 $N = 0$ - $2 => 3$\ 任取极大理想 $m$,将有: $ M tensorProduct A quo m = M quo m M != 0 => m M != M $ - $3 => 2$\ 事实上,不妨设 $N$ 有限生成。如果不是,就在其中选出有限个元素生成新的 $N'$,证明对于这个 $N$ 有 $M tensorProduct N$ 足以(既然 $M$ 平坦,保持嵌入仍为嵌入)\ 此时不可能对于所有极大理想均有 $m N = N$,否则利用 Nakayama 引理得 $N_m = 0$ 对于所有极大理想都成立,进而 $N = 0$,矛盾!\ 此时,注意到 $(M quo m M) tensorProduct_(A quo m) (N quo m N)$ 是域上两个非零线性空间的张量积,当然非零,因此: $ 0 != (M quo m M) tensorProduct_(A quo m) (N quo m N) = (M tensorProduct_A A quo m) tensorProduct_(A quo m) (N tensorProduct_A A quo m) \ =M tensorProduct_A (A quo m tensorProduct_(A quo m) (N tensorProduct_A A quo m)) = (M tensorProduct_A N) tensorProduct_A A quo m $ 导出我们的结论 - $2 => 1$\ 取序列: $ N' ->^f N ->^g N'' := S $ 假设 $S tensorProduct M$ 正合,往证 $S$ 也正合 - 首先,注意到: $ im(g f) tensorProduct M tilde.eq im(g_m f_m) = 0 => im (g f) = 0 $ 因此是复形 - 其次,设 $H$ 是该处同调群,有: $ H(S) tensorProduct M tilde.eq H(S tensorProduct M) = 0 => H(S) = 0 $ 表明正合性 ] #corollary[][ 设 $A, B$ 是局部环,$psi: A -> B$ 是局部同态,$M$ 是有限 $AModule(B)$,则 $M$ 是 $A$ 上的忠实平坦模当且仅当它是平坦模 ] #proof[ 设 $m_A, m_B$ 是极大理想,注意到: $ m_A M = psi(m_A) M subset m_B M $ 注意到若 $m_A M = M$,利用 Nakayama 可得 $M = 0$,这是荒谬的,继而由上面的结论知只要 $M$ 是平坦的,它就是忠实平坦的 ] #proposition[][ 自由模是忠实平坦的 ] #lemma[][ 设 $M$ 在 $A$ 上忠实平坦,则: - $M quo I M$ 在 $A quo I$ 上忠实平坦 - $Inv(S) M$ 在 $Inv(S) A$ 上忠实平坦 ] #proof[ 注意到: $ (M quo I M) tensorProduct_(A quo I) E = (M tensorProduct_A A quo I) tensorProduct_(A quo I) E = M tensorProduct_A E\ Inv(S) M tensorProduct_(Inv(S) A) Inv(S) E = M tensorProduct_A E $ 因此结论显然 ] #proposition[][ 设 $psi:A -> B$ 是环同态使得 $B$ 忠实平坦,则: + $forall N in Mod_A, N -> N tensorProduct B$ 是单射。特别的,$psi$ 是单射 + 任取 $A$ 的理想 $I$,均有 $I B sect A = I$ + $psi^*: Spec B -> Spec A$ 是满射 ] #proof[ - 取 $x !=0 in N$,则 $A x != 0$,以下序列正合: $ 0 -> A x -> N\ 0 -> A x tensorProduct_A B -> N tensorProduct_A B $ 注意到 $A x tensorProduct_A B = (x tensorProduct_A 1)B $,由忠实平坦知 $x tensorProduct 1 != 0$,再结合正合性知它在 $N tensorProduct B$ 中也不为零 - 断言 $B tensorProduct_A A quo I = B quo I B$ 在 $A quo I$ 上忠实平坦,从而: $ A quo I -> B quo I B $ 是单射,继而: $ ker(A quo I -> B quo I B) = (A sect I B) quo I = 0 => A sect I B = I $ - 任取 $p in Spec(A)$,做局部化,断言 $B_p = B tensorProduct A_p$ 在 $A_p$ 上忠实平坦\ 由之前的定理,这表明在唯一的极大理想 $p A_p$ 上,有: $ p B_p != B_p $ 如此,找到极大理想 $m$ 使得: $ p B_p subset m subset.neq B_p $ 交换图: #align(center)[#commutative-diagram( node((0, 0), $A$, 1), node((0, 1), $B$, 2), node((1, 0), $A_p$, 3), node((1, 1), $B_p = B tensorProduct A_p$, 4), arr(1, 2, $phi$), arr(1, 3, $$), arr(2, 4, $$), arr(3, 4, $$),)] 中依次取逆像得: #align(center)[#commutative-diagram( node((0, 0), $p_A$, 1), node((0, 1), $p_B$, 2), node((1, 0), $p_A A_p$, 3), node((1, 1), $m$, 4), arr(1, 2, $phi$), arr(1, 3, $$), arr(2, 4, $$), arr(3, 4, $$),)] 然而注意到 $p A_p subset p_A A_p => p_A = p$,证毕 ] #theorem[结构性定理][ 设 $psi:A -> B$ 是环同态,以下条件等价: - $psi$ 是忠实平坦 - $psi$ 是平坦的,且 $psi^*: Spec B -> Spec A$ 是满射 - $psi$ 是平坦的,且对于任取 $m in max(A)$,存在 $m' in max(B)$ 使得 $psi(m) subset m'$ ] #proof[ - $1 => 2$ 已经证明 - $2 => 3$\ 注意到对于任取 $m in max(A)$,存在 $m' in Spec(B)$ 使得 $m = Inv(psi)(m')$\ 将 $m'$ 扩充成极大理想 $m''$,将有 $m subset Inv(psi)(m'')$,由极大性可得 $m = Inv(psi)(m'') => psi(m) subset m''$ - $3 => 1$\ 只要证任取 $m in max(A), m B != B$\ 事实上,由条件存在 $m' in max(B)$ 使得 $m B subset m' != B$,因此当然有 $m B != B$ ] #proposition[faithfully flat descent][ 设 $B$ 是 $A$ 上的忠实平坦代数,$M$ 是 $AModule(A)$,则: - $M$ 是平坦/忠实平坦 $<=> M tensorProduct_A B$ 在 $B$ 上平坦/忠实平坦 - 若 $A$ 是局部环且 $M$ 在 $A$ 上有限生成,则 $M$ 是自由 $AModule(A)$当且仅当 $M tensorProduct_A B$ 是自由 $AModule(B)$ ] #proof[ - $=>$ 平凡,往证 $arrow.double.l$,注意到: $ (S tensorProduct_A M) tensorProduct_A B = (S tensorProduct_A B) tensorProduct_B (M tensorProduct_A B) $ 因此 $S tensorProduct_A M$ 正合当且仅当 $(S tensorProduct_A M) tensorProduct_A B$ 正合当且仅当 $(S tensorProduct_A B) tensorProduct_B (M tensorProduct_A B)$ 正合 - 若 $M tensorProduct B$ 忠实平坦,这就等价于 $S tensorProduct_A B$ 正合,等价于 $S$ 正合,证毕 - 若 $M tensorProduct B$ 平坦且 $S$ 正合,则 $S tensorProduct_A B$ 正合进而 $(S tensorProduct_A B) tensorProduct_B (M tensorProduct_A B)$ 正合,证毕 - 注意到 $A$ 是局部环且 $M$ 有限生成,此时自由模等价于平坦模,因此右推左成立。同时 @free-extension 给出了左推右 ] #theorem[Going-down for flat morphism][ 是 $psi: A -> B$ 是平坦同态,则下降性质对于 $psi$ 成立,也即: $ forall p, p' in Spec A, p subset p'\ forall q' in Spec B "lying over" p'\ exists q in Spec B "lying over" p, s.t. q subset q' $ ] #proof[ 首先做局部化,将 $psi$ 延拓到 $A_p' -> B_q'$,这个延拓产生于以下的交换图表: #align(center)[#commutative-diagram( node((0, 0), $A$, 1), node((0, 1), $B$, 2), node((1, 0), $A_p'$, 3), node((1, 1), $B_q'$, 4), arr(1, 2, $phi$), arr(1, 3, $$), arr(2, 4, $$), arr(3, 4, $phi'$), )] 这是因为条件给出: $ Inv(phi)(q') = p'\ A - p' = Inv(phi)(B) - Inv(phi)(q') = Inv(phi)(B - q') $ 因此: $ ((B -> B_q') compose phi)(A - p') = (B -> B_q')(phi(A - p')) subset (B -> B_q')(B - q') subset U(B_q') $ 故泛性质给出 $phi'$\ - 首先,证明这个映射仍然是平坦同态。事实上,$B -> B_(q')$ 作为局部化是平坦同态,由传递性 $A -> B_q'$ 平坦,它在局部化函子下的提升 $phi'$ 当然也平坦(注意到 $Inv((A-p')) B_(q') = B_(q')$,故 $phi'$ 就是 $Inv((A-p')) (A -> B_q')$ - 此时,双方都是局部环,进而 $phi'$ 忠实平坦,由之前的结构性定理知 $phi^*$ 是满射,进而存在 $q^* in Spec (B_q')$ lying over $p A_p'$,也即 $Inv(phi')(q^*) = p A_p$,取 $q = q^* sect B subset q'$ - 只需证明 $Inv(phi)(q) = p$,事实上交换图表给出: $ Inv(phi)(q) = Inv(phi) compose Inv((B -> B_q')) (q^*) = Inv((A -> A_p')) compose Inv(phi') (q^*) = p $ 证毕 ] = 链条件|Chain conditions, Artin 与 Noether <chain-cond> 本章的内容是关于代数结构的经典有限性条件 == 链条件 #theorem[acc / maximal condition for a partially ordered set][ 设 $Sigma$ 是偏序集,以下条件等价: - 每个上升序列 $x_1 <= x_2 <= ... <= x_n <= ...$ 都是稳定的,也即在有限步后不再改变 - 每个非空子集有极大元 ] #proof[ - $2 => 1$ 取 ${x_n}$ 的极大元即可 - $1 => 2$ 任取非空子集 $A$,若其中没有极大元,显然可以构造其中一个不断上升的序列,与条件矛盾 ] 从形式上可以看出,上面的定理是 Zoun 引理的一个替代,它反映了某种有限性。对称的,还有 dcc 也即降链条件。 #definition[Noetherian Space|诺特空间][ 称拓扑空间 $X$ 是诺特 (Noetherian) 的,如果它的开集族满足升链条件(等价的,闭子集族满足降链条件) ] #theorem[诺特归纳法|Noether induction method][ 设 $E$ 是满足 dcc 的偏序集(例如诺特空间的闭子集族),$P$ 是关于 $P$ 中元素的性质,如果: $ forall a in E ((forall b < a, P(b)) -> P(a)) $ 则 $forall x in E, P(x)$ ] #proposition[][ - 诺特空间的子空间仍然是诺特空间 - 有限个诺特空间的并集仍然是诺特空间 - 诺特空间是拟紧的 - 若空间中所有开子集都拟紧,则空间是诺特的 - 诺特空间只有有限多的不可约分支 ] 我们的目标是将这些几何条件应用于环或者模之上。 #definition[Noether Ring, Artin Ring][ - 称 $A$ 是 Noether 环,如果理想族满足升链条件 - 称 $A$ 是 Artin 环,如果理想族满足降链条件 ] #definition[Noether Module, Artin Module][ - 称 $M$ 是 Noether 模,如果子模族满足升链条件 - 称 $M$ 是 Artin 模,如果子模族满足降链条件 ] #example[][ - 有限阿贝尔群是 $ZZ$ 上的 Noether/Artin 模 - 唯一分解分解整环是 Noether 的 - $ZZ$ 是 Noether 但不是 Artin 的 - 设 $p$ 是素数,$G = ZZ[1/p] quo ZZ$,该 $G$ 是 Artin 模,但不是 Noether 模(作为 $ZZ$ 模) 事实上,不难发现其中子模均形如 $1/p^n ZZ quo ZZ$,既然 $n$ 可以无限上升(继而子模可以无限上升)但不能无限下降(继而子模不能无限下降),故它是 Artin 模但不是 Noether 模 ] #proposition[][ 设: $ 0 -> M' ->^alpha M ->^beta M'' -> 0 $ 是 $Mod_A$ 中正合列,则: - $M "Noether" <=> M', M'' "Noether"$ - $M "Artin" <=> M', M'' "Artin"$ ]<exact-noether-artin> #proof[ 只证明 1\ - $=>$ \ 任取 $M'$ 的子模升链,注意到 $alpha$ 是单射,该升链对应到 $im alpha$ 的子模升链,当然最终稳定\ 任取 $M''$ 的子模升链,由于 $beta$ 是满射,该升链对应到 $M quo ker beta$ 的子模升链,当然最终稳定 - $arrow.double.l$ 任取 $M$ 的子模升链 $M^i$ - 首先利用 $beta$ 给出的一一对应,$M^i + ker beta$ 对应到 $M''$ 的子模升链是最终稳定的 - 再利用 $alpha$ 给出的一一对应,$M^i sect im alpha$ 对应到 $M'$ 的子模升链是最终稳定的 - 由于 $M^i sect im alpha = M^i sect ker beta subset M^i subset M^i + ker beta$,两边夹逼得到 $M_i$ 最终也是稳定的 ] #corollary[][ 模的有限直和是 Noether/Artin 的当且仅当每项都是 Noether/Artin 的 ] #proof[ 只证明两项情况,此时有正合列: $ 0 -> M_1 -> M_1 directSum M_2 -> M_2 -> 0 $ 由上面的结论知结论成立 ] #theorem[][ 设 $M$ 是 $AModule(A)$,则 $M$ 诺特当且仅当所有子模都是有限生成的 ]<noether-finite> #proof[ - $arrow.double.l$ \ 取子模升链 $M_1 <= M_2 <= ... <= M_n <= ...$\ 由假设条件,将有: $ N = union M_i = sum_(i=1)^n A x_i $ 由于这里只有有限多个元素,找到充分大的 $k$ 使得 $x_i in M_k, forall i$,进而 $N = M_k$,表明升链稳定,证毕 - $=>$\ 假设 $N subset M$ 不是有限生成的,令: $ Sigma = {N "的有限生成子模"} $ 由于 $Sigma$ 非空且 $M$ 诺特,$Sigma$ 将有极大元 $N_0$ 是 $N$ 的有限生成子模\ 由假设 $N_0 != N$,将可以找到 $x in N - N_0$,此时 $A x + N_0$ 是比 $N_0$ 更大的有限生成子模,矛盾! ] #corollary[][ - 诺特模是有限生成的 - 环是诺特的当且仅当所有的理想都有限生成 ] #lemma[][ Noether/Artin 环上的有限自由模是 Noether/Artin 的 ] #proposition[][ Noether/Artin 环上的有限生成模是 Noether/Artin 的 ] #proof[ 设 $A^N$ 是自由模,$N$ 是模的生成元集(有限),则有正合列: $ 0 -> ker f -> A^N ->^f M -> 0 $ 由于 $A^N$ 是 Noether/Artin 的,由 @exact-noether-artin 知 $M$ 也是 Noether/Artin 的 ] == 有限长度模 #definition[子模链/合成序列][ 设 $M$ 是 $AModule(A)$,一个子模链是指: $ 0 = M_0 < M_1 < ... < M_n = M $ 并记其长度为 $n$ 若一个子模链不能再加入任何子模,则称其是合成序列|composition。这等价于 $M_n quo M_(n-1)$ 是单模(不含非平凡子模的模) ] #theorem[Jordan-Holder][ 假设 $M$ 存在长度为 $n$ 的合成列,则每个合成列的长度都是 $n$,且每个子模链都可以被延长到一个合成列。更进一步,任意合成列中记重数集 ${M_n quo M_(n-1)}$ 是不变的 ] #proof[ 定义 $l(M)$ 是 $M$ 的合成列中的最小长度 #lemmaLinear[][ 设 $N$ 是 $M$ 的真子模,则 $l(N) < l(M)$ ] #proof[ 设 $M_i$ 是 $M$ 的合成列,断言: $ M_i sect N $ 是 $N$ 的合成列。事实上,有: $ (M_(i-1) sect N) quo (M_(i) sect N) subset M_(i-1) quo M_(i) $ 因此这些商模要么是 $0$,要么是单模。去掉所有的 $0$ 之后便成为长度为 $l' <= l(M)$ 的合成列\ 同时,假设 $l= l(M)$,表明上面的 $N_(i-1) quo N_i tilde.eq M_(i-1) quo M_i$,可以递归证明 $M_i = N_i$,这是荒谬的 ] #theorem[][ 模是有限长度模当且仅当它是 Artin 并且 Noether 的 ] #lemmaLinear[][ $M$ 中任何一个子模链的长度不超过 $l(M)$ ] #proof[ 在任意子模链: $ M = M_0 supset.neq M_1 supset.neq ... supset.neq M_n = 0 $ 中,将有: $ l(M) > l(M_1) > ... > l(M_n) = 0 $ 进而 $l(M) >= n$ ] 由定义及上面的引理,当然有任何一个合成列的长度都是 $l(M)$ 对于第二个命题,任意子模链当然可以进行延拓。由上面的引理,延拓必将在有限步终止,终止时当然就得到一个合成列。 ] #proposition[][ 设: $ 0 -> M' ->^alpha M ->^beta M'' -> 0 $ 是 $Mod_A$ 中正合列,则 $l(M) = l(M') + l(M'')$ ] #proof[ $M'$ 的合成列合并 $Inv(beta)(M'' "的合成列")$ 可得 $M$ 的合成列 ] #theorem[][ 设 $V$ 是 $k$ 上的线性空间,则以下事实等价: - $dim V < infinity$ - $l(V) < infinity$ - $V$ 是 Noether 的 - $V$ 是 Artin 的 成立时,将有 $dim V = l(V)$ ] #proof[ 利用线性代数的基本结论,这是容易的 ] #lemma[][ 模是 Artin/Noether 的当且仅当子模链中每一项都是 Artin/Noether 的 ]<compositor-noether-artin> #corollary[][ 设 $A$ 是环且存在有限多个极大理想(允许重复) $m_i$ 使得 $m_1 m_2 ... m_n = (0)$,则 $A$ 是 Artin 环当且仅当 $A$ 是 Noether 环 ]<artin-noether> #proof[ 考虑合成列: $ A > m_1 > m_1 m_2 > ... > m_1 m_2 ... m_n = (0) $ 注意到每个合成因子: $ m_1 m_2 .. m_i quo m_1 m_2 ... m_(i+1) $ 都是线性空间,从而每个因子是 Artin 当且仅当是 Noether 的,利用 @compositor-noether-artin 即可 ] == Noether 环的构造 #lemma[][ 设 $A$ 是 Noether 环,则: - $A$ 的满射像是 Noether 环 - $A$ 的局部化 $Inv(S) A$ 是 Noether 环 - $A$ 的扩张(也就是有限 $A-$代数或者有限生成 $A-$模)是 Noether 环 ] #proof[ - $A$ 的满射像中的理想与 $A$ 中包含 $ker f$ 的理想一一对应,当然满足升链条件 - $Inv(S) A$ 与 $A$ 中与 $S$ 不交的理想一一对应,当然满足升链条件 - 前面证明了有限生成 $AModule(A)$ 是 Noether 模,因此它的理想作为子模有限生成,当然有限生成 ] #theorem[Hilbert's base theorem][ 设 $A$ 是 Noether 环,则 $A[x]$ 也是 Noether 环。特别的,有限生成的 $A-$代数是 Noether 环 ]<Hilbert-base> #proof[ 由 @noether-finite,只要证明所有的理想都有限生成即可。任取 $I$ 是 $A[x]$ 的理想,定义: - $I_0 = {I "中多项式的首项系数"}$,它是 $A$ 的理想,进而有限生成,可设 $I_0 = (a_1, a_2, ..., a_n)$ - 设 $f_i$ 分别是首项系数为 $a_i$ 的 $I$ 中多项式,由于可以同时乘一个因子,不妨设它们都是 $r$ 次,再设 $I' = (f_1, f_2, ..., f_n)$ - 断言:$I = union_(h in I, deg(h) < r) I' + h$\ 事实上,任取 $f$ 使得 $deg f >= r$,它的首项系数 $a in I_0$,继而存在 $u_i$ 使得: $ deg(f - sum u_i a_i) < deg(f) $ 反复进行即可将 $f$ 的次数降至 $r$ 以下,证毕 - 接下来,归纳证明:设 $I$ 由次数小于 $n$ 的元素生成,则 $I$ 是有限生成的 ] #theorem[weak form of Hilbert's Nullstellensatz][ 设 $k$ 是域且是有限生成 $A-$代数,$m$ 是极大理想,则 $A quo m$ 是 $k$ 的有限扩张\ 等价的,如果 $E$ 是有限生成 $k-$代数,且 $E$ 是域,则它是 $k$ 的有限代数扩张 ] == 环的维数 #definition[Krull chain][ 设 $A$ 是环,一个 Krull 链是指: $ p_0 < p_1 < ... < p_n $ 其中每个 $p_i$ 是素理想,$n$ 称为长度 对于一个环,这样的链的长度的上确界称为环的维数(可能为无穷) ] #proposition[][ - $dim(A) >= 0$ - $dim(k) = 0, k$ 是域 - $dim(ZZ) = 1$ ] == Artin 环的结构 #lemma[][ Artin 环的满射像/局部化仍然是 Artin 环 ] #proof[ 同前 ] #proposition[][ 设 $A$ 是 Artin 环,则: - 每个素理想都极大 - $Spec A$ 是有限集 - $A$ 的幂零根是幂零的(也即存在 $n$ 使得 $Re^n = 0$) ] #proof[ - 考虑 $A quo p$,它是整环,同时也是 Artin 环\ 考察 $x in A quo p$,降链: $ (x) >= (x^2) ... >= (x^n) >= ... $ 最终稳定,进而 $(x^n) = (x^(n+1)) => x^n = x^(n+1) y => x y = 1$,表明 $x$ 是可逆元。这就表明 $A quo p$ 是域 - 任取一列 $p_i in Spec(A)$,考虑: $ m_n = sect_i^n p_i $ 它是理想的降链,最终稳定,设它稳定到 $m = sect_i^n p_i$,将有: $ m subset p_i, forall i >= n $ 再由 @prime-avoidance 知 $sect_i^n p_i subset p_j => exists i <= n, p_i subset p_j => p_i subset p_j, forall j > i$\ 表明 $Spec(A)$ 中不存在无穷序列,继而是有限集 - 由降链条件,存在 $k$ 使得: $ Re^k = Re^(k+1) = ... := I $ 假设 $I != 0$,设: $ Sigma = { J subset A | I J != 0} $ 则 $Sigma$ 有极小元 $J$,这样的理想当然由唯一的元素 $x$ 生成。\ 注意到: $ (x I) * I = x I^2 = x I != 0 $ 因此 $x I in Sigma$,由极小性知 $x I = (x)$,因此存在 $y in I$ 使得 $x y = x = x y^2 = ... = x y^n = 0$,矛盾!进而结论成立 ] #theorem[][ $A$ 是 Artin 环当且仅当 $dim A = 0$ 且 $A$ 是 Noether 环 ] #proof[ 设环是 Artin 环,上面命题给出 $max(A) = Spec(A)$ 有限,不妨设 $max(A) = {m_1, m_2, ..., m_n}$\ 注意到取充分大的 $k$ 将有: $ product_(i) m_i^k subset (sect m_i)^k = Re^k = 0 $ 由 @artin-noether 该环是 Noether 环,而 $dim A = 0$ 由每个素理想都极大立刻给出 反之,$dim A = 0$ 蕴含每个素理想都极大,设: $ Sigma = {product S | S subset Spec(A) "且有限"} $ #TODO ] #proposition[][ 设 $A$ 是 Noether local 环,则下面两者有且只有一个成立: - $m^n != m^(n+1), forall n$ 进而 $A$ 不是 Artin 环 - $exists n, m^n = 0$ 进而 $A$ 是 Artin 环,此时它也只有一个素理想 ]<noether-local-classification> #proof[ 假设 $m^n = m^(n+1)$,由 Nakayama 得 $m^n = 0$,进而由 @artin-noether 知它是 Artin 环 ] #example[][ 任取 $A$ 是 Noether 环,则 $A_p$ 是 Noether local 环,进而 $(A_p) quo (p A_p)^n$ 是 Artin 局部环,这样我们便可以构造出很多的 Artin 环 ] #theorem[Artin 环的结构定理][ 设 $A$ 是 Artin 环,则 $A$ 是有限个 Artin 局部环的直积 ] #proof[ 选出所有极大理想 $m_i$,注意到这些 $m_i^k$ 当然互素,且 $product_(i) m_i^k = 0$,由中国剩余定理: $ A = product_(i) A quo m_i^k $ 而 $A quo m_i^k$ 当然是 Artin 的局部环,证毕 ] #example[][ 我们构造一个仅有一个素理想的环,但不是 Noether 的,进而也不是 Artin 的。\ 令 $A = k[x_1, x_2, ..., x_n,...] quo (x_i^2)$,任取其中素理想 $p$,将有 $x_i^2 = 0 in p => x_i in p$,因此: $ (x_1, x_2, ..., x_n, ...) subset p $ 然而上式左侧是极大理想,进而就是 $p$,而这不是有限生成的,因此 $A$ 不是 Noether 环 ] #example[][ 设 $A$ 是局部环,$m$ 是素理想,则模 $m quo m^2$ 也是 $A quo m$ 上的向量空间。事实上我们之后会证明: $ dim m quo m^2 >= dim A quo m $ 若 $m$ 有限生成,则它的生成元当然也是向量空间的生成元 ] #proposition[][ 设 $A$ 是 Artin local 环,以下事实等价: - $A$ 是主理想环且所有理想都是主理想的幂次 - 极大理想 $m$ 是主理想 - $dim_k m quo m^2 <= 1$ ]<artin-local-prop> #proof[ 前两项显然,只证明 $3 => 1$ - 假设 $dim_k m quo m^2 = 0$,则 $m = m^2$,由 Nakayama 得 $m = 0$,进而 $A$ 是域,结论当然正确 - 反之,设 $dim_k m quo m^2 = (1)$,当然有 $m = (x)$,继而我们证明所有理想都是主理想。\ 任取 $I subset m$,注意到 $m$ 幂零,取 $r$ 使得 $I subset m^r, I subset.not m^(r+1)$\ 取 $y in.not (x^(r+1))$,但 $y = a x^r$,进而 $a in.not (x) = m$,然而局部环中不在极大理想意味着 $a$ 是单位,表明 $x^r in I => m^r subset I$\ 根据取法,一定有 $I = (x^r)$,证毕 ] #example[][ 设 $A = k[x^2, x^3] quo (x^4)$,注意到生成元都是幂零的,进而有唯一素理想 $(x^2, x^3)$,且是 Noether 的,进而是 Artin 的局部环。然而极大理想不是主理想,因此 $dim_k m quo m^2 >= 2$\ 事实上 $m^2 = 0$,因此 $dim_k m = 2$ ] == Noether 环中模的 filtration #theorem[][ 设 $A$ 是 Noether 环,$M$ 是有限生成模,则存在升链: $ (0) = M_0 < M_1 < ... < M_n = M $ 使得 $M_i quo M_(i-1) tilde.eq A quo p_i, p_i in Spec(A)$ ]<noether-filtration> #proof[ 只需证明存在 $M_1$ 使得 $M_1 tilde.eq A quo p$,接下来不断取商即可\ #definition[associated prime][ 设 $A$ 是 Noether 环,若以下等价条件成立: - $exists x in M, Ann(x) = p$ - $M$ 包含同构于 $A quo p$ 的子模 则称 $p$ 是 $M$ 的 associated prime,记这些素理想的集合为 $Ass(M)$ ] 化归成证明这样的素理想存在 #proposition[][ 设 $Sigma = {Ann(x) | x != 0 in M}$,由 Noether 环知它有极大元,则极大元是素理想。特别的: $ union_(p "是 associated prime") p = union_(x != 0 in M) Ann(x) $ ] #proof[ 设 $p = Ann(x)$ 是极大元,取 $a b in p, b in.not p$,则: $ b x != 0\ a b x = 0 => a in Ann(b x)\ Ann(b x) supset Ann(x) => Ann(b x) = Ann(x) => a in Ann(x) $ 证毕 ] ] #lemma[][ 设 $0 -> M' ->^f M ->^g M''$ 正合,则 $Ass(M) subset Ass(M') union Ass(M'')$ ] #proof[ 取 $p in Ass(M), M supset N tilde.eq A quo p$ - 若 $N sect M' = 0$,则有: $ N tilde.eq (N directSum ker g)quo ker g tilde.eq g(N) $ 因此 $g(M)$ 含有一个同构于 $N$ 的子模,故 $p in Ass(M'')$ - 若 $N sect M' != 0$ ,此时取 $x in N sect M'$,注意到: $ N tilde.eq A quo p => Ann(x) = p => p in Ass(M') $ ] #lemma[][ 设 $M$ 是有限生成模,则 $Ass(M)$ 有限 ] #proof[ 取 @noether-filtration 中升链,有正合列: $ 0 = M_0 -> M_1 -> M_1 quo M_0 -> 0 -> M_1 -> M_2 -> M_2 quo M_1 ...\ -> 0 -> M_(n-1) -> M_n -> M_n quo M_(n-1) -> 0 $ 将有: $ Ass(M) &subset Ass(M_n quo M_(n-1)) union Ass(M_(n-1))\ &subset Ass(M_n quo M_(n-1)) union Ass(M_(n-1) quo M_(n-2)) union Ass(M_(n-2))\ &...\ &subset union_(i = 0)^(n-1) Ass(M_(i+1) quo M_i) $ 右边都是些整环,断言其 $Ass$ 只能是 $p_i$\ 事实上,若存在 $a + p in A quo p$ 使得 $Ann(a + p) = q$,首先当然有 $p subset q$,其次任取 $x in q$ 将有: $ x(a+p) = 0 => x a in x p subset p => x in p or a in p $ 显然可设 $a in.not p$,因此 $q subset p$,故 $Ass(A quo p) = {p}$ 因此它们的并当然有限,证毕 ] #lemma[][ $Ass(Inv(S)A) = Ass(A) sect {p | p sect S = 0}$ ]<localization-ass> #theorem[][ $ Ass(M) subset "Supp"(M) := {p | M_p != 0} $ 且 $"Supp"(M)$ 的极小元落在 $Ass(M)$ ] #proof[ 先任取 $p in Ass(M)$,有正合列: $ 0 -> A quo p -> M $ 利用局部化的正合性: $ 0 -> (A quo p)_p -> M_p\ 0 -> (A_p quo p A_p) -> M_p\ $ 从而显然有 $M_p != 0$ 取 $p$ 是极小元,利用 @localization-ass,不妨通过局部化假设 $p$ 是唯一极大理想。然而由极小性,将有 $"Supp" M = {p}$,结合 $Ass(M)$ 非空得 $p in Ass(M)$ ] 期中考试内容到此 = 整独立|Integral dependence == 整元 #definition[整元][ 设 $A subset B$ 是子环,称 $b in B$ 在 $A$ 上是整的,如果存在首一多项式 $f(x) in A[x]$ 使得 $f(b) = 0$ ] 整元的概念当然是代数扩张的自然推广 #lemma[][ 以下条件等价: + $x in B$ 在 $A$ 上整 + $A[x]$ 是有限生成 $AModule(A)$ + 存在有限扩张 $A[x] subset C subset B$ 其中 $C$ 是有限 $A-$代数 + 存在忠实 $AModule(A[x])$($forall y in A[x], y M = 0 => y = 0$)作为 $AModule(A)$有限生成, ] #proof[ - 1 $=>$ 2 利用首一的带余除法即可 - 2 $=>$ 3 取 $C = A[x]$ 即可 - 3 $=>$ 4 取 $M = C$,注意到 $1 in M$ 从而当然忠实 - 4 $=> 1$ 考虑自同态 $phi: m: M -> x m$,可以利用 @Hamiton-Cayley 得存在首一多项式使得: $ f(phi) = 0 => f(x) M = 0 => f(x) = 0 $ 证毕 ] #corollary[][ 设 $x_i$ 是整元,则 $A[x_1, x_2, ..., x_n]$ 是有限 $A-$代数,特别的其中元素 $x_i + x_j, x_i x_j$ 是整元。故 $B$ 中的 $A$ 上整元构成子环,这个子环称为 $A$ 在 $B$ 中的整闭包 ] #definition[][ - 若 $B$ 中 $A$ 上整元只有 $A$ 中元素,则称 $A$ 在 $B$ 中整闭 - 若 $B$ 中所有元素都在 $A$ 上整,则称 $B$ 在 $A$ 上整 ] #example[][ - $ZZ subset QQ$ 是整闭的(注意我们只选首一多项式) - 一般的,唯一分解整环在分式域中就是整闭的。否则,显然元素 $k/s$ 的零化多项式恰如: $ (s x - k) in k[x] $ 无妨设 $k, s$ 互素,容易看出有首一多项式 $in (s x - k) sect A[x]$ 除非 $s$ 在 $A$ 中可逆,进而这个元素只能在 $A$ 中 ] #definition[][ 设 $phi: A -> B$ 是环同态,称 $B$ 在 $A$ 上整,如果 $B$ 在 $f(A)$ 上整,也称 $phi$ 是整的或者 $B$ 是整 $A-$代数 ] #corollary[][ 设 $f$ 是整的且有限生成,则 $f$ 是有限的 ] #proof[ 每一个生成元都整,进而作为模是有限生成的 ] #theorem[传递性][ 设 $B$ 在 $A$ 上整,$C$ 在 $B$ 上整,则 $C$ 在 $A$ 上整 ]<integral-transitivity> #proof[ 设 $x in C$,则存在首一多项式 $f(x) in B[x]$ 使得 $f(x) = 0$\ 设 $f$ 的系数为 $b_i$,这些系数都在 $A$ 上整,进而: $ f(x) in (A[b_i])[x] $ 而 $A[b_i]$ 是有限生成的代数,$x$ 在其上整,进而 $A[b_i, x]$ 也是有限生成代数,故 $x$ 在 $A$ 上整 ] #corollary[][ 设 $A subset B$, $C$ 是 $A$ 的整闭包,则 $C$ 在 $B$ 上整闭 ] #proof[ 否则,设 $C'$ 是 $C$ 的整闭包,由 @integral-transitivity 得 $C'$ 在 $A$ 上也整,矛盾! ] #proposition[][ 设 $A subset B$ 且 $B$ 在 $A$ 上整,则 - 任取 $B$ 的理想 $J, B quo J$ 在 $A quo (J sect A)$ 上整 - 任取 $A$ 的乘性子集 $S, Inv(S) B$ 在 $Inv(S) A$ 上整 ] #proposition[][ 设 $A subset B$, $C$ 是 $A$ 在 $B$ 上的整闭包,则 $Inv(S) C$ 是对应的整闭包 ] #proof[ $Inv(S) C$ 是整扩张前面已经证明,任取 $b / s$ 在 $Inv(S) A$ 上整,只需证明它落在 $Inv(S)C$,也即: $ exists t in S, t b in C $ 由条件,存在多项式使得: $ (b/s)^n + a_1/s_1 (b/s)^(n-1) + ... + a_n/s_n = 0\ b^n + (a_1 s)/s_1 b^(n-1) + ... + a_n/s_n s^n = 0\ (s_1 s_2 ... s_n b)^n + a_1 s_2 s_3 ... s_n (b s_1 s_2 ... s_n)^(n-1) + ... + a_n (s_1 s_2 ... s_n)^n = 0 $ 取 $t = s_1 s_2 ... s_n$,上式给出了 $b t$ 的一个首一零化多项式,进而 $b t in C$,得证 ] == going-down 与 going-up #proposition[][ 设 $A subset B$ 且 $B$ 在 $A$ 上整 - 若 $A, B$ 是整环,则 $B$ 是域当且仅当 $A$ 是域 - 若 $q in Spec(B)$ 在 $p = q sect A in Spec(A)$ 之上,则有整环间的整扩张 $A quo p -> B quo q$,从而 $p$ 是极大理想当且仅当 $q$ 是极大理想 - 设 $q subset q' in Spec(B)$,若 $q sect A = q' sect A := p$,则 $q = q'$ ]<integral-prime-containing> #proof[ - 先证明假设 $A$ 是域,则 $B$ 也是域\ 任取 $b in B$,存在多项式使得: $ b^n + a_1 b^(n-1) + ... + a_n = 0 $ 不妨设 $a_n != 0$,则: $ b(b^(n-1) + a_1 b^(n-2) + ... + a_(n-1)) = -a_n $ 然而上式右侧是单位,因此 $b$ 也是单位,证毕 再假设 $B$ 是域,任取 $x in A, Inv(x) in B$ 是整元,存在多项式: $ x^(-n) + a_1 x^(-n+1) + ... + a_n = 0\ x^(-1) + a_1 + ... + a_n x^(n-1) = 0 $ 上式中除 $Inv(x)$ 外的项都在 $A$ 中,进而它也在 $A$ 中,证毕 - 就是前一个命题的直接推论 - 做局部化 $A_p$,设 $B_p = Inv((A - p))B$,则 $p A_p$ 是极大理想,且 $q B_p subset q' B_p$ 是 $B_p$ 的素理想,由上面结论得它们都是极大理想,进而 $q B_p = q' B_p$\ 假设 $q' != q$,取 $y' in q' - q$,则 $y'/1 in q' B_p => y'/1 = y/1 => exists x in A - p, x(y' - y) = 0 => x y' = x y in q => x in q or y' in q => x in q => x in A sect q = p$,这是荒谬的 ] #theorem[][ 设 $A subset B$ 且 $B$ 在 $A$ 上整,则 $Spec(B) -> Spec(A)$ 是满射 ] #proof[ 任取 $p in Spec(A)$,类似的做 $A_p$ 并令 $B_p = Inv(A - p) B$,任取 $B_p$ 的极大理想 $m$,由之前的结论知 $m sect A_p$ 也是极大理想,从而只能是 $p A_p$,证毕 ] #theorem[going-up][ 设 $A subset B$ 且 $B$ 在 $A$ 上整。任取 $Spec(B)$ 中升链 $ q_1 < q_2 < ... < q_m $ 对应 $Spec(A)$ 中升链的一部分: $ p_1 < p_2 < ... < p_m < p_(m+1) < ... < p_n $ 使得 $p_i = q_i sect A, forall i = 1, 2, ..., m$\ 则 $q_i$ 可以被拓展到 $n$ 项,并且满足 $q_i = p_i sect A, forall i = 1, 2, ..., n$ ] #proof[ 由 $Spec(B) -> Spec(A)$ 的满射性,取原像即可 ] #definition[][ 称一个整环是整闭的,如果环在分式域上整闭 ] #proposition[][ 设 $A$ 是整环,则以下条件等价: - $A$ 整闭 - 对于任何素理想 $p$ 均有 $A_p$ 整闭 - 对于任何极大理想 $m$ 均有 $A_m$ 整闭 ] #proof[ 取 $C$ 是 $A$ 在分式域中的整闭包,$f$ 是嵌入,则以上条件等价于 $f$ 是满射(可以验证兼容性) ] #definition[][ 设 $A subset B, I subset A$ 是理想,称 $b in B$ 在 $I$ 上整,如果 $exists f(x) in I[x], f(b)= 0$\ 类似的,可以定义 $I$ 上的整闭包 ] #lemma[][ 设 $A subset B, I subset A$ 是理想,$C$ 是 $A$ 在 $B$ 中的整闭包,则 $I$ 在 $B$ 上的整闭包恰为: $ sqrt(I C) $ 特别的,这是一个理想,因此整闭包对于加法和乘法有封闭性 ] #proof[ 任取 $x in B$ 在 $I$ 上整,则 $x in C$ 且: $ x^n + a_1 x^(n-1) + ... + a_n = 0 $ 其中除了 $x^n$ 之外都在 $I C$ 之中,进而 $x^n$ 也在,故 $x in sqrt(I C)$ 对于另一个方向,设 $x in sqrt(I C)$,则: $ x^n = sum a_i c_i $ 其中 $c_i$ 在 $A$ 上是整的,因此 $M := A[c_i]$ 是有限生成 $AModule(A)$\ 考虑自同态 $phi: m : M -> x^n m$,上式给出 $phi(M) subset I M$,由 @Hamiton-Cayley 得存在首一多项式 $f(x) in I[x]$ 使得: $ f(phi) = 0 => f(x^n) M = 0 $ 而 $M$ 作为模忠实,故 $f(x^n) = 0$,表明 $x^n$ 是整的,继而 $x$ 也是,证毕 ] #proposition[][ 设 $A subset B$,$A$ 在分式域 $k$ 中整闭,设 $x in B$ 在 $I subset A$ 上整,则 $x$ 是 $k$ 上的代数元,并设其最小多项式为 $t^n + k_1 t^(n-1) + ... + k_n$,则有 $k_i in sqrt(I)$\ 简而言之,整元的极小多项式是整系数的 ] #proof[ $x$ 是 $k$ 上是代数元显然\ 设极小多项式 $f = ^n + k_1 t^(n-1) + ... + k_n$,取 $f$ 的分裂域 $L$,其中有 $n$ 个零点: $ x_1 = x, x_2 , ..., x_n $ 显然 $x_i$ 都是 $I$ 上整元。注意到系数 $k_i$ 都是 $x_1$ 的多项式,因此落在 $I$ 的整闭包之中,进而: $ k_i in sqrt(I C) = sqrt(I A) = sqrt(I) $ 证毕 ] #theorem[going down][ 设 $A subset B$ 都是整环,$B$ 在 $A$ 上整,$A$ 在其分式域中整闭。若在 $A$ 中有素理想降链: $ p_1 > p_2 >... > p_n $ 其中前一部分在 $B$ 中有对应: $ q_1 > q_2 > ... > q_m, m >= n $ 则存在 $q_(m+1) > ... > q_n$ 使得: $ q_i sect A = p_i, forall i = 1, 2, ..., n $ ] #proof[ 同样只需要证明 $n = 2, m = 1$ 情形\ 经典的技巧是使用商环扩充素理想,使用分式环降低素理想。这里使用分式环。\ 利用 @integral-prime-containing 任取一个元素 $x in p_2 B_(q_1) sect A, x$ 将形如: $ x = y / s, y in p_2 B, s in B - q_1 $ 断言 $y in B$ 在 $p_2 subset A$ 中整(既然 $p_2$ 在 $B$ 中的整闭包是 $sqrt(p_2 B)$,进而它的极小多项式系数落在 $sqrt(p_2) = p_2$ 中,也即其最小多项式形如: $ t^r + a_1 t^(r-1) + ... + a_r, a_i in p_2 $ 将 $y = s x$ 代入,得: $ s^r + b_1 s^(r-1) + ... + b_r = 0, b_i = v_i/x^r $ 然而再次利用上面的引理,将有 $b_i in A$,进而: $ x^r b_i = v_i in p_2, x^r, b_i in A $ 由 $p_2$ 是素理想,如果 $x in.not p_2$,则 $b_i in p_2$,进而: $ s^r = -b_1 s^(r-1) - ... - b_r in p_2 $ 故 $s in p_2$,然而之前假设 $s in B - q_1$,矛盾! 这表明 $x in p_2$,也即 $p_2 B_(q_1) sect A subset p_2$,反之 $p_2 subset p_2 B_(q_1) sect A$ 是显然的,最终有 $p_2 B_(q_1) sect A = p_2$ ] #theorem[][ 设 $A subset B$ 都是整环,$B$ 在 $A$ 上整,$A$ 在其分式域 $k$ 中整闭,则: - 若存在正规扩张 $L quo k$ 使得 $B$ 是 $A$ 在 $L$ 中的整闭包,则任何两个 lying over 同一个素理想 $p$ 的 $B$ 中素理想 $q_1, q_2$ 都在 $Aut(L quo k)$ 中某个自同构下共轭 - going down 性质成立 ] #proof[ - 先不证明 - 设 $p_1 > p_2$,先通过 going up 产生 $q_1' > q_2'$ 使得 $q_1 sect A = q_1 sect A = p_1$,由前面的命题得它们共轭,也即: $ sigma(q'_1) = q_1 $ 如此可以证明 $sigma(q'_2) sect A = p_2$ #TODO ]
https://github.com/maucejo/book_template
https://raw.githubusercontent.com/maucejo/book_template/main/template/appendix/app1.typ
typst
MIT License
#import "../../src/book.typ": * #show: chapter.with( title: "Algorithmes", toc: false ) #lorem(100) La Figure @fig:A illustre le cas d'industriels utilisant des absorbants. #figure( image("../images/chapitre1/cnam_region.png", width: 75%), caption: [#lorem(10)], ) <fig:A> #figure( table( columns: 3, table.header( [Substance], [Subcritical °C], [Supercritical °C], ), [Hydrochloric Acid], [12.0], [92.1], [Sodium Myreth Sulfate], [16.6], [104], [Potassium Hydroxide], table.cell(colspan: 2)[24.7], ), caption: [#lorem(2)] )
https://github.com/darkMatter781x/OverUnderNotebook
https://raw.githubusercontent.com/darkMatter781x/OverUnderNotebook/main/entries/boomerang/boomerang.typ
typst
#import "/packages.typ": notebookinator, gentle-clues #import notebookinator: * #import themes.radial.components: * #import gentle-clues: * #import "/util.typ": qrlink #show: create-body-entry.with( title: "Concept: Boomerang", type: "concept", date: datetime(year: 2024, month: 2, day: 28), author: "<NAME>", ) = Boomerang Controller: So how do you get from point a to point b with a heading of theta? Seems like a pretty trivial question right? Just drive towards point b, and turn once reaching point b, but this isn't the most efficient solution. The better solution would be to take an arc-like path that causes the robot to end with the target heading. This solution / algorithm is called the boomerang controller. It works by creating a carrot point for every loop of the controller that the bot will attempt to go to. The generation of this point is done in such a way that as the robot nears the target point, it will converge on the target point. The algorithm and graph for the generation for the carrot point is below. == Calculations: The distance between target position and the carrot point: $h=sqrt( (x#sub[current] - x#sub[target])^2 + (y#sub[current] - y#sub[target])^2 )$ The coordinates for the carrot: $x#sub[carrot]=x#sub[target]-h cos(theta#sub[target]) d#sub[lead]$ $y#sub[carrot]=y#sub[target]-h sin(theta#sub[target]) d#sub[lead]$ == Visualization #set align(center) #image("./desmos.png", height: 30%) === Interactive Visualization #qrlink("https://www.desmos.com/calculator/p4aocro3bg", width: 35mm)
https://github.com/storopoli/Bayesian-Statistics
https://raw.githubusercontent.com/storopoli/Bayesian-Statistics/main/slides/08-poisson_regression.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "@preview/polylux:0.3.1": * #import themes.clean: * #import "utils.typ": * #import "@preview/cetz:0.1.2": canvas, plot #new-section-slide("Poisson Regression") #slide(title: "Recommended References")[ - #cite(<gelman2013bayesian>, form: "prose") - Chapter 16: Generalized linear models - #cite(<mcelreath2020statistical>, form: "prose"): - Chapter 10: Big Entropy and the Generalized Linear Model - Chapter 11, Section 11.2: Poisson regression - #cite(<gelman2020regression>, form: "prose") - Chapter 15, Section 15.2: Poisson and negative binomial regression ] #focus-slide(background: julia-purple)[ #align(center)[#image("images/memes/poisson-distribution.jpg")] ] #slide(title: [Count Data])[ #v(3em) Poisson regression is used when our dependent variable can only take *positive values*, usually in the context of *count data*. ] #slide(title: [What is Poisson Regression?])[ Poisson regression behaves exactly like a linear model: it makes a prediction by simply computing a weighted sum of the independent variables $bold(X)$ with the estimated coefficients $bold(β)$: $bold(y)$. But, different from linear regression, it outputs the *natural log* of $bold(y)$: $ log(bold(y))= α dot β_1 x_1 dot β_2 x_2 dot dots dot β_k x_k $ which is the same as: $ bold(y) = e^((α + β_1 x_1 + β_2 x_2 + dots + β_k x_k)) $ ] #slide(title: [Exponential Function])[ #align(center)[ #canvas( length: 0.9cm, { plot.plot( size: (16, 9), x-label: $x$, y-label: $e^x$, x-tick-step: 1, y-tick-step: 20, y-min: -0.01, { plot.add( domain: (-1, 5), samples: 200, // label: $"exponential"(x)$, // FIXME: depends on unreleased cetz 2.0.0 x => calc.exp(x), ) }, ) }, ) ] ] #slide(title: [Comparison with Linear Regression])[ Linear regression has the following mathematical expression: $ "linear" = α + β_1 x_1 + β_2 x_2 + dots + β_k x_k $ where: - $α$ -- intercept. - $bold(β) = β_1, β_2, dots, β_k$ -- independent variables' $x_1, x_2, dots, x_k$ coefficients. - $k$ -- number of independent variables. If you implement a small mathematical transformation, you'll have *Poisson regression*: - $log(y) = e^("Linear") = e^(α + β_1 x_1 + β_2 x_2 + dots + β_k x_k)$ ] #slide(title: [Poisson Regression Specification])[ We can use Poisson regression if the dependent variable $bold(y)$ has count data, i.e., $bold(y)$ only takes positive values. *Poisson likelihood function* uses an intercept $α$ and coefficients $bold(β)$, however these are "exponentiated" ($e^x$): #v(1em) $ bold(y) &tilde "Poisson"(e^((α + bold(X) bold(β)))) \ α &tilde "Normal"(μ_α, σ_α) \ bold(β) &tilde "Normal"(μ_(bold(β)), σ_(bold(β))) $ ] #slide(title: [Interpreting the Coefficients])[ When we see the Poisson regression specification, we realize that the coefficient interpretation requires a transformation. What we need to do is undo the logarithm transformation: $ log^(-1)(x) = e^x $ So, we need to "exponentiate" the values of $α$ and $bold(β)$: $ bold(y) &= e^((α + bold(X) bold(β))) \ &= e^(α) dot e^((X_((1)) dot β_((1)))) dot e^(( X_((2)) dot β_((2)) )) dot dots dot e^((X_((k)) dot β_((k)))) $ ] #slide(title: [Interpreting the Coefficients])[ Finally, notice that, when transformed, our dependent variables is no more a "weighted sum of an intercept and independent variables": #v(1em) $ bold(y) &= e^((α + bold(X) bold(β))) \ &= e^(α) dot e^((X_((1)) dot β_((1)))) dot e^(( X_((2)) dot β_((2)) )) dot dots dot e^((X_((k)) dot β_((k)))) $ #v(1em) It becomes a *"weighted product"*. ]
https://github.com/flaribbit/indenta
https://raw.githubusercontent.com/flaribbit/indenta/master/lib.typ
typst
MIT License
// https://github.com/flaribbit/indenta #let fix-indent(unsafe: false)={ return it=>{ let _is_block(e,fn)=fn==heading or (fn==math.equation and e.block) or (fn==raw and e.has("block") and e.block) or fn==figure or fn==block or fn==list.item or fn==enum.item or fn==table or fn==grid or fn==align or (fn==quote and e.has("block") and e.block) // TODO: smallcaps returns styled(...) let _is_inline(e,fn)=fn==text or fn==box or (fn==math.equation and not e.block) or (fn==raw and not (e.has("block") and e.block)) or fn==highlight or fn==overline or fn==smartquote or fn==strike or fn==sub or fn==super or fn==underline or fn==emph or fn==strong or (fn==quote and not (e.has("block") and e.block)) let st=2 for e in it.children{ let fn=e.func() if fn==heading{ st=2 }else if _is_block(e,fn){ st=1 }else if st==1{ if e==parbreak(){st=2} else if e!=[ ]{st=0} }else if st==2 and not (_is_block(e,fn) or e==[ ] or e==parbreak()){ if unsafe or _is_inline(e,fn){context h(par.first-line-indent)} st=0 } e } }}
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fh-joanneum-iit-thesis/1.2.2/template/chapters/8-conclusion.typ
typst
Apache License 2.0
#import "global.typ": * = Conclusion and Outlook #lorem(55) #todo( [ Sum up the results achieved and give an outlook by suggesting further research by explaining how others could built on your results. ], )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/simple-preavis/0.1.0/template/example.typ
typst
Apache License 2.0
#import "@preview/simple-preavis:0.1.0": lettre-preavis, locataire, adresse, proprietaire #lettre-preavis( locataire: locataire( "<NAME>", "Jean", adresse( "123 rue de la Paix", "75000", "Paris", complement: "Appartement 2" ) ), proprietaire: proprietaire( "<NAME>", "Sophie", adresse( "456 avenue des Champs-Élysées", "75008", "Paris" ), "Madame" ), date-etat-des-lieux: datetime(year:2024, month:9, day:21) )
https://github.com/jamesrswift/musicaux
https://raw.githubusercontent.com/jamesrswift/musicaux/main/src/commands/time.typ
typst
#import "basic-content.typ": basic-content, basic-text-above, space #import "../symbols.typ": * #let common = basic-content.with(pitch: 3, symbols.time.common) #let cut = basic-content.with(pitch: 3, symbols.time.cut) #let signature(top, bottom) = { let sized = text.with(size: 0.7em, weight: "bold", font:"Bravura") space(0.25em) basic-content(pitch: -1.4, width: 0em, sized(top)) basic-content(pitch: 2.5, width: 0em, sized(bottom)) space(0.25em) } #let tempo( content, bpm: 120, font: "Bravura" ) = { basic-content( dy: -2.8em, place( box(text(font: font, size: 12pt)[*#content*#h(0.4em);( 𝅘𝅥𝅮 = #bpm )], width: 100em) ) ) }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/014%20-%20Khans%20of%20Tarkir/008_The%20Salt%20Road.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Salt Road", set_name: "Khans of Tarkir", story_date: datetime(day: 12, month: 11, year: 2014), author: "<NAME>", doc ) "Captain." The lieutenant jogged up beside him, kicking up a spray of dusty sand that drifted sideways in the breeze sweeping across the craggy steppes that hot afternoon. "Do you see that smoke there on the horizon, to the east of Golem Rock? That could be a Mardu camp." He raised his arm to illustrate the vector and pointed with his gloved hand, each overlapping metal plate of the articulated fingers clicking into place as he straightened his index finger.   "Good eye," Riza responded, scanning in that direction. "But that is no Mardu encampment. We would see many campfires as they like to make a show of numbers in order to confuse enemies. And if it was a Mardu scout, the only evidence we would see would be the hoof prints left in the dirt." Riza breathed a quiet sigh of relief that his lieutenant was wrong. #emph[Let us pray] , he thought, #emph[that we do not make contact with the enemy for the remainder of this patrol] . He looked over his shoulder at his men, fifty strong, walking in two columns, maintaining a disciplined march, but engaged in small talk and laughter.   "When I get back to my wife," his krumar chief of scales boasted, "I'm going to drink an entire jug of wine, eat an entire hindquarter of a goat, and I will not leave my bedroom for two days."   "And I," Riza replied, "will sing my children to sleep." He paused. "And then drink a jug of wine, eat a goat, and retire to my bedroom." His men laughed as they marched the shepherd's path that paralleled the Salt Road, moving ever farther from the safety and civilization of the Abzan territories.   #figure(image("008_The Salt Road/01.jpg", width: 100%), caption: [Sandsteppe Citadel | Art by <NAME>], supplement: none, numbering: none) As the day wore into a reddish afternoon, the lieutenant again hurried up to the commander's side.   "Commander, do you see that smoke there?" He pointed it out in the hazy distance. "It looks like many campfires."   "Yes," Riza replied slowly, his smile fading, "I do see that." He stopped and his men drew to a halt behind him. "What do you make of that?"   "Sir," his battle priest said, "I do not think that is a campfire. I sense something very different."   The patrol marched on, more quietly now as they slowly approached the distant smoke. It became obvious that it was not campfires they were seeing but burning buildings, as the smoke rolled up thick and black, drifting back and forth in the shifting desert winds. The men grew silent and wary, keeping keen eyes in all directions. The patrol's falconer dispatched their buzzard who screeched as he took wing, a stray feather circling back to the ground behind him.   #figure(image("008_The Salt Road/02.jpg", width: 100%), caption: [Plains | Art by Noah Bradley], supplement: none, numbering: none) Eventually, they reached the source of the smoke, a summer camp for the shepherds who grazed their flocks in the grasses of the nearby mountain slopes. The horror of the scene was hard for the men to absorb. They had seen villages ravaged by Mardu hordes before, but nothing quite this brutal. The small village lay in utter desolation. No survivors were left. Men, women, and children lay where they fell, splayed open or missing limbs and heads. Each of the wood-framed lean-to huts smoldered, with not one left standing.   The patrol fruitlessly looked for survivors. The scouts counted hoof-prints to determine the size of the horde that had moved on to the north, estimating at least one hundred.   #emph[I do not want to meet this horde] , the commander thought as he ordered his men to bury the bodies.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   The hordechief dropped the goat bone he had just stripped of its meat and chugged the last gulps of wine before letting the vessel fall to the ground and break.   "This is the fruits of our labor!" he exclaimed to his warriors as he slumped back on his pillows. The small army arrayed across the field before him looked up from its meat and wine to hail its fearless leader.   #figure(image("008_The Salt Road/03.jpg", width: 100%), caption: [Raiders' Spoils | Art by <NAME>], supplement: none, numbering: none)   "Backstabber, take stock of our new supplies and figure how long before we must loot again."   Backstabber took a final bite and slinked away to count the stolen goats and cheeses.   "Nightrider, we must discuss our next target." He motioned his advisor to come closer. "The shepherds will be moving their flocks north to the villages for winter. Let us raid while the pickings are easy." #emph[And keep away from Abzan strongholds when we can] , he thought.   He surveyed his horde—orcs, humans, goblins, horses, all relying on him. #emph[They need me] , he thought, self-satisfied yet grave. #emph[Their survival depends on my unwavering certainty. Any crack in my façade is the opportunity another will take to become horde leader. It is how I gained my rank, it is the way of our people, and it is what has kept us alive for so many generations.]   He was roused from his introspection by the return of one of his spies. The diminutive goblin slinked up and whispered in his ear.   "I have news. An Abzan patrol is tailing us, only half a day's ride to the south. Their numbers are half of ours, mostly on foot, well-armed and armored, and they know we are here. They have seen the shepherd camp." He looked up at his leader, awaiting a reaction.   The horde leader breathed out slowly, reached for a nearby flagon, and drank deeply.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   "We are outnumbered two to one," Riza, the patrol captain, said to his top lieutenants, who stood in a circle around a map of the area. "I do not think direct confrontation is wise."   "Sir," said his battle priest, "we are the law on the Salt Road. If we do not act, more innocents will surely die."   "If we march out there and confront the Mardu," Riza replied, "we will find ourselves outflanked, outnumbered, and completely open to their deadly archery. If we are slaughtered by the horde, no one will protect the shepherds who feed the Sandsteppe Gateway."   His men murmured consent. #emph[I am afraid] , he thought, #emph[but I must remain steadfast. The Mardu strike like lightning on a dry day. We will be slaughtered like stray dogs and I will never see my family again.]   "We will fall back to the oasis at Canyon Falls and await the larger Salt Road patrol. Once we rendezvous, we will have the strength and support to drive the horde back to their lands. Lieutenant, send runners to find the patrol and apprise them of our situation. Also, engage our spy to put eyes on the horde."   #figure(image("008_The Salt Road/04.jpg", width: 100%), caption: [Watcher of the Roost | Art by <NAME>], supplement: none, numbering: none)   When the Abzan had finished burying the dead and giving their rites, the patrol rested briefly before packing up and backtracking toward the oasis.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   The hordechief stood up and brushed crumbs and gristle from his belly.   "Abandon your feast," he yelled with a suddenness that froze his warriors arrayed around him for hundreds of yards. "The foolish Abzan have sent a patrol after us that is half our strength. Once we slaughter them we will be free to raid these lands at our will. Anyone who makes an Abzan kill may claim the spoils of the body."   #figure(image("008_The Salt Road/05.jpg", width: 100%), caption: [Mardu Warshrieker | Art by <NAME>], supplement: none, numbering: none)   The leader's advisors stared in shock at the unexpected dictate. Only the quartermaster spoke up.   "I advise against this," she said. "We are fat with supplies and hoped to give our warriors a deserved rest. If this patrol is so weak, they are no threat to us. Let us feast for a night and enjoy our victory."   Anger flashed in the hordechief's eyes. "Do you want to lead this horde? Do you want the responsibility on your shoulders? Because if we wait, the Abzan will gather their strength and build their defenses. Reinforcements are never far behind their patrols. You do not question my orders."   The quartermaster's mouth twisted into a pained expression as her eyes flinched away from the leader in a submissive gesture.   "I am giving you a warning so that you will remember not to question my authority in front of my people. Hold out your hand."   The quartermaster tentatively reached her hand toward the leader, who quickly snatched it, drew his knife, and sliced the tip off the pinky finger before she could react. The other advisors backed away, ready to fulfill the hordechief's orders. #emph[It pains me to hurt her] , he thought, #emph[but there can be no question of my absolute authority.]   "We ride at once!" he screamed at his people, who burst into action, packing their camp and gathering their mounts as the golden sun turned red on its last dip toward the horizon.   #figure(image("008_The Salt Road/06.jpg", width: 100%), caption: [<NAME> | Art by <NAME>], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   The buzzard spy returned to the patrol early the following morning, circling down from beyond the vision of ordinary men. The sun had not yet crested the mountains to the east and the desert dew lay thick on the crumbly earth. The moon had not yet set and the patrol navigated by the watery reflection off the flat earth.   "The horde has turned south to engage us," the falconer reported. "They have been riding all night and will be upon us before noon."   The captain gathered his lieutenants around him but did not halt the march. They stepped to the side to confer quietly, out of earshot of the rank and file.   "We cannot retreat as fast as they can ride," he began. "There is little hope we can rendezvous with the larger patrol before we are caught. I am afraid our only hope is to prepare for a direct fight."   "If we hurry, sir, we might be able to reach the oasis. The canyon will nullify the advantage of their cavalry. We might be able to establish a strong defense using the terrain and trees of the oasis. If we can hold them back, we may be able to outlast them until reinforcements show up. We will have access to water and shelter, and they will be fighting from the open desert."   The first lieutenant looked at the other men, pleased.   #figure(image("008_The Salt Road/07.jpg", width: 100%), caption: [Chief of the Scale | Art by <NAME>umbo], supplement: none, numbering: none)   The captain looked at each of his lieutenants in turn. No one disagreed with that course of action.   "If we are caught retreating, we are surely dead. But even if we stand and fight here we will probably perish anyway. Let's give ourselves the best odds." He stood tall among his men.   "Double time," the captain ordered, and jogged to the front of the ranks.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   The hordechief slumped forward a bit on his warhorse. Riding through the night was tiring. But not as tiring as marching, like the Abzan were surely doing. He had hoped to overrun them in the dark and take them unawares, but clearly they had been alerted to his plans. The horde had been following the retreating tracks of the patrol ever since they had passed the burned-out shepherds' camp.   If the Abzan had time to establish a defensive position, it would be foolish to attack them head on. His riders were swift, but they were lightly armored. Even a smaller Abzan patrol could prove devastating once it had prepared for an attack. But now that his plan was set in motion, he had to retain the initiative. To change course would be a sign of uncertainty. He could not show weakness if he wanted to maintain his position as hordechief. At that point, he simply hoped they would come upon the Abzan before their enemies had time to gather reinforcements or establish a defense. It was still possible, although it was turning into a larger gamble than he had hoped for.   But this was the way of the Mardu. The strong survive. And the clan was strong. They had been living off of the labor of the weak for generations. All these warriors were relying on him to provide unwavering leadership in order to survive. The traditions of the clan, which had kept them alive and thriving for so long, must be maintained.   #figure(image("008_The Salt Road/08.jpg", width: 100%), caption: [Mardu Ascendancy | Art by <NAME>], supplement: none, numbering: none)   Perhaps this would be the day they were to die. But if not, then his position as leader would be extended once again.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   The captain gathered his lieutenants in the shade of a boulder and passed his water skin around. The day was already hot. The fifty men of the Abzan patrol filled their water skins from the oasis pool and watered the few ibex.   "<NAME>, join us," Riza said to his Mardu krumar chief of scales, who stood nearby scanning the horizon for signs of the horde. "Array your men at the mouth of the canyon and form a shield wall. Make sure they have ample spears and water."   The krumar hurried to fulfill the captain's orders.   #figure(image("008_The Salt Road/09.jpg", width: 100%), caption: [Take Up Arms | Art by <NAME>], supplement: none, numbering: none) "Hide our archers among the boulders along the west rim of the canyon to keep the horde away from that side. That should protect the men and supplies at the bottom. Send the rest of the men to the north end of the canyon where the spring begins to flow and set an ambush in case they try to come at us from behind. Keep four soldiers with the gear to resupply us and run my orders to the troops."   His lieutenants nodded. The battle priest supplicated himself to the ancestors and passed his blessing on to the troops, who crowded around the shade of the palms that grew along the spring bed.   "When we are on patrol, you are my family," Riza said to his soldiers. "It is this bond that gives us our strength. I believe in the capabilities of this unit and together we will make a defense worthy of our Abzan heritage."   The troops shared the interlocking handshake of the Abzan military and quickly busied themselves.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   The Mardu horde picked up speed as the oasis came into view. Only a few miles of hard, pebbly desert separated the two. Although the horde had ridden through the night, it was not exhausted. The temptation of battle and the hope for glory spurred it on. The hordechief looked back at the line of dust stretching hundreds of yards across the flat steppes. He closed his eyes and listened to the thunder of his cavalry, felt the hot desert wind rush through his hair. Victory was no longer in is hands. It was in the hands of the dragon now. The speed of the dragon's wings would win the day.   #figure(image("008_The Salt Road/10.jpg", width: 100%), caption: [Rush of Battle | Art by <NAME>], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   "The horde is closing!" cried the runner as he swept past the men stationed at the mouth of the canyon. Twenty-five heavily armored dragonscale infantry took up their spears and locked shields forming a solid wall across the small mouth of the canyon. No arrow could penetrate the wall that now stood as invulnerable as the dragon's back. The horde was swift, they knew, but the horde could not endure like the scales of the dragon.   The air hummed with the flight of arrows. The Abzan took shelter beneath their shields and behind trees and rocks. An unnatural wind blew into their faces and for a surprised few, there was no shelter from the barrage. The dragonscale infantry nervously filled in the holes left from their fallen comrades.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   The Mardu horde fluidly divided into two, on the hoof, wheeling toward both ends of the oasis canyon.   "To the victor goes the spoils!" the hordechief shrieked, as he drew his sword, the power of his voice spurring the horses faster, as if by magic.   He rose in his saddle just in time to see the tower of the Abzan siege elephant poking through the haze in the distance…   #figure(image("008_The Salt Road/11.jpg", width: 100%), caption: [Ivorytusk Fortress | Art by <NAME>], supplement: none, numbering: none)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-AA60.typ
typst
Apache License 2.0
#let data = ( ("MYANMAR LETTER KHAMTI GA", "Lo", 0), ("MYANMAR LETTER KHAMTI CA", "Lo", 0), ("MYANMAR LETTER KHAMTI CHA", "Lo", 0), ("MYANMAR LETTER KHAMTI JA", "Lo", 0), ("MYANMAR LETTER KHAMTI JHA", "Lo", 0), ("MYANMAR LETTER KHAMTI NYA", "Lo", 0), ("MYANMAR LETTER KHAMTI TTA", "Lo", 0), ("MYANMAR LETTER KHAMTI TTHA", "Lo", 0), ("MYANMAR LETTER KHAMTI DDA", "Lo", 0), ("MYANMAR LETTER KHAMTI DDHA", "Lo", 0), ("MYANMAR LETTER KHAMTI DHA", "Lo", 0), ("MYANMAR LETTER KHAMTI NA", "Lo", 0), ("MYANMAR LETTER KHAMTI SA", "Lo", 0), ("MYANMAR LETTER KHAMTI HA", "Lo", 0), ("MYANMAR LETTER KHAMTI HHA", "Lo", 0), ("MYANMAR LETTER KHAMTI FA", "Lo", 0), ("MYANMAR MODIFIER LETTER KHAMTI REDUPLICATION", "Lm", 0), ("MYANMAR LETTER KHAMTI XA", "Lo", 0), ("MYANMAR LETTER KHAMTI ZA", "Lo", 0), ("MYANMAR LETTER KHAMTI RA", "Lo", 0), ("MYANMAR LOGOGRAM KHAMTI OAY", "Lo", 0), ("MYANMAR LOGOGRAM KHAMTI QN", "Lo", 0), ("MYANMAR LOGOGRAM KHAMTI HM", "Lo", 0), ("MYANMAR SYMBOL AITON EXCLAMATION", "So", 0), ("MYANMAR SYMBOL AITON ONE", "So", 0), ("MYANMAR SYMBOL AITON TWO", "So", 0), ("MYANMAR LETTER AITON RA", "Lo", 0), ("MYANMAR SIGN PAO KAREN TONE", "Mc", 0), ("MYANMAR SIGN TAI LAING TONE-2", "Mn", 0), ("MYANMAR SIGN TAI LAING TONE-5", "Mc", 0), ("MYANMAR LETTER SHWE PALAUNG CHA", "Lo", 0), ("MYANMAR LETTER SHWE PALAUNG SHA", "Lo", 0), )
https://github.com/schang412/typst-whalogen
https://raw.githubusercontent.com/schang412/typst-whalogen/master/gallery/example.typ
typst
Apache License 2.0
#import "@local/whalogen:0.2.0": ce #set page(width: auto, height: auto) $ #ce("HCl + H2O -> H3O+ + Cl-") $
https://github.com/maucejo/tutorial_template
https://raw.githubusercontent.com/maucejo/tutorial_template/main/docs/manual.typ
typst
MIT License
#import "./manual-template.typ": * #import "../src/tutorial.typ": * #show: checklist.with(fill: eastern.lighten(95%), stroke: eastern, radius: .2em) #let TeX = style(styles => { set text(font: "New Computer Modern") let e = measure("E", styles) let T = "T" let E = text(1em, baseline: e.height * 0.31, "E") let X = "X" box(T + h(-0.15em) + E + h(-0.125em) + X) }) #let LaTeX = style(styles => { set text(font: "New Computer Modern") let a-size = 0.66em let l = measure("L", styles) let a = measure(text(a-size, "A"), styles) let L = "L" let A = box(scale(x: 110%, text(a-size, baseline: a.height - l.height, "A"))) box(L + h(-a.width * 0.67) + A + h(-a.width * 0.25) + TeX) }) //--------------------------------------------------------- #let abstract = [ #package[Tutorial] est un modèle #typst pour la rédaction de sujets d'exercices ou d'examens ] #show: manual-template.with( title: "Modèle pour les sujets d'exercices", subtitle: "", typst-version: "Typst 0.11.1", version: "0.1.0", abstract: abstract ) = Qu'est-ce que Typst ? #typst est un nouveau langage de balise open source é crit en Rust et développé à partir de 2019 par deux étudiants allemands, <NAME> et <NAME>. La version 0.1.0 a été publiée sur GitHub le 04 avril 2023#footnote[Adresse du dépôt GitHub : #link("https://github.com/typst/typst", text("https://github.com/typst/typst", fill: typst-color))]. #typst se présente comme un successeur de #LaTeX plus moderne, rapide et simple d'utilisation. Parmi ses avantages, on peut citer : - la compilation incrémentale ; - des messages d'erreur clair et compréhensible ; - un langage de programmation Turing-complet ; - une système de style cohérent permettant de configurer aisément tous les aspects de son document (police, pagination, marges, #sym.dots) ; - une communauté active et sympathique (serveur Discord pour le support, annonce de nouveaux paquets) ; - un système de paquets simple d'utilisation (pour rechercher ou voir la liste des paquets, n'hésitez pas à visiter #link("https://typst.app/universe", text("Typst: Universe", fill: typst-color))) ; - des extensions pour VS Code existent, comme `Typst LSP` ou `Tinymist`, pour avoir des fonctionnalités similaires à `LaTeX Workshop`. #v(0.5em) Pour finir, la documentation de #typst est suffisamment bien écrite et détaillée pour permettre de créer rapidement ses propres documents. Il faut compter moins d'une heure pour prendre en main la syntaxe (sans mentir #emoji.face.beam). Pour accéder à la documentation, suivez ce #link("https://typst.app/docs", text("lien", fill: typst-color)). Pour faciliter la transition de #LaTeX vers #typst, un guide est disponible #link("https://typst.app/docs/guides/guide-for-latex-users/", text("ici", fill: typst-color)). = Usage == Utilisation du template Pour utiliser le modèle, il faut l'importer dans votre fichier principal `typ` en utilisant la commande suivante. #codesnippet[ ```typ #import "./tutorial.typ": * ``` ] #ibox[ #set text(size: 11pt) Si vous décomposez votre document en différents fichiers, il faut insérer la commande précédente en préambule de chaque fichier. ] == Initilisation du modèle Après avoir importé le modèle, celui doit être initialisé en appliquant une règle d'affichage (`show` rule) avec la commande #cmd("tutorial") en passant les options nécessaires avec l'instruction `with` dans votre fichier principal `typ` : #codesnippet( ```typ #show tutorial.with( ... ) ``` ) Le modèle #cmd("tutorial") possède un certain nombre de paramètres permettant de personnaliser le document. Voici la liste des paramètres disponibles : #command("tutorial", ..args( title: none, subtitle: none, docfont: "Lato", docfontmath: "Lete Sans Math", [body]) )[#argument("title", default: none, types: "string")[Titre du document] #argument("subtitle", default: (), types: "string")[Sous-titre du document] #argument("docfont", default: none, types: "string")[Police de caractectères pour le corps du texte] #argument("docfontmath", default: none, types: "string")[Police de caractères pour les équations mathématiques] ] == Fonctions additionnelles Le modèle #package[Tutorial] fournit un certain nombre de fonctions additionnelles pour faciliter la rédaction de votre document. === Environnements *Exercice* Pour créer un nouvel exercice, il suffit d'utiliser la commande #cmd("exercice") : #codesnippet[ ```typ #exercice("Titre de l'exercice")[Texte de l'exercice] ``` ] #ibox[La numérotation des exercices est automatique.] *Question* Pour ajouter une question à un exercice, il suffit d'utiliser la commande #cmd("question") : #codesnippet[ ```typ #question[Texte de la question] ``` ] #ibox[La numéroration des questions est automatique et est réinitialisée pour chaque exercice.] *Correction* Pour ajouter une correction à une question, il suffit d'utiliser la commande #cmd("correction") : #example-box[ ```typ // À mettre au début du document // Mettre le paramètre `false` pour masquer les corrections #let corr = true // À mettre à la suite de la question #let rep = [Correction] #correction(corr, rep) ``` #align(center)[#line(stroke: 1pt + typst-color, length: 95%)] #let corr = true #let rep = [Correction] #correction(corr, rep) ] #pagebreak() === Boîtes englobantes Les boîtes englobantes sont des éléments graphiques permettant de mettre en avant des informations importantes. Le modèle #package[Tutorial] en propose actuelle trois types : `obj`, `reco` et `info`. #v(0.5em) 1. La boîte `obj` est utilisée pour mettre en avant les objectifs des exercices ou de l'examen. #example-box[ ```typ #obj[ + Objectif 1 + Objectif 2 ] ``` #align(center)[#line(stroke: 1pt + typst-color, length: 95%)] #obj[ + Objectif 1 + Objectif 2 ] ] #v(0.5em) 2. La boîte `reco` est utilisée pour mettre en avant les recommandations pour la réalisation des exercices ou de l'examen. #example-box[ ```typ #reco[ #lorem(20) ] ``` #align(center)[#line(stroke: 1pt + typst-color, length: 95%)] #reco[ #lorem(20) ] ] 3. La boîte `info` est utilisée pour mettre en avant des informations importantes. #example-box[ ```typ #info[ #lorem(20) ] ``` #align(center)[#line(stroke: 1pt + typst-color, length: 95%)] #info[ #lorem(20) ] ] === Sous-figures #typst ne dispose pas actuellement de mécanismes permettant de gérer les sous-figures (numérotation et référencement). Pour pallier ce manque, le modèle intègre une fonction #cmd("subfigure") permettant de gérer les sous-figures de manière adaptée. Cette fonction encapsule la fonction #cmd("subpar.grid") du package `subpar`. #codesnippet[ ```typ #subfigure( figure(image("image1.png"), caption: []), <figa>, figure(image("image2.png"), caption: []), <figb>, columns: (1fr, 1fr), caption: [(a) Première image and (b) Seconde image], label: <fig> ) ``` ] = Feuille de route Le modèle #package[Tutorial] est en cours de développement. Certaines fonctionnalités devront être implémentées dans les prochaines versions. Voici la liste des fonctionnalités actuelles et à venir : - [x] Mise en place du modèle de base - [ ] Ajout de boîtes englobantes (`warning`, `tip`, `important`) - [ ] Ajout de zones de réponses
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/mmgg-morning-walk.typ
typst
#import "mmgg-template.typ": mmgg-template #import "base-utils.typ": * #import "pinyin-sentence-layout.typ": zhuyin-atom, zhuyin-sentence, zhuyin-wrapper, zhuyin-sentence-chunk #let main(file) = { let options = ( blockSpacing: 15, englishNameSizing: 0.85, sentence: ( k: 0.50, // represents the length it is allowed to take leading: 0.95em, ) ) let (sentences, title) = json(file) let spacer = v(options.blockSpacing * 1pt) let mapper = zhuyin-sentence-chunk.with(..options.sentence) let main = block(sentences.map(mapper).join(spacer)) mmgg-template(main, title: title, englishNameSizing: options.englishNameSizing) } #let file = "/home/kdog3682/mmgg/morning_walk/v3.json" #main(file) // #main("/home/kdog3682/2023/clip.js") // well it works
https://github.com/Me0wzz/study-note
https://raw.githubusercontent.com/Me0wzz/study-note/main/LinearAlgebra/note.typ
typst
= Chapter 1.1 - 1.4 Linear Equation: $c_1 x_1 + c_2 +x_2 + ... + c_v x_v = b$ 형태 Matrix Equation: $mat(delim:"[",a_1,a_2,...,a_n) mat( delim:"[",x_1;x_2;...;x_3)$ 형태 $A X = [m times n][m times o]->[m times o]$ form Example 1)\ Linear Eq \ $ x_1 + 2x_2 - x_3 = 4 \ -5x_2 +3x_3 =1 $ Vector Eq \ $ x_1 mat(delim:"[",1;0) + x_2mat(delim:"[",2;-5) + x_3mat(delim:"[",-1;3)=mat(delim:"[",4;1) $ Matrix Eq \ $ mat(delim: "[", 1,2,-1;0,-5,3 ) mat(delim: "[", x_1; x_2; x_3) = mat(delim:"[", 4;1) $ If $A =m times n$ matrix, Everything below is equivalent.\ ($A$ is coefficient matrix, not augmented matrix)\ [m equations; n unknowns; n columns; b in $RR ^m$]\ 1. For each b in $RR^m$ $A x=B$ has "a"(at least one) solution. 2. Each b in $RR^m$ is linear combination of columns of $A$\ 3. The columns of $A$ span $RR^m$ 4. Matrix $A$ has pivot position in every row = 선형성 \ $A(u+v) = A(u) + A(v)$\ $A(c u) = c(A u)$\ #pagebreak() = Chapter 1.5 - 1.9\ == Homogeneous Linear System\ $A x = b$ 꼴\ $x=0$ means trivial solution\ if non-zero vector $x$ exist, that is non-trivial solution.\ For Homogeneous Equation(Ax=b),\ if free variable exists, Ax=b has nontrivial solution. - non-trivial solution has some zero entries, so long as not all of its entries are zero.\ $x=mat(delim:"[", x_1;x_2;x_3)=x_2mat(delim:"[",0.3;1;0) x_3 mat(delim:"[",0.2;0;1)=x_2 u + x_3 v$ \ Solution set is $s p a n{u, v}$ - $u, v$ are not scalar multiple of the other, the solution set is plane through the origin. = Parametric Vector Form Parametric Equation: $upright(x = s u + t v space (s,t in RR))$\ General Solution for Non-Homogeneous Equation ($upright(A x = b)$)\ $upright(b = p + t v_h)$ - $upright(t)$ as general parameter - For homogeneous, $upright(b = t v_h space (t in RR))$ - Non-Homogeneous => Solution of Homogenous Eq + vector $p$ - RREF 를 통하여 basic/free variables 를 구한 뒤, general solution 꼴로 표현 - $upright(x = p + v_h)$에서 $upright(p)$ 는 parameter 포함 X, $upright(v_h)$는 parameter을 포함 = Linear Dependency #grid( columns:(30%, 30%), gutter: 10pt, "Linearly dependent", "Linearly Independent", "Non-Trivial Solution", "Trivial Solution", "Det(A) == 0", "Det(A) != 0", "At least one is linear combination of others", "Nothing is linear combination of others", "p>n", "Depend on", "Zero vector in row vector", "Depend on" ) - If $upright(A x = 0 )$ has only trivial solution, columns of A is linearly independent. - Linearly dependent: 한 평면에 존재 - Linearly independent: 한 평면에 존재 X = Linear Transformation - $RR^n "to" RR_m"," RR^n "is called Domain of" T, RR^m "is codomain"$ - trivial(linearly independent) means one-to-one - T maps $RR^n "onto" RR^m "if and only if columns of" A "span" RR^m$ - onto means Existence question, one-to-one means Uniqueness question. - $T "is one-to-one" upright(T(x) = b) "has unique solution or none of all."$ #pagebreak() = Matrix Operations Matrix addtion: $upright(A + B)$ - They should have same size $m times n$ $A = m times n, B = n times o -> A B = m times o$ - $A B != B A$ - $(A^T)^T = A$ - $(A+B)^T = A^T+B^T$ - $(r A)^T = r A^T$ - $(A B)^T = B^T A^T$ (Remember reverse order) = Inverse of the Matrix $A^(-1) A = I$ - Invertible(가역) : Singular matrix(특이 행렬) - Non-Invertible(비가역): Non-Singular Matrix(정칙 행렬) - If $thin("Det" A) != 0$, Matrix $A$ is invertible. - $(A^(-1))^(-1) = A$ - $(A B)^(-1) = B^(-1) A^(-1)$ - $(A^T)^(-1) = (A^(-1))^T$ - to find $A^(-1), "use Identity Matrix." mat(delim:"[", A, I) "or" mat(delim:"[", I, A) $ = Characterizations of Invertible Matrices == IMT (Invertible Matric Theorem) for $n times n$ matrix - A is invertible Matrix - A is row equivalent to $n times n$ identity Matrix $I_n$ - n has n pivot positions - $upright(A x = 0)$ has only trivial solution. - Columns of A form linearly independent set - Linear transformation $upright(x -> A x)$ is one-to-one - $upright(A x = b)$ has at least one solution for each b in $RR^n$ - Columns of A span $RR^n$ - Linear transformation $upright(x -> A x)$ is onto - There is $n times n$ Matrix C/D such that $C A = I, A D=I$ - $A^T$ is invertible matrix = LU Decomposition (factorization) - Matrix multiplication involves synthesis of data - Matrix decompostion involves analysis of data - $U (m times n)$ is echelon form of matrix $A$ - $L (m times m)$ is unit lower triangular matrix - $upright(A x = b -> L (U x) = b)$, $upright( "solve y through L y = b, and get x through Ly = b")$ - U is upper triangular form (echelon form of A) - L is unit lower triangular form (You can get L while finding U) #pagebreak() = Subspace of $RR^n$ - Col A : All Linear combinations of Column of A - Nul A : All Solutions of homogeneous equation $upright(A x = 0)$ - Basis of subspace H : Linearly independent set in H that spans H == Subspace of $RR^n$ - Zero vector is in H - For each u and v in H, u+v is in H - For each u and each scalar c, cu is in H - {0} and $RR^n$ is subspace of $RR^n$ == Col A - Column space of matrix A is the set Col A of all linear combinations of columns of A - If A = $mat(a_1, ..., a_n) "with columns of" RR^m, "Col A is same as span"{a_1,...,a_n}$ - If $upright(A x = b)" is consistent, " upright(b) "is in Col" A$ == Nul A - Null space of matrix A is set of Nul A of all solutions of homogeneous equation $upright(A x=0)$ - Zero vector is in Nul A ($A 0 = 0$) - $upright(A u = 0 "," A v = 0", then " A(u+v) = 0)$ = Basis for Subspace - Basis for Subspace H of $RR^n$ is linearly independent set in H that spans H. - Pivot Columns of matrix A forms basis of Column space of a #pagebreak() = Dimension of Subspace - Dimension of vector subspace H: $upright(dim H)$ - count of vector that consists Basis - $H = {0} -> "dim" H = 0$ - 직선: 1, 평면: 2, 공간: 3 = Rank - $upright("Rank" A " means dimension of Column space of matrix A")$ - Counts of Pivot Columns - Rank A = Rank A|b -> Consistent - Rank A = Rank A|b = unknowns -> Unique - Rank A = Rank A|b $!=$ unknowns -> Infinite Solutions - Rank A $!=$ Rank A|b -> No Solution = Theorem's about subspace - n = rank A + dim(Nul A) [Rank theorem] - Let H be a p-dimensional subspace of $RR^n$ - Any linearly independent set of p elements in H is basis for H - any p elements of H that spans on H is basis for H = Extended IMT (Invertible Matric Theorem) - The columns of A forms a basis of $RR^n$ - Col A = $RR^n$ - dim(Col A) = n - rank A = n - Nul A = {0} - dim(Nul A) = 0 #pagebreak() = Determinant Determinant - $2 times 2 "matrix:" A = mat(a_11,a_12;a_21,a_22) -> |A| = a_11a_22 - a_12a_21$ - $3 times 3 "matrix: submatrix" A_(i j) <- " exclude i-th row, j-th column"$ #image("assets/2024-04-12-13-38-58.png") - $det A = Sigma_(j=1)^n (-1)^(1+j)a_(1 j)det A_(1 j)$ - 일반화: $det A = |A| = Delta = Sigma_(j=1)^n (-1)^(i+j)a_(i j)det A_(i j) = Sigma_(j=1)^n a_(i j)C_(i j) $ - i 의 값이 달라도 det A의 값은 똑같음. - $n times n "matrix" ,_ "submatrix" A_(i j) (n - 1 times n - 1) $ - $det A != 0 -> "Invertible matrix"$ - Cofactor: $C_(i j) = (-1)^(i+j)det A_(i j)$ - If $A "is" n times n "matrix, " det A "= product of entries of main diagonals of " A$ - $-n p <= det A <= n p [n times n "matrix", p = "abs(n largest elements in matrix" A)]$ #pagebreak() = Properties of Determinants == Theorem 3 - $A~U~I_n$ (If $A$ is invertible) - Replacement: $A -> B: det A = det B$ - Interchange: $A <->B : det B = - det A$ - Scaling: $det B = k det A$ - zero column/row $-> det A = 0$ - $"Col 1" = k"Col b" -> det A = 0$ - $det(k A) = k^n det A$ - $det A = (-1)^("count of interchange") det U$ - $det U = U_(11)+U_(22)+...+U_(n n)$ - if A = invertible $-> det U != 0$ - $det A = 0 ->$ rows/columns of A is linearly dependent - = Column Operations - $det A^T = det A$ - $det A B = det A det B$ - $det(A+B) != det A + det B$ #pagebreak() = Cramer's rule - $A_i (b) = mat(delim:"[",a_1,a_2,...,b,...a_n)$ - $x_i = (det A_i (b)) / (det A) (i=1,2,3,...,n)$ - $A I_i (x) = A[e_1...x...e_n] = [a_1...b...a_n] = A_i (b)$ - $(det A)(det I_i (x)) = det(A_i (b))$ = A Fomula for $A^(-1)$ - $A^(-1) = (1) / (det A) "adj" A$ - adjugate matrix is transpose of matrix of cofactors #pagebreak() = Questions 1 선형 방정식, 벡터 방정식, 행렬 방정식의 차이점을 설명하고, 각각의 예시를 들어주세요. 2 선형 시스템이 적어도 하나의 해를 가지기 위한 충분조건을 설명해주세요. 이때, 계수 행렬의 특성에 대해 언급해주세요. 3 선형 독립과 선형 종속의 개념을 설명하고, 이들의 특징을 비교해주세요. 또한, 행렬식(determinant)과의 관계에 대해 설명해주세요. 4 선형 변환(linear transformation)이란 무엇인가요? 선형 변환이 일대일 대응(one-to-one)이거나 전사함수(onto)가 되기 위한 조건을 설명해주세요. 5 행렬의 곱셈에 대해 설명하고, 행렬 곱셈의 성질 중 3가지를 예시와 함께 설명해주세요. 6 가역행렬(invertible matrix)이란 무엇인가요? 가역행렬이 되기 위한 필요충분조건을 3가지 이상 나열해주세요. 7 LU 분해(LU decomposition)에 대해 설명하고, LU 분해를 이용하여 선형 시스템을 푸는 과정을 간단히 설명해주세요. 8 $RR^n$ 공간의 부분공간(subspace)에 대해 설명하고, Col A와 Nul A의 의미를 각각 설명해주세요. #pagebreak() #let mathbf(text) = text #let bm(body) = mathbf(body) = 선형대수학 문제 다음 선형 시스템을 행렬 형태로 나타내고, 가우스 소거법을 사용하여 해를 구하세요. $ 2x_1 + 3x_2 - x_3 = 5\ x_1 - 2x_2 + 4x_3 = 3\ 3x_1 + x_2 - 2x_3 = 4 $ 다음 벡터들이 선형 독립인지 판별하세요. $bm(v_1) = (1, 2, -1)$ $bm(v_2) = (2, 1, 3)$ $bm(v_3) = (3, 5, 1)$ 다음 행렬 A의 LU 분해를 구하세요. $ bm(A) = mat( 2, 1, -1; -3, -1, 2; -2, 1, 2 ) $ 다음 행렬 A가 가역행렬인지 판별하고, 가역행렬이라면 역행렬을 구하세요. $ bm(A) = mat( 1, 2, 1; 0, 1, -1; 2, 3, 4 ) $ 다음 선형 변환 T가 일대일 대응이면서 전사함수인지 판별하세요. $ T : RR^3 -> RR^3, quad T(x_1, x_2, x_3) = (x_1 + x_2, x_2 + x_3, x_1 + x_3) $ 다음 행렬 A의 열공간($C o l bm(A)$)과 영공간($N u l bm(A)$)의 기저를 구하세요. $ bm(A) = mat( 1, 0, 2; -1, 2, 3; 2, -4, -3 ) $
https://github.com/linsyking/messenger-manual
https://raw.githubusercontent.com/linsyking/messenger-manual/main/intro.typ
typst
#import "@preview/fletcher:0.4.5" as fletcher: diagram, node, edge #import fletcher.shapes: hexagon = Introduction There are several Elm packages like #link("https://package.elm-lang.org/packages/evancz/elm-playground/latest/")[elm-playground], which offer simple APIs to create a game. However, these packages have many limitations and are not suitable for creating complex games. Messenger is a 2D game engine for Elm based on `elm-canvas`. It provides an architecture, a set of APIs, and many library functions to enable rapid game development. Additionally, Messenger is message-based and abstracts the concept of objects using the _co-inductive type_ technique. Messenger has many cool features: - *Coordinate System Support* The view-port and coordinate transformation functions are already implemented. Messenger is also adaptive to window size changes. - *Separate User Code and Core Code* User code and core code are separated. Any side effects are controlled by the Messenger core. This helps debugging and decrease security concerns. - *Basic Game Engine API Support* Messenger provides handy common game engine APIs. Including data storage, audio manager, sprite(sheet) manager, and so on. More features are still under development. - *Modular Development* Every component, layer, and scene is a module, simplifying code management. The implementation is highly packaged, allowing focus on the specific logic of the needed functions. Messenger is designed for convenience and ease of use. - *Highly Customizable* The data of each object can be freely defined. The target matching logic and message type are also customizable. Users can create their own object types using the provided General Model type. - *Flexible Design* The engine can be used to varying degrees, with separate management of different tasks. Components can be organized flexibly using the provided functions, allowing classification of portable and non-portable components in any preferred way. == Messenger Modules There are several modules (subprojects) within the Messenger project. All the development of Messenger is on GitHub. - #link("https://github.com/linsyking/Messenger")[Messenger CLI]. A handy CLI to create the game rapidly - #link("https://github.com/linsyking/messenger-core")[Messenger-core]. Core Messenger library - #link("https://github.com/linsyking/messenger-extra")[Messenger-extra]. Extra Messenger library with experimental features - #link("https://github.com/linsyking/messenger-examples")[Messenger examples]. Some example projects - #link("https://github.com/linsyking/messenger-templates")[Messenger templates]. Templates to use Messenger library. Used in the Messenger CLI *Note.* This manual is compatible with core `12.0.0 <= v < 13.0.0`, templates 0.3.7 and CLI 0.3.7. == Messenger Model The concept of the Messenger model is summarized in the following diagram: #align(center)[ #diagram( node-stroke: 1pt, edge-stroke: 1pt, node((1, 0), width: 10pt, height: 10pt, shape: circle, fill: yellow.lighten(60%), stroke: 1pt + yellow.darken(20%)), node((1+0.5, 0), width: 10pt, height: 10pt, shape: circle, fill: yellow.lighten(60%), stroke: 1pt + yellow.darken(20%)), node((1+0.5, 1), width: 10pt, height: 10pt, shape: circle, fill: yellow.lighten(60%), stroke: 1pt + yellow.darken(20%)), node((1, 1), width: 10pt, height: 10pt, shape: circle, fill: yellow.lighten(60%), stroke: 1pt + yellow.darken(20%)), node([Layer], enclose: ((1, 0), (1+0.5, 1)), corner-radius: 5pt, fill: teal.lighten(80%), stroke: 1pt + teal.darken(20%), name: <l1>), edge((1+0.5, 0), (1+0.5, 1), "->", stroke: 1pt + yellow.darken(20%)), edge((1, 0), (1+0.5, 0), "->", stroke: 1pt + yellow.darken(20%)), edge((1, 1), (1, 0), "->", stroke: 1pt + yellow.darken(20%)), edge((1, 1), (1+0.5, 1), "->", stroke: 1pt + yellow.darken(20%)), node((2, 0), width: 10pt, height: 10pt, shape: circle, fill: yellow.lighten(60%), stroke: 1pt + yellow.darken(20%)), node((2+0.5, 0), width: 10pt, height: 10pt, shape: circle, fill: yellow.lighten(60%), stroke: 1pt + yellow.darken(20%)), node((2+0.5, 1), width: 10pt, height: 10pt, shape: circle, fill: yellow.lighten(60%), stroke: 1pt + yellow.darken(20%)), node((2, 1), width: 10pt, height: 10pt, shape: circle, fill: yellow.lighten(60%), stroke: 1pt + yellow.darken(20%)), node([Layer], enclose: ((2, 0), (2+0.5, 1)), corner-radius: 5pt, fill: teal.lighten(80%), stroke: 1pt + teal.darken(20%), name: <l2>), edge((2+0.5, 0), (2+0.5, 1), "->", stroke: 1pt + yellow.darken(20%)), edge((2, 0), (2+0.5, 0), "->", stroke: 1pt + yellow.darken(20%)), edge((2, 1), (2, 0), "->", stroke: 1pt + yellow.darken(20%)), edge((2, 1), (2+0.5, 1), "->", stroke: 1pt + yellow.darken(20%)), edge(<l1>, <l2>, "<->", stroke: 1pt + teal.darken(20%)), node(enclose: ((0.5,-1), (3,2)), corner-radius: 5pt, stroke: 1pt + blue, align(left + top, [Scene]), name:<scene>), node((1.2, 4.8), [`WorldEvent`], corner-radius: 5pt,fill: red.lighten(60%), stroke: 1pt + red.darken(20%), name:<world>), node((1.2, 5.6), [Elm Subscriptions], corner-radius: 5pt,fill: gray.lighten(60%), stroke: 1pt + gray.darken(20%), name:<sub>), node((0.4, 4), [`GlobalData`], corner-radius: 5pt,fill: red.lighten(60%), stroke: 1pt + red.darken(20%), name:<gd>), node((1.2, 4), [`UserEvent`], corner-radius: 5pt,fill: red.lighten(60%), stroke: 1pt + red.darken(20%), name:<user>), edge(<gd>, <scene>, "->"), edge(<user>, <scene>, "->"), edge(<sub>, <world>, "->"), edge(<world>, <user>, "->", label: "Filter"), node((2, 4), [`GlobalData`], corner-radius: 5pt, fill: green.lighten(60%), stroke: 1pt + green.darken(20%), name:<ngd>), node((2.8, 4), [`SceneOutputMsg`], corner-radius: 5pt, fill: green.lighten(60%), stroke: 1pt + green.darken(20%), name:<som>), node((2.8, 6), [`SOMHandler`], fill: yellow.lighten(60%), stroke: 1pt + yellow.darken(20%), name:<somhandler>, shape: hexagon), node((3.8, 5), [`ViewHandler`], fill: yellow.lighten(60%), stroke: 1pt + yellow.darken(20%), name:<viewhandler>, shape: hexagon), node((3.8, 6), [Side Effects], corner-radius: 5pt, fill: gray.lighten(60%), stroke: 1pt + gray.darken(20%), name:<sideeff>), node((3.8, 4), [`Renderable`], corner-radius: 5pt, fill: green.lighten(60%), stroke: 1pt + green.darken(20%), name:<render>), node((2, 5.5), [Core Data], corner-radius: 5pt, fill: orange.lighten(60%), stroke: 1pt + orange.darken(20%), name:<cdata>), edge(<world>, (2, 4.8), <cdata>, "-->"), edge(<somhandler>, (2.6, 5.5), <cdata>, "-->"), edge(<scene>, <ngd>, "->"), edge(<scene>, <som>, "->"), edge(<ngd>, <somhandler>, "->"), edge(<som>, <somhandler>, "->"), edge(<render>, <viewhandler>, "->"), edge(<viewhandler>, <sideeff>, "->"), edge(<somhandler>, <sideeff>, "->"), edge(<scene>, <render>, "->"), node(enclose: ((0,-2),(3.5, 2.5)), align(left + top, [User Code]), stroke: (paint: blue, dash: "dashed")), edge(<somhandler> ,(0.4,6), <gd>, "->"), node(enclose: ((0, 3),(4.8, 6.5)), align(left + top, [Core Code]), stroke: (paint: red, dash: "dashed")), ) ] Messenger provides two parts that users can use. The template _user code_ and the _core library code_. Users write code based on the template code and may use any functions in core library. In user code, users need to design the _logic_ of scenes, layers and components. _Logic_ includes the data structure it uses, the `update` function that updates the data when events occur, `view` function that renders the object. Messenger core will first transform world event into user event, then send that event to the scene with the current `globalData`. `globalData` is the data structure Messenger keeps between scenes and users can read and write. The user code will updates its own data and generate some `SceneOutputMessage`. Messenger core ("core" for short) will handle all that messages and updates `globalData`. Messenger manages a game through three levels of objects (Users can create more levels if they want), listed from parents to children: 1. *Scenes*. The core maintains *one scene* at a time. Example: a single level of the game 2. *Layers*. One scene may have multiple layers. Example: the map of the game, and the character layer 3. *Components*. One layer may have multiple components. The small yellow circles in layers in the diagram are _components_. Example: bullets a character shoots Parent levels can hold children levels, while children levels can send messages to parent levels. Messages can also be sent inside a level between different objects. === General Model There are many similarities among scenes, layers and components. Messenger abstracts those object into one thing called _general model_. Scene is not a general model as it is special, but it is similar to a general model. One of the most important features of Messenger is its _customizability_, i.e. users can define their own datatype for their general models. However, if the layers or components in one same scene are not the same type, how could the core update them? The key is that although the data of general model differs, the _interface_ or actions on those objects are the same. For example, the `update` function is the same for all layers in one scene. As an analogy, an abstract class in OOP may define many _virtual functions_, and the derived class will implement those functions with their own data structure and implementation details. It's possible to convert a derived class instance to a base class instance and only use the base class interface. The type of base class is the same while the derived class may have different types. In Messenger, the "derived class" is a "concrete object" that users need to implement and they can use whatever datatype they want. The "base class" is an "abstract object" that "upper-casts" the concrete object. Therefore, users are able to store different types of objects together in a list by casting them to abstract form. However, unlike in OOP, it is impossible to down-cast an abstract object to a concrete object. Therefore, users should only upper-cast at the last moment. Layers and components are defined as an alias of `AbstractGeneralModel`. It is generated by a `ConcreteGeneralModel`, where users implement their logic. Its definition is this: ```elm type alias ConcreteGeneralModel data env event tar msg ren bdata sommsg = { init : env -> msg -> ( data, bdata ) , update : env -> event -> data -> bdata -> ( ( data, bdata ), List (Msg tar msg sommsg), ( env, Bool ) ) , updaterec : env -> msg -> data -> bdata -> ( ( data, bdata ), List (Msg tar msg sommsg), env ) , view : env -> data -> bdata -> ren , matcher : data -> bdata -> tar -> Bool } ``` `init` is the function to initialize the object. `update` is the function to update the object when an event occur. `updaterec` is the function to update when other object send you a message. `view` is the function to generate `Renderable`. `matcher` is the function to identifies itself. Type `env` is the _environment type_. It contains global data and common data, if any. `event` is the event type, `data` is the user defined datatype. `bdata` is the base data used in components (see @component). `ren` is the rendering type. Messenger CLI will use templates to help you create scenes, layer and components. === Msg Model The `Msg` type of Messenger is defined as below: #grid(columns: (4fr, 5fr), [```elm type Msg othertar msg sommsg = Parent (MsgBase msg sommsg) | Other (othertar, msg) ``` where `MsgBase` is defined as ```elm type MsgBase othermsg sommsg = SOMMsg sommsg | OtherMsg othermsg ``` `SOMMsg`, or _Scene Output Message_, is a message that can directly interact with the core. For example, to play an audio, users can emit a `SOMPlayAudio` message, and the core will handle it. ], [ #set align(right) #diagram( node-stroke: 1pt, edge-stroke: 1pt, node((0, -.2), [Component], corner-radius: 2pt), node((1.6, -.2), [Component], corner-radius: 2pt), node((.8, .8), [Layer], corner-radius: 2pt), edge((0, -.2), (1.8, -.2), `Other`, "->"), edge((0, -.2), (.8, .8), `Parent`, "->", bend: -30deg), edge((1.6, -.2), (.8, .8), `Parent`, "->", bend: 30deg) ) #v(.5pt) #diagram( node-stroke: 1pt, edge-stroke: 1pt, node((0, 0), [Component], corner-radius: 2pt), node((1.3, 0), [Layer], corner-radius: 2pt), node((1.3, .8), [Layer], corner-radius: 2pt), node((2.6, 0), [Scene], corner-radius: 2pt), node((2.6, .8), [Messenger], corner-radius: 2pt), edge((0, 0), (1.3, 0), `SOMMsg`, "->"), edge((1.3, 0), (2.6, 0), `SOMMsg`, "->"), edge((2.6, 0), (2.6, .8), `SOMMsg`, "->"), edge((0, 0), (1.3, .8), `OtherMsg`, "->", bend: -10deg) ) ] ) `SOMMsg` is passed to the core from Component $->$ Layer $->$ Scene. It's possible to block `SOMMsg` from a higher level. See @sommsg to learn more about `SOMMsg`s. Users may need to handle `Parent` messages from components in a layer. Messenger provides a handy function `handleComponentMsgs` which is defined in `Messenger.Layer.Layer`, to help users handle those messages. Users need to provide a `MsgBase` handler, for example: ```elm handleComponentMsg : Handler Data SceneCommonData UserData Target LayerMsg SceneMsg ComponentMsg handleComponentMsg env compmsg data = case compmsg of SOMMsg som -> ( data, [ Parent <| SOMMsg som ], env ) OtherMsg _ -> ( data, [], env ) _ -> ( data, [], env ) ``` Then users can combine it with `updateComponents` to define the `update` function in layers (provided in the Messenger template): ```elm update : LayerUpdate SceneCommonData UserData LayerTarget LayerMsg SceneMsg Data update env evt data = let ( comps1, msgs1, ( env1, block1 ) ) = updateComponents env evt data.components ( data1, msgs2, env2 ) = handleComponentMsgs env1 msgs1 { data | components = comps1 } [] handleComponentMsg in ( data1, msgs2, ( env2, block1 ) ) ``` === Example <example1> A, B are two layers (or components) which are in the same scene (or layer) C. The logic of these objects are as follows: - If A receives an integer $0 <= x <= 10$, then A will send $3x$ and $10-3x$ to B, and send $x$ to C. - If B receives an integer $x$, then B will send $x-1$ to A. Now at some time B sends $2$ to A, what will C finally receive? Answer: 2, 5, 3, 8, 0, 9.
https://github.com/wjakethompson/wjt-quarto-ext
https://raw.githubusercontent.com/wjakethompson/wjt-quarto-ext/main/wjt-letter/README.md
markdown
Creative Commons Zero v1.0 Universal
# WJT Letter Format Based on the KU letterhead format for Accessible Teaching, Learning, and Assessment Systems. **NOTE**: This format requires the pre-release version of Quarto v1.4, which you can download here: <https://quarto.org/docs/download/prerelease>. ## Installing ```bash quarto use template wjakethompson/wjt-quarto-ext/wjt-letter ``` This will install the format extension and create an example qmd file that you can use as a starting place for your document. ## Using The example qmd demonstrates the document options supported by the wjt-letter format (subject, recipient, logo, etc.). For example, your document options might look something like this: ```yaml --- subject: "Consultation Report Title" shorttitle: "Short Title" reporttype: "Report Type" name: | <NAME>, Ph.D. logo: "consulting-logo.png" sender: | 12261 S Crest Drive Olathe, KS 66061 \ <EMAIL> \ (785) 643-9244 recipient: | Mr. <NAME> \ Acme Corp. \ 123 Glennwood Ave \ Quarto Creek, VA 22438 \ sent: "September 4, 2016" format: wjt-letter-typst: default --- ``` WJT letter documents are rendered as follows: ![](wjt-letter.png)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/gradient-radial_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #square( size: 100pt, fill: gradient.radial(..color.map.rainbow, space: color.hsl), )
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/并行程序设计/上篇:并行程序设计导论/单元Ⅰ:并行程序设计基础.typ
typst
#import "../../../lib.typ": * == 并行程序设计基础 === 并行计算机系统与结构模型 === PC机群的搭建 === 并行程序设计简介 === 并行编译简介 ==== 数据依赖关系 #showybox(title: [Def1])[ / $S #sym.delta^f T$ :若x #sym.in OUT(S)且 x#sym.in IN(T)且T使用S计算出的x的值,T流依赖于S; / $S #sym.delta^a T$ :若x #sym.in IN(S)且 x#sym.in OUT(T)但S使用x值先于T对x的定值;T反依赖于S; / $S #sym.delta^o T$ :若x #sym.in OUT(S)且 x#sym.in OUT(T)但S较之T先对x进行定值;T输出依赖于S; ] ==== 依赖距离和依赖向量 令 $alpha = (alpha_1, alpha_2, dots, \)$ 和 $beta = (beta_1, beta_2, dots, beta_n)$ 是 n 层循环内的 n 个整数下标向量,假定 $alpha$ 和 $beta$ 存在数据相关性,则依赖距离向量(Dependent Distance Vector)$D = (D_1, D_2, dots, D_n)$ 定义为 $beta - alpha$; 而依赖方向向量(Dependent Direction Vector)$d = (d_1, d_2, dots, d_n)$ 定义为: $ d_i = cases( <(1) space space space space space alpha_i < beta_i , =(0) space space space space space alpha_i = beta_i , >(-1) space space alpha_i > beta_i ) $ 例如,有如下的三层循环嵌套: ```plaintext for i = l₁ to u₁ do for j = l₂ to u₂ do for k = l₃ to u₃ do A(i + 1, j, k - 1) = A(i, j, k) + C ``` 则数组 $A$ 的三维迭代之间的相关距离向量: $D = (i + 1 - i, j - j, k - 1 - k) = (1, 0, -1)$ 和相关方向向量: $= (<, =, >)$ ==== 语句依赖图和迭代依赖图
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/027%20-%20Conspiracy%3A%20Take%20the%20Crown/005_Bloody%20Instructions.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Bloody Instructions", set_name: "Conspiracy: Take the Crown", story_date: datetime(day: 17, month: 08, year: 2016), author: "<NAME> & <NAME>", doc ) #emph[The city of Paliano is quickly descending into political chaos. Meanwhile, the goblins Grenzo and Daretti have plans to cause chaos of a different kind.] #figure(image("005_Bloody Instructions/02.png", height: 40%), caption: [], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) It was a sweltering night, but the fireworks on the streets kept Paliano aglow. A lone sentry stood at his post. In the distance, the Festival of Our Sovereign Lady’s Grace raged. Obscene profusions of color and light danced their way through the plaza, loudly declaring the populace’s love for its new sovereign. Drink was flowing. This morning they whispered about Marchesa’s legitimacy to the throne, but tonight they sang her praises. The sentry, however, had neither song nor drink. He considered abandoning his post, but no, he remained steadfast, guarding the home of an old buffoon of a man from the fallen Academy. Royal decree had recently dissolved the institution, long considered the seat of knowledge and study. Stripped of his professional stature, the academic was now simply a citizen. A very old and very paranoid citizen. Night after night he stood here. And night after night the academic told him to remain alert. And it annoyed the guard. He knew the academic had been instrumental in bringing cogwork to Paliano, back before it was outlawed. But who would care about some forgotten relic of a dead institution? #figure(image("005_Bloody Instructions/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) In an alleyway across from his post, the sentry spotted a toothy smile. A goblin, small, probably just a child, watched him. The guard waved. "Go home, kid." The goblin slunk back into the shadows. Then suddenly something came flying at the guard from the alleyway. Small and round. It arced through the air toward him. An overripe, mealy tomato splattered across his carefully polished armor and spilled down the plate like blood. "Kid, get out of here!" From the shadows of an adjacent alleyway, another missile came hurtling toward him. An apple this time, with an impact to his helmet that set his ears ringing before it bounced to the ground. He spun in the direction it came from. A volley of vegetables—heads of lettuce, bundles of carrots—sailed toward him. It was like someone had catapulted a fruit cart. From the alley, he could see a dozen squinting eyes on green faces. They chortled and laughed. The sound seemed to reverberate all around him. "You filthy goblin scum! What’s your game?" Then from behind him, he heard something else. He spun around again to see a glass bottle sailing through the night air in his direction. It landed at his feet with a burst of liquid that erupted instantly in flames. He stumbled backward, flames burning on the street. He looked around and spotted the mob. They smiled back at him. Some held torches, some weapons, one had a cart full of rotting vegetables. Weapon raised, he raced for them. The mob turned and scattered, tripping over themselves and abandoning their cart to get away from his wrath, laughing all the while. #figure(image("005_Bloody Instructions/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Waiting in the shadows nearby, Daretti shifted uncomfortably in his chair. He watched after the fleeing guard and the goblin mob. "Buffoonery," he said. "Amateurs." The street was empty again, but the distraction hardly seemed like a certainty. From beside him, Grenzo hobbled across the cobblestones, a hunched but hulking figure of a goblin. "They’re passionate," said Grenzo, smiling, "like wildfire. You just need to get them started in the right place." He reached the unguarded door, his huge frame hoisted by his staff. Three of his tiny lackeys hurried to catch up with him. Daretti gripped the arms of his chair. This was not the delicately orchestrated night of revenge he had planned. Grenzo looked at the door and shook the knob. It gave a satisfying rattle of heavy metal tumblers and latches but refused to give. He grinned. "Will you at least maintain a modicum of quiet?" Daretti hissed. "Bah! I will have you know that I have been breaking down doors since before you had hair on your cheeks." One sharp thump from his staff and the villa door crashed to the ground. "If Marchesa wants to hang up her poisons and wear a new hat, that’s her business, but if she wants to take away my keys and lock me out of my dungeons, then we’re coming to the surface and we’ll make our own doors." The goblins answered with a chorus of shrieking cheers. Daretti scowled and looked over his shoulder. "You worry too much. Embrace not knowing. Besides," said Grenzo, pointing up at the fireworks exploding overhead, "who could hear us over this squall?" Grenzo waved and his lackeys rushed in. "Go forth and claim your bounty, my beautiful cubs!" He stepped inside, alive in the darkness, soaking in the treasures of the villa. The crowd of goblins flooded into the foyer, covering the pristine Trestian blue marble columns with kerosene fingerprints. One grabbed the hide of a rare albino feline from its artful arrangement over a chair and repurposed it into a handsome cape. From vaulted ceilings above them, framed portraits of aristocratic forebears sneered down at the mob. Daretti entered more cautiously, maneuvering his chair around the fallen door. "Perhaps, old man, perhaps, but also consider: who could sleep through all this?" #figure(image("005_Bloody Instructions/08.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Upstairs, <NAME> tossed back and forth in his bed. He could hear the pomp and grandeur outside through latched windows. Through the curtains, flashes of garish reds, blues, purples, and greens from the fireworks illuminated his room. The spectacles he’d left on his nightstand vibrated to the drumbeat of drunken parade heralds. It wasn’t a sound so unfamiliar to him once. Once. Once those heralds had trumpeted his approach. Once he’d commanded crowds of his own. Back in his Academy days. He’d been their darling. And they’d been his world. A world he moved through with ease. Family members opened doors for him and he played the system like an artist. He was never a genius, he knew that, but one invention, the universal cog (who could even say whether it was his own?), a whole lot of hand shaking, a few books, a few lectures, and he was set for life. Let the Muzzios of the world toil in their laboratories. Until it all came crashing down… #figure(image("005_Bloody Instructions/10.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Three city guards lay unconscious on the floor, pinned under a toppled bookshelf. Broken vases and mangled paintings lay all around, a sign of their fray with the goblins. As his underlings went about the task of tying up the guards, Grenzo pulled out his loot sack and returned to the wall of bookshelves. "I thought you told me this guy was some kind of big deal. But this is all junk. Our dank sewer is more luxurious than this festering heap." With a sweep of his staff, books tumbled to the floor. He tapped at the wall behind. Nothing. "I told you he was considered a forebear to the field of cogwork." Daretti lifted a fallen volume. He cringed. #emph[Principles of Cogwork Autonomy: A Comprehensive Treatise on Constructing Mechanical Life] . Daretti thumbed through the pages, but he knew it all only too well. "But your observation is accurate. The professor was in all ways a fraud." Grenzo moved onto an exquisitely carved rosewood desk, inlaid with opaline stones. Every drawer was carefully locked. With a heave, he brought his staff down onto the center. Splinters of rosewood flew off and locks scattered across the floor. Inside, he found nothing but stacks and stacks of papers. Daretti picked up one and read. It was a personal note from a supposed academic luminary. Full of effusive praise for Fimarell’s "genius." Grenzo grabbed a handful and dropped them into his sack. "What is your goal here, old man?" asked Daretti. "This is nothing but garbage." "No," said Grenzo, hoisting his bag and packing it underneath the hump of his hunchback. "This is fuel." Daretti made a face. In the volume was a folded piece of paper. He opened it. "Ha! Old man, do you know what this is? It’s the blueprints for a cogwork sentry. One of the first of its kind, intended for municipal security." He laid out the sheet on the desk. "Look at these appendages, such a mess. The power requirements alone must have cost a small fortune. Garbage. Can you imagine the team of technicians it would have required to—" "Talk! Talk! Talk! It’s all garbage! Every word in here. You gave your life to the academy, you dedicated your existence to that braying pack of blowhards. You begged for scraps from them. You dedicated yourself to that apprentice Muzzio and what did he do for you? What did they all do to you? Well, the academy is dead and Muzzio is exiled. And do you know why? Because all it takes is a few open locks, a few great inventions crawling through the streets, and everyone throws away all reason." Grenzo leaned in close. "All your precious cogwork is broken, scattered, and outlawed. Everything you dedicated yourself to is dead. And we, we are the hyenas picking at its bones. Now stop acting like a scientist and start acting like a hyena." Daretti paused. The academy seal at the bottom of the plans glittered gold. Daretti handed it back to Grenzo. Fuel. He could feel it ignite inside him. Daretti nodded. "Burn it. Burn it all. Burn the ashes. Burn the guilty. Burn the righteous." Grenzo smiled. Daretti eyed something among the papers on the desk. His eyes widened. He withdrew some yellowed parchment. His hands shook. "This is it, old man. This is it!" He swallowed and spoke carefully. "I believe it is time for us hyenas to stop congregating around this particular cadaver and seek a fresher one." His chair clanked into motion and carried him toward the stairs. Daretti moved with purpose now. Grenzo’s smile broadened. He followed up the marble staircase. At the top, Daretti came to a sudden stop. He dropped the papers carefully in his lap and started searching himself, turning out pockets. "I’ve forgotten it." He turned to Grenzo and gave a pleading look. "I must have misplaced it. We need to turn around. I could not possibly proceed without my speech." "What? Suddenly, you can’t talk?" "No, and I am as startled as you." "Look, smart guy, you know this." "Grenzo, I don’t. My mind is a blank. All that preparation for naught. We’ll reseal the door, we’ll drag the guards out, return the papers. I’ll review and return tomorrow night." "Cub, you can you can relock a door, but you can’t so easily put it back on its hinges. Now say it with me, whether or not I agree: ‘To be honest is a constant…'" "Yes, yes. That’s it. ‘To be honest is a constant, thankless churn." "One cannot hide…" "One cannot hide behind honesty—" "Goblins!" Fimarell stood in the hallway in his dressing gown, bedroom door open. Grenzo and Daretti exchanged glances. "Thieves!" Fimarell yelled and slammed the door. They chased after him. Daretti rattled the door. Locked. He looked to Grenzo. Another thump of his staff and the door collapsed. The elder human scientist was at the window, calling out. "Someone help me!" He turned toward them, shaking. "Filthy goblin vermin from the street! This is a respectable neighborhood and I am a respectable man!" Daretti stared blankly. Grenzo tapped his chair with the staff. Daretti shook himself and began addressing Fimarell, "To be honest is a constant, thankless churn. One cannot hide behind honesty. Falsehood and deception is the chiefest sin for the scientist. And it is the burden of the honest to bring lies to bear and carry the falsifier to justice." Daretti’s chair extended its mechanical legs, hoisting itself off from its wheels and raising him up to nearly the height of the ceiling. In the flickering lights from the street, Daretti was like some vast spider descending upon its prey. #figure(image("005_Bloody Instructions/12.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) The whimpering academic shrunk to the ground. "You may not remember my name, nor my face, but I suspect you remember my robes and my hat. I once wore my station with pride as an agent of the highest order—knowledge, and engineering, and truth." His tone lowered. "But you would know nothing of such virtues." The chair lurched the goblin forward, bringing their faces close enough that Daretti could see the beads of sweat running down the wrinkles of the old man’s face. "The academy knows your name very well. Your name is written oh so many times." He held up the papers. "Like this one." Fimarell went white. "Do you recognize it? Do you recognize the handwriting? You criticized it. You criticized all my words, then took them as your own. You built your career on the back of my words. How dare you call us thieves, you sham!" Daretti’s breathing was heavy. His eyes narrowed. He balled up the top page of the manuscript and shoved it into Fimarell’s mouth. From behind them, Grenzo called out in an exasperated tone, "Stop drawing this out, you green fool! This is Paliano—murder is how we get things done. Just kill him and let’s get on with it." Daretti and Fimarell eyed each other awkwardly. Daretti called back, "Will you please give me my moment?" Grenzo raised his hands. "Fine! But I’ll be starting fires until you’re done talking." Fimarell’s eyes shifted between them. Daretti tried to regain his menacing composure. "I…" He stammered. "I…the career I was supposed…where was I?" Fimarell spit out the page in his mouth. "The manuscript I stole from you…" he said cautiously. "Oh yes," said Daretti. "Well…it’s you who is the…" He paused. "Very well. Let’s get on with it." Daretti reached under Fimarell’s legs and heaved him up and through the window. He tumbled down two stories and landed with a heavy thump on the street below. Daretti leaned forward and held himself by the windowsill to see the limp body. The ground was smeared red beneath it. It was done. So much time had passed since he was a young man desperate to share his words with the academy. He’d long ruminated on this moment, yet it was over in a flash. "Not bad. Was that as cathartic as you hoped?" Grenzo was beside him again. He held a large ornate pot under one arm and a burning torch in the other. "I believe it might have been. Next time…let me finish." Grenzo held up the pot. It was stuffed full of refuse. Daretti picked up the pages of his manuscript and dropped them in. Grenzo dropped the torch after them. The pot ignited with a crackle. "One last step." Grenzo hoisted the pot to the window. Burning garbage rained down onto the Paliano street. Somewhere in the city, the fireworks had begun again. #figure(image("005_Bloody Instructions/14.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Downstairs, Grenzo’s minions had cleared out anything of value and were now smashing apart furniture. They swept it into the corners with heaps of paper and books. One poured oil over the pile. Daretti and Grenzo descended the staircase. "Well, good work, my protégé. You’ll make a fine goblin yet." Daretti recoiled. "Your protégé? No, no, no. Let’s be clear here. You are my enforcer." "Bah! You wish! More like you’re my crony." "Crony?!" "Boss," interrupted one of the goblin lackeys, holding a torch aloft. "Er…bosses. Are you ready?" "We’ll discuss this later, Grenzo," said Daretti. "Yes, burn it, please. Burn it all down." The flames caught quickly and the fire crackled, crawling up the walls. Daretti shook his head. "Let’s head home." He sighed. "Back underground." "Who’s next on your list?" "His name’s Alendis. Told me the Academy wasn’t ready for a goblin. Told me I was bad for their reputation. Sounds like the oily bastard joined the Custodi." "Well, if that means he’s in league with Marchesa, then he’s on my list too." Grenzo stepped out of the house and back into the garden. Daretti followed. "Okay, you old crank. How about right-hand man?" The air crackled. Fire burned behind them. Already goblins were scattering in every direction. "The queen used to run in shadows," said Grenzo, looking up at the smoky sky. "She knew the game. She knew the sweet twist of a knife. Now she’s got her comfy chair and locks every door at night. At least she knows how to throw a party." "I suppose everyone leaves the shadows eventually." "We should crash a party. We should crash all their parties." Overhead, pyrotechnics lit the sky in reds, blues, and greens. Daretti fanned himself with one hand. The night remained swelteringly hot.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/enum-05.typ
typst
Other
// Edge cases. + Empty \ +Nope \ a + 0.
https://github.com/tingerrr/hydra
https://raw.githubusercontent.com/tingerrr/hydra/main/tests/get-rules/text-dir/test.typ
typst
MIT License
// Synopsis: // - a change in styles mid page is not observed in the footer // - this assures that with an anchor, the resolved styles will still be correct if hydra is used // in the footer // - text dir is the only style which could change between an anchor and a hdyra call // - given an in text use of hydra, this would cause unexpected behavior #import "/src/lib.typ": core #set page( paper: "a7", header: context core.get-text-dir(), footer: context core.get-text-dir(), ) #lorem(1) #set text(dir: rtl) #context core.get-text-dir() #lorem(1)
https://github.com/simon-epfl/notes-ba3-simon
https://raw.githubusercontent.com/simon-epfl/notes-ba3-simon/main/probastats/notes.typ
typst
== Combinatorics We want to choose `k` elements among `n` elements. #table( columns: (auto, auto, auto), table.header( [], [*Repetition not allowed*], [*Repetition allowed*], ), [*Order does not matter*], [$ n!/((n-k)!k!) $ (`n` choices, then `n-1` choices, etc. and we stop at `n-k`, we also remove `n!` because order does not matter and `n!` is the number of permutations)], [ $ binom(n - 1 + r, n - 1) $ It's stars and bars method. We want `r` stars + `n` stars for each box. Then, we transform `n-1` of these stars into bars to separate the `r` stars into boxes.], [*Order matters*], [$ n! $ (`n` choices, then `n-1` choices, etc.)], [$ n^k $ Cartesian product.] ) == Probabilities === Solving a probability problem - list possible outcomes, define the probability space - sometimes we keep a general $Omega$ and different $cal(F)$ depending on the point of view (colorblind/not colorblind, etc.) === Terminology - $Omega$ is the *sample space*, containing all possible outcomes $omega$. - $cal(F)$ is an *event space* (there are multiple event spaces!). It is a set of the subsets of $Omega$. The powerset of $Omega$ includes all $cal(F)$. $|cal(F)| = 2^(|Omega|)$ only if $Omega$ is finite. $cal(F)$ is also called a sigma-algebra. ==== Example for a fair die: - *Sample space:* ${1,2,3,4,5,6}$ - *Events*: ${1}, {2}, {3}, {4}, {5}, {6}, {1, 2}, {1, 3}, ..., {1, 2, 3, 4, 5, 6}$ note that this is only for one throw! ${a,b}$ is read "getting $a$ or getting $b$". - *Event space:* all events === Axioms $ P(A union B) = P(A) + P(B) - P(A sect B)$ Generalization of the OR between events: $ P(A_1) + P(A_2) + P(A_3) - P(A_1 sect A_2) - P(A_2 sect A_3) - P(A_1 sect A_3) + P(A_1 sect A_2 sect A_3) $ $ PP(union_(i = 1)^n A_i) = sum_(r = 1)^n (-1)^(r+1) sum_(1 <= i_1 < i_2 < ... < i_r < n) (A_i_1 sect ... sect A_i_r) $ (les $i_k$ doivent donc être différents) Conditional probabilities: $ P(A|B) = P(A sect B)/P(B) $ === Law of total probability Let ${B_i}_(i = 1)^infinity$ be pairwise disjoint events, and let $A subset union_(i = 1)^(infinity) B_i$ then: $ P(A) = sum_(i = 1)^(infinity) P(A sect B_i) = sum_(i = 1)^(infinity) PP(A|B_i)PP(B_i) $ === Bayes' Theorem: $ PP(A|B) = (PP(B|A)PP(A))/(PP(B)) $ but we can replace $P(B)$ by what we know, low of total probability: $ PP(A|B) = (PP(B|A)PP(A))/PP(B) = (PP(B|A)PP(A))/(PP(B|A)PP(A) + PP(B|A^c)PP(A^c)) $ === Derangement $ !n = sum_(i = 0)^n ((-1)^i)/(i!), n >= 0 $ Si on veut un élément non dérangé parmis $n$: $n dot 1/n dot !(n-1)$ Si on en veut $r$: (comment on choisit les $r$ bien rangés $dot$ le fait qu'ils soient bien rangés et que les restants soient dérangés) $ binom(n, r) dot (n-r)!/n! dot !(n - r) $ === Independence If $A$ and $B$ are independent then $PP(A|B) = PP(A)$. They are independent iff $PP(A union B) = PP(A)PP(B)$. If two events are disjoint they can not be independent unless their respective probabilities are 0. ==== Pairwise Independence If you take any two events, they are independent. === Random variable (notation) We will use $Y$ to denote a random variable. \ We will use $y$ to denote a specific value that $Y$ can take. $Y : Omega arrow RR$ is a function. $ D_Y = { x in RR : exists omega in Omega " s.t. " X(omega) = y } $ $D_Y$ is called the support of X. If $D_Y$ is countable, then $Y$ is a discrete random variable. $PP(Y = y) equiv p_Y (y)$ $p_Y$ is called the probability mass function. A probability distribution is a table or a graph that provides $p(y) forall y$. For everything to hold, $sum_y p(y) = 1$. === Expected Value $ E(Y) = sum_y y p(y) $ === Binomial Random Variable A binomial random variable $X$ has PMF: $ f(x) = binom(n, x)p^x(1-p)^(n - x), x = 0,1,...,n, n in NN, 0 <= p <= 1 $ We write $ X tilde B(n,p)$ and call $n$ the denomiator and $p$ probability of success. #image("distrib.png") == Geometric distribution $ f_X(x) = p(1-p)^(x-1) $ 1 success and $x-1$ failures. the probability to have exactly one success Memorylessness : $ P(X > n + m | X > m) = P(X > n) $ Thanks to independence. == Negative binomial distribution #image("binneg.png") k-1 parce que le dernier doit être un succès. == Hypergeometric distribution #image("hypgeo.png") == Discrete uniform distribution #image("discreteunif.png") Chaque évènement a la même probabilité de se produire. == Poisson random variable #image("poisson.png") Le nombre d'événements qui se produisent dans un intervalle de temps ou d'espace fixe, lorsque ces événements se produisent avec une certaine moyenne (taux d'évènements $lambda$) et de manière indépendante. Par exemple le nombre d'appels téléphoniques reçus par un centre d'appel en une heure. == Cumulative Distribution Function #image("cdf.png") La probabilité que $X$ prenne une valeur inférieure ou égale à $x$. == Moments $ E(X^r) = sum_x (x_i)^r f_X (x_i) $ == Variance On pourrait étudier la différence entre $X$ et la moyenne pour voir à quel point X "varie" (une fonction constante aurait 0) : $E|X - E(X)|$. Cependant on met un carré pour éviter les problèmes avec l'utilisation de la valeur absolue. $ "var"(X) = E(X^2) - E(X)^2 $ == Expected value $ E(X) = E(X|B)P(B) + E(X|B^c)P(B^c) $ == Probability density function === Uniformly distributed variable $ f(x) = 1/(b - a) $ === Exponential random variable $ f(x) = lambda e^-(lambda x), forall x > 0, 0 "otherwise" $
https://github.com/duskmoon314/THU_AMA
https://raw.githubusercontent.com/duskmoon314/THU_AMA/main/docs/ch1/0-序论与背景知识.typ
typst
Creative Commons Attribution 4.0 International
#import "/book.typ": book-page, cross-link #show: book-page.with(title: "序论与背景知识") = 序论与背景知识 - #cross-link("/docs/ch1/1-背景.typ")[背景] - #cross-link("/docs/ch1/2-发展史.typ")[发展史] - #cross-link("/docs/ch1/3-例题与应用.typ")[例题与应用]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/github-pages/docs/readme.typ
typst
Apache License 2.0
// let style_color = rgb("#ffffff") // background: rect(fill: rgb("#343541"), height: 100%, width: 100%), #include "../../docs/cookery/introduction.typ" + #link("https://myriad-dreamin.github.io/typst.ts/cookery/introduction.html")[Full Documentation]
https://github.com/Myriad-Dreamin/shiroa
https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/github-pages/docs/guide/faq.typ
typst
Apache License 2.0
#import "/github-pages/docs/book.typ": book-page #show: book-page.with(title: "Frequently Asked Questions") We are collecting questions and answers about the `shiroa` project here. Feel free to ask questions in #link("https://github.com/Myriad-Dreamin/shiroa/issues")[Github Issues].
https://github.com/ern1/typiskt
https://raw.githubusercontent.com/ern1/typiskt/main/README.md
markdown
# Typst resume template <img src="https://raw.githubusercontent.com/ern1/resume/main/output/resume.svg?token=<KEY>" width="60%"/>
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/patterns/weeks/week13.typ
typst
#import "../../utils.typ": * #subsubsection([Parameterize from Above]) #set text(size: 14pt) Problem | How can I provide individual services that need to run independently of each other with global data without using singletons?\ Solution | Parameterize from above, aka first define global services and put them into the application, then register "horizontal" services one by one, see picture. Participants : - #set text(size: 11pt) // images The idea is that you have certain services, that need to run at each layer, while other services need to run on top of each other. This means you can't just inject the horizontally layered services into the application. #align( center, [#image("../../Screenshots/2023_12_28_04_33_56.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_12_28_04_27_41.png", width: 100%)], ) ```java public final class Bootstrapper { public static void main(string[] args) { // PfA applied // instantiate vertical layer contexts first SecurityContext securityContext = new SecurityContextImpl(); ConfigurationSettings configuration = new ConfigurationSettingsImpl(args); // encapsulate variables into an application context var applicationContext = new ApplicationContextImpl( securityContext, configuration); // instantiate horizontal layer contexts from bottom to top DataContext dlContext = new DataContextImpl(applicationContext); BusinessContext blContext = new BusinessContextImpl(applicationContext, dlContext); UIContext uiContext = new UIContextImpl(applicationContext, blContext); // show initial UI dialog uiContext.show(); } } ``` #columns( 2, [ #text(green)[Benefits] - no global variables - implementations of parametrized functionalities are exchangeable - additional implementation possible -> testing etc. - enforces separation of concerns at architecture level - view, logic, data are separated #colbreak() #text(red)[Liabilities] - complexity - Object instances aren’t accessible from everywhere; access to application context needed - Programmers must understand and accept the concept - contexts must be passed through the entire application stack - fragile bootstrapper: application must be wired completely at startup ], ) #subsubsection([Dependency Injection]) #set text(size: 14pt) Problem | The bootstrapper from the Parameterize from above pattern is not flexible enough, hence I want a solution with which I can override existing services.\ Solution | Inject a framework container with dependencies, which can then be used, exchanged, etc with framework components. Participants | - central container, which acts as a service registry - container searches for services via *interfaces* provided by user - code annotations: users apply these to components - declare the interface implementations - reference required interfaces - clients do not reference container directly #set text(size: 11pt) // images #align( center, [#image("../../Screenshots/2023_12_28_04_41_52.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_12_28_04_42_33.png", width: 100%)], ) #columns( 2, [ #text(green)[Benefits] - reduces coupling between client and implementation - no need to reference container - The contracts between the classes are based on interfaces - Classes relate to each other not directly, but mediated by their interfaces - Supports the open/closed principle - Allows flexible replacement of an implementation - Implementations can be marked as “single” (only one in the system) or “transient” (new instance per injection) #colbreak() #text(red)[Liabilities] - black magic -> how does this work? - code annotations... - debugging can be hard - recursive dependencies are hard to find and may prevent the system from startup - relies on reflection and can result in a performance hit ], ) #subsubsection([Flyweight]) #set text(size: 14pt) Problem | Many objects use the same constant data, how can we avoid copying this data, with objects that might also have non-shared data?\ Solution | Create global access to constant data for all objects, hence avoiding copying this data.\ Participants : - extrinsic data: unshared data - intrinsic data: shared data - *immutable!* #set text(size: 11pt) // images #align( center, [#image("../../Screenshots/2023_12_28_04_52_21.png", width: 80%)], ) #align( center, [#image("../../Screenshots/2023_12_28_04_52_45.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_12_28_04_52_56.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_12_28_04_53_13.png", width: 100%)], ) #text( red, )[Note, the UnsharedConcreteFlyweight is essentially it's own object, aka it doesn't get included anywhere.] ```java // FlyweightFactory package ch.ost.pf.flyweight; import java.util.Hashtable; public class FlyweightFactory { private final Hashtable<Character, FlyweightChar> chars = new Hashtable<>(); public FlyweightChar getFlyweight(char key) { if (!chars.containsKey(key)) { chars.put(key, createFlyweight(key)); } return chars.get(key); } protected FlyweightChar createFlyweight(char key) { return new ConcreteFlyweightChar(key); } } // FlyweightChar package ch.ost.pf.flyweight; public interface FlyweightChar { int getCharCode(); } // ConcreteFlyweightChar package ch.ost.pf.flyweight; public class ConcreteFlyweightChar implements FlyweightChar { private final char character; public int getCharCode() { return character; } ConcreteFlyweightChar(char character) { this.character = character; } } ``` #columns( 2, [ #text(green)[Benefits] - Reduction of the total number of instances (space savings). Savings depend on several factors: - the reduction in the total number of instances comes from sharing - the amount of intrinsic state per object - whether extrinsic state is computed (=computation time) or stored (= space cost) #colbreak() #text(red)[Liabilities] - Can’t rely on object identity; stored elements contain Value characteristics - May introduce run-time costs associated finding Flyweights, and/or computing extrinsic state ], ) Notes:\ - often combined with composite - Hierarchical structure as a graph with shared leaf nodes - Leaf nodes cannot store a pointer to their parent - Parent pointer is passed to the flyweight as part of its extrinsic state - Impacts on how the objects in the hierarchy communicate with each other - handles with fine-grained elements, which contain immutable value characteristics - fine-grained objects are stored globally, lazy initialized - Behavior similar to a multi-Singleton; a single class stores multiple shared instances - Objects are created in a Class Factory (Simple Factory / Static Factory Method)-like manner - Flyweight contains a pool of shared objects - Pooling pattern by POSA3 - #text( red, )[Flyweight is categorized as a structural pattern, but it is kinda everything, especially creational] #align( center, [#image("../../Screenshots/2023_12_28_04_57_18.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_12_28_05_06_16.png", width: 100%)], ) #subsubsection([Pooling]) #set text(size: 14pt) Problem | I require fast/efficient access to resources that need to be available to multiple objects.\ Solution | Create a pool of resources which can be acquired or released by clients.\ #set text(size: 11pt) // images #align( center, [#image("../../Screenshots/2023_12_28_05_07_07.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_12_28_05_07_22.png", width: 100%)], ) Notes:\ - Define the maximum number of resources that are maintained by the resource pool - Typically set at initialization time of the pool - decide between lazy or eager acquisition of resources - Determine resource recycling/eviction semantics - E.g. clean up stack after thread execution has completed - Use appropriate allocation and destruction patterns - *Resources are not named -> unlike caching, acquire will get you a random resource!* #columns( 2, [ #text(green)[Benefits] - Improves the performance of an application - Helps reduce the time spent in costly release and re-acquisition - Lookup and release of previously-acquired resources is predictable - Simplified release and acquisition of resources - New resources can be created dynamically if demand exceeds the available resources #colbreak() #text(red)[Liabilities] - The management of resources results in a certain overhead - Depending on the environment and resource type, resources must be released back to the pool - Acquisition requests must be synchronized to avoid race conditions ], )
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/ISI/docs/TE/TE1.typ
typst
// In the main.typ #import "/_settings/typst/template-te.typ": * #show: resume.with( "Résumé ISI", "<NAME>", cols: 3 ) = Type d’attaquants - Script kiddy: Jouent avec des outils - Pirates défi: Attirés par le defi - Pirates vengeurs: Comme Sony (Par vengeance) - Pirates par conviction: A but « politique » - Pirates étatiques: Cyber-guerre / Cyber-espionnage == Motivations des attaquants S’amuser, Curiosité, Prise de contrôle (ego), Acquérir des connaissances techniques, Idéologiques (politique), Ressources gratuites, Argent (escroqueries), Terrorisme, espionnage == Intentions des attaquants - Constructives: Test pénétration (pentest) - Neutres: zone grise - Destructives: Pirate Malveillances = Principe CIA Préservation de la confidentialité, intégrité et disponibilité de l'information. === Condifentialité (Confidentiality) - s'assurer que l'information est accessible seulement à ceux qui sont autorisés à y avoir accès === Intégrité (Integrity) - protéger l'exactitude et la complétude de l'information et des méthodes de traitement === Disponibilité (Availability) s'assurer que les utilisateurs autorisés ont accès à l'information et aux ressources associées au moment et au lieu exigés = SSI (Sécurité du système d'information) == Cycle de vie - une prévention (via une protection) contre les incidents de sécurité - la détection (via une surveillance) de ces dernières - la réaction (analyse, confinement) - la récupération (reprise, sanctions éventuelles), puis analyse «post mortem» suite aux dommages survenus = 5 couches de sécurité Souvent décrite comme une sécurité sous forme d'onion car composé de plusieurs couche. 1. Physique : - sécurité physique 2. Réseau : - architecture et éléments réseau, adressage IP. 3. Protocoles : - Protocoles de communication, middleware. 4. Hosts : - systèmes d'exploitation et applications hosts. 5. Applications : - langages de programmation, applications spécifiques/dédiées, données spécifiques. = Contrôle d’accès (AAA) - *Authentication* - S’assurer que la personne est bien celle qu’elle prétend être - Déterminer son identité et éventuellement sonrôle • *Authorization* - Détermine en fonction de l’identité (ou rôle), que cela soit une personne ou système, si l’accès (ou le traitement) est autorisé - *Accounting/Auditing* - S’assurer qu’il soit possible de suivre les accès/traitement qui ont été effectués - Logging = 5 principes fondamentaux 1. La sécurité globale est aussi forte que le maillon le plus faible 2. La sécurité parfaite n’existe pas 3. La sécurité est un processus, pas un produit 4. La sécurité est inversement proportionnelle à la complexité 5. Participation des utilisateurs = Types de menaces - Accidentelles: mauvaises manips, suppression - Environnementales: naturelle ou industrielle - Délibérées: origine criminelle = Vulnérabilités - Matériel: disque saturés / morts - Logiciel: oubli / incompétence (WEF) - Réseau: trafic non protégé - Personnel: manque de formation - Site (physique): alim instable - Organisation: enregistrement d'utilisateurs = Attack Kill Chain Malicious and ethical hackers use the same steps + Reconnaissance + Exploit + Post Exploit Etapes: + Collecte d'informations + Scanning + Enumérations + Intrusions + Escalade de privilèges + Pillage + Nettoyage des traces + Backdoors, rootkits = Cassage de mots de passe Hachage: procédé cryptographique à sens unique En ligne: requêtes vers site web, serveur,... Hors ligne: tout en local == Etapes + Obtenir les empreintes (hash) + Attaque - Force brute: toutes les combinaisons - Dictionnaire: liste générique/thématique - Heuristique: variations des éléments des dictionnaires - Pré-génération d'empreintes == Méthode Hellman Hasher le MDP, réduire le hash, hasher la réduction, ... == Rainbow tables Méthode de Hellman mais avec une réduction différente à chaque étape La réduction donne une chaine de lettres (plaintext) - Evite les collisions - Réduit l'espace nécessaire - Réduit le temps de calcul == Empreinte salées Ajoute une string aléatoire au mot de passe avant de le hasher. (i.e. le même mot de passe produira des hashs différents) - Impossible de calculer à l'avance les tables de "crackage" == Windows Security Accounts Manager `c:\Windows\system32\config\SAM` === Hashage - Win 98/ME: LM (LAN Manager) - Win NT/2k/XP/2003: NTLM et LM - Win Vista/7/8/10/11: NTLM === LAN Manager Hash Hash séparamment les deux parties du MDP, max 14 char (128b) === NT LAN Manager Hash Hash tout d'un coup, max 256 char (128b) = Linux `/etc/shadow` == Identifiants - vide: DES, sans sel - 1: MD5 (vieux linux & BSD) - 2a/2b/2x/2y: Blowfish (OpenBSD) - 5/6: SHA-256/SHA-512 (Linux/FreeBSD) - y: yescrypt (Linux & glibc récente) = Comparaison des méthodes de cassage #table( columns: (1.7cm, auto, auto, 1cm, auto, auto), rows: (1.6cm,auto,auto,auto,auto,auto), align: horizon+center, [*Méthode*], [#rotate(270deg)[*Temps préparation*]], [#rotate(270deg)[*Temps cassage*]],[#rotate(270deg)[*Taille mémoire*]],[#rotate(270deg)[*Probabilité succès*]],[#rotate(270deg)[*Sel*]], "Dictionnaire","0","?","Faible","?","Idem", "Heuristique","0","?","Faible","?","Idem", "Force brute","0","O(N)","0","100%","Idem", "Pré-calcultaion complète","O(N)","0","O(N)","100%","Plus Dur", "Hellman","Long","Faible","Variable","50-95%","Plus Dur", "Rainbow tables","Long","Faible","Variable","50-95%","Plus Dur", ) = Authentification des emails - SPF: vérifie que l'expéditeur est autorisé - DKIM: vérifie signature authentique == Protection - Utiliser TLS (Transport Layer Security protocol) - Utiliser l'authentification - Utiliser la messagerie sécurisée - chiffrement - signature électronique = Malware == Types - Virus - Code executable - Se reproduit automatiquement - S'attache à d'autres programmes / fichiers - Besoin des utilisateurs pour se propager - Ver - Code executable - Se reproduit automatiquement - Se propage via les réseaux - Autonome (pas besoin d'utilisateurs) - Spyware, Canular, Adware - Gov-ware, Cyber War = Antivirus Protection sur 4 niveaux recommandé - Tous les postes clients - Serveurs de fichiers - Serveurs de messagerie - Proxies internet
https://github.com/5eqn/osa-fp-talk
https://raw.githubusercontent.com/5eqn/osa-fp-talk/main/main.typ
typst
#import "template.typ": * #show: project.with( title: "如何用 143 行代码搓出新编程语言?", authors: ( "5eqn", ), ) = 前言 答案是用「函数式编程」! 本次 Talk 是个科普,旨在描绘函数式编程的美,不会深入进行逻辑推导。 即使你只是单纯好奇,也可以来听! #figure( image("res/tenet.png", width: 50%), caption: [ 《信条》剧照 / 不要试图理解它,要感受它 ], ) == 目标受众 推荐学习过 C 语言或其它相似语言的人参加本次 Talk,以获得最佳体验。 == 自我介绍 哈深大二 CS 人,开源技术协会核心成员,有适量工业编程实践 #footnote[在 GitHub 和某实验室。] 的同时爱好编程语言理论。 喜欢发猫猫虫表情包以及玩 Eggy Party。 如果有条件的话,考虑在 GitHub 给本次 Talk 讲义和开源代码点个星 #footnote[https://github.com/5eqn/osa-fp-talk] qwq == 鸣谢 本讲义能有现在的质量,离不开大量同学的建议和帮助,我在此表达真诚的感谢。 下面是鸣谢名单(按照字典序),但只有征得同意的一部分,且可能有疏漏: #columns(3)[ - Anqur - AntibodyGame - Clouder - harpsichord - launchd #colbreak() - N3M0 - Origami404 - San_Cai - SeparateWings - SoraShu #colbreak() - toaster - yyx - zc - zly - ... ] #pagebreak() 特别感谢「开源技术协会」!如果你喜欢开源技术,欢迎加入我们! #figure( image("res/osa.jpg", width: 50%), caption: [ 开源技术协会群二维码 ], ) #pagebreak() == 导语 你是否好奇过,机器是如何把编程语言转化成执行结果的? #figure( image("res/lang.png", width: 50%), caption: [ ? ], ) 业界有很多种实现方式,本次 Talk 我们讲最简单的一种:再写一个程序来转化! #figure( image("res/code.png", width: 50%), caption: [ ! ], ) 但是,写程序处理一个编程语言,一看就是个大工程!真的能在一节课内搞定吗? 可以! 只需要拆成两步,一切都会变得简单: #figure( image("res/pi.png", width: 50%), caption: [ 两步 ], ) 可以看到中间是棵树,存储着程序的「意思」,以更简单地算出程序的运行结果。 理论存在,实践开始! #pagebreak() 先看第一个步骤,正常而言这一步代码量非常大,感受下规模就好: #figure( image("res/cpp.png", width: 10%), caption: [ 这只是部分代码 #footnote[https://github.com/drmenguin/minilang-interpreter/blob/master/src/parser/parser.cpp] ], ) #pagebreak() 但用函数式编程,核心代码可以被减少到 50 行之内: #figure( image("res/parser.png", width: 50%), caption: [ 我的程序 #footnote[https://github.com/5eqn/osa-fp-talk/blob/main/defect-lang/src/main/scala/Main.scala] ], ) #pagebreak() 下面的 Python 代码可以完成第二步: #figure( image("res/python.png", width: 50%), caption: [ keleshev/mini #footnote[https://github.com/keleshev/mini/blob/master/mini.py] ], ) #pagebreak() 是不是比你想象的短很多? 你先别急,因为用函数式编程实现几乎相同的功能,只需要: #figure( image("res/carbon.png", width: 50%), caption: [ 我的程序 ], ) 经过本系列 Talk,你也将大致知道怎么搓出自己的编程语言! #sect(title: "补充:如果你真的想跟着做……", color: "blue")[ 你需要安装 Scala3 #footnote[https://www.scala-lang.org/download/]。 ] #pagebreak() = 第一部分 / 横看成岭侧成峰 惯常把程序看成一条一条指令的我们,或许从未想过,换个视角便能看到不同的美。 如果说 C 语言是在问「怎么做」,那函数式编程便是在问「是什么」。 #figure( image("res/swap.png", width: 50%), caption: [ C 语言和函数式编程解决交换问题 ], ) 听完本章,你将收获: - 了解「函数式编程」的基本概念 - 掌握用函数式编程处理「字符串」的技巧 - 学会用函数式编程建模简单的东西 预计时间:40 分钟 #pagebreak() == 1 / 4 什么是函数式编程? 考虑在 C 语言中,你会怎么写一个函数,用于把数加一? 一种方法是直接写函数: #sect[```c int f(int x) { return x + 1; } ```] 一种方法是「修改」一个数: #sect[```c void f(int *x) { *x = *x + 1; }```] 在函数式编程中,相比 C 语言最大的不同就是:不能「修改」一个值。 若要采用函数式编程的写法把数加一,你只能: #sect[ #grid(columns: (auto, auto), gutter: 10pt, [ === Scala3 代码 ```scala def f(x: Int): Int = x + 1 ``` ], [ === 意义 定义 $f$ 使得 $f(x) = x + 1$,其中 $x$ 和 $f(x)$ 的类型是整数。 ])] #sect(title: "一些例题", color: "blue")[ 不用在意语法,只要不修改值就行。 1. 请写一个函数 `isNumeric`,判断一个字符是不是数字。 2. 请写一个函数 `isAlphabetic`,判断一个字符是不是字母。 答案在 GitHub #footnote[https://github.com/5eqn/osa-fp-talk/blob/ab7c09acf7e7ac38242d675984cb2888edccbcb4/defect-lang/src/main/scala/Main.scala#L6-L7],我在 Talk 里也会讲。] #pagebreak() == 2 / 4 来点更难的问题 我们是要处理编程语言,而不是 $f(x) = x + 1$,因此我们需要有能力处理字符串。 如果我们要从一个字符串 `str = "you are new bee"` 里面提取出第一个单词,可以怎么做? 你可能会想用一个指针从 `str[0]` 往后扫,扫到不是字母的东西,就把指针前面的作为结果。 但这背后的逻辑其实很简单:你希望从前往后处理。 在函数式编程中,我们可以「不依赖外界值,直接用数据表达顺序」: #figure( image("res/string.png", width: 50%), caption: [ C 和函数式编程对字符串的不同处理方式 ], ) 具体地,我们可以把字符串看成一个「有两种情况的东西」: #sect(title: "两种情况", color: "blue")[ 1. 由一个字符 `head` 和一个字符串 `tail` 拼接而成,例如 `"Au5" = 'A' + "u5"` 2. 为空,例如 `""`] 这两个规则便可以完整地描述字符串的概念! 现在我们尝试来写提取出第一个单词的函数,`collect`: #sect[ #grid(columns: (auto, auto), gutter: 10pt, [ === Scala3 代码 ```scala def collect(str: String): String = str.headOption match case Some(head) if isAlphabetic(head) => // ? case _ => // ? ``` ], [ === 意义 若要提取 `str` 的第一个单词: - 讨论 `head` 的情况 - `head` 存在且为字母 - 其他情况 ])] 若 `head` 存在且为字母,那我们自然要保留这个 `head`: 考虑到 `head == 'y'`,`collect("ou are new bee") == "ou"`,结果可以写成: #sect[ #grid(columns: (40%, 60%), gutter: 10pt, [ === Scala3 代码 ```scala val res = collect(str.tail) head + res ``` ], [ === 意义 - 设 `collect(str.tail)` 的结果为 `res` - 则 `collect(str)` 的结果为 `head + res` ])] 若 `head` 不存在或者不是字母,显然什么都提取不出,返回空字符串即可。 #pagebreak() === 选读:How it works? #sect[```scala collect("you are new bee") == (val res = collect("ou are new bee"); 'y' + res) collect("ou are new bee") == (val res = collect("u are new bee"); 'o' + res) collect("u are new bee") == (val res = collect(" are new bee"); 'u' + res) collect(" are new bee") == "" collect("u are new bee") == (val res = collect(" are new bee"); 'u' + res) == (val res = ""; 'u' + res) == "u" collect("ou are new bee") == (val res = collect("u are new bee"); 'o' + res) == (val res = "u"; 'o' + res) == "ou" collect("you are new bee") == (val res = collect("ou are new bee"); 'y' + res) == (val res = "ou"; 'y' + res) == "you" ```] #pagebreak() == 3 / 4 再难一点 在处理编程语言的时候,我们总不能读入一个东西,就把后面的字符串全部丢掉吧! #figure( image("res/recycle.png", width: 50%), caption: [ 你不想这样做 ], ) 如果我们需要同时收集剩下的字符串,可以怎么修改这个函数? #sect[ #grid(columns: (auto, auto), gutter: 10pt, [ === Scala3 代码 ```scala def collect(str: String): (String, String) = str.headOption match case Some(head) if isAlphabetic(head) => // ? case _ => // ? ``` ], [ === 意义 若要同时收集剩下的字符串: - 讨论 `head` 的情况 - `head` 存在且为字母 - 其他情况 ])] 第一种情况下,注意到 `collect("ou are new bee") = ("ou", " are new bee")`, 我们希望返回 `("you", " are new bee")`,剩下的字符串不会变化,因此考虑写成: #sect[ #grid(columns: (auto, auto), gutter: 10pt, [ === Scala3 代码 ```scala val (res, rem) = collect(str.tail) (head + res, rem) ``` ], [ === 意义 - 设 `collect(str.tail)` 的结果为 `(res, rem)` - 则 `collect(str)` 的结果为 `(head + res, rem)` ])] 第二种情况下,整个字符串都是被剩下的,所以结果是 `("", str)`。 #pagebreak() === 选读:How it works? #sect[```scala collect(" are new bee") == ("", " are new bee") collect("u are new bee") == (val (res, rem) = collect(" are new bee"); ('u' + res, rem)) == (val (res, rem) = ("", " are new bee"); ('u' + res, rem)) == ("u", " are new bee") collect("ou are new bee") == (val (res, rem) = collect("u are new bee"); ('o' + res, rem)) == (val (res, rem) = ("u", " are new bee"); ('o' + res, rem)) == ("ou", " are new bee") collect("you are new bee") == (val (res, rem) = collect("ou are new bee"); ('y' + res, rem)) == (val (res, rem) = ("ou", " are new bee"); ('y' + res, rem)) == ("you", " are new bee") ```] #pagebreak() == 4 / 4 现实是有失败的 设想你已经写好了一个编程语言,但有人给你: #sect[```c #include <studio.h> int mian() { printf("Hell Word!") remake 0; } ```] 这不找茬吗? 事实上,你永远不能指望用户给你的输入是正确的,因此你需要先准备好处理错误。 假设我们希望 `collect` 遇到 `114514` 这种不以字母开头的字符串就直接报错,该怎么办? 我们又遇到了一种「有两种情况的东西」:处理结果。 #sect[ #grid(columns: (auto, auto), gutter: 10pt, [ === Scala3 写法 ```scala enum Result[+A]: case Success(res: A, rem: String) case Fail ``` ], [ === 意义 分析结果有两种可能, - 分析成功:返回「值」`res` 和「剩余字符串」`str` - 分析失败:啥也不返回,记为 `Fail` ])] #figure( image("res/cases.png", width: 30%), caption: [ 无论成功还是失败,都是结果! ], ) 我们可以把 `collect` 包装起来: #sect[ #grid(columns: (auto, auto), gutter: 10pt, [ === Scala3 写法 ```scala def ident(str: String) = val (res, rem) = collect(str) if res.length() > 0 then Result.Success(res, rem) else Result.Fail ``` ], [ === 意义 定义一个新函数 `ident`: - 设 `collect(str)` 的结果为 `(res, rem)` - 若 `res` 的长度大于 $0$ - 则 `ident(str)` 为 `Success(res, rem)` - 否则 `ident(str)` 为 `Fail` ])] #sect(title: "一些例题", color: "blue")[ 1. 请写一个函数 `exactChar`,判断字符串是否以字符 `exp` 开头。 2. 请写一个函数 `exactString`,判断字符串是否以字符串 `exp` 开头。 3. 请写一个函数 `number`,读入字符串开头的非负数字,可能有多位。] #pagebreak() === 选读:How it works? #sect[```scala collect("you are new bee") == ("you", " are new bee") res == "you" rem == " are new bee" res.length() > 0 == true ident("you are new bee") == Result.Success("you", " are new bee") ```] #pagebreak() = 第二部分:只用 143 行的秘密 上面讲述的只是函数式编程的「普通玩法」。 在下面的「进阶玩法」中,我们可以激进地提取出代码中的共同逻辑,从而有效减少行数! #figure( image("res/reduce.png", width: 50%), caption: [ 提取共同逻辑 ], ) 听完本章,你将收获: - 了解一种提取共同逻辑的方式 预计时间:40 分钟 #pagebreak() == 1 / 4 提取! 现在我们就来尝试提取一下 `ident`、`exact` 和 `number` 的共同特征: 它们都是从 `String` 到某种 `Result` 的函数。 不妨给 `String => Result[A]` 套一层盒子,叫做 `Parser[A]`: #sect[```scala case class Parser[A](run: String => Result[A]): ```] #figure( image("res/box.png", width: 50%), caption: [ `Parser` 是盒子,`run` 是拆开盒子的剪刀 ], ) 把 `ident` 写成 `Parser[String]`,就是: #sect[ #grid(columns: (auto, auto), gutter: 10pt, [ === Scala3 写法 ```scala def ident = Parser( str => val (res, rem) = collect(str) if res.length() > 0 then Result.Success(res, rem) else Result.Fail ) ``` ], [ === 意义 定义 `ident` 为一个 `Parser`,装着: - 一个接受 `str` 作为参数的函数 - 设 `collect(str)` 的结果为 `(res, rem)` - 若 `res` 的长度大于 $0$ - 则返回 `Success(res, rem)` - 否则返回 `Fail` ])] #sect(color: "blue")[ 注意 `Parser` 装着的那个函数没有名字,被直接以 `str => ...` 的形式创建! 这样的函数也叫「匿名函数」。] 要使用 `ident`,本来我们 `ident("some str")` 就可以,现在要 `ident.run("some str")`。 …… 现在 `ident`、`exact` 和 `number` 都是某种 `Parser`,已经蓄势待发。 接下来,请见证表达力的起飞! #pagebreak() === 选读:How it works? #sect[```scala ident == Parser(str => val (res, rem) = collect(str); ...) ident.run == str => val (res, rem) = collect(str); ... ident.run("you are new bee") == (val (res, rem) = collect("you are new bee"); ...) == Result.Success("you", " are new bee") ```] #pagebreak() == 2 / 4 截胡 现在假设我们的编程语言里只会出现变量和数字: #sect[ #grid(columns: (auto, auto), gutter: 10pt, [ === Scala3 写法 ```scala enum Term: case Num(value: Int) case Var(name: String) ``` ], [ === 意义 表达式有两种可能: - 数字,例如 `51121` 会被处理成 `Num(51121)` - 变量,例如 `oiiai` 会被处理成 `Var("oiiai")` ])] 要用已有的 `number` 来写一个读取 `Term.Num` 的 `Parser`,最简单的方式是什么? 已知 `number.run("51121cat") = Success(51121, "cat")`, 我们希望结果变成 `Success(Term.Num(51121), "cat")`。 设想我们能「截胡」处理出来的值 `51121`,然后换成 `Term.Num(51121)`,不就简单了吗? #figure( image("res/map.png", width: 50%), caption: [ 截胡的过程 ], ) 假设这个「截胡」函数是 `map`,读入 `Term.Num` 只需要: #sect[ #grid(columns: (auto, auto), gutter: 10pt, [ === Scala3 写法 ```scala def pos = number.map( x => Term.Num(x) ) ``` ], [ === 意义 - 定义 `pos` 为对 `number` 截胡得到的新 `Parser` - 截胡用的函数把数字 `x` 变成 `Term.Num(x)` ])] 是不是很简单? 不妨想想怎么从 `ident` 实现 `atom`,用于读取一个 `Term.Var`。只需要一个 `map` 就行! #pagebreak() === 选读:How it works? #sect(color: "blue")[ `map` 的实现是这样子的: ```scala def map[B](cont: A => B) = Parser(str => run(str) match case Result.Success(res, rem) => Result.Success(cont(res), rem) case Result.Fail => Result.Fail ) ```] #sect[```scala pos == number.map(x => Term.Num(x)) == Parser(str => number.run(str) match case Result.Success(res, rem) => Result.Success((x => Term.Num(x))(res), rem) case Result.Fail => Result.Fail) pos.run == str => number.run(str) match case Result.Success(res, rem) => Result.Success((x => Term.Num(x))(res), rem) case Result.Fail => Result.Fail pos.run("51121cat") == number.run("51121cat") match case Result.Success(res, rem) => Result.Success((x => Term.Num(x))(res), rem) case Result.Fail => Result.Fail == Result.Success(51121, "cat") match case Result.Success(res, rem) => Result.Success((x => Term.Num(x))(res), rem) case Result.Fail => Result.Fail == Result.Success((x => Term.Num(x))(51121), "cat") == Result.Success(Term.Num(51121), "cat") ```] #pagebreak() == 3 / 4 第二条命 截胡有一个致命缺点:只有一条命。 比如 `pos` 虽然对 `number` 进行了截胡,但不能再读入更多东西,已经寄掉了。 若要读一个负数,如果用 `map`,读了 `'-'` 之后也会寄掉,读不了数字了。这很不好! 如果截胡之后还能有「第二条命」,那该多好? #figure( image("res/flatmap.png", width: 50%), caption: [ 第二条命 ], ) 假设这个「给第二条命的截胡」函数是 `flatMap`,读入一个负数只需要: #sect[ #grid(columns: (auto, auto), gutter: 10pt, [ === Scala3 写法 ```scala def neg = exact('-').flatMap( _ => number.map( x => Term.Num(-x) ) ) ``` ], [ === 意义 - 定义 `neg` 为对 `exact('-')` 截胡得到的新 `Parser` - 直接忽略结果,用续的命再读一个 `number`,再截胡 - 把数字 `x` 变成 `Term.Num(-x)` ])] 是不是依然很简单? #pagebreak() === 选读:How it works? #sect(color: "blue")[ `flatMap` 的实现是这样子的: ```scala def flatMap[B](cont: A => Parser[B]) = Parser(str => run(str) match case Result.Success(res, rem) => cont(res).run(rem.trim()) case Result.Fail => Result.Fail ) ``` 若不用 `trim`,在连读两个数字 `"114 514"` 时,第一次会剩下 `" 514"`,注意前面有空格! 这个空格会导致第二次读入失败。`trim` 就是为了删除这种前导空格。 另一种选择是每次读入东西之后都专门再读入空格。] #sect[```scala val cont = _ => number.map(x => Term.Num(-x)) neg == exact('-').flatMap(cont) == Parser(str => exact('-').run(str) match case Result.Success(res, rem) => cont(res).run(rem.trim()) case Result.Fail => Result.Fail) neg.run == str => exact('-').run(str) match case Result.Success(res, rem) => cont(res).run(rem.trim()) case Result.Fail => Result.Fail neg.run("-114 and 514") == exact('-').run(str) match case Result.Success(res, rem) => cont(res).run(rem.trim()) case Result.Fail => Result.Fail == Result.Success('-', "114 and 514") match case Result.Success(res, rem) => cont(res).run(rem.trim()) case Result.Fail => Result.Fail == cont('-').run("114 and 514".trim()) == number.map(x => Term.Num(-x)).run("114 and 514") == Result.Success(-114, " and 514") ```] #pagebreak() == 4 / 4 神说,要有加 只读入数字和变量怎么行?我们要读入 `add(1, 1)` 这种加法! 你可能会想,这么多元素,要写几个 `flatMap`? 答案是,0 个! 由于 `flatMap` 嵌套的模式在 Scala3 中过于普遍,Scala3 允许我们进行「简写」: #sect[ #grid(columns: (auto, auto), gutter: 40pt, [ === 原始写法 ```scala def neg = exact('-').flatMap( _ => number.map( value => Term.Num(-value) ) ) ``` ], [ === 简写写法 ```scala def neg = for { _ <- exact('-') value <- number } yield Term.Num(-value) ``` ])] #figure( image("res/for.png", width: 40%), caption: [ 对应关系 ], ) 你甚至可以把 `<-` 想成某种赋值! 现在再实现 `add`,就清晰了不少: #sect[ #grid(columns: (auto, auto), gutter: 40pt, [ === Scala3 写法 ```scala def add = for { _ <- exact("add") _ <- exact('(') lhs <- pos _ <- exact(',') rhs <- pos _ <- exact(')') } yield Term.Add(lhs, rhs) ``` ], [ === 意思 - 定义 `add` 为这样的 `Parser`: - 先读一个 `"add"` - 再读一个 `'('` - 再读一个正数,记为 `lhs` - 再读一个 `','` - 再读一个正数,记为 `rhs` - 再读一个 `')'` - 最终处理结果为 `Term.Add(lhs, rhs)` ])] #sect(title: "按照这种思路,我们还可以读取", color: "blue")[ - `if a == b then c else d`,选择分支,记为 `Term.Alt(Term.Var("a"), ...)` - `let x = 1 in x`,定义新值,记为 `Term.Let("x", Term.Num(1), Term.Var("x"))` - `(x) => add(x, 1)`,创建匿名函数,记为 `Term.Lam("x", Term.Add(...))` - `app(f, x)`,函数调用,记为 `Term.App(Term.Var("f"), ...)`] #pagebreak() = 第三部分 / 搓出编程语言! 我们已经有了足够的知识储备,现在可以来搓一个编程语言了! 我搓的语言是 `defect-lang`,名字来源于游戏 Slay the Spire 中的一个角色: #figure( image("res/defect.jpg", width: 50%), caption: [ The Defect ], ) 用 143 行搓出来的语言,虽然有一些缺陷,但也能实现意想不到的事情。 听完本章,你将收获: - 了解如何搓出一个编程语言 预计时间:40 分钟 #pagebreak() == 1 / 2 神说,要有或 细心的你可能已经发现了:`add` 不能读取负数相加、变量相加,这很坏。 我们需要有能力「尝试多条路径」,才能读入「正数或负数或变量」。 #figure( image("res/alt.png", width: 50%), caption: [ 尝试多条路径读入 `-2` ], ) 令 `term` 为读入「正数或负数或变量」的 `Parser`: #sect[ #grid(columns: (auto, auto), gutter: 40pt, [ === Scala3 写法 ```scala def term: Parser[Term] = pos | neg | var ``` ], [ === 意思 定义 `term` 为 `pos` 或 `neg` 或 `var`。 ])] 随着能读入的东西种类越来越多,`term` 的可选路径也会越来越多。 例如,在实现 `add` 后,`term` 也要能读取一个加法式子,变成 `... | add`。 #pagebreak() === 选读:How it works? #sect(color: "blue")[ `|` 的实现是这样子的: ```scala def |(another: Parser[A]) = Parser(str => run(str) match case Result.Success(res, rem) => Result.Success(res, rem) case Result.Fail => another.run(str) ) ``` ] #sect[```scala term == (pos | neg) | var == Parser(str => (pos | neg).run(str) match case Result.Success(res, rem) => Result.Success(res, rem) case Result.Fail => var.run(str)) pos | neg == Parser(str => pos.run(str) match case Result.Success(res, rem) => Result.Success(res, rem) case Result.Fail => neg.run(str)) (pos | neg).run("-114 and 514") == pos.run("-114 and 514") match case Result.Success(res, rem) => Result.Success(res, rem) case Result.Fail => neg.run("-114 and 514") == Result.Fail match case Result.Success(res, rem) => Result.Success(res, rem) case Result.Fail => neg.run("-114 and 514") == neg.run("-114 and 514") == Result.Success(-114, " and 514") term.run("-114 and 514") == (pos | neg).run("-114 and 514") match case Result.Success(res, rem) => Result.Success(res, rem) case Result.Fail => var.run("-114 and 514") == Result.Success(-114, " and 514") match case Result.Success(res, rem) => Result.Success(res, rem) case Result.Fail => var.run("-114 and 514") == Result.Success(-114, " and 514") ```] #pagebreak() == 2 / 2 怎么求值? 就摁求! #sect[ #grid(columns: (auto, auto), gutter: 40pt, [ === Scala3 代码 ```scala enum Val: case Num(value: Int) case Lam(body: Val => Val) ``` ], [ === 含义 值有两种可能: - 是一个数字 - 是一个从值到值的函数 ])] 要求一个 `Term` 的值,我们就直接定义求值函数,对每种 `Term` 分类讨论: #sect[```scala def eval(env: Map[String, Val], term: Term): Val = term match case Term.Num(value) => case Term.Var(name) => case Term.Lam(param, body) => case Term.App(func, arg) => case Term.Add(lhs, rhs) => case Term.Let(name, value, next) => case Term.Alt(lhs, rhs, x, y) => ```] #sect(title: "env 是个什么东西?", color: "blue")[如果你 `let x = 1`,`env` 里就会多出 `x -> 1` 这条记录。 换言之,参数 `env` 存储已知的名字到值的对应关系。 ] `Term.Num(value)` 的值,显然是 `Val.Num(value)`! `Term.Var(name)` 的值,需要在当前语境 `env` 中查找,所以是 `env(name)`。 `Term.Lam(param, body)` 表示匿名函数,显然值是 `Val.Lam(arg => ?)` 的形式。 接受参数 `arg` 后语境中多出了 `param -> arg`,因此 `?` 是 `eval(env + (param -> arg), body)`。 剩下的求值都相对简单,读者可以尝试构思,答案在 GitHub #footnote[https://github.com/5eqn/osa-fp-talk/blob/ab7c09acf7e7ac38242d675984cb2888edccbcb4/defect-lang/src/main/scala/Main.scala#L140-L166]。 #pagebreak() === 选读:How it works? 要处理以下的程序: #sect[```scala app((x) => add(x, 1), 4) ```] 过程是这样子的: #sect[```scala val f = Term.Lam("x", Term.Add(Term.Var("x"), Term.Num(1))) eval(Map(), Term.App(f, Term.Num(4))) == eval(Map(), f) match case Val.Lam(body) => body(eval(Map(), Term.Num(4))) case _ => throw new Exception("app") eval(Map(), Term.Lam("x", Term.Add(Term.Var("x"), Term.Num(1)))) == Val.Lam(arg => eval(env + ("x" -> arg), Term.Add(Term.Var("x"), Term.Num(1)))) eval(Map(), Term.Num(4)) == Val.Num(4) eval(Map(), Term.App(f, Term.Num(4))) == (arg => eval( Map() + ("x" -> arg), Term.Add(Term.Var("x"), Term.Num(1)) ))(Val.Num(4)) == eval(Map("x" -> Val.Num(4)), Term.Add(Term.Var("x"), Term.Num(1))) == (eval(Map("x" -> Val.Num(4)), Term.Var("x")), eval(Map("x" -> Val.Num(4)), Term.Num(1))) match case (Val.Num(a), Val.Num(b)) => Val.Num(a + b) case _ => throw new Exception("add") eval(Map("x" -> Val.Num(4)), Term.Var("x")) == Map("x" -> Val.Num(4))("x") == Val.Num(4) eval(Map(), Term.App(f, Term.Num(4))) == (Val.Num(4), Val.Num(1)) match case (Val.Num(a), Val.Num(b)) => Val.Num(a + b) case _ => throw new Exception("add") == Val.Num(4 + 1) == Val.Num(5) ```] #pagebreak() 恭喜你已经实现了一个自己的编程语言!下面是一些扩展阅读内容。 == 函数式编程的工业应用 在目前工业实践中,FP 不仅可以以单独的函数式语言的形式存在,而且可以融合在一些主流语言的主流框架之中,且后者的应用显著更广泛。以下是几个例子: - #tag[前端] React.js 的设计模式和 FP 非常共通,例如提倡使用不可变变量 - #tag[后端] Rocket.rs 基于 Rust 语言,Rust 本身大量借鉴 FP 元素,例如模式匹配 - #tag[AI] PyTorch 中模型的模块其实就是一个个函数,自动求导也能用类似的方式实现 - #tag[游戏开发] Unity 中 ECS 架构中的 System 可以被视为上一状态到下一状态的函数 同时也有不少工业向的 FP or FP-ish 语言,例如: - #tag[Rust] 相当通用的语言,有独特的生命周期和所有权机制,编程语言中的「原神」(? - #tag[Kotlin] Java 家族成员,主要用于安卓开发,沾 FP 但只沾一点点 - #tag[Clojure] 基于 JVM 的 Lisp 方言,比较通用 - #tag[PureScript] 和 Haskell 很像,编译成 JavaScript,主要用于 Web 前端 - #tag[Elm] 专门用来写 Web 前端的语言 - #tag[Idris2] 不仅 FP 而且 Type-driven,希望消灭所有运行时错误 #footnote[https://github.com/edwinb/SPLV20] == 深入研究方向 - #tag[源码] PL Zoo #footnote[http://plzoo.andrej.com/],各种编程语言实现技巧的代码演示,使用 OCaml 语言。 - #tag[类型论] FP 和类型论高度相关,考虑从类型论暑校 #footnote[https://infinity-type-cafe.github.io/ntype-cafe-summer-school/] 开始入门类型论,我下次也会讲。 == 我为什么选择这个题材 显然有不少人对怎么自己搓出编程语言感兴趣,用这个题材能吸引更多人来听,这样就不会出现观众全部比我懂 FP 的尴尬情况,我也可以真的为传播美的事物 #footnote[这里指 FP。] 做出一点点贡献。 如果搞成「单子的应用举例」这种标题,可能会有些人看在这是近期第一次协会 talk 的份上进来围观,但其实又不是真的想看内容,然后出于礼貌在会议室挂机 #footnote[如果有会议室的话。],这不是我希望看到的局面。 还有一个原因,我希望我的 talk 中出现手搓代码的情节,这样看起来比较有趣。如果观众能产生「我们一起写成了」的感觉,那真的是泰裤辣! Fun Fact: 我原先打算讲怎么用 FP 搓 AI 中的自动求导,但感觉讲起来太过困难,听众对 AI 基础原理有一定了解之后才容易接受,因此这次没有选择 AI 话题。如果大家真的很希望我(而不是哈深随处可见的 AI 力比我强的大佬)讲的话,我还是很愿意找个时间讲的( == 下期预告,如果有 类型论 #pagebreak() == 左递归 如果要处理任意长度、没打括号的加减法串,该怎么做呢? 主要难点在于处理左递归。我们希望把形如 `1-2-3-4` 的东西拆成 `((1-2)-3)-4`。起初我们可能想这样写(这里用了 Haskell 语法): #sect[ ```haskell series : Parser Int series = do left <- series char '-' next <- num pure (left + next) ``` ] 但是,这段代码会死循环!因为 `series` 没有经过任何其他模块,就直接调用了它自身。 其实,处理左递归是一个相当困难的问题,在 Parser Combinator #footnote[其实就是这种模块化的语法分析。] 被第一次提出的 19 年 #footnote[这篇文章说的 19 年,但我考证不了:https://zhuanlan.zhihu.com/p/25867784] 后(2008 年)才得到解决 #footnote[https://www.semanticscholar.org/paper/Parser-Combinators-for-Ambiguous-Left-Recursive-Frost-Hafiz/cc524e8e95294be0491aa3b4bdf7e1125b85a39c](我之前扩展了一下 Parser Combinator 才解决这个问题 #footnote[https://github.com/5eqn/aevum-lang/blob/8f92acdc0ab0dde2aa43cf4e29b36ca2141a83c9/src/Aevum/Main.idr#L81-L84],并不是标准解法,虽然当时我都不知道 Parser Combinator)。如果使用正常的自底向上 #footnote[大白话就是读一点处理一点,不像现在这样搞模块化。现在这种叫自顶向下。] 写法就没有这个问题,这或许也是优美代码的代价吧…… 参考 Parsec 库 #footnote[https://github.com/haskell/parsec/blob/c5add8bd1da56ee11fd327409b3b46aa8015a974/src/Text/Parsec/Combinator.hs#L217-L241] 的做法,设想如果不使用 `left <- series` 来引用左侧括号内的内容,而是从外部获取左边的结果,会发生什么?代码将发生以下三个改变: - 函数签名变成 `(left : Int) -> Parser Int`,因为需要接受外部参数 - 结束时不能直接用 `pure` 返回,而是把结果塞给自己 - 需要专门读取第一个数作为初始的 `left` 值 于是我们这样实现(顺带加上了加减法的选择): #sect[ ```haskell series : Parser Int series = do left <- num rest left where rest : Int -> Parser Int rest left = (do char '+'; next <- num; rest (left + next)) <|> (do char '-'; next <- num; rest (left - next)) <|> pure left ``` ]
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/PianoDiProgetto/sections/PianificazioneSprint/UndicesimoSprint.typ
typst
MIT License
#import "../../functions.typ": glossary === Undicesimo #glossary[sprint] *Inizio*: Venerdì 01/03/2024 *Fine*: Giovedì 07/03/2024 *Obiettivi dello #glossary[sprint]*: - Proseguire la stesura del _Piano di Progetto_: - Aggiornare pianificazione e preventivo pertinenti allo #glossary[sprint] 11 e inserire il consuntivo pertinente allo #glossary[sprint] 10; - Aggiornare ed aggiungere rispettivamente per gli #glossary[sprint] 11 e 12, pianificazione e preventivo; - Proseguire con la stesura della _Specifica Tecnica_, con piccole correzioni e aggiunte che possano raffinare il documento in modo da rappresentare in modo sempre più accurato l'#glossary[architettura]\; - Individuazione degli strumenti necessari al calcolo delle metriche di codifica e di prodotto e definizione delle relative procedure di utilizzo nelle _Norme di Progetto v2.0_; - Iniziare la fase di implementazione dell'#glossary[architettura] nel prodotto, che dopo la progettazione è pronta per essere sviluppata, seguendo quindi il documento _Specifica Tecnica_ e le prassi definite nelle _Norme di Progetto v2.0_: - Configurazione delle componenti necessarie all'interno di un file di configurazione docker-compose; - Realizzazione della struttura, definita nella _Specifica Tecnica_, per l'esecuzione contemporanea dei simulatori; - Implementazione dei simulatori dei dati ambientali.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/rivet/0.1.0/src/vec.typ
typst
Apache License 2.0
#let vec(x, y) = { return (x: x, y: y) } #let add(v1, v2) = { return vec( v1.x + v2.x, v1.y + v2.y ) } #let sub(v1, v2) = { return vec( v1.x - v2.x, v1.y - v2.y ) } #let mul(v, f) = { return vec( v.x * f, v.y * f ) } #let div(v, f) = { return vec( v.x / f, v.y / f ) } #let mag(v) = { return calc.sqrt(v.x * v.x + v.y * v.y) } #let normalize(v) = { let m = mag(v) if m == 0 { return (x: 0, y: 0) } return div(v, m) }
https://github.com/zadigus/math
https://raw.githubusercontent.com/zadigus/math/main/number-theory/page-6/template.typ
typst
#import "@preview/ctheorems:1.0.0": * #show: thmrules // The project function defines how your document looks. // It takes your content and some metadata and formats it. // Go ahead and customize it to your liking! #let project(title: "", authors: (), body) = { // Set the document's basic properties. set document(author: authors, title: title) set text(font: "Linux Libertine", lang: "en") set par(justify: true) body } #let lemma = thmbox( "theorem", "Lemma", fill: rgb("#eeffee") ).with(numbering: none) #let proof = thmplain( "proof", "Proof", base: "lemma", bodyfmt: body => [#body #h(1fr) $square$] ).with(numbering: none)
https://github.com/cadojo/correspondence
https://raw.githubusercontent.com/cadojo/correspondence/main/src/vita/vita.typ
typst
MIT License
#import "src/resume.typ": * #import "src/cv.typ": *
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/06-features-2/anchor/amiri-kern-2.typ
typst
Other
#import "/lib/draw.typ": * #import "/template/lang.typ": arabic-amiri #let start = (0, 0) #let end = (500, 200) #let graph = with-unit((ux, uy) => { // mesh(start, end, (50, 50)) txt([关闭`calt`#h(1fr)#arabic-amiri(text(features: ("calt": 0, "kern": 0))[(لبے)])], (0, 180), anchor: "lt", size: 42 * ux) txt([开启`calt`关闭`kern`#h(1fr)#arabic-amiri(text(features: ("calt": 1, "kern": 0))[(لبے)])], (0, 120), anchor: "lt", size: 42 * ux) txt([开启`calt + kern`#h(1fr)#arabic-amiri(text(features: ("calt": 1, "kern": 1))[(لبے)])], (0, 60), anchor: "lt", size: 42 * ux) }) #canvas(end, width: 70%, graph)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/grid-rtl-00.typ
typst
Other
#set text(dir: rtl) - מימין לשמאל
https://github.com/AntoineCorbel/typst
https://raw.githubusercontent.com/AntoineCorbel/typst/main/info-box.typ
typst
// todo: key this by the provided label or just use dependency injection #let this-counter = counter("info-box") #let info-box( title: none, sections: none, label: none, caption: none, radius: 3pt, inset: 16pt, outset: 0pt, fill: luma(45), ) = { set block(spacing: 0pt) let title-radius = radius if sections != none { title-radius = (top: radius) } pad( y: inset, [ #pad( x: outset, rect( width: 100%, inset: 0pt, stroke: fill, radius: radius, [ #if title != none { block( width: 100%, radius: title-radius, fill: fill, pad( inset, par( justify: false, text( hyphenate: false, white, title ) ) ) ) } #if sections != none { let i = 0 for section in sections { if i > 0 { line(length: 100%) } pad( inset, section ) i += 1 } } ] ) ) #if caption != none { align( center, pad( 12pt, [ #if label != none { label } #this-counter.display(): #caption ] ) ) this-counter.step() } ] ) }
https://github.com/harrellbm/Bookletic
https://raw.githubusercontent.com/harrellbm/Bookletic/main/example/example.typ
typst
Apache License 2.0
#import "@preview/bookletic:0.3.0" // To use through preview //#import "..\src\lib.typ" // To use on a local clone of the library //#import "bookletic.typ" // To use on a clone to the Typst app #set document(author: "<NAME>", title: "Bookletic Example") //Barebones example #let my-eight-pages = ( [ = Cover Page (or Page One) The content given within each bracket will appear as a single page in the booklet. ], [ = Page Two #lorem(80) ], [ = Page Three #lorem(80) ], [ = Page Four #lorem(80) ], [ = Page Five #lorem(80) ], [ = Page Six #lorem(80) ], [ = Page Seven #lorem(80) ], [ = Back Cover (or Page Eight) ], ) // provide your content pages in order and they // are placed into the booklet positions. // the content is wrapped before movement so that // padding and alignment are respected. #set page(flipped: true, paper: "us-letter") #bookletic.sig( contents: my-eight-pages // Content to be laid out in the booklet ) // Styling Options Example // Note: Normal show and set rules work just like normal! #show heading: set align(center) #set text(size: 16pt, font: "PT Serif", lang: "en") #set par(justify: true) #let more-eight-pages = ( [ #v(45%) = Cover Page ], [ = Page One \ #lorem(80) ], [ = Page Two \ #lorem(100) ], [ = Page Three \ #lorem(80) ], [ = Page Four \ #lorem(40) #lorem(40) #lorem(40) ], [ = Page Five \ #lorem(80) ], [ = Page Six \ #lorem(120) ], [ #v(45%) = Back Cover ], ) // Note: You can use the regular page function to set the paper size, and outside margins #set page(flipped: true, paper: "us-legal", margin: (top: 0.5in, bottom: 0.5in, left: 0.5in, right: 0.5in)) // Use bookletic's sig function to set booklet specific settings #bookletic.sig( page-margin-binding: 0.5in, // Binding margin for each page page-border: none, // Whether to draw a border around each page eg, luma(0) draft: false, // Whether to output draft or final layout p-num-layout: ( // Refer to example below for further explination of page number usage bookletic.num-layout( p-num-start: 1, p-num-alt-start: none, p-num-pattern: "~ 1 ~", p-num-placement: bottom, p-num-align-horizontal: right, p-num-halign-alternate: true, p-num-align-vertical: horizon, p-num-pad-left: 0pt, p-num-pad-horizontal: 0pt, p-num-size: 16pt, p-num-border: none, ), ), pad-content: 0pt, // Padding around page content contents: more-eight-pages ) //Example of how to specify specific page numbers for different page ranges // This example removes page numbers on the front and back cover, adds roman numberal page numbers on the table of contents page and starts numbering from one for content pages. #let more-more-my-eight-pages = ( [ = Cover Page This page has no page number ], [ = Table of Contents This page has a roman numeral page number + #lorem(10) + #lorem(10) + #lorem(10) + #lorem(10) ], [ = Page One of the Book This page starts fresh numbering the books actual content #lorem(80) ], [ = Page Two #lorem(80) ], [ = Page Three #lorem(80) ], [ = Page Four #lorem(80) ], [ = Page Five #lorem(80) ], [ = Back Cover This page also has no page number ], ) #set page(flipped: true, paper: "us-letter") #bookletic.sig( draft:true, page-border: luma(0), // Whether to draw a border around each page eg, luma(0) page-margin-binding: 0.2in, // Binding margin for each page p-num-layout: ( // Each entry in the p-num-layout array allows defining a specific style of page numbers starting from the specified page bookletic.num-layout( p-num-start: 1, // Beginning Page for this page number layout p-num-pattern: none, // Adding none here will remove page numbers for this section ), bookletic.num-layout( p-num-start: 2, p-num-alt-start: none, // Adding none here will continue numbering the pages using their physical page number p-num-pattern: "I", // Pattern for page numbering p-num-placement: bottom, // Placement of page numbers (top or bottom) p-num-align-horizontal: center, // Horizontal alignment of page numbers p-num-halign-alternate: false, p-num-align-vertical: top, // Vertical alignment of page numbers p-num-pad-left: 90%, // Extra padding added to page number //Note: Extra padding does not work when horizontal alignment is set to left or right p-num-pad-horizontal: 5pt, // Horizontal padding for page numbers p-num-size: 20pt, // Size of page numbers p-num-border: none, // Border color for page numbers ), bookletic.num-layout( p-num-start: 3, p-num-alt-start: 1, // Specifing a number here will start numbering this section from that number. In this case starting from one again p-num-pattern: (..nums) => box(inset: 3pt, text(size: 10pt, sym.lt.curly.double )) + " " + nums .pos() .map(str) .join(".") + " " + box(inset: 3pt, text(size: 10pt, sym.gt.curly.double)), // This is how to use custom symbols around page numbers p-num-placement: top, p-num-align-horizontal: center, p-num-halign-alternate: false, p-num-align-vertical: horizon, p-num-pad-left: 0pt, p-num-pad-horizontal: 1pt, p-num-size: 18pt, p-num-border: oklab(27%, 20%, -3%, 50%), ), bookletic.num-layout( p-num-start: 8, p-num-pattern: none ), ), contents: more-more-my-eight-pages )
https://github.com/donRumata03/aim-report
https://raw.githubusercontent.com/donRumata03/aim-report/master/lib/presentation-utilities.typ
typst
#import "@preview/codelst:1.0.0": sourcecode, code-frame #import "@preview/polylux:0.3.1": only #let codeblock(body, highlight: (), dark: false, nums: true, fill: none, size: 1em, width: 100%) = { if dark {set text(fill: orange)} let sourcecode = if not nums { sourcecode.with(numbering: none) } else {sourcecode} set text(size: size) sourcecode(frame: code-frame.with( fill: if dark {black.lighten(5%)} else {fill}, stroke: none, inset: (x: 5pt, y: 10pt)), highlighted: highlight, highlight-color: if dark {black.lighten(20%)} else {green.lighten(70%)}, body) } #let timeblock-only(blocks, index: 0) = { if blocks.len() == 0 { return } only(index + 1, blocks.remove(0)) timeblock-only(index: index + 1, blocks) } #let timeblock(time-light: (), body, dark: false) = [ #let timeblocks = time-light.map(h => codeblock(body, highlight: h, dark: dark)) #timeblock-only(timeblocks) ] #let superblock(body) = [ #todo[ Заплатите 1М\$, чтобы убрать ожидание этой функции. ] ] #let set-code(size: 1) = { it => { show raw: set text(size: size*1em) it } } #let set-code-for-bad-projector(body) = { set raw(theme: "../res/GitHub.tmTheme") show raw: set text(size: 1.1em) body }