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/043%20-%20Innistrad%3A%20Midnight%20Hunt/002_Tangles.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Tangles",
set_name: "Innistrad: Midnight Hunt",
story_date: datetime(day: 03, month: 09, year: 2021),
author: "<NAME>",
doc
)
There was something unique about the air on Innistrad. Maybe it was the horrors the trees had witnessed here, the blood that watered the soil on which they fed their thirsty roots, the bones that littered the riverbeds, but the air of this Plane was like no other. Wrenn and Six took a step—one of their last together—and put their massive foot down on the soil of Innistrad, deep within the Kessig forest. This was near the place where they had met for the first time.
#emph[Here?] Wrenn inquired, asking without opening her mouth. How the question ached and burned at her, how it #emph[ached] . This part was always painful.
#figure(image("002_Tangles/01.jpg", width: 100%), caption: [Wrenn and Seven | Art by: Heonhwa Choe], supplement: none, numbering: none)
Somehow, it hurt more this time than it had when she was parted from Four, who had been injured so badly in battle that they had barely been able to complete their last steps together before the valiant old tree had shuddered and expelled her from its heart, sending her to sprawl, bare-limbed and exposed, on the earth of Innistrad. It had been a new Plane to her then, but one she had heard rumor of before.
Those rumors, from the mouths of other planeswalkers, held that the finest trees grew in the Kessig forest, and after her time with Six, she was inclined to agree.
#emph[No. Close] , replied the tree. Wrenn nodded their vast head and continued into the wood, away from the place where they had arrived, looking for a clearing large enough to support Six's glory.
Perhaps this parting hurt more because Six #emph[could] keep going, #emph[could] stay with her, but was choosing not to, and part of why their partnership had always worked so well was that she listened when the big tree spoke. They were partners, not an owner and a tool. She had seen mages who treated their partners like beasts of burden and forced them to perform past the point of their own exhaustion. Wrenn's seed had been planted by a better parent, and she had been raised to respect those who served with her, even if her war was not their own.
They had taken another five steps when the tree spoke again, saying, #emph[Here. Stop.]
Wrenn stopped. They drove their roots deep into the ground, and bit by bit, she began to pull herself out of the home that had been hers for so long. As she pulled, her awareness of the great tree dwindled, until she felt like a tooth that had been loosened in its socket, still part of the body but awaiting only one last sharp blow to knock it out entirely.
Then, with a final yank that she felt all the way to the bottom of her stomach, she uprooted herself and was no longer joined with Six. Six, who was no longer the majestic, towering treefolk he had become during their time together—trees had no gender as such, but dryads did, and upon discovering the concept in her mind, he had considered his choices and decided he preferred the masculine—was now a mature, healthy, beautifully twisting Innistrad oak, his branches reaching for the clouded sky.
Wrenn sighed and leaned her forehead against his bark, breathing in the familiar scent of him for the final time. "Someday," she promised. "Someday, a very long time from now, when Seven wearies and I have need of my Eight, I will return here. I will walk these woods again, and I will find you, old friend, and your acorns will have had time to grow into strong young trees, and I will offer them the choice I once offered you, and if one of them should accept it, I will consider myself fortunate beyond measure."
They could no longer communicate in silence, their minds separated for the first time. Six's consciousness would fade as he settled into the ground and rejoined the trees who were his natural companions and kin. Her partner was leaving her, and while she could still have pulled herself inside, this was what he wanted. She would let him go, for his own sake. The life of a planeswalker was no simple thing, even for one who heard the call unaided.
Still, she fancied she felt gratitude and joy through his bark, and she smiled as she pulled away. She would miss him. But that was the thing about the past; it was behind you. The future was ahead.
It was time to find hers.
After the better part of a day spent wandering the Kessig forest, following the whisper of treesong that told her there was a viable partner growing here, she was beginning to doubt the future's promise would ever be fulfilled. Her feet ached, and her legs were tired. They were things she always had but rarely had reason to use. Now they were so sore, they felt as if they were the whole of her, and still the treesong lured her deeper into the forest, urging her on, promising a compatible partner ahead.
Those lucky few whose Planes harbored native dryads tended to assume they could bond with any tree, that any woody vessel would be enough to sustain them. That wasn't so. As with any form of magic, theirs required a certain harmony to sing properly. The song of Wrenn's sapling filled her body. Any tree near her could hear it, and the ones who knew the harmonies would sing them in return.
Six had sung to her, once. Now he was a silent presence behind her as she moved deeper into the wood, and the new singer was either very far away or very weak, for their song was small and hard to hear.
Perhaps she should have been less respectful of Six's desire to come home and stopped at the first harmonious tree she saw once he announced his desire to be parted. But that would have been a cruelty, and her strength was not yet at an end. She could continue.
Determined to do as her kind had always done, survive, Wrenn walked onward, deeper and deeper into the Kessig forest, following the song of the tree that waited for her somewhere in the glades.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Teferi had not visited Innistrad before. It had always been a story told by other travelers, a rumor whispered in passing, until curiosity and time combined to make it a worthwhile destination. The locals were frightened people, with good reason, wary of strangers but generous of hospitality once convinced their visitors meant no harm. They were, some of them, desperate for any hint of hope, any kind word or possibility that life might be easier elsewhere. Unable to free them from their homeland and unwilling even to consider the logistics of such a wild endeavor, Teferi had begun to find their constant company wearing.
#figure(image("002_Tangles/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Relief came in an unexpected form, when cathars from the local church came charging into the inn with reports of a white witch seen in the woods. Here on Innistrad, it was not unreasonable to assume any unknown phenomena could pose a danger, and the hospitality he had been offered was enough that he felt obligated to offer aid. So it was with that he found himself at the wood's edge accompanied by and yet apart from a detachment of men, their swords and bows at the ready, searching for their so-called white witch and the terrible abomination she had supposedly summoned. He had no idea what the threat might be, only that it had been seen as enough to drive the cathars to the wood and provide him with exit from his hosts.
The cathars spread out, searching for signs of the witch they had been told lurked within these trees. Teferi watched them go before strolling into the trees on his own. No local witchling was going to present much of a threat to him, and he wanted to understand this forest if he could. Woodlands were different on every Plane, but they had certain commonalities—oaks and elms, for example, could be found almost anywhere that had trees, and the scent of their leaves never varied as much as he would have expected it to. Perhaps if he'd been more attuned to natural magics, he would have understood the reasons. Perhaps it would be a good thing to discuss with the next nature-aligned mage he encountered, assuming they were in the mood for conversation. It was always enlightening to learn more about the working of the Planes, which could be so very different and so very harmonious at the same time.
"This way," called one of the cathars, voice followed by the sound of footsteps crackling on leaves as they set out, presumably chasing their quarry. As none of them were in sight to notice his lingering, Teferi felt no pressing need to follow.
Something flickered on the edge of his awareness, other than the trees, other than the departing cathars. He spun around, peering into the shadows. He saw nothing there. After a moment's pause to frown at the empty path, he resumed his wandering, more slowly now, taking his time to study his surroundings.
Perhaps that was why he heard the woman.
She was speaking softly, voice low and gently pitched, with rounded vowels that matched no accent he knew. He adjusted his path, heading for the voice, not yet calling the cathars to join him, and paused when he saw the figure standing in the shadow of one of the great oaks.
She was pale, so pale that she looked like she'd been sketched entirely from aspen bark, a white wraith against the darker trunks of the oaks around her. Her hair was long, loose, and even whiter, bone-bleached and stark. Her forehead was resting against one of the trees, face obscured by the angle, and her words seemed to be aimed at the tree itself.
Teferi walked toward her, hands out and open, fingers spread to show that he was shaping no arcane symbols, readying no spells. Given her coloring, she was likely to be the cathars' "white witch," but she seemed more like a gift from the wood, for none could understand the natural world like a dryad could, even as there was space for misunderstanding between those of flesh and bone and those of sap. His foot, placed without looking, snapped the smallest of fallen twigs, and she whirled, eyes gone wide, pressing her back to the bark of the tree she had been speaking with. As she did not meld into it, he thought himself safe to continue approaching, and moved closer, stopping at a respectful distance and offering her a shallow bow.
"Forgive me the intrusion, but you seemed unwell," he said. "May I offer aid?"
"Stay back, mage," she said, voice sharp as a broken branch, but still soft, as if half the heart had been cut out of it. "I can defend myself."
"I'd rather not fight," he said. "It's a dull way of meeting people. The locals are more than battle hungry enough for the both of us. May I assume you came seeking a moment's peace?"
"I came looking for a tree," she replied, narrow eyed and wary.
"Look no further." Teferi spread his hands, indicating the trees all around them.
The dryad laughed, wryly. "If only it were so simple. But no. None of these trees are strong enough to hold me."
Teferi frowned. "Forgive me, but I was under the impression that a dryad was born with their tree, grew in tandem with it, and never left it."
"They are," she said. "I mean, #emph[we] are. I mean, there was a great fire once. It devoured the trees of my people, until I found a way to pull it into myself. It burns there still. It burns me now. It grants me the flexibility to move from tree to tree, if the tree can contain the fire. When it was still new and bright, the inferno led me to a tree whose song knew my own. We came together, and we were One." Her expression softened. "With One, I learned that those of us who have no roots to anchor us can walk as we will, not limited to a single Plane, and when she was done serving her time as my partner, I allowed her to take root on another Plane, and found another tree to sing with."
"You have no tree now."
"No."
"Are you trapped on this Plane without one?"
"I need a partner to travel," she admitted. "But Six grew weary, and this forest was his beginning, so he asked if I could take him home before he stilled, and he was good to me. He carried me far. I carried him home and listened for the song that would allow me to continue my own journeys. And I thought I had found it, so I traveled toward it until I could go no farther, and now I fear the fire will have me."
Teferi frowned, trying to sort through the puzzling phrases, as footsteps in the trees heralded the presence of the cathars. "I think the mage went this way," one yelled.
The dryad looked to Teferi with sudden loathing. "So you were a lure to call and catch me, then?" she demanded, hands balling into fists, air above them going red-hot with flickering fire. "I'm not so easy to kill when I have something left to burn."
Teferi put his own hands up. "Peace, please. They're not with me." Then he grimaced. "Well, they are, I suppose, but I'm not with #emph[them] . If we go deeper into the wood, we can slow them down. Can you walk?"
Wrenn nodded. "I can't leave this Plane on my own, but I can walk."
Teferi stepped over and offered her his arm. "Then we walk."
The heat above her hands flickered and went out, and her fingers, as she slipped them into the crook of his elbow, were as cool as untouched wood and less pliant than he would have expected them to be. But they bent as fingers were meant to bend, cupping his flesh, and when they began to walk, she was nimble as any other.
They hadn't gone far when he winced and sighed, closing his eyes. "Are you well?" asked Wrenn.
"We're being followed," he said. She tensed. "No, not by the cathars, and don't bother to turn around. It was following me before, and I saw nothing when I looked."
"Not everything on Innistrad is visible," said Wrenn. "The soil does not encourage the dead to rest."
"Do the dead intend us harm?"
"Anything that would follow travelers in the wood without approaching them means no good," said Wrenn. "I would assume it means us harm, yes."
"That was my fear." Teferi turned, slowly to keep Wrenn from stumbling, and scowled into the gloom behind them. "Show yourself."
Nothing materialized. But the shadows, which were already deep, deepened and grew heavy with the feeling of an unseen presence. Whatever it was, it meant them no good; the aura of malice radiating from the deepest dark was palpable enough that even Wrenn, who had little connection to either the dead or spiritual worlds, stiffened and narrowed her eyes.
"It isn't of the trees," she murmured. "It has no song."
"Show yourself," repeated Teferi, flicking his fingers in a quick series of curling, spiraling lines that ended with a raise of his hand, palm pointed toward the deep shadows. Blue light flared from his skin, and when it faded, a figure lurked where the malicious presence had been. It was a warped and twisted parody of a humanoid, caught somewhere at the intersection between man, beast, and tree. Its mouth was a gaping maw filled with angular teeth that had never grown in the jaw of anything living.
#figure(image("002_Tangles/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
It hissed, the sound deep and guttural, and Teferi reacted without thought, raising his hands and unleashing a torrent of flickering blue magic. The shape writhed and surged forward, accurately interpreting this as an attack, and Teferi's eyes widened. Any simple ghost or wraith would have been banished by that blast, thrown forward into time and leaving them unthreatened. He muttered a soft phrase and shoved more magic through his fingers, as the specter shoved back, hissing still, and finally vanished in a burst of terrible, necrotic energy.
He turned back to Wrenn, lowering his hands. She had fallen when he yanked away so sharply, and watched him from the ground, a delicate, displeased ghost of a woman. "You have my apologies," he said, kneeling to offer his hands. "But the thing is gone, for now."
"As is our path back," she said sourly, as she allowed herself to be pulled to her feet. "Look what you've done, mage."
Teferi looked over his shoulder. The path was gone, or rather, the path was replicated, transformed from a reasonably straight line cut through the trees to a tangled ball of identical paths, each one branching off in a different direction, until it seemed they must run out of separate ways for them to go. The distinctive crackle of time magic hung over it all.
"~Oh," said Teferi, faintly.
"Yes," said Wrenn. "Oh." Then, with more anger in her voice, she said, "The tree that called me is gone. I can't hear it anymore. Do you know what you've #emph[done] ?"
"I'm afraid I don't." Teferi looked at his hands, then at the air, still crackling blue in spots. "Which is worrisome. You came here looking for a tree. Can't you take refuge in one of these?" He indicated the trees around them.
"If only," she said, a hint of manic laughter in her voice. "These are fine, mature trees that would carry me far~if they were suitable partners. But none of them sing to me. None of them can carry my fire. The tree that called me was a sapling yet. Too young to hold me. Too small to contain the burning."
Teferi frowned. "So we find you another tree, before you burn to nothing."
"It doesn't #emph[work] that way," protested the woman, voice growing even more ragged. "Dryads walk the Planes with our trees to keep and anchor us. Because my heart is made of fire, when I walk, my tree walks with me. I can have no partner too small to accommodate me, nor can I convince any unsuitable tree to carry me into the Plane. I #emph[must] find a tree, and I don't have as much time as I would prefer!"
Teferi frowned, following the thread of her story in the things she wasn't saying. He began to walk again, and she followed, too sensible to remain behind alone. "Peace, friend," he said, finally. "You need to find a tree. I need to find a way out of this mess I've made. Perhaps we can find these things together?"
"It's not as if there's anything else to do," said the woman. "But as I said, my time is short."
Teferi nodded, pondering. "I understand not wishing to admit weakness to a stranger, but it sounds as if you say that without a tree, you will die."
"I can defend myself!" she snapped, the air around her hands growing hazy with heat as she tapped into what mana she had remaining to her. "Do not try me, mage."
"Peace, dryad," he said. "Peace, and names. Mine is Teferi. Yours?"
She straightened, some of the wariness leaving her expression. "They call me Wrenn. I have heard of you, mage. Your legend travels farther than your feet."
It had the cadence of a proverb. Teferi smiled. "Good things, I hope. Things that lead you to believe I wouldn't injure an innocent."
"None who walk the Planes are innocent," said Wrenn. "Still, most of your tales have been~less than terrible. Many call you a kind man. I will trust you for now." The heat haze around her hands vanished. "Yes. Without a tree, my journey will be finished here."
"Can you listen for another, do you think, if I lend you my support?"
"I can listen, but you'll have to lead the way."
Teferi looked around the twisted maze the Plane had become, devoid of cathar and spectral presence, and sighed. "As well as anyone can, I suppose I shall."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
They had been walking for the better part of the afternoon, following the twisting path. Neither of them was familiar enough with the area to know which of the bends had been introduced when Teferi banished the monster. Some of the nearby trees looked dauntingly familiar, and Teferi reached out, spark flaring, and flinched as the shell of his own spell knocked him back, so similar to what he'd done to Zhalfir, and yet not similar in the least. He could feel the passage of time around them; Wrenn was getting weaker, still searching for the treesong that would save her. Time was marching onward. They were still in phase with Innistrad.
They were just~stuck.
#figure(image("002_Tangles/04.jpg", width: 100%), caption: [Art by: Isis], supplement: none, numbering: none)
"We've been here before," said Wrenn. "We've made a big loop."
"No," said Teferi, despite his own suspicions. "We never turned around. We've been walking south, or roughly south, this entire time."
"Can you hear the treesong the way I can?" asked Wrenn. "Do the trees whisper their desires to you, making you understand what they wish? If yes, then I will believe you. If, as feels more likely, no, then you have no way to contradict me, and I'm tired. We are almost back where we began."
Teferi eyed her, looking for any sign of levity. She looked calmly back, eyes open and unguarded. Near as he could tell, she spoke the truth. He stopped in the middle of the path, feeling the time swirling around them, and there, right on the edges of the working, flavoring without tainting it, was the remainder of the lurking presence. It was #emph[right there] . He should have been able to tear this spell down without a second thought!
And instead, it endured, trapping and taunting them. Wrenn pulled her hand away from his arm and stepped over to a rotting log, still graceful despite her clear increasing weariness. She sat, back slightly slumped, and said, "This is not the ending I envisioned to the story I was seeded to."
"It's not an ending," Teferi protested. "It's a spell gone wrong. Surely you've seen spells go wrong before."
"Yes, and when it happens to me, I pick them apart until they dissolve in my hands~" She trailed off, frowning at the look on Teferi's face. "What?"
"Pick them apart #emph[how] , exactly?"
"Everything that comes from you remains of you, forever," she said. "The water that passes through the soil into the roots of the tree is still a part of the clouds; the story that maps your footsteps is still a part of who you were, and who you were is forever part of who you are and will be. If the spell endures, you can gather it close, find the places where it became tangled beyond your intentions, and pull it into pieces. Those can be released harmlessly, back into the mana that is all things." Wrenn blinked. "Is this not how your people see the roots of magic?"
"No," said Teferi carefully. "We view our workings in somewhat less~organic ways. It's an interesting idea."
"Magic lives. Can you see your spell?"
"I can."
"Can you touch it?"
He grimaced, remembering the sting of brushing his fingers against the magic, but admitted, "I can."
"Can you hold it?"
"Not on my own."
"Ah. Your roots are too shallow. Here—I'll help." She hummed, a single clear, carrying note, and the natural magic of the wood swirled around him, bright and growing, bolstering the sparks of his own time-tied working. "Now can you hold it?"
Teferi reached for the spell again and smiled as it failed to push him away. "I can."
"Good. Now, you have to remember that you best undo a tangle by moving through it. There's always an entry point, a place where the branches don't quite interlace. Use that to enter its song. Find the place where it fails to find perfect harmony with itself, and you can unmake it."
Teferi frowned, but didn't want to argue with her, not when she had faded so far within the grasp of his own snarling time magic gone awry. He took a breath and felt for the distortion, for the snag she had described. When he found it, it was not a note out of place or a failure to harmonize; it was a second hand ever so slightly out of tune, an hourglass throat allowing the barest trickle too much sand. It was so slight he could have overlooked it a thousand times if he'd been studying the spell in the normal way, at a slight remove, without Wrenn's natural magic feeding his own. Now, he ran the hands of his awareness over it and when that slightest weakness bent before him, dug his mental fingers into the opening like splitting the skin of an orange.
With the outer layer shucked aside, it was easier to "see" the ways in which the spell had become distorted, the interaction of that dreadful presence and his own clear blue mana. Time was bent, a smashed clock, in the middle of what should have been a simple working. Bit by bit, he straightened and unbent the cogs, repairing the spell's original intent, and when he was done, it no longer stung his fingers. He could touch it as easily as anything intact.
He raised his head, and the path was back as it had been, not straight, but not a tangled and forbidding labyrinth, either. The way was clear. The feeling of time magic gone awry no longer hung heavy in the air. Wrenn's magic pulled away from his own, and he turned back to her. She was watching him with weary eyes.
"Your legend travels virtuously," she said. "You deserve the songs they sing of you."
"Not all of them," Teferi said, success paling before past failure. "The place I come from originally, Zhalfir~I lost it."
"You #emph[lost] it?"
"Yes. The entire continent, through a spell much like this one. I've never been able to undo what I did." Then he brightened. "But if we find you a new tree, perhaps—"
"If our paths meet again," she said, and stiffened, attention going to a point behind him in the wood.
Teferi cursed himself for a fool. If the presence had not been fully banished, removing his spell might have allowed it to return. Even if it had been, the cathars could still be haunting this wood. He turned slowly, ready for an attack.
Instead, he saw a tree like every other tree around it, a tall, mature oak with healthy green leaves and spreading branches. Then Wrenn was brushing past him, her eyes on the trunk, seemingly unable to tear them away. He wasn't sure she was breathing. He also wasn't sure dryads needed to breathe. The laws of nature were somewhat different where the daughters of the glade were concerned. They walked in their own definition of the real.
Wrenn was walking, step by unsteady step, toward that tree. When she was close enough, she raised her hands, fingertips brushing the bark, and whistled. The sound was low and sweet. If Teferi hadn't been watching her, he would have taken it for birdsong. She cocked her head as if listening and then dove into the tree itself, vanishing into its body like a fish vanishes into clear water. The tree gave no sign that any of this had happened, and Wrenn was gone.
#figure(image("002_Tangles/05.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Teferi blinked and took his own steps toward the tree. He had almost reached it when the bark rippled and Wrenn's head poked out. The sight of a perfectly normal tree with the head and shoulders of a woman protruding from the side was only mildly disconcerting, and no stranger than anything else that had happened this day.
"You are a miracle, mage," she said, blissfully. "A miracle and a mistake in the same moment is a more commonplace thing than you might think!"
"What do you mean?"
"Ask the song," she said, and withdrew back into the tree, which began to shake and tremble, like it was pulling itself out of the ground. Then, as Teferi watched, it unfolded into the model of a man, a slumbering treefolk in the process of waking. Wrenn reappeared as the tree unfolded, jutting from its chest like the figurehead on a ship, most of her body still contained within the bark, a beatific smile on her face.
In an instant, Teferi understood. "This is the sapling that sang to you."
"You bent time. Trees turn time into wisdom, and this one knew I was near. It gathered all the time it could contain." She paused a moment, cocking her head to the side like she was listening. "Seven says they are grateful for what you've done, even if you didn't mean to do it. They were calling for me but thought I wouldn't have the chance to listen. They want to see the Planes."
"And you can show them?"
"Your legend travels farther than your feet. My legend travels only precisely as far," she said. "You have my gratitude."
"As you have mine, for helping me to dismantle my own tangle."
"Then we are well met, mage, and I wish you all peace in whatever you came here to find. I will aid you if I can, in the future, but for now, I have promised Seven lands outside of Innistrad, and I must keep my word." The tree—or treefolk, or vessel, or whatever it had become—was still growing, towering above the other oaks, bearing Wrenn away. She waved to Teferi, then leaned back into the trunk behind and around her, closing her eyes. The great treefolk took a step forward and then another as the trees bent away from them and back to conceal their form. When all the trees sprang back, dryad and treefolk were gone.
For the first time since entering these woods, Teferi was alone. He smiled at the empty air and turned to go back to the village he had come from. He could tell the cathars the danger had been dealt with, and he wouldn't be lying. Perhaps this hadn't been the peace he was seeking, but it had been a lesson unsought, and a new ally found, and those things were better than peace, especially to a man whose feet could travel farther than his legend.
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/src/elements/multiplexer.typ | typst | Apache License 2.0 | #import "@preview/cetz:0.2.2": draw
#import "../util.typ"
#import "element.typ"
#import "ports.typ": add-port
#let draw-shape(id, tl, tr, br, bl, fill, stroke, h-ratio: 60%) = {
let margin = (100% - h-ratio) / 2
let tr2 = (tr, margin, br)
let br2 = (br, margin, tr)
let f = draw.group(name: id, {
draw.merge-path(
inset: 0.5em,
fill: fill,
stroke: stroke,
close: true,
draw.line(tl, tr2, br2, bl)
)
draw.anchor("north", (tl, 50%, tr2))
draw.anchor("south", (bl, 50%, br2))
draw.anchor("west", (tl, 50%, bl))
draw.anchor("east", (tr2, 50%, br2))
draw.anchor("north-west", tl)
draw.anchor("north-east", tr2)
draw.anchor("south-east", br2)
draw.anchor("south-west", bl)
})
return (f, tl, tr, br, bl)
}
/// Draws a multiplexer
///
/// #examples.multiplexer
/// For other parameters description, see #doc-ref("element.elmt")
/// - entries (int, array): If it is an integer, it defines the number of input ports (automatically named with their binary index). If it is an array of strings, it defines the name of each input.
/// - h-ratio (ratio): The height ratio of the right side relative to the full height
#let multiplexer(
x: none,
y: none,
w: none,
h: none,
name: none,
name-anchor: "center",
entries: 2,
h-ratio: 60%,
fill: none,
stroke: black + 1pt,
id: "",
debug: (
ports: false
)
) = {
let ports = ()
let ports-y = (
out: (h) => {h * 0.5}
)
if (type(entries) == int) {
let nbits = calc.ceil(calc.log(entries, base: 2))
for i in range(entries) {
let bits = util.lpad(str(i, base: 2), nbits)
ports.push((id: "in" + str(i), name: bits))
}
} else {
for (i, port) in entries.enumerate() {
ports.push((id: "in" + str(i), name: port))
}
}
let space = 100% / ports.len()
let l = ports.len()
for (i, port) in ports.enumerate() {
ports-y.insert(port.id, (h) => {h * (i + 0.5) / l})
}
element.elmt(
draw-shape: draw-shape.with(h-ratio: h-ratio),
x: x,
y: y,
w: w,
h: h,
name: name,
name-anchor: name-anchor,
ports: (west: ports, east: ((id: "out"),)),
fill: fill,
stroke: stroke,
id: id,
ports-y: ports-y,
auto-ports: false,
debug: debug
)
for (i, port) in ports.enumerate() {
let pct = (i + 0.5) * space
add-port(id, "west", port, (id+".north-west", pct, id+".south-west"))
}
add-port(id, "east", (id: "out"), (id+".north-east", 50%, id+".south-east"))
} |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/supercharged-dhbw/1.0.0/titlepage.typ | typst | Apache License 2.0 | #let titlepage(authors, title, date, at-dhbw, logo-left, logo-right, course-of-studies, university, university-location, supervisor, heading-font) = {
stack(dir: ltr,
spacing: 1fr,
// Logo at top left if given
align(horizon,
if logo-left != none {
set image(width: 6cm)
logo-left
}
),
// Logo at top right if given
align(horizon,
if logo-right != none {
set image(width: 6cm)
logo-right
}
)
)
v(1.5fr)
align(center, text(font: heading-font, 2.2em, title))
v(4em)
align(center, text(1.2em, [from the Course of Studies #authors.map(author => author.course-of-studies).join(" | ")]))
v(1em)
align(center, text(1.2em, [at the #university #university-location]))
v(3em)
align(center, text(1em, "by"))
v(2em)
grid(
columns: 100%,
rows: auto,
gutter: 18pt,
..authors.map(author => align(center, {
text(weight: "medium", 1.5em, [#author.name])
}))
)
v(2em)
align(center, text(1.2em, date.display(
"[day].[month].[year]"
)))
v(1fr)
// Author information.
if (at-dhbw) {
grid(
columns: (180pt, auto),
gutter: 11pt,
text(weight: "semibold", [Student ID, Course:]),
stack(
dir: ttb,
for author in authors {
text([#author.student-id, #author.course])
linebreak()
}
),
text(weight: "semibold", "Supervisor:"),
text[#supervisor]
)
} else {
grid(
columns: (180pt, auto),
gutter: 11pt,
text(weight: "semibold", [Student ID, Course:]),
stack(
dir: ttb,
for author in authors {
text([#author.student-id, #author.course])
linebreak()
}
),
text(weight: "semibold", [Company:]),
stack(
dir: ttb,
for author in authors {
let company-address = text([#author.company.name, #author.company.post-code, #author.company.city])
if (author.company.country != "") {
company-address+= text([, #author.company.country])
}
company-address
linebreak()
}
),
text(weight: "semibold", "Supervisor in the Company:"),
text[#supervisor]
)
}
pagebreak()
} |
https://github.com/EpicEricEE/typst-droplet | https://raw.githubusercontent.com/EpicEricEE/typst-droplet/master/tests/extract/test.typ | typst | MIT License | #import "/src/lib.typ": dropcap
#set page(width: 6cm, height: auto, margin: 1em)
// Test that the first letter is extracted correctly.
#dropcap[First letter]
#dropcap[1. Wash your hands]
#dropcap[“This is a quote,” said someone.]
#dropcap[#super[1] In the beginning...]
#dropcap[H#sub[2] is hydrogen.]
#dropcap[#box[This] is a boxed word.]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/truthfy/0.2.0/example.typ | typst | Apache License 2.0 | #import "main.typ": *
#columns(2)[
#generate-table($u_7 => u_(22) => u$, $u_7 ? u_22 : u$)
#generate-table($A xor B$, $A and B$)
#colbreak()
#generate-table($A and B$, $B or A$, $A => B$)
#generate-table($p => q$, $not p => (q <=> p)$, $p or q$, $not p xor q$)
] |
https://github.com/VZkxr/Typst | https://raw.githubusercontent.com/VZkxr/Typst/master/Tarea%20Examen%202%20-%20Analisis%20matematico/doc.typ | typst | #set page(
numbering: "1"
)
#set text(font: "Times New Roman", size: 12pt)
#align(center, text(font: "Times New Roman", size: 15pt)[
*Tarea-Examen II*
])
#align(center, text(font: "Times New Roman", size: 10pt)[
* Alumno: <NAME> *
])
1. Sea $X$ un conjunto, prueba que las siguientes funciones son métricas.
#enum(
numbering: "a)",
indent: .5cm,
[En $X = {(x_1,x_2) in RR^2: x_2 > 0}$ definimos
$
d((x_1,x_2),(y_1,y_2)) = cases( bar.v x_2 - y_2 bar.v "si" x_1 = x_2,
bar.v x_2 bar.v + bar.v x_1 - y_1 bar.v + bar.v y_2 bar.v "si" x_1 eq.not x_2
)
$],
[En $X= NN times NN$ si $(k,m) in NN times NN$, $d(k,m) = bar.v frac(1,k) - frac(1,m) bar.v $, es una métrica en $NN times NN$.],
[Si $X = RR$, ¿$d(x,y) = bar.v s e n(x) - s e n(y) bar.v$ es métrica?.],
[Sea $X$ un campo completo y ordenado para $0 < alpha lt.eq 1$, la función $d(x,y) = bar.v x - y bar.v^alpha$ para toda $x,y in X$.]
)
_Demostración._ \
a). Sean $(x_1, x_2),(y_1,y_2),(z_1,z_2) in X$. \
I. \
Si $x_1 eq.not y_1$,
$
d((x_1, x_2),(y_1, y_2)) = bar.v x_2 bar.v + bar.v x_1 - y_1 bar.v + bar.v y_2 bar.v> 0
$
Si $x_1 = y_1$ y $x_2 eq.not y_2$,
$
d((x_1, x_2),(y_1, y_2)) = bar.v x_2 - y_2 bar.v > 0
$
Si $x_1 = y_1$ y $x_2 = y_2$,
$
d((x_1, x_2),(y_1, y_2)) = bar.v x_2 - y_2 bar.v = 0
$
Entonces $d((x_1, x_2),(y_1, y_2)) gt.eq 0$. \
II. \
Si $x_1 = y_1$,
$
d((x_1, x_2),(y_1, y_2)) &= bar.v x_2 - y_2 bar.v \
&= bar.v -(y_2 - x_2) bar.v \
&= bar.v -1 bar.v bar.v y_2 - x_2 bar.v \
&= bar.v y_2 - x_2 bar.v \
&= d((y_1, y_2),(x_1, x_2))
$
Si $x_1 eq.not y_2$,
$
d((x_1, x_2),(y_1, y_2)) &= bar.v x_2 bar.v + bar.v x_1 - y_1 bar.v + bar.v y_2 bar.v \
&= bar.v y_2 bar.v + bar.v -(y_1 - x_1) bar.v + bar.v x_2 bar.v \
&= bar.v y_2 bar.v + bar.v y_1 - x_1 bar.v + bar.v x_2 bar.v \
&= d((y_1, y_2),(x_1, x_2))
$
III. \
Si $x_1 = y_1 = z_1$, tenemos que
$
d((x_1, x_2),(y_1, y_2)) = bar.v x_2 - y_2 bar.v \
d((y_1, y_2),(z_1, z_2)) = bar.v y_2 - z_2 bar.v \
d((x_1, x_2),(z_1, z_2)) = bar.v x_2 - z_2 bar.v
$
de donde,
$
bar.v x_2 - y_2 bar.v + bar.v y_2 - z_2 bar.v & gt.eq bar.v x_2 - y_2 + y_2 - z_2 bar.v = bar.v x_2 - z_2 bar.v
$
entonces
$
d((x_1, x_2),(z_1, z_2)) lt.eq d((x_1, x_2),(y_1, y_2)) + d((y_1, y_2),(z_1, z_2))
$
Luego, si $x_1 eq.not y_1$ y $y_1 eq.not z_1$,
$
d((x_1, x_2),(y_1, y_2)) = bar.v x_2 bar.v + bar.v x_1 - y_1 bar.v + bar.v y_2 bar.v \
d((y_1, y_2),(z_1, z_2)) = bar.v y_2 bar.v + bar.v y_1 - z_1 bar.v + bar.v z_2 bar.v \
d((x_1, x_2),(z_1, z_2)) = bar.v x_2 bar.v + bar.v x_1 - z_1 bar.v + bar.v z_2 bar.v
$
entonces, $d((x_1, x_2),(y_1, y_2)) + d((y_1, y_2),(z_1, z_2))$ es igual a
$
& bar.v x_2 bar.v + bar.v x_1 - y_1 bar.v + bar.v y_2 bar.v + bar.v y_2 bar.v + bar.v y_1 - z_1 bar.v + bar.v z_2 bar.v \
&= bar.v x_2 bar.v + bar.v x_1 - y_1 bar.v + 2 bar.v y_2 bar.v + bar.v y_1 - z_1 bar.v + bar.v z_2 bar.v \
& gt.eq bar.v x_2 bar.v + bar.v x_1 - y_1 + y_1 - z_1bar.v + 2 bar.v y_2 bar.v + bar.v z_2 bar.v \
&= bar.v x_2 bar.v + bar.v x_1 - z_1bar.v + 2 bar.v y_2 bar.v + bar.v z_2 bar.v \
& gt.eq bar.v x_2 bar.v + bar.v x_1 - z_1bar.v + bar.v z_2 bar.v \
&= d((x_1, x_2),(z_1, z_2))
$
entonces
$
d((x_1, x_2),(z_1, z_2)) lt.eq d((x_1, x_2),(y_1, y_2)) + d((y_1, y_2),(z_1, z_2))
$
Por lo tanto es métrica.
#align(right)[$square.stroked$]
b).
2. Muestra que $(RR^n, d_l ^2)$, donde
$
d_(l^2)(macron(x),macron(y)) &= d_(l^2)((x_1,x_2,x_3,...,x_n),(y_1,y_2,y_3,...,y_n)) \
&= sqrt((x_1 - y_1)^2 + (x_2 - y_2)^2 +...+ (x_n - y_n)^2) \
&= sqrt(sum_(i=1)^n (x_i - y_i)^2)
$
es un espacio métrico. \
_Demostración._ \
Sean $macron(x) = (x_1,x_2,x_3,...,x_n)$ y $macron(y) = (y_1,y_2,y_3,...,y_n) in RR^n$, notemos que
$
d_(l^2)(macron(x),macron(y)) = sqrt(sum_(i=1)^n (x_i - y_i)^2) = 0 & arrow.l.r.double.long sum_(i=1)^n (x_i - y_i)^2 = 0 \
& arrow.l.r.double.long x_i = y_i #h(.5cm) text("para toda") i =1,...,n\
& arrow.l.r.double.long macron(x) = macron(y)
$
Luego,
$
d_(l^2)(macron(x),macron(y)) = sqrt(sum_(i=1)^n (x_i - y_i)^2) = sqrt(sum_(i=1)^n (y_i - x_i)^2) = d_(l^2)(macron(y),macron(x))
$
Es decir que para todo $macron(x), macron(y) in RR^n$ se cumple que $d_(l^2)(macron(x),macron(y)) = d_(l^2)(macron(y),macron(x))$.
Ahora consideremos $macron(z) = (z_1,z_2,z_3,...,z_n) in RR^n$, entonces
$
d_(l^2)(macron(x),macron(y))^2 &= (sqrt(sum_(i=1)^n (x_i - y_i)^2))^2 \
&= sum_(i=1)^n (x_i - y_i)^2 \
&= sum_(i=1)^n (x_i - z_i + z_i - y_i)^2 \
&= sum_(i=1)^n [(x_i - z_i) + (z_i - y_i)]^2 \
&= sum_(i=1)^n (x_i - z_i)^2 + 2 sum_(i=1)^n (x_i - z_i)(z_i - y_i) + sum_(i=1)^n (z_i - y_i)^2 \
& lt.eq sum_(i=1)^n (x_i - z_i)^2 + 2 sqrt(sum_(i=1)^n (x_i - z_i)^2)sqrt(sum_(i=1)^n (z_i - y_i)) + sum_(i=1)^n (z_i - y_i)^2 \
&= d_(l^2)(macron(x),macron(z))^2 + 2d_(l^2)(macron(x),macron(z))d_(l^2)(macron(z),macron(y)) + d_(l^2)(macron(z),macron(y))^2 \
&= [d_(l^2)(macron(x),macron(z)) + d_(l^2)(macron(z),macron(y))]^2
$
De aquí obtenemos que
$
d_(l^2)(macron(x),macron(y))^2 lt.eq [d_(l^2)(macron(x),macron(z)) + d_(l^2)(macron(z),macron(y))]^2 arrow.r.double.long d_(l^2)(macron(x),macron(y)) lt.eq d_(l^2)(macron(x),macron(z)) + d_(l^2)(macron(z),macron(y))
$
$therefore (RR^n, d_l ^2)$ es un espacio métrico.
#align(right)[$qed$]
3. Prueba las siguientes series de desigualdades en $RR^n$:
#enum(
numbering: "a)",
indent: .5cm,
[$d_(l^2)(x,y) lt.eq d_(l^1)(x,y) lt.eq sqrt(n) d_(l^2)(x,y)$],
[$frac(1,sqrt(n))d_(l^2)(x,y) lt.eq d_(l^(infinity))(x,y) lt.eq d_(l^2)(x,y)$]
)
Donde #h(.3cm) $d_(l^1)(x,y) = sum_(i=1)^n divides x_i - y_i divides$ #h(.3cm) y #h(.3cm) $d_(l^(infinity))(x,y) = sup{divides x_i - y_i divides : 1 lt.eq i lt.eq n}$. \
_Demostración._ \
a). Sea $macron(z)=(x_1-y_1, x_2 - y_2, ..., x_n - y_n)$. Notemos que
$
d_(l^1)(x,y) &= sum_(i=1)^n bar.v z_i bar.v \
arrow.r.double.long d_(l^1)(x,y)^2 &= (sum_(i=1)^n bar.v z_i bar.v)^2 \
& lt.eq sum_(i=1)^n (bar.v z_i bar.v ^2) sum_(i=1)^n ( 1^2) \
&= sum_(i=1)^n (bar.v z_i bar.v ^2)n
$
Donde la desigualdad se da por la #text(fill: rgb("#300CA4"))[Desigualdad de Hölder,] entonces
$
(sum_(i=1)^n bar.v z_i bar.v)^2 & lt.eq sum_(i=1)^n (bar.v z_i bar.v ^2)n \
arrow.r.double.long sum_(i=1)^n bar.v z_i bar.v & lt.eq sqrt(sum_(i=1)^n (bar.v z_i bar.v ^2)n) \
arrow.r.double.long d_(l^1)(x,y) & lt.eq sqrt(n)sqrt(sum_(i=1)^n (x_i - y_i)^2) \
therefore d_(l^1)(x,y) & lt.eq sqrt(n) d_(l^2)(x,y)
$
Luego, notemos que
$
(sum_(i=1)^n bar.v z_i bar.v)^2 gt.eq sum_(i=1)^n bar.v z_i bar.v ^2
$
por ser $bar.v z_i bar.v$ no negativo. Entonces, sacando raíz de ambos lados,
$
sum_(i=1)^n bar.v z_i bar.v & gt.eq sqrt(sum_(i=1)^n bar.v z_i bar.v ^2) \
therefore d_(l^2)(x,y) & lt.eq d_(l^1)(x,y) \
therefore d_(l^2)(x,y) lt.eq d_(l^1)(x,y) & lt.eq sqrt(n) d_(l^2)(x,y)
$
#align(right)[$square.stroked$]
b). Sea $macron(z)=(x_1-y_1, x_2 - y_2, ..., x_n - y_n)$. Notemos que
$
bar.v.double macron(z) bar.v.double_2 & = sqrt(sum_(i=1)^n bar.v z_i bar.v^2)
$
$
& lt.eq sqrt(sum_(i=1)^n limits(max)_(i=1,...,n) bar.v z_i bar.v^2) \
& = sqrt(n dot limits(max)_(i=1,...,n) bar.v z_i bar.v^2) \
& = sqrt(n) dot limits(max)_(i=1,...,n) bar.v z_i bar.v \
& = sqrt(n) bar.v.double macron(z) bar.v.double_(infinity) \ \ \
arrow.r.double.long bar.v.double macron(z) bar.v.double_2 & lt.eq sqrt(n) bar.v.double macron(z) bar.v.double_(infinity) #h(.7cm) #text(fill: rgb("#054CC8"))[...(1)]
$
Por otro lado, tenemos que
$
bar.v.double macron(z) bar.v.double_(infinity) & = limits(max)_(i=1,...,n) bar.v z_i bar.v \
& = sqrt(limits(max)_(i=1,...,n) bar.v z_i bar.v^2) \
& lt.eq sqrt(sum_(i=1)^n bar.v z_i bar.v^2) \
& = bar.v.double macron(z) bar.v.double_2 \ \ \
arrow.r.double.long bar.v.double macron(z) bar.v.double_(infinity) & lt.eq bar.v.double macron(z) bar.v.double_2 #h(.7cm) #text(fill: rgb("#054CC8"))[...(2)]
$
Y de este modo, juntando las desigualdades (1) y (2),
$
bar.v.double macron(z) bar.v.double_2 lt.eq sqrt(n) bar.v.double macron(z) bar.v.double_(infinity) lt.eq sqrt(n) bar.v.double macron(z) bar.v.double_2 #h(.7cm)
arrow.r.double.long #h(.7cm) frac(1, sqrt(n))bar.v.double macron(z) bar.v.double_2 lt.eq & bar.v.double macron(z) bar.v.double_(infinity) lt.eq bar.v.double macron(z) bar.v.double_2 \
therefore frac(1,sqrt(n))d_(l^2)(x,y) lt.eq d_(l^(infinity))(x,y) lt.eq d_(l^2)(x,y)
$
#align(right)[$qed$]
4. Sea ${a_n}_(n=1) ^infinity$ y ${b_n}_(n=1) ^infinity$ dos sucesiones en un espacio métrico $(X,d)$. Supongamos que $op("lim", limits: #true)_(n -> infinity) a_n = a$ y $op("lim", limits: #true)_(n -> infinity) b_n = b$ con $a,b in X$. Muestra que $op("lim", limits: #true)_(n -> infinity) d(a_n,b_n) = d(a,b)$.
_Demostración._ \
Sea $epsilon > 0$, tenemos que existe $N in NN$ tal que $d(a_n,a) < frac(epsilon,2)$ para $n gt.eq N$, por ser $(X,d)$ un espacio métrico. Luego, existe $N' in NN$ tal que $d(b_n,b) < frac(epsilon,2)$ para $n gt.eq N'$. \
De este modo, tomemos $n gt.eq max{N,N'}$, entonces
$
bar.v d(a_n,b_n) - d(a,b) bar.v & lt.eq d(a_n,a) + d(a,b_n) - d(a,b_n) + d(b_n,b) \
&= d(a_n,a) + d(b_n,b) \
&< frac(epsilon,2) + frac(epsilon,2) \
&= epsilon \
therefore op("lim", limits: #true)_(n -> infinity) d(a_n,b_n) = d(a,b)
$
#align(right)[$qed$]
5. Sea $p gt.eq 1$, $bar.v.double (x,y) bar.v.double := (bar.v x bar.v^p + bar.v y bar.v^p)^(1/p)$ y sea
$
d((x,y),(r,s)) = (bar.v x - r bar.v^p + bar.v y - s bar.v^p)^(1/p)
$
Demuestra que es una norma y por lo tanto $d((x,y),(r,s))$ es una métrica en $RR^2$.
_Demostración._ \
Primero se tiene que
$
bar.v.double (x, y) bar.v.double = (bar.v 0 bar.v ^p + bar.v 0 bar.v^p)^(1/p) = 0
$
si $x,y = 0$. Además,
$
bar.v.double (alpha x, alpha y) bar.v.double &= (bar.v alpha x bar.v ^p + bar.v alpha y bar.v^p)^(1/p) \
&= (bar.v alpha bar.v ^p bar.v x bar.v^p + bar.v alpha bar.v ^p bar.v y bar.v^p)^(1/p) \
&= bar.v alpha bar.v (bar.v x bar.v^p + bar.v y bar.v^p)^(1/p) \
&= bar.v alpha bar.v dot bar.v.double (x,y) bar.v.double
$
Y para la desigualdad del triángulo se tiene que
$
bar.v.double (x_1 + x_2, y_1 + y_2) bar.v.double &= (bar.v x_1 + x_2 bar.v^p + bar.v y_1 + y_2 bar.v ^p)^(1/p) \
& lt.eq (bar.v x_1 bar.v^p + bar.v x_2 bar.v ^p)^(1/p) + (bar.v y_1 bar.v^p + bar.v y_2 bar.v ^p)^(1/p) \
& = bar.v.double (x_1,y_1) bar.v.double + bar.v.double (x_2,y_2) bar.v.double
$
Donde la desigualdad se da por la #text(fill: rgb("#300CA4"))[Desigualdad de Minkowski.] Ahora, para probar que $d((x,y),(r,s)) = (bar.v x - r bar.v^p + bar.v y - s bar.v^p)^(1/p)$ es métrica, notemos que
$
d((x,y),(r,s)) = 0 arrow.l.r.double.long (bar.v x - r bar.v^p + bar.v y - s bar.v^p)^(1/p) = 0 arrow.l.r.double.long x = r #h(.3cm) #text(font: "Times New Roman")[y] #h(.3cm) y = s
$
Luego,
$
d((x,y),(r,s)) &= (bar.v x - r bar.v^p + bar.v y - s bar.v^p)^(1/p) \
&= (bar.v r - x bar.v^p + bar.v s - y bar.v^p)^(1/p) \
&= d((r,s),(x,y))
$
Y finalmente,
$
d((x,y),(r,s)) &= (bar.v x - r bar.v^p + bar.v y - s bar.v^p)^(1/p) \
& lt.eq (bar.v x - u bar.v^p + bar.v y - v bar.v^p)^(1/p) + (bar.v u - r bar.v^p + bar.v v - s bar.v^p)^(1/p) \
&= d((x,y),(u,v)) + d((u,v),(r,s))
$
Donde la desigualdad se da, nuevamente por la #text(fill: rgb("#300CA4"))[Desigualdad de Minkowski.] y operaciones aitméticas en $RR$. \
Por lo tanto, $bar.v.double (x,y) bar.v.double$ es una norma y $d((x,y),(r,s))$ es una métrica en $RR^2$.
#align(right)[$qed$]
6. Sea $(E, bar.v.double bar.v.double)$ un espacio normado y sea $B(x_0,1) := {x in E: bar.v.double x bar.v.double < 1 }$.
#enum(
numbering: "a)",
indent: .5cm,
[Demuestra que $B(x_0,1)$ es un conjunto convexo; es decir que si $x,y in B(x_0, 1)$, entonces $t x + (1-t)y in B(x_0,1)$ para todo $0<t<1$.],
[Demuestra que el conjunto de todas las métricas definidas en un conjunto $X$ es un conjunto convexo.]
)
_Demostración._ \
a). Sean $x, y in B(x_0,1)$, entonces, por definición, $bar.v.double x bar.v.double < 1$ y $bar.v.double y bar.v.double < 1$. \
Queremos demostrar que $bar.v.double t x + (1-t)y bar.v.double < 1$ para todo $0 < t < 1 $. Entonces notemos que
$
bar.v.double t x + (1-t)y bar.v.double lt.eq bar.v.double t x bar.v.double + bar.v.double (1-t)y bar.v.double = t bar.v.double x bar.v.double + (1-t)bar.v.double y bar.v.double
$
Y dado que $bar.v.double x bar.v.double < 1$ y $bar.v.double y bar.v.double < 1$, podemos escribir $bar.v.double x bar.v.double lt.eq a$ y $bar.v.double y bar.v.double lt.eq b$ con $a,b < 1$. Entonces
$
bar.v.double t x + (1-t)y bar.v.double lt.eq bar.v.double t a + (1-t)b bar.v.double < bar.v.double t 1 + (1-t)1 bar.v.double = bar.v.double 1 bar.v.double = 1 \
arrow.double.long bar.v.double t x + (1-t)y bar.v.double < 1 \
therefore t x + (1-t)y in B(x_0,1)
$
#align(right)[$square.stroked$]
b). Sea $cal(M)$ el conjunto de todas las métricas definidas en un conjunto $X$. Debemos demostrar que si $d_1$ y $d_2$ son métricas en $X$, entonces $d_t = t d_1 + (1-t)d_2$ para $0 < t < 1$ es también una métrica en X. Así, observemos que
$
d_t (x,y) = t d_1 (x,y) + (1-t)d_2 (x,y) gt.eq 0
$
ya que $d_1 (x,y) gt.eq 0$ y $d_2 (x,y) gt.eq 0$. \
Luego,
$
d_t (x,y) = 0 & arrow.l.r.double.long t d_1 (x,y) + (1-t)d_2 (x,y) = 0 \
& arrow.long.double d_1(x,y) = 0 #h(.3cm) #text(font: "Times New Roman")[y] #h(.3cm) d_2(x,y) = 0
$
Lo cual es cierto siempre que $x = y$, pues $d_1$ y $d_2$ son métricas. \
Ahora,
$
d_t (x,y) = t d_1 (x,y) + (1-t)d_2 (x,y) = t d_1 (y,x) + (1-t)d_2 (y,x) = d_t (y,x) \
arrow.long.double d_t (x,y) = d_t (y,x)
$
Y finalmente,
$
d_t (x,z) &= t d_1 (x,z) + (1-t)d_2 (x,z) \
& lt.eq t (d_1 (x,y) + d_1 (y,z)) + (1-t)(d_2 (x,y) + d_2 (y,z)) \
& = t d_1 (x,y) + t d_1 (y,z) + (1-t)d_2 (x,y) + (1-t)d_2 (y,z) \
& = (t d_1 (x,y) + (1-t)d_2 (x,y)) + (t d_1 (y,z) + (1-t)d_2 (y,z)) \
& = d_t (x,y) + d_t (y,z) \
& arrow.long.double d_t (x,z) lt.eq d_t (x,y) + d_t (y,z)
$
Así, $d_t$ cumple las tres propiedades para ser métrica en $X$, por lo tanto, hemos demostrado que el conjunto $cal(M)$ es un conjunto convexo.
#align(right)[$qed$]
7. Demuestra el siguiente resultado. Sea ${x_n} subset RR$, con $x_(2n) lt.eq x_(2n+2) lt.eq x_(2n+1) lt.eq x_(2n-1)$ para toda $n in NN$ y $op("lim", limits: #true)_(n -> infinity) (x_(2n-1) - x_(2n)) = 0$. Entonces ${x_n}$ converge a alguna $x in RR$ y $x_(2n) lt.eq x lt.eq x_(2n-1)$ para toda $n in NN$. Después usa ese resultado para probar que la siguiente sucesión:
$
{a_n} = cases(
a_1 = 1,
a_(n+1) = frac(1,1+a_n)
)
$
Converge a $frac(1,2)(sqrt(5)-1)$.
8. Para toda $n in NN$, sean $a_n = (1 + frac(1,n))^n$ y $b_n = (1 + frac(1,n))^(n+1)$, verifica que
#enum(
numbering: "a)",
indent: .5cm,
[${a_n}$ es estrictamente creciente.],
[${b_n}$ es estrictamente decreciente.],
[$op("lim", limits: #true)_(n -> infinity) a_n$ $=$ $op("lim", limits: #true)_(n -> infinity) b_n$ el límite de estas dos sucesiones es denotado por $e$. Tenemos que $2 < e < 4$.]
)
_Solución._ \
a). Consideremos $frac(a_(n+1), a_n) = frac((1+frac(1,n+1))^(n+1), (1 + frac(1,n))^n)$ y notemos que
$
ln(frac(a_(n+1), a_n)) &= ln((1+frac(1,n+1))^(n+1)) - ln((1 + frac(1,n))^n) \
&= (n+1)ln(1 + frac(1,n+1)) - n ln(1+frac(1,n))
$
Y por la expansión de Taylor respecto al logaritmo natural $ln(1+x) approx x - frac(x^2,2) + O(x^3)$ nos queda que
$
ln(1 + frac(1,n+1)) & approx frac(1,n+1) - frac(1, 2(n+1)^2) \
ln(1 + frac(1,n)) & approx frac(1,n) - frac(1, 2n^2)
$
Entonces
$
(n+1)ln(1 + frac(1,n+1)) - n ln(1+frac(1,n)) &= (n+1)(frac(1,n+1) - frac(1, 2(n+1)^2)) - n (frac(1,n) - frac(1, 2n^2)) \
&= 1 - frac(1,2(n+1)^2) -1 + frac(1,2n) \
&= frac(1,2n) - frac(1,2(n+1))
$
Finalmente,
$
frac(1,2n) - frac(1,2(n+1)) > 0 arrow.r.double.long ln(frac(a_(n+1), a_n)) > 0 arrow.r.double.long frac(a_(n+1), a_n) > 0 \
$
$therefore {a_n}$ es estrictamente creciente.
#align(right)[$square.stroked$]
b). Consideremos $frac(b_n, b_(n+1)) = frac((1+frac(1,n))^(n+1), (1 + frac(1,n+1))^(n+2))$ y notemos que
$
ln(frac(b_n, b_(n+1))) &= (n+1)ln(1+frac(1,n)) - (n+2) ln(1+frac(1,n+1))
$
Y por la expansión de Taylor mencionada previamente,
$
ln(1 + frac(1,n)) & approx frac(1,n) - frac(1, 2n^2) \
ln(1 + frac(1,n+1)) & approx frac(1,n+1) - frac(1, 2(n+1)^2)
$
Entonces
$
(n+1)ln(1+frac(1,n)) - (n+2) ln(1+frac(1,n+1)) &= (n+1)(frac(1,n) - frac(1, 2n^2)) - (n+2) (frac(1,n+1) - frac(1, 2(n+1)^2)) \
&= (1 + frac(1,n) - frac(n+1,2n^2)) - (1 + frac(1,n+1) - frac(n+2,2(n+1)^2)) \
&= frac(1,n) - frac(1,n+1) - frac(n+1, 2n^2) + frac(n+2,2(n+1)^2) \
&= frac(1,n) - frac(1,n+1) - (frac(n+1, 2n^2) - frac(n+2,2(n+1)^2))
$
Luego,
$
frac(1,n) - frac(1,n+1) > 0
$
Y $(frac(n+1, 2n^2) - frac(n+2,2(n+1)^2))$ es siempre negativa, en particular decreciente, afectada por la diferencia con $(frac(1,n) - frac(1,n+1))$, por lo que $ln(frac(b_n, b_(n+1))) > 0$, entonces $frac(b_n, b_(n+1)) > 0$ y por lo tanto, ${b_n}$ es estrictamente decreciente. \
#align(right)[$square.stroked$]
c). Consideremos a la sucesión $b_n = (1+ frac(1,n))^(n+1)$. Podemos reescribir a $b_n$ en términos de la sucesión $a_n$ como:
$
b_n = (1+ frac(1,n))^(n+1) = (1+ frac(1,n))^(n) (1+ frac(1,n))
$
Y se sabe que
$
op("lim", limits: #true)_(n -> infinity) (1 + frac(1,n))^n = e
$
Por otro lado,
$
op("lim", limits: #true)_(n -> infinity) (1 + frac(1,n)) = 1
$
Entonces,
$
b_n = (1+ frac(1,n))^(n) (1+ frac(1,n)) = e dot 1 = e \ \ \
therefore op("lim", limits: #true)_(n -> infinity) a_n = op("lim", limits: #true)_(n -> infinity) b_n
$
#align(right)[$qed$]
9. Sea $a,z in CC$. Entonces la serie $sum_(n=0) ^infinity a dot z^n$ converge y su suma es $frac(a,1-z)$ si $bar.v.double z bar.v.double < 1$. Si $a eq.not 0$ y $ bar.v.double z bar.v.double gt.eq 1$, entonces esta serie diverge.
_Demostración._ \
Primero notemos que
$
sum_(n=0) ^infinity z^n &= op("lim", limits: #true)_(n -> infinity) sum_(k=0) ^n z^k \
&= op("lim", limits: #true)_(n -> infinity) (frac(1-z^(n+1),1-z)) \
&= op("lim", limits: #true)_(n -> infinity) (frac(1,1-z) - frac(z^(n+1),1-z)) \
&= frac(1,1-z) - (frac(z,1-z) op("lim", limits: #true)_(n -> infinity) z^n)
$
De donde, si tenemos que $bar.v.double z bar.v.double < 1$, entonces $op("lim", limits: #true)_(n -> infinity) z^n = 0$, de modo que
$
sum_(n=0) ^infinity z^n = frac(1,1-z) & arrow.long.double a sum_(n=0) ^infinity z^n = a frac(1,1-z) \
therefore sum_(n=0) ^infinity a z^n &= frac(a,1-z) #h(.4cm) #text(font: "Times New Roman")[para] #h(.4cm) bar.v.double z bar.v.double < 1
$
Ahora, si $op("lim", limits: #true)_(n -> infinity) z^n = infinity$ dado que $bar.v.double z bar.v.double gt.eq 1$ y $a eq.not 0$, tendría que suceder lo siguiente:
$
sum_(n=0) ^infinity z^n &= op("lim", limits: #true)_(n -> infinity) sum_(k=0) ^n z^k \
&= op("lim", limits: #true)_(n -> infinity) sum_(k=0) ^n frac(1-z^(n+1),1-z) \
&=infinity
$
Es decir que $sum_(n=0) ^infinity a z^n$ diverge.
#align(right)[$qed$]
10. Sea $b > 1$ y $b in NN$ y sea ${x_j}_(j=1) ^infinity$ una sucesión de naturales con $0 lt.eq x_j < b$ para toda $j$. Entonces la serie $sum_(j=1) ^infinity x_j b^(-j)$ converge y su suma $x$ satisface que $0 lt.eq x lt.eq 1$.
11. Sea $p in NN$, $a in [0, infinity)$ y ${a_n}_(n=1) ^infinity subset [0,infinity)$. Entonces $op("lim", limits: #true)_(n -> infinity) root(p,a_n) = root(p,a)$ si y sólo si $op("lim", limits: #true)_(n -> infinity) a_n = a$.
_Demostración._\
$arrow.l.double ]$. Sea $epsilon > 0$. Dado que $op("lim", limits: #true)_(n -> infinity) a_n = a$, entonces existe un $N in NN$ tal que para todo $n gt.eq N$, se cumple que $bar.v a_n - a bar.v < epsilon$. \
Consideremos $a > 0$, se tiene que
$
bar.v (a_n)^(1/p) - a^(1/p) bar.v = bar.v ((a + (a_n - a))^(1/p) - a^(1/p)) bar.v < epsilon
$
lo cual implica que para $epsilon > 0$, existe $N$ tal que para $n gt.eq N$, $bar.v (a_n)^(1/p) - a^(1/p) bar.v < epsilon$. \
El caso en donde $a = 0$ es simple;
$
op("lim", limits: #true)_(n -> infinity) a_n = 0
$
lo cual implica la definición de que $forall epsilon > 0, exists N in NN$ tal que $forall n gt.eq N, 0 lt.eq a_n < epsilon$. Entonces para $n in NN$, $(a_n)^(1/p) < epsilon ^(1/p)$. Por lo tanto, $op("lim", limits: #true)_(n -> infinity) root(p,a_n) = root(p,a)$. \
$arrow.r.double ]$. Sea $epsilon > 0$, para $a > 0$ tenemos que
$
op("lim", limits: #true)_(n -> infinity) (root(p,a_n))^p = (a^(1/p))^p arrow.r.long.double op("lim", limits: #true)_(n -> infinity) a_n = a
$
Para $a=0$,
$
op("lim", limits: #true)_(n -> infinity) (root(p,a_n))^p = 0
$
lo cual implica la definición de que $forall epsilon > 0, exists N in NN$ tal que $forall n gt.eq N, 0 lt.eq (a_n)^(1/p) < epsilon$. Entonces $a_n < epsilon_1 = epsilon^p$.
$
therefore op("lim", limits: #true)_(n -> infinity) root(p,a_n) = root(p,a) arrow.l.r.double.long op("lim", limits: #true)_(n -> infinity) a_n = a
$
#align(right)[$qed$]
12. Evalúa
#enum(
numbering: "a)",
indent: .5cm,
[$op("lim", limits: #true)_(n -> infinity) sqrt(n^2 + 2n) -n$ #v(.3cm)],
[$op("lim", limits: #true)_(n -> infinity) frac(2^n + n, 3^n - n)$ #v(.3cm)],
[$op("lim", limits: #true)_(n -> infinity) frac(2^n^2 + 1, sqrt(n^4 + n^3))$]
)
_Solución._ \
a)
$
op("lim", limits: #true)_(n -> infinity) sqrt(n^2 + 2n) -n &= op("lim", limits: #true)_(n -> infinity) sqrt(n^2 + 2n) -n (frac(sqrt(n^2 + 2n) +n,sqrt(n^2 + 2n) +n)) \
&= op("lim", limits: #true)_(n -> infinity)frac(n^2 + 2n + n sqrt(n^2 + 2n) -n sqrt(n^2 + 2n) - n^2,sqrt(n^2 + 2n) +n) \
&= op("lim", limits: #true)_(n -> infinity) frac(2n,sqrt(n^2 + 2n) +n) \
&= 2 op("lim", limits: #true)_(n -> infinity) frac(n,sqrt(n^2 + 2n) +n)
$
$
&= 2 op("lim", limits: #true)_(n -> infinity) frac(frac(n,n),frac(sqrt(n^2 + 2n),n) +frac(n,n)) \
&= 2 op("lim", limits: #true)_(n -> infinity) frac(1,frac(sqrt(n^2(1 + 2(frac(1,n)))),n) +1) \
&= 2 op("lim", limits: #true)_(n -> infinity) frac(1,sqrt(1 + 2(frac(1,n))) +1) \
&= 2 frac(1,sqrt(1) +1) \
&= 1
$
b)
$
op("lim", limits: #true)_(n -> infinity) frac(2^n + n, 3^n - n) &= op("lim", limits: #true)_(n -> infinity) frac(frac(2^n + n,3^n), frac(3^n - n,3^n)) \
&= op("lim", limits: #true)_(n -> infinity) frac((frac(2,3))^n + frac(n,3^n), 1 - frac(n,3^n)) \
&= op("lim", limits: #true)_(n -> infinity) frac((frac(2,3))^n + n(frac(1,3))^n, 1 - n (frac(1,3))^n) \
&= frac(0+0,1+0) \
&= 0
$
c)
$
op("lim", limits: #true)_(n -> infinity) frac(2^n^2 + 1, sqrt(n^4 + n^3)) &= op("lim", limits: #true)_(n -> infinity) frac(frac(2^n^2,2^n^2) + frac(1,2^n^2), frac(sqrt(n^4 + n^3), 2^n^2)) \
&= op("lim", limits: #true)_(n -> infinity) frac(1 + (frac(1,2))^(n^2), (frac(1,2))^n^2 sqrt(n^2(n^2 + n))) \
&= op("lim", limits: #true)_(n -> infinity) frac(1 + (frac(1,2))^(n^2), (frac(1,2))^n^2 n sqrt(n^2(1 + frac(1,n)))) \
&= op("lim", limits: #true)_(n -> infinity) frac(1 + (frac(1,2))^(n^2), (frac(1,2))^n^2 n^2 sqrt(1 + frac(1,n)))
$
Aquí notemos que $op("lim", limits: #true)_(n -> infinity) n^2 sqrt(1 + frac(1,n)) = infinity$ y $op("lim", limits: #true)_(n -> infinity) x^n$ para $bar.v x bar.v < 1$ es igual a $0$, entonces
$
op("lim", limits: #true)_(n -> infinity) frac(1 + (frac(1,2))^(n^2), (frac(1,2))^n^2 n^2 sqrt(1 + frac(1,n))) = frac(1+0,0+0) = infinity
$
Por lo tanto esta sucesión diverge.
13. Sea $0 < a < b < infinity$. Define $x_1 = a, x_2 = b, x_(n+2) = frac(1,2) (x_n + x_(n+1))$. Determine si ${x_n}$ converge y de ser así, calcule su límite.
_Solución._ \
Definimos #h(.2cm) $y_(n) &= x_(2n-1)$ #h(.1cm) y #h(.1cm) $z_(n) = x_(2n)$.#h(.1cm) Entonces tenemos que
$
y_(n+1) &= x_(2(n+1)-1) \
&= x_(2n+1) \
&= frac(1,2)(x_(2n-1) + x_(2n)) \
&= frac(1,2)(y_(n) + z_n)
$
Y por otro lado,
$
z_(n+1) &= x_(2(n+1)) \
&= x_(2n + 2) \
&= frac(1,2)(x_(2n) + x_(2n+1)) \
&= frac(1,2)(z_(n) + frac(1,2)(y_n + z_n)) \
&= frac(1,2)(z_(n) + frac(1,2)y_n + frac(1,2)z_n) \
&= frac(1,2)z_(n) + frac(1,4)y_n + frac(1,4)z_n \
&= frac(3,4)z_(n) + frac(1,4)y_n
$
Entonces
$
y_(n+1) &= frac(1,2)(y_(n) + z_n) \
z_(n+1) &= frac(1,2)(frac(3,2)z_(n) + frac(1,2)y_n)
$
De modo que tanto $y_n$ como $z_n$ son medias ponderadas de los términos anteriores, lo que sugiere que las diferencias entre términos consecutivos disminuye en $n$ y la relación entre $y_(n+1)$ y $z_(n+1)$ asegura que la sucesión promedie valores.
Para el límite, supongamos que $y_n$ y $z_n$ tienden a $L$ cuando $n$ tiende a infinito, entonces
$
L = frac(1,2)(L + L) = L
$
Y
$
L = frac(3,4)L + frac(1,4)L = L
$
Como ambas expresiones son válidas y consistentes, la sucesión ${x_n}$ debe converger a un único valor $L$, y notemos que las ${y_n}$ y las ${z_n}$ deben promediar los valores iniciales en cada paso, a saber, los valores $a$ y $b$, entonces
$
L = frac(a+b,2) \
therefore {x_n} arrow frac(a+b,2)
$
#align(right)[$qed$]
15. Si ${a_n}_(n=1)^infinity subset RR$ y ${b_n}_(n=1)^infinity subset (0, infinity)$ y ${frac(a_n,b_n)}_(n=1) ^infinity$ es monótona, entonces la sucesión ${c_n}_(n=1)^infinity$ definida como $c_n = frac((a_1 + ... + a_n),b_1 + ... + b_n)$, es también monótona.
Sugerencia: Si $frac(a,b) lt.eq frac(c,d)$, entonces $frac(a,b) lt.eq frac(a+c,b+d) lt.eq frac(c,d)$. \
_Demostración._ \
Analicemos que ocurre cuando la sucesión es creciente; para $n in NN$, $a_(n+1) gt.eq a_n$, entonces, dados $a_1 lt.eq a_2$ y $b_1 lt.eq b_2$, se tiene que
$
frac(a_1,b_1) lt.eq frac(a_2,b_2) & arrow.long.double frac(a_1,b_1) lt.eq frac(a_1 + a_2,b_1 + b_2) lt.eq frac(a_2,b_2) \
& arrow.long.double frac(a_2,b_2) lt.eq frac(a_2 + a_3,b_2 + b_3) lt.eq frac(a_3,b_3) \
& arrow.long.double frac(a_1,b_1) lt.eq frac(a_1 + a_2 + a_3,b_1 + b_2 + b_3) lt.eq frac(a_3,b_3) \
& arrow.long.double frac(a_1,b_1) lt.eq frac(a_1 + a_2,b_1 + b_2) lt.eq frac(a_1 + a_2 + a_3,b_1 + b_2 + b_3) lt.eq frac(a_2, b_2) lt.eq frac(a_3,b_3)
$
Entonces,
$
frac(a_1,b_1) lt.eq underbrace(frac(a_1 + ... + a_n, b_1 + ... + b_n), c_n) lt.eq underbrace(frac(a_1 + ... + a_(n+1),b_1 + ... + b_(n+1)), c_(n+1)) lt.eq frac(a_n, b_n) lt.eq frac(a_(n+1),b_(n+1))
$
Por lo que ${c_n}_(n=1)^infinity$ es monótona creciente. \
Ahora, cuando la sucesión es decreciente; $a_(n+1) lt.eq a_n$, entonces, análogamente al caso creciente,
$
frac(a_1,b_1) gt.eq frac(a_2,b_2) & arrow.long.double frac(a_1,b_1) gt.eq frac(a_1 + a_2,b_1 + b_2) gt.eq frac(a_2,b_2) \
& arrow.long.double frac(a_2,b_2) gt.eq frac(a_2 + a_3,b_2 + b_3) gt.eq frac(a_3,b_3) \
& arrow.long.double frac(a_1,b_1) gt.eq frac(a_1 + a_2 + a_3,b_1 + b_2 + b_3) gt.eq frac(a_3,b_3) \
& arrow.long.double frac(a_1,b_1) gt.eq frac(a_1 + a_2,b_1 + b_2) gt.eq frac(a_1 + a_2 + a_3,b_1 + b_2 + b_3) gt.eq frac(a_2, b_2) gt.eq frac(a_3,b_3)
$
Entonces,
$
frac(a_1,b_1) gt.eq underbrace(frac(a_1 + ... + a_n, b_1 + ... + b_n), c_n) gt.eq underbrace(frac(a_1 + ... + a_(n+1),b_1 + ... + b_(n+1)), c_(n+1)) gt.eq frac(a_n, b_n) gt.eq frac(a_(n+1),b_(n+1))
$
Por lo que ${c_n}_(n=1)^infinity$ es monótona decreciente. \
#align(right)[$qed$] |
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/content-field.typ | typst | Apache License 2.0 | // Integrated test for content fields.
#let compute(equation, ..vars) = {
let vars = vars.named()
let f(elem) = {
let func = elem.func()
if func == text {
let text = elem.text
if regex("^\d+$") in text {
int(text)
} else if text in vars {
int(vars.at(text))
} else {
panic("unknown math variable: " + text)
}
} else if func == math.attach {
let value = f(elem.base)
if elem.has("t") {
value = calc.pow(value, f(elem.t))
}
value
} else if elem.has("children") {
elem
.children
.filter(v => v != [ ])
.split[+]
.map(xs => xs.fold(1, (prod, v) => prod * f(v)))
.fold(0, (sum, v) => sum + v)
}
}
let result = f(equation.body)
[With ]
vars
.pairs()
.map(p => $#p.first() = #p.last()$)
.join(", ", last: " and ")
[ we have:]
$ equation = result $
}
#compute($x y + y^2$, x: 2, y: 3)
|
https://github.com/RoyalRoppers/stadgar | https://raw.githubusercontent.com/RoyalRoppers/stadgar/master/template.typ | typst | #let template(body) = {
set document(title: "RoyalRoppers stadgar")
set page(numbering: "1", number-align: center, margin: 4cm)
set text(font: "Linux Libertine", lang: "sv", hyphenate: false, size: 12pt)
set heading(numbering: sym.section + " 1.1")
set ref(supplement: sym.section)
set list(indent: 1em)
show par: set block(below: 1.2em)
show heading: set block(above: 1.4em, below: 1em)
v(1fr)
block(text(2em, weight: 700, [
RoyalRoppers stadgar
]))
text([
Org. nr.: 802539-6931 \
3 december 2022
])
v(7cm)
pagebreak()
outline(title: "Innehåll", indent: true, fill: none)
pagebreak()
set par(justify: true)
body
}
|
|
https://github.com/Readon/NSFC-application-template-typst | https://raw.githubusercontent.com/Readon/NSFC-application-template-typst/main/template.typ | typst | MIT License | #import "@preview/cuti:0.2.1": show-cn-fakebold, show-fakebold
#let custom-numbering(base: 1, depth: 5, first-level: auto, second-level: auto, third-level: auto, format, ..args) = {
if (args.pos().len() > depth) {
return
}
if (first-level != auto and args.pos().len() == 1) {
if (first-level != "") {
numbering(first-level, ..args)
}
return
}
if (second-level != auto and args.pos().len() == 2) {
if (second-level != "") {
numbering(second-level, args.pos().at(1))
}
return
}
if (third-level != auto and args.pos().len() == 3) {
if (third-level != "") {
numbering(third-level, ..args)
}
return
}
// default
if (args.pos().len() >= base) {
numbering(format, ..(args.pos().slice(base - 1)))
return
}
}
// This function gets your whole document as its `body` and formats
// it as a simple fiction book.
#let proposal(
body,
) = {
show: show-cn-fakebold
let title = [报告正文]
let headsize = 14pt
let headfont = "KaiTi"
let headcolor = rgb("#0070c0")
set document(title: title)
set text(12pt, font: ("Times New Roman", "SongTi"), lang: "zh", region: "cn")
set page(
paper: "a4",
margin: (bottom: 2.5cm, top: 2.78cm, left: 3cm, right: 3cm),
)
set par(leading: 1em, first-line-indent: 2em, justify: true)
show par: set block(spacing: 1.2em)
// Configure chapter headings.
set heading(numbering: custom-numbering.with(base: 2, first-level: "(一)", second-level: "1. ", depth: 5, "1.1"))
show heading.where(level: 1): it => {
show: show-fakebold
set text(headsize, font: headfont, weight: "bold", fill: headcolor)
set par(first-line-indent: 21pt, justify: true)
show par: set block(above: 18.2pt, below: 18.4pt)
[#counter(heading).display()#it.body]
}
show heading.where(level: 2): it => {
set text(headsize, font: headfont, weight: "medium", fill: headcolor)
set par(leading: 12.4pt, first-line-indent: 27.5pt, justify: true)
show par: set block(above: 12.6pt, below: 0.2pt)
[#counter(heading).display()#it.body]
}
{
set text(headsize, font: headfont)
{
set text(15.5pt, font: headfont, weight: "bold")
set align(center)
// show par: set block(above: 8pt)
v(-1pt)
[*#title*]
}
set par(leading: 13pt, first-line-indent: 28pt, justify: true)
show par: set block(above: 16.5pt)
[参照以下提纲撰写,要求内容翔实、清晰,层次分明,标题突出。]
text(weight: "bold", fill: headcolor, [请勿删除或改动下述提纲标题及括号中的文字。])
}
set text(11.8pt, font: ("Times New Roman", "SongTi"), lang: "zh", region: "cn")
set par(leading: 14.5pt, first-line-indent: 24pt, justify: true)
show par: set block(spacing: 1em, above: 14.2pt)
body
}
|
https://github.com/jamesrswift/chemicoms-paper | https://raw.githubusercontent.com/jamesrswift/chemicoms-paper/main/src/elements/header-journal.typ | typst | #let header-journal(args) = {
block(
inset: 0.2cm,
width:100%,
{
text(28pt, args.at("venue", default: none))
h(1fr)
text(28pt, args.header.article-meta)
}
)
} |
|
https://github.com/5eqn/osa-fp-talk | https://raw.githubusercontent.com/5eqn/osa-fp-talk/main/template.typ | typst | // color profiles
#let colors = (
gray: luma(238),
blue: rgb(240, 240, 250),
red: rgb(255, 240, 240),
)
#let tag(body, color: "gray") = {
set text(font: ("Noto Sans CJK SC"), 10pt)
box(
fill: colors.at(color),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
body
)
}
#let sect(body, color: "gray", title: "") = {
if title == "" {
box(
width: 100%,
fill: colors.at(color),
radius: 3pt,
inset: 1em,
body
)
} else {
set heading(numbering: none, outlined: false, supplement: "Box")
box(
width: 100%,
fill: colors.at(color),
radius: 3pt,
inset: 1em,
)[
=== #title
#body
]
}
}
#let project(
title: "",
authors: (),
body,
) = {
set document(author: authors, title: title)
set page(numbering: "1", number-align: center)
set text(font: ("Noto Serif CJK SC"), size: 15pt)
align(center)[
#block(text(weight: 700, 1.75em, title))
#v(1em, weak: true)
]
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, strong(author))),
),
)
set par(justify: true, leading: 0.75em)
show heading: it => {
set block(above: 1em, below: 1em)
it
}
body
}
|
|
https://github.com/daskol/typst-templates | https://raw.githubusercontent.com/daskol/typst-templates/main/iclr/main.typ | typst | MIT License | #import "/logo.typ": LaTeX, LaTeXe
#import "/iclr2025.typ": iclr2025
#let author-note = footnote[
Use footnote for providing further information about author (webpage,
Alternative address) --- *not* for acknowledging funding agencies. Funding
Acknowledgements go at the end of the paper.
]
/**
* Authors should be specified as a list of entries. Each entry enumerates
* authors with the same affilation and address. Field `names` is mandatory.
*/
#let authors = (
(
names: ([<NAME>], [<NAME>],
[<NAME>#author-note]),
affilation: [
Department of Computer Science \
Cranberry-Lemon University
],
address: [Pittsburgh, PA 15213, USA],
email: "{<EMAIL>,<EMAIL>",
),
(
names: ([<NAME>], [<NAME>]),
affilation: [
Department of Computational Neuroscience \
University of the Witwatersrand
],
address: [Joburg, South Africa],
email: "{<EMAIL>",
),
(
names: ([Coauthor], ),
affilation: [Affiliation],
address: [Address],
email: "<EMAIL>",
)
)
#show: iclr2025.with(
title: [Formatting Instructions for ICLR 2025\ Conference Submissions],
authors: authors,
keywords: (),
abstract: [
The abstract paragraph should be indented 1/2~inch (3~picas) on both left
and right-hand margins. Use 10~point type, with a vertical spacing of
11~points. The word #smallcaps[Abstract] must be centered, in small caps,
and in point size 12. Two line spaces precede the abstract. The abstract
must be limited to one paragraph.
],
bibliography: bibliography("main.bib"),
appendix: [
= Appendix
You may include other additional sections here.
],
accepted: false,
)
#let url(uri) = link(uri, raw(uri))
= Submission of conference papers to ICLR 2025
ICLR requires electronic submissions, processed by
#url("https://openreview.net/"). See ICLR's website for more instructions.
If your paper is ultimately accepted, the statement `\iclrfinalcopy` should be
inserted to adjust the format to the camera ready requirements.
The format for the submissions is a variant of the NeurIPS format. Please read
carefully the instructions below, and follow them faithfully.
== Style
Papers to be submitted to ICLR 2025 must be prepared according to the
instructions presented here.
Authors are required to use the ICLR #LaTeX style files obtainable at the ICLR
website. Please make sure you use the current files and not previous versions.
Tweaking the style files may be grounds for rejection.
== Retrieval of style files
The style files for ICLR and other conference information are available online
at:
#block(width: 100%, spacing: 13.5pt, {
set align(center)
url("https://www.iclr.cc/")
})
The file `iclr2025_conference.pdf` contains these instructions and illustrates
the various formatting requirements your ICLR paper must satisfy. Submissions
must be made using #LaTeX and the style files `iclr2025_conference.sty` and
`iclr2025_conference.bst` (to be used with #LaTeXe). The file
`iclr2025_conference.tex` may be used as a "shell" for writing your paper. All
you have to do is replace the author, title, abstract, and text of the paper
with your own.
The formatting instructions contained in these style files are summarized in
sections #ref(<gen_inst>, supplement: none), #ref(<headings>, supplement:
none), and #ref(<others>, supplement: none) below.
#v(-3pt) // Reduce spacing manually because of LaTeX/LaTeXe ligatures.
= General formatting instructions <gen_inst>
The text must be confined within a rectangle 5.5~inches (33~picas) wide and
9~inches (54~picas) long. The left margin is 1.5~inch (9~picas). Use 10~point
type with a vertical spacing of 11~points. Times New Roman is the preferred
typeface throughout. Paragraphs are separated by 1/2~line space, with no
indentation.
Paper title is 17~point, in small caps and left-aligned. All pages should start
at 1~inch (6~picas) from the top of the page.
Authors' names are set in boldface, and each name is placed above its
corresponding address. The lead author's name is to be listed first, and the
co-authors' names are set to follow. Authors sharing the same address can be on
the same line.
Please pay special attention to the instructions in @others regarding figures,
tables, acknowledgments, and references.
There will be a strict upper limit of 10 pages for the main text of the initial
submission, with unlimited additional pages for citations.
= Headings: first level <headings>
First level headings are in small caps, flush left and in point size 12. One
line space before the first level heading and 1/2~line space after the first
level heading.
== Headings: second level
Second level headings are in small caps, flush left and in point size 10. One
line space before the second level heading and 1/2~line space after the second
level heading.
=== Headings: third level
Third level headings are in small caps, flush left and in point size 10. One
line space before the third level heading and 1/2~line space after the third
level heading.
= Citations, figures, tables, references <others>
These instructions apply to everyone, regardless of the formatter being used.
== Citations within the text
Citations within the text should be based on the `natbib` package and include
the authors' last names and year (with the "et~al." construct for more than two
authors). When the authors or the publication are included in the sentence, the
citation should not be in parenthesis using `\citet{}` (as in "See
#cite(<Hinton06>, form: "prose") for more information."). Otherwise, the
citation should be in parenthesis using `\citep{}` (as in "Deep learning shows
promise to make progress towards AI~@Bengio_chapter2007.").
The corresponding references are to be listed in alphabetical order of authors,
in the #smallcaps[References] section. As to the format of the references
themselves, any style is acceptable as long as it is used consistently.
== Footnotes
Indicate footnotes with a number#footnote[Sample of the first footnote] in the
text. Place the footnotes at the bottom of the page on which they appear.
Precede the footnote with a horizontal rule of 2~inches
(12~picas).#footnote[Sample of the second footnote]
== Figures
All artwork must be neat, clean, and legible. Lines should be dark enough for
purposes of reproduction; art work should not be hand-drawn. The figure number
and caption always appear after the figure. Place one line space before the
figure caption, and one line space after the figure. The figure caption is
lower case (except for first word and proper nouns); figures are numbered
consecutively.
Make sure the figure caption does not get separated from the figure. Leave
sufficient space to avoid splitting the figure and figure caption.
You may use color figures. However, it is best for the figure captions and the
paper body to make sense if the paper is printed either in black/white or in
color.
#figure(
caption: [Sample figure caption.],
rect(width: 4.25cm, height: 4.25cm, stroke: 0.4pt),
)
== Tables
All tables must be centered, neat, clean and legible. Do not use hand-drawn
tables. The table number and title always appear before the table. See
@sample-table.
Place one line space before the table title, one line space after the table
title, and one line space after the table. The table title must be lower case
(except for first word and proper nouns); tables are numbered consecutively.
#figure(
caption: [Sample table title],
placement: top,
table(
columns: 2,
stroke: none,
table.header([*NAME*], [*DESCRIPTION*]),
table.hline(),
[Dendrite], [Input terminal ],
[Axon ], [Output terminal],
[Soma ], [Cell body (contains cell nucleus)],
)
) <sample-table>
= Default Notation
In an attempt to encourage standardized notation, we have included the notation
file from the textbook, _Deep Learning_ @goodfellow2016deep available at
#url("https://github.com/goodfeli/dlbook_notation/"). Use of this style is not
required and can be disabled by commenting out `math_commands.tex`.
#v(4em, weak: true)
#align(center, [*Numbers and Arrays*])
#table(
columns: (1in + 5pt, 3.25in + 15pt),
inset: 5pt,
stroke: none,
$a$, [A scalar (integer or real)],
$bold(a)$, [A vector],
$bold(A)$, [A matrix],
$bold(upright(sans(A)))$, [A tensor],
$bold(I)_n$, [Identity matrix with $n$ rows and $n$ columns],
$bold(I)$, [Identity matrix with dimensionality implied by context],
$bold(e)^((i))$, [Standard basis vector $[0,dots,0,1,0,dots,0]$ with a 1 at position $i$],
$op("diag")(bold(a))$, [A square, diagonal matrix with diagonal entries given by $bold(a)$],
$upright(a)$, [A scalar random variable],
$bold(upright(a))$, [A vector-valued random variable],
$bold(upright(A))$, [A matrix-valued random variable])
#v(0.25cm, weak: true)
#align(center, [*Sets and Graphs*])
#table(
columns: (1.25in + 5pt, 3.25in + 5pt),
inset: 5pt,
stroke: none,
$AA$, [A set],
$RR$, [The set of real numbers],
$\{0, 1\}$, [The set containing 0 and 1],
$\{0, 1, dots, n \}$, [The set of all integers between $0$ and $n$],
$[a, b]$, [The real interval including $a$ and $b$],
$(a, b]$, [The real interval excluding $a$ but including $b$],
$AA \\ BB$, [Set subtraction, i.e., the set containing the elements of $AA$ that are not in $BB$],
$cal(G)$, [A graph],
$italic(P a)_cal(G)(upright(x)_i)$, [The parents of $upright(x)_i$ in $cal(G)$])
#v(0.25cm, weak: true)
#align(center, [*Indexing*])
#table(
columns: (1.25in + 5pt, 3.25in + 5pt),
inset: 5pt,
stroke: none,
$a_i$, [Element $i$ of vector $bold(a)$, with indexing starting at 1],
$a_(-i)$, [All elements of vector $bold(a)$ except for element $i$],
$A_(i, j)$, [Element $i, j$ of matrix $bold(A)$],
$bold(A)_(i, :)$, [Row $i$ of matrix $bold(A)$],
$bold(A)_(:, i)$, [Column $i$ of matrix $bold(A)$],
$sans(A)_(i, j, k)$, [Element $(i, j, k)$ of a 3-D tensor $bold(upright(sans(A)))$],
$bold(upright(sans(A)))_(:, :, i)$, [2-D slice of a 3-D tensor],
$upright(a)_i$, [Element $i$ of the random vector $bold(upright(a))$])
#v(0.25cm, weak: true)
#align(center, [*Calculus*])
#table(
columns: (1.25in + 5pt, 3.25in + 5pt),
inset: 5pt,
stroke: none,
$display((d y) / (d x))$, [Derivative of $y$ with respect to $x$],
$display((diff y) / (diff x))$, [Partial derivative of $y$ with respect to $x$],
$nabla_bold(x) y$, [Gradient of $y$ with respect to $bold(x)$],
$nabla_bold(X) y$, [Matrix derivatives of $y$ with respect to $bold(X)$],
$nabla_bold(upright(sans(X))) y$, [Tensor containing derivatives of $y$ with respect to $bold(upright(sans(X)))$],
$display((diff f) / (diff bold(x)))$, [Jacobian matrix $bold(J) in RR^(m times n)$ of $f: RR^n arrow.r RR^m$],
$nabla_bold(x)^2 f(bold(x)) "or" bold(H)(f)(bold(x))$, [The Hessian matrix of $f$ at input point $bold(x)$],
$display(integral f(bold(x)) d bold(x))$,
[Definite integral over the entire domain of $bold(x)$],
$display(integral_SS f(bold(x)) d bold(x))$,
[Definite integral with respect to $bold(x)$ over the set $SS$])
#v(0.25cm, weak: true)
#align(center, [*Probability and Information Theory*])
#table(
columns: (1.25in + 5pt, 3.25in + 5pt),
inset: 5pt,
stroke: none,
$P(upright(a))$, [A probability distribution over a discrete variable],
$p(upright(a))$, [A probability distribution over a continuous variable, or over a variable whose type has not been specified],
$upright(a) tilde P$, [Random variable $upright(a)$ has distribution $P$],
$EE_(upright(x) tilde P) [ f(x) ] "or" EE f(x)$, [Expectation of $f(x)$ with respect to $P(upright(x))$],
$op("Var")(f(x))$, [Variance of $f(x)$ under $P(upright(x))$],
$op("Cov")(f(x), g(x))$, [Covariance of $f(x)$ and $g(x)$ under $P(upright(x))$],
$H(upright(x))$, [Shannon entropy of the random variable $upright(x)$],
$D_"KL" (P || Q)$, [Kullback-Leibler divergence of $P$ and $Q$],
$cal(N)(bold(x); bold(mu), bold(Sigma))$, [Gaussian distribution over $bold(x)$ with mean $bold(mu)$ and covariance $bold(Sigma)$])
#v(0.25cm, weak: true)
#align(center, [*Functions*])
#table(
columns: (1.25in + 5pt, 3.25in + 5pt),
inset: 5pt,
stroke: none,
$f: AA arrow.r BB$, [The function $f$ with domain $AA$ and range $BB$],
$f circle.stroked.tiny g$, [Composition of the functions $f$ and $g$],
$f(bold(x); bold(theta))$,
[A function of $bold(x)$ parametrized by $bold(theta)$. (Sometimes we write
$f(bold(x))$ and omit the argument $bold(theta)$ to lighten notation)],
$log x$, [Natural logarithm of $x$],
$sigma(x)$, [Logistic sigmoid, $display(1 / (1 + exp(-x)))$],
$zeta(x)$, [Softplus, $log(1 + exp(x))$],
$norm(bold(x))_p$, [$L^p$ norm of $bold(x)$],
$norm(bold(x))$, [$L^2$ norm of $bold(x)$],
$x^+$, [Positive part of $x$, i.e., $max(0,x)$],
$bold(1)_"condition"$, [is 1 if the condition is true, 0 otherwise])
#v(0.25cm, weak: true)
= Final instructions
Do not change any aspects of the formatting parameters in the style files. In
particular, do not modify the width or length of the rectangle the text should
fit into, and do not change font sizes (except perhaps in the
#smallcaps[References] section; see below). Please note that pages should be
numbered.
= Preparing PostScript or PDF files
Please prepare PostScript or PDF files with paper size "US Letter", and not,
for example, "A4". The `-t` letter option on dvips will produce US Letter
files.
Consider directly generating PDF files using `pdflatex` (especially if you are
a MiKTeX user). PDF figures must be substituted for EPS figures, however.
Otherwise, please generate your PostScript and PDF files with the following
commands:
```shell
dvips mypaper.dvi -t letter -Ppdf -G0 -o mypaper.ps
ps2pdf mypaper.ps mypaper.pdf
```
== Margins in #LaTeX
Most of the margin problems come from figures positioned by hand using
`\special` or other commands. We suggest using the command `\includegraphics`
from the graphicx package. Always specify the figure width as a multiple of the
line width as in the example below using .eps graphics
```tex
\usepackage[dvips]{graphicx} ...
\includegraphics[width=0.8\linewidth]{myfile.eps}
```
or
```tex
\usepackage[pdftex]{graphicx} ...
\includegraphics[width=0.8\linewidth]{myfile.pdf}
```
for .pdf graphics. See Section~4.4 in the graphics bundle documentation
(#url("http://www.ctan.org/tex-archive/macros/latex/required/graphics/grfguide.ps").
A number of width problems arise when #LaTeX cannot properly hyphenate a line.
Please give #LaTeX hyphenation hints using the `\-` command.
== Author Contributions
If you'd like to, you may include a section for author contributions as is
done in many journals. This is optional and at the discretion of the authors.
=== Acknowledgments
Use unnumbered third level headings for the acknowledgments. All
acknowledgments, including those to funding agencies, go at the end of the
paper.
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/tequila/graph-state/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 0pt)
#import "/src/quill.typ" as quill: tequila as tq
#quill.quantum-circuit(
..tq.graph-state((1,2), (0,2), (0,3), (0,1), (2,3))
)
#pagebreak()
#quill.quantum-circuit(
..tq.graph-state((1,2), (0,2), (0,3), (0,1), (2,3), n: 6),
) |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/036%20-%20Guilds%20of%20Ravnica/009_The%20Gathering%20Storm%3A%20Chapter%203.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Gathering Storm: Chapter 3",
set_name: "Guilds of Ravnica",
story_date: datetime(day: 19, month: 06, year: 2019),
author: "<NAME>",
doc
)
The closer Ral got to New Prahv, the more he could feel his skin crawl.
The Azorius had always been officious and overbearing, but something had changed. #emph[I’ve spent too much time locked in my workshop of late.] The streets around the great citadel of the Senate were as neat and orderly as ever, but now the soldiers of Azorius’ Lyev Column were everywhere, standing guard at the entrance to every important building and patrolling the street in their glossy white armor. Hussars trotted past, lances at the ready. In the skies overhead, for once free of rain, winged constructs circled lazily, staring down with multi-faceted, gem-like eyes.
#emph[They’re running scared.] Ral smiled tightly. The military presence was supposed to be a show of strength, but to Ral it tasted more like weakness. #emph[They know there’s nothing more useless then a senate nobody listens to.]
New Prahv itself was as impressive as ever, three titanic towers that dominated the Tenth District skyline arranged equidistant around a central courtyard, flanked by the domes and spires of lesser buildings. The borders of the enormous compound were marked by tall, spiked fences, and at the gate a dozen white-armored soldiers manned a checkpoint, processing a long queue of pedestrians. Ral ignored them and walked directly to the gate, where a blue-skinned vedalken sergeant glared at him through the narrow slit in his helmet.
"All non-guildmembers must have their papers processed before entry," the sergeant said. "Please wait your turn."
Ral gave the queue a contemptuous look. "I’m in a hurry."
"No exceptions," the sergeant growled. Two more soldiers stepped forward to flank him. "Please don’t cause trouble, citizen."
#emph[Definitely running scared.] Ral put on a haughty smile. "My name is <NAME>, personal representative of Guildmaster Niv-Mizzet. I’m here to see Supreme Judge Isperia on a matter of utmost importance."
"No exceptions—" The sergeant paused as one of the other soldiers whispered urgently in his ear. His blue lips curled into a sour expression. "Very well. Wait here."
"Not for long, I hope," Ral said.
It was, in fact, nearly a quarter of an hour before the sergeant returned, with a captain in tow. The young man, in a uniform but unarmored, gave Ral a slight bow.
"Welcome, <NAME>. I am Captain <NAME>. Come with me, please."
Ral favored the sergeant with one last superior smile as he followed the captain through the checkpoint. Liosh led him rapidly across the central square, past the three great monoliths, and into the maze of subsidiary buildings that housed the administrative apparatus of the senate. Ral was struck by how different it was from the halls of Nivix—not just that the walls and floor were covered with cracks and scorch-marks, of course, but the #emph[silence] . The floors were polished marble, with no carpets or hangings to muffle the echoes, and every footstep echoed like a thunderclap. Clerks shuffled past, heads down, not looking either at Ral or the guards who stood like ceramic statues at regular intervals. There was a steady stream of homunculi as well, small, wizened-looking creatures who performed menial administrative tasks, hurrying back and forth with their small arms piled high with scrolls.
Captain Liosh stopped in front of a grand double door, inlaid with the Azorius guild crest in silver. From inside, Ral could hear the faint sound of voices raised in anger. The captain coughed.
"The delegation from the Boros Legion has already arrived," he said. "I understand that the guildmaster will be a few moments longer. Please wait inside."
He opened the door, bowing again. Beyond, Ral found an oval conference chamber, with a long, highly polished table down the center. One side of the table was lined with high-ranking Azorius functionaries, in the white robes of senators or military uniforms.
On the other were more soldiers, but of a very different cut. Where the Azorius military was all chilly precision and gleaming ceramic armor, the Boros Legion delegation wore brushed steel, well-polished but with the nicks and scars that spoke of actual combat. There were five of them, ranging from two young captains up to an older minotaur woman wearing a lieutenant’s insignia. She sat in silence, arms folded, while her subordinates engaged in a shouting match with the gaggle of politicians.
Against the rear wall, watching, was an angel.
#emph[Aurelia.] Ral couldn’t help but stare. He didn’t know much about the angelic hierarchy that dominated the upper ranks of the Boros, but Aurelia had become guildmaster after she ousted Feather. She was a head taller than him, but gave an impression of delicate grace that belied her size. Her features were striking, androgynous and beautiful, and her bright crimson hair flowed down over her shoulder like a river of blood dripping across her well-worn armor. Her great wings were folded behind her. She surveyed the ongoing argument with a faintly amused expression, like a parent watching children in fierce debate.
"If we are weak," one of the Boros lieutenants was saying, "it is #emph[your] doing. The Legion and the Senate are intended to work together, for the good of Ravnica, but you have taken it upon yourselves to usurp our function."
"Only because you refuse to perform it," a pot-bellied senator shot back. "If the Legion would enforce the laws—"
"How are we supposed to enforce the laws when they change every day?" another soldier said. "The Senate has lost its grip."
"The Legion has become a dangerous rogue element," snapped an Azorius vedalken.
"Dangerous?" The minotaur woman leaned forward, silencing the others for a moment. One of her long horns gleamed dangerously, while the other had broken off, and was now capped by a silver stopper. "The Boros are dangerous only to those who would transgress against justice. Is that you, senator?"
"Of course not," the vedalken shot back. "We are the #emph[law] . How can we break it?"
"Justice and the law are not the same." Aurelia’s voice was surprisingly high and musical. "The Azorius would do well to remember that." She turned her glowing eyes on Ral. "Greetings, <NAME>. We have been anxiously awaiting your arrival."
"Send your complaints to the sergeant at the gates," Ral said. "Or whoever designed this maze of a building." He bowed toward Aurelia, and inclined his head to the Azorius side of the table. "Guildmaster Aurelia. Masters. Thank you for coming."
"Zarek," the pot-bellied senator said. "Good. I, for one, have some questions for you. Who #emph[exactly] is this threat you claim is nearly upon us?"
"And what can you tell us about its capabilities?" the minotaur said. "How many men can it field, and with what equipment?"
"I think," Aurelia said, "that it would be best to wait until Guildmaster Isperia and I have had a chance to discuss the matter."
"I agree," Ral said. The last thing he wanted was to get bogged down trying to convince these squabbling subordinates of the depth of the problem. "Will she be ready for us soon?"
"She is ready now," said a cold voice from the other end of the room. A door there had opened, and a tall, thin-limbed vedalken stood beside it. "The guildmaster requests that <NAME> and Guildmaster Aurelia join her alone."
"It could be a trap," the minotaur woman said at once. "Let her see us all together."
"The honor of the Azorius would never allow such a thing," the senator said. "But I agree that we should all—"
"The guildmaster has made her decision clear," the vedalken said.
"I appreciate your concern," Aurelia said. "But I will be fine." The angel nodded to Ral. "Shall we?"
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The next room was much larger, out of necessity.
Isperia, Supreme Judge of the Azorius Senate, was a sphinx. Her long, leonine body was bigger than a cart, made even bulkier by broad, feathered wings. Her enormous forepaws were folded in front of her. Her face and head looked more human, framed by long purple hair, her features as famously inscrutable as all her kind.
One chair stood beside her, and two more were set up opposite. Ral, already feeling at something of a disadvantage in conversation with this enormous creature, chose to stand, and Aurelia did likewise. The vedalken took the other chair, settling in with precise movements and folding his hands in front of him.
"Welcome," Isperia said. Her deep voice had a trace of a lion’s roar in the bottom registers. "Aurelia. It has been too long."
"It has," the angel said. "I regret the recent . . . tension between our guilds."
"And I don’t believe we have met, <NAME>," the sphinx went on. "I am, of course, well-acquainted with your master."
"The Firemind sends his greetings," Ral said. He glanced at the vedalken, curiously.
"Ah, yes." Isperia nodded in his direction. "This is Grand Arbiter <NAME>. He is my second, and may have some expertise in the matter before us."
"Greetings," Baan said, his blue features emotionless.
"Your master called this meeting, Zarek," Aurelia said. "I must say when I received his message, it seemed far-fetched. A dragon from another world? I’ve always dismissed such myths." She smiled.
"It would explain much about Azor. And the Firemind must never be discounted entirely," Isperia said. "At the same time, we have grown used to ignoring his . . . flights of fancy. However." She glanced at Dovin, who cleared his throat.
"<NAME> is quite real," the vedalken said. "I crossed path with him, or his agents, on my home plane of Kaladesh. My subsequent investigations led me here, where I believe he will make his next move."
"You claim to be from another world, then?" Aurelia said.
"Yes," Baan said. "I am a Planeswalker."
Ral cleared his throat. "I realize the idea seems absurd at first," he said. "But I can give you my personal assurance that such people exist."
It felt strange to say it so baldly. Not long ago, Ral had been working desperately to prevent the secret of Planeswalkers and other worlds from becoming widely known. He’d assumed that if those without the Spark became aware of the strangers in their midst, the paranoid reaction would be dangerous for all of them. Every Planeswalker he’d met over the years had the same policy, an unwritten rule that kept their abilities hidden from most of the Multiverse.
Now he was breaking that taboo, to two of the most powerful and influential creatures in Ravnica. #emph[But there’s no way around it. ] He’d never convince anyone that <NAME> was a threat if he couldn’t explain where the dragon was coming #emph[from] .
"I have received documentation from Niv-Mizzet on the subject," Aurelia said. "I assume you have as will?"
Isperia nodded. "I am prepared to accept his word, for the moment."
"Let us proceed on that assumption." Aurelia turned back to Ral. "This <NAME> is coming to Ravnica, then, from parts unknown. He is powerful?"
"Significantly more powerful than my master," Ral said. "At present."
"And yet that is hardly an insurmountable obstacle," Aurelia said. "Forgive me for being blunt, but if it came to a confrontation, I would certainly hazard the combined might of the Legion against Niv-Mizzet alone. I cannot see why this Bolas would be any different."
"I agree," Isperia said. "One dragon is much like another."
"Bolas won’t be alone," Ral said. "He has allies."
"Who?" Aurelia said. "How many? In what strength?"
"At least some Ravnicans," Ral said. "We know that Lazav and the Dimir are working with him."
"Hardly unexpected," Isperia said. "You have no other information?"
"I have my personal experience," Ral said. "Bolas is no simple threat. What he wants, he usually gets."
"I concur," Baan said, his tone still neutral. "If he is coming to Ravnica, it is because he believes himself strong enough to rule."
"For the moment," Isperia said, "let us move on. What is Niv-Mizzet’s proposal?"
"He wants to amend the Guildpact," Ral said. "To make himself into a force capable of defeating Bolas. He pledges to leave the Izzet behind, and to take no further part in the conflicts of the guilds."
"A lofty appeal," Aurelia said. "But not one I have a great deal of confidence in."
"Who would lead the Izzet afterward?" Isperia said.
Ral gave a slight bow. "I would."
The sphinx regarded him curiously. "And do you believe the Firemind would remain neutral, as he claims?"
"I do." Ral didn’t add that it was damned hard to get the dragon to care about anything #emph[now] if it didn’t bear directly on his studies. "I think this is our best chance."
There was a long pause.
"I am not convinced," Aurelia said slowly, "that this Bolas is as dire a threat as you claim. However . . ."
She looked at Isperia, and the sphinx nodded slowly.
"There is a sickness in the guilds," the angel said. "The Living Guildpact was intended to keep them in check, but <NAME> is gone. I suppose he is also one of these Planeswalkers?"
"Yes," Ral said. "Niv-Mizzet believes he may be dead."
"He was on Kaladesh," Baan said mildly. "Where he went from there, I do not know."
#emph[He knows Beleren?] Ral shot the vedalken a sharp look, and resolved to question him further later.
"In any event," Isperia went on. "The Living Guildpact is not performing his function. It may be that further amendments are required." The sphinx’s huge body shifted in a shrug. "At the very least, it will do no harm to assemble a guild summit."
"Getting agreement will not be easy," Aurelia said. "The Gruul will object on principle, and the Orzhov will consider only their own private advantage. As for Dimir, who knows?
"Niv-Mizzet has his own plans in motion," Ral said, with a lot more confidence then he truly felt. #emph[If he can bring the Gruul to the table, he truly deserves to be called the Firemind.] "But you agree, in principle?"
The angel nodded. "Yes. The present situation cannot go on, and this threat must be addressed. The Boros Legion will negotiate in good faith."
"We will handle the particulars," Isperia said. "But convincing the other guilds to attend at all will still be your responsibility, <NAME>. I hope you are equal to it."
"Leave it to me," Ral said, forcing a grin.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
In spite of his misgivings, Ral had to admit as he left New Prahv that things were looking, if not actually #emph[up] , then at least less than completely hopeless. For all that the other guilds protested against the authority of the Azorius, the Senate commanded a vestige of respect. Isperia’s endorsement went a long way toward making this look less like an Izzet power play, especially with Aurelia and the Boros also on board.
#emph[Gruul is still going to be a problem, though.] Not only were the chaotic tribes constitutionally opposed to anything like cooperation with the other guilds, their rivalry with Boros ran deep. #emph[And Dimir is already against us. I hope the Niv-Mizzet really does have something up his sleeve.] #emph[] #emph[] He walked out through the market square that fronted New Prahv, outside the Azorius checkpoints but still well within their jurisdiction. It was bustling with the break in the rain, thick with sentient creatures of a dozen different races and a hundred varieties of beasts of burden. Above the heads of the humanoids, faeries flitted back and forth on colorful trails of magic, mixed with the buzz of insects and the whirr of small constructs. Stalls around the edges of the square sold food and drink: spitted potatoes, fried mushrooms in fantastic varieties from the depths of the undercity, roasted meat of dubious origin, and wine that might or might not have come anywhere near a grape.
"<NAME>?" a small voice said, while Ral was contemplating a haunch of something green and scaly. He looked around, frowning, and then glanced down to find a small elven girl tugging at his sleeve.
"I don’t want to buy anything," he growled.
"Someone wants to talk to you," the girl said, looking shyly at the cobblestones. "Says it’s important."
"I don’t—"
"Says it’s about bowl-uhs. Dunno what that means."
Ral froze. His eyes searched the market.
"Where did he want me to go?" he said.
"Was a lady," the girl said. "Sit on the bench and wait, she said."
Before he could stop her, the elf slipped away, darting nimbly through the crowd. In the center of the square were a set of stone benches ranged around a central fountain, in which a statue of Azor was surrounding by water-spouting nymphs. Many of them were occupied, but Ral couldn’t see anyone who seemed threatening.
#emph[Even Tezzeret would hesitate before trying something this publicly.] Not only was the square full of shoppers and merchants, but Azorius guards were much in evidence, patrolling in small groups or standing at intervals in their glossy white armor. #emph[If it’s a trap, it’s a subtle one.] #emph[] #emph[] He made his way over to the bench, found a clear spot, and sat down. It gave him a good view of half the square, but the back of his neck itched, wary of what might be hiding out of his line of vision. He felt half-naked without his accumulator and mizzium bracers, left behind out of respect for his Azorius hosts. When he reached out with his power, only a few crackles of lightning in the brooding clouds overhead were close enough to tap.
Across the way, a troop of Rakdos puppeteers were performing, to the delight of a crowd of watching children. Under the stern eye of the Azorius guards, they settled for biting satire instead of setting things on fire, much to the disappointment of their audience. One of the puppets had a shock of wild hair with a white streak down the center. #emph[I wonder what they’re saying about me now.] #emph[] #emph[] "Zarek," said a woman’s voice behind him. "Don’t look around."
Ral put his chin in his hands, pretending to be absorbed in the puppet show. "And you are?" he murmured.
"Lavinia," the woman said. "Formerly of the Azorius."
#emph[Lavinia.] He knew her by reputation. She had been one of the Senate’s most notorious investigators, dogged in her pursuit of anything that looked like wrongdoing or corruption, prior to working with Beleren as Steward of the Guildpact. Her resignation from the guild had caused a minor scandal, though it had been quickly swallowed up by all the other strange news of late.
"I have an office, you know," Ral said. "You’re always welcome to make an appointment."
"They’re watching you."
"A lot of people are watching me. It comes with the territory."
"Don’t play dumb. You know who I mean."
"Bolas." Ral grimaced. "Care to tell me how you know that name?"
"I still have my sources inside the Senate," Lavinia said. "That place leaks like a sieve. By tomorrow morning, everyone in the district will know what you and the sphinx are up to."
Ral shrugged. "We were planning to announce it in any event. So what’s #emph[your] angle? I thought you left the guild."
"I left the guild," Lavinia grated, "because I started pulling on a thread, and they didn’t like what I found."
"What thread would that be?"
"There are agents of a foreign power in the Tenth District," Lavinia said. "I’ve been tracking them for months, intercepting their communications, trying to understand their purpose and who they work for. Now I have the answer to at least one of those questions."
"You think they work for Bolas."
"It’s the only thing that makes sense."
"So why are you telling #emph[me] about it?"
"Because you’re far too trusting."
Ral laughed. "I like to think I’m appropriately paranoid."
"Listen," Lavinia said, lowering her voice. "This is an organized network, spread through all the guilds. I don’t know what their goal is, not yet, but if you’re working against Bolas, they’re going to try to stop you. And I don’t know how many more agents there are that I #emph[haven’t] identified. You can’t trust anyone."
"Except you, I assume."
"You’d be a fool if you did."
"What do you want, Lavinia?"
"I want to help you. Whatever Bolas has planned, it’s not going to be good for Ravnica. But you have to be #emph[careful] ."
"I’m second in command of a guild of mad geniuses," Ral said. "I haven’t gotten there by being careless."
"Even if you manage to bring the guilds together, it’s likely that Bolas will have already sunk his claws into them." Lavinia sighed. "I hope you know what you’re doing, I really do."
"Knowing who is already on his side would be nice, if you really want to be #emph[helpful] ."
"I’ll do what I can," Lavinia said. "I don’t want to spook them, not yet. I’ll contact you again when I have something."
"Thanks." Ral waited for a response, and when none came he looked over his shoulder. The bench behind him was empty.
#emph[Well. That was . . . odd.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[Lavinia’s not wrong] , Ral thought as he walked across the Tenth District. #emph[A little paranoid, maybe, but not wrong.] Bolas was a born schemer and knew better then to put all his bets on one throw of the dice. #emph[If he has one agent among the guilds, he’ll have many.] Somehow, they’d have to figure out who was on the dragon’s payroll before the guild summit convened.
He did his best to put it out of his mind, at least for the moment. As always, coming here brought a little surge of guilt—not that he was doing anything #emph[wrong] , but that he was stealing time that might have been put to use at Nivix, studying reports or checking up on his projects. As always, Ral assured himself that everything was on track. #emph[It will take time for Isperia to send her messages and receive replies. We won’t have any new information until morning, at the earliest.] The brief respite from the autumn rains had ended, and Ral put up his deflection spell and kept his head down as the gutters once again gurgled and splashed.
The apartment was in the Dogsrun neighborhood, a genteel rectangle of quiet streets tucked away from the major thoroughfares. It was close enough to Nivix for convenience, but far enough that it wasn’t part of Izzet territory. Renting it had been an odd experience—it had been a long time since Ral had any cause for handling money, and he’d been surprised to discover that he was, if not rich, at least comfortably well off. He’d spent decades living in the Izzet laboratories, while the guild’s bean-counters had dutifully credited his account with regular contributions. Apparently Niv-Mizzet was generous to his most successful underlings. #emph[No wonder <NAME> is so eager to maintain her position.] #emph[] #emph[] Belatedly realizing he was on the hook for dinner, he stopped in at a viashino eatery on the way there. The old lizard-woman behind the counter grinned to see him, showing a mouthful of sharp teeth, and barked a laugh at his usual request to "hit him with her best shot." Two curries in waxed paper packages secured, he made his way up the streets of Dogsrun, past brick-faced apartment buildings with window-box gardens and wrought-iron fences. His key let him into one, safely anonymous in the center of a row, and he climbed three flights of stairs.
He was running late. No sooner had he shrugged out of his coat and put the food on the table then there was the sound of another key in the lock. Ral opened the door and raised an eyebrow at the sight of <NAME>, his hair soaked through and his glasses splattered with raindrops.
"You look like a wet rat," Ral said.
"I feel like a wet rat," Tomik said. "Left my coat at the cathedral. I thought I could make it here before the skies opened up again." He pulled off his glasses and wiped them on his shirt, which didn’t actually help much. "This one your fault, too?"
"You cause #emph[one] thunderstorm, and they never let you hear the end of it," Ral said. "I brought curry."
"Hmm. I suppose I can forgive you, then."
Tomik stepped forward, and Ral leaned in and kissed him thoroughly. Finally Tomik broke away, shoved past Ral in spite of his mock complaints, and headed straight for the table.
"I see where your priorities are," Ral said.
"Damned right," Tomik said, sitting down. "I missed lunch."
"I think the brown one is yours."
"I can tell by the fact that breathing near it doesn’t sear my nasal passages," Tomik said. "Honestly, I don’t understand how you can eat that stuff."
"Spend half a year stuck on campaign with a bunch of scorchbringers, and you’ll learn." The viashino had a habit of seasoning their food with whatever spice, vegetable, or fungus would burn hottest. Ral’s curry was an angry crimson, full of chunks of seared meat like bloody icebergs. He speared one, savoring the heat of it.
Tomik, watching, rolled his eyes and attacked his considerably milder curry. For a while they ate in comfortable silence, but it slowly transitioned into #emph[un] comfortable silence. Ral polished off his food and found Tomik only halfway through his, staring absently down into the depths of his curry as though it contained some dangerous secret.
"Something wrong?" Ral said, after some hesitation.
"Oh." Tomik laid down his fork and looked up. "You know. Guild business."
"Guild business." They said it almost simultaneously, and Tomik smiled a little.
It was a joke, sort of. He and Tomik had met when the young secretary was pursuing <NAME>’s agenda of greater ties between the Orzhov and the other guilds. Tomik’s quick mind (and the way he fiddled with his glasses when he was flustered) had intrigued Ral, and he had taken the unusual step of suggesting they meet privately once the negotiations had concluded. After that, one thing had somehow led to another.
But it was clear to both of them that this—whatever #emph[this] was, and frankly Ral didn’t want to think too hard about that—was only going to work if they kept their respective positions out of it. Ral had rented the apartment to have a private place to meet while keeping a low profile. It wasn’t that Izzet officials didn’t have lovers or partners, of course. Just that if it became widely known that the second-in-command of the Izzet was spending time with the personal secretary of the Karlov heir apparent, questions would be asked on Ral’s side, and he assumed the same was true of Tomik.
Given how much time and attention each of them committed to their guilds, it was a hard line to walk. Sometimes, Ral wondered if he was fooling himself if he thought this was more than a brief interlude, like a dozen others that had come and gone over the years. #emph[But Tomik . . .] #emph[] #emph[] He shook his head. #emph[Not the time.] Worrying about it wasn’t going to help.
"Guild business," he said again, and sighed. "I know the feeling, believe me."
Tomik looked as though he wanted to say something, but he only bit his lip and shook his head. Ral yawned, ostentatiously, and got up from the table.
"I, for one, have had enough of guild business for the day." He gave Tomik a cocky grin. "What about you?"
Tomik grinned back.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
In the broad, soft bed, with Tomik curled against his back like a comfortable cat, <NAME> dreamed. Or remembered.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
In his dream, he was seventeen again.
The Tenth District, with its guildhalls and great markets, was the center of Ravnica, if a city that stretched on forever could really be said to have a center. By the same token, Tovrna was the outskirts, a backwater in the endless city. Once a power in its own right, it had slipped into somnolence over the centuries, ruled by a handful of petty oligarch families who owned the vast factory rows where the rest of the population labored. The downtown of Tovrna was a few blocks of elegant apartments and townhouses, surrounded by a thin ring of dilapidated buildings for the servants, scribes, and other hangers-on.
Beyond that were the crumbling tenements of the poor, and the long, low sheds of the factories themselves, powered by superheated gas rising from underground caverns. The machines inside whirred day and night, turning thread into cloth, pig iron into neat rods, or creating any one of a hundred other products Tovrna exported to the wealthier districts. It would have been easier and safer to use magic, of course, but mages were expensive. Tenement dwellers with nothing to lose were cheap, and easy to replace.
Ral’s mother had been one such, working in a cloth factory until she’d been mangled in an accident when Ral was eleven. She’d lived a cripple for another two years, never really healing, with Ral doing everything he could to help her. After she’d finally died, it had only taken a few months for the thirteen-year-old to abandon his drunken lout of a father and strike out on his own.
Four years later, he’d managed a precarious existence. A place to live, a job of sorts. And, to his great surprise, love.#linebreak "You’re off?" Elias said, spying Ral changing through the open bedroom door.
Ral nodded, pulling on a shirt that was slightly less threadbare than the rest and examining himself in the cracked mirror propped against the pockmarked plaster wall. #emph[It’ll do] , he decided, #emph[if I keep my coat on.] #emph[It’s not like the count ever pays much attention to me anyway. ] His client had a great-grandfather in the Orzhov and pretensions to nobility.
Their apartment was in that precarious ring, too far from the center of the district to be respectable, but not quite part of the slum. It had once been fashionable, with high ceilings and faded gilt wallpaper in the hall, but most of the furnishings had long ago been stripped. Ral and Elias had replaced them with their own eclectic collection, mostly scavenged from oligarch castoffs. A few rickety shelves held small paintings and sculptures, courtesy of Elias’s bohemian friends, who were always gifting one another with their latest artistic efforts. Privately, Ral thought that most of these looked like little more than lumpy trolls or blots of spilled paint, but his lover seemed to adore them, so he held his tongue.
Elias himself was at work in the main room, lying on his stomach in front of their ratty old sofa, pencil in hand. A stack of the clean white paper—one of the few indulgences Ral’s meager earnings would stretch to—sat in front of him, the top sheet bearing a single word repeatedly crossed out.
"Tough morning?" Ral said.
Elias rolled over and threw one arm across his forehead with a theatrical sigh. Ral laughed, and Elias stuck out his tongue. He was a year older than Ral, but smaller and slighter, with dark brown skin and long hair dyed a deep green in the imitation of elven fashion, a look that was apparently the done thing at the moment.
"I’ll have you know that I’m in the midst of wrestling my muse to the ground," Elias said. He lay back and carefully balanced the pencil on his nose, staring at the ceiling. "Aaaaany minute now. I’ll be churning out the pages."
"Well." Ral wanted to jump on him, knock the pencil away and kiss the smirk off his face. #emph[But I can’t be late, not after last time.] "I won’t distract you, then."
"No? Not even for a little while?"
Ral laughed, waved, and walked out the door.
It was high summer, and the sun baked the mud between the cobblestones into a fine dust that coated everything. Ral skirted the center of the district, sticking to back streets without much carriage traffic, until he came to the count’s townhouse. It was enormous, at least four stories high, and had long ago swallowed the buildings behind it to extend further back from the streets. That was where the terraced gardens were, four levels of riotous green, producing fruits and herbs for the count’s table.
Ral bypassed the front doors and went around the side to the tradesman’s entrance—he’d only made #emph[that] mistake once. A sour-faced butler greeted him when he rapped at the door. His expression as he looked over Ral’s weather-beaten coat and patched trousers could have curdled milk.
"Ah," he said. "The rain mage."
#emph[Rain mage, rain mage.] The man’s voice echoed in Ral’s head, taunting him. He swallowed a knot in his throat and nodded.
"You’ll have to wait," the butler said. "The master is entertaining in the garden now."
"He told me this morning would be all right," Ral said. "I have appointments—"
"The count has changed his plans," the butler said, slowly and carefully as if speaking to an idiot. "You will have to wait."
And so Ral ended up cooling his heels for the better part of an hour in the kitchen, while the servants gave him curious looks and the life of the great house went on around him. When a maid finally summoned him to the gardens, he got a brief glimpse of the count and his guests leaving through the main door, like a herd of brilliant peacocks compared to the drab attire of the servants.
They’d left the gardens a mess, plants trampled and discarded plates and cutlery everywhere. That, at least, wasn’t Ral’s problem. He sat in the garden’s highest tier, cross-legged, and focused.
#emph[Rain mage.] They’d hung that name on him in the streets when he was a boy, shouted it at him in mockery. He had a talent for magecraft, he’d discovered, but not for fire or mind magic or healing or anything #emph[truly] impressive. Just . . . rain. #emph[What can you do with rain?] #emph[] #emph[] Overhead, there was a tiny crash of thunder, and then heavy drops began to land on the leaves of the garden. The parched, thirsty earth drank in the water, which curved politely around Ral himself.
This is what you could do with rain. The trick wasn’t calling the rain, something Ral had been able to do when he was ten. The trick was getting it to rain #emph[here] but not anywhere else; the count and his neighbors would not be pleased if he soaked their party guests. It had taken Ral years to learn that kind of control, not that it had earned him much respect.
Each tier had to be watered in turn, so it was well after noon before Ral was finished. He accepted the lunch the butler had, with bad grace, offered him, plain bread and leftover stew, and the small bag of zinos that had come along with it. Enough to pay the rent and keep himself and Elias fed for another few days, until the next job came along. Until Elias finally found an audience for his poetry, and made good on all his promises. #emph[Just a little longer.] #emph[] #emph[] He’d just emerged from the house, shrugging into his coat, when he heard the call.
"Hey, rain mage!"
Ral looked up, and swore, very quietly.
Gunther was the count’s oldest son, Ral’s age, though you wouldn’t know it under the layers of silk and cosmetics. Ral thought it made him look like a performer at the circus, but Gunther clearly thought himself the height of fashion, and his entourage seemed to agree, aping the boy’s overdressed style. There were half a dozen of them, young men from respectable families, and one slightly older, slightly shabbier-looking fellow with the look of a hired hand. They blocked the way back onto the street.
Ral kept his head down as he walked toward them.
"Rain mage!" Gunther said. "I’m talking to you."
There was nothing to do but answer, if he didn’t want to actually walk over the boy. Ral sighed and looked up.
"Yes?"
"What are you going to do," Gunther said, "about my hat?"
His hat was large, green, and fringed with silk. As he tipped it toward Ral, a wet streak down one side was visible.
"It’s absolutely #emph[ruined] ," Gunther said.
"I’m sorry to hear that," Ral said. "But I was only doing as your father instructed."
#emph[And I’m sure the garden was empty.] Gunther had to have noticed the rainstorm and gone into it on purpose.
"My father did #emph[not] instruct you to butcher my wardrobe!" Gunther said. "Would you like to come with me and ask him about it?"
"No," Ral said tightly. "I’m sorry."
"You’re simply going to have to pay for it." Gunther stepped forward. "Let’s see your purse."
The entourage tittered, except for the hired hand. Ral fists clenched.
"No," he said quietly. "I won’t."
"Excuse me?" Gunther bent forward. "You will. Or else you’ll be #emph[disciplined] ."
"I won’t," Ral said again.
Gunther’s fist hit him in the gut, hard and fast. Given the way he looked, it seemed unfair that Gunther could throw a decent punch, but his father had apparently not skimped on his physical training, and there were muscles under the frippery. Ral doubled over, then straightened up slowly.
"Now #emph[there’s] a dangerous look," Gunther said. "What are you going to do, rain mage? Moisten me?"
"No," Ral grated. "Sir. I’d just like to go."
"Varo," Gunther said airily. "Show this fellow what a #emph[real] mage can do."
The hired hand stepped forward. He caught Ral’s eye, and shrugged.
"Sorry, kid."
Ral had time to throw up his hands before Varo made a complicated gesture, and a wave of raw force picked Ral up and tossed him against the side of the alley. The air went out of him in a rush, and he felt his nose break with a #emph[crunch] and a spike of pain. A moment later he was lying on his back, spitting blood, while Gunther and his friends laughed.
"#emph[Very] well done, Varo," Gunther said.
"Yessir."
"I think that’s vengeance for my hat taken," the boy announced. "Who’s for darts?"
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
An indeterminate amount of time passed. Ral had to work just to breath, and he could feel his nose swelling. He closed his eyes to slits against the sun.
A shape swam into view. A man, with his hand extended.
"Do you need help, boy?" The voice sounded friendly, amused.
Ral hesitated only a moment before taking the hand. A strong grip returned him to his feet. He blinked, eyes watering, and then winced as the stranger’s fingers pressed against his face.
"That’s a bad break," the man said. "I can do something about it, if you’d like."
"What’ll it cost me?" Ral said, his voice blocked and nasal.
"Let’s say . . . a moment of your time. I’d like it if you joined me for a cup of coffee."
Ral gave a cautious nod. The man pressed two fingers carefully against his broken nose, and Ral felt the weird sensation of flesh twisting against itself as it straightened. Healing magic tingled gently, then faded.
"Here." The man handed him a handkerchief. "You might want to clean yourself up a bit. You look like you’ve been in the wars."
"Thank you," Ral said, relieved to breathe easily. He mopped at the blood on his face. "I’m not sure a cup of coffee is enough to repay you."
"Well." Now that Ral could see him clearly, the stranger was a tall, handsome older man, with his graying hair tied back in a queue. He was immaculately dressed, though in a style that Ral found vaguely foreign. "Perhaps you could further oblige me by considering an offer. I think that you show promise."
"What, at getting my teeth kicked in?"
"I admit I have been watching you." The stranger cocked his head. "Am I correct that you might be amenable to additional employment?"
Ral nodded.
"And further, that you would not mind performing tasks that are counter to the interests of the highest echelons of society? Such as, for example, the count and his charming son."
Ral, once he’d followed the circumlocutions of the man’s speech, found himself laughing.
"No," he said. "I wouldn’t mind that at all."
"Excellent," the stranger said. "Then we have much to discuss."
He extended a hand, and Ral shook it.
"<NAME>," Ral said.
"Bolas," the stranger said. He grinned, his smile showing very white, slightly pointed teeth. "<NAME>."
|
|
https://github.com/sicheng1806/typst-book-for-sicheng | https://raw.githubusercontent.com/sicheng1806/typst-book-for-sicheng/main/README.md | markdown | # typst-book-for-sicheng
我使用typst整理的学习笔记
|
|
https://github.com/Mc-Zen/tidy | https://raw.githubusercontent.com/Mc-Zen/tidy/main/src/helping.typ | typst | MIT License | #import "styles.typ"
#import "utilities.typ"
#import "testing.typ"
#import "parse-module.typ": parse-module
#import "show-module.typ": show-module
#let help-box(content) = {
set text(size: .9em)
block(
above: 1em,
inset: 1em,
stroke: rgb("#AAA"),
fill: rgb("#F5F5F544"),
text(size: 2em, [? #smallcaps("help")#h(1fr)?]) + content
)
}
#let parse-namespace-modules(entry) = {
// "Module" is made up of several files
if type(entry) != array {
entry = (entry,)
}
parse-module(entry.map(x => x()).join("\n"))
}
#let search-docs(search, searching, namespace, style) = {
if search == "" { return help-box(block[_empty search string_]) }
let search-names = "n" in searching
let search-descriptions = "d" in searching
let search-parameters = "p" in searching
let search-argument-dict(args) = {
if search in args { return true }
for (key, value) in args {
if "description" in value and search in value.description { return true }
}
return false
}
let filter = definition => {
(search-names and search in definition.name) or (search-descriptions and "description" in definition and search in definition.description) or (search-parameters and "args" in definition and search-argument-dict(definition.args))
}
let definitions = ()
let module = parse-namespace-modules(namespace.at("."))
let functions = ()
let variables = ()
for (name, modules) in namespace {
let module = parse-namespace-modules(modules)
functions += module.functions.filter(filter)
variables += module.variables.filter(x => search in x.name or search in x.description)
}
module.functions = functions
module.variables = variables
return help-box({
show search: highlight.with(fill: rgb("#FF28"))
show-module(module, style: style)
})
}
#let get-docs(
definition-name, namespace, package-name, style,
onerror: msg => assert(false, message: msg)
) = {
let name = definition-name
let result
if type(name) == function { name = repr(name) }
assert.eq(type(name), str, message: "The definition name has to be a string, found `" + repr(name) + "`")
let name-components = name.split(".")
name = name-components.pop()
let module-name = name-components.join(".")
if module-name == none { module-name = "." }
if module-name not in namespace {
return onerror("The package `" + package-name + "` contains no module `" + module-name + "`")
}
let module = parse-namespace-modules(namespace.at(module-name))
// We support selecting a specific parameter name (for functions)
let param-name
if "(" in name {
let match = name.match(regex("(\w[\w\d\-_]*)\((.*)\)"))
if match != none {
(name, param-name) = match.captures
if param-name == "" { param-name = none }
definition-name = definition-name.slice(0, definition-name.position("("))
}
}
// First check if there is a function with the given name
let definition-doc = module.functions.find(x => x.name == name)
if definition-doc != none {
if param-name != none { // extract only the parameter description
let style-functions = utilities.get-style-functions(style)
let style-args = (
style: style-functions,
label-prefix: "",
first-heading-level: 2,
break-param-descriptions: true,
omit-empty-param-descriptions: false,
colors: styles.default.colors,
enable-cross-references: false
)
let eval-scope = (
// Predefined functions that may be called by the user in docstring code
example: style-functions.show-example.with(
inherited-scope: module.scope
),
test: testing.test.with(
inherited-scope: testing.assertations + module.scope,
enable: false
),
// Internally generated functions
tidy: (
show-reference: style-functions.show-reference.with(style-args: style-args)
)
)
eval-scope += module.scope
style-args.scope = eval-scope
// Show the docs
if param-name not in definition-doc.args {
if ".." + param-name in definition-doc.args {
param-name = ".." + param-name
} else {
return onerror("The function `" + definition-name + "` has no parameter `" + param-name + "`")
}
}
let info = definition-doc.args.at(param-name)
let types = info.at("types", default: ())
let description = info.at("description", default: "")
result = block(strong(name), above: 1.8em)
result += (style.show-parameter-block)(
param-name, types, utilities.eval-docstring(description, style-args),
style-args,
show-default: "default" in info,
default: info.at("default", default: none),
)
}
module.functions = (definition-doc,)
module.variables = ()
} else {
let definition-doc = module.variables.find(x => x.name == name)
if definition-doc != none {
assert(param-name == none, message: "Parameters can only be specified for function definitions, not for variables. ")
module.variables = (definition-doc,)
module.functions = ()
} else {
if module-name == "." {
return onerror("The package `" + package-name + "` contains no (documented) definition `" + name + "`")
} else {
return onerror("The module `" + module-name + "` from the package `" + package-name + "` contains no (documented) definition `" + name + "`")
}
}
}
if result == none {
result = show-module(
module,
style: style,
enable-cross-references: false,
enable-tests: false,
show-outline: false
)
}
return result
}
/// Generates a `help` function for your package that allows the user to
/// prints references directly into their document while typing. This allows
/// them to easily check the usage and documentation of a function or variable.
///
/// - namespace (dictionary): This dictionary should reflect the "namespace" of the package
/// in a flat dictionary and contain `read.with()` instances for the respective code
/// files.
/// Imagine importing everything from a package, `#import "mypack.typ": *`. How a
/// symbol is accessible now determines how the dictionary should be built.
/// We start with a root key, `(".": read.with("lib.typ"))`. If `lib.typ` imports
/// symbols from other files _into_ its scope, these files should be added to the
/// root along with `lib.typ` by passing an array:
/// ```typ
/// (
/// ".": (read.with("lib.typ"), read.with("more.typ")),
/// "testing": read.with("testing.typ")
/// )
/// ```
/// Here, we already show another case: let `testing.typ` be imported in `lib.typ`
/// but without `*`, so that the symbols are accessed via `testing.`. We therefore
/// add these under a new key. Nested files should be added with multiple
/// dots, e.g., `"testing.float."`.
///
/// By providing instances of `read()` with the filename prepended, you allow tidy
/// to read the files that are not part of the tidy package but at the same time
/// enable lazy evaluation of the files, i.e., a file is only opened when a
/// definition from this file is requested through `help()`.
/// - style (dictionary): A tidy style that is used for showing parts of the documentation
/// in the help box. It is recommended to leave this at the `help` style which is
/// particularly designed for this purpose. Please post an issue if you have problems
/// or suggestions regarding this style.
/// - package-name (str): The name of the package. This is required to give helpful
/// error messages when a symbol cannot be found.
/// - onerror (function): What to do with errors. By default, an assertion is failed (the document panics).
#let generate-help(
namespace: (".": () => ""),
package-name: "",
style: styles.help,
onerror: msg => assert(false, message: msg)
) = {
let validate-namespace-tree(namespace) = {
let validate-file-reader(file-reader) = {
assert(type(file-reader) == function, message: "The namespace must have instances of `read.with([filename])` as leaves, found " + repr(file-reader))
}
for (entry, value) in namespace {
if type(value) == array {
for file-reader in value {
validate-file-reader(file-reader)
}
} else if type(value) == dictionary {
validate-namespace-tree(value)
} else {
validate-file-reader(value)
}
}
}
validate-namespace-tree(namespace)
let help-function = (
..args,
search: none,
searching: "ndp", // Enable search of: name, descriptions, parameters
style: style
) => {
if search == none {
if args.pos().len() == 0 { return none }
let name = args.pos().first()
help-box(get-docs(name, namespace, package-name, style, onerror: onerror))
} else {
search-docs(search, searching, namespace, style)
}
}
help-function
}
#let flatten-namespace(namespace) = {
let sub-namespace-name = ""
let flatten-impl(dict, name) = {
let name-without-dot = name.trim(".")
let flattened-dict = ((name-without-dot): ())
for (key, value) in dict {
if type(value) == function { value = (value,) }
if key == "." {
flattened-dict.at(name-without-dot) += value
} else if type(value) == array {
flattened-dict.insert(name + key, value)
} else if type(value) == dictionary {
let u = flatten-impl(value, name + key + ".")
flattened-dict += u
}
}
return flattened-dict
}
let flattened-namespace = flatten-impl(namespace, "")
}
#flatten-namespace((
".": read,
"math": read,
"matrix": (
".": (read, read),
"vector": (
"algebra": read,
"addition": (
"binary": read
)
)
),
)) |
https://github.com/davidedomini/DTM-2425-Crash-Course | https://raw.githubusercontent.com/davidedomini/DTM-2425-Crash-Course/master/slides/lesson03.typ | typst | Apache License 2.0 | #import "@preview/polylux:0.3.1": *
#import "@preview/fontawesome:0.1.0": *
#import themes.metropolis: *
#show: metropolis-theme.with(
aspect-ratio: "16-9",
)
#set text(font: "Fira Sans", weight: 350, size: 20pt)
#show math.equation: set text(font: "Fira Math")
#set strong(delta: 200)
#set par(justify: true)
#set quote(block: true)
#show quote: set align(left)
#show quote: set pad(x: 2em, y: -0.8em)
#set raw(tab-size: 4)
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 1em,
radius: 0.7em,
width: 100%,
)
#show bibliography: set text(size: 0.8em)
#show footnote.entry: it => {
block(inset: (x: 2em, y: 0.1em))[#text(size: 0.75em)[#it.note.body]]
}
#let fcite(clabel) = {
footnote(cite(form: "full", label(clabel)))
}
#let author = block(inset: 0.1em)[
#table(inset: 0.5em, stroke: none, columns: (auto, 4fr), align: (left, left),
[#alert[*<NAME>*]], [`<EMAIL>`],
)
#place(right, dy:-1.5em)[
#figure(image("images/disi.svg", width:40%))
]
]
#let arrow = box[
#figure(image("images/arrow.svg", width: 2%))
]
#title-slide(
title: "Introduction to Programming Languages",
subtitle: "Digital Transformation Management @ 2024",
author: author,
// date: datetime.today().display("[day] [month repr:long] [year]"),
)
#slide(title:"Overview of Developer Tools")[
- #alert[Why Tools Matter:] Efficiency, Quality, Collaboration
- #underline[Categories of Tools:]
- IDEs (Integrated Development Environments)
- Linters and Code Formatters
- Debugging Tools
- Version Control (Git)
- CI/CD (Continuous Integration/Continuous Delivery)
]
#focus-slide[IDEs]
#slide(title:"IDEs")[
#align(center)[
_An #alert[Integrated Development Environment] (IDE) is a comprehensive software tool that provides everything a developer needs in one place. It combines a code editor, compiler/interpreter, debugger, and other useful features to facilitate the software development process._
]
=== Why should we use an IDE?
- #alert[Productivity Boost:] provides shortcuts, code suggestions, and integrated tools to speed up coding
- #alert[Error Reduction:] immediate feedback through syntax highlighting and error detection
- #alert[Code Management:] makes organizing, searching, and navigating through large codebases easier
]
#slide(title:"Core features of IDEs")[
- #alert[Code Editor]
- The main workspace where you write code.
- Supports syntax highlighting (colors specific parts of code based on language)
- Auto-completion suggests possible code completions as you type, speeding up development and reducing errors
- Many editors offer code snippets, allowing you to insert common code blocks quickly
- #alert[Debugger]
- Built-in tools to test and troubleshoot your code.
- Set breakpoints to pause the execution at specific lines of code
- Step-through feature to execute code line-by-line, helping you understand the flow and locate bugs
- Inspect variables and states while the program is running to find incorrect logic or data
- #alert[Compiler/Interpreter Integration]
- Run your code directly within the IDE
- Provides error messages and warnings during compilation, helping you spot issues early
- Support for various languages through plugins (e.g., Java, Python, C++)
- #alert[Version Control Integration]
- Built-in tools for managing your code through version control systems like Git
- Allows you to commit, push, pull, and merge changes directly from the IDE
- Visual tools for comparing changes between file versions
- #alert[Package Management]
- IDEs often integrate with package managers like npm (JavaScript) or pip (Python)
- Allows easy installation and management of external libraries and dependencies
- #alert[Code Refactoring Tools]
- Simplify and clean up code without changing its functionality
- Common refactoring options: rename variables, extract methods, inline variables, and more
- Ensures your code stays maintainable and readable over time
- #alert[Customization & Extensions]
- Most IDEs support plugins and themes
- Customize your development environment by adding tools for specific programming languages, linters, code formatters, or even team collaboration tools like Slack or Jira
]
#slide(title:"Advantages of Using an IDE")[
- #alert[Efficiency:] a one-stop solution for coding, debugging, testing, and deploying software, no need to switch between different tools
- #alert[Consistency:] provides a consistent development environment, reducing setup time and ensuring that code behaves the same for all team members
- #alert[Collaboration:] shared configurations and built-in version control integration make team-based development smoother
- #alert[Learning Curve:] can simplify the learning process for new developers by offering autocomplete, helpful tooltips, and built-in documentation
]
#slide(title:"Some Popular IDES")[
#figure(
image("images/ides.svg")
)
]
#slide(title:"Choosing the Right IDE")[
- #alert[Project Type:] some IDEs are optimized for specific languages or platforms. For example, PyCharm for Python, IntelliJ IDEA for Java, or Xcode for iOS/macOS
- #alert[Customization:] tools like VS Code offer a vast marketplace of extensions, making it a flexible choice for a variety of languages and frameworks
- #alert[Team Collaboration:] consider the tools your team uses for version control and debugging. IDEs like JetBrains' family (PyCharm, IntelliJ IDEA) and VS Code offer robust Git integration
- #alert[Performance:] IDEs like Eclipse and IntelliJ IDEA can be heavy on system resources, while lighter editors like VS Code provide flexibility at the cost of requiring more setup for complex workflows
]
#focus-slide[Linters and Code Formatters]
#slide(title:"Linters and Code Formatters")[
#align(center)[
_A #alert[linter] is a tool that analyzes your source code for potential errors, bugs, style violations, or suspicious constructs. It helps enforce coding standards, improving code quality and reducing bugs before they even occur_
]
]
#slide(title:"Why Linters are Important")[
- #alert[Prevents bugs early:] helps catch mistakes that could lead to bugs before they reach production
- #alert[Enforces consistency:] ensures that all team members follow the same coding conventions, making code more readable and maintainable
- #alert[Saves time:] automated checks reduce the need for manual code reviews on style issues
]
#slide(title:"Common Linter Types")[
- #alert[Syntax Linters:]
- Focus on basic #underline[syntactical correctness] (e.g., missing parentheses, incorrect variable declarations)
- Example: JSLint for JavaScript
- #alert[Style Linters:]
- Focus on enforcing #underline[coding style guidelines], such as indentations, naming conventions, and spacing
- Example: ESLint for JavaScript, Pylint for Python
- #alert[Static Analysis Linters:]
- Perform deeper analysis to catch #underline[logical errors or code that may lead to bugs], such as unused variables, unreachable code, or inefficient loops
- Example: SonarQube (supports multiple languages)
]
#slide(title:"Code Formatters")[
#align(center)[
_A #alert[code formatter] is a tool that automatically formats your code to match a specific style guide, ensuring consistency throughout the project_
]
- After writing code, the formatter adjusts the layout, applying uniform styling #underline[based on predefined rules] (such as line length, indentation, spaces vs. tabs, etc.)
- Why Use a Code Formatter?
- #alert[Enforces consistency:] keeps code style uniform across the project
- #alert[Saves time:] developers no longer need to worry about formatting issues during code reviews
- #alert[Improves readability:] well-formatted code is easier to read and maintain
]
#focus-slide[Debugging Tools]
#slide(title:"Debugging Tools")[
#align(center)[
_#alert[Debugging] is the process of identifying, isolating, and fixing issues or bugs in your code. Bugs can manifest as errors, incorrect logic, or unexpected behavior that disrupts the intended functionality of the program._
]
- #underline[Why Debugging is Important:]
- Ensures your code works as intended
- Helps identify logical errors or unintended consequences in the code
- Essential for maintaining code quality and reducing future errors
]
#slide(title:"How Debuggers Work")[
- A debugger helps you run your code #underline[interactively], allowing you to:
- #alert[Pause] (Break) the execution at specific points
- #alert[Inspect] the values of variables and the state of the program at any given point
- #alert[Step] through code line-by-line to see exactly how it is being executed
- #alert[Change] variable values during execution to test different scenarios
]
#focus-slide[Version Control System]
#slide(title:"Version Control Systems")[
#align(center)[
_A #alert[Version Control System] (VCS) is a tool that tracks and manages changes to code over time. It allows multiple developers to collaborate, maintain historical versions of the code, and resolve conflicts when merging changes from different contributors._
]
]
#slide(title:"Why Use Version Control?")[
- #alert[Collaboration:] multiple developers can work on the same codebase simultaneously
- #alert[Backup and Restore:] you can revert to previous versions of your code if something goes wrong
- #alert[Track Changes:] keep a history of all modifications, including what changed, who made the change, and why
- #alert[Branching and Merging:] safely experiment with new features without disrupting the main codebase
]
#slide(title:"Git")[
=== What is Git?
- Git is the most popular distributed version control system (VCS) used in software development
=== Why Git?
- #alert[Distributed:] every developer has a full copy of the entire codebase and its history
- #alert[Branching:] Git's lightweight branching model encourages experimentation and easy integration of new features
- #alert[Speed and Efficiency:] operations like committing changes, switching branches, and merging are very fast in Git compared to older VCS systems
]
#focus-slide[Last Lab]
#slide(title:"Lab 2")[
#side-by-side[
#link("https://tinyurl.com/DTM-LAB02")
][
#figure(image("images/DTM-LAB02.svg", width:50%))
]
] |
https://github.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024/master/entries/pre_building/spin_up_reflections.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/templates/entries.typ": *
#import "/templates/headers.typ": *
#import "/templates/text.typ": *
#create_footerless_page(
title: [Spin Up Reflections],
date: [],
content:[
#box_header(
title: [Networking],
color: blue.lighten(60%)
) \
#entry_text()
We've discovered that one of the most effective ways to learn is through engaging conversations with teams from diverse regions. Despite not qualifying for the world championships, a golden opportunity emerged at the US Open when we had the chance to connect with a remarkable team that would eventually make it to the top 8 teams at Worlds: team 2775V. Their insights were invaluable, and they introduced us to their ingenious creation – the JAR Template. The template includes everything needed in the programming aspect, from PID to Odometry. The best part is that it is compatible with Vexcode V5 Pro, which most are not. It was also great to learn about how they approach alliances, prepare for matches, and their communication in the driving pit.
#image("/assets/gabe_and_sammy.jpg")
#entry_text()
#align(center)[
_Gabriel with members of 2775V at US Open_
]
#box_header(
title: [Cad],
color: yellow.lighten(60%)
) \
#entry_text()
Last season there was a concern regarding the lack of designing and planning in the club. The coaches noticed that the team was building robots blindly and recommended spending some independent time creating CADs before starting to build. The benefit of creating a CAD design for a drive-train before attempting to physically create it is that it allows for freely changing the spacing of the gears to get it correct and as compact as possible. Below is a prototype of a 6 motor drive, which the team might plan to recreate. The drivetrain uses a 3:5 ratio, 3 '25 omni wheels, and an RPM of 360.
#box_header(
title: [Driving],
color: red.lighten(60%)
) \
#entry_text()
Last season, we realized the importance of consistent and sufficient practice for our driver to perform at their best. While we faced challenges in tournaments due to inadequate practice time, we have learned from this and are taking a new approach this season. As the current driver, I have prioritized practicing fundamental skills, such as maneuvering around obstacle courses, to improve my driving abilities. By tracking my progress and regularly practicing, I am confident that I will be able to compete at a higher level and contribute to the team's success in this season.
]
)
#create_headerless_page(
design: [],
witness: [],
content: [
#box_header(
title: [Team Efficiency],
color: blue.lighten(60%)
) \
#entry_text()
Throughout last season, our team's performance in Vex Robotics tournaments suffered from a lack of efficiency. As the new lead of Team 53B in our upcoming competition, I recognize the importance of adhering to Akin's Law of Spacecraft Design. This principle emphasizes the value of simplicity, avoiding unnecessary complexity, and focusing on essential tasks to increase efficiency and productivity.
Thanks to our coach, we have embraced Akin's Law as a valuable framework for our Vex Robotics process. Before designing and building our robot for the new game challenge, we have made sure to do the necessary math and physics calculations, especially for climbing the pole. As the lead programmer, I am testing our code to ensure its reliability and efficiency.
David, our builder, is following Conway's Law, which advocates for organizing teams based on the system they are designing. By working closely with Jin, our CAD specialist, David ensures that our robot is built in a modular and cohesive way. This approach makes it easier to maintain and modify our robot during the competition.
Immad, our driver, is following Murphy's Law, which anticipates and prepares for the worst-case scenarios. By thoroughly testing the robot's programming and drivetrain's reliability, Immad is ready to handle unforeseen circumstances and make quick decisions during matches.
Juan, our scout, is following Pareto's Law, which prioritizes the most impactful data. He is gathering and analyzing key information to inform our strategy for each match, maximizing our scouting efficiency.
As a team, we are committed to notebooking and documenting our progress and lessons learned. By following Akin's Law of Spacecraft Design, Conway's Law, Murphy's Law, and Pareto's Law, we are working together cohesively to achieve success in our upcoming Vex Robotics competition.
#box_header(
title: [Organization],
color: purple.lighten(60%)
) \
#entry_text()
Last season, organization was a big problem for our team. Things were constantly getting lost, and it created many situations where we had to compromise. This year, I want to have an emphasis on organized workflow, as well as more organized operation of the bot. One change we have decided to make is making our notebook virtual. This allows work to be split a lot easier, and prevents one member from being overwhelmed.
]
)
|
https://github.com/Amelia-Mowers/typst-tabut | https://raw.githubusercontent.com/Amelia-Mowers/typst-tabut/main/doc/example-snippets/import-csv.typ | typst | MIT License | #import "@preview/tabut:<<VERSION>>": tabut, rows-to-records
#import "example-data/supplies.typ": supplies
#let auto-type(input) = {
let is-int = (input.match(regex("^-?\d+$")) != none);
if is-int { return int(input); }
let is-float = (input.match(regex("^-?(inf|nan|\d+|\d*(\.\d+))$")) != none);
if is-float { return float(input) }
input
}
#let titanic = {
let titanic-raw = csv("example-data/titanic.csv");
rows-to-records( titanic-raw.first(), titanic-raw.slice(1, -1) )
.map( r => {
let new-record = (:);
for (k, v) in r.pairs() { new-record.insert(k, auto-type(v)); }
new-record
})
} |
https://github.com/pluttan/electron | https://raw.githubusercontent.com/pluttan/electron/main/dz2/dz2.typ | typst | #import "@docs/bmstu:1.0.0":*
#import "@preview/tablex:0.0.8": tablex, rowspanx, colspanx, cellx
#show: student_work.with(
caf_name: "Компьютерные системы и сети",
faculty_name: "Информатика и системы управления",
work_type: "домашней работе",
work_num: "2",
discipline_name: "Электроника",
theme: "Моделирование работы усилительного каскада на биполярном ",
themecol2: "транзисторе по схеме с общим эмиттером (Вариант №19)",
author: (group: "ИУ6-42Б", nwa: "<NAME>"),
adviser: (nwa: "<NAME>"),
city: "Москва",
table_of_contents: true,
)
= Цель и задание
== Цель работы
Исследование вольт-амперных характеристик модели биполярного транзистора в программе аналогового и цифрового моделирования электрических и электронных цепей Micro-Cap 12 и расчет номиналов элементов усилительного каскада, работающего в соответствии с заданными техническими условиями.
== Задание
1) Построить семейство входных и выходных вольт-амперных характеристик биполярного транзистора (модель выбирается согласно варианту, см. приложенный к заданию файл). На полученных характеристиках отметить запрещенные режимы работы.
2) Рассчитать номиналы элементов усилительного каскада на биполярном транзисторе с общим эмиттером, при которых работа усилительного каскада удовлетворяет условиям:
- амплитуда напряжения выходного сигнала – не менее 15 % от напряжения питания;
- коэффициент усиления усилительного каскада по мощности – не менее 20 дБ;
- коэффициент нелинейных искажений выходного сигнала – не\ более 15 %;
- (напряжение питания усилительного каскада задано вариантом, в качестве входного сигнала используется гармоническое (однотональное) колебание с частотой, заданной вариантом).
== Задание по варианту
#align(center)[
#tablex(
columns: 3,
inset: 10pt,
align: center+horizon,
[Модель\ транзистора],[Напряжение\ питания, В],[Частота\ сигнала, кГц],
[KT3102E],[8,2],[1800]
)
]
= Выполнение работы
== Задание 1
Соберем схему для исследования входных и выходных ВАХ транзистора в схеме с общим эмиттером. Добавим на схему биполярный транзистор KT310E.
#img(image("1.png", width:60%), [Схема с общим эммиттером])
Проведем анализ Dynamic DC.
#img(image("2.png", width:60%), [Dynamic DC])
#pagebreak()
Запустим анализ DC. На рисунке показано окно Limits.
#img(image("3.png", width:60%), [DC Limits])
Получили 11 графиков -- выходных ВАХ при разных входных значениях.
#img(image("4.png", width:100%), [Графики ВАХ])
Не все значения на графиках являются допустимыми для этой модели транзистора. Для того чтобы получить максимально допустимые значения обратимся к документации транзистора.
#img(image("5.png", width:60%), [Документация транзистора])
Из этих значений возьмем 3: максимальный ток коллектора ($I_(К max)$), максимальное напряжение коллектор − эмиттер ($U_(К Э max)$) и максимальная мощность, рассеиваемая на коллекторе ($P_(К max)$)
#align(center)[
#tablex(
columns: 3,
inset: 10pt,
align: center+horizon,
[$I_(К max)$, мА],[$U_(К Э max)$, В],[$P_(К max)$, мВт],
[100],[20],[250]
)
]
Построим ограничивающие кривые, чтобы определить допустимый диапазон токов и напряжений для работы транзистора. Заштрихуем запрещенный режим работы.
#img(image("6.png", width:60%), [DC Limits с ограничивающими кривыми])
#img(image("7.png", width:100%), [Графики ВАХ с ограничивающими кривыми])
#img(image("8.png", width:100%), [Графики ВАХ с заштрихованной запрещенной зоной])
Построим входные ВАХ -- зависимость тока базы от напряжения коллектор-эмиттер.
#img(image("9.png", width:60%), [DC Limits для входных ВАХ])
#img(image("10.png", width:100%), [Графики входных ВАХ])
== Задание 2
Построим усилительный каскад с общим эмиттером и рассчитаем номиналы его элементов: $R_1, R_2, R_к$. А так же рассчитаем амплитуду входного сигнала.
Для этого вернемся к семейству выходных ВАХ и найдем входную силу тока $I_Б$ для самой верхней ветви, начало линейного участка которой не лежит в запрещенной области.
$ I_Б = I_(Б max) = 0.023"мА" * 7 = 161"мкА" $
Далее, по входной ВАХ определим $U_(Б Э min)$ и $U_(Б Э max)$. Для этого выделим на ней линейный участок, то что будет его началом и концом и будет $U_(Б Э min)$ и $U_(Б Э max)$ соответственно.
#img(image("11.png", width:70%), [DC Limits для входной ВАХ])
#img(image("12.png", width:100%), [График входной ВАХ])
$ U_(Б Э min) = 673.892"мВ"; U_(Б Э max) = 739.692"мВ" $
Определим среднее из этих двух значений:
$ U_"БЭ0" = (U_(Б Э min) + U_(Б Э max))/2 = 706.792"мВ" $
Из полученных значений определим амплитуду входного сигнала:
$ U_"Ампл" = U_"БЭ0" - U_(Б Э min) = 32.9"мВ" $
Далее определим сопротивление $R_k$ для этого проведем на графиках выходных вах нагрузочную характеристику через точки $U = E_п; I = 0$ и точку начала линейного участка наибольшей допустимой ВАХ.
#img(image("13.png", width:90%), [Нагрузочная характеристика])
При $U = 0$ получаем, что $I_k = 94"мА"$. Тогда по закону Ома получаем:
$ R_k = E_п/I_k = 8.2/(94*10^"-3") = 87.23 "Ом" $
Теперь определим номиналы $R_1$ и $R_2$. Возьмем, что силы тока на этих резисторах совпадают и равны $I_D (I_"Б0"<< I_D)$. По закону Ома: $E_п = I_D (R_1 + R_2)$; $U_"БЭ0" = I_D R_2$. Тогда получаем
$ E_п/U_"БЭ0" = (R_1 + R_2)/R_2 $
Возьмем, что $R_2 = 100 "Ом"$ и вычислим $R_1$:
$ 8.2/(706.792*10^"-3") = (R_1 + 100)/100 arrow R_1 = 1060.17 "Ом" $
Вот какая схема вышла в итоге:
#img(image("14.png", width:60%), [Усилительный каскад с общим эмиттером])
Проведем анализ переходных процессов. Для начала рассмотрим входное и выходное напряжение в зависимости от времени.
#img(image("15.png", width:60%), [Transient Limits])
#img(image("16.png", width:60%), [Анализ Transient])
Рассмотрим входную амплитуду: по заданию она должна быть больше, чем $E_п/100*15 = 0.082*115 = 1.23$.
#img(image("17.png", width:60%), [Анализ Transient])
По графику определим максимум и минимум синусоиды и получим:
$ U_"Ампл вых" = (5.525 - 0.881)/2 = 2.322 > 1.23 $
Построим график нелинейных искажения выходного сигнала.
#img(image("18.png", width:80%), [Transient Limits])
#img(image("19.png", width:100%), [График нелинейных искажений])
Искажения находятся в приделах красной линии -- условие менее 15% искажений выполняется.
Вычислим коэффициент усиления усилительного каскада по мощности.
$ K_p = P_"вых"/P_"вх" = (I_"k0"*U_"k0")/(I_"БЭ0"* U_"БЭ0") = (0.047*4.1)/(0.00066*0.706792) = 415 $
$ K_"p d" = 10 ∗ log_"10" (k_p) = 10 ∗ log_"10" (415) = 26.1 "Дб" > 20 "Дб" $
Все условия выполнены.
== Вывод
При выполнении домашнего задания были применены знания о расчете номиналов элементов усилительного каскада класса "А". Были изучены устройство и работа транзистора, входные и выходные ВАХ транзистора и анализ выходных графиков на запрещенные зоны. Результаты соответствуют условию домашнего задания, следовательно, схема усилительного каскада собрана верно.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-14.typ | typst | Other | // Test the `insert` and `remove` methods.
#{
let array = (0, 1, 2, 4, 5)
array.insert(3, 3)
test(array, range(6))
array.remove(1)
test(array, (0, 2, 3, 4, 5))
}
|
https://github.com/abaisero/abaisero-typst | https://raw.githubusercontent.com/abaisero/abaisero-typst/main/README.md | markdown | # abaisero-typst
This repository contains the `abaisero.typ` typst style package, which contains
a bunch of commands and definitions I use very frequently.
[This document][example] shows all the provided commands.
[example]: example.pdf
## Commands
* **math**: Mathematics
* **linalg**: Linear algebra
* **optim**: Optimization
* **stats**: Statistics
* **dists**: Distributions
* **ml**: Machine learning
* **rl**: Reinforcement learning
* **misc**: Miscelanea, e.g., commands that exists in latex
|
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Maths_Expertes_Ex_14_11_2023.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Maths Expertes Ex 14 11 2023",
authors: (
"<NAME>",
),
date: "11 Novembre, 2023",
)
#set heading(numbering: "1.1.")
== Démonstration 1
<démonstration-1>
+ L’équation az+b\=0 à une seule solution $minus b / a$ avec
$a eq.not 0$ ou aucune solution si $a eq 0$ donc L’équation a bien au
plus une solution. Or l’équation est de degré 1 donc l’équation a au
plus n solutions.
+ Si $P$ n’a pas de solution l’équatio $P lr((z)) eq 0$ n’a pas de
solution donc elle a bien moins de $lr((n plus 1))$ solutions.
+ On sait que $P lr((z))$ est un polynôme de degré $n plus 1$ et peut
être écris sous la forme $lr((z minus a)) Q lr((z))$, le polynôme
$lr((z minus a))$ est de degré 1 car z est à la première puissance Or
deux polynôme multiplié on pour degré leur puissance respective
additionnée soit pour trouver $P lr((z))$ avec un degré $n plus 1$ le
polynôme $Q lr((z))$ a un degré $n$.
+ $P lr((z)) eq 0 arrow.r.double lr((z minus a)) Q lr((z)) eq 0$ donc
$z eq a$ ou $Q lr((z)) eq 0$ or d’après l’hypothèse de récurrence un
polynôme de degré n a au plus n solutions donc $P lr((z)) eq 0$ a au
plus $lr((n plus 1))$ solutions
+ Car les racines d’un polynôme $P$ sont les solutions de
$P lr((z)) eq 0$
== Démonstration 2
<démonstration-2>
+ Lorsque $q eq.not 1$ on a
$1 plus q plus dot.basic dot.basic dot.basic plus q^(n minus 2) plus q^(n minus 1) eq frac(q^n minus 1, q minus 1)$
donc par produit en croix des fractions on obtient
$q^n minus 1 eq lr((q minus 1)) lr((1 plus q plus dot.basic dot.basic dot.basic plus q^(n minus 2) plus q^(n minus 1)))$
et pour $q eq 1$ on a $q^n minus 1 eq 0$ et $q minus 1 eq 0$. Quand
$a eq 0$ on a $z^n eq z^(n minus 1) z$ donc la propriété est vraie.
Quand $a eq.not 0$
$z^n / a^n minus 1 eq lr((z / a minus 1)) lr((1 plus z / a plus dot.basic dot.basic dot.basic plus z^(n minus 2) / a^(n minus 2) plus z^(n minus 1) / a^(n minus 1)))$
$z^n minus a^n eq lr((z minus a)) lr((z^(n minus 1) plus a z^(n minus 2) plus dot.basic dot.basic dot.basic plus a^(n minus 2) z plus a^(n minus 2)))$
+ Soit $P$ un polynôme de degré n
$ P lr((z)) eq a_n z^n plus a_(n minus 1) z^(n minus 1) plus dot.basic dot.basic dot.basic plus a_1 z plus a_0 $
$ P lr((a)) eq a_n a^n plus a_(n minus 1) a^(n minus 1) plus dot.basic dot.basic dot.basic plus a_1 a plus a_0 eq 0 $
$ P lr((z)) minus P lr((a)) eq a_n lr((z^n minus a^n)) plus a_(n minus 1) lr((z^(n minus 1) minus a^(n minus 1))) plus dot.basic dot.basic dot.basic plus a_1 lr((z minus a)) $
$ P lr((z)) minus P lr((a)) eq a_n lr((z minus a)) lr((sum_(k eq 0)^(n minus 1) z^(n minus 1 minus k) a^k)) plus a_(n minus 1) lr((z minus a)) lr((sum_(k eq 0)^(n minus 2) z^(n minus 1 minus k) a^k)) plus dot.basic dot.basic dot.basic plus a_1 lr((z minus a)) $
$ P lr((z)) eq P lr((z)) minus P lr((a)) eq lr((z minus a)) lr((a_n sum_(k eq 0)^(n minus 1) z^(n minus 1 minus k) a^k plus a_(n minus 1) sum_(k eq 0)^(n minus 2) z^(n minus 1 minus k) a^k plus dot.basic dot.basic dot.basic plus a_1)) $
Donc il existe bien un polynôme $Q$ tel que
$P lr((z)) eq lr((z minus a)) Q lr((z))$ avec
$Q lr((z)) eq a_n sum_(k eq 0)^(n minus 1) z^(n minus 1 minus k) a^k plus a_(n minus 1) sum_(k eq 0)^(n minus 2) z^(n minus 1 minus k) a^k plus dot.basic dot.basic dot.basic plus a_1$
== Exercice 38
<exercice-38>
$ R lr((z)) eq 8 z^3 minus 1 $
$ R lr((z)) eq lr((root(3, 8) z))^3 minus 1^3 eq lr((root(3, 8) z minus 1)) lr((lr((root(3, 8) z))^2 plus root(3, 8) z plus 1)) $
$ R lr((z)) eq lr((2 z))^3 minus 1^3 eq lr((2 z minus 1)) lr((4 z^2 plus 2 z plus 1)) $
$R lr((z)) eq 0 arrow.r.double$ $cases(2 z minus 1 eq 0, 4 z^2 plus 2 z plus 1 eq 0)$ \
$arrow.r.double$ $cases(z_0 eq 1 / 2, Delta eq minus 12 eq lr((2 sqrt(3) i))^2 lt 0 upright("Donc il existe deux solutions complexes conjuguées") z_1 eq minus 1 / 4 plus sqrt(3) / 4 i quad z_2 eq overline(z_1) eq minus 1 / 4 minus sqrt(3) / 4 i)$
\
$S_(bb(C)) eq brace.l 1 / 2 semi minus 1 / 4 plus sqrt(3) / 4 i semi minus 1 / 4 minus sqrt(3) / 4 brace.r i$
== Exercice 39
<exercice-39>
+ Il existe un racine réelle évidente de $R$
$R lr((1)) eq lr((1))^3 minus 1 eq 0$ donc 1 est racine de $R$
+ Donc $R lr((z))$ peut s’écrire sous la forme
$R lr((z)) eq lr((z minus 1)) lr((z^2 plus z plus 1))$ et les racines
de $lr((z^2 plus z plus 1))$ sont
$Delta eq minus 3 eq lr((sqrt(3) i))^2 lt 0$ donc il y a deux
solutions complexes conjuguées
$z_1 eq minus 1 / 2 plus sqrt(3) / 2 i quad z_2 eq minus 1 / 2 minus sqrt(3) / 2 i$
donc $z^2 plus z plus 1$ peut s’écrire sous la forme
$lr((z plus 1 / 2 plus sqrt(3) / 2 i)) lr((z plus 1 / 2 minus sqrt(3) / 2 i))$
donc on
$R lr((z)) eq lr((z minus 1)) lr((z plus 1 / 2 plus sqrt(3) / 2 i)) lr((z plus 1 / 2 minus sqrt(3) / 2 i))$
== Exercice 48
<exercice-48>
+ Il existe une racine entière évidente de $P$
$P lr((3)) eq 3^3 minus 9 lr((3))^2 plus 31 lr((3)) minus 39 eq 27 minus 81 plus 93 minus 39 eq 0$
+ On peut donc écrire $P$ sous la forme
$P lr((z)) eq lr((z minus 3)) lr((a z^2 plus b z plus c)) eq a z^3 plus lr((b minus 3 a)) z^2 plus lr((c minus 3 b)) z minus 3 c$
avec $a eq 1 comma b eq minus 6 comma c eq 13$ soit
$P lr((z)) eq lr((z minus 3)) lr((z^2 minus 6 z plus 13))$ Les racines
de $z^2 minus 6 z plus 13$ peut s’obtenir en calculant le discriminant
$Delta eq minus 16 eq lr((4 i))^2 lt 0$ donc il existe deux solutions
complexes conjuguées $z_1 eq 3 plus 2 i quad z_2 eq 3 minus 2 i$. On
remarque que toutes les racines de $P lr((z))$ on $R e lr((a)) eq 3$
donc les points correspondant aux affixes des racines sont alignés sur
la droite vertical passant par le point d’affixe 3 sur le plan
complexe et d’équation cartésienne $x eq 3$.
|
|
https://github.com/Myriad-Dreamin/shiroa | https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/packages/shiroa/supports-text.typ | typst | Apache License 2.0 |
#let _styled = smallcaps("").func();
#let _equation = $1$.func();
#let _sequence = [].func();
/// Collect text content of element recursively into a single string
/// https://discord.com/channels/1054443721975922748/1088371919725793360/1138586827708702810
/// https://github.com/Myriad-Dreamin/shiroa/issues/55
#let plain-text(it) = {
if type(it) == str {
return it
} else if it == [ ] {
return " "
}
let f = it.func()
if f == _styled {
plain-text(it.child)
} else if f == _equation {
plain-text(it.body)
} else if f == text or f == raw {
it.text
} else if f == smartquote {
if it.double {
"\""
} else {
"'"
}
} else if f == _sequence {
it.children.map(plain-text).filter(t => type(t) == str).join()
} else {
none
}
}
|
https://github.com/Quaternijkon/QUAD | https://raw.githubusercontent.com/Quaternijkon/QUAD/main/README.md | markdown | Typst Theme With For Colours. |
|
https://github.com/ivaquero/book-control | https://raw.githubusercontent.com/ivaquero/book-control/main/13-动态规划.typ | typst | #import "@local/scibook:0.1.0": *
#show: doc => conf(
title: "最优控制",
author: ("ivaquero"),
header-cap: "现代控制理论",
footer-cap: "github@ivaquero",
outline-on: false,
doc,
)
= 最优控制
<最优控制>
最优控制是为了得到在约束条件下最优系统表现。
== 位置控制
<位置控制>
对独轮车模型
#figure(
image("images/model/unicycle.drawio.png", width: 40%),
caption: [独轮车],
supplement: "图",
)
令
#block(
height: 5em,
columns(3)[
- 位置
- $x_1(t) = p_x(t)$
- $x_2(t) = p_y(t)$
- 速度
- $x_3(t) = v(t)$
\
- 角速度
- $x_4(t) = θ(t)$
],
)
于是有
$ 𝒙(t) = mat(delim: "[", p_x(t); p_y(t); v(t); θ(t)) $
设计输入(控制量)
$ 𝒖(t) = mat(delim: "[", u_1(t); u_2(t)) = mat(delim: "[", α_1(t); ω_2(t)) $
可得
$
dv(𝒙(t), t) =
mat(delim: "[", v(t) cos θ(t); v(t) sin θ(t); 0; 0) +
mat(delim: "[", 1; 0; α(t); ω(t)) = f(𝒙(t)), 𝒖(t)
$
#pagebreak()
== 离散化
<离散化>
对时间$t$离散化,有
$ 𝒙_([k+1]) = f_d [𝒙_([k]), 𝒖_([k])] $
设目标为
$ 𝒙_d = mat(delim: "[", p_(x d)(t); p_(y d)(t); 0; 0) $
设计代价函数(性能指标)
$
J &= ∑_(i=1)^4 (x_(i[N]) - x_(i d))^2\
&= (𝒙_([N]) - 𝒙_d)^(⊤)(𝒙_([N]) - 𝒙_d)
$
寻找合适的控制策略,使$J$最小
$
𝒖^* =[𝒖_([0]), 𝒖_([1]), 𝒖_([2]), …, 𝒖_([N-1])] \
𝒖^* = "arg" min J
$
考虑实际因素,每个状态变量的重要性不同,于是有
$
J
&= 1 / 2 (𝒙_([N]) - 𝒙_(d[N]))^(⊤) 𝑺 (𝒙_([N]) - 𝒙_(d[N]))\
&= 1 / 2 (𝒙_([N]) - 𝒙_(d[N]))^(⊤)
dmat(delim: "[", S_1, S_2, S_3, S_4)(𝒙_([N]) - 𝒙_(d[N]))\
&= 1 / 2 ∑_(i=1)^4 S_i (x_(i[N]) - x_(i d[N]))^2\
&= 1 / 2 norm(𝒙_([N]) - 𝒙_(d[N]))_𝑺^2
$
其中,$𝑺_n$为半正定对称阵,$1/2 norm(𝒙_([N]) - 𝒙_(d[N]))_𝑺^2$称末端代价,$n$为自变量个数。
== 实际约束
<实际约束>
考虑物理约束(硬约束)
- 速度范围
- 控制量
同时,考虑能耗,有
$
J = 1 / 2 lr(norm(𝒙_([N]) - 𝒙_(d[N])))_𝑺^2 + 1 / 2 ∑_(k=1)^(N - 1) norm(𝒖_([k]))_𝑹^2
$
其中,$𝑹 = mat(delim: "[", r_1, med; med, r_2)$为正定对称阵。由于其通过算法对$J$进行约束,故属于软约束
- 不关注能耗,则$𝑺 ≫ 𝑹$
- 关注能耗,则$𝑹 ≫ 𝑺$
#tip[
$𝑹_(p × p)$正定时,$J$方有最小值。
]
在硬、软约束的基础上,对轨迹进行约束,有
$
J = 1 / 2 norm(𝒙_([N]) - 𝒙_(d[N]))_𝑺^2 + 1 / 2 ∑_(k=1)^(N - 1)(norm(𝒙_([k])) - 𝒙_(d[k]))_𝑸^2 + norm(𝒖_([k]))_𝑹^2
$
其中,$𝑸_(n × n)$为半正定对角阵,$1/2 norm(𝒙_([k]) - 𝒙_(d[k]))_𝑸^2$称运行代价。
又轨迹中间点,$p_(x[k]), p_(y[k]) in p^*_(x[k]), p^*_(y[k])$,则
$ 𝒙_(1[k]), 𝒙_(2[k]) in X^* $
称为容许轨迹(admissible trajectory)。而控制量约束
$ 𝒖^* ∈ Ω $
称为容许控制域(set of admissible control)。
= 动态规划
<动态规划>
动态规划由 <NAME> 于 1966 年在《Science》上发表。
== 高度控制
<高度控制>
对无人机模型,现需要求解,从地面升高至 10m 的最短时间
#figure(
diagram(
node-fill: gradient.radial(white, blue, radius: 100%),
node-stroke: blue,
node((2, 0), [m], shape: rect),
node((2, 1), [mg], fill: none, stroke: none),
node((2, -1), [f(t)], fill: none, stroke: none),
node((1.2, -.5), [h(t)], fill: none, stroke: none),
edge((2, 0), "u", "->", snap-to: (<bar>, auto)),
edge((2, 0), "d", "->", snap-to: (<bar>, auto)),
edge((2, 0), "l", "-"),
edge((1.5, 0), "u", "->"),
),
caption: [无人机模型],
supplement: "\n图",
)
#block(
height: 9em,
columns()[
初始和最终条件为
- $h(0) = 0$
- $dot(h)(0) = 0$
- $h_f = 10$
- $dot(h)_f = 0$
物理约束为
- $a(t) in[-3, 2]$
- $v(t) in[0, 3]$
],
)
关系式为
$ m dot.double(h)(t) = f(t) - m g $
控制量为
$ u = 1 / m (f(t)) - m g = a $
其中,$f(t) = F(v_("motor"))$
于是有
- $macron(v) = 1 / 2 (v(k)) + v(k + 1)$
- $t = dd(x) / 1 / 2 (v_k + v_(k + 1))$
- $a = (v_k + v_(k + 1)) / t$
== 策略
<策略>
- 以终为始
- 空间换时间
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fh-joanneum-iit-thesis/1.1.0/template/chapters/2-intro.typ | typst | Apache License 2.0 | #import "global.typ": *
= Introduction
#v(1em)
#quote(
[Privacy matters; privacy is what allows us to determine who we are and who we want to be. I don't want to live in a world where there's no privacy, and therefore no room for intellectual exploration and creativity.],
[<NAME>])
#v(1em)
#lorem(25)
#todo([ Describe the kind of problem at hand? The problem is relevant in which context? What does not work well at the moment? What do people need? Describe the background, the prerequisites for your work. Optionally, add terms and definitions whenever they might not be clear to a fellow student. ])
== Problem Statement
#lorem(25)
#todo([ What is the overall problem? Give examples. Motivate! Compared to existing solutions for the problem at hand, why does someone need a better, faster, and somewhat different solution? ])
== Research Questions
#lorem(25)
#todo([ Focus on one or two main research questions and detail on them. ])
== Hypothesis
#lorem(25)
#todo([ State a hypothesis – a rough idea – of how you think a solution might look like. Explain, how to possibly solve a given problem. ])
== Method
#lorem(25)
#todo([
Describe your structured, academic approach to find — and evaluate — a solution. When you needed (large) data sets for you work, explain how you collected and filtered raw data. For the validation (see Section Evaluation 6) you want to describe the criteria for objective measurement.
])
#todo([
Note the so called "*<NAME>*": At the end of one chapter you might sum up the content. Then you give an outlook on the next chapter.
For example, at the end of the introduction you might start the text with:
_The remainder of the thesis is structured as follows:_
_The implementation is presented in @implementation (including the backend @backend and the frontend @frontend). The evaluation ...
..._
])
|
https://github.com/OCamlPro/ppaqse-lang | https://raw.githubusercontent.com/OCamlPro/ppaqse-lang/master/src/base.typ | typst | // polylux gives slides stuff
#import "@preview/polylux:0.3.1": *
// import graphical stuff
#import "@preview/cetz:0.2.0" as cetz: *
#import "@preview/fletcher:0.4.1" as fletcher: node, edge
// import formatting stuff
#import "@preview/oxifmt:0.2.1": strfmt
// logo
#let logo = table(
stroke: none,
columns: (auto, auto),
image(width: 3cm, "imgs/ocp.png"),
image("imgs/Logo carré bleu - fond transparent.png"),
)
#let common(doc) = [
#show raw.where(block: true): it => rect(width: 100%, radius: 4pt, it)
#set text(
font: ("Marianne"),
//fallback: false,
)
#show figure.where(kind: raw): it => {
show raw: set align(left)
it
}
#set par(justify: true)
#doc
]
#let presentation(body) = {
show: common
// slides need bigger font
set text(size: 22pt)
set page(
paper: "presentation-16-9",
margin: (top: 2cm, bottom: 2cm, left: 3cm, right: 3cm),
header: [
#align(center, [
#stack(dir: ttb, spacing: 2pt,
logo,
line(length: 100%)
)
])
],
numbering: "1 / 1",
footer: [
#stack(
dir: ttb,
spacing: 2pt,
line(length: 100%),
v(5pt),
align(
center + horizon,
[
#set text(size: 14pt)
#counter(page).display("1 / 1", both: true)
]
)
)
]
)
body
}
#let title-slide(title: "", subtitle: "", authors: [], body: []) = {
polylux-slide[
#align(center + horizon,
stack(dir: ttb, spacing: 1cm,
text(size: 40pt, [*#title*]),
text(size: 30pt, [*#subtitle*]),
authors,
body,
v(1fr),
image("imgs/by.png")
)
)
]
}
#let slide(body) = {
show heading: it => [#it #v(1cm)]
polylux-slide[
#body
]
}
#let abstract(body) = {
}
#let report(
title: [],
version: [],
version_title: "Version",
authors: array,
right_to_know: none,
need_to_knows: (),
paraphes: false,
reference: [],
abstract: [],
doc
) = {
/* Using common stuff */
show: common
let authors_array = authors.map(author =>
author.firstname + " " + author.lastname
+ " (" + author.email + ")"
)
/* Setting metadatas */
set document(
title: title,
author: authors_array
)
set heading(numbering: "1.")
// labeling stuff. It's fragile for now : only "confidential"
// RTK is supported and we don't check NTKS size...
let labelling(rtk, ntks) = {
if rtk != none {
show "confidential": w => text(red, upper(w))
table(
columns: (auto, auto),
[#text(size: 16pt, [#rtk])],
[#text(size: 16pt, blue, [#ntks.join(", ")])]
)
}
}
let topsize = if right_to_know != none {3cm} else {2cm}
set page(
paper: "a4",
margin: (top: topsize, bottom: 2cm, left: 3cm, right: 3cm),
header: [
#align(center, [
#stack(dir: ttb, spacing: 2pt,
logo,
line(length: 100%),
v(2pt),
labelling(right_to_know, need_to_knows)
)
])
],
numbering: "1 / 1",
footer: [
#stack(
dir: ttb,
spacing: 5pt,
line(length: 100%),
align(
center + horizon,
stack(dir: ttb, spacing: 2pt,
grid(
columns: (40%, 20%, 40%),
rows: (auto),
[],
[
#set text(size: 10pt)
#counter(page).display("1 / 1", both: true)
],
{
if paraphes {
rect(
stroke: gray.darken(40%),
width: 6cm,
height: 1cm,
radius: 2pt,
align(left, text(gray.darken(40%), [Paraphes:])))
}
},
)
)
)
)
]
)
align(
center,
stack(
dir: ttb,
spacing: 1cm,
v(10%),
text(size: 20pt, [
#set par(justify: false)
*#title*
]),
text(
size: 14pt,
table(
columns: (auto, auto),
align: (right, left),
stroke: none,
[ *#version_title:*], version,
..if reference != [] {
([*Référence:*], reference)
}
)
),
stack(
spacing: 5pt,
stack(
spacing:8pt,
text(size: 12pt)[#if authors.len() > 1 [*Auteurs:*] else [*Auteur:*]],
..authors_array,
),
..if abstract != [] {
(
v(10%),
stack(
dir: ttb,
spacing: 10pt,
text(size: 12pt)[*Résumé*],
abstract,
)
)
}
),
v(1fr),
image("imgs/by.png")
)
)
/* content */
doc
}
|
|
https://github.com/Stevens-Linux-Users-Group/resources | https://raw.githubusercontent.com/Stevens-Linux-Users-Group/resources/main/nixos-workshop/main.typ | typst | #import "@preview/touying:0.5.2": *
#import themes.university: *
#show: university-theme.with(aspect-ratio: "16-9")
= NixOS Workshop #datetime(year: 2024, month: 10, day: 08).display()
= Why NixOS?
== Reproducible builds
- All package inputs are hashed.
- In a pure build, same input $->$ same output.
- If you can build it now, you can still build it after months, or years.
== Declarative config
- Entire system can be build from a single config file.
- Declarative config + reproducible builds = time machine.
- Changing a system component is as simple as changing the config file.
- Single interface for entire system setup. Good and bad.
- Ability to restore to previous state.
== Nixpkgs
#figure(image("packages.png", height: 90%), caption: [https://repology.org/repositories/statistics/newest])
== You can do this...
```sh
nix-shell -p gimp --run gimp
nix-shell -p typst
nix-shell -p jdk8
nix-shell -p python312
nix-shell -p cargo
nix-shell -p whatever-you-want it-will-probably-work
```
Actually, you can do this on any Linux platform (and Mac(?)).
= How NixOS?
== Installation
- Graphic Calamares installer (very similar to other distros). \
https://nixos.org/download/#nixos-iso
- Manual installation also available. \
https://nixos.org/manual/nixos/stable/#sec-installation-manual \
Quicker than Arch since NixOS orchestrates for you.
== How to find things
- https://search.nixos.org/options
- https://search.nixos.org/packages
- https://home-manager-options.extranix.com/
= Show and tell
|
|
https://github.com/fredguth/abnt-typst | https://raw.githubusercontent.com/fredguth/abnt-typst/main/_config.typ | typst | #let metadados = (
titulo: "Naufrágio e ressureição da imagem",
subtitulo: "A fotografia de <NAME> inquieta o imaginário
contemporâneo",
título-curto: none,
codigo_cutter: "RR696n", //ex. S659n
codigo_cdu: none,//ex. 911.375:028
tipo_trabalho: "Dissertação de Mestrado", //ex. "Tese de Doutorado", "Dissertação de Mestrado", "Trabalho de Conclusão de Curso"
titulacao_objetivo: "Mestrado em Comunicação",
programa_pos: "Programa de Pós Graduação em Comunicação", //ex. Ciência da Computação
departamento: "Faculdade de Comunicação",
autor: (nome: "<NAME>", sobrenome_nome: "Rodrigues, <NAME>"),
publicacao: (
preambulo:"Dissertação apresentada como requisito para obtenção do título de mestre. Linha de Pesquisa: Imagem, Som e Escrita." ,
local: "Brasília",
instituicao: "UnB",
logo_instituicao: "../arquivos/logo_unb.svg",
data: 2018,
palavras-chave: "\1. Fotografia . 2. <NAME> . 3. Imagem e imaginário . 4. Redes sociais . 5. Sociedade em rede. I. Araújo de Sá, Sérgio, orient. II. Título" //ficha catalográfica
),
//instituicoes de pessoas relacionadas ao trabalho academico
supervisao: (
orientadores:(
( chamar: "Orientador:"
, nome: "<NAME>"
, sobrenome_nome: "Sá, <NAME>"
, titulo: "Prof. Dr."
),
),
coorientadores: none,
coordenador: none,
banca: none
)
)
#let estilo = (
folha: "a4",
// ABNT NBR 14724:2011 §5.1 - FORMATO
// (...) utilizar papel branco ou reciclado, no formato A4 (21 cm × 29,7 cm).
margens: (interna: 3cm, externa: 2cm, superior: 3cm, inferior: 2cm),
// ABNT NBR 14724:2011 §5.1 - FORMATO
// As margens devem ser: para o anverso, esquerda e superior de 3 cm e
// direita e inferior de 2 cm; para o verso, direita e superior de 3 cm
// e esquerda e inferior de 2 cm.
fonte:(
// serif:"Times New Roman",
// serif:"STIX Two Text",
serif:"Libre Caslon Text",
// sans:"TeX Gyre Heros",
// sans:"Helvetica",
sans:"Lato",
mono:"SF Mono",
// mono:"IBM 3270",
tamanho:(normal: (size:1em)
, large: 18pt
, larger: 20pt
, huge: 25pt
, small: 10pt
, tiny: 7pt
, corpo: 14pt
, regular:12pt
,
),
),
// ABNT NBR 14724:2011 §5.1 - FORMATO
// Recomenda-se, quando digitado, a fonte tamanho 12 para todo o trabalho (...)
// Tamanhos de letra baseadas na regular. regular = 1em
espacamento: (
// ABNT NBR 14724:2011 §5.2 - ESPAÇAMENTO
// Todo texto deve ser digitado ou datilografado com espaçamento 1,5 entre linhas
// entrelinhas: 1.5,
entrelinhas: 1.2,
entreparagrafos: 1.5,
titulos: 3,
),
numeracao: (titulos: "1.1.1.1.1", enumeracoes: "1.1.1.1.1.",),
tema: red.darken(50%), // cor do tema (afeta links e outros pequenos detalhes)
)
#let config = (
metadados: metadados,
estilo: estilo,
estrutura: (),
) |
|
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/visualization/program.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator, diagraph, codetastic
#import notebookinator: *
#import themes.radial.components: *
#import diagraph: *
#import codetastic: qrcode
#show: create-body-entry.with(
title: "Program: Data Visualization",
type: "program",
date: datetime(year: 2023, month: 11, day: 18),
author: "<NAME>",
witness: "<NAME>",
)
Now what we had a rough idea of what we were doing we could implement them. If
you want to see our final implementation you can look at it on our GitHub. #footnote([
Our implementation:
#align(
bottom,
qrcode("https://github.com/BattleCh1cken/loginator", size: 2pt),
)
]). We call it the Loginator.
= Project Overview
We decided to write this in Rust, mainly due to Rust's strong ecosystem when it
comes to command line tools. There were also existing Rust libraries for MQTT
and Bluetooth. We ended up using the following libraries:
- Clap as a CLI #footnote("See glossary.") framework.
- Btleplug as our Bluetooth library
- Rumqttc as our MQTT library
The tool establishes a Bluetooth connection with the Brain, and then polls it
for data. Once data is received, that data is decoded from COBS, and then
parsed. Once we have our data, it can be sent to a local MQTT broker. The one we
use is called Mosquitto.
= Bluetooth
Obtaining a Bluetooth connection is the most difficult part of the whole
process. The process for connecting and polling from the brain looks like this:
+ Check for Brains in the surrounding area
+ Have the user chose which Brain is theirs
+ Have the user input their Brain's Bluetooth code
+ Check if the code is correct
+ Receive data from the brain
Most of this is relatively simple and doesn't differ from Btleplug's example
code, but the authentication is a little more complicating, so we'll go over it
here.
The first thing we need to do is have the Brain display it's 4 digit
authentication codeon it's LCD screen. We can do this by sending a packet
containing `0xfffffffff` to it's system characteristic. For the uninitiated, a
characteristic is like a channel for information to be read/written to for a
Bluetooth device. ```rs
let characteristic = Self::find_characteristic(&brain, SYSTEM_CHAR).unwrap();
brain
.write(
&characteristic,
&[0xff, 0xff, 0xff, 0xff], // This tells the brain to display the verification
code on it's screen
WriteType::WithResponse,
)
.await
.unwrap();
```
Once we receive the code from the user we need to send the code to the brain
from our application to verify ourselves.
```rs
// We need to convert the code from a string to bytecode
let code: Vec<u8> = code
.trim()
.chars()
.map(|c| c.to_digit(10).unwrap() as u8)
.collect();
let characteristic = Self::find_characteristic(&brain, SYSTEM_CHAR).unwrap();
// Send the code to the Brain
brain
.write(&characteristic, &code, WriteType::WithResponse)
.await
.unwrap();
// If the code was correct the Brain will echo it back to us from the same characteristic
let response = brain.read(&characteristic).await.unwrap();
if response != code {
return Err(BrainControllerError::IncorrectCode);
}
```
= COBS
Once we have a connection with the brain, decoding the information coming off it
isn't so simple. PROS #footnote("See glossary.") uses an algorithm called COBS
(consistent overhead byte stuffing) to encode its data. This has a few benefits,
but it also means that we can't read the information coming off the Brain
directly. We'll need to decode it first.
COBS' main application is that it allows us to verify the integrity of packets
with as little overhead as possible. It does this by adding a `0x00` byte after
every packet. It then adds a byte at the beginning of the packet who's value is
equal to how many bytes away the next `0x00` byte is.
#image("./basic-cobs.svg", width: 40%)
This becomes an issue when there are existing `0x00` bytes in the packet before
encoding. COBS has a simple solution for this though. Each `0x00` byte gets
replaced with a byte that who's value is equal to the distance to the next
`0x00` byte.
#image("./complex-cobs.svg", width: 80%)
This marker bytes can then be traversed to decode the encoded byte. If the
length of the packet does not match up with the final marker byte, then we know
the packet has been corrupted.
Here's the Loginator's decoding solution: ```rs
/// Adds a single byte for the decoder to decode.
pub fn feed(&mut self, byte: u8) -> Result<Option<Vec<u8>>, DecodeError> {
if !self.is_parsing {
self.pointer = byte as usize; // The first pointer is always the overhead byte.
self.is_parsing = true;
} else if byte == 0 {
// If the byte being received is zero then we know that we have all of our data
let result = self.buffer.clone();
if !(self.buffer.len() + 1 == self.pointer) {
self.buffer = vec![];
return Err(DecodeError::InvalidLength);
}
self.buffer = vec![];
return Ok(Some(result));
} else if self.buffer.len() + 1 == self.pointer {
// If the current index is pointer then the current value was originally zero,
but was changed during encoding.
// We have to add 1 to the length to account for the overhead byte.
self.buffer.push(0);
self.pointer = self.buffer.len() + byte as usize;
} else {
// If none of the other conditions are true then the data does not need to be
modified at all.
self.buffer.push(byte);
}
Ok(None)
}
``` Bytes are fed in one at a time. The algorithm then checks if that byte is
valid based on the existing information it has. If it detects that the data is
complete and uncorrupted, it returns that data.
= Verifying Telemetry
Not all data sent by the brain is telemetry. We wanted a way to have data be
identifiable as telemetry. We use a simple regular expression to check if the
data is actually telemetry. ```rs
let regex = Regex::new(r"TELE_DEBUG:(.*?)TELE_END").unwrap();
```
This ensures that we don't accidentally parse something else.
= Final Product
Once the MQTT integration was completed, sending data to Grafana was dead
simple. All we had to do was start the Mosquitto and Grafana services locally,
and then start up the Loginator. The CLI we created only needs three commands to
get started.
```sh
loginator list-brains
# User must now change the name of the Brain in the config to match their brain
loginator display-code
# User must now put the code into the config file
loginator connect
# The the Loginator should now be connected, and ready to send information
```
Once the Loginator is configured, all the user needs to do is run the last
command, and the Loginator will work right away.
The Brain side experience is still a little shaky. In order to send data, users
are required to use LemLib. Here's an example of a packet being sent: ```cpp
#define TEMPERATURE_ROUTE 0
lemlib::telemetrySink()->debug("{},{},{}", TEMPERATURE_ROUTE,
motor1.get_temperature(), motor2.get_temperature());
// Currently the loginator will only work with debug level messages
``` The data must be numerical, separated by numbers. Data in any other format
will not work. We'd like to make this easier to use, but we're unsure of a
better way to do it.
#figure(
image("./loginator_pid.png", width: 60%),
caption: "Grafana, receiving data PID from the loginator",
)
Overall we're very happy with how this turned out, and will continue to use it
in the future. We hope that other teams will use it and benefit from it as well.
#metadata(none) <loginator-program>
|
https://github.com/andreasKroepelin/TypstJlyfish.jl | https://raw.githubusercontent.com/andreasKroepelin/TypstJlyfish.jl/main/examples/pkg.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 1em)
#import "../typst/lib.typ": *
#read-julia-output(json("pkg-jlyfish.json"))
#jl-pkg("[email protected]", "Plots")
What is $3 + 5$?
#jl(```julia
import Example
Example.domath(3)
```)
Let's plot something!
#set image(width: 10em)
#jl(```julia
using Plots
plot(pi .* (-3:.01:3), sin, legend = nothing)
```)
|
https://github.com/whs/typst-govdoc | https://raw.githubusercontent.com/whs/typst-govdoc/master/govdoctest.typ | typst | #import "thai.typ": thnum
#import "govdoc.typ": gov, govhead, govsign, govsender
#show: gov
#govhead(
id: thnum("อก 0712/ 5079"),
address: [
สำนักงานมาตรฐานผลิตภัณฑ์อุตสาหกรรม \
#thnum("ถนนพระรามที่ 6 เขตราชเทวี") \
#thnum("กรุงเทพฯ 10400")
],
date: thnum("26 มีนาคม 2561"),
title: thnum("ขอความอนุเคราะห์เผยแพร่ประชาสัมพันธ์เรื่อง ชุดสายพ่วง มอก. 2432-2555"),
attention: "อธิบดีกรมส่งเสริมการปกครองส่วนท้องถิ่น",
secrecy: "ตัวอย่าง",
)
#h(2.5cm)ด้วย สำนักงานมาตรฐานผลิตภัณฑ์อุตสาหกรรม (สมอ.) ได้กำหนดให้ผลิตภัณฑ์อุตสาหกรรม
ชุดสายพ่วงต้องเป็นไปตามมาตรฐานผลิตภัณฑ์อุตสาหกรรมเต้าเสียบและเต้ารับสำหรับใช้ในที่อยู่อาศัยและงาน
ทั่วไปที่มีจุดประสงค์คล้ายกัน : ชุดสายพ่วง มาตรฐานเลขที่ มอก. #thnum("2432-2555") เนื่องจากสาเหตุหนึ่งของ
ไฟฟ้าลัดวงจร ซึ่งเป็นต้นเหตุของการเกิดเพลิงไหม้ ส่วนใหญ่มาจากชุดสายพ่วงที่ไม่ได้มาตรฐาน โดยมีผลบังคับ
ใช้ตั้งแต่วันที่ #thnum("24 กุมภาพันธ์ 2561") เป็นต้นมา เป็นผลให้ผู้ผลิต ผู้นำเข้า และผู้จัดจำหน่าย ต้องผลิต นำเข้า และ
จำหน่ายชุดสายพ่วงที่ได้รับอนุญาต และแสดงเครื่องหมายมาตรฐานจากสำนักงานเท่านั้น
สำนักงานจึงได้จัดทำสื่อเผยแพร่เพื่อประชาสัมพันธ์เรื่องชุดสายพ่วง มอก. #thnum("2432-2555")
โดยเผยแพร่ทาง www.tisi.go.th , pr.tisi.go.th และ www.facebook.com/tisiofficial เพื่อสร้างความ
ตระหนักในการใช้ผลิตภัณฑ์ดังกล่าว ในการนี้ จึงใคร่ขอความอนุเคราะห์จากท่านประชาสัมพันธ์ให้ความรู้เรื่อง
ชุดสายพ่วงแก่องค์กรปกครองส่วนท้องถิ่นให้มีความรู้ความเข้าใจที่ถูกต้องในการเลือกซื้อชุดสายพ่วงที่ได้
มาตรฐาน โดยสามารถลิงค์ข้อมูลได้ที่ https://goo.gl/jyjFqS
จึงเรียนมาเพื่อโปรดพิจารณา สำนักงานหวังเป็นอย่างยิ่งว่าจะได้รับความอนุเคราะห์จากท่าน
และขอขอบคุณมา ณ โอกาสนี้
#govsign(
name: "นายณัฐพล รังสิตพล",
position: "เลขาธิการสำนักงานมาตรฐานอุตสาหกรรม"
)
#govsender([
กองส่งเสริมและพัฒนาด้านการมาตรฐาน \
กลุ่มส่งเสริมมาตรฐาน \
โทร. #thnum("0 2202 3429 0 2202 3517") \
โทรสาร #thnum("0 2354 3315 0 2354 3157")
])
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/lovelace/0.1.0/lib.typ | typst | Apache License 2.0 | #let ind = metadata("lovelace indent")
#let ded = metadata("lovelace dedent")
#let no-number = metadata("lovelace no number")
#let pseudocode(
line-numbering: true,
line-number-transform: it => it,
indentation-guide-stroke: none,
..children
) = {
let lines = ()
let indentation = 0
let line-no = 1
let curr-label = none
let numbered-line = true
let indentation-box = box.with(
inset: (left: 1em, rest: 0pt),
stroke: (left: indentation-guide-stroke, rest: none)
)
let rep-app(fn, init, num) = {
let x = init
for i in range(num) {
x = fn(x)
}
x
}
for child in children.pos() {
if child == ind {
indentation += 1
} else if child == ded {
indentation -= 1
} else if child == no-number {
numbered-line = false
} else if type(child) == "label" {
curr-label = child
} else {
lines.push((
no: if numbered-line and line-numbering {
align(right + horizon)[
#figure(
kind: "lovelace-line-no",
supplement: "Line",
[#line-number-transform(line-no)]
)
#curr-label
]
},
line: rep-app(
indentation-box,
pad(left: -2pt, rest: 4pt, child),
indentation
)
))
if numbered-line {
line-no += 1
}
curr-label = none
numbered-line = true
}
}
set par(hanging-indent: .5em)
let columns = if line-numbering { 2 } else { 1 }
let cells = if line-numbering {
lines.map(line => ( line.no, line.line ) ).flatten()
} else {
lines.map(line => line.line)
}
grid(
columns: columns,
column-gutter: 1em,
row-gutter: .0em,
..cells
)
}
#let algorithm = figure.with(kind: "lovelace", supplement: "Algorithm")
#let setup-lovelace(
line-number-style: text.with(size: .7em),
line-number-supplement: "Line",
body
) = {
show ref: it => if (
it.element != none and
it.element.func() == figure and
it.element.kind == "lovelace-line-no"
) {
link(
it.element.location(),
{ line-number-supplement; sym.space; it.element.body }
)
} else {
it
}
show figure.where(kind: "lovelace-line-no"): it => line-number-style(it.body)
show figure.where(kind: "lovelace"): it => {
let booktabbed = block(
stroke: (y: 1.3pt),
inset: 0pt,
breakable: true,
width: 100%,
{
set align(left)
block(
inset: (y: 5pt),
width: 100%,
stroke: (bottom: .8pt),
{
strong({
it.supplement
sym.space.nobreak
counter(figure.where(kind: "lovelace")).display(it.numbering)
[: ]
})
it.caption
}
)
block(
inset: (bottom: 5pt),
breakable: true,
it.body
)
}
)
let centered = pad(x: 5%, booktabbed)
if it.placement in (auto, top, bottom) {
place(it.placement, float: true, centered)
} else {
centered
}
}
body
}
#let comment(body) = {
h(1fr)
text(size: .7em, fill: gray, sym.triangle.stroked.r + sym.space + body)
}
|
https://github.com/nichitacebotari0/cv-typst | https://raw.githubusercontent.com/nichitacebotari0/cv-typst/master/CV.typ | typst | #let primary_colour = rgb("#3E0C87") // vivid purple
#let link_colour = rgb("#12348e") // blue
#let light_purple = rgb("#975bf1") // light purple
#let icon(name, shift: 1.5pt) = {
box(
baseline: shift,
height: 10pt,
image("icons/" + name + ".svg")
)
h(3pt)
}
#let findMe(services) = {
set text(8pt)
let icon = icon.with(shift: 2.5pt)
services.map(service => {
linebreak()
icon(service.name)
if "display" in service.keys() {
link(service.link)[#{service.display}]
} else {
link(service.link)
}
}).join(h(10pt))
[
]
}
#let term(period, location) = {
text(light_purple,9pt)[#icon("calendar") #period #h(1fr) /* #icon("location") #location */]
}
#let styled-link(dest, content) = emph(text(
fill: link_colour,
link(dest, content)
))
#let workplace(jobName, imageName, period, sidebarWidth: 30pt, location: "Chisinau, MD") = {
grid(
columns: (sidebarWidth, auto),
gutter: 5pt,
image("icons/" + imageName),
[
#v(3pt)
#heading(level: 3, jobName) \
#term[#period][]
])
}
#let positions(items: (), sidebarWidth: 30pt) = { layout(size => style(styles => {
let n = 0
for item in items {
let sidebarCircle = box(
width: sidebarWidth,
align(center + top,
circle(radius: 2.5pt, stroke: light_purple)
)
)
let positionHeader = [
#heading(level: 4,item.name)
#linebreak()
]
stack(dir: ltr,
sidebarCircle,
positionHeader)
let positionDescription = [
#item.description
]
let heightOfTitle = measure(block(width: size.width, positionHeader), styles).height
let heightOfDescription = measure(block(width:size.width, positionDescription), styles).height
let continuationLine = [
#if (n < items.len() - 1) {
block(
width: sidebarWidth,
inset: 0pt,
align(center + top,
{
v(-heightOfTitle)
rect(width: 1pt,height: heightOfDescription+heightOfTitle, fill: light_purple)
})
)
} else {
block(width: sidebarWidth)
}
]
box(stack(dir: ltr,
continuationLine,
positionDescription))
n += 1;
}
}))}
#let cv(
name: "",
links: (),
content,
) = {
set document(
title: name + "'s CV",
author: name,
)
set text(9.8pt, font: "Lato")
set page(
margin: (x: 46pt, y: 46pt),
)
show heading.where(
level: 1
): it => {
text(
fill: primary_colour,
it.body
)}
show heading.where(
level: 2
): it => text(
fill: primary_colour,
[
#{it.body}
#v(-7pt)
#line(length: 100%, stroke: 1pt + primary_colour)
]
)
show heading.where(
level: 3
): it => text(
fill: primary_colour,
it.body
)
show heading.where(
level: 4
): it => text(it.body)
stack(dir: ltr, spacing: 5pt,
image(width: 60pt,
"icons/" + "photo.jpg"),
stack(dir: ttb,
v(3pt),
[= #name],
findMe(links)
))
content
}
#cv(
name: "<NAME>",
links: (
(name: "email", link: "mailto:<EMAIL>"),
// (name: "website", link: "https://example.com/", display: "example.com"),
(name: "github", link: "https://github.com/nichitacebotari0", display: "@nichitacebotari0"),
(name: "linkedin", link: "https://www.linkedin.com/in/nichita-cebotari-015b15176/", display: "<NAME>"),
),
[
== Experience
#workplace("Alvys", "alvys.jpg","Feb 2023 --- Present", sidebarWidth: 30pt)
#positions(items: (
(name: "Senior Software Engineer",
description: [Project was a Transportation Management System for truck freight in USA. Working for over half a year on a *ASP .NET 7 Web Api* written in *C\#*. The Web Api was hosted in *Azure* Web App with *Cosmos Db* as the main data store and azure yaml pipelines for CI and classic releases for CD. Responsible for implementing the communication protocol *AS2* and business logic used for integrating with third parties, also served as a point of contact for said third parties.]),
))
#workplace("Endava", "endava.jpg","Mar 2018 --- Mar 2022", sidebarWidth: 30pt)
#positions(items: (
(name: "Software Engineer",
description: [Most recent project was a clearing bank *SOA* multi-tenant application. I was involved in the data team where we would gather data from other services that communicated over *Azure Service Bus* and process it with streaming jobs written in *Scala* using *Databricks*. Also was responsible for writing scheduled jobs that would run daily using *Azure Functions*. Deployments were done using *Terraform* and azure *Yaml pipelines*.]),
(name: "Software Developer",
description: [Worked for over 2 years on financial derivatives trading platform made up of *Windows Services* wrttien in *.NET Framework 4.6* communicating over a pub-sub *Message Bus*. Main storage was *MySQL* with data being served by a specific service. Responsibilities included imiplementing new features, fixing bugs inlegacy code, rewriting components or entire services when needed, updating *WCF* contracts exposed to upstream providers of pricing data,etc.]),
(name: "Junior Software Developer",
description: [One of the earliest projects I was involved in was a desktop app *Windows Forms*, used by brokers to approve/reject trades.Application was written in *C\#* using a *Model-View-Presenter* architecture, it communicated with backend services over a a message bus.]),
(name: "Intern",
description: [As part of internship had to implement an *MVC* backend app used for an internal library app meant for inventory tracking and allowing borrowing of books. It was written in *C\#*, using code-first *Entity Framework* to communicate with an *MSSQL* database.])
))
References available on request
#pagebreak()
== Education
=== Associate Degree \
_C.E.I.T.I._\
#term[Sep 2019 --- Jul 2023][Location, UK]
Professional Diploma in Computer Science.
// == Interests
// - Bouldering
// - Video Game Development
// - The Zig programming language
== Languages
*English:* Fluent \
*Romanian:* Fluent \
*Russian:* Fluent \
// == Projects
// ==== #link("https://example.com")[Some project]
// #lorem(30)
// #styled-link("https://example.com")[Example page]
]
) |
|
https://github.com/jamesrswift/journal-ensemble | https://raw.githubusercontent.com/jamesrswift/journal-ensemble/main/template/articles/1.typ | typst | The Unlicense | #import "/src/lib.typ" as journal
#show: journal.article.rule()
#journal.contents.mark("Advancements in Medical Technology: Bridging the gap for Enhanced Healthcare")
#journal.article.one-column(top, {
journal.article.header()
journal.article.title[
Advancements in Medical Technology: Bridging the gap for Enhanced Healthcare
]
journal.article.authors[
<NAME>, <NAME>, <NAME>, <NAME>
]
journal.article.meta[
#journal.article.dates((
("Received", "June 23 2023"),
("Accepted", "June 23 2023"),
("Published Online", "June 23 2023"),
))
#linebreak()
*Keywords:* Health Information Technology, Wearable Technology, Digital Health, Telemedicine
]
journal.article.abstract-list[
- *Background:* #lorem(45)
- *Methods:* #lorem(40)
- *Results:* #lorem(55)
- *Conclusions:* #lorem(25)
]
})
#show: journal.article.line-numbers()
= Introduction
#lorem(125)
#lorem(125) #footnote[Arghhhh!]
== Something
#lorem(125)
#lorem(125)
= Methodology
#lorem(125)
#import "@preview/cetz:0.2.2"
#journal.elements.plot(columns: 1, figure-args: (caption: [Testing]),{
cetz.plot.add((x)=>x, domain: (-1, 1))
})
#lorem(50)
#journal.elements.plot(columns: 1, figure-args: (caption: [Testing]),{
cetz.plot.add((x)=>x, domain: (-1, 1))
})
#lorem(150)
#lorem(150) |
https://github.com/qujihan/typst-book-template | https://raw.githubusercontent.com/qujihan/typst-book-template/main/template/utils.typ | typst | #import "params.typ": *
#let reference-block(title, content) = {
set par(first-line-indent: 0em)
block(
width: 100%,
fill: util-reference-block-color,
stroke: (left: 7pt + util-reference-line-color),
radius: 6pt,
inset: (left: 8pt, right: 1em, bottom: 1em, top: 1em),
breakable: true,
)[
#v(0.5em)
#text(fill: content-color, size: 1.2em)[
#align(center)[
*#title*
]
]
#content
#v(0.5em)
]
}
#let tips-block(title, content) = {
set par(first-line-indent: 0em)
set text(fill: content-color)
block(
above: 2em,
below: 2em,
stroke: 0.5pt + line-color,
radius: 6pt,
width: 100%,
inset: 14pt,
breakable: true,
)[
#place(
top + left,
dy: -25pt,
dx: 0pt,
block(fill: white, inset: 2pt, outset: 2pt)[
#v(0.5em)
#text(fill: blue)[
*#title*
]
#v(0.5em)
],
)
#content
]
}
|
|
https://github.com/WinstonMDP/math | https://raw.githubusercontent.com/WinstonMDP/math/main/knowledge/polynomials.typ | typst | #import "../cfg.typ": cfg
#show: cfg
= Polynomials
A sequence is finite $:=$ a set of its nonzero members is finite.
$F^oo :=$ a set of finite sequences over a field $F$.
$e_i :=$ a finite sequence where only $i$-th member is one and all others are zero.
$e_i e_j := e_(i + j)$.
$F^oo$ is an algebra over a field $F$.
An algebra of polynomials $:= F[x] := F^oo$.
An algebra of formal power series over a field $F :=
F[[x]] :=$
a set of sequences over $F$.
$forall f, f' in F[x]: deg f, deg f' < |F| -> f != f' -> exists c: op(f) c != op(f') c$.
$forall f, g in F[x]:
g != 0 -> exists! q, r in F[x]:$
+ $f = q g + r$.
+ $r = 0 or deg r < deg g$.
A root of a polynomial $f := c: op(f) c = 0$.
A root $c$ of a polynomial $f$ is prime $:= (x - c)^2 divides.not f$.
*Taylor's formula:* $f = sum_(i = 0)^n (op(f^((i)))c)/i! (x - c)^i$.
A field is algebraically closed $:=$
each polynomial with a positive degree over it has at least one root.
$CC$ is algebraically closed.
*Vieta's formula:*
A polynomial with roots $c_1, ..., c_n$ is decomposed into linear multipliers $->
sum_(i_1 < ... < i_k) c_i_1 ... c_i_k = (-1)^k a_(n - k)/a_n$.
A sequence $a_0, ...$ has a sign change in a position $i :=$
+ $a_i != 0$.
+ $exists j < i: a_j != 0$.
+ $op("sgn") a_i != op("sgn") a_(max j < i: a_j != 0)$.
*Descartes' theorem:*
A number of positive roots of a polynomial $f in RR[x]$ doesn't exceed sign changes of
its coefficient sequence and is congruent modulo $2$. If all complex roots are real,
these numbers are equal.
A polynomial with many variables is symmetric $:=$
it's resistant to permutations of variables.
Elementary symmetric polynomial $:= sigma_k := sum_(i_1 < ... < i_k) x_i_1 ... x_i_k$.
A symmetric polynomial is uniquely represented in a form of a polynomial of
elementary symmetric polynomials.
*Cardano's formula:*
the roots of $x^3 + a_1 x + a_0 x$ are
$root(3, -a_0/2 + sqrt(a_1^3/27 + a_0^2/4)) +
root(3, -a_0/2 - sqrt(a_1^3/27 + a_0^2/4))$.
A field of rational fractions $:= K(x) := op("quot") K[x]$.
A rational fraction $f/p^k$ over a field $K$ is the simplest $:=$
+ $p in K[x]$.
+ $p$ is prime.
+ $deg f < deg p$.
|
|
https://github.com/darrior/typst-mirea-template | https://raw.githubusercontent.com/darrior/typst-mirea-template/main/template.typ | typst | // The project function defines how your document looks.
// It takes your content and some metadata and formats it.
// Go ahead and customize it to your liking!
#let indent_first = 12.5mm
#let equation_counter = counter("equation")
#let image_counter = counter("image")
#let table_counter = counter("table")
#let code_counter = counter("code")
#let crutch = {
linebreak()
v(-1.5em)
}
#let eqn(content) = {
figure(
kind: "eqn",
supplement: "Формула",
content
)
}
#let numberless(content) = {
set heading(numbering: none)
pagebreak(weak: true)
set align(center)
[= #content]
}
#let application = {
}
#let project(title: "", authors: (), body) = {
// Set the document's basic properties.
set document(author: authors, title: title)
set page(
margin: (left: 30mm, right: 10mm, top: 20mm, bottom: 20mm),
numbering: "1",
number-align: center,
)
show outline: it => {
set par(first-line-indent: 0pt)
set page(numbering: none)
set outline(
title: align(center)[#upper[Содержание]],
)
it
}
set text(font: "Times New Roman", lang: "ru", size: 14pt)
set heading(numbering: "1.1")
// Set run-in subheadings, starting at level 3.
set par(
justify: true,
first-line-indent: indent_first,
leading: 1em
)
show heading: it => {
show par: p => {
set par(first-line-indent: 0pt)
block(spacing: 2em, p)
}
if it.level == 1 {
set text(18pt)
if it.numbering != none {
pagebreak(weak: true)
image_counter.step()
table_counter.step()
equation_counter.step()
code_counter.step()
h(indent_first)
counter(heading).display()
h(5pt)
upper(it.body)
} else {
upper(it.body)
parbreak()
}
} else if it.level >= 2 {
parbreak()
if it.level == 2 {
set text(16pt)
} else {
set text(14pt)
}
h(indent_first)
counter(heading).display()
h(5pt)
it.body
parbreak()
}
}
show par: it => {
set block( spacing: 1em)
it
}
show list: it => {
set block(spacing: 1em)
set par(hanging-indent: 0mm)
it
crutch
}
set list(
indent: 1.25cm,
body-indent: 1cm,
tight: true,
spacing: 1em,
marker: [---]
)
show enum: it => {
set block(spacing: 1em)
set par(hanging-indent: 0mm)
it
crutch
}
set enum(
indent: 1.25cm,
body-indent: 1cm,
)
show table: it => {
set table(
align: center,
)
set text(12pt)
it
crutch
}
set figure(numbering: "1.1")
show figure.where(kind: image): it => {
image_counter.step(level: 2)
set align(center)
it.body
set text(12pt, weight: "bold")
set par(leading: 2pt)
it.supplement
" "
image_counter.display()
if it.has("caption") {
[ --- ]
it.caption
}
}
show figure.where(kind: table): it => {
table_counter.step(level: 2)
{
set text(12pt, style: "italic")
set par(
first-line-indent: 0pt,
leading: 2pt
)
it.supplement
" "
table_counter.display()
if it.has("caption") {
[ --- ]
it.caption
}
v(-0.5em)
}
set align(center)
it.body
}
show figure.where(kind: raw): it => {
code_counter.step(level: 2)
{
set text(12pt, style: "italic")
set par(
leading: 2pt,
first-line-indent: 0pt,
)
"Листинг "
code_counter.display()
if it.has("caption") {
[ --- ]
it.caption
}
v(-0.5em)
}
it.body
}
show figure.where(kind: "eqn"): it => {
equation_counter.step(level: 2)
set math.equation(
block: true,
numbering: (..args) => {
"(" + equation_counter.display() + ")"
}
)
it.body
crutch
}
show raw: it => {
set text(12pt, font: "Courier New")
set block(
stroke: black,
inset: 0.5em,
width: 100%)
it
}
show ref: it => {
locate(loc => {
let find_figure = query(it.target, loc).first()
let num
if find_figure.func() == figure {
if find_figure.kind == table {
find_figure.supplement + " "
num = table_counter.at(find_figure.location())
} else if find_figure.kind == image {
find_figure.supplement + " "
num = image_counter.at(find_figure.location())
} else if find_figure.kind == raw {
num = code_counter.at(find_figure.location())
find_figure.supplement + " "
} else if find_figure.kind == "eqn" {
num = equation_counter.at(find_figure.location())
}
if num.len() < 2 {
num.push(0)
}
str(num.first()) + "." + str(num.last() + 1)
} else {
it
}
})
}
body
}
|
|
https://github.com/jxpeng98/typst-coverletter | https://raw.githubusercontent.com/jxpeng98/typst-coverletter/main/README.md | markdown | MIT License | # Typst-ModernPro-Coverletter
This is a cover letter template for Typst with Sans font. It is a modern and professional cover letter template. It is easy to use and customize. This cover letter template is suitable for any job application or general purpose.
If you want to find a CV template, you can check out [modernpro-cv](https://github.com/jxpeng98/Typst-CV-Resume/blob/main/README.md).
## How to use
### Use from the Typst Universe
It is simple and easy to use this template from the Typst Universe. If you prefer to use the local editor and `typst-cli`, you can use the following command to create a new cover letter project with this template.
```bash
typst init @preview/modernpro-coverletter
```
It will create a new cover letter project with this template in the current directory.
### Use from GitHub
You can also use this template from GitHub. You can clone this repository and use it as a normal project.
```bash
git clone https://github.com/jxpeng98/typst-coverletter.git
```
## Features
This package provides one **cover letter** template and one **statement** template.
### Cover Letter
```typst
#import "@preview/fontawesome:0.5.0": *
#import "@preview/modernpro-coverletter:0.0.5": *
#show: coverletter.with(
font-type: "PT Serif",
name: [example],
address: [],
contacts: (
(text: [#fa-icon("location-dot") UK]),
(text: [123-456-789], link: "tel:123-456-789"),
(text: [example.com], link: "https://www.example.com"),
(text: [github], link: "https://github.com/"),
(text: [<EMAIL>], link: "mailto:<EMAIL>"),
),
recipient: (
start-title: [],
cl-title: [],
date: [],
department: [],
institution: [],
address: [],
postcode: [],
),
)
#set par(justify: true, first-line-indent: 2em)
#set text(weight: "regular", size: 12pt)
```
| Parameter | Description |
| --- | --- |
| `font-type` | The font type of the cover letter, e.g. "PT Serif" |
| `name` | The name of the sender |
| `address` | The address of the sender |
| `contacts` | The contact information of the sender(text:[], link: []) |
| Parameter in Recipient | Description |
| --- | --- |
| `start-title` | The start title of the letter |
| `cl-title` | The title of the letter (i.g., Job Application for Hiring Manager) |
| `date` | The date of the letter(If "" or [], it will generate the current date) |
| `department` | The department of the recipient, can be "" or [] |
| `institution` | The institution of the recipient |
| `address` | The address of the recipient |
| `postcode` | The postcode of the recipient |
### Statement
```typst
#import "@preview/fontawesome:0.5.0": *
#import "@preview/modernpro-coverletter:0.0.5": *
#show: statement.with(
font-type: "PT Serif",
name: [],
address: [],
contacts: (
(text: [#fa-icon("location-dot")]),
(text: [#fa-icon("mobile") 123-456-789], link: "tel:123-456-789"),
(text: [#fa-icon("link") example.com], link: "https://www.example.com"),
(text: [#fa-icon("github") github], link: "https://github.com/"),
(text: [#fa-icon("envelope") <EMAIL>], link: "mailto:<EMAIL>"),
),
)
#v(1em)
#align(center, text(13pt, weight: "semibold")[#underline([Title])])
#set par(first-line-indent: 2em, justify: true)
#set text(11pt, weight: "regular")
// Main body of the statement
```
| Parameter | Description |
| --- | --- |
| `font-type` | The font type of the cover letter, e.g. "PT Serif" |
| `name` | The name of the sender |
| `address` | The address of the sender |
| `contacts` | The contact information of the sender(text:[], link: []) |
### Icons
The new version also integrates the FontAwesome icons. You can use the `#fa-icon("icon")` function to insert the icons in the cover letter or statement template as shown above.
You just need to import the FontAwesome package at the beginning of the document.
```typst
#import "@preview/fontawesome:0.5.0": *
```
## Preview
### Cover Letter

### Statement

|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/contrib/templates/typst-ts-templates/doc.typ | typst | Apache License 2.0 |
#import "lib.typ": doc-project
#import "@preview/doc:0.1.0": parse-module2, show-module
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: doc-project.with(
title: "templates",
subtitle: "document/page for typst.ts.",
authors: (
"Myriad-Dreamin",
),
// Insert your abstract after the colon, wrapped in brackets.
// Example: `abstract: [This is my abstract...]`
abstract: [document/page for typst.ts. ],
date: "2023",
)
// We can apply global styling here to affect the looks
// of the documentation.
#set text(font: "DM Sans")
#show heading.where(level: 1): it => {
align(center, it)
}
#show heading: set text(size: 1.5em)
#show heading.where(level: 3): set text(size: .7em, style: "italic")
#{
let template-module = parse-module2("lib.typ", read("lib.typ"), name: "Typst.ts Templates")
show-module(template-module, first-heading-level: 1)
// Also show the "complex" sub-module which belongs to the main module (funny-math.typ) since it is imported by it.
// show-module(template-module-ext, show-module-name: false, first-heading-level: 1)
}
|
https://github.com/feil7/Cheatsheets | https://raw.githubusercontent.com/feil7/Cheatsheets/master/Vim.typ | typst | #import "template.typ": conf, part, cut
#show: doc => conf(
//Title
title: [Cheatsheet NeoVim],
//Autor
authors: (
(
name: "<NAME>",
affiliation: "Fdev",
email: "<EMAIL>",
),
),
abstract: [used with NV Chad, none-ls, dpa, etc.],
doc,
)
#part(
"In Textmode:",
[
#cut("Reverse:"," strg + u")
]
)
#part(
"In Normal Mode:",
[
Move:
#cut("Left Down Up Right","hjkl")
Start Textmode:
#cut("In line under current position:", " A")
]
)
#part(
"Treesitter info",
[
#cut("Installed Languages:",":TSInstallInfo")
]
)
#part(
"Buffer",
[
#cut("New Buffer:", "")
]
)
#part(
"Tabs:",
[
#cut("New Tab:",":tabnew")
]
)
#part(
"Tree:",
[
#cut("Open Tree:","strg + n")
#cut("New File", "a")
#cut("Copy and Paste Files:","c p")
#cut("Go up in Folder Structure:","Hiphen Key: -")
#cut("Mark File for easy refind:","m")
]
)
#part(
"Window:",
[
#cut("Split Window Horizontal / Vertikal:",":sp :wsp")
]
) |
|
https://github.com/lebinyu/typst-thesis-template | https://raw.githubusercontent.com/lebinyu/typst-thesis-template/main/thesis/chapter2.typ | typst | Apache License 2.0 | // #import "reference.bib"
#let title = [
Title of chapter 2
]
#let chaptnumber = 2
#let introduction = [
// = this is a chapter <aaa>
#lorem(20)
]
#let mainbody = [
== subsetion test
#lorem(50)
$ F = m a $
#lorem(400)
#cite("wilson1983superconducting")
== subsection testtest
$ 2+1 = beta $
#lorem(500)
// == Bibliography
// #bibliography(title: none, "reference2.bib")
]
|
https://github.com/Mc-Zen/pillar | https://raw.githubusercontent.com/Mc-Zen/pillar/main/README.md | markdown | MIT License | # Pillar
_Shorthand notations for table column specifications in [Typst](https://typst.app/)._
[](https://typst.app/universe/package/pillar)
[](https://github.com/Mc-Zen/pillar/actions/workflows/run_tests.yml)
[](https://github.com/Mc-Zen/pillar/blob/main/LICENSE)
- [Introduction](#introduction)
- [Column specification](#column-specification)
- [Number alignment](#number-alignment)
- [`pillar.cols()`](#pillarcols)
- [`pillar.table()`](#pillartable)
- [`vline` customization](#vline-customization)
## Introduction
With **pillar**, you can significantly simplify the column setup of tables by unifying the specification of the number, alignment, and separation of columns. This package is in particular designed for scientific tables, which typically have simple styling:
<p align="center">
<picture>
<source media="(prefers-color-scheme: light)" srcset="docs/images/piano-keys.svg">
<source media="(prefers-color-scheme: dark)" srcset="docs/images/piano-keys-dark.svg">
<img alt="Table of some piano notes and their names and frequencies" src="docs/images/piano-keys.svg">
</picture>
</p>
In order to prepare this table with just the built-in methods, some code like the following would be required.
```typ
#table(
columns: 5,
align: (center,) * 4 + (right,),
stroke: none,
[Piano Key], table.vline(), [MIDI Number], [Note Name], [Pitch Name], table.vline(), [$f$ in Hz],
..
)
```
Using **pillar**, the same can be achieved with
```typ
#table(
..pillar.cols("c|ccc|r"),
[Piano Key], [MIDI Number], [Note Name], [Pitch Name], [$f$ in Hz], ..
)
```
or alternatively
```typ
#pillar.table(
cols: "c|ccc|r",
[Piano Key], [MIDI Number], [Note Name], [Pitch Name], [$f$ in Hz], ..
)
```
**Pillar** is designed for interoperability. It uses the powerful standard tables and provides generated arguments for `table`'s `columns`, `align`, `stroke`, and for the specified vertical lines. This means that all features of the built-in tables (and also `show` and `set` rules) can be applied as usual.
## Column specification
This package works with _column specification strings_. Each column is described by its alignment which can be `l` (left), `c` (center), `r` (right), or `a` (auto).
The width of a column can optionally be specified by appending a (relative) length, or fraction in square brackets to the alignment specifier, e.g., `c[2cm]` or `r[1fr]`.
Vertical lines can be added between columns with a `|` character. Double lines can be produced with `||` (see [`vline` customization](#vline-customization)). The stroke of the vertical line can be changed by appending anything that is usually allowed as a stroke argument in square brackets, e.g., `|[2pt]`, `|[red]` or `|[(dash: \"dashed\")]`.
A column specification string may contain any number of spaces (e.g., to improve readability) — all spaces will be ignored.
_If you find yourself writing highly complex column specifications, consider not using this package and resort to the parameters that the built-in tables provide. This package is intended for quick and relatively simple column specifications._
## Number alignment
Choosing capital letters `L`, `C`, `R`, or `A` instead of lower-case letters activates number alignment at the decimal separator for a specific column (similar to the column type "S" of the LaTeX package [siunitx](https://github.com/josephwright/siunitx)). This feature is provided via the Typst package **Zero**. [Here](https://github.com/Mc-Zen/zero) you can read up on the configuration of number formatting.
```typ
#let percm = $"cm"^(-1)$
#pillar.table(
cols: "l|CCCC",
[], [$Δ ν_0$ in #percm], [$B'_ν$ in #percm], [$B''_ν$ in #percm], [$D'_ν$ in #percm],
table.hline(),
[Measurement], [14525.278], [1.41], [1.47], [1.5e-5],
[Uncertainty], [2], [0.3], [0.3], [4e-6],
[Ref. [2]], [14525,74856], [1.37316], [1.43777], [5.401e-6]
)
```
<p align="center">
<picture>
<source media="(prefers-color-scheme: light)" srcset="docs/images/number-alignment.svg">
<source media="(prefers-color-scheme: dark)" srcset="docs/images/number-alignment-dark.svg">
<img alt="Number alignment" src="docs/images/number-alignment.svg">
</picture>
</p>
Non-number entries (e.g., in the header) are automatically recognized in some cases and will not be aligned. In ambiguous cases, adding a leading or trailing space tells Zero not to apply alignment to this cell, e.g., `[Voltage ]` instead of `[Voltage]`.
## `pillar.cols()`
This function produces an argument list that may contain arguments for `columns`, `align`, `stroke`, and `column-gutter` as well as instances of `table.vline()`. These arguments are intended to be expanded with the `..` syntax into the argument list of `table` as shown in the examples.
## `pillar.table()`
This is a thin wrapper that behaves just like the built-in `table`, except that it extracts the first positional argument if it is a string, and runs it through `pillar.cols()`.
## `vline` customization
In order to customize the default line setting, just use set rules on `table.vline`, e.g.,
```typ
#set table.vline(stroke: .7pt)
#table(..pillar.cols("c|cc"), ..)
```
Double lines are currently experimental and are realized through column gutters. They could also be realized through patterns, but this can produce artifacts with some renderers. As it currently is, double lines are not supported before the first and after the last column. On the other hand, with the current method, double lines are styled with set rules on `table.vline` which is nice and not achievable in the same way with patterns.
## Examples
### Double lines
The following example uses a double line for visually separating repeated table columns.
```typ
#pillar.table(
cols: "ccc ||[.7pt] ccc",
..([\#], [$α$ in °], [$β$ in °]) * 2,
table.hline(),
[1], [34.3], [11.1], [6], [34.0], [12.9],
[2], [34.2], [11.2], [7], [34.3], [12.8],
[3], [34.6], [11.4], [8], [33.9], [11.9],
[4], [34.7], [10.3], [9], [34.4], [11.8],
[5], [34.3], [11.1], [10], [34.4], [11.8],
)
```
<p align="center">
<picture>
<source media="(prefers-color-scheme: light)" srcset="docs/images/measurement-results.svg">
<source media="(prefers-color-scheme: dark)" srcset="docs/images/measurement-results-dark.svg">
<img alt="Demonstration example using double vertical lines" src="docs/images/measurement-results.svg">
</picture>
</p>
### Further customization
This example shows the codes of the first ten printable ASCII characters, demonstrating stroke and column width customization.
```typ
#pillar.table(
cols: "ccc|ccc|[1.8pt + blue] l[5cm]",
[Dec],[Hex],[Bin],[Symbol], [HTML code], [HTML name], [Description],
table.hline(),
[32], [20], [00100000], [ ], [], [SP], [Space],
[33], [21], [00100001], [!], [!], [!], [Exclamation mark],
[34], [22], [00100010], ["], ["], ["], [Double quotes],
[35], [23], [00100011], [#], [#], [\#], [Number sign],
[36], [24], [00100100], [$], [$], [\$], [Dollar sign],
[37], [25], [00100101], [%], [%], [%], [Percent sign],
[38], [26], [00100110], [&], [&], [&], [Ampersand],
[39], [27], [00100111], ['], ['], ['], [Single quote],
[40], [28], [00101000], [(], [&lparen;], [(], [Opening parenthesis],
[41], [29], [00101001], [)], [&rparen;], [)], [Closing parenthesis],
)
```
<p align="center">
<picture>
<source media="(prefers-color-scheme: light)" srcset="docs/images/ascii-table.svg">
<source media="(prefers-color-scheme: dark)" srcset="docs/images/ascii-table-dark.svg">
<img alt="Demonstration example using double vertical lines" src="docs/images/ascii-table.svg">
</picture>
</p>
## Tests
This package uses [typst-test](https://github.com/tingerrr/typst-test/) for running [tests](tests/).
|
https://github.com/howardlau1999/sysu-thesis-typst | https://raw.githubusercontent.com/howardlau1999/sysu-thesis-typst/master/chapters/ch02.typ | typst | MIT License | = 理论
== 理论一 <theory1>
让我们首先回顾一下 @intro 中的部分公式:
$ frac(a^2, 2) $
$ vec(1, 2, delim: "[") $
$ mat(1, 2; 3, 4) $
$ lim_x =
op("lim", limits: #true)_x $
== 理论二
在 @theory1 中,我们回顾了 @intro 中的公式。下面,我们来推导一些新的公式:
那次父对来风饭他操见速,身吗数时多票利,职和个求设。 境庭环先张时。 过小画员地义书车都母,良底然而的于包...... 史可事然以知着有了为开或山改种新不有,高全想你清较海很人...... 双究教...... 行的买况药影趣物像分印亲如门便母义现实之更那名大是情的相接路,急以多连声门对当开的手上长国上来了了苦产知...... 身达家来斯语了把集成生美光阳战用,政国相加,老保保酒服时客艺学富。 全明非了此?
引罗下先人候物但有水人。 然石人对考,叫市主房个念就么灯电广金! 展经是当世功地去可适比基见不。 县是不平总觉,古你这家般好学所使团医加神产海每构电士眼看常除的系要。 主展空外但关会初布现用花你我定流我我本办无。 看小就用血。 分决想死破天龙想还改医多教留喜能别喜,人是再整一包读心面终馆,利古民生不家,或作有; 做数年花那影治比好教地女一流:个白约行步车确样产是成中见毛、是是举着地电知年可何教论运流起一孩为家油可不新放为不、已风相部水政接化,长背公境湾去子话心你据以打星现资。 总之业不白本买必时罗物节们! 已好长的路可来以、分生是意能品省必家义感性往我,见委上方的起河成正表正,开任方续欢保家时电同; 是厂乐师奖热印研电湾到...... 药字司然来自流益的出须觉开、台突部; 满清不那成可一自共甚必检...... 生课清清惊! 乐方拿争; 老天原开的全还家民花写血放水型立不主兴去一爸节表西有不候数成养子无情教期子看的台车死大物招湾。 地虽生...... 国产国个路...... 资法压量灯、史命时语,感这长生气口! 饭们至成试,作要下明了草同子他然本。
给单久:使白就感得雄型诉方见有分结?
是家大只,问种则法法光情会天,放四和达影起期英; 生意销自形欢再提叫大听的光目:他交型黄场福工因强操气青当影达古风心用新超:空林能、怀只失工河就有去你备提或,人倒剧何了德状告车经角。 天气行运...... 安心然把家有可除基...... 轻事总人,天终接多会也语把关苦食了看面新力生势人直时师自参然的...... 亲我单写是战自,呢真快别苦女计找客,维作管之金应散先上地头眼; 钱客方得,十理再苦下我会在,备量官分教所动头台二、不设脚明石等们儿了往是家备是长用致弟部统,在电部克:象题国妈保视过进员! 下人有面管定在孩跟位! 发少名脚之异! 到些王我医保中。
类今起参生有母大用做道马,乎出而喜意也独中因得人利第接的进作的式的力角间在日上心代。 国只功游那也开管城系海系两成市。
白何不、团一声没科专当我于年。 加华是好? 参书年能剧早果本新告专配怎活,水供早中:排礼了育发当天这共住什的人表; 在百之相土市先一,人速儿势么康方向告台,一初在院在的,上太己们意性物局道,助系不其中当的今及分心这战质:企者这神、不有论离给虽! 新举树。 口利要面还快代总。
检张课是层非如; 八不半要者经天在口口条检自有神金。 公风得布高? 以进教。
公家轻防般英今统险易器的小资们助世,头要论的想入利否学至该长片家实? 明认安? 外山以放了由有场不学。
了近河园名建即时务产负清学,共片故转个过本我很发家功音光求代一府细下流呢的几因际单时到游研面死金,它破前美落吃都止! 是了就领正济式觉...... 收保会是得爱美大当,内斯热品人是我说会新或朋的土西、儿有们举且书书,想的常动以师来行先小书阳料我好她业施是那立庭就能? 不法。
用国人、龙行市后。 打其地,成个要台决都笑创; 改来用品树易费边机那...... 同你家一不比着争大这,物半住就笑这。 来和过。 里图学她年一人但华思北长是母理叶军克身,的有提,研久片飞物认地定香方去开,前形事不情全的总一德,公此日值本义无力? 在子更评业个越湾制...... 由着比费,路是此目最国许回物势法纸给行以高如外足业东变机过名子今活商真开增够制上画北大子然处甚用黄失怀么济其物看、卖程所着其感开一读为导欢人、功当价完。
轻国信了供古足、西中为多如也响源说过然样如可认水统的班,趣务事夜精欢天雨年跑一光人进,不年老他标平传研益近国巴好心人能毛严。 须言党角中呢心兴,政出球李自:技活场市方,后自美顾如包拉来! 过过望风越高发小产政怕旅后。
事区设口司着每续。
把了去,用些时着愿较了海男,智常去断感义简! 了后法常不具保离今代生、动是力现。 们去马笑,出往机于公市星市?
最市球至断自声这、重河才取他,一不你议,长用的? 前令再社此容门毛南中进长星动政花。 师今公的受得们,好质中有告:决读起包而料区。 体案停什生系是发、花港客,经明从情住景象要品们的收爱杂头,得倒文么电位在士天回赛人中成要几改情这用小班湾新地党者重!
外己时是才义张必色岸住出。 大体合多失,节孩终一不分中长中不意血中?
流理相前座信型世随?
格品不。 吃合高是不。 来关们手火交在心须应时达手电食续然全造王事定能再来两:过处字使,玩个野上年他师间地,和观部一不的较性特次国种于里的经。
大唱化相不应国,走比说方还月好识的从县收步的。 位评己头人停念府? 音全师人持经个而没来习...... 我出观不观诗格在说保花人求过我地; 体空已建无意然内? 机己如家人答引我不环静家了问主我委,还军小黄你生眼于。 女进山前西情件成委本上是命高度给。 不再他备系器何儿多亲现林?
成山预青; 他书十人,下天要,年着关? 差乎式; 修试流者切现友常...... 弟诉品业、强业白话容气写接乐到海剧说型去了来全正见团,合充够的地共治的望,器文通、家以人出的。 出开那想政了实过此是人我改选进地做完市味进; 喜地华,吃例被想了深华; 做我乐理老兴动果于跟表这是商展平外政什得他不难不人作不,可有点过道是减,会够失一华大丽拉我少果利引层有用湾收面面营:安动么明书住开有器界成闻参去山之理令转高生学没这游已青来部; 马究没、一无产月一生是化黑金资中都但园陆成委告二要公动友法那口向产个未生感健特时国还了能人演场点,天成向吃后,却紧生会种包建研小几。 为少如时能去界它投什觉的什期、出点力步企长企:国光断进统学容命惊回才放得图构气面。
|
https://github.com/matthiasGmayer/typst-math-template | https://raw.githubusercontent.com/matthiasGmayer/typst-math-template/main/main.typ | typst | #import "template.typ": *
#import datetime
// Take a look at the file `template.typ` in the file panel
#let my_abstract = [
#lorem(40)
]
#show: project.with(
title: "Title",
authors: (
(name: "MyName", email: "<EMAIL>"),
),
abstract:my_abstract,
date: datetime.today().display("[month repr:long] [year]"),
)
#{manage.is_main_document.update(true)}
#pagebreak()
#tableofcontents
#pagebreak()
= Introduction
#include "introduction.typ"
#pagebreak()
#bibliography(("citations.yml","citations.bib"),style:"ieee") |
|
https://github.com/msakuta/typst-test | https://raw.githubusercontent.com/msakuta/typst-test/master/laplace-transform-jp.typ | typst | #set page(
numbering: "1",
)
#set text(font: ("linux libertine", "IPAMincho"))
#set math.equation(numbering: "(1)")
#align(center, text(17pt)[
*ラプラス変換*
])
#outline()
= ラプラス変換
ラプラス変換は、下記に示す[[FFT|フーリエ変換]]によく似ている。
$
F(omega) &= integral_(-infinity)^infinity f(t) e^(-j omega t) d t
$
違いは、 $e^(-j omega t)$ の代わりに $e^(-s t)$ を使い、積分範囲を $"[" 0, infinity ")"$ としたものである。
$
F(s) = integral_0^infinity f(t) e^(-s t) d t
$
こうして得られた $F(s)$ は、フーリエ変換と同じく複素数 $s$ の関数であり、 $cal(L)[f]$ と表し、 $f$ のラプラス変換と呼ぶ。
フーリエ変換と同じく、線形システム解析に極めて有用であるが、微妙な違いがある。
まず式から明らかなように、 $F(s)$ は $f(t)$ の $t$ が正の範囲しか含まない。
このため $f(t)$ が時間 $t$ だけ過去の情報を示しているとすれば、過去の状態のみに依存する関数となる。
このことは過渡応答のような因果性のある事象の解析にはフーリエ変換に比べて有利である。
また、被積分関数の係数 $e^(-s t)$ を見ればわかるように、 $t$ を負の無限大まで拡張すると積分も無限大に発散する。
このため単なる積分演算上の都合からも正の範囲に限る必要がある。
== ラプラス変換の演算
ラプラス変換の最も重要な特徴は、微分・積分演算が積算・除算演算に帰着できるということである。
詳しい証明は文献#footnote[山田直平・國枝壽博 応用数学講座 ラプラス変換・演算子法 (昭和34年) さすがに古すぎるのでもっと新しい教科書を探したほうが良いと思う]に譲るが、もし $f^((0))(0)=f^((1))(0)=...=f^((n))(0)=0$ であり、ラプラス変換の積分が収束するならば
$
cal(L)[f^((n))] = s^n cal(L)[f]
$
である。
積分に関しては
$
cal(L) lr([integral_0^t f(t) d t ]) = 1 / s cal(L)[f]
$
であり、多重積分は
$
cal(L) lr([ underbrace(integral_0^t integral_0^t dots.c integral_0^t, n) f(t) d t]) = 1 / (s^n) cal(L)[f]
$ <eq:multiint>
となる。
一般に $f(t)$ を微係数とする関数は
$
f^((-1))(t) = f^((-1))(0) + integral_0^t f(t) d t
$
と書けるので、 @eq:multiint は
$
cal(L)[f^((-n))] = 1 / s^n cal(L)[f]
$
とも書ける。
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/name-it/0.1.0/name-it.typ | typst | Apache License 2.0 | #let name-it(num, show-and: true, negative-prefix: "negative") = {
let digit-name(digit, show-zero) = {
let names = ("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
if digit == "0" and not show-zero {
return ""
}
return names.at(int(digit))
}
let three-digit-name(num, show-zero, show-and) = {
if num.len() == 3 {
let hundreds = digit-name(num.at(0), false)
let tens = three-digit-name(num.slice(1), show-zero and num.at(0) == "0", show-and)
return (
hundreds
+ if hundreds != "" { " hundred" }
+ if tens.trim() != "" and show-and { " and" }
+ tens
)
}
let names = ("", none, "twenty-", "thirty-", "fourty-", "fifty-", "sixty-", "seventy-", "eighty-", "ninety-")
let teens = ("ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen")
let name = names.at(int(num.at(0)))
if name != none { num = num.slice(1) }
if num.len() == 1 {
name += digit-name(num, name == "" and show-zero)
} else {
name += teens.at(int(num.slice(1)))
}
return " " + name.trim("-", at: end)
}
assert(
type(num) == int
or type(num) == str and num.contains(regex("^-?\d+$")),
message: "argument must be either an integer or a string of an integer, got " + repr(num),
)
let name = ""
num = str(num)
let is-negative = num.at(0) == "-"
if is-negative { num = num.slice(1) }
let group-names = ("", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion")
// pad left with zeros to a multiple of 3
num = ((int((num.len() - 1) / 3) + 1) * 3 - num.len()) * "0" + num
let group-count = int(num.len() / 3)
for group in range(group-count) {
let group-name = group-names.at(group-count - 1 - group)
let named = three-digit-name(num.slice(group * 3, count: 3), group-count == 1, show-and)
name += " "
name += named
if named.trim() != "" {
name += " "
name += group-name
}
}
name = name.replace(regex("^ *and"), "").trim().replace(regex(" +"), " ")
if is-negative { name = negative-prefix + " " + name }
return name
}
|
https://github.com/bionick7/kiergergaard-pillars | https://raw.githubusercontent.com/bionick7/kiergergaard-pillars/master/README.md | markdown | # Kiergergaard_pillars
A Lancer supplementary Frame collection
## How to modify
edit templates in content_yaml. Remove top comment to activate. Build with template_builder.py (requires python and pyyaml)
Maunal can be compiled with typst
## Content
This supplement adds 4 new manufacturers and 12 new licenses. Summary below
GMS-HIPS / Humanitarian intervention and pioneering supplier
- Midzor / Support – Premiere tool of any pioneer
- Attakulla / Controller/Striker – Air command's favourite
- Kilimanjaro / Support – Firefighting fridge
Lanika Corp. budget paramilitary supplier
- <NAME> / Support – Interconnected anti-virus calculator
- Orinoco / Striker/Controller – Covert commando coder
- Mississippi / Defender – Armoured personnel chassis
- Yukon / Striker – Laser assault
Harrison Skyhoppers
- Charlemagne / Striker – Stumbling knight of massive proportions
- Schwarzkopf / Striker – Soaring dragon burning through the sky.
IPSN Blackbox
- Columbus / Artillery/Support – A spacers trusted counterbattery
- Janszoon / Controller – Old school radio operator
- Amunsden / Striker – The running man's Drake
[Incomplete list] |
|
https://github.com/coco33920/typst-association-statuts | https://raw.githubusercontent.com/coco33920/typst-association-statuts/master/README.md | markdown | The Unlicense | # Template pour écrire des statuts d'associations en Typst!
Tout est dans le titre! Remplissez juste les variable au début de example.typ et voilà ! Vous avez vos status :)
*Adapté de [cette template LaTeX](https://github.com/maxence-lagalle/statuts-loi1901) en CC-0*
|
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.typ | typst | Other | #import "/lib/draw.typ": *
#import "/template/lang.typ": arabic-amiri
#let start = (0, 0)
#let end = (500, 120)
#let graph = with-unit((ux, uy) => {
// mesh(start, end, (50, 50))
txt([关闭`calt`#h(1fr)#arabic-amiri(text(features: ("calt": 0, "kern": 0))[(لبے)])], (0, 110), anchor: "lt", size: 42 * ux)
txt([开启`calt`#h(1fr)#arabic-amiri(text(features: ("calt": 1, "kern": 0))[(لبے)])], (0, 50), 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/compiler/spread-07.typ | typst | Other | // Error: 10-14 expected identifier, found boolean
#let f(..true) = none
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10530.typ | typst | Apache License 2.0 | #let data = (
("CAUCASIAN ALBANIAN LETTER ALT", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER BET", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER GIM", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER DAT", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER EB", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER ZARL", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER EYN", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER ZHIL", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER TAS", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER CHA", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER YOWD", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER ZHA", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER IRB", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER SHA", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER LAN", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER INYA", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER XEYN", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER DYAN", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER CAR", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER JHOX", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER KAR", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER LYIT", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER HEYT", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER QAY", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER AOR", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER CHOY", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER CHI", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER CYAY", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER MAQ", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER QAR", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER NOWC", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER DZYAY", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER SHAK", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER JAYN", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER ON", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER TYAY", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER FAM", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER DZAY", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER CHAT", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER PEN", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER GHEYS", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER RAT", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER SEYK", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER VEYZ", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER TIWR", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER SHOY", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER IWN", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER CYAW", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER CAYN", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER YAYD", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER PIWR", "Lo", 0),
("CAUCASIAN ALBANIAN LETTER KIW", "Lo", 0),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
("CAUCASIAN ALBANIAN CITATION MARK", "Po", 0),
)
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/math/limits.md | markdown | MIT License | # Setting limits
Sometimes we want to change how the default attaching should work.
## Limits
For example, in many countries it is common to write definite integrals with limits below and above.
To set this, use `limits` function:
```typ
$
integral_a^b\
limits(integral)_a^b
$
```
You can set this by default using `show` rule:
```typ
#show math.integral: math.limits
$
integral_a^b
$
This is inline equation: $integral_a^b$
```
## Only display mode
Notice that this will also affect inline equations. To enable limits for display math only, use `limits(inline: false)`:
```typ
#show math.integral: math.limits.with(inline: false)
$
integral_a^b
$
This is inline equation: $integral_a^b$.
```
Of course, it is possible to move them back as bottom attachments:
```typ
$
sum_a^b, scripts(sum)_a^b
$
```
## Operations
The same scheme works for operations. By default, they are attached to the bottom and top:
```typ
$a =_"By lemme 1" b, a scripts(=)_+ b$
```
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/attach-p2_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test frame base.
$ (-1)^n + (1/2 + 3)^(-1/2) $
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/selector-logical.typ | typst | Apache License 2.0 | //Tests for logical (and/or) selectors
---
= A
== B
#figure([Cat], kind: "cat", supplement: [Other])
=== D
= E <first>
#figure([Frog], kind: "frog", supplement: none)
#figure([Giraffe], kind: "giraffe", supplement: none) <second>
#figure([GiraffeCat], kind: "cat", supplement: [Other]) <second>
= H
#figure([Iguana], kind: "iguana", supplement: none)
== I
#let test-selector(selector, ref) = locate(loc => {
let elems = query(selector, loc)
test(elems.map(e => e.body), ref)
})
// Test `or`.
#test-selector(
heading.where(level: 1).or(heading.where(level: 3)),
([A], [D], [E], [H]),
)
#test-selector(
heading.where(level: 1).or(
heading.where(level: 3),
figure.where(kind: "frog"),
),
([A], [D], [E], [Frog], [H]),
)
#test-selector(
heading.where(level: 1).or(
heading.where(level: 2),
figure.where(kind: "frog"),
figure.where(kind: "cat"),
),
([A], [B], [Cat], [E], [Frog], [GiraffeCat], [H], [I]),
)
#test-selector(
figure.where(kind: "dog").or(heading.where(level: 3)),
([D],),
)
#test-selector(
figure.where(kind: "dog").or(figure.where(kind: "fish")),
(),
)
// Test `or` duplicates removal.
#test-selector(
heading.where(level: 1).or(heading.where(level: 1)),
([A], [E], [H]),
)
// Test `and`.
#test-selector(
figure.where(kind: "cat").and(figure.where(kind: "frog")),
(),
)
// Test `or` with `before`/`after`
#test-selector(
selector(heading)
.before(<first>)
.or(selector(figure).before(<first>)),
([A], [B], [Cat], [D], [E]),
)
#test-selector(
heading.where(level: 2)
.after(<first>)
.or(selector(figure).after(<first>)),
([Frog], [Giraffe], [GiraffeCat], [Iguana], [I]),
)
// Test `and` with `after`
#test-selector(
figure.where(kind: "cat")
.and(figure.where(supplement: [Other]))
.after(<first>),
([GiraffeCat],),
)
// Test `and` (with nested `or`)
#test-selector(
heading.where(level: 2)
.or(heading.where(level: 3))
.and(heading.where(level: 2).or(heading.where(level: 1))),
([B], [I]),
)
#test-selector(
heading.where(level: 2)
.or(heading.where(level: 3), heading.where(level:1))
.and(
heading.where(level: 2).or(heading.where(level: 1)),
heading.where(level: 3).or(heading.where(level: 1)),
),
([A], [E], [H]),
)
// Test `and` with `or` and `before`/`after`
#test-selector(
heading.where(level: 1).before(<first>)
.or(heading.where(level: 3).before(<first>))
.and(
heading.where(level: 1).before(<first>)
.or(heading.where(level: 2).before(<first>))
),
([A], [E]),
)
#test-selector(
heading.where(level: 1).before(<first>, inclusive: false)
.or(selector(figure).after(<first>))
.and(figure.where(kind: "iguana").or(
figure.where(kind: "frog"),
figure.where(kind: "cat"),
heading.where(level: 1).after(<first>),
)),
([Frog], [GiraffeCat], [Iguana])
)
|
https://github.com/Ad4u/ad4u.github.io | https://raw.githubusercontent.com/Ad4u/ad4u.github.io/main/dinner_fr.typ | typst | #let WIDTH = 90mm
#let HEIGHT = 160mm
#let MARGIN = 6mm
#let FRONT_TOP_MARGIN = 35mm
#let BACKGROUND = image("assets/background.jpg", width: WIDTH, height: HEIGHT)
#let FRONT = image("assets/front.jpg", width: WIDTH, height: HEIGHT)
#let BACK = image("assets/back.jpg", width: WIDTH, height: HEIGHT)
#set document(title: "Diner de mariage de Betty & Romain")
#show heading: item => [
#pagebreak()
#set align(center)
#set text(font: "Better Smile", size: 44pt)
#item
#v(-20mm)
#image("assets/separator.png", width: 60%)
#v(-8mm)
]
// Page setup
#set par(leading: 0.55em, justify: true)
#set page(width: WIDTH, height: HEIGHT, margin: MARGIN)
// Front page
#set text(font: "Better Smile", size: 44pt, weight: "medium")
#set page(background: FRONT)
#set page(margin: (top: FRONT_TOP_MARGIN))
#align(center)[Diner \ de \ mariage \ de \ Betty & Romain]
// Body
#set page(background: BACKGROUND, margin: MARGIN)
#set text(font: "TT Chocolates Trl", size: 16pt, weight: "medium")
= Remerciements
#read("speeches/ThankYou_FR.txt")
= Discours 4
#read("speeches/4_FR.txt")
= Discours 5
#read("speeches/5_FR.txt")
= Discours 6
#read("speeches/6_FR.txt")
= Discours 7
#read("speeches/7_FR.txt")
= Discours 8
#read("speeches/8_FR.txt")
= Discours 9
#read("speeches/9_FR.txt")
// Back page
#set page(background: BACK)
#pagebreak()
|
|
https://github.com/JakMobius/courses | https://raw.githubusercontent.com/JakMobius/courses/main/mipt-os-basic-2024/sem03/main.typ | typst |
#import "@preview/polylux:0.3.1": *
#import "@preview/cetz:0.2.2"
#import "../theme/theme.typ": *
#import "./utils.typ": *
#show: theme
#title-slide[
#align(horizon + center)[
= Файловые системы
АКОС, МФТИ
26 сентября, 2024
]
]
#show: enable-handout
#focus-slide[
#set block(above: 25pt, below: 25pt)
#set text(size: 50pt)
*Всё есть файл...*
#uncover((beginning: 2))[
#set text(size: 25pt)
*...овый дескриптор*
]
]
#slide(
place-location: center, background-image: none,
)[
#let transparent = color.rgb(255, 255, 255, 0)
#let left-color = cell-color(palette.at(0))
#let right-color = cell-color(palette.at(3))
#let box-options = (inset: (x: 25pt, y: 30pt), width: 12cm, radius: 20pt)
#grid(
columns: 2, rows: (1.5cm, auto), column-gutter: 2cm, stroke: none, align: (column, row) => {
if row == 0 { top + center } else { top + left }
}, [
= Встроенные
], [
= Пользовательские
], [
#align(
center,
)[
#box(
fill: left-color.background-color, stroke: 1pt + left-color.stroke-color, ..box-options,
)[
#align(left, [
#set text(size: 25pt)
#set list(marker: raw("="))
- #codebox(lang: "c", "STDIN_FILENO")
- #codebox(lang: "c", "STDOUT_FILENO")
- #codebox(lang: "c", "STDERR_FILENO")
])
]
]
- *Потоки консоли:* ввод, вывод, ошибки;
- Почти всегда равны #codebox("0") , #codebox("1") и #codebox("2");
- Но лучше использовать константы;
- Их даже можно закрыть (но зачем?).
], [
#align(
center,
)[
#box(
fill: right-color.background-color, stroke: 1pt + right-color.stroke-color, ..box-options,
)[
#align(left, [
#set text(size: 25pt)
#set list(marker: raw("="))
- #codebox(lang: "c", "open(...)")
- #codebox(lang: "c", "socket(...)")
- #codebox(lang: "c", "accept(...)")
- #codebox(lang: "c", "epoll(...)")
- #codebox(lang: "c", "socketpair(...)") #super("*")
- #codebox(lang: "c", "signalfd(...)") , ...
])
]
]
- Файлы, сеть, мультиплексеры,...;
- Всё, что работает как поток данных.
],
)
]
#focus-slide[
#text(size: 50pt)[
*Почему не #codebox(lang: "c", "fopen(...)") ?*
]
#uncover(
(beginning: 2),
)[
#text(
size: 25pt,
)[
#place(
center + bottom,
)[
#codebox(lang: "c", "fopen(...)") возвращает #codebox(lang: "c", "FILE*"), а не
дескриптор
]
]
]
]
#slide(
header: [Папки -- тоже файлы?], background-image: none,
)[
#place(horizon + center)[
#set text(size: 30pt)
#code(numbers: true, leading: 5pt, ```c
int main() {
int fd = open("/", O_RDONLY, 0);
struct dirent ent = {};
while(getdents64(fd, &ent, sizeof(ent)) > 0) {
printf("%s\n", ent.d_name);
lseek(fd, ent.d_off, SEEK_SET);
}
}
```)
]
#uncover(
(beginning: 2),
)[
#place(bottom + center)[
#set text(size: 21pt)
*Да, это тоже файловые дескрипторы.* А ещё это директории, а не папки.
]
]
]
#slide(
header: [А если вызвать #codebox(lang: "c", "read(...)") на директорию?], background-image: none,
)[
#place(horizon)[
#text(size: 30pt)[
#code(numbers: true, leading: 5pt, ```c
int main() {
int fd = open("/", O_RDONLY, 0);
char buffer[16];
if(read(fd, buffer, sizeof(buffer)) >= 0) {
printf("%15s", buffer);
} else perror("read");
}
```)
]
]
#place(
bottom,
)[
#uncover(
(beginning: 2),
)[
#text(
size: 25pt,
)[
*Вывод:* #codebox("read: Is a directory") . *Причина:* #codebox(lang: "c", "read(...) == -EISDIR")
]
]
]
]
#slide(
header: [Файловый дескриптор - это], place-location: horizon + left,
)[
#let codeblocks(arr) = {
arr.map(code => codebox(lang: "c", code)).join(" , ")
}
- *Число*, сопоставленное какому-то ресурсу.
- Его можно понимать, как *"указатель" на виртуальный класс*.
- *Разработчик должен помнить* типы дескрипторов. Это упрощают обёртки:
- #codeblocks(("FILE", "fopen()", "fclose()", "fread()", "fwrite()", "fseek()")) ,
... для файлов;
- #codeblocks(("DIR", "opendir()", "closedir()", "readdir()", "seekdir()")) , ...
для директорий;
- *И практически ничего* для работы с сокетами / сигналами / pipe-ами.
- Активные дескрипторы процесса можно увидеть в #codebox("/proc/<pid>/fd/")
]
#slide(
header: [#codebox(lang: "c", "open(char *path, int flags, mode_t mode)")], background-image: none,
)[
== Открыть (создать) файл (директорию).
== *#codebox(lang: "c", "int flags") :*
#set list(marker: `|=`)
- #codebox("O_RDONLY") : Открыть на *чтение*;
- #codebox("O_WRONLY") : Открыть на *запись*;
- #codebox("O_RDWR") : Открыть на *чтение и запись*;
- #codebox("O_TRUNC") : *Очистить* файл при открытии;
- #codebox("O_CREAT") : *Создать* файл, если его нет;
- #codebox("O_EXCL") : Сломаться, если файл уже есть.
== *#codebox(lang: "c", "mode_t mode")* : маска прав для создаваемого файла.
]
#slide(
header: [Чтение и запись], background-image: none, place-location: horizon,
)[
- Для этого служат самые известные системные вызовы:
#[
#set list(marker: none)
- #codebox(lang: "c", "read(int fd, void* buf, size_t count)")
- #codebox(lang: "c", "write(int fd, void* buf, size_t count)")
]
- Существуют #codebox(lang: "c", "pread(...)") и #codebox(lang: "c", "pwrite(...)") ,
которые *явно принимают позицию файла*.
- Если хочется одновременно записать *несколько буферов*, можно использовать:
#[
#set list(marker: none)
- #codebox(lang: "c", "readv(int fd, struct iovec *vector, int count)")
- #codebox(lang: "c", "writev(int fd, struct iovec *vector, int count)")
]
]
#slide(
header: [#codebox(lang: "c", "lseek(int fd, off_t offset, int whence)")], background-image: none,
)[
== Настройка позиции файла
== *#codebox(lang: "c", "int whence") :*
#set list(marker: `=`)
- #codebox("SEEK_SET") : Установить позицию на #codebox("offset") ;
- #codebox("SEEK_CUR") : Сдвинуть позицию на #codebox("offset") ;
- #codebox("SEEK_END") : Установить позицию в *конец* и сдвинуть на #codebox("offset") .
== #codebox(lang: "c", "lseek()") возвращает позицию в байтах от начала файла.
]
#slide(
header: [#codebox(lang: "c", "fcntl(int fd, int cmd, long arg)")],
background-image: none,
)[
== Системный вызов управления дескрипторами.
== *#codebox(lang: "c", "int cmd") :*
#set list(marker: `=`)
- #codebox("F_SETFD") : Установить флаги дескриптора;
- #codebox("F_SETFL") : Установить флаги статуса;
- #codebox("F_SETLK") : Установить *блокировку* на файл;
- #codebox("F_DUPFD") : *Дублировать* дескриптор;
- #codebox("F_SETSIG") : Получить сигнал, когда будет доступно чтение / запись;
- #codebox("F_SETPIPE_SZ") : Настроить размер очереди.
== *#codebox(lang: "c", "long arg") :* аргумент, используется в #codebox("F_SET*") -- командах
]
#slide(
header: [Какие флаги можно настраивать?], background-image: none,
)[
== Флаги дескриптора (#codebox("F_SETFD")):
- #codebox("FD_CLOEXEC") : автоматически закрыть файл при вызове #codebox(lang: "c", "exec()")
- И всё, их ровно одна штука 🤷🏻♂️.
== Полезные флаги статуса (#codebox("F_SETFL")):
- #codebox("O_APPEND") : дописывать в конец файла, как в лог;
- #codebox("O_NONBLOCK") : запретить блокирующий ввод/вывод;
- #codebox("O_NOATIME") : не изменять время последнего доступа к файлу;
== Бесполезные флаги статуса:
- #codebox("O_ASYNC") : получать сигнал по доступности чтения/записи;
- #codebox("O_DIRECT") : прямая запись, обход кеширования ядра;
]
#focus-slide[
#text(size: 50pt)[
*А что такое файл?*
]
]
#slide(
header: [Файл -- это не путь!], background-image: none, place-location: horizon + center,
)[
#let pathbox(content) = [
#box(radius: 10pt, fill: rgb(60, 60, 60), inset: 20pt)[
#set text(fill: white)
#raw(content)
]
]
#set block(above: 30pt, below: 30pt)
#set text(size: 45pt)
#pathbox("/home/you/test.txt")
#set text(size: 25pt)
*Может быть тем же файлом, что и:*
#set text(size: 45pt)
#pathbox("/home/you/test2.txt")
]
#slide(
background-image: none, place-location: horizon + center,
)[
#cetz.canvas(
length: 1cm, {
cetz.draw.set-style(
content: (padding: .2), fill: gray.lighten(70%), stroke: gray.lighten(70%),
)
let box-options = (width: 100%, height: 100%, radius: 10pt, inset: 20pt)
let largecodebox(lang: none, content) = {
box(radius: 5pt, fill: rgb(60, 60, 60), width: 15cm, height: 1.5cm)[
#set align(horizon + center)
#set text(fill: white)
#set raw(theme: "../theme/halcyon.tmTheme")
#raw(lang: lang, content)
]
}
let background(color) = {
box(
fill: cell-color(color).background-color, width: 100%, height: 100%,
)
}
let title(color, content) = {
place(
top + left,
)[
#box(
inset: 15pt,
)[
#text(
weight: "black", size: 30pt, fill: cell-color(color).stroke-color,
)[
#content
]
]
]
}
cetz.draw.content((0, 1), (30, -4), padding: none, {
background(blue)
title(blue, [Программа])
place(horizon + center)[
#box(..box-options)[
#set text(size: 30pt)
#set align(center)
#largecodebox(lang: "c", "write(fd, \"Hi!\", 4);")
]
]
})
cetz.draw.content((0, -4), (30, -9), padding: none, {
background(red)
title(red, [Ядро])
place(horizon + center)[
#box(..box-options)[
#set text(size: 30pt)
#set align(center)
#largecodebox(lang: "c", "process->fds[fd]->inum")
]
]
})
cetz.draw.content(
(0, -9), (30, -16), padding: none, {
background(black)
title(black, [Диск])
place(
center + bottom,
)[
#box[
#text(size: 50pt)[*...*]
#h(1em)
#box(
baseline: 2.5cm,
)[#grid(
rows: (3cm, 1cm), columns: (3cm,) * 8, row-gutter: 5pt, align: center + horizon, inset: 0pt, ..range(8).map(i => [
#box(width: 100%, height: 100%, stroke: 2pt + black)[
*Index Node*
]
]), ..range(8).map(i => [
#set text(size: 30pt, weight: "black")
#raw("[" + str(i + 48) + "]")
]),
)]
#h(1em)
#text(size: 50pt)[*...*]
#v(1em)
]
]
},
)
cetz.draw.set-style(mark: (end: ">"), stroke: 5pt + black, fill: none)
let a = (x: 14, y: -2.5)
let b = (x: 17, y: -5.5)
let c = (x: 20, y: -7.5)
let d = (x: 11, y: -11)
cetz.draw.bezier((a.x, a.y), (b.x, b.y), (a.x, b.y), (b.x, a.y), name: "line1")
cetz.draw.bezier((c.x, c.y), (d.x, d.y), (c.x, d.y), (d.x, c.y), name: "line2")
cetz.draw.content((name: "line1", anchor: 30%), anchor: "south-west", padding: .4, [
#text(size: 25pt)[*Дескриптор*]
])
cetz.draw.content(("line2.mid"), anchor: "south", padding: .4, [
#text(size: 25pt)[*Номер inode*]
])
},
)
]
#let largecell(color, content) = [
#let color = cell-color(color)
#box(
radius: 10pt, fill: color.background-color, stroke: 3pt + color.stroke-color, inset: 30pt,
)[
#set text(fill: black)
#content
]
]
#slide(
place-location: center + horizon,
)[
#box(
width: 75%, height: 10cm,
)[
#align(center)[
#set block(spacing: 40pt)
#text(size: 60pt, weight: "black")[#largecell(black, [Index Node])]
]
#align(
left,
)[
- *Структура, которую обычно называют "файлом"*;
- Хранится в длинном массиве на жестком диске;
- *Знает*, где на жестком диске хранится *содержимое её файла*;
- *Хранит число ссылок* на саму себя (как #codebox(lang: "cpp", "std::shared_ptr")).
]
]
]
#let draw-dir-ent(position, values, more: true) = {
let column-width = 3.2
let index-node-height = 2.5
let margin = 1.0
let dirent-start = index-node-height + margin
let dirent-height = 1.8 * values.len()
if (more) {
dirent-height += 1
}
let left = position.x - column-width / 2
let right = position.x + column-width / 2
cetz.draw.set-style(mark: (end: ">"), stroke: 5pt + black, fill: none)
cetz.draw.content(
(left, position.y), (right, position.y - index-node-height), padding: none, {
set align(horizon + center)
let color = cell-color(black)
box(
width: 100%, height: 100%, fill: color.background-color, stroke: 2pt + color.stroke-color, radius: 10pt,
)[
*Index Node*
]
},
)
cetz.draw.line(
(position.x, position.y - index-node-height - 0.1), (position.x, position.y - index-node-height - margin + 0.1), stroke: 4pt + black,
)
cetz.draw.content(
(left, position.y - dirent-start), (right, position.y - dirent-start - dirent-height), padding: none, {
set align(center)
set block(spacing: 5pt)
set text(size: 25pt)
let colors = cell-color(palette.at(1))
grid(
rows: (1.8cm,) * values.len(), columns: 100%, align: horizon + center, stroke: 2pt + colors.stroke-color, fill: colors.background-color, ..values,
)
if (more) {
text(size: 30pt)[*...*]
}
},
)
}
#let horizontal-bezier(a, b) = {
cetz.draw.bezier((a.x, a.y), (b.x, b.y), (b.x, a.y), (a.x, b.y))
}
#slide(
place-location: center + top, background-image: none,
)[
#cetz.canvas(
length: 1cm, {
cetz.draw.set-style(
content: (padding: .2), fill: gray.lighten(70%), stroke: gray.lighten(70%),
)
let largecodebox(lang: none, content) = {
let color = cell-color(blue)
box(
radius: 5pt, fill: color.background-color, width: 12cm, height: 1.7cm, stroke: 2pt + color.stroke-color,
)[
#set align(horizon + center)
#set text(fill: black)
#set raw(theme: "../theme/halcyon.tmTheme")
#raw(lang: lang, content)
]
}
cetz.draw.content((0, -1), (30, -4), padding: none, {
box(width: 100%, height: 100%)[
#set text(size: 30pt)
#set align(center)
#largecodebox("/usr/bin/bash")
]
})
let indices = (3, 2, 2)
let index-node-positions = range(4).map(x => 6 + x * 6)
let data = (
(`.`, `..`, `etc`, [*`usr`*]), (`.`, `..`, [*`bin`*], `share`), (`.`, `..`, [*`bash`*], `mkdir`), ("0x7f", "0x45", "0x4c", "0x46").map(a => codebox(a)),
)
for (i, pos) in index-node-positions.enumerate() {
draw-dir-ent((x: pos, y: -4.5), data.at(i))
}
for (i, dirent-index) in indices.enumerate() {
let position = index-node-positions.at(i)
let index-node = (x: 4.25 + position, y: -5.75)
let dirent = (x: 1.75 + position, y: -9 - 1.8 * dirent-index)
horizontal-bezier(dirent, index-node)
}
cetz.draw.line((0, -5.75), (4.25, -5.75), name: "root", stroke: luma(80) + 5pt)
cetz.draw.content((name: "root", anchor: 50%), anchor: "south", padding: .4, [
#text(size: 20pt, fill: luma(80))[*Корень*]
])
cetz.draw.set-style(mark: (end: none))
cetz.decorations.flat-brace(
(index-node-positions.at(0) - 2.5, -8), (index-node-positions.at(0) - 2.5, -8 - 1.8 * 4), flip: true, name: "brace",
)
cetz.draw.content("brace.content", anchor: "south", padding: 1.3, angle: 90deg, [
#text(size: 25pt)[*Directory Entries*]
])
},
)
]
#slide(place-location: center + horizon)[
#box(width: 65%, height: 10cm)[
#align(center)[
#set block(spacing: 40pt)
#text(
size: 60pt, weight: "black",
)[#largecell(palette.at(1), [Directory Entry])]
]
#align(left)[
- Структура c *именем* и *адресом* Index Node;
- Может *ссылаться на свой же Index Node*(#codebox("./"));
- Живёт там, где обычно хранятся данные файла;
- Хранится в массиве других Directory Entry.
]
]
]
#slide(
header: [Что, если на Index Node несколько ссылок?], background-image: none,
)[
#place(
horizon + center,
)[
#cetz.canvas(
length: 1cm, {
let dirs = (".", "..", "test1", "test2").map(raw)
let file = ("H", "e", "l", "l").map(a => codebox(lang: "c", "'" + a + "'"))
draw-dir-ent((x: 0, y: 0), dirs)
cetz.draw.line((-6, -1.25), (-1.6, -1.25), name: "root", stroke: 5pt + luma(80))
cetz.draw.content((name: "root", anchor: 50%), anchor: "south", padding: .4, [
#text(size: 20pt, fill: luma(80))[*Корень*]
])
let indicies = (2, 3)
let index-node = (x: 10, y: -4)
// Чтобы сдвинуть всё в центр
cetz.draw.content((-6, 0), (16, 0), [])
cetz.draw.set-style(mark: (end: none))
let c = (x: 5, y: -5)
let d = (x: 8.4, y: -1.25)
for (i, dirent-index) in indicies.enumerate() {
let dirent = (x: 1.75, y: -4.5 - 1.8 * dirent-index)
let a = dirent
let b = (x: c.x, y: a.y)
cetz.draw.bezier((a.x, a.y), (c.x, c.y), (b.x, b.y))
}
cetz.draw.set-style(mark: (end: ">"), stroke: 5pt + black, fill: none)
cetz.draw.bezier((c.x, c.y), (d.x, d.y), (c.x, d.y))
draw-dir-ent((x: 10, y: 0), file)
},
)
]
#place(
center + bottom,
)[
#uncover(
(beginning: 2),
)[
#text(
size: 25pt, [Это называется *жесткая ссылка.* Так можно только с файлами.],
)
]
]
]
#slide(
background-image: none,
)[
#let header = [= Задача: сколько ссылок у пустой директории?]
#only("1")[
#place(center + horizon, header)
]
]
#slide(
background-image: none,
)[
#let header = [= Задача: сколько ссылок у пустой директории?]
#uncover(
(beginning: 2),
)[
#header
#place(
horizon + center,
)[
#cetz.canvas(
length: 1cm, {
let dirs = (".", "..", "dir").map(raw)
let file = (".", "..").map(raw)
draw-dir-ent((x: 0, y: 0), dirs, more: false)
cetz.draw.line((-6, -1.25), (-1.6, -1.25), name: "root", stroke: 5pt + luma(80))
cetz.draw.content((name: "root", anchor: 50%), anchor: "south", padding: .4, [
#text(size: 20pt, fill: luma(80))[*Корень*]
])
let indicies = (2, 3)
let index-node = (x: 10, y: -4)
// Чтобы сдвинуть всё в центр
cetz.draw.content((-6, 0), (16, 0), [])
cetz.draw.set-style(mark: (end: none))
let dirent(x, y, left: false) = {
let shift = if left { -1.75 } else { 1.75 }
if (y == -1) {
(x: shift + 10 * x, y: -1.25)
} else {
(x: shift + 10 * x, y: -4.5 - 1.8 * y)
}
}
{
let a = dirent(0, 2)
let d = dirent(1, -1, left: true)
cetz.draw.bezier((a.x, a.y), (d.x, d.y), (5, d.y), mark: (end: ">"))
}
for i in range(0, 2) {
for j in range(0, 2 - i) {
let a = dirent(i, j)
let c = dirent(i, -1)
let b = (x: a.x + j * 0.5 + 1.2, y: (a.y + c.y) * 0.5)
cetz.draw.bezier((a.x, a.y), (c.x, c.y), (b.x, b.y), mark: (end: ">"))
}
}
{
let a = dirent(1, 1, left: true)
let d = dirent(0, -1)
cetz.draw.bezier((a.x, a.y), (d.x, d.y), (5, d.y), mark: (end: ">"))
}
draw-dir-ent((x: 10, y: 0), file, more: false)
},
)
]
#place(bottom)[
#colbox(color: green)[*Ответ: 2*]
]
]
]
#focus-slide[
#set block(above: 25pt, below: 25pt)
#text(size: 50pt)[
*VFS*
]
= Виртуальная файловая система
]
#slide(
place-location: horizon,
)[
- К системе может быть подключено *много накопителей*: диски, USB-носители, ...;
- Каждый из них может иметь свою файловую систему;
#set align(center)
= *Как работать со всем сразу?*
]
#slide(
header: [VFS - Обобщённый интерфейс для ФС.], place-location: horizon + center,
)[
#set align(center)
=== Можно думать об этом, как о виртуальном классе:
#v(1em)
#text(size: 25pt, weight: "bold")[
```cpp
class ExFat: public virtual VFS { /* ... */ }
class Fat32: public virtual VFS { /* ... */ }
class NTFS: public virtual VFS { /* ... */ }
class FAT: public virtual VFS { /* ... */ }
class HFS: public virtual VFS { /* ... */ }
// ...
```
]
=== Теперь любую из этих файловых систем можно подключить к системе:
#text(size: 25pt, weight: "bold")[
```cpp
void System::mount(VFS* filesystem, const char* path);
```
]
]
#slide(
header: [#codebox("procfs") -- не файловая файловая система.], place-location: horizon,
)[
#set list(marker: none)
- #bash("cat /proc/meminfo") : информация о памяти;
- #bash("cat /proc/cpuinfo") : информация о CPU;
- #bash("cat /proc/version") : версия ядра;
- #bash("cat /proc/schedstat") : информация от планировщика о каждом CPU;
- #bash("cat /proc/filesystems") : информация о файловых системах.
- #bash("cat /proc/<pid>/schedstat") : информация от планировщика о процессе;
- #bash("ls /proc/<pid>/fd") : открытые файловые дескрипторы;
*Эта файловая система тоже реализует интерфейс VFS.*
]
#slide(header: [Другие примеры], place-location: horizon + left)[
== Системные:
#set list(marker: none)
- #codebox("sysfs") : содержит информацию об устройствах и драйверах;
- #codebox("pipefs") : служит для создания и использования pipe-ов;
- #codebox("ramfs") : использует оперативную память вместо диска;
- #codebox("tmpfs") : как #codebox("ramfs") , но со сбросом на swap;
== Общего назначения:
- #codebox("ecryptfs") : хранит файлы в зашифрованном виде;
- #codebox("unionfs") : объединяет несколько файловых систем вместе;
- #codebox("overlayfs") : хранит разницу двух файловых систем
]
#slide(
place-location: horizon + center,
)[
#box(
width: 90%, height: 70%,
)[
#set block(below: 25pt, above: 40pt)
= *Как быть, если очень хочется свою ФС?*
#uncover((beginning: 2))[
#text(size: 50pt, weight: "black")[FUSE]
=== Filesystem in userspace
]
#uncover((beginning: 3))[
#parbreak()
#set align(left)
#set list(marker: none)
- #pro() *Избавляет от необходимости разрабатывать драйвер для ядра*;
- #con() *Работает медленнее, чем встроенные в ядро файловые системы*.
]
]
]
#slide(
place-location: horizon + center)[
#cetz.canvas(length: 1cm, {
let background(color) = {
box(
fill: cell-color(color).background-color, width: 100%, height: 100%,
)
}
let title(color, content) = {
place(
top + left,
)[
#box(
inset: 15pt,
)[
#text(
weight: "black", size: 30pt, fill: cell-color(color).stroke-color,
)[
#content
]
]
]
}
cetz.draw.content((0, 0), (30, -8.5))[
#background(blue)
#title(blue, [Userspace])
]
cetz.draw.content((0, -8), (30, -17))[
#background(red)
#title(red, [Ядро])
]
cetz.draw.content((10.5, -1.5), (19.5, -6))[
#let cell-color = cell-color(blue);
#box(width: 100%, height: 100%, fill: cell-color.background-color, stroke: 3pt + cell-color.stroke-color, inset: 10pt)[
#align(center + horizon)[
#text(size: 30pt, fill: cell-color.stroke-color)[
*Ваша программа*
]
]
]
]
cetz.draw.content((5, -10), (25, -16))[
#let cell-color = cell-color(red);
#box(width: 100%, height: 100%, fill: cell-color.background-color, stroke: 3pt + cell-color.stroke-color, inset: 20pt)[
#align(center + horizon)[
#text(size: 30pt, fill: cell-color.stroke-color)[
*Драйвер ФС в ядре*
]
]
]
]
cetz.draw.set-style(content: (padding: .2), stroke: 10pt + black)
cetz.draw.line((13.5, -6.5), (13.5, -9.5), mark: (end: ">", start: "<"))
cetz.draw.line((16.5, -9.5), (16.5, -6.5), mark: (end: ">", start: "<"))
})
]
#slide(
place-location: horizon + center)[
#cetz.canvas(length: 1cm, {
let background(color) = {
box(
fill: cell-color(color).background-color, width: 100%, height: 100%,
)
}
let title(color, content) = {
place(
top + left,
)[
#box(
inset: 15pt,
)[
#text(
weight: "black", size: 30pt, fill: cell-color(color).stroke-color,
)[
#content
]
]
]
}
cetz.draw.content((0, 0), (30, -8.5))[
#background(blue)
#title(blue, [Userspace])
]
cetz.draw.content((0, -8), (30, -17))[
#background(red)
#title(red, [Ядро])
]
cetz.draw.content((5.5, -2), (14.5, -6))[
#let cell-color = cell-color(blue);
#box(width: 100%, height: 100%, fill: cell-color.background-color, stroke: 3pt + cell-color.stroke-color, inset: 10pt)[
#align(center + horizon)[
#text(size: 30pt, fill: cell-color.stroke-color)[
*Ваша программа*
]
]
]
]
cetz.draw.content((15.5, -2), (24.5, -6))[
#let cell-color = cell-color(blue);
#box(width: 100%, height: 100%, fill: cell-color.background-color, stroke: 3pt + cell-color.stroke-color, inset: 10pt)[
#align(center + horizon)[
#text(size: 30pt, fill: cell-color.stroke-color)[
*Userspace-драйвер*
]
]
]
]
cetz.draw.content((5, -10), (25, -16))[
#let cell-color = cell-color(red);
#box(width: 100%, height: 100%, fill: cell-color.background-color, stroke: 3pt + cell-color.stroke-color, inset: 20pt)[
#align(center + horizon)[
#text(size: 30pt, fill: cell-color.stroke-color)[
*Драйвер FUSE*
]
]
]
]
cetz.draw.set-style(content: (padding: .2), stroke: 10pt + black)
cetz.draw.line((13.5 - 5, -6.5), (13.5 - 5, -9.5), mark: (start: "<"))
cetz.draw.line((16.5 - 5, -9.5), (16.5 - 5, -6.5), mark: (end: ">"))
cetz.draw.line((13.5 + 5, -6.5), (13.5 + 5, -9.5), mark: (start: "<"))
cetz.draw.line((16.5 + 5, -9.5), (16.5 + 5, -6.5), mark: (end: ">"))
})
]
#focus-slide[
#text(size: 50pt)[
*Сеанс магии*
]
]
#slide(
header: [И всё же, зачем?], place-location: horizon,
)[
- #bash("sshfs") : проект сообщества, позволяет монтировать ФС через #bash("ssh");
- Снижает поверхность атаки;
- Позволяет монтировать *почти любые образы дисков*, не имея прав администратора.
]
#title-slide[
#place(horizon + center)[
= Спасибо за внимание!
]
#place(
bottom + center,
)[
// #qr-code("https://github.com/JakMobius/courses/tree/main/mipt-os-basic-2024", width: 5cm)
#box(
baseline: 0.2em + 4pt, inset: (x: 15pt, y: 15pt), radius: 5pt, stroke: 3pt + rgb(185, 186, 187), fill: rgb(240, 240, 240),
)[
🔗 #link(
"https://github.com/JakMobius/courses/tree/main/mipt-os-basic-2024",
)[*github.com/JakMobius/courses/tree/main/mipt-os-basic-2024*]
]
]
] |
|
https://github.com/SeniorMars/tree-sitter-typst | https://raw.githubusercontent.com/SeniorMars/tree-sitter-typst/main/examples/meta/link.typ | typst | MIT License | // Test hyperlinking.
---
// Link syntax.
https://example.com/
// Link with body.
#link("https://typst.org/")[Some text text text]
// With line break.
This link appears #link("https://google.com/")[in the middle of] a paragraph.
// Certain prefixes are trimmed when using the `link` function.
Contact #link("mailto:<EMAIL>") or
call #link("tel:123") for more information.
---
// Test that the period is trimmed.
#show link: underline
https://a.b.?q=%10#. \
Wahttp://link \
Nohttps:\//link \
Nohttp\://comment
---
// Styled with underline and color.
#show link: it => underline(text(fill: rgb("283663"), it))
You could also make the
#link("https://html5zombo.com/")[link look way more typical.]
---
// Transformed link.
#set page(height: 60pt)
#let mylink = link("https://typst.org/")[LINK]
My cool #box(move(dx: 0.7cm, dy: 0.7cm, rotate(10deg, scale(200%, mylink))))
---
// Link containing a block.
#link("https://example.com/", block[
My cool rhino
#box(move(dx: 10pt, image("/rhino.png", width: 1cm)))
])
---
// Link to page one.
#link((page: 1, x: 10pt, y: 20pt))[Back to the start]
|
https://github.com/binhtran432k/ungrammar-docs | https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/literature-review/ast.typ | typst | #import "/components/glossary.typ": gls
== Abstract Syntax Tree (AST) <sec-ast>
#gls("ast", mode: "full") are a fundamental data structure used in the fields
of programming languages, compilers, and interpreters to represent the
syntactic structure of source code. An #gls("ast") simplifies code analysis by
abstracting away unnecessary details, such as specific syntax (punctuation or
parentheses), while preserving the essential structure that reflects the
hierarchical organization of the code.
The AST remains a cornerstone in the field of programming language theory and
tool development. As programming languages evolve and become more dynamic,
AST-based parsing, analysis, and transformation techniques will continue to
play a critical role in making languages more robust and tools more efficient.
=== Historical Background
#gls("ast", mode: "short")s have been integral to the development of compilers
since the early days of computer science. Early compiler design, like in the
`FORTRAN` and `ALGOL` languages, involved creating data structures that
represented program structure, leading to the first iterations of tree-based
code representations. <NAME>'s work on Context-Free Grammars in the 1960s
laid the foundation for systematic code parsing techniques, from which ASTs
naturally evolved as a means of efficiently representing parsed code
@bib-art-cp.
=== AST in Compiler Design
#gls("ast", mode: "short")s play a key role in compiler front-ends, which
consist of the lexical analysis, parsing, and semantic analysis phases. After
the lexical analyzer tokenizes the source code, the parser generates an AST
based on the syntactic rules of the language. The tree structure allows
compilers to handle complex program logic by recursively breaking down
statements, expressions, and declarations into manageable components.
Early texts like "The Dragon Book" @bib-compilers emphasized the use of
ASTs for efficiently representing language constructs. Unlike parse trees,
which capture all details of a grammar's production rules, ASTs are more
abstract. They omit unnecessary symbols and reduce the tree to semantically
meaningful nodes, making ASTs more efficient for transformations and code
generation.
=== Recent Innovations and Tools
With the increasing complexity of modern programming languages, #gls("ast")
manipulation has become essential for various tools beyond compilers, including
linters, code analyzers, and IDEs. Tools such as LLVM's Clang, Roslyn (for
C\#), and GraalVM leverage ASTs for optimization, code refactoring, and runtime
analysis.
=== Use of AST in Static Analysis and Linters
#gls("ast", mode: "short")s are central to static analysis tools like ESLint,
Prettier, and Clippy (for Rust). These tools traverse ASTs to identify
stylistic or logical errors in the code, apply transformations, or suggest
optimizations without executing the program. ASTs offer a flexible and
language-agnostic way to analyze source code, enabling linting across multiple
languages by parsing the code into a common tree structure.
|
|
https://github.com/lebinyu/typst-thesis-template | https://raw.githubusercontent.com/lebinyu/typst-thesis-template/main/README.md | markdown | Apache License 2.0 | # typst-thesis-template
This is a [typst](https://github.com/typst/typst) template for a thesis.
The main idea is to split each part of a thesis into separate files to avoid a cumbersome main.typ file.
A template.typ include all the styling functions. main.typ is for final compilation.
Thanks to Repo [thesis-template-typst](https://github.com/ls1intum/thesis-template-typst#thesis-template-typst) (A thesis template from CIT School of TUM) for inspiring.
This template is still under construction.
|
https://github.com/sthenic/technogram | https://raw.githubusercontent.com/sthenic/technogram/main/src/keep-with-next.typ | typst | MIT License | /* We resort to a somewhat hacky solution to prevent a page break between the
content supplied as `body` and the upcoming content (which is usually text).
We create an unbreakable block containing the `body` and vertical spacing
equal to the height of five lines of text. This threshold is configurable,
but `5em` is an empirical value that seems to work in all situations where
the `body` is followed by free-form text. Likely this has something to do
with Typst's runt thresholds, potentially different within a `grid`?. If this
unbreakable block gets pushed to the next page, we know the content wouldn't
stay together like we wanted to. We follow up by undoing the vertical
spacing.
See https://github.com/typst/typst/issues/993 */
#let keep-with-next(threshold: 5em, body) = {
block(breakable: false)[
#body
#v(threshold)
]
v(-threshold)
}
|
https://github.com/ana-jiangR/Himcm-Typst-Template | https://raw.githubusercontent.com/ana-jiangR/Himcm-Typst-Template/main/Template/template_Himcm.typ | typst | MIT License | #let conf(
// Team Number.
teamNo: none,
// Summary Sheet.
summary: none,
//Problem Chosen.
problem: none,
// A list of index terms to display after the abstract.
index-terms: (),
// The paper size.
paper-size: "a4",
// The path to a bibliography file.
bibliography-file: none,
// The paper's content.
body
) = {
// Set the body font.
set text(font: "STIX Two Text", size: 12pt)
// Configure the page.
set page(
paper: paper-size,
// The margins depend on the paper size.
margin: if paper-size == "a4" {
(x: 41.5pt, top: 80.51pt, bottom: 89.51pt)
},
header: [
#set text(12pt)
#smallcaps[Team \#1234]
#h(1fr)
_Page_
_#counter(page).display("1 of 1", both:true)_
],
)
// Config equation numbering and spacing.
set math.equation(numbering: "(1)")
show math.equation: set block(spacing: 1em)
// Config tables.
set table(
fill: (col, _) => if calc.odd(col) { luma(240) } else { white },
align: (col, row) =>
if row == 0 { center }
else if col == 0 { left }
else { right },
)
// Config Code.
show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
show raw.where(block: true): block.with(
fill: luma(240),
inset: 6pt,
radius: 4pt,
breakable: true
)
// Config lists.
set enum(indent: 10pt, body-indent: 9pt)
set list(indent: 10pt, body-indent: 9pt)
// Config figures
show figure: set block(breakable: true)
// Config headings.
set heading(numbering: "I.A.1.")
show heading: it => locate(loc => {
// Find out the final number of the heading counter.
let levels = counter(heading).at(loc)
let deepest = if levels != () {
levels.last()
} else {
1
}
set text(13pt, weight: 400)
if it.level == 1 [
// First-level headings are centered smallcaps.
#let is-ack = it.body in ([Acknowledgment], [Acknowledgement])
#set align(center)
#set text(if is-ack { 15pt } else { 15pt })
#show: smallcaps
#v(18pt, weak: true)
#if it.numbering != none and not is-ack {
numbering("I.", deepest)
h(7pt, weak: true)
}
#it.body
#v(13.75pt, weak: true)
] else if it.level == 2 [
// Second-level headings are run-ins.
#set par(first-line-indent: 0pt)
#set text(style: "italic", weight: "medium")
#v(13pt, weak: true)
#if it.numbering != none {
numbering("A.", deepest)
h(7pt, weak: true)
}
#it.body
#v(10pt, weak: true)
] else [
// Third level headings are run-ins too, but different.
#if it.level == 3 {
numbering("1.", deepest)
[ ]
}
_#(it.body):_
]
})
// Display TeamNo and ProblemNo.
if teamNo != none [
#align(center, smallcaps[#text(size:10pt, weight: 500)[Team Control Number]])
#v(7pt, weak: true)
#set text(14pt, weight: 300)
#align(center, smallcaps[#text(size:25pt, weight: 500, fill: rgb("#be3030"))[#teamNo]])
#v(12pt, weak: true)
]
if problem != none [
#align(center, smallcaps[#text(size:10pt, weight: 500)[Problem Chosen]])
#v(7pt, weak: true)
#set text(14pt, weight: 300)
#align(center, smallcaps[#text(size:25pt, weight: 500, fill: rgb("#be3030"))[#problem]])
#v(10pt, weak: true)
#align(center, smallcaps[#text(size:14pt, weight: 500)[2023]])
#v(5pt, weak: true)
#align(center, smallcaps[#text(size:10pt, weight: 500)[HiMCM]])
#v(10pt, weak: true)
]
// Display summary sheet and index terms.
if summary != none [
#align(center, smallcaps[#text(size:15pt, weight: 700)[Summary Sheet]])
#line(length: 100%)
#set par(justify: true, first-line-indent: 2em)
#set text(12pt, weight: 300)
#summary
#if index-terms != () [
#set text(13pt, weight: 300)
#linebreak()
#h(2em) _*Index terms*_ --- #index-terms.join(", ")
]
#v(2pt)
]
pagebreak()
// Display outline.
align(center)[
#set text(13pt)
#show outline.entry.where(
level: 1
): it => {
v(25pt, weak: true)
strong(delta:500, it)
}
#outline(title: smallcaps[#text(weight: 700, size:20pt)[Contents]], indent: auto)
]
pagebreak()
// Start two column mode and configure paragraph properties.
// show: columns.with(2, gutter: 12pt)
set par(justify: true, first-line-indent: 1em)
show par: set block(spacing: 0.65em)
// Display the paper's contents.
body
// Display bibliography.
if bibliography-file != none {
show bibliography: set text(12pt)
bibliography(bibliography-file, title: text(13pt)[References], style: "ieee")
}
}
|
https://github.com/mariunaise/HDA-Thesis | https://raw.githubusercontent.com/mariunaise/HDA-Thesis/master/graphics/quantizers/s-metric/2_2_reconstruction.typ | typst | #import "@preview/cetz:0.2.2": canvas, plot, draw, decorations, vector
#let line_style = (stroke: (paint: red, thickness: 2pt))
#let line_style2 = (stroke: (paint: blue, thickness: 2pt))
#let dashed = (stroke: (dash: "dashed"))
#canvas({
plot.plot(size: (8,6), name: "plot",
legend: "legend.south",
legend-style: (orientation: ltr, item: (spacing: 0.5)),
x-tick-step: 1/4,
//x-ticks: ((3/16, [3/16]), (7/16, [7/16]), (11/16, [11/16]), (15/16, [15/16])),
y-label: $cal(R)(2, 2, tilde(x))$,
x-label: $tilde(x)$,
y-tick-step: none,
y-ticks: ((1/4, [00]), (2/4, [01]), (3/4, [10]), (1, [11])),
axis-style: "left",
x-min: 0,
x-max: 1,
y-min: 0,
y-max: 1,{
plot.add(((0,1/4), (3/16,1/4), (7/16,2/4), (11/16,3/4), (15/16, 1), (15/16, 1/4), (1, 1/4)), line: "vh", style: line_style, label: [Metric 1])
plot.add(((0, 1), (1/16, 1), (1/16, 1/4), (5/16, 1/4), (9/16, 2/4), (13/16, 3/4), (13/16, 1), (1, 1)),line: "vh", style: line_style2, label: [Metric 2])
plot.add-hline(1/4, 2/4, 3/4, 1, style: dashed)
plot.add-vline(1/4, 2/4, 3/4, 1, style: dashed)
plot.add-anchor("2phi1", (0.25, 0.25))
plot.add-anchor("2phi2", (5/16, 1/4))
plot.add-anchor("1phi1", (0.25, 0.5))
plot.add-anchor("1phi2", (3/16, 2/4))
})
decorations.brace("plot.2phi2", "plot.2phi1", name: "plusphi")
draw.content((v => vector.add(v, (+0.1, -0.2)), "plusphi.south"), [$plus phi$])
decorations.brace("plot.1phi2", "plot.1phi1", name: "minusphi")
draw.content((v => vector.add(v, (-0.1, +0.3)), "minusphi.north"), [$minus phi$])
})
|
|
https://github.com/CarlosCraveiro/PDSA_Presentation | https://raw.githubusercontent.com/CarlosCraveiro/PDSA_Presentation/main/README.md | markdown | Other | # Apresentação: MIMD - Múltiplos Fluxos de Instruções-Múltiplos Fluxos de Dados - SEL0631
Essa apresentação foi elaborada como atividade avaliativa para a disciplina SEL0631 - Processadores Digitais de Sinais e Aplicações, ministrada no segundo semestre de 2024 pelo professor doutor <NAME>.
|**Data** |**Título** |
|----------|----------------------------------------------------------------|
|08/24/2024| MIMD - Múltiplos Fluxos de Instruções-Múltiplos Fluxos de Dados|
-----------------------------------------------------------------------------
## Banner/Poster
Está disponível em [`main.pdf`](https://github.com/CarlosCraveiro/PDSA_Presentation/blob/main/main.pdf).
## Template utilizado
O template utilizado `poster.typ` foi retirado do repositório [typst-poster](https://github.com/pncnmnp/typst-poster/tree/master), com apenas algumas poucas adaptações.
## Compilar a apresentação
Baixe as dependências você mesmo, basicamente o `typst` e um visualizador de pdf.
Ou use `nix` para gerenciar as dependências para você:
```bash
nix --experimental-features 'nix-command flakes'
nix develop -c $SHELL
```
Então, só compilar com:
```bash
typst compile main.typ
```
Agora você deve ter um `main.pdf` para olhar!
## Autores
| Estudante | Nº USP |
|---------------------------------------|--------- |
| <NAME> | 12547187 |
| <NAME> | 11798853 |
## Licensa
Este trabalho está sob a licensa **Creative Commons Attribution-ShareAlike 4.0 International**, o que inclui as imagens indicadas como autorais.
|
https://github.com/SE-legacy/physics_lectures_3_term | https://raw.githubusercontent.com/SE-legacy/physics_lectures_3_term/main/lesson_4/main.typ | typst | #import "conf.typ": conf
#show: conf.with(
meta: (
title: "Физика. Занятие №4, 30.09.2024",
author: "<NAME>., СГУ им. Чернышевского",
group: 251,
city: "Саратов",
year: 2024,
)
)
= Ток проводимости
Носители зарядов совершают сложное движение:
+ Хаотическое со срелней скоростью $v dash.wave sqrt(k T)$
+ Направленное со средней скоростью $v dash.wave E$ (доли мм/с)
За направление тока условно принято направление положительных зарядов.
#underline[Параметры тока:]
+ Сила тока (I) --- количественная мера (характеристика) электрического тока
$I = (d q) / (d t)$ В СИ: $[1 А = (1 "Кл") / (1 "с")]$
+ Плотность тока --- характеристика распределения заряда по сечению проводника
$j = (d q) / (d S_n d t) = (d I) / (d S_n)$ В СИ: $[A / "м"^2]$
#image("images/1.jpg")
$d I = overline(j) d overline(S) = j d S cos(angle overline(j), d overline(S)) = j d s cos(alpha) = j d S_n$.
!! $I = integral_S overline(j) d overline(S)$
#image("images/2.jpg")
$I = (d q) / (d t) = (n e d V) / (d t) = (n e angle.l lambda angle.r d S) / (d t) = (n e v d t d S) / (d t) = n e angle.l v angle.r d S$
!! $j = I / (d S) = n e angle.l v angle.r$
Потенциал $phi$ и плотность заряда $rho$ остаются неизменными, т.е. rho не зависит от времени $t$, ток называется *стационарным*
$d i v overline(j) = 0$
+ Физическая величина, численно равная работе сторонней силы по переносу единичного положительного заряда внутри источника --- электродвижущая сила (ЭДС):
$epsilon = A / q_(0+)$
ЭДС в замкнутой цепи может быть определена как циркуляция вектора напряженности сторонних сил
$epsilon = #sym.integral.cont overline(E_("ст")) d overline(l)$
на заряды на участке цепи, в котором есть источник тока, действуют кулоновские и сторонние силы.
Напряжение на участке цепи:
$U = phi_1 - phi_2 + epsilon$
= Закон Ома для однородного проводника
*Сила тока, протекающего по однородному проводнику, пропорциональна разности потенциалов на его концах*
$R = rho l / s$, $I = U / R$, $j S = (E l) / ((rho l) / S) = (E S) / rho$
Сопротивление проводника заависит от его температуры
$rho = rho_0 (1 + alpha dot t)$
$R = R_0 ( 1 + alpha dot t)$
#image("images/3.jpg")
Закон Ома в локальной форме: в однородном материале плотность тока в любой точке пропорциональна величине электрического поля:
$overline(j) = sigma overline(E)$, где $sigma = 1 / rho$ --- уд. электропроводимость среды
В случае стационарных токов макроскопические электрические заряды могут находиться только на поверхности или в местах неоднородности проводящей среды.
#image("images/4.jpg")
Если источник ЭДС включен таким образом, что в направлении протекания тоа он повышает потенциал электрической цепи, то он берется с "+"
*Сила тока, протекающего по неоднородному проводнику, пропорциональна сумме разности потенциалов на его концах и ЭДС сторонних сил*
$I = epsilon / (R + r_i)$, где $epsilon$ --- ЭДС, $r_i$ --- сопротивление внутреннее, $R$ --- сопротивление внешнее.
= Правила Кирхгофа
#image("images/5.jpg")
Формулировка 1: *Сумма всех токов, втекающих в узел равна сумме всех токов вытекающих из узла*
Формулировка 2: *Алгебраическая сумма всех токов равна нулю.*
$sum_(i = 1)^n I_i = 0$
Формулировка: *Алгебраическая сумма ЭДС, действующих в замкнутом контуре, равна алгебраической сумме падений напряжения на всех резистивных элементах в этом контуре*
$sum_(i = 1)^n I_i R_i = sum_(i = 1)^k epsilon_id$
Необходимые условия:
+ Произвольный замкнутый контур обходится в одном направлении через все его участки и элементы.
+ Если в разветвленной цепи имеется N узлов, то число уровней составленных по 1 з-ну (N - 1). Число независимых уравнений по 2 з-ну равно наименьшему числу разрывов, которые слудует сделать в цепи, чтобы нарушить все контуры.
#image("images/6.jpg")
При параллельном соединении резисторов $R_1, R_2, ... , R_n$ падение напряжения $U$ одинаково на всех резисторах.
$sum_(i = 1)^n I_i = I$
!! $ 1 / R = sum_(i = 1)^n 1 / R_i = (sum_(i = 1)^n I_i) / U$
= <NAME>
Если в проводнике устанавливается равновесие, то работа электрического тока должна быть равна потерям энергии на этом участке цепи.
$d A = d q * (phi_1 - phi_2) = I (phi_1 - phi_2) d t$
$P = (d A) / (d t) = I (phi_1 - phi_2) = I U = I^2 R = (U^2) / R$
!!$Q = I^2 R t + I^2 r t = I^2(R + r) t$
Этот закон был экспериментально открыт в 1841 году Дж. Джоулем и независимо от него в 1842 году Э.Х.Ленцем.
Формулировка: Удельная тепловая мощность тока пропорциональна квадрату плотности электрического тока и удельному сопротивлению среды в данной точке.
!!$P _"уд" = (d Q) / (V d t) = P / t = rho j^2$
!!$P_"уд" = overline(j) dot overline(E) = sigma E^2$
= Закон электролиза Фарадея
Электролитами ы широком смысле слова называются вещества, химичкски разлагающиеся на составные части, когда по ним проходит электрический ток.
Разложение электролита на его составные части под действием электрического тока называется электролизом.
Первая гипотеза для объяснения электролиза была предложена Гротгусом в 1805 г. Согласно этой гипотезе молекулы растворенного вещества состоят из двух частей, из которых одна заряжена положительно, а другая --- отрицательно. Данный механизм доказан в 2015 году.
#image("images/7.jpg")
#image("images/8.jpg")
Законы Фарадея определяют количества первичных продуктов, выделяющихся на электродах при электролизе.
Пусть на электроде выделилось n ионов. Тогда их заряд по абсолютной величине будет $n v e$.
Если эти ионы выделились на катоде, то их заряд нейтрализуется электронами, подтекающими к катоду по проводам, соединяющим его с ичсточником тока.
Если же они выделяются на аноде, то такое же количество электронов по проводам утечет от анода. В обоих случаях чеоез цепь пройдет количество жлекьричеста $q = n v e$
Первый закон Фарадея: масса вещества, выделяющегося при электролизе на каждом электроде, пропорциональна количеству прошедшего электричества:
$M = k Q = k I t$
Второй закон утверждает, что эта масса пропорциональна электрохимическому эквиваленту k
$k = 1/ F dot A / z$, где $A = N_A dot m$ --- атомная масса элемента, $z$ --- валентность, $F$ = 96485.3 Кл/моль --- постоянная Фарадея
$M = 1/ F dot A/z Q$, $F = N e$
#image("images/9.jpg")
Закон Ома для электролитов:
$j = z n e alpha (u_(+) + u(-)) E => j = sigma E$
$sigma = z n e alpha (u_(+) + u(-))$, где $z$ --- валентность ионов, $sigma$ --- уд. электропроводность электролитов, $alpha$ --- коэфициент диссоциации, $n$ --- концентрация всех молекул растворенного вещества, $u$ --- подвижность ионов
Электролитическая диссоциация --- расщепление нейтральной молекулы на положительные и отрицательные ионы в результате взаимодействия растворенного вещества с растворителем.
Процесс образования нейтральной молекулы при столкновении положительного и отрицательного ионов называется рекомбинацией (молизацией).
*При увеличении температуры подвижность ионов растет, а сопротивление уменьшается*
Применение электролиза:
#image("images/11.jpg")
== Электрический ток в газах
Процесс ионизации заключается в том, что под действием высокой температуры или некоторых лучей молекулы газа теряют электроны, и тем самым превращаются в положительные ионы.
Ионизация газа может происходить под действием коротковолнового излучения --- ультрафиолетовых, рентгеновских и гамма-лучей, а также альфа, бета- и космических лучей.
Электрический ток, возникающий в процессе ионизации газа --- ток в газах --- это встречный поток ионов и свободных электронов.
Прохождение электрического тока через газы называется газовым разрядом.
В проводимости газов одновременно участвуют положительные, отрицательные ионы и электроны.
Если не учитывать проводимость электронов, то по аналогии с электролитами можно записать закон Ома для газов: (бля, пропустил)
#image("images/11.jpg")
#image("images/12.jpg")
Появление ярко светящегося канала искры предшествует возникновение слабосветящихся скопления ионизованного газа --- стримеров.
Стримеры возникают в результате образования электронных лавин вследствие ударной или фотонной ионизации.
Лавины, следуя одна за другой образуют проводящие каналы из стримеров, следствием чего является образование канала искрового разряда.
Примечание: свеча зажигания, искровые разрядники, электроискровая обработка металлов.
#image("images/13.jpg")
Впервые дуговой разряд был получен <NAME> в 1802 году.
Поддерживается за счет высокой температуры катода из-за интенсивной термоэлектронной эмиссии и термической ионизации молекул.
Применение: электросварка, дуговые электропечи, мощные источники света.
#image("images/14.jpg")
Высоковольтный электрический разряд при высоком давлении (близком к атмосферному) в сильно неоднородном электрическом поле.
При напряженности электрического поля $E dash.wave 30 "кВ"/"см"$ вблизи острия вощникает свечение по форме, напоминающее корону.
#image("images/15.jpg")
*Коронный разряд:*
+ Коронирует катод --- отрицательная корона: электроны выбиваются из катода при его бомбардировке положительными ионами. Электроны вызывают ударную ионазицию молекул газа.
+ Коронирует Анод --- положительная корона: электроны рождаются вследствие фотоионизации газа вблизи анода.
Применение: молниеотводы, электрофильтры, нанесение красок в коронном разряде.
Вредное действие: радиопомехи, возникновение на проводах высоковольтных ЛЭП приводит к возникновению утечек тока.
#image("images/16.jpg") |
|
https://github.com/HarumiKiyama/resume | https://raw.githubusercontent.com/HarumiKiyama/resume/master/cv_cn.typ | typst | #set text(font: "FiraCode Nerd Font Mono")
#show link: underline
// Uncomment the following lines to adjust the size of text
// The recommend resume text size is from `10pt` to `12pt`
// #set text(
// size: 12pt,
// )
// Feel free to change the margin below to best fit your own CV
#set page(
margin: (x: 0.9cm, y: 1.3cm),
)
// For more customizable options, please refer to official reference: https://typst.app/docs/reference/
#set par(justify: true)
#let chiline() = {v(-3pt); line(length: 100%); v(-5pt)}
= 王力超
<EMAIL> | +86-18668042190 |
#link("https://github.com/harumikiyama")[github.com/harumikiyama] | #link("https://harumikiyama.github.io")[harumikiyama.github.io]
== Work Experience
#chiline()
*浙江长河拾贝投资管理有限公司* #h(1fr) 2020-03 -- 至今 \
Quant Developer #h(1fr) 杭州 \
- #lorem(20)
- #lorem(30)
- #lorem(40)
*Mozat PTE LTD* #h(1fr) 2018/10 -- 2020/01 \
Senior Data Engineer #h(1fr) Singapore \
- #lorem(20)
- #lorem(30)
- #lorem(40)
*南京贝湾信息科技有限公司* #h(1fr) 2017/07 -- 2018/10 \
Backend Engineer #h(1fr) 南京 \
- #lorem(20)
- #lorem(30)
- #lorem(40)
*杭州陌仟科技有限公司* #h(1fr) 2015/09 -- 2017/06 \
Backend Engineer #h(1fr) 杭州 \
- #lorem(20)
- #lorem(30)
- #lorem(40)
== 个人项目
#chiline()
*chibicc_rust* #h(1fr) \
基于 *chibicc*, 使用 rust 实现了一个迷你版 c 语言编译器
== 教育经历
#chiline()
*华中科技大学* #h(1fr) 2011/09 -- 2015/06 \
生物科学实验班(本科) #h(1fr) 武汉 \
|
|
https://github.com/maxgraw/bachelor | https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/4-concept/0-index.typ | typst | Im folgenden Kapitel wird die Wahl der Technologie im Kontext der Konzeptentwicklung eingehend betrachtet, wobei besonderes Augenmerk auf die Erfüllung der Zielgruppenanforderungen und die effektive Erreichung der definierten Ziele gelegt wird.
== Zielgruppenanalyse
#include "group.typ"
== Anforderungsanalyse
#include "requirement.typ"
== Definition und Abgrenzung des Konzeptes
#include "definition.typ"
== Architektur <architecture-chapter>
#include "architecture.typ"
== User Flow <user-flow-chapter>
#include "userflow.typ"
== Wireframe
#include "wireframe.typ"
== Externe Schnittstelle
#include "shop-interface.typ" |
|
https://github.com/JakMobius/courses | https://raw.githubusercontent.com/JakMobius/courses/main/mipt-os-basic-2024/sem02/floats.typ | typst |
#let get-bit-length(number) = {
let length = 0
while number != 0 {
number = int.bit-rshift(number, 1)
length += 1
}
length
}
#let is-bit-set(number, bit) = {
let mask = int.bit-lshift(1, bit)
int.bit-and(mask, number) != 0
}
#let float-construct(
sign: none,
mantissa: none,
exponent: none,
mantissa-bits: none,
exponent-bits: none
) = {
if exponent < 0 {
// zero
exponent = 0
mantissa = 0
}
let exponent-max = int.bit-lshift(1, exponent-bits) - 1
if exponent >= exponent-max {
// infinity
exponent = exponent-max
mantissa = 0
}
let mantissa-max = int.bit-lshift(1, mantissa-bits) - 1
mantissa = int.bit-and(mantissa, mantissa-max)
return (
sign: sign,
mantissa: mantissa,
exponent: exponent,
mantissa-bits: mantissa-bits,
exponent-bits: exponent-bits,
)
}
#let float-nan(exponent-bits, mantissa-bits) = {
// Constructor is not invoked here, it would turn it into infinity
(
sign: false,
mantissa: int.bit-lshift(1, mantissa-bits - 1),
exponent: int.bit-lshift(1, exponent-bits) - 1,
mantissa-bits: mantissa-bits,
exponent-bits: exponent-bits,
)
}
#let float-one(sign, exponent-bits, mantissa-bits) = {
float-construct(
sign: sign,
mantissa: 0,
exponent: int.bit-lshift(1, exponent-bits - 1),
mantissa-bits: mantissa-bits,
exponent-bits: exponent-bits,
)
}
#let float-infinity(sign, exponent-bits, mantissa-bits) = {
float-construct(
sign: sign,
mantissa: 0,
exponent: int.bit-lshift(1, exponent-bits) - 1,
mantissa-bits: mantissa-bits,
exponent-bits: exponent-bits,
)
}
#let float-zero(sign, exponent-bits, mantissa-bits) = {
float-construct(
sign: sign,
mantissa: 0,
exponent: 0,
mantissa-bits: mantissa-bits,
exponent-bits: exponent-bits,
)
}
#let float-is-zero(float) = {
float.exponent == 0 and float.mantissa == 0
}
#let float-is-nan(float) = {
float.exponent == int.bit-lshift(1, float.exponent-bits) - 1 and float.mantissa != 0
}
#let float-is-infinity(float) = {
float.exponent == int.bit-lshift(1, float.exponent-bits) - 1 and float.mantissa == 0
}
#let float-from-int(number, exponent-bits, mantissa-bits) = {
if number == 0 {
return float-zero(false, exponent-bits, mantissa-bits)
}
let abs-number = calc.abs(number)
let mantissa-mask = int.bit-lshift(1, mantissa-bits + 1) - 1
let mantissa-high-bit = int.bit-lshift(1, mantissa-bits)
let mantissa-result = int.bit-and(int(abs-number), mantissa-mask)
let mantissa-shift = 0
while (int.bit-and(mantissa-result, mantissa-high-bit) == 0) {
mantissa-result = int.bit-lshift(mantissa-result, 1)
mantissa-shift += 1
}
let exponent-max = int.bit-lshift(1, exponent-bits) - 1
let exponent-zero = int.bit-lshift(1, exponent-bits - 1) - 1
let exponent-result = mantissa-bits - mantissa-shift + exponent-zero
float-construct(
sign: number < 0,
mantissa: mantissa-result,
exponent: exponent-result,
mantissa-bits: mantissa-bits,
exponent-bits: exponent-bits
)
}
#let float-from-bits(bits, exponent-bits, mantissa-bits) = {
let exponent = 0
let mantissa = 0
for i in array.range(exponent-bits) {
if bits.at(i + 1) {
exponent = int.bit-or(exponent, int.bit-lshift(1, exponent-bits - i - 1));
}
}
for i in array.range(mantissa-bits) {
if bits.at(i + exponent-bits + 1) {
mantissa = int.bit-or(mantissa, int.bit-lshift(1, mantissa-bits - i - 1));
}
}
(
sign: bits.at(0),
mantissa: mantissa,
exponent: exponent,
mantissa-bits: mantissa-bits,
exponent-bits: exponent-bits,
)
}
#let float-is-normalized(float) = {
return float.exponent != 0
}
#let float-get-full-mantissa(float) = {
if float-is-normalized(float) {
let mantissa-extra-bit = int.bit-lshift(1, float.mantissa-bits);
return int.bit-or(float.mantissa, mantissa-extra-bit)
}
return float.mantissa
}
#let float-value(float) = {
if(float-is-zero(float)) {
return if float.sign { -0 } else { +0 }
}
if(float-is-infinity(float)) {
return if float.sign { -calc.inf } else { +calc.inf }
}
if(float-is-nan(float)) {
return if float.sign { -calc.nan } else { +calc.nan }
}
let factor-power = float.exponent - int.bit-lshift(1, float.exponent-bits - 1) + 1
if not float-is-normalized(float) {
factor-power += 1
}
let result = float-get-full-mantissa(float) * calc.pow(2, factor-power - float.mantissa-bits)
if float.sign {
-result
} else {
result
}
}
#let float-bits(float) = {
let bit-array = (float.sign,)
for i in array.range(float.exponent-bits) {
if is-bit-set(float.exponent, float.exponent-bits - i - 1) {
bit-array.push(true)
} else {
bit-array.push(false)
}
}
for i in array.range(float.mantissa-bits) {
let bit = is-bit-set(float.mantissa, float.mantissa-bits - i - 1)
bit-array.push(bit)
}
bit-array
}
#let float-compare(a, b) = {
assert.eq(a.mantissa-bits, b.mantissa-bits, message: "can only compare floats with same format")
assert.eq(a.exponent-bits, b.exponent-bits, message: "can only compare floats with same format")
a.sign == b.sign and a.exponent == b.exponent and a.mantissa == b.mantissa
}
#let shr-with-rounding(number, bits) = {
if bits == 0 {
return number
}
number = int.bit-rshift(number, bits - 1)
let round-up = is-bit-set(number, 0)
number = int.bit-rshift(number, 1)
return number + int(round-up)
}
#let trim-mantissa(mantissa, bits) = {
let mantissa-overflow-bit = int.bit-lshift(1, bits + 1);
let round-up = false
let counter = 0
while mantissa >= mantissa-overflow-bit {
round-up = is-bit-set(mantissa, 0)
counter += 1
mantissa = int.bit-rshift(mantissa, 1)
}
// Round up if last trimmed bit was 1
if round-up and mantissa + 1 < mantissa-overflow-bit {
mantissa += 1;
}
return (counter, mantissa)
}
#let float-add(a, b) = {
assert.eq(a.mantissa-bits, b.mantissa-bits, message: "can only add floats with same format")
assert.eq(a.exponent-bits, b.exponent-bits, message: "can only add floats with same format")
if(float-is-nan(a) or float-is-nan(b)) {
return float-nan(a.exponent-bits, b.mantissa-bits)
}
if(float-is-infinity(a) and float-is-infinity(b) and a.sign != b.sign) {
return float-nan(a.exponent-bits, b.mantissa-bits)
}
if(float-is-infinity(a) or float-is-zero(b)) {
return a
}
if(float-is-infinity(b) or float-is-zero(a)) {
return b
}
let a-exponent = a.exponent + int(not float-is-normalized(a))
let b-exponent = b.exponent + int(not float-is-normalized(b))
let max-exponent = calc.max(a-exponent, b-exponent)
let a-mantissa = float-get-full-mantissa(a)
let b-mantissa = float-get-full-mantissa(b)
// panic(float-value(a), float-value(b))
// panic((a-exponent, a-mantissa), (b-exponent, b-mantissa))
let normalized-a-mantissa = shr-with-rounding(a-mantissa, max-exponent - a-exponent)
let normalized-b-mantissa = shr-with-rounding(b-mantissa, max-exponent - b-exponent)
if a.sign { normalized-a-mantissa = -normalized-a-mantissa }
if b.sign { normalized-b-mantissa = -normalized-b-mantissa }
// panic((max-exponent, normalized-a-mantissa, normalized-b-mantissa))
let mantissa-result = normalized-a-mantissa + normalized-b-mantissa
let sign = mantissa-result < 0
mantissa-result = calc.abs(mantissa-result)
let mantissa-result-length = get-bit-length(mantissa-result)
let exponent-result = calc.max(a.exponent, b.exponent)
// panic((mantissa-result, mantissa-result-length, a.mantissa-bits))
// Avoid extending denormalized float
if mantissa-result-length > a.mantissa-bits + 1 {
let (trimmed-bits, trimmed-mantissa) = trim-mantissa(mantissa-result, a.mantissa-bits)
mantissa-result = trimmed-mantissa
exponent-result += trimmed-bits;
} else if mantissa-result-length < a.mantissa-bits + 1 {
if(mantissa-result == 0) {
return float-zero(false, a.exponent-bits, a.mantissa-bits);
}
for i in array.range(mantissa-result-length, a.mantissa-bits + 1) {
if exponent-result > 0 {
exponent-result -= 1;
}
if exponent-result > 0 {
mantissa-result = int.bit-lshift(mantissa-result, 1);
}
}
}
float-construct(
sign: sign,
mantissa: mantissa-result,
exponent: exponent-result,
mantissa-bits: a.mantissa-bits,
exponent-bits: a.exponent-bits,
)
}
#let float-mul(a, b) = {
assert.eq(a.mantissa-bits, b.mantissa-bits, message: "can only mul floats with same format")
assert.eq(a.exponent-bits, b.exponent-bits, message: "can only mul floats with same format")
if(float-is-nan(a) or float-is-nan(b)) {
return float-nan(a.exponent-bits, b.mantissa-bits)
}
if(float-is-infinity(a) or float-is-infinity(b)) {
if(float-is-zero(a) or float-is-zero(b)) {
return float-nan(a.exponent-bits, b.mantissa-bits)
}
return float-infinity(a.sign != b.sign, a.exponent-bits, b.mantissa-bits)
}
if(float-is-zero(a) or float-is-zero(b)) {
return float-zero(a.sign != b.sign, a.exponent-bits, a.mantissa-bits)
}
let exponent-zero = int.bit-lshift(1, a.exponent-bits - 1) - 1
let a-mantissa = float-get-full-mantissa(a)
let b-mantissa = float-get-full-mantissa(b)
let (trimmed-bits, mantissa-result) = trim-mantissa(a-mantissa * b-mantissa, a.mantissa-bits)
let exponent-result = a.exponent + b.exponent - exponent-zero - a.mantissa-bits + trimmed-bits
float-construct(
sign: a.sign != b.sign,
mantissa: mantissa-result,
exponent: exponent-result,
mantissa-bits: a.mantissa-bits,
exponent-bits: a.exponent-bits,
)
}
#let float-div(a, b) = {
assert.eq(a.mantissa-bits, b.mantissa-bits, message: "can only div floats with same format")
assert.eq(a.exponent-bits, b.exponent-bits, message: "can only div floats with same format")
if(float-is-nan(a) or float-is-nan(b)) {
return float-nan(a.exponent-bits, b.mantissa-bits)
}
if float-is-zero(a) {
if float-is-zero(b) {
return float-nan(a.exponent-bits, a.mantissa-bits)
}
return float-zero(a.sign != b.sign, a.exponent-bits, a.mantissa-bits)
}
if float-is-infinity(a) {
if float-is-infinity(b) or float-is-zero(b) {
return float-nan(a.exponent-bits, b.mantissa-bits)
}
return float-infinity(a.sign != b.sign, a.exponent-bits, b.mantissa-bits)
}
if float-is-zero(b) {
return float-infinity(a.sign != b.sign, a.exponent-bits, a.mantissa-bits)
}
if float-is-infinity(b) {
return float-zero(a.sign != b.sign, a.exponent-bits, b.mantissa-bits)
}
let exponent-max = int.bit-lshift(1, a.exponent-bits) - 1
let exponent-zero = int.bit-lshift(1, a.exponent-bits - 1) - 1
let a-mantissa = float-get-full-mantissa(a)
let b-mantissa = float-get-full-mantissa(b)
let exponent-result = a.exponent - b.exponent + exponent-zero + a.mantissa-bits
let mantissa-result = 0
let rem = a-mantissa
let shift = 0
// Do the long division
let mantissa-max = int.bit-lshift(1, a.mantissa-bits) - 1;
while mantissa-result <= mantissa-max {
if rem >= b-mantissa {
mantissa-result += 1
rem -= b-mantissa
}
mantissa-result = int.bit-lshift(mantissa-result, 1)
rem = int.bit-lshift(rem, 1)
exponent-result -= 1
}
float-construct(
sign: a.sign != b.sign,
mantissa: mantissa-result,
exponent: exponent-result,
mantissa-bits: a.mantissa-bits,
exponent-bits: a.exponent-bits,
)
}
#let float-neg(float) = {
float-construct(
sign: not float.sign,
mantissa: float.mantissa,
exponent: float.exponent,
mantissa-bits: float.mantissa-bits,
exponent-bits: float.exponent-bits,
)
}
#let find-exponent(exponent-bits, mantissa-bits, guide-float) = {
let exponent-mask = int.bit-lshift(1, exponent-bits) - 1
let mantissa-mask = int.bit-lshift(1, mantissa-bits) - 1
let result = float-construct(
sign: false,
mantissa: 0,
exponent: 0,
exponent-bits: exponent-bits,
mantissa-bits: mantissa-bits
)
let exponent-zero = int.bit-lshift(1, result.exponent-bits - 1) - 1
let offset = calc.pow(2, -exponent-zero - result.mantissa-bits)
while(float-value(result) <= guide-float + offset / 2) {
result.exponent += 1
if result.exponent == exponent-mask {
break
}
offset *= 2
}
result.exponent -= 1
result
}
#let float-from-string(string, exponent-bits, mantissa-bits) = {
let guide-float = float(string)
let sign = false
if guide-float < 0 {
sign = true
guide-float = -guide-float
}
let mantissa-mask = int.bit-lshift(1, mantissa-bits) - 1
let exponent-mask = int.bit-lshift(1, exponent-bits) - 1
let result = find-exponent(exponent-bits, mantissa-bits, guide-float)
for i in array.range(0, result.mantissa-bits) {
let mask = int.bit-lshift(1, result.mantissa-bits - i - 1)
let old-mantissa = result.mantissa
result.mantissa = int.bit-or(result.mantissa, mask)
if float-value(result) > guide-float {
result.mantissa = old-mantissa
}
}
if float-value(result) < guide-float {
float-infinity(sign, result.exponent-bits, result.mantissa-bits)
}
result.sign = sign
result
}
#let floats-test() = {
let size(exponent, mantissa) = {
(
float: (number) => {
float-from-string(str(number), exponent, mantissa)
},
inf: (sign: false) => {
float-infinity(sign, exponent, mantissa)
},
nan: (sign: false) => {
float-nan(exponent, mantissa)
},
neg: (float) => {
float-neg(float)
},
check-add: (a, b, c) => {
let sum = float-add(a, b)
assert(float-compare(c, sum), message: str(float-value(a)) + " + " + str(float-value(b)) + " = " + str(float-value(sum)) + " instead of " + str(float-value(c)));
},
check-mul: (a, b, c) => {
let sum = float-mul(a, b)
assert(float-compare(c, sum), message: str(float-value(a)) + " * " + str(float-value(b)) + " = " + str(float-value(sum)) + " instead of " + str(float-value(c)));
},
check-div: (a, b, c) => {
let sum = float-div(a, b)
assert(float-compare(c, sum), message: str(float-value(a)) + " / " + str(float-value(b)) + " = " + str(float-value(sum)) + " instead of " + str(float-value(c)));
}
)
}
let test-size(exponent, mantissa) = {
let (float, inf, nan, neg, check-add, check-mul, check-div) = size(exponent, mantissa)
check-add(float(4), float(-2), float(2))
assert.eq(float-value(float(1)), 1)
assert.eq(float-value(float(3)), 3)
assert(not float-compare(float(1), float(2)))
assert(float-compare(float(1), float(1)))
assert(float-compare(float(-1), neg(float(1))))
assert(float-compare(inf(), neg(inf(sign: true))))
assert(float-compare(neg(inf()), inf(sign: true)))
check-add(float(0), float(1), float(1))
check-add(float(1), float(0), float(1))
check-add(neg(float(0)), float(1), float(1))
check-add(float(1), neg(float(0)), float(1))
check-add(float(1), float(2), float(3))
check-add(float(2), float(1), float(3))
check-add(float(2), float(2), float(4))
check-add(float(2), float(4), float(6))
check-add(float(4), float(2), float(6))
check-add(float(4), float(4), float(8))
check-add(float(4), float(-2), float(2))
check-add(float(-2), float(4), float(2))
check-add(float(4), float(-4), float(0))
check-add(float(4), float(-6), float(-2))
check-add(float(-2), float(6), float(4))
check-add(float(-2), nan(), nan())
check-add(nan(), float(-2), nan())
check-add(nan(), nan(), nan())
check-add(inf(), float(5), inf())
check-add(float(5), inf(), inf())
check-add(nan(), inf(), nan())
check-add(inf(), nan(), nan())
check-add(inf(), inf(), inf())
check-add(inf(), inf(sign: true), nan())
check-add(inf(sign: true), inf(), nan())
check-mul(float(1), float(1), float(1))
check-mul(float(1), float(2), float(2))
check-mul(float(2), float(1), float(2))
check-mul(float(2), float(2), float(4))
check-mul(float(2), float(-2), float(-4))
check-mul(float(-2), float(2), float(-4))
check-mul(float(-2), float(-2), float(4))
check-mul(float(5), float(-1), float(-5))
check-mul(float(5), float(0), float(0))
check-mul(float(0), float(5), float(0))
check-mul(float(-2), nan(), nan())
check-mul(nan(), float(0), nan())
check-mul(nan(), nan(), nan())
check-mul(inf(), float(5), inf())
check-mul(float(5), inf(), inf())
check-mul(inf(), inf(), inf())
check-mul(inf(), inf(sign: true), inf(sign: true))
check-mul(inf(sign: true), inf(), inf(sign: true))
check-mul(inf(), float(0), nan())
check-mul(float(0), inf(), nan())
check-div(float(1), float(0), inf())
check-div(float(1), neg(float(0)), inf(sign: true))
check-div(nan(), nan(), nan())
check-div(inf(), float(0), nan())
check-div(inf(), float(1), inf())
check-div(inf(sign: true), float(1), inf(sign: true))
check-div(inf(sign: true), float(-1), inf())
check-div(inf(), float(-1), inf(sign: true))
check-div(float(10), float(1), float(10))
check-div(float(10), float(2), float(5))
check-div(float(10), float(10), float(1))
check-div(float(10), float(-10), float(-1))
check-div(float(0), float(10), float(0))
check-div(float(0), float(-10), neg(float(0)))
}
test-size(3, 3)
test-size(3, 4)
test-size(4, 3)
test-size(4, 4)
{
let (float, inf, nan, neg, check-add, check-mul, check-div) = size(3, 4)
// Check rounding
check-mul(float(1.1875), float(1.1875), float(1.4375))
}
{
let (float, inf, nan, neg, check-add, check-mul, check-div) = size(3, 4)
// Check denormalized floats
let smallest-float = float(0.015625)
assert.eq(smallest-float.exponent, 0)
assert.eq(smallest-float.mantissa, 1)
assert.eq(float-value(smallest-float), 0.015625)
let two-smallest-floats = float-add(smallest-float, smallest-float)
assert.eq(float-value(two-smallest-floats), 0.015625 * 2)
let one-exponent = float(0.25)
assert.eq(one-exponent.exponent, 1)
assert.eq(one-exponent.mantissa, 0)
assert.eq(float-value(one-exponent), 0.25);
assert.eq(float-add(smallest-float, one-exponent).exponent, 1)
assert.eq(float-add(smallest-float, one-exponent).mantissa, 1)
assert.eq(float-value(float-add(smallest-float, one-exponent)), 0.265625)
assert.eq(float-add(one-exponent, neg(smallest-float)).exponent, 0)
assert.eq(float-add(one-exponent, neg(smallest-float)).mantissa, 15)
}
} |
|
https://github.com/marcantoinem/CV | https://raw.githubusercontent.com/marcantoinem/CV/main/fr/project.typ | typst | #import "../src/style.typ": experience
#let generateur = {
experience(
"Générateur d'horaire de l'AEP v2",
link("https://beta.horaires.aep.polymtl.ca/", "beta.horaires.aep.polymtl.ca"),
"Août 2023 - Présent",
"Réécriture du générateur d'horaire",
[
- Remplacement de l'ancien générateur d'horaires AEP, une application web qui aide les étudiants de Polytechnique Montréal à générer leur emploi du temps pour le semestre.
- Mise en œuvre d'un nouvel algorithme pour générer des horaires plus équilibrés et optimisés pour les étudiants, tout en étant *jusqu'à 100 fois plus rapide* pour générer des horaires que l'algorithme précédent.
- Amélioration de l'interface utilisateur pour la rendre plus conviviale et accessible à tous les étudiants.
- Utilisation d'un framework Rust full stack avec *Leptos*, *Tailwind* et *WebAssembly* pour construire l'application et permettre de générer les horaires localement au lieu de sur le serveur.
],
)
}
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/model/cite.typ | typst | --- cite-footnote ---
Hello @netwok
And again: @netwok
#pagebreak()
#bibliography("/assets/bib/works.bib", style: "chicago-notes")
--- cite-form ---
#set page(width: 200pt)
Nothing: #cite(<arrgh>, form: none)
#cite(<netwok>, form: "prose") say stuff.
#bibliography("/assets/bib/works.bib", style: "apa")
--- cite-group ---
A#[@netwok@arrgh]B \
A@netwok@arrgh B \
A@netwok @arrgh B \
A@netwok @arrgh. B \
A @netwok#[@arrgh]B \
A @netwok@arrgh, B \
A @netwok @arrgh, B \
A @netwok @arrgh. B \
A#[@netwok @arrgh @quark]B. \
A @netwok @arrgh @quark B. \
A @netwok @arrgh @quark, B.
#set text(0pt)
#bibliography("/assets/bib/works.bib", style: "american-physics-society")
--- cite-grouping-and-ordering ---
@mcintosh_anxiety
@psychology25
@netwok
@issue201
@arrgh
@quark
@distress,
@glacier-melt
@issue201
@tolkien54
@sharing
@restful
#show bibliography: none
#bibliography("/assets/bib/works.bib", style: "american-physics-society")
--- issue-785-cite-locate ---
// Test citation in other introspection.
#set page(width: 180pt)
#set heading(numbering: "1.")
#outline(
title: [Figures],
target: figure.where(kind: image),
)
#pagebreak()
= Introduction <intro>
#figure(
rect(height: 10pt),
caption: [A pirate @arrgh in @intro],
)
#context [Citation @distress on page #here().page()]
#show bibliography: none
#bibliography("/assets/bib/works.bib", style: "chicago-notes")
--- issue-1597-cite-footnote ---
// Tests that when a citation footnote is pushed to next page, things still
// work as expected.
#set page(height: 60pt)
A
#footnote[@netwok]
#show bibliography: none
#bibliography("/assets/bib/works.bib")
--- issue-2531-cite-show-set ---
// Test show set rules on citations.
#show cite: set text(red)
A @netwok @arrgh.
B #cite(<netwok>) #cite(<arrgh>).
#show bibliography: none
#bibliography("/assets/bib/works.bib")
--- issue-3481-cite-location ---
// The locator was cloned in the wrong location, leading to inconsistent
// citation group locations in the second footnote attempt.
#set page(height: 60pt)
// First page shouldn't be empty because otherwise we won't skip the first
// region which causes the bug in the first place.
#v(10pt)
// Everything moves to the second page because we want to keep the line and
// its footnotes together.
#footnote[@netwok \ A]
#show bibliography: none
#bibliography("/assets/bib/works.bib")
--- issue-3699-cite-twice-et-al ---
// Citing a second time showed all authors instead of "et al".
@mcintosh_anxiety \
@mcintosh_anxiety
#show bibliography: none
#bibliography("/assets/bib/works.bib", style: "chicago-author-date")
--- cite-type-error-hint ---
// Test hint for cast error from str to label
// Error: 7-15 expected label, found string
// Hint: 7-15 use `<netwok>` or `label("netwok")` to create a label
#cite("netwok")
--- cite-type-error-hint-invalid-literal ---
// Test hint for cast error from str to label
// Error: 7-17 expected label, found string
// Hint: 7-17 use `label("%@&#*!\\")` to create a label
#cite("%@&#*!\\")
|
|
https://github.com/maucejo/presentation_touying | https://raw.githubusercontent.com/maucejo/presentation_touying/main/src/presentation-template.typ | typst | MIT License | #import "@preview/touying:0.5.2": *
#import "_boxes.typ": *
#import "_slides.typ": *
#let presentation-theme(
aspect-ratio: "16-9",
lang: "fr",
navigation: "topbar",
..args,
body
) = {
show: touying-slides.with(
config-info(
title: none,
short-title: none,
author: none,
institution: none,
font: "Lato",
math-font: "Lete Sans Math",
code-font: "DejaVu Sans Mono",
logo: image("resources/assets/logo_cnam_lmssc.png"),
footer-logo: image("resources/assets/lecnam.png"),
title-logo-height: 4em
),
config-colors(
primary: rgb("#c1002a"),
secondary: rgb("#405a68"),
background: rgb("#405a68").lighten(95%),
box: rgb("#405a68"),
info: rgb("#c1002a"),
tip: rgb(31, 136, 61),
important: rgb(9, 105, 218),
question: rgb(130, 80, 223),
),
config-page(
paper: "presentation-" + aspect-ratio,
header-ascent: 30%,
footer-descent: 30%,
margin: (top: 3em, bottom: 1.5em, x: 2em),
),
config-common(
slide-fn: slide,
new-section-slide-fn: new-section-slide,
),
config-methods(
init: (self: none, body) => {
set text(font: self.info.font, size: 20pt, lang: lang, ligatures: false)
show math.equation: set text(font: self.info.math-font)
show raw: set text(font: self.info.code-font)
set par(justify: true)
set list(marker: ([#text(fill:self.colors.primary)[#sym.bullet]], [#text(fill:self.colors.primary)[#sym.triangle.filled.small.r]]))
set enum(numbering: n => text(fill:self.colors.primary)[#n.])
body
}
),
config-store(
align: align,
lang: lang,
navigation: navigation,
mini-slides: (display-section: false, display-subsection: true, short-heading: false),
sec-count: counter("sec-count"),
app-count: counter("app-count"),
),
..args,
)
body
} |
https://github.com/Shedward/dnd-charbook | https://raw.githubusercontent.com/Shedward/dnd-charbook/main/dnd/page/quests.typ | typst | #import "../core/core.typ": *
#let quests = {
let headerCell(colspan: 1, body) = grid.cell(
colspan: colspan,
align: left,
tableHeader(body)
)
let emptyCell = grid.cell([])
let questFrame(fromLines: 2, goalLines: 5, rewardLines: 1) = [
#framed(
fitting: expand-h,
insets: (top: paddings(1), bottom: 0pt, rest: paddings(2))
)[
#grid(
columns: (1fr),
rows: paddings(2),
stroke: innerRowStrokes(),
headerCell[Goal:], emptyCell,
..((emptyCell,) * goalLines),
headerCell[From:],
..((emptyCell,) * fromLines),
headerCell[Reward:], emptyCell,
..((emptyCell,) * rewardLines)
)
]
#place(
top + left,
dx: -paddings(1),
dy: paddings(1.1),
rhombus(
width: paddings(2),
stroke: strokes.normal,
fill: white
),
)
#place(
bottom + left,
dx: -paddings(1.5),
dy: -paddings(4),
rhombus(
width: paddings(3),
stroke: strokes.normal,
fill: white
),
)
]
page(
header: section[Quests]
)[
#grid(
columns: (1fr, 1fr),
rows: 1fr,
stroke: none,
gutter: paddings(2),
..((questFrame(),) * 6),
)
]
}
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/gloss-awe/0.0.3/glossary.typ | typst | Apache License 2.0 | // Copyright 2023 <NAME>, <NAME>
// gls[term]: Marks a term in the document as referenced.
// gls(glossary-term)[term]: Marks a term in the document as referenced with a
// different expression ("glossary-term") in the glossary.
// To ensure that the marked entries are displayed properly, it is also required
// to use a show rule, like the following:
// #show figure.where(kind: "jkrb_glossary"): it => {it.body}
// We use a figure element to store the marked text and an optional
// reference to be used to map to the glossary. If the latter is empty, we use the body
// for the mapping.
#let gls(entry: none, display) = figure(display, caption: entry, numbering: none, kind: "jkrb_glossary")
// Add a keyword to the glossary, even if it is not in the documents content.
#let gls-add(entry) = figure([], caption: entry, numbering: none, kind: "jkrb_glossary")
// This function creates a glossary page with entries for every term
// in the document marked with `gls[term]`.
#let make-glossary(
// Indicate missing entries.
missing: text(fill: red, weight: "bold")[ No glossary entry ],
// Function to format the Header of the entry.
heading: it => { heading(level: 2, numbering: none, outlined: false, it)},
// The glossary data.
..glossaries
) = {
let figure-title(figure) = {
let ct = ""
if figure.caption == none {
if figure.body.has("text") {
ct = figure.body.text
}
else {
for cc in figure.body.children {
if cc.has("text") {
ct += cc.text
}
}
}
}
else{
ct = figure.caption.text
}
return ct
}
let lookup(key, glossaries) = {
let entry = none
for glossary in glossaries.pos() {
if glossary.keys().contains(key) {
let entry = glossary.at(key)
return entry
}
}
return entry
}
locate(loc => {
let words = () //empty array
let elements = query(figure.where(kind: "jkrb_glossary"), loc)
let titles = elements.map(e => figure-title(e)).sorted()
for t in titles {
if words.contains(t) { continue }
words.push(t)
heading(t)
let e = lookup(t, glossaries)
if e != none {
e.description
if e.keys().contains("link") {
e.link
}
} else {
missing
}
}
})
}
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/link-04.typ | typst | Other | // Verify that opening brackets without closing brackets throw an error.
// Error: 22-22 expected closing bracket in link
https://exam(ple.com/
|
https://github.com/OriginCode/typst-homework-template | https://raw.githubusercontent.com/OriginCode/typst-homework-template/master/template.typ | typst | #let project(title: "", authors: (), show_info: true, body) = {
// Set the document's basic properties.
set document(author: authors, title: title)
set page(paper: "us-letter")
set text(11pt, font: "New Computer Modern", lang: "en")
show raw: text.with(font: "Iosevka")
if show_info {
// Title row.
align(center)[
#block(text(weight: 700, 1.75em, title))
]
// Author information.
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, strong(author))),
),
)
}
// Main body.
set par(justify: true)
body
}
#let question_counter = counter("question_counter")
#let part_counter = counter("part_counter")
#let disp_question_counter = false
#let question(title, body) = {
question_counter.step()
// Title bar
move(dy: .4em, line(length: 100%))
show: text.with(weight: "bold")
if disp_question_counter [#question_counter.display("1. ")]
title
move(dy: -.4em, line(length: 100%))
show: text.with(weight: "regular")
body
part_counter.update(0)
pagebreak(weak: true)
}
#let part(body) = {
part_counter.step()
block[#{
show: text.with(weight: "bold")
part_counter.display("(a)")
show: text.with(weight: "regular")
body
}]
}
#let indented(body) = pad(
left: .2in,
body,
)
|
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Home.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Home",
authors: (
"<NAME>",
),
date: "30 Octobre, 2023",
)
#set heading(numbering: "1.1.")
= Home
<home>
== Links
<links>
#link("Maths.pdf")[Maths] #link("Francais.pdf")[Français]
|
|
https://github.com/LDemetrios/Conspects-4sem | https://raw.githubusercontent.com/LDemetrios/Conspects-4sem/master/README.md | markdown | # Conspects 4 semester
Здесь располагается честная попытка автора репозитория ~~начать учиться~~ вести конспект.
Речь идёт о четвёртом семестре КТ ИТМО, следующих курсах:
- Технологии программирования, оно же Java Advanced
- Программирование на видеокартах
- Что-нибудь ещё, если захочется...
###
Устройство репозитория
- Некоторое место занимают файлы gradle. Так надо, для одновременной компиляции всего во всех вариантах
- Стили для всего конспекта (пока что только `header.typ`).
- `mode.txt` для общения gradle с документом.
- Собственно исходники конспектов в sources
- Скомпилированные конспекты в нескольких темах:
- dev -- Белый на чёрном
- dark -- Светлый на тёмном
- sepia -- Чёрный на тёплом светлом
- regular -- Чёрный на белом
- print -- Вариант для печати (оттенки серого даже в рисунках, длина страницы А4)
-- соответственно, в output/<соответствующий вариант>.
### Как это собирать локально
Для этого в системе должен быть установлен typst. Соответственно, можно запустить сборку через
```
./gradlew typst-compile
```
Как это работает? Не спрашивайте, сэр Генри, не спрашивайте.
Сначала для каждого исходникак через typst query получаем список возможных режимов (записанных в `#metadata(modes.keys()) #label("available-modes")`), потом по очереди пишем имя режима в mode.txt и компилируем в соответствующую папку. В пределах этого проекта этот список постоянен (см. выше), но в принципе работать будет и по-другому. Feel free утащить в свой проект, когда-нибудь у меня руки дойдут запилить gradle plugin... Да...
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-11600.typ | typst | Apache License 2.0 | #let data = (
("MODI LETTER A", "Lo", 0),
("MODI LETTER AA", "Lo", 0),
("MODI LETTER I", "Lo", 0),
("MODI LETTER II", "Lo", 0),
("MODI LETTER U", "Lo", 0),
("MODI LETTER UU", "Lo", 0),
("MODI LETTER VOCALIC R", "Lo", 0),
("MODI LETTER VOCALIC RR", "Lo", 0),
("MODI LETTER VOCALIC L", "Lo", 0),
("MODI LETTER VOCALIC LL", "Lo", 0),
("MODI LETTER E", "Lo", 0),
("MODI LETTER AI", "Lo", 0),
("MODI LETTER O", "Lo", 0),
("MODI LETTER AU", "Lo", 0),
("MODI LETTER KA", "Lo", 0),
("MODI LETTER KHA", "Lo", 0),
("MODI LETTER GA", "Lo", 0),
("MODI LETTER GHA", "Lo", 0),
("MODI LETTER NGA", "Lo", 0),
("MODI LETTER CA", "Lo", 0),
("MODI LETTER CHA", "Lo", 0),
("MODI LETTER JA", "Lo", 0),
("MODI LETTER JHA", "Lo", 0),
("MODI LETTER NYA", "Lo", 0),
("MODI LETTER TTA", "Lo", 0),
("MODI LETTER TTHA", "Lo", 0),
("MODI LETTER DDA", "Lo", 0),
("MODI LETTER DDHA", "Lo", 0),
("MODI LETTER NNA", "Lo", 0),
("MODI LETTER TA", "Lo", 0),
("MODI LETTER THA", "Lo", 0),
("MODI LETTER DA", "Lo", 0),
("MODI LETTER DHA", "Lo", 0),
("MODI LETTER NA", "Lo", 0),
("MODI LETTER PA", "Lo", 0),
("MODI LETTER PHA", "Lo", 0),
("MODI LETTER BA", "Lo", 0),
("MODI LETTER BHA", "Lo", 0),
("MODI LETTER MA", "Lo", 0),
("MODI LETTER YA", "Lo", 0),
("MODI LETTER RA", "Lo", 0),
("MODI LETTER LA", "Lo", 0),
("MODI LETTER VA", "Lo", 0),
("MODI LETTER SHA", "Lo", 0),
("MODI LETTER SSA", "Lo", 0),
("MODI LETTER SA", "Lo", 0),
("MODI LETTER HA", "Lo", 0),
("MODI LETTER LLA", "Lo", 0),
("MODI VOWEL SIGN AA", "Mc", 0),
("MODI VOWEL SIGN I", "Mc", 0),
("MODI VOWEL SIGN II", "Mc", 0),
("MODI VOWEL SIGN U", "Mn", 0),
("MODI VOWEL SIGN UU", "Mn", 0),
("MODI VOWEL SIGN VOCALIC R", "Mn", 0),
("MODI VOWEL SIGN VOCALIC RR", "Mn", 0),
("MODI VOWEL SIGN VOCALIC L", "Mn", 0),
("MODI VOWEL SIGN VOCALIC LL", "Mn", 0),
("MODI VOWEL SIGN E", "Mn", 0),
("MODI VOWEL SIGN AI", "Mn", 0),
("MODI VOWEL SIGN O", "Mc", 0),
("MODI VOWEL SIGN AU", "Mc", 0),
("MODI SIGN ANUSVARA", "Mn", 0),
("MODI SIGN VISARGA", "Mc", 0),
("MODI SIGN VIRAMA", "Mn", 9),
("MODI SIGN ARDHACANDRA", "Mn", 0),
("MODI DANDA", "Po", 0),
("MODI DOUBLE DANDA", "Po", 0),
("MODI ABBREVIATION SIGN", "Po", 0),
("MODI SIGN HUVA", "Lo", 0),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
("MODI DIGIT ZERO", "Nd", 0),
("MODI DIGIT ONE", "Nd", 0),
("MODI DIGIT TWO", "Nd", 0),
("MODI DIGIT THREE", "Nd", 0),
("MODI DIGIT FOUR", "Nd", 0),
("MODI DIGIT FIVE", "Nd", 0),
("MODI DIGIT SIX", "Nd", 0),
("MODI DIGIT SEVEN", "Nd", 0),
("MODI DIGIT EIGHT", "Nd", 0),
("MODI DIGIT NINE", "Nd", 0),
)
|
https://github.com/marcantoinem/CV | https://raw.githubusercontent.com/marcantoinem/CV/main/fr/work-experience.typ | typst | #import "../src/style.typ": experience
#let nuvu = {
experience(
"Nuvu Cameras",
"Montréal, Canada",
"Mai 2024 - Août 2024",
"Stagiaire en développement électronique embarqué",
[
- Développement de bancs d'essai avec VUnit pour plus de *30 000 lignes* de code VHDL afin d'assurer le bon fonctionnement du FPGA de la nouvelle génération de caméras.
- Mise en place d'une pipeline CI/CD complète sur Jenkins pour automatiser les tests du FPGA et garantir la qualité du code.
- Couverture de *95%* de la base de code avec des bancs d'essai pour assurer la fiabilité du code et détecter de nombreux bugs avant qu'ils n'atteignent le matériel.
- Développement d'un contrôleur RAM AXI4 en VHDL pour interfacer le FPGA de Microchip avec la RAM DDR3 et DDR4, atteignant un débit de plus de *48 Gb/s* pour écrire un tampon circulaire d'images prises par la caméra.
],
)
}
#let charge = {
experience(
"Polytechnique Montréal",
"Montréal, Canada",
"Août 2024 - Présent",
"Chargé de laboratoire",
[
- Donner les laboratoires des cours programmation orientée objet (*INF1010*) et conception et réalisation de systèmes numériques (*INF3500*)
- Fournir un soutien technique et des conseils aux étudiants pour favoriser la compréhension du matériel du cours.
- Évaluer les devoirs, offrir des commentaires détaillés.
],
)
}
#let repetition = {
experience(
"Polytechnique Montréal",
"Montréal, Canada",
"Août 2023 - Présent",
"Répétiteur",
[
- Donner une répétition dans les cours suivants : *INF1005D*, *INF1015*, *INF1900*, *INF2610*
- Répondre aux questions des étudiants durant les laboratoires
- Résoudre divers problèmes logiciels et matériels
],
)
}
#let lainco = {
experience(
"Lainco",
"Terrebonne, Canada",
"Mai 2023 - Août 2023",
"Développeur logiciel stagiaire",
[
- Production de scripts puissants et conviviaux pour automatiser le placement des poutres en acier dans un logiciel CAD, suivant automatiquement les spécifications de l'ingénieur mécanique et permettant d'économiser jusqu'à *plusieurs semaines* de travail répétitif pour le concepteur CAD sur plusieurs projets.
- Réécriture intégrale d'une base de code héritée de Python2 à Python3 pour améliorer la maintenabilité et la lisibilité.
- Construction d'un estimateur d'efficacité de placement d'acier en *Rust* pour réduire la perte d'acier de *15%*.
],
)
}
|
|
https://github.com/liuguangxi/suiji | https://raw.githubusercontent.com/liuguangxi/suiji/main/src/lib.typ | typst | MIT License | #import "random.typ": gen-rng, integers, random, uniform, normal, discrete-preproc, discrete, shuffle, choice
#import "random-fast.typ": gen-rng-f, randi-f, integers-f, random-f, uniform-f, normal-f, discrete-preproc-f, discrete-f, shuffle-f, choice-f
#import "chinese.typ": rand-sc
|
https://github.com/mariunaise/HDA-Thesis | https://raw.githubusercontent.com/mariunaise/HDA-Thesis/master/graphics/quantizers/s-metric/s-metric-compar1.typ | typst | #import "@preview/cetz:0.2.2": canvas, plot, draw
#let line_style = (stroke: (paint: black, thickness: 2pt))
#let dashed = (stroke: (dash: "dashed"))
#let fill_aqua = (stroke: none, fill: teal)
#let fill_olive = (stroke: none, fill: maroon)
#canvas({
plot.plot(size: (7,3),
legend: "legend.south",
legend-style: (orientation: ltr, item: (spacing: 0.5)),
x-tick-step: none,
x-ticks: ((-1.25, [-a]), (1.25, [a]), (0, [0])),
y-label: $cal(E)(1, 2, x)$,
x-label: $x$,
y-tick-step: none,
y-ticks: ((0, [0]), (1, [1])),
axis-style: "left",
x-min: -3,
x-max: 3,
y-min: 0,
y-max: 1,{
plot.add(((-3,0), (-1.25,0), (-1.25,1), (1.25,1), (1.25, 0), (3, 0)), line: "vh", style: line_style)
plot.add-hline(1, style: dashed)
})
})
|
|
https://github.com/GYPpro/Java-coures-report | https://raw.githubusercontent.com/GYPpro/Java-coures-report/main/.VSCodeCounter/2023-12-14_20-30-42/results.md | markdown | # Summary
Date : 2023-12-14 20:30:42
Directory d:\\Desktop\\Document\\Coding\\JAVA\\Rep\\Java-coures-report
Total : 35 files, 2294 codes, 87 comments, 428 blanks, all 2809 lines
Summary / [Details](details.md) / [Diff Summary](diff.md) / [Diff Details](diff-details.md)
## Languages
| language | files | code | comment | blank | total |
| :--- | ---: | ---: | ---: | ---: | ---: |
| Java | 33 | 2,115 | 85 | 387 | 2,587 |
| Typst | 1 | 178 | 2 | 39 | 219 |
| Markdown | 1 | 1 | 0 | 2 | 3 |
## Directories
| path | files | code | comment | blank | total |
| :--- | ---: | ---: | ---: | ---: | ---: |
| . | 35 | 2,294 | 87 | 428 | 2,809 |
| . (Files) | 3 | 235 | 9 | 56 | 300 |
| rubbish | 1 | 73 | 0 | 15 | 88 |
| sis1 | 1 | 26 | 0 | 3 | 29 |
| sis2 | 2 | 192 | 15 | 22 | 229 |
| sis3 | 2 | 63 | 5 | 11 | 79 |
| sis4 | 1 | 34 | 0 | 3 | 37 |
| sis5 | 5 | 501 | 31 | 81 | 613 |
| sis6 | 2 | 124 | 8 | 19 | 151 |
| sis7 | 3 | 261 | 1 | 35 | 297 |
| sis8 | 10 | 435 | 18 | 120 | 573 |
| sis9 | 5 | 350 | 0 | 63 | 413 |
Summary / [Details](details.md) / [Diff Summary](diff.md) / [Diff Details](diff-details.md) |
|
https://github.com/zenor0/FZU-report-typst-template | https://raw.githubusercontent.com/zenor0/FZU-report-typst-template/main/fzu-report/parts/main-body-report-fn.typ | typst | MIT License | #import "../utils/states.typ": part-state
#import "../utils/fonts.typ": 字体, 字号
#let main-body-report-conf(doc, enable-header: false, header: "福州大学课程报告") = {
set page(
header: {
set align(center)
set text(font: 字体.宋体, size: 字号.小五, lang: "zh")
set par(first-line-indent: 0pt, leading: 16pt, justify: true)
show par: set block(spacing: 16pt)
[#header]
v(-12pt)
line(length: 100%, stroke: (thickness: 0.5pt))
counter(footnote).update(0)
},
) if enable-header
set page(
numbering: "1",
header-ascent: 10%,
footer-descent: 10%
)
// indent list
set enum(indent: 1em)
set list(indent: 1em)
show raw.where(block: false): it => box(
inset: (x:3pt),
box(
fill: luma(240),
inset: (x: 2pt),
outset: (y: 3pt),
radius: 3pt
)[#text(size: 10pt)[#it]])
show raw: set text(font: 字体.代码, size: 10pt)
pagebreak(weak: false)
counter(page).update(1)
counter(heading.where(level: 1)).update(0)
doc
} |
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/meta-environments/imports-class_handouts.typ | typst |
#import "/meta-environments/env-templates.typ": *
#import "@preview/gloss-awe:0.1.5": * |
|
https://github.com/liuguangxi/fractusist | https://raw.githubusercontent.com/liuguangxi/fractusist/main/tests/test-sierpinski-curve.typ | typst | MIT License | #set document(date: none)
#import "/src/lib.typ": *
#set page(margin: 1cm)
= n = 1
#align(center)[
#sierpinski-curve(1, step-size: 40)
]
= n = 2
#align(center)[
#sierpinski-curve(2, step-size: 20, fill-style: gray, stroke-style: none)
]
= n = 3
#align(center)[
#sierpinski-curve(3, step-size: 10, fill-style: silver, stroke-style: stroke(paint: orange, thickness: 3pt, cap: "round", join: "round"))
]
#pagebreak(weak: true)
= n = 4
#align(center)[
#sierpinski-curve(4, step-size: 6, fill-style: gradient.radial((orange, 0%), (silver, 100%), focal-center: (30%, 30%)), stroke-style: stroke(paint: gradient.linear(..color.map.crest, angle: 45deg), thickness: 2pt))
]
= n = 5
#align(center)[
#sierpinski-curve(5, step-size: 4, fill-style: gradient.linear(..color.map.crest, angle: 45deg), stroke-style: none)
]
#pagebreak(weak: true)
|
https://github.com/zjutjh/zjut-report-typst | https://raw.githubusercontent.com/zjutjh/zjut-report-typst/main/template/utils.typ | typst | #import "fonts.typ":*
#let date_format(
date: (2023,5,14)
) = {
set text(font: font_style.songti, size: font_size.四号);
[#date.at(0) 年 #date.at(1) 月 #date.at(2) 日]
}
#let toc() = {
align(center)[
#text(font: font_style.heiti, size: 18pt, "目 录")
]
parbreak()
set text(font: font_style.heiti, size: 12pt)
set par(first-line-indent: 0pt)
show outline: it => {
set text(font: font_style.heiti, size: 12pt)
it
parbreak()
}
outline(
title: none,
indent: true,
)
}
|
|
https://github.com/cu1ch3n/menu | https://raw.githubusercontent.com/cu1ch3n/menu/main/README.md | markdown | > **This repository will stop updating and be archived.**
>
> I probably won't be interested in cooking in the near future, even though I recently moved into an new apartment with a great kitchen and was hoping to make some food vlogs. I have forever lost the girl who taught me how to cook, tasted every dish on the menu, and would smile and praise my cooking.
>
> I guess I'll just continue ordering takeout.
# 🍔 Chen’s Private Cuisine
I've recently developed a passion for cooking, so I've been organizing and updating my menu using Typst (just for fun). The resulting menu.pdf file is available at https://files.cuichen.cc/menu.pdf.

## Scan the QR Code to Get the Latest Menu

|
|
https://github.com/extua/october | https://raw.githubusercontent.com/extua/october/main/template/main.typ | typst | MIT No Attribution | #import "@preview/october:1.0.0": calendar
#set page(
"a4",
flipped: true,
)
#show: calendar.with(
year: datetime.today().year(),
)
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/数学模型/main.typ | typst | #import "../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark, der, partialDer, inner, fourierTrans
#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: "数学模型",
author: "YHTQ",
date: none,
logo: none,
)
#let vol = $"vol"$
= 前言
- 教师:邵嗣烘
- 没有教材,每次具体留作业
主要涉及的数学模型:
+ 图模型
+ 0-1表示模型
+ 图灵机模型
+ 微分方程模型
+ 随机模型
= 图模型
#definition[图][
图是由顶点集合和边集合组成的一个二元组$G=(V,E)$,其中$V$是顶点集合,$E$是边集合。
]
#definition[图割问题][
考虑简单无向图 $G$,任给 $V$ 的两个不相交子集 $A, B$,定义之间的割值为:
$
"cut"(A, B) = sum_(a in A, b in B) w(a, b)
$
约定:
$
"cut"(A) = "cut"(A, V-A)\
vol(A) = sum_(a in A) d(a)
$
经典的四类图割问题:
- 最小割问题
$
h_(min) := min "cut"(A)/(1/2 vol(V))
$
- 最大割问题
$
h_(max) := max "cut"(A)/(1/2 vol(V))
$
- cheeger 问题(均匀最小割)
$
h := min "cut"(A) / min("vol"(A), vol(V-A))
$
- 反 cheeger 问题
$
h_("anti") := max "cut"(A) / max("vol"(A), vol(V-A))
$
上述四个问题中,最小割问题有多项式时间算法,其余三个问题都是 NP 完全的。
]
#example[][
例如并行计算中,我们可以将任务抽象为图,节点表示任务计算量,边表示数据依赖关系和通信量。假如我们有 $k$ 个对等的机器,我们希望将任务分配到机器上,使得每台机器的计算量尽量均衡,同时尽量减少机器之间的通信量。这就是一个图割问题。
]
== cheeger 问题的估计
#definition[指示向量][
对于图 $G$ 和集合 $A$,定义:
$
x_i = cases(
1\, quad i in A,
-1\, quad i not in A
)
$
]
#theorem[][
- $"cut"(A) = sum_({i, j} in E(A, V - A)) w(i, j) = sum_({i, j} in E) |x_i - x_j| = sum_({i, j} in E) (x_i - x_j)^2$
- $"vol"(A) = sum_(i in V) d_i x_i = sum_(i in V) d_i x_i^2$
- $"vol"(V - A) = sum_(i in V) d_i (1 - x_i)^2$
-
$
min("vol"(A), vol(V - A)) = min_(c in {0, 1}) sum_(i in V) d_i (x_i - c)^2
$
]
任取图的一个定向,定义关联矩阵 $B$,我们发现:
$
sum_({i, j} in E) (x_i - x_j)^2 = norm(B x) = x^T B^T B x
$
#definition[组合 Laplace 矩阵][
称 $L = B^T B = D - W$ 为图 $G$ 的组合 Laplace 矩阵,其中 $D$ 为图的度矩阵,$W$ 为图的邻接矩阵。
]
至此,我们将所有式子化成了实解析的形式。接下来只需要将 $c, x$ 看成 $RR$ 上变元就可以得到估计。通过一些拉格朗日乘子法,我们可以得到:
$
min (x^T L x)/(x^T D x)\
"with" x dot (D arrow(1)) = 0
$
其中 $L$ 是拉普拉斯矩阵,$D = "diag"(d_1, d_2, ..., d_n)$ 为每个顶点的度 。
- 先解决前者。这个形式也被称为广义特征值问题。\
该问题可以化为标准的特征值问题,事实上由于 $D$ 是正定的对角矩阵,可取 $D = C^2$,并利用拉格朗日乘子法,问题化为:
$
L v = lambda C^2 v\
Inv(C) L v = lambda (C v)\
(Inv(C) L Inv(C)) v = lambda v
$
($lambda$ 是拉格朗日乘子,可以计算得到它也是上面最优化问题的最优值)\
这是标准的特征值问题,且 $Inv(C) L Inv(C)$ 是实对称矩阵,故其特征值都是实数,且在记重数的情况下恰有 $n$ 个。\
这里注意到了 $L = B^T B$ 是半正定矩阵,$Inv(C) L Inv(C)$ 合同于 $L$,故这些特征值都是非负数。\
我们将特征值从小到大排列得到 $lambda_1 <= lambda_2 <= ... <= lambda_n$\
此外,可以计算得到 $L arrow(1) = 0$,因此 $L$ 有广义特征值 $0$
- 对于后者,我们发现 $D arrow(1)$ 事实上刚好是 $0$ 所对应的特征向量,因此只是在说不考虑该特征值/特征向量(注意特征向量都正交)
综合而言,我们发现第二特征值 $lambda_2$ 就是我们给出的 $h$ 的估计。注意到当 $lambda_2$ 非零时,它就是最小特征值,是很容易计算的。接下来我们需要估计 $lambda_2$ 与实际 $h$ 的差距。
=== $lambda_2$ 与 $h$
假设 $A$ 是一个取得 $h$ 的图割,也就是:
$
h(G) = "cut"(A)/(min("vol"(A), vol(V-A)))
$
令指示向量
$
y_i = cases(
1 / (vol A)\, quad i in A,
-1 / (vol (V-A))\, quad i not in A
)
$我们试图反过来去计算 $lambda_2$,断言:
- $y dot D arrow(1) = 0$\
验证:
$
sum_(i in V) d_i y_i = sum_(i in A) d_i / ("vol"A) - sum_(i in V-A) d_i / ("vol"(V-A)) = 0
$
因此由定义,当然有
$
lambda_2 <= (y^T L y)/(y^T D y) = (sum_(i, j in E) (y_i - y_j)^2)/(sum_(i in V) d_i y_i^2)\
= "cut"(A)(1/("vol"A) + 1/("vol"(V-A))) \
<= 2 h(G)
$
#theorem[Cheeger][
$lambda_2/2 <= h(G)$
]
至此,我们给出了 $h(G)$ 的上界。自然的,我们要思考是否可以给出上界。
对于任意的 $y in RR^n$,定义:
$
R(y) = (y^T L y)/(y^T D y)
$
称为 $y$ 的 Rayleigh 商。由于 $y$ 是任取的,因此通过估计 $R(y)$,可以得到 $h(G)$ 的一个上界。
#lemma[][
$forall y in RR^n$,存在 $V$ 的非空子集 $S$ 使得:
$
"cut"(S)/("vol"(S)) <= sqrt(2 R(y))
$
且:
$
S subset V_1 (y) = {i in V | y_i != 0}
$
]
#proof[
注意到 $R(y)$ 关于 $y$ 齐次,因此不妨设 $y in [-1, 1]^n$\
我们的目标是将不是两值向量的向量取整,称为 Rounding\
取 $t ~ U(0, 1)$ 也就是服从 $(0, 1)$ 上随机分布的数\
令:
$
S_t = {i in V | y_i^2 >= t}
$
我们的目标是:
$
E ("cut"(S_t) - sqrt(2 R(y)) "vol"(S_t)) <= 0
$
- 先计算第一个期望
$
E("cut" S_t) = integral_0^1 "cut"(S_t) dif t = integral_0^1 sum_({i, j} in E) i_A (t) dif t
$
其中 $i_(A_(i j)) (t)$ 是 $A_(i j) = {t in [0, 1] | y_i^2 <=t < y_j^2 or y_j^2 <= t < y_i^2}$ 的特征函数\
上式等于:
$
sum_({i, j} in E) integral_0^1 i_(A_(i j)) (t) dif t\
= sum_({i, j} in E) |y_j^2 - y_i^2| \
= sum_({i, j} in E) |(y_j - y_i)(y_j+y_i)|\
<= sqrt( sum_({i, j} in E) (y_j - y_i)^2) sqrt(sum_({i, j} in E) (y_j + y_i)^2)("柯西-施瓦兹不等式")\
<= sqrt( sum_({i, j} in E) (y_j - y_i)^2) sqrt(sum_({i, j} in E) 2(y_i^2 + y_j^2))\
= sqrt( sum_({i, j} in E) (y_j - y_i)^2) sqrt(sum_(i in V) 2 d_i y_i^2)\
= sqrt(2 R(y)) (sum_(i in V) d_i y_i^2)
$
- 再计算第二个期望
$
E(vol(S_t)) = integral_0^1 vol(S_t) dif t = integral_0^1 sum_(i in V) i_(B_i) (t) d_i dif t\
= sum_(i in V) d_i integral_0^1 i_(B_i) (t) dif t\
= sum_(i in V) d_i y_i^2 dif t\
$
其中 $B_i = {t in [0, 1] | t <= y_i^2}$
两式合并不难发现原结论成立
]
#theorem[Cheeger][
$h(G) <= sqrt(2 lambda_2)$
]
为了证明这个结论,设 $x$ 是 $lambda_2$ 对应的广义特征向量。为了实现估计,我们当然希望 $x$ 是两值的向量,但是实际上往往与两值向量相去甚远。为此,我们尝试取得 $c in RR$ 以此作为对实向量两值化的阈值。同时为了使得分母的 $min("vol"(A), "vol"(V - A))$ 便于计算,我们希望:
$
"vol"{i in V | x_i < C} <= 1/2 "vol"(V)\
"vol"{i in V | x_i > C} <= 1/2 "vol"(V)
$
事实上,我们不妨设 $x_i$ 从小到大排列,考虑:
$
sum_(i=1)^k d_i, forall k = 1, 2, ..., n
$
只需找到一个 $k$ 使得:
$
sum_(i=1)^k d_i <= 1/2 "vol"(V)\
sum_(i=1)^(k+1) d_i >= 1/2 "vol"(V)
$
取 $C = x_(k+1)$ 即可,某种意义上只是在取中位数。我们把所有这样的取值集合称为 $"median"(x)$
#proof[
设 $x$ 是 $lambda_2$ 所对应的特征向量,取 $c in "median"(x)$,进而有:
$
vol{i in V | x_i < c} <= 1/2 vol(V)\
vol{i in V | x_i > c} <= 1/2 vol(V)
$
令 $y = x - c dot 1$,断言:
- $y^t L y = x^t L x$(平移不变性)
- $y^T D y >= x^T D x$
$
y^T D y = x^T D x - 2 c 1^T D x + c^2 1^T D 1
$
注意到 $x dot (D 1) = 0$(这是之前的约束条件),因此该结论成立
进而有:
$
lambda_2 = (x^T L x)/(x^T D x) >= (y^T L y)/(y^T D y)\
= (y^T L y)/(y^T_+ D y_+ + y^T_- D y_-)\
>= (y^T_+ L y_+ + y^T_- L y_-)/(y^T_+ D y_+ + y^T_- D y_-) (y^T_+ L y_- <= 0)\
>= min {(y^T_+ L y_+)/(y^T_+ D y_+), (y^T_- L y_-)/(y^T_- D y_-)}
$
由引理,将有:
$
sqrt(2 R_(y_+)) >= ("cut" S)/(vol S) = ("cut" S)/(min {vol(S), vol(V - S)}) >= h(G)
$
进而连上之前的不等式,结果成立
]
#remark[][
尽管我们做出了很大的努力,实际尝试就会发现我们给出的上下界是非常宽松的(尽管确实是紧的)。一大问题在于我们将连续的向量二值化的过程中产生了严重的损失,调整取整方法或许能一定情况下改善这一点。
]
=== 另一条道路 $mu_2$
$
h = min "cut"(A) / min("vol"(A), vol(V-A))\
= min_(x in {0, 1}^n) (sum_((i, j) in E) |x_i - x_j|)/min("vol"(A), vol(V-A))\
= min_(x in {0, 1}^n) (sum_((i, j) in E) |x_i - x_j|)/(min_(c in {0, 1}) sum_(i in V) d_i |x_i - c|)\
$
我们尝试另一条道路,不用二次型将上式光滑化,而是保持绝对值,将取值范围放松。我们将会惊喜地得到以下结果
#lemma[][
$
N(x) = min_(c in RR) sum_(i in V) d_i |x_i - c| := min_(c in RR) g(c_i, x)
$
在 $c^*$ 取最小值的当且仅当 $c^* in "median"(x)$
]<median-min>
#theorem[][
设:
$
h' = min_(x in RR^n)(sum_((i, j) in E) |x_i - x_j|)/(min_(c in RR) sum_(i in V) d_i |x_i - c|)
$
则 $h' = h$
]
#proof[
记 $I(x) = sum_((i, j) in E) |x_i - x_j|, N(x) = min_(c in RR) sum_(i in V) d_i |x_i - c|$\
由引理,我们仿照之前的操作进行 $c$ 平移,结合平移不变性,原式化为:
$
min_(0 in "median"(x)) I(x)/(norm(x)_d)
$
注意到上式也是齐次式,因此令 $S = {x in RR^n | norm(x)_d = 1}, pi = {x in S | 0 in "median"(x)}$,上式等于:
$
min_(x in pi) I(x)
$
设 $A$ 是取得 $h$ 的最小割,我们计算 $A$ 上的 $h'$\
令
$
y_i = cases(
1 / (vol A) quad i in A,
-1 / (vol (V-A)) quad i in.not A
)
$
显然 $h' <= I(y)/N(y)$,仿照之前的计算得:
$
I(x) = "cut"(A)(1/(vol A) + 1/(vol (V-A)))\
N(x) = min {sum_(i in A) d_i (1/(vol A) + 1/(vol(V - A))), sum_(i in V-A) d_i (1/(vol A) + 1/(vol(V - A)))}
$
其中第二式利用了 $N(x)$ 的形式是关于 $c$ 的一元折线函数的和的最小值,取值点恰在在 $"median"(x)$ 之中,而此时 $x$ 只有两值,当然应该是两者之一\
计算得 $h' <= ("cut"(A))/(min {vol(A), vol(V - A)}) = h$
现在考虑另一个方向,我们希望得到 $h <= h'$,我们希望仿照 Cheeger 不等式的另一侧
#lemma[][
任取 $x in RR^n$,存在一个 $S subset U_plus.minus (x)$,使得:
$
("cut"(S))/("vol"(S)) <= I(x)/N(x)
$
]
#proof[
任意取定 $x in RR^n$,不妨设 $x_i in [-1, 1]^n$ \
对于某个阈值 $t in RR$,令:
$
S_t = {i in V | abs(x_i) > t} subset U_plus.minus (x)
$
显然 $S_0 = U_plus.minus (x), S_1 = emptyset$\
只需证明:
$
exists t in [0, 1], N(x) "cut" S_t <= I(x) "vol"(x)
$
为此,我们证明:
$
E (N(x) "cut" S_t - I(x) "vol"(x)) <= 0
$<target>
足以说明原式
- 先计算 $E ("cut" S_t)$,有:
$
E ("cut" S_t) &= E (sum_({i, j} in E) abs(1^t_i - 1^t_j)) "(其中" 1^t "是" S_t "的指示向量)" \
&= sum_({i, j} in E) E (abs(1^t_i - 1^t_j)) \
&= sum_({i, j} in E) E (1^t_i - 1^t_j | 1^t_i > 1^t_j) P(1^t_i > 1^t_j) + E (1^t_j - 1^t_i | 1^t_i < 1^t_j) P(1^t_i < 1^t_j) \
&= sum_({i, j} in E) E (1^t_i - 1^t_j | 1^t_i > 1^t_j) P(1^t_i > 1^t_j) + E (1^t_j - 1^t_i | 1^t_i < 1^t_j) P(1^t_i < 1^t_j) \
$
注意到 $P(1^t_i > 1^t_j), P(1^t_i < 1^t_j)$ 由 $abs(x_i), abs(x_j)$ 的大小关系决定,且两者至多一个不是零
- 当 $abs(x_i) = abs(x_j)$ 时,两者同时为零
- 当 $abs(x_i) < abs(x_j)$ 时,有:
$
&E (1^t_i - 1^t_j | 1^t_i > 1^t_j) P(1^t_i > 1^t_j) + E (1^t_j - 1^t_i | 1^t_i < 1^t_j) P(1^t_i < 1^t_j) \
=& E (1^t_j - 1^t_i | 1^t_i < 1^t_j) P(1^t_i < 1^t_j)\
=& 1 dot (abs(x_j) - abs(x_i))\
=& abs(x_j) - abs(x_i)
$
- 类似的,若 $abs(x_i) > abs(x_j)$,则原式等于 $abs(x_i) - abs(x_j)$
综上,有:
$
&sum_({i, j} in E) E (1^t_i - 1^t_j | 1^t_i > 1^t_j) P(1^t_i > 1^t_j) + E (1^t_j - 1^t_i | 1^t_i < 1^t_j) P(1^t_i < 1^t_j)\
&= sum_({i, j} in E) abs(abs(x_i) - abs(x_j))
$
- 再计算 $E ("vol"(x))$,有:
$
E ("vol"(x)) = E(sum_(i in V) d_i 1^t_i) = sum_(i in V) d_i E (1^t_i) = sum_(i in V) d_i P(abs(x_i) > t) = sum_(i in V) d_i abs(x_i)
$
综上,有:
$
E (N(x) "cut" S_t) = (min_(c in RR) sum_(i in V) d_i abs(x_i - c)) (sum_({i, j} in E) abs(abs(x_i) - abs(x_j)))\
E (I(x) "vol"(x)) = (sum_(i in V) d_i abs(x_i)) (sum_({i, j} in E) abs(x_i - x_j))
$
显然有:
$
0 <= min_(c in RR) sum_(i in V) d_i abs(x_i - c) <= sum_(i in V) d_i abs(x_i)\
0 <= sum_({i, j} in E) abs(abs(x_i) - abs(x_j)) <= sum_({i, j} in E) abs(x_i - x_j)
$
因此@target 成立!
]
#let h1 = $h'$
回到目标,设 $x_0$ 可使 $h1$ 取最小的的 $x$,不妨设 $x in [-1, 1]^n$。\
注意到:
$
I(x)/N(x) = (sum_({i, j} in E) abs(x_i - x_j)) / (min_(c in RR) sum_(i in V) d_i abs(x_i - c) )
$
上下齐次且分子分母都在平移下保持不变,因此可设 $x in [0,1]^n$\
取 $c in "median"_d (x)$,将有:
$
"vol"({i in V | x_i < c}) <= 1/2 "vol"(V)\
"vol"({i in V | x_i >= c}) <= 1/2 "vol"(V)
$
并设:
$
y = x - c
$
我们的目标是:
$
h1(x) = h1(y) = I(y)/N(y) = (I(y^+) + I(y^-))/(N(y^+) + N(y^-)) >= min(I(y^+)/N(y^+), I(y^-)/N(y^-)) >= h(G)
$
其中仅有第三个等号:
$
I(y)/N(y) = (I(y^+) + I(y^-))/(N(y^+) + N(y^-))
$
并不平凡,我们需要证明:
- $I(y) = I(y^+) + I(y^-)$
我们只需要逐项验证:
- $x_i x_j >= 0$ 时,$abs(x_i - x_j)$ 恰为 $abs(x_i^+ - x_j^+), abs(x_i^- - x_j^-)$ 其中之一(另一个是零)
- $x_i x_j < 0$,不妨设 $x_i > 0, x_j < 0$,则:
$
abs(x_i - x_j) = abs(x_i) + abs(x_j) = abs(x_i^+ - x_j^+) + abs(x_i^- - x_j^-)
$
表明 $abs(x_i - x_j) = abs(x_i^+ - x_j^+) + abs(x_i^- - x_j^-)$ 总是成立
- $N(y) = N(y^+) + N(y^-)$
注意到 $0 in "median"_d (y)$ 表明:
$
N(y) = sum_(i in V) d_i abs(y_i) = sum_({i in V | y_i >= 0}) d_i abs(y_i) + sum_({i in V | y_i < 0}) d_i abs(y_i) = N(y^+) + N(y^-)
$
得证
]
延续 $I(x), N(x)$ 的定义,接下来需要考虑如何解决这个绝对值函数的最优值。我们仍然希望使用拉格朗日乘子法,由于 $I(x)/N(x)$ 齐次,依然只在 $norm(x)_d = sum_i d_i abs(x_i) =
1$ 上讨论,更进一步,按照之前的讨论,我们有:
$
h(G) = min_(x in pi) I(x), pi = {x | norm(x)_d = 1 and 0 in "median"(x)}
$
容易验证 $pi$ 是闭集\
我们需要处理绝对值,虽然理论上不能求导,但我们可以不严格的求导得到:
$
diff I(x) = mu diff norm(x)_d
$<informallyD>
为了拓展拉格朗日乘子法,注意到我们在这里处理的函数都是凸的,一元的情形上它单侧导数总存在,且几乎处处可微
#definition[次梯度][
设 $f$ 为凸函数,对于任意 $x in X$,定义:
$
G = {g in RR^n | forall y in X, f(y) >= f(x) + g^T (y - x)}
$
称 $G$ 中所有元素都是 $f$ 在 $x$ 处的某个次梯度,有时也将 $G$ 记作 $diff f$,称为 $f$ 的次梯度\
当 $f$ 具有一些良好性质时,次梯度是存在(非空)的
]
#proposition[][
设 $f$ 是开区域 $C$ 上的凸函数:
- 若于 $x$ 点,可微,则 $diff x = {triangle.b f(x)}$
- 若 $alpha >0$,则 $diff (alpha x) = alpha diff x$\
- 设 $g$ 是另一个区域上的凸函数,则:
$
diff(f + g) = diff f + diff g
$
- 以上两条给出 $diff$ 是(半空间意义下)的线性算子
- $diff f$ 是闭的凸集
- 设 $f$ 一次齐次,则:
- 任取 $s in diff f(x)$,将有 $f(x) = s^T x$
- 任取 $s in diff f(y)$,将有 $f(x) >= s^T x$
- $diff abs(x) = "Sgn(x)"$,其中:
$
"Sgn"(x) = cases(
{1} quad x> 0,
{-1} quad x < 0,
[-1, 1] quad x = 0
)
$
]
#lemma[][
设 $C$ 是开区域,$x$ 是其上的最小值点,则:
$
0 in diff f(x)
$
反之,若上式成立,则 $x$ 是最小值点
]
在@informallyD 中,等号不应该理解为集合间的相等,而是集合相交非空。计算:
$
(diff norm(x))_j = d_j "Sgn"(x_j) := D "Sgn"(x)
$
其中 $"Sgn"(x)$ 定义为 $product_i "Sgn"(x_i) in RR^n$(作为子集的外积)\
对于另一侧,将 $I(x)$ 看作复合函数 $I(x) = norm(B x)_1$,其中 $B$ 是关联矩阵,$norm(x)_1 = sum_i abs(x_i)$
#lemma[][
设 $h$ 是凸函数,$f$ 是线性函数,则 $h compose f$ 是凸函数
]<convexity>
#proof[
设定义域为凸集 $X$, 任取 $x, y in X, t in [0, 1]$,计算:
$
h(f(t x + (1 - t) y)) = h(t f(x) + (1-t) f(y)) <= t h(f(x)) + (1-t) h(f(y))
$
由定义知 $h compose f$ 是凸函数
]
#lemma[][
若 $A$ 列满秩,有(某种意义上的链式法则):
$
diff f = A^T diff h(A x + b)
$
]
#proof[
利用@convexity,这当然是凸函数。为了计算 $diff f(x_0)$,设:
$
forall x in RR^n, f(x) - f(x_0) >= g^T (x - x_0)
$
上式化简为:
$
h(A x + b) - h(A x_0 + b) >= g^T (x - x_0)
$<eq1>
任取 $t in diff h(A x_0 + b)$,有:
$
h(y) - h(A x_0 + b) >= t^T (y - A x_0 - b)
$<eq2>
- 设 $t in diff h(A x_0 + b)$,在@eq2 中取 $y = A x + b, g = A^T t$ 即得@eq1 恒成立,进而 $A^T t in diff f(x_0)$,故 $A^T diff h(A x_0 + b) subset diff f(x_0)$
- 反之,若 $x -> A x + b: RR^m -> RR^n$ 是满射,任取 $g = A^T t in diff f(x_0)$,有:
$
forall y = A x + b in RR^m, h(y) - h(A x_0 + b) >= (t^T) (y - A x_0 - b)
$
换言之 $t in A^T diff h(A x_0 + b) => diff f(x_0) subset A^T diff h(A x_0 + b)$
综上,当上述映射是满射(也即 $A$ 列满秩)时,有 $diff f(x_0) = A^T diff h(A x_0 + b)$
]
由引理我们得到:
$
diff I(x) = B^T "Sgn"(B x)\
= {sum_({i, j} in E) z_(i j)(x) | z_(i j) in "Sgn"(x_i - x_j) and z_(i j) = - z_(j i), forall i, j}
$
#definition[][
称 $(u, x)$ 是 $Delta_1-$特征对,如果:
$
diff I(x) sect mu D "Sgn"(x) != emptyset
$
]
#theorem[][
对于任意一组特征对 $mu, x$,存在 $V$ 的子集 $A$ 使得 $mu = "cut"(A)/("vol"(A))$
]
#proof[
- 设 $x$ 是 $mu$ 的特征向量 ,并且满足有:
- 保号性 $x_i >= 0 => y_i >=0, x_i <= 0 => y_i <= 0$
- 保序性:$x_i >= x_j => y_i >= y_j, x_i <= x_j => y_i <= y_j$
则 $x, y$ 的凸组合将也是特征向量
由引理,对任意 $x$ 是特征向量,令:
$
y_i = cases(
0 quad x_i <=0,
1 quad x_i > 0
)
$
由引理得知 $y$ 也是特征向量,令:
$
A = {i in V | y_i = 1}
$
则取 $v in diff I(y) sect mu D "Sgn"(y)$,将有:
$
"cut"(A) = I(y) = v^T y = sum_(i in A) v_i = sum_(i in A) mu d_i = mu "vol"(A)
$
(这里运用了 $I(y)$ 一次齐次,因此 $I(y) = v^T y, forall y in diff I(y)$
证毕
]
接下来考虑如何研究所有的 $mu$,显然由上面的等式可以看出,所有可能的 $mu$ 不多于可能的割的数量,而割当然只有有限个。
回到之前的最优化问题,我们添加了约束:
$
0 in "median"_d (x)
$
仿照之前的 $lambda_2$ ,有定理:\
#theorem[][
$0 in "median"_d (x) <=> 0 in sum_(i in V)d_i "Sgn"(x_i)$
]
#proof[
设 $g(c, x) = sum_(i in V) d_i abs(x_i -c)$,则:
$
0 in diff g(0, x) = sum_(i in V) d_i "Sgn"(x_i) <=> c = 0 "是 " g(c, x) "的最小值点" <=> 0 in "median"_d (x)
$
]
容易验证 $(0, arrow(1))$ 成为一个 $Delta_1$ 特征对,从而设 $mu > 0$ 是非零的特征值 $x$ 是一个对应的特征向量,我们希望依次验证:
- $mu = I(x)$\
类似的,取 $v in I(x) sect mu D "Sgn"(x)$,有:
$
I(x) = v^T x = mu sum_(i in V) d_i "Sgn"(x_i) x_i = mu norm(x)_(1, d) = mu
$
- 若 $mu > 0$,则 $0 in sum_(i in V) d_i "Sgn"(x_i)$\
取:
$
v_i = sum_({i, j in E}) z_(i j)(x), z_(i j) = -z_(j i) in mu d_i "Sgn"(x_i)\
sum_(i in V) v_i = 0 in sum_(i in V) mu d_i "Sgn"(x_i)
$
若 $mu != 0$,则上式表明 $0 in sum_(i in V) d_i "Sgn"(x_i) $
- $h(G)$ 确实是特征值\
这里注意到 $pi = {x in RR^n|0 in "median"_d (x) and norm(x)_(1, d) =1}$ 是有界闭集,也是紧集,连续函数在紧集上当然可以取得最小值,前面已经证明了最小值就是 $h(G)$,因此可以 $x in pi$ 使得 $I(x) = h(G)$
由 $0 in "median"_d (x)$ 知可以取得 $v in diff norm(x)_(1, d)$ 使得 $v^T 1 = 0$\
往证:$forall y in RR^n, I(y) - h(G) v^T y >= 0 = I(x) - h(G) norm(x)_(1, d)$
- 如若不然,设 $y$ 使得上式不成立,令:
$
y' = y - alpha 1, alpha in "median"_d (x)\
y'' = y'/(norm(y)_(1, d)) in pi
$
注意到:
$
I(y'') - h(G) v^T y'' &= 1/(norm(y)_(1, d)) (I(y')-h(G)v^T y') \
&= 1/(norm(y)_(1, d)) (I(y - alpha 1)-h(G)v^T (y - alpha 1))\
&= 1/(norm(y)_(1, d)) (I(y)-h(G)v^T y) < 0
$
表明 $I(y'') < h(G) v^T y <= h(G) norm(y)_(1,d) = h(G)$,注意到 $y in pi$,矛盾!\
(这里利用了若 $f(x)$ 是一次齐次的凸函数,则 $f(y) >= v^T y, v in diff f(x)$)
因此,我们有 $0 in diff(I(x) - h(G) v^T x) = diff I(x) - h(G) v subset diff I(x) - h(G) diff norm(x)_(1, d) $\
上式即说明 $h(G), x$ 是一个特征对,证毕
== 从 cheeger 问题到最大割
或许我们会想用类似的思路解决最大割问题,然而稍加尝试便可发现,最大割问题将是在求凸函数的最大值,这使得我们用过的许多性质不再成立。类似的对 $p in{1, 2}$,(这个 $p$ 并不重要,只是和之前的结果统一)定义:
$
I_p (x) = sum_({i, j} in E) abs(x_i -x_j)^p\
norm(x)_p = max abs(x_i)^p
$
类似于之前的两值向量,希望取 $x in {-1, 1}^n$ 模拟凸函数的最大值问题(它总是应该在边界处取得)\
注意到:
$
h_(max) (G) = max_(x in {0, 1}^n, x != 0) (I_p (x))/(2^(p-1) "vol"V )
$
#theorem[][
$
h_(max)(G) = max_(x != 0) (I_p (x))/(2^(p-1) norm(x) "vol"V )
$
]
#proof[
#lemma[][
凸函数在有界闭凸集内的最大值可以在边界处取得
]
#proof[
如若不然,设 $x_0 in X$ 是凸函数 $f$ 在有界闭凸集 $X$ 内的最大值点,而 $x_0$ 不在 $X$ 的边界上,并且:
$
f(diff X) subset (-infinity, f(x_0))
$
此时 $x_0$ 是内点,不妨任取一个方向向量 $v$ 可设:
$
h(t) = x_0 + t v\
T = {t in [-infinity, +infinity] |h(t) subset X} = Inv(h)(X)
$
显然 $T$ 是闭集(由 $h$ 连续性)且有界(否则 $X$ 无界),因此可取:
$
t_0 = cases(
sup T quad abs(sup T) < abs(inf T),
inf T quad abs(sup T) >= abs(inf T)
)
$
这是为了保证 $x_0 plus.minus t v in X$,由凸性有:
$
1/2 (f(x_0 + t_0 v) + f(x_0 - t_0 v)) >= f(x_0)
$
注意到 $x_0$ 已经是最大值点,因此一定有:
$
f(x_0 + t_0 v) = f(x_0 - t_0 v) = f(x_0)
$
但 $x_0 plus.minus t v$ 至少有一个在边界上,矛盾!
]
回到目标,注意到:
$
f(x) = (I_p (x))/(2^(p-1) norm(x) "vol" V)
$
是齐次函数,因此:
$
max_(x in RR - {0} ) f(x)&= max_(abs(x) = 1) (I_p (x))/(2^(p-1) norm(x) "vol" V) \
&= max_(abs(x) = 1) (I_p (x))/(2^(p-1) "vol" V)\
&= 1/(2^(p-1) "vol" V) max_(abs(x) = 1) I_p (x)\
&= 1/(2^(p-1) "vol" V) max {max_(x in [-1, 1]^n quo [-1, 1]) I_p (x)|_(x_i = 1) | i in 1, 2, 3, ...,n}\
$
这里 $max_(x in [-1, 1]^n quo [-1, 1]) I_p (x)|_(x_i = 1)$ 就是如下的最大值问题:
$
max_(x' in [-1, 1]^(n-1)) I'(x')
$
由引理,它的最大值应该在边界处取得,也即至少一个 $x_i = 1$,进而:
$
max_(x' in [-1, 1]^(n-1)) I'(x') = max {max_(x' in [-1, 1]^(n-1) quo [-1, 1]) I' (x')|_(x_i = 1) | i in 1, 2, 3, ..., n-1}
$
归纳进行即得最大值 $I_p (x)$ 的最大值点 $x_0 in {-1, 1}^n$,因此:
$
max_(x in RR - {0} ) f(x)= max_(x in {-1, 1}^n)f(x)
$<eq11>
另一方面,容易计算得到:
$
h_(max) (G) = max_(x in {0, 1}^n) (I_p (x))/("vol" V)
$
定义一一映射:
$
phi: {0, 1} &<-> {-1,1}\
0 &<-> -1\
1 &<-> 1
$
将其广播得到的一一映射映射 ${0, 1}^n <-> {-1,1}^n$ 也记作 $phi$,容易验证:
$
I_p (x) = 1/2^(p-1) I_p (phi(x))
$
进而有:
$
max_(x in {0, 1}^n) (I_p (x))/("vol" V) = max_(phi(x) in {-1, 1}^n) (I_p (x))/("vol" V) = max_(phi(x) in {-1, 1}^n) (I_p (phi(x)))/(2^(p-1) "vol" V)
$
将 $phi(x)$ 换成 $x$ 结合@eq11 即得结论成立
]
然而凸函数在凸区域的上的最大值问题并不容易,上面的证明本质上只有形式上的意义,丝毫没有减少求最大值的困难。
== Lovasz 延拓
回顾之前的过程,我们发现我们总是在将一个离散的最值问题延拓到连续区间,变成连续的优化问题。更加广泛地说,我们发现解决连续的问题往往比解决离散的问题更加简单,因此当然希望能把离散的问题延拓到连续的问题进行求解。
显然,对于任何一个离散最优化问题,我们可以找到无穷个连续曲线使得它们有相同的最优解。而给出一个具体的并不容易,本节就给出了一种具体的方法
#let absSigmaI(i) = $abs(x_sigma(#i))$
#let fL = $f^L$
#definition[Lovasz 延拓][
$forall x in RR^n, sigma: V union {0} -> V union {0}$ 使得 $abs(x_(sigma(i))) <= abs(x_sigma(i+1) ) $\
约定:
$
sigma(0) = 0\
x_(sigma(0)) = 0
$
对于 $i in {0, 1, 2..., n}$ 定义如下集合:
$
V_(sigma(i))^plus.minus = {j in V | plus.minus x_j > abs(x_(sigma(i)))}
$
对于任给的函数:
$
f: P_2 (V) -> RR
$
其中 $P_2 (V) = {(a, b) in V times V | a sect b = emptyset}$\
称其 Lovasz 延拓为:
$
f^L (x) = sum_(i=0)^(n-1) (abs(x_(sigma(i+1))) - abs(x_(sigma(i)))) f(V_(sigma(i))^plus, V_(sigma(i))^minus)
$
]
#example[][
对于 $(A, B) in P_2 (V) - {(emptyset, emptyset)}$,定义:
$
1_(A, B) = 1_A - 1_B in {-1, 0, 1}^n
$
则:
$
f^L (1_(A, B)) = (1 - 0)f(V_sigma(i)^+, V_sigma(i+1)^-)
$
其中 $sigma(i) = 0, abs(sigma(i+1)) = 1$\
从而:
$
V_sigma(i)^+ = {j in V| x_j > 0} = A\
V_sigma(i)^- = {j in V| x_j < 0} = B
$
进而 $f^L (1_(A, B)) = f(A, B)$
]
#proposition[][
- 设 $f: P_2 (V) -> RR$ 满足 $f(emptyset, emptyset)$,则有:
$
forall (A, B) in P_2 (V), f^L (1_(A, B)) = f(A, B)
$
- Lovasz 延拓有积分表示,也即:
$
f^L (x) = integral_0^(norm(x)_infinity) f(V_t^+ (x), V_t^- (x)) dif t
$
其中 $V_t^(plus.minus) (x) = {i in V | plus,minus x_i > t}$\
这给出 $f^L$ 是连续函数,事实上被积函数是分段常函数
- $forall alpha > 0, f^L (alpha x) = alpha f^L (x)$
]
#proof[
- 只是在上面的计算中补充了平凡情况
- 当 $absSigmaI(i) < t < absSigmaI(i+1)$ 时,有:
$
V_t^+ (x) = V_(sigma(i))^+\
V_t^- (x) = V_(sigma(i))^-
$
从而:
$
f^L (x) &= sum_(i=0)^(n-1) (abs(x_(sigma(i+1))) - abs(x_(sigma(i)))) f(V_(sigma(i))^plus, V_(sigma(i))^minus) \
&= sum_(i=0)^(n-1)integral_(absSigmaI(i))^(absSigmaI(i+1)) f(V_t^+ (x), V_t^- (x)) dif t\
&= integral_0^(norm(x)_infinity) f(V_t^+ (x), V_t^- (x)) dif t
$
证毕
- 做积分变换即可
]
#theorem[Lovasz 延拓][
设 $f, g: P_2 (V) -> [0, +infinity]$,且对任意 $(A, B) in P_2 (V) - {(emptyset, emptyset)}$ 有 $g(A, B) > 0$,则我们有:
$
min_((A, B) in P_2 (V) - {(emptyset, emptyset)}) (f(A, B))/(g(A, B)) = min_(x in RR^n - {0}) (f^L (x))/(g^L (x))\
max_((A, B) in P_2 (V) - {(emptyset, emptyset)}) (f(A, B))/(g(A, B)) = max_(x in RR^n - {0}) (f^L (x))/(g^L (x))
$
]
#proof[
+ 先证明最小值形式,最大值形式同理可得
- 首先要证明右侧的最小值存在。事实上前面证明了 $f^L, g^L$ 是一次齐次的连续函数,因此可以在任何一个有界闭集上取得最小值,例如 ${x | norm(x) = 1}$,其上的最小值也是它在整个定义域上的最小值
- 其次,显然有:
$
min_((A, B) in P_2 (V) - {(emptyset, emptyset)}) (f(A, B))/(g(A, B)) = min_((A, B) in P_2 (V) - {(emptyset, emptyset)}) (f^L (1_(A, B)))/(g^L (1_(A, B))) >= min_(x in RR^n - {0}) (f^L (x))/(g^L (x))
$
因此只要证明另一侧不等式
- 任取 $x !=0 $:
$
(f^L (x))/(g^L (x)) = (sum_(i=0)^(n-1) (absSigmaI(i+1) - absSigmaI(i)) f(V^+_(sigma(i)), V^-_(sigma(i)))) /(sum_(i=0)^(n-1) (absSigmaI(i+1) - absSigmaI(i)) g(V^+_(sigma(i)), V^-_(sigma(i))))
$
注意到我们总可以取得 $(C, D) in P_2 (V)$ 使得:
$
(f(C, D))/(g(C, D)) = min_(0<= i <= n-1) (f(V^+_(sigma(i)), V^-_(sigma(i)))) /(g(V^+_(sigma(i)), V^-_(sigma(i))))
$
有:
$
&(f^L (x))/(g^L (x)) - (f(C, D))/(g(C, D)) \
&=
(
sum_(i=0)^(n-1) (absSigmaI(i+1) - absSigmaI(i)) f(V^+_(sigma(i)), V^-_(sigma(i)))
-
(sum_(i=0)^(n-1) (absSigmaI(i+1) - absSigmaI(i)) g(V^+_(sigma(i)), V^-_(sigma(i)))) (f(C, D))/(g(C, D))
)
/
(
sum_(i=0)^(n-1) (absSigmaI(i+1) - absSigmaI(i)) g(V^+_(sigma(i)), V^-_(sigma(i)))
)
\
&>= (sum_(i=0)^(n-1) (absSigmaI(i+1) - absSigmaI(i)) f(V^+_(sigma(i)), V^-_(sigma(i)))
-
(sum_(i=0)^(n-1) (absSigmaI(i+1) - absSigmaI(i)) g(V^+_(sigma(i)), V^-_(sigma(i)))) (f(V^+_(sigma(i)), V^-_(sigma(i))))/(g(V^+_(sigma(i)), V^-_(sigma(i)))))
/(sum_(i=0)^(n-1) (absSigmaI(i+1) - absSigmaI(i)) g(V^+_(sigma(i)), V^-_(sigma(i))))\
&= 0
$
因此
$
min_(x in RR^n - {0}) (f^L (x))/(g^L (x)) >= (f(C, D))/(g(C, D)) >= min_((A, B) in P_2 (V) - {(emptyset, emptyset)}) (f(A, B))/(g(A, B))
$
证毕
]
我们得到了很强的结论,但是会发现最大割问题或者 Cheeger 问题要求集对是图割而不是一般的集对,因此必须使用下面的引理进行处理
#lemma[][
设 $f, g: P(V) -> [0, +infinity]$ 是对称的函数,也即:
$
f(A) = f(V - A)\
g(A) = g(V - A)
$
且满足 $g > 0$\
记:
$
F(A, B) = f(A) + f(B)\
G(A, B) = g(A) + g(B)
$
则:
$
min_(A in P(V)) (f(A))/(g(A)) = min_((A, B) in P_2 (V)) (F(A, B))/(G(A, B))\
$
最大值形式也对
]
#proof[
以最小值形式为例,设 $(A_0, B_0)$ 使得上式右侧取得最小值,不妨设:
$
(f(A_0))/(g(A_0)) <= (f(B_0))/(g(B_0))
$
于是:
$
(f(A_0) + f(B_0))/(g(A_0) + g(B_0)) - (f(A_0))/(g(A_0)) = (f(B_0) -(f(A_0))/(g(A_0))g(B_0))/(g(A_0) + g(B_0)) >= 0
$
给出:
$
min_((A, B) in P_2 (V)) (F(A, B))/(G(A, B)) = (f(A_0) + f(B_0))/(g(A_0) + g(B_0)) >= (f(A_0))/(g(A_0)) >= min_(A in P(V)) (f(A))/(g(A))
$
另一侧也是类似的
]
#example[][
对于最大割问题,可设:
$
f(A) = "cut"(A)\
g(A) = 1/2 "vol"(A)
$
则:
$
h_(max)(G) = max_(A in P(V)) (f(A))/(g(A)) = max_((A, B) in P_2 (V)) (F(A, B))/(G(A, B)) = max_((A, B) in P_2 (V)) ("cut"(A) + "cut"(B))/("vol"(A))
$
只需计算:
$
F^L (x) &= integral_0^(norm(x)_infinity) ("cut"(V_t^+ (x)) + "cut"(V_t^- (x))) dif t\
&= integral_0^(norm(x)_infinity) "cut"(V_t^+ (x)) dif t + integral_0^(norm(x)_infinity) "cut"(V_t^- (x)) dif t\
&= sum_({i, j} in E) integral_0^(norm(x)_infinity) chi_{x_j <= t < x_i} (t) + chi_{x_i <= t < x_j} (t) dif t \ &+ integral_0^(norm(x)_infinity) chi_{x_j <= -t < x_i} (t) + chi_{x_i <= -t < x_j} (t) dif t\
&"(注意这里积分可以改变有限个点值,因此正负号无所谓)"\
&= sum_({i, j} in E) integral_0^(norm(x)_infinity) chi_{x_j <= t < x_i} (t) + chi_{x_i <= t < x_j} (t) dif t \ &+ integral_(-norm(x)_infinity)^(0) chi_{x_j <= t < x_i} (t) + chi_{x_i <= t < x_j} (t) dif t\
&= sum_({i, j} in E) integral_(-norm(x)_infinity)^(norm(x)_infinity) chi_{x_j <= t < x_i} (t) + chi_{x_i <= t < x_j} (t) dif t \
&= sum_({i, j} in E) abs(x_i - x_j)\
G^L (x) &= integral_0^(norm(x)_infinity) "vol"(V) dif t = "vol"(V) norm(x)_infinity
$
这就可以得到和之前一致的结论
对于 cheeger 问题,会这里有些小问题,如果允许 $x = 0, 1$,则可能出现 $0/0$ 的问题,我们需要修改一下定理,利用:
#corollary[][
设 $f, g: P_2(V) -> [0, +infinity]$ 是集对函数,并且满足:
$
f(emptyset, V) = f(V, emptyset) = 0
$
记:
$
P'_2(V) = P_2(V) - {(emptyset, V), (V, emptyset), (emptyset, emptyset)}
$
若 $g(x) > 0, forall x in P'_2(V)$
则:
$
min_((A, B) in P'_2 (V)) (f(A, B))/(g(A, B)) = min_(x in RR^n - {0, 1}) (f^L (x))/(g^L (x))\
$
最大值形式也对
]
回到具体的计算,与上面的例子相比分子是一样的,只对:
$
G (x) = min {vol(A), vol(V - A)} + min {vol(B), vol(V - B)}
$
进行计算:
$
G^L (x) &= integral_(0)^(norm(x)) min {vol(A), vol(V - A)} + min {vol(B), vol(V - B)} dif t\
&= integral_(0)^(norm(x)) min {vol(V_t^+), vol(V - V_t^+)} + min {vol(V_t^-), vol(V - V_t^-)} dif t\
&= integral_(-norm(x))^(norm(x)) min {vol(V_t^+), vol(V - V_t^+)} dif t\
$
取 $sigma in S_n$ 使得:
$
x_(sigma(1)) <= x_(sigma(2)) <= ... <= x_(sigma(n))
$
则一定存在 $k_0$ (中位数)使得:
$
sum_(i=1)^(k_0 - 1) d_(sigma(i)) < 1/2 "vol" V <= sum_(i=1)^(k_0) d_(sigma(i))
$
则有:
$
min {vol(V_t^+), vol(V - V_t^+)} = cases(
vol(V - V_t^+) quad t < x_(sigma(k_0)),
vol(V_t^+) quad t >= x_(sigma(k_0))
)
$
原式化为:
$
&quad integral_(-norm(x))^(norm(x)) min {vol(V_t^+), vol(V - V_t^+)} dif t\
&= integral_(-norm(x))^(x_(sigma(k_0))) vol(V - V_t^+) dif t + integral_(x_(sigma(k_0)))^(norm(x)) vol(V_t^+) dif t\
&= sum_(i=1)^(k_0 - 1) (x_sigma(i+1) - x_(sigma(i))) sum_(j=1)^i d_(sigma(i)) + sum_(i=k_0)^(n - 1) (x_sigma(i+1) - x_(sigma(i))) sum_(j=i+1)^n d_(sigma(i))\
&"(利用阿贝尔变换)"\
&= sum_(i=1)^(k_0 - 1) d_(sigma(i)) (x_sigma(k_0) - x_sigma(i) ) + sum_(i=k_0 + 1)^(n - 1) d_(sigma(i)) (x_sigma(i) - x_sigma(k_0) )\
&= sum_(i=1)^(n_1) d_(sigma(i)) abs(x_sigma(k_0) - x_sigma(i) ) \
$
使用 @median-min,注意到 $k_0$ 是一个中位数,上式恰为:
$
min_(c in RR) sum_(i=1)^n d_i abs(x_i - c)
$
]
== 图模型算法简介
本节我们给出一些近似算法。以最大割问题为例,前面已经证明答案就是:
$
h_(max) (G) = max_(x in RR^n - {0}) I(x)/(norm(x) vol V)
$
我们发现比例式的形式颇为常见,往往将这种问题称为 分式规划|fractional programming
#theorem[Dinkerbach 迭代][
设 $A$ 是紧集,$P, Q$ 是连续函数,针对分式规划问题:
$
max_(x in A) P(x)/Q(x)
$
可以构造迭代
$
cases(
x^(k+1) = argmin_(x in A) {Q(x) y^k - P(x) },
y^(k+1) = P(x^(k+1))/Q(x^(k+1))
)
$
- 述迭代产生的序列 ${y^k}$ 单调递增
- 若原问题有最优值,则上述迭代产生的序列收敛于原问题的解
]
#example[][
对于最大割问题迭代方法是:
$
cases(
x^(k+1) = argmin_(norm(x) = 1) {r^k norm(x) vol V - I(x)},
r^(k+1) = I(x^(k+1))/(norm(x^(k+1)) vol V)
)
$
则对任意初始点 $x_0$ 满足 $norm(x_0) = 1$,上述迭代产生的序列 ${r^k}$ 单调递增,且收敛于原问题的解。\
然而对于该问题,由于迭代过程本身也有难解的优化问题,我们需要进一步采用所谓的*次梯度下降*,问题变成:
$
cases(
x^(k+1) = argmin_(norm(x) = 1) {r^k norm(x) vol V - s^(k) dot x},
r^(k+1) = I(x^(k+1))/(norm(x^(k+1)) vol V),
s^(k+1) in partial I(x^(k+1))
)
$
虽然如何选取次梯度以及收敛性更为困难,但至少它在计算上已经没有了困难。
事实上,我们可以证明 $r^k$ 仍然单调,但未必能收敛到原问题的最优解。如果次梯度选取恰当,它可以收敛到原问题的局部最优解。在此不会证明这些结果。
]
#proof[
注意到:
$
r^k norm(x^(k+1)) vol V - I(x^(k+1)) <= r^k norm(x^k) vol V - I(x^k) = 0\
r^k <= I(x^(k+1))/(norm(x^(k+1)) vol V) = r^(k+1)
$
注意到最大割问题的解 $r_(max)$ 存在,且每个 $r_n$ 都不超过 $r_(max)$,因此序列单调有上界,进而有极限 $r <= r_(max)$\
同时,设 $x_0$ 是取得原问题最大值的点,将有:
$
r^n norm(x^(n+1)) vol V - I(x^(n+1)) <= r^n norm(x_0) vol V - I(x_0)
$
注意到 $x^n$ 是紧集上的序列,可取其一个收敛子列,不妨设它本身就收敛,上式取极限即得:
$
r >= r_(max)
$
或者定义 $f(r) = min_(norm(x) = 1) {r norm(x) - I(x)} in C(RR)$,计算得:
$
f(r^k) = norm(x) (r^k - r^(k+1))
$
取极限的 $f(r) = 0$,进而 $r norm(x_0) - I(x_0) >= 0 => r >= r_(max)$,得证
]
这是使用 $norm(x)_1 = max_(i) abs(x_i)$ 的结果,但已有的结果更多是使用 $norm(x)_2 = max_i x_i^2$,也就是要解最优化问题:
$
max_(x in {-1, 1}^n) 1/8sum_(i, j in V) w_(i j) (x_i - x_j)^2 where w_(i j) = 1 "if" (i, j) in E "else" 0
$
上式化为:
$
max_(x in {-1, 1}^n) 1/4 sum_(i, j in V) w_(i j) (1 - x_i x_j) := P_1
$
简化一下,只需要:
$
min_(x in {-1, 1}^n) sum_(i, j in V) w_(i j) x_i x_j\
<=> min sum_(i, j in V) w_(i j) x_i x_j with abs(x_i) = 1 := P_2\
$
令 $X = x x^T$,将问题转化为
$
min inner(W, X) with "rank"(X) = 1, X_(i i) = 1, X >= 0 := P_3
$
#lemma[][
$P_2, P_3$ 两个问题是等价的
]
解决半正定矩阵空间上最优化问题的学科称为 SDP(semi-definite programming),由于半正定矩阵空间是凸的,这本质是凸优化问题,有很多成熟的结论。然而秩 1 的要求是很困难的,因此有下面的松弛形式(往往称为秩 2 松弛):
$
min inner(W, X) with "rank"(X) <= 2, X_(i i) = 1, X >= 0 := P_6\
<=>^(X = V^T V) min sum_(i j) w_(i j) inner(v_i, v_j) with inner(v_i, v_j) = 1, v_i in SS^1 := P_7\
where SS^1 = {(x, y) in RR^2 | x^2 + y^2 < 1}
$
再用参数表示 $SS^1$,经计算可得:
$
min_(theta in RR^n) sum_(i, j) w_(i j) cos(theta_i - theta_j) := P_8
$
这种算法称为 Circut,不过我们还面临如下问题:
+ 如何计算上面的最优化
+ 如何从上面的问题回到最初的 cut
+ $P_8$ 的解与 $P_3$ 的解有什么关系
这已经是非常前沿的问题,这里不再赘述。这种算法的误差很好,但是计算量大,主要问题还没有非常快的方法解决 $P_8$
回到之前的 $P_3$,还有更激进的方法是在 $P_3$ 中放弃秩 1 的要求,放弃后的最优化问题称为 $P_4$。这种算法是所谓的 Goemans-Williamson (G-W) 算法,问题转化为了标准的 SDP 问题,已经是多项式内可解。
假设 $P_4$ 的最优值点是 $X^*$,反推代回原问题可以得到最大割问题的一个近似解 $Z_("SDP")$,我们还要面临如何恢复 cut 以及近似解的估计问题,G-W 算法采取的策略是
- 首先将 $X^*$ 分解为 $u^T u$,再设 $u$ 的列向量组为 $u_i$。注意到由约束条件,$u_i in SS^(n-1)$,为了将其恢复到 ${-1, 1}$ 上,以均匀分布在 $SS^(n-1)$ 上随机选择 $a in SS^(n-1)$,再令 $u_i$ 取 $a, -a$ 中夹角为锐角的一方 $u'_i$(也就是以 $a$ 为轴分成两个半球,取 $u_i$ 在的一方),最后取 $x_i := u'_i / a$
- 计算这个 $X$ 对应的割值,记为 $z$
#theorem[][
$
E z >= alpha h_(max "cut") where alpha = min_(theta in [0, pi]) {2/pi theta/(1 - cos theta)} approx 0.879
$
]
#proof[
$
E z &= E (sum_(i < j) 1/2(1- x_i x_j) w_(i j))\
&= 1/2 sum_(i < j) w_(i j) E (1 - x_i x_j)\
&= 1/2 sum_(i < j) w_(i j) (0 P(x_i x_j = 1) + 2 P(x_i x_j = -1 ))\
&= sum_(i < j) w_(i j) P(x_i x_j = -1 )\
$
#lemmaLinear[][
$P(x_i x_j = -1 ) = theta/pi$,其中 $theta$ 是 $u_i, u_j$ 夹角中的锐角
]
#proof[
考虑 $0, u_i, u_j$ 构成的平面,在该平面做 $a$ 的垂线 $v$ 。由构造过程,$x_i x_j = -1$ 意味着直线 $v$ 穿过 $x_i, x_j$ 的夹角之内。由对称性直线的角度在圆盘上均匀分布,因此这个概率就是 $theta/pi$
]
由引理,继续化简可得:
$
E z &= E (sum_(i < j) 1/2(1- x_i x_j) w_(i j))\
&= sum_(i < j) w_(i j) P(x_i x_j = -1 )\
&= 1/pi sum_(i < j) w_(i j) theta_(i j)\
$
取:
$
alpha = min_(theta in [0, pi]) {2/pi theta/(1 - cos theta)}
$
则有:
$
theta/pi >= alpha/2 (1- cos theta)
$
从而:
$
1/pi sum_(i < j) w_(i j) theta_(i j) &>= alpha/2 sum_(i < j) w_(i j) (1 - cos theta_(i j)) \
&= alpha/2 sum_(i < j) w_(i j) (1 - u_i^T u_j) \
&= alpha/4 sum_(i, j in V) w_(i j) (1 - u_i^T u_j) \
$
回顾上面的松弛过程,应当有:
$
sum_(i, j in V) w_(i j) u_i^T u_j &= inner(W, X) \
&<= min inner(W, X) "with" "rank"(X) = 1, X_(i i) = 1. X >= 0\
&= min_(x in {-1, 1}^n) sum_(i, j in V) w_(i j) x_i x_j\
$
因此:
$
&quad alpha/4 sum_(i, j in V) w_(i j) (1 - u_i^T u_j)\
&= alpha/4 sum_(i, j in V) w_(i j) - alpha/4 sum_(i, j in V) w_(i j) u_i^T u_j\
&>= alpha/4 sum_(i, j in V) w_(i j) - alpha/4 min_(x in {-1, 1}^n) sum_(i, j in V) w_(i j) x_i x_j\
&= alpha/4 max_(x in {-1, 1}^n) sum_(i, j in V) w_(i j) (1 - x_i x_j)\
&= alpha/4 sum_(i, j in V) w_(i j) (1 - x_i x_j)\
&= alpha h_(max "cut")
$
]
然而,这个算法的实际表现往往不如一些简单的启发式算法,只不过它作为有理论保证的算法具有重要意义。
= 高维模型
高维模型往往追求精度与效率的平衡
== 傅里叶级数
对于可积函数 $f(x)$,可以写出形式傅里叶级数:
$
f(x) &tilde a_0/2 + sum_(n=1)^infinity (a_n cos(n pi x) + b_n sin(n pi x)) \
where
&a_n = integral_(-pi)^pi f(x) cos(n x) dif x\
&b_n = integral_(-pi)^pi f(x) sin(n x) dif x
$
它当然未必取等。由分析学的知识,我们接下来的讨论都在 $L^2$ 空间中进行,可以保证取得等号。\
傅里叶技术有更常用的复形式,也称之为平面波形式。将 $e^(i x) = cos x + i sin x$ 代入上面的级数,在收敛性较好的情况下可以重排,得到:
$
a_0/2 + sum_(n=1)^infinity (a_n cos(n pi x) + b_n sin(n pi x)) = sum_(n = -infinity)^(infinity) c_n e^(n x i)
$
(注意最后一个求和是主值意义下的极限也即 $lim_(N -> +infinity) sum_(n = -N)^(N) c_n e^(n x i)$)\
其中:
$
c_n = cases(
(a_n - i b_n)/2 quad n>=0,
(a_(n) + i b_(n))/2 quad n<0
)
$\
注意到$sin n x \/ cos n x \/ e^(i n x)$ 都是周期函数,周期为 $(2 pi )/n$,换言之 $n$ 恰好是其对应的频率。因此在实际应用中往往会将 $n$ 看作频率。在复形式的求和式中,$n >= 0$ 的部分称为正频,$n < 0$ 的部分称为负频,它们往往都很关键,往往应该对称考虑而不能只考虑一部分。
== 函数空间与傅里叶变换
令 $E([-pi, pi])$ 为 $(-pi, pi]$ 上所有复值连续函数构成的线性空间:
$
E([-pi, pi]) = {f(x) + i g(x) | f, g in C([-pi, pi])}
$
并且定义复内积:
$
(f, g) = integral_(-pi)^pi f(x) overline(g(x)) dif x
$
易知 ${1/sqrt(2 pi ) e^(i n x) | n in ZZ}$ 构成一组标准正交基,进而函数 $f$ 的傅里叶系数 $c_n$ 满足:
$
c_n sqrt(2 pi) = (f, 1/sqrt(2 pi) e^(i n x)) => c_n = 1/(2 pi) (f, e^(i n x))
$
一般的,对函数在区间 $[-l, l]$ 上做 $2l$ 为傅里叶展开的结果是:
$
f(x) = sum_(n = -infinity)^(infinity) c_n e^(i omega_n x)\
where &c_n = 1/(2 l) (f, e^(i omega_n x))\
&omega_n = (n pi)/l
$<fourier-discrete>
往往认为 $triangle.t omega_n = omega_n - omega_(n-1) = pi/l$ 是频谱上最小的区分间隔,计算发现:
$
f(x) = 1/(2 pi) sum_(n = -infinity)^(infinity) triangle.t omega_n integral_(-l)^(l) f(t) e^(i omega_n (x- t)) dif t
$
不严格地说,令 $l -> +infinity$,上式几乎化为:
$
f(x) = 1/(2 pi) integral_(-infinity)^infinity dif omega integral_(-infinity)^(infinity) f(t) e^(i omega (x- t)) dif t
$<fourier-continuous>
在实际应用中,$[-l, l]$ 往往代表了输入信号的时间。假如输入更长的时间,采用更高的频率分辨率,可以想象估计得到的函数将会更加准确,这就是上面式子的含义,进而引出了下面的傅里叶变换。
#definition[傅里叶变换][
设 $f in E(RR)$,则称:
$
fourierTrans(f)(omega) = 1/sqrt(2 pi) integral_(-infinity)^(infinity) f(x) e^(-i omega x) dif x
$
为傅里叶变换,对应的还有傅里叶逆变换:
$
f(x) = 1/sqrt(2 pi) integral_(-infinity)^(infinity) fourierTrans(f)(omega) e^(i omega x) dif omega
$
以上两个积分都是主值意义下的无穷积分,具体的存在性/收敛性和两者互逆的条件这里不作说明,至少在比较良好的条件下这是成立的。
]
#remark[][
在@fourier-discrete 中,系数 $c_n$ 的衰减速度可以表现有限截断的误差,同时也在 $fourierTrans(f)$ 中体现为在无穷处的衰减速度(事实上,如果衰减过慢,可能导致 $fourierTrans(f)$ 的逆变换不存在)。一些较为复杂的分析表明,这个衰减速度与 $f$ 的光滑性有密切的关系,光滑性越好,衰减速度越快。
]
== 谱方法
在更加现实的问题中,我们往往不知道 $u(x)$ 的所有值,只知道它在个别点的值,因此如何构造一个谱逼近是一个十分经典的问题。假设总共有 $N$ 个点,均匀采样自然是最简单的方法,令:
$
x_j = j (2 pi)/N, j = 0, 1, 2, ..., N - 1\
u_j = u(x_j)
$
#let (hu, tu) = ($hat(u)$, $tilde(u)$)
目标是逼近:
$
hu_k = 1/(2 pi) integral_(0)^(2 pi ) u(x) e^(-i k x) dif x
$
最简单的想法当然是用黎曼和,用:
$
tu_k := 1/N sum_(j = 0)^(N - 1) u_j e^(-i k x_j)
$
最后函数的估计式是:
$
u(x) approx sum_(k = -A)^(A) tu_k e^(i k x)
$
自然我们需要解决:
- 最多能确定多少 $A$\
当然了,有限个点总不能区分比较接近的原函数,这种现象称为混淆。\
事实上,容易验证 $tu_(k+N) = tu_k$,表明约 $A = N/2$ 是较好的选择。继而,我们得到的逼近空间是:
$
g_N = {sum_(i = -N/2)^(N/2) tu_k e^(i k x) | tu_(N/2) = tu_(-N/2)}
$
同时,应该处理一下边界情况,实际使用:
$
tu_k := 1/N 1/c_k sum_(j = 0)^(N - 1) u_j e^(-i k x_j)\
c_k = cases(
2 quad k = N/2,
1 quad "else"
)
$
计算上面的系数,效果更好
- 逼近的效果如何:\
令:
$
I_N (u: L^2(omega)) = x: omega -> sum_(k = -N/2)^(N/2) tu_k e^(i k x)
$
#theorem[][
$
I_N (u)(x_j) = u(x_j)
$
]
#proof[
#definition[Dirichlet 核][
$
D_N (x) = sum_(k=-N)^N e^(i k x) = (e^(-i N x)(1 - e^((2 N + 1) i x)))/(1 - e^(i x))\
= (e^(i (N+1/2) x) - e^(- i (N + 1/2) x))/(e^(1/2 x) - e^(-1/2 x))\
= sin((N + 1/2) x)/sin(x/2)
$
]
计算可得:
$
sum_(k = - N/2)^(N/2) hu_k e^(i k x) = 1/(2 pi) integral_(0)^(2 pi) D_(N/2)(x-tau) hu(tau) dif tau
$
进而:
$
I_N (u)(x) = sum_(k = - N/2)^(N/2) (1/N 1/c_k sum_(j=0)^(N-1) u_j e^(-i k x_j)) e^(i k x_j)\
= 1/N sum_(j=0)^(N-1) u_j sum_(k = - N/2)^(N/2) 1/c_k e^(i k (x - x_j))\
= 1/N sum_(j=0)^(N-1) u_j D_(N/2 - 1)(x - x_j) +1/2 e^(i N/2 (x - x_j)) + 1/2 e^(-i N/2 (x - x_j))\
= 1/N sum_(j=0)^(N-1) u_j (sin ((N-1) (x-x_j)/2))/ (sin (x-x_j)/2) + cos (N (x-x_j)/2)\
= 1/N sum_(j=0)^(N-1) u_j sin(N (x-x_j)/2) cot ((x-x_j)/2) \
$
代入 $x_j$ 取极限即可
]
因此,称上面的 $I$ 为插值算子
更进一步,可以进一步求导数构造导数的逼近。当然有两种求导数方式,一种是计算导数的傅里叶系数,另一种是计算刚刚逼近的导数。
#theorem[谱精度][
任意 $u in H_p^m (omega), m > 1/2$,将有:
$
norm((I(u) - u)^((mu)))_mu <= k N^(mu - m) abs(u)_mu
$
其中
- $H_p^m (omega)$ 是指 ${u in L^2(Omega) | forall mu = 0, 1, 2, ..., m, u^((mu))(x) in L^2(Omega) "且以" 2 pi "为周期"}$
- $norm(u) = (sum_(k = -infinity)^(+infinity) (1+k^2)^mu norm(hu_k)^2)^(1/2)$
- $abs(u)_mu = (sum_(k = -infinity)^(+infinity) (k^2)^mu norm(hu_k)^2)^(1/2)$
- $mu in NN^+, k$ 是与 $N$ 无关的常数
]
#proof[
从现在开始我们索性假设有 $2 N$ 个点,既然只关心 $N$ 的阶
#let hp = $hat(P)$
#definition[投影算子][
定义投影算子:
$
hp_N (u)(x) = sum_(k = -N)^(N) hu_k e^(i k x)
$
也就是取出傅里叶级数的有限项
]
#lemma[][
$forall u in H_p^m (Omega)$,将有:
$
norm(hp_N u - u)_mu <= k N^(mu-m) abs(u)_m
$
]<projection-approx>
#proof[
考虑 $hp_N u - u$ 的傅里叶系数,将有:
$
norm(hp_N u - u)_mu^2 = sum_(abs(k) > N) (1+k^2)^mu norm(hu_k)^2\
= sum_(abs(k) > N) (k^2)^(m-mu) (1+k^2)^mu (1/k^2)^m_mu norm(hu_k)^2\
<= (1/N^2)^(m - mu) sum_(abs(k) > N) ((1+k^2)/k^2)^mu (k^2)^m norm(hu_k)^2
$
注意到上式中 $((1+k^2)/k^2)^mu$ 是有界量,自然有:
$
<= M (1/N^2)^(m - mu) sum_(abs(k) > N) (k^2)^m norm(hu_k)^2\
<= M (1/N^2)^(m - mu) sum_(k) (k^2)^m norm(hu_k)^2
$
得证
]
#lemma[][
$
c_k tu_k = hu_k + sum_(r) hu_(k plus.minus 2 N r)
$
]
#proof[
由定义:
$
c_k tu_k = 1/(2 N) sum_(j = 0)^(2 N - 1) (sum_(norm(n) < infinity) hu_n e^(i n x_i)) e^(-i k x_j) \
= sum_(norm(n) < infinity) 1/(2 N) hu_n sum_(j = 0)^(2 N - 1) e^(i (n - k) x_j)\
= sum_(norm(n) < infinity) 1/(2 N) hu_n sum_(j = 0)^(2 N - 1) e^(i (n - k) (pi)/n j)\
$
为了利用等比数列求和,稍微讨论一下特殊情况,也即 $n = k$ 时求和恰为 $2 N$。计算可得上式就是:
$
sum_(norm(n) < infinity) hu_(k + 2 N n)
$
]
#lemma[][
$
norm(P_N u - I_N u) <= k N^(-m) abs(u)_m
$
]
#proof[
利用正交性:
$
norm(P_N u - I_N u)^2 = (P_N u - I_N u, P_N u - I_N u)\
= sum_(abs(k) <= N) abs(hu_k - tu_k)^2\
= sum_(abs(k) < N) abs(hu_k - tu_k)^2 +1/4 sum_(abs(k) = N) abs(2 hu_k - 2 tu_k)^2\
<= sum_(abs(k) < N) abs(hu_k - tu_k)^2 + 1/2 sum_(abs(k) = N) abs(hu_k - 2 tu_k)^2 + 1/2 sum_(abs(k) = N) abs(hu_k)^2\
<= sum_(abs(k) <= N) abs(hu_k - c_k tu_k)^2 + 1/2 sum_(abs(k) = N) abs(hu_k)^2\
<= sum_(abs(k) <= N) abs(sum_(abs(r) < infinity) hu_(k + 2 N r) )^2 + 1/2 abs(hu_(-N))^2 + 1/2 abs(hu_N)^2\
<= sum_(abs(k) <= N) abs((sum_(abs(r) < infinity) (k+2 N r)^(-2m))(sum_(abs(r) < infinity) (k+2 N r)^(2m)abs(hu_(k+2 N r))^2 ) ) + 1/2 abs(hu_(-N))^2 + 1/2 abs(hu_N)^2\
"(利用柯西不等式)"\
<= k abs((sum_(abs(r) < infinity) (1 + 2 N r)^(-2m))) sum_(abs(k) <= N) (sum_(abs(r) < infinity) (k+2 N r)^(2m)abs(hu_(k+2 N r))^2 ) + 1/2 abs(hu_(-N))^2 + 1/2 abs(hu_N)^2\
"(调和级数的收敛性)"\
<= k N^(-2 m) 2 abs(u)_m^2 + 1/N^(2 m) sum_(abs(k) > N) abs(k)^(2m) abs(hu_k)^2)\
<= k' N^(-m) abs(u)_m
$
]
最后,我们只剩下对导函数的谱逼近
#lemma[][
$
forall u in "Span"{e^(i k x) | -N <= k <= N},\
norm(u^(mu) (x)) <= N^(mu) norm(u)
$
]<anti-der>
#proof[
只需证明 $mu = 1$,之后逐次求导即可\
有:
$
u(x) = sum_(k = -N)^(N) c_k e^(i k x)\
u' (x) = sum_(k = -N)^(N) i k c_k e^(i k x)\
norm(u' (x)) = sum_(k = -N)^(N) k^2 abs(c_k)^2 <= N^2 sum_(k = -N)^(N) abs(c_k)^2 = N^2 norm(u)
$
]
这个不等式被称为反不等式,因为它利用了函数值去估计导数值。我们终于可以估计导数的谱逼近:
$
norm((I_N u - u)') <= norm((I_N u - P_N u)') + norm((P_N u - u)') \
$
分别利用 @anti-der 和 @projection-approx,可得上式:
$
<= N^mu norm(I_N u - P_N u) + N^(mu - m) abs(u)_m\
<= N^mu k N^(-m) abs(u)_m + N^(mu - m) abs(u)_m\
$
证毕
]
== 快速傅里叶变换
用最朴素的方法,计算 $N$ 个傅里叶级数的系数需要 $O(N^2)$ 的时间,这在 $N$ 较大时是不可接受的。因此,我们需要一种快速算法,这就是快速傅里叶变换(FFT, Fast Fourier Transformation)。它的出现确保了谱分析方法的实用性。\
#let FFT = math.op("FFT")
#let IFFT = math.op("InverseFFT")
#definition[DFT][
离散傅里叶变换/反离散傅里叶变换是指两个向量上的算法,使得:
$
"DFT"(X) &= (sum_(j=1)^n X_j w_n^((j - 1)(k-1))) := W X\
"InverseDFT"(Y) &= 1/n (sum_(j=1)^n Y_j w_n^(-(j - 1)(k-1)))\
&where w_n = e^(-2 pi i/n)
$
这里从 $1$ 开始是为了和 Matlab 统一,与之前的记号有对应:
$
u_j = X_(j + 1)\
tu_k = cases(
1/N Y_(k+1) quad k = 0\, 1\, ...\, N/2 - 1,
1/N Y_(N+k+1) quad k = - N/2 + 1\, - N/2 + 2\, ...\, -1,
1/(2 N) Y_(N/2 + 1) quad k = plus.minus N/2
)
$
]
#FFT/#IFFT 是解决上述问题的高效算法,利用了适当的分治来减少重复计算。为了方便,接下来不妨设 $n = 2^k$
#let pOdd = $p_("odd")$
#let pEven = $p_("even")$
#let odd = $"odd"$
#let even = $"even"$
#definition[FFT][
快速傅里叶变换是指一个递归算法,使得:
$
FFT(X)_k &= p(w^(k-1)) := Y_k\
where p(theta) &= x_1 + x_2 theta + x_3 theta^2 + ... + x_n theta^(n-1)\
$
计算 $p(theta)$ 时,进行奇偶分拆:
$
p(theta) = pOdd (theta^2) + theta pEven (theta^2)\
$
将有:
$
Y_k = pOdd (w^(2(k-1))) + w^(k-1) pEven (w^(2(k-1)))
$
在上式中将 $k$ 换成 $n/2$ 发现:
$
Y_(k + n/2) = pOdd (w^(2(k-1) + n)) + w^(k-1 + 2/ n) pEven (w^(2(k-1) + n))\
= pOdd (w^(2(k-1))) - w^(k-1) pEven (w^(2(k-1)))
$
(注意到 $w$ 是 $n$ 次单位根)\
此外,由定义得对于 $k <= n/2$
$
Y_k &= pOdd (w^(2(k-1))) + w^(k-1) pEven (w^(2(k-1))) \
&= FFT_(n/2)(odd(X))_k + w^(k-1) FFT_(n/2)(even(X))_k\
where &odd(X) = (x_1, x_3, ..., x_(n-1))^T\
&even(X) = (x_2, x_4, ..., x_n)^T
$
因此,分别计算 $FFT_(n/2)(odd(X)), FFT_(n/2)(even(X))$ 再按上面的公式即得 $FFT(X)$
]
#proposition[][
$FFT(X)$ 的时间复杂度为 $O(n log n)$
]
#proof[
设 $n$ 阶 $FFT$ 的乘法次数为 $M_n$,加法次数为 $A_k$ ,有:
$
M_1 = 0, A_1 = 0
$
根据上面的过程,将有:
$
M_k = 2 M_(k/2) + k/2\
A_k = 2 A_(k/2) + k
$
设 $k = 2^m$ 并令 $a_m = M_(2^m), b_m = A_(2^m)$,有:
$
a_m = 2 a_(m-1) + 2^(m-1)\
2^(-m) a_m = 2^(-(m-1)) a_(m-1) + 1/2\
2^(-m) a_m = 1/2 m => a_m = 1/2 m 2^m\
b_m = 2 b_(m-1) + 2^m\
2^(-m) b_m = 2^(-(m-1)) b_(m-1) + 1\
2^(-m) b_m = m => b_m = m 2^m
$
化简得 $A_k, M_k$ 都是 $O(n log n)$ 的,证毕
]
== 高维模型中的维度灾难
#let kv = $bold(k)$
#let xv = $bold(x)$
#let toKB(x) = x/1024
#let toMB(x) = x/1024/1024
#let toGB(x) = x/1024/1024/1024
#let FG = $"FG"$
#let absMix(x) = $abs(#x)_"mix"$
#let absMix2(x) = $abs(#x)_"mix"^2$
设 $xv, kv$ 是 $d$ 维向量,注意到有简单的计算式:
$
e^(i kv^T xv) = product_(k) e^(i kv_k xv_k)
$
表明高维的平面波可以自然地分裂成一维平面波的乘积,也称其为张量形式。用这种形式可以进行函数逼近:
$
u(xv) approx u_N (xv) = sum_(k in FG_N) tu_kv e^(i kv^T xv)\
$
其中 $FG_N$ 是指全网格(Full grid),具体定义为:
$
FG_N = ([-N, N] sect ZZ)^d
$
容易计算其中约有 $(2 N)^d$ 个网格点。即使有高效算法 $FFT$ 在维度较高的情况下计算量也是不可接受的,这是维度灾难的体现之一,例如 $d = 6, n = 100$ 时假设使用两字节的浮点数,将需要空间:
$
2 dot 2^6 dot 100^6 "Byte" = #(toGB(2*calc.pow(100, 6)*calc.pow(2, 6))) "GB"
$
同时,谱精度也会随着 $d$ 增加快速衰减,这也是十分糟糕的。
因此,我们当然需要更好的解决方法,有以下几个目标:
- 复杂度不随 $d$ 指数增长
- 精确度不随 $d$ 快速衰减
== 稀疏网格方法
#let SG = $"SG"$
上面的两个目标当然无法轻易实现,需要很多的设计和取舍。例如一个经典的方法是所谓的*双曲截断*,考虑到系数在每个维度上衰减都十分迅速,因此应该取那些合适的格点使得每个维度都不要取过高项的系数。具体来说,取格点:
$
SG_N = {kv | product_(j=1)^n max(abs(kv_j), 1) := absMix(kv) <= N}
$
此时,近似函数所在的函数空间为:
$
Sigma_N = "span"{ e^(i kv xv)| kv in SG_N }
$
我们需要解决:
- 使用该方法取格点的精度如何,有定理:
#let absKpm(x) = $abs(#x)_K_p^m$
#let absKpm2(x) = $abs(#x)_(K_p^m)^2$
#theorem[][
若:
$
u(xv) = sum_(kv in ZZ^n) hu_kv e^(i kv^T xv)
$
则称 $u$ 函数有平面波展开\
任取 $u in K_p^m (Omega)$,有结论:
$
inf_(v in Sigma_N) norm(u - v)_(K_p^mu) <= k N^(mu - m) absKpm(u)
$
其中:
- $absKpm2(sum_(kv in ZZ^n) hu_kv e^(i kv^T xv)) = sum_(kv in ZZ^n) (absMix(kv))^(2m) abs(hu_kv)^2$
- $K_p^m (Omega) = {u(xv) | u "可被平面波展开且" absKpm(u) < infinity}$
- $mu = 0, 1, 2, ..., m$
]
#proof[
左侧取得接近下确界的最佳估计当然是投影,也即
$
inf_(v in ZZ_n) norm(u - v)_(K_p^mu)^2
&<= norm(u - sum_(kv in SG_N) hu_kv e^(i kv^T xv))_(K_p^mu)^2\
&= norm(sum_(kv in ZZ^n - SG_N) hu_kv e^(i kv^T xv))_(K_p^mu)^2\
&= norm(sum_(kv in ZZ^n - SG_N) hu_kv e^(i kv^T xv))_(K_p^mu)^2\
&= sum_(kv in ZZ^n - SG_N) absMix(kv)^(2 mu) abs(hu_kv)^2\
&= sum_(absMix(kv) > N) absMix(kv)^(2 mu) abs(hu_kv)^2\
&< 1/N^(2 m - 2mu)sum_(absMix(kv) > N) absMix(kv)^(2m) abs(hu_kv)^2\
&< 1/N^(2 m - 2mu) absKpm2(u)
$
证毕
]
#remark[][
上面的定理说明了投影可以保持精度,理论上还要证明插值也保持投影的精度,这里不再赘述。
这里函数空间的限制(也即 $absKpm(u) < infinity$ )是非常重要的,不难看出一旦失去了这个条件精度便会失去估计。从形式上看,这需要 $tu_k$ 衰减地非常之快,谱方法中它确实往往有较好的收敛速度,但在一般的数值方法中未必。
然而有趣的是,双曲截断方法的提出在历史上并非最早为了谱逼近方法提出,而是为了在谱方法之前更加常用的分片常数/多项式逼近设计的。
]<approx-remark>
- 使用该方法需要取多少格点,也即稀疏性如何。为此,希望计算 $abs(SG_N)$
#theorem[][
$d$ 维的稀疏网格满足:
$
abs(SG_N) = O(N (log N)^(d-1))
$
]
#proof[
利用数学归纳法
- $d = 1$ 是容易的
- 一般的:
$
{kv | product_(j=1)^n max(abs(kv_j), 1) := absMix(kv) <= N} \
= union_(s =0)^N {kv | product_(j=1)^n max(abs(kv_j), 1) <= N, abs(kv_1) = s}\
= (union.big_(s =1)^N {kv | product_(j=2)^n max(abs(kv_j), 1) <= N/s, abs(kv_1) = s}) union {kv | product_(j=2)^n max(abs(kv_j), 1) <= N, abs(kv_1) = 0}\
$
上式中均为不交并,因此对其计数并利用归纳假设,有:
$
abs(SG_N^d) = 2 sum_(s=1)^N abs(SG_(N/s)^(d-1)) + abs(SG_N^(d-1))\
= sum_(s=1)^N O(N/s (log (N/s))^(d-2)) + O(N (log N)^(d-2))\
= N sum_(s=1)^N O(1/s (log N - log s)^(d-2) )+ O(N (log N)^(d-2))
$
只需要估计 $sum_(s=1)^N O(1/s (log N - log s)^(d-2) )$,利用积分有:
$
sum_(s=1)^N O(1/s (log N - log s)^(d-2) )&<= integral_(1)^(N) 1/x (log N - log x)^(d-2) dif s\
&=^(t = log s) k integral_(0)^(log N) (log N - t)^(d-2) dif t\
&=^(u = log N - t) k integral_(0)^(log N) u^(d-2) dif u\
&= O((log N)^(d-1))
$
故原式约为 $O(N (log N)^(d-1)) + O(N (log N)^(d-2)) = O(N (log N)^(d-1))$,证毕
]
这个结果当然比之前的全网格好得多,我们只需要稍微劣于线性的复杂度就可以取得足够多的项。
== 分片线性逼近中的稀疏网格
#let oddl = $odd_l$
@approx-remark 中提到了稀疏网格方法的历史问题,为了完善起见我们论述如何在更加简单的分片线性逼近中实现稀疏网格方法。核心而言,我们要:
- 找到合适的正交基。在谱方法中我们采用了三角函数的振荡正交,而在这里我们索性简单地将不同基的非零部分(称为*支集*)分开。
- 找到指数级别的衰减性。一般的分片逼近并无如此强的衰减性,我们必须迅速增加分点个数以保证高速衰减。
#definition[分片线性逼近][
令:
$
Phi(x) = cases(
1 - abs(x) quad abs(x) <= 1,
0 quad "else"
)
$
对 $[0, 1]$ 做均匀划分,网格步长为 $h_l = 2^(-l)$,分点为:
$
0 = x^l_0 < x^l_1 < ... < x^l_(2^l) = 1
$
以这些分点构造分片线性基函数:
$
Phi_(l i) = Phi((x - x^l_(i))/h_l)
$
其紧支集为 $[x^l_i - h_l, x^l_i + h_l]$\
记 $V_l = "span" {Phi_(l i) | i = 0, 1, ..., 2^l}$,称为分片线性函数逼近空间。\
方便起见,不妨设函数在边界为零,因此不需要再考虑 $Phi_(l 0), Phi_(l 2^l)$
考虑如下的嵌套基组:
$
W_l = "span" {Phi_(l i) | i in {1, 3, 5, ..., 2^l - 1} := oddl}\
$
不难发现 $W_l$ 中每两个函数之间的紧支集至多交于一点,且 $W_l$ 中任何一个基函数在 $W_(l+1)$ 中恰好分成两个函数(所谓的嵌套关系)
]
#proposition[][
在不考虑边界的情况下,有:
$
V_L = plus.circle_(1 <= l <= k) w_l
$
继而任取 $u in V_L$ 将有:
$
u(x) = sum_(l=1)^L sum_(i in oddl) hu_(l i) Phi_(l i)(x)
$<linear-approx>
]
#let diffI(y, h) = $I_((#y, #h))$
#theorem[][
在上面的命题中,有:
$
hu_(l i) = diffI(x_(l i), h_l) u(x) \
where diffI(y, h) u(x) = u(y) - 1/2(u(y-h) + u(y+h))
$
]
#proof[
注意到 $I$ 具有线性,以 $I$ 作用于 @linear-approx 将有:
$
diffI(x_(l i), h_l) u(x) = sum_(l'=1)^L sum_(i' in oddl) hu_(l' i') diffI(x_(l i), h_l) (Phi_(l' i')(x) )
$
只需计算:
$
diffI(x_(l i), h_l) (Phi_(l' i')(x) ) = Phi_(l' i')(x_(l i)) - 1/2(Phi_(l' i')(x_(l i) - h_l) + Phi_(l' i')(x_(l i) + h_l))\
$
- $l' < l$ 时,$x_(l i) plus.minus h_l$ 一定落在 $Phi_(l' i')$ 中的同一个线性分支上(线性增加/减少/支集之外),观察 $I$ 的表达式可得一定为零
- $l' > l$ 时,观察发现 $x_(l i) plus.minus h_l$ 在高层基函数的取值均为零,当然也是零
- $l = l'$ 时,由不重叠性非零除非 $i = i'$,此时 $Phi_(l' i')(x_(l i) + h_l) = 1$
综上,$Phi_(l' i')(x_(l i) + h_l) = delta_(i, i') delta_(l, l')$,代回即可得到所证式子
]
#corollary[][
在上面的命题中,有:
$
hu_(l i) = integral_(0)^(1) (-1/2) 2^(-l) Phi_(l, i) (x) u''(x) dif x
$
]
#proof[
$
integral_(0)^(1) (-1/2) 2^(-l) Phi_(l, i) (x) u''(x) dif x
&= - 2^(-l-1) integral_(x_l^i - h_l)^(x_l^i + h_l) Phi_(l, i) (x) u''(x) dif x\
&"(利用分部积分计算并展开)"\
&= - 2^(-l-1) (integral_(x_l^i - h_l)^(x_l^i ) (u'(x))/(h_l) dif x - integral_(x_l^i )^(x_l^i + h_l ) (u'(x))/(h_l) dif x)\
&= - 1/2 (integral_(x_l^i - h_l)^(x_l^i ) u'(x) dif x - integral_(x_l^i )^(x_l^i + h_l ) u'(x) dif x)\
&= diffI(x_(l i), h_l) u(x)
$
]
#let lv = $bold(l)$
类似的,对于高维的情形我们也希望做类似处理。此时,我们用一个向量 $lv$ 表示在每个方向的划分层数(例如 $(2, 3)$ 表示 $x$ 方向划分两层,$y$ 方向划分三层)。高维情形下,有结论:
#lemma[][
$
hu_(lv, xv) = integral_(Omega) (-1/2)^(d) 2^(- norm(lv)_1) Phi_(lv, xv) (x) D^(bold(2)) u(x) dif x
$
其中:
- $D^(bold(alpha)) u(x) = (partial^(norm(alpha)_1) u)/(partial x_1^(alpha_1) ... partial x_n^(alpha_n))$
]<int_approx>
#proof[
它可以化归到一维情形,这里不做详细证明
]
#let nv = $bold(n)$
#let iv = $bold(i)$
#let onev = $bold(1)$
#let twov = $bold(2)$
#let vninf = $V_n^((infinity))$
#let vn1 = $V_n^((1))$
接下来,讨论全网格和稀疏网格。记:
$
vninf &:= V_nv = plus.circle_(1 <= lv <= nv) w_lv = plus.circle_(norm(l)_infinity <= n) w_lv\
where nv &= vec(n, n, dots.v, n)\
1& = vec(1, 1, dots.v, 1)\
alpha <= beta &<=> alpha_i <= beta_i, forall i
$
这是全网格,而*稀疏网格*是:
$
vninf = plus.circle_(norm(l)_1 <= d + (n-1)) w_lv
$
意指每个维度所分层数总和不超过一定的上界。
仍然要回答网格是否稀疏,精度是否保持两个问题。稀疏性看起来比较简单,有如下结论:
#theorem[两种网格的稀疏性][
$
abs(vninf) = O(N^d)\
abs(w_lv) = 2^(norm(lv)_1 - d)\
abs(vn1) = O(N (log N)^(d-1))\
where N = 2^n
$
]
#proof[
- $vninf$ 的结论是容易的,既然在每个维度上都做 $2^n$ 等分
- $w_lv$ 中,每个维度的基个数恰为 $2^(l_i)$ 的一半,计算可得就是 $2^(norm(lv)_1 - d)$
- 最后来讨论 $vn1$,有:
$
abs(vn1) = sum_(i <= d + (n-1)) 2^(i - d) C_(i - 1)^(d-1)
$
这个组合数来自于将 $norm(l)_1$ 的层数总和任意分给 $d$ 个维度的分球问题。大致估计有:
$
sum_(i <= d + (n-1)) 2^(i - d) C_(i - 1)^(d-1) &<= sum_(i <= d + (n-1)) 2^(i - d) C_(d-1+n-1)^(d-1)\
&= 2^n C_(d-1+n-1)^(d-1)\
&= 2^n (n(n-1)...(n+d-2))/(d-1)! \
&= O(2^n n^(d-1))\
&= O(N (log N)^(d-1))
$
]
#theorem[两种网格的精度][
给定性质足够好的函数 $u$ ,令:
$
u_n^((infinity)) := sum_(norm(lv)_infinity <= n) u_(lv) (xv)\
u_n^((1)) := sum_(norm(lv)_1 <= d+ n-1) u_(lv) (xv)\
where u_lv (xv) = sum_(iv in oddl) hu_(lv iv) Phi_(lv iv) (xv)
$
则有:
$
norm(u-u_n^((infinity)))_infinity <= d/6^d 2^(-2n) norm(u)_(twov, infinity)\
norm(u-u_n^((1)))_infinity <= d/8^d 2^(-2n) A(d, n) norm(u)_(twov, infinity)\
$
其中:
- $A(d, n)$ 的量级约为 $n^(d-1)$
- $u$ 可以被展开为:
$
u = sum_(lv in NN^d) u_(lv)
$
- $norm(u)_(alpha, infinity) := norm(D^alpha u)_infinity$
]
#proof[
#lemmaLinear[][
$
norm(u_lv)_infinity <= (-1/2)^(d) 2^(- 2norm(lv)_1) norm(u)_(twov, infinity)
$
]
#proof[
$
norm(u_lv)_infinity &= norm(sum_(iv in oddl) hu_(lv iv) Phi_(lv iv) (xv))_infinity\
&<= max_(iv in odd l){abs(hu_(lv iv))} norm(sum_(iv in oddl) Phi_(lv iv) (xv))_infinity
$
回忆 $Phi_(lv iv)$ 的定义和嵌套分层方式,上式的求和不会大于 $1$,并且代入 @int_approx 将有:
$
norm(u_lv)_infinity <= max_(iv in odd l){abs(hu_(lv iv))}\
<= max_(iv in odd l){abs(integral_(Omega) (-1/2)^(d) 2^(- norm(lv)_1) Phi_(lv, xv) (x) D^(bold(twov)) u(x) dif x)}\
<= (-1/2)^(d) 2^(- norm(lv)_1) max_(iv in odd l){abs(integral_(Omega) Phi_(lv, xv) (x) D^(bold(twov)) u(x) dif x)}\
<= (-1/2)^(d) 2^(- norm(lv)_1) max_(iv in odd l){integral_(Omega) abs(Phi_(lv, xv) (x) D^(bold(twov)) u(x) dif x)}\
<= (-1/2)^(d) 2^(- norm(lv)_1) norm(u)_(twov, infinity) max_(iv in odd l){integral_(Omega) abs(Phi_(lv, xv) (x) dif x)}\
<= (-1/2)^(d) 2^(- norm(lv)_1) norm(u)_(twov, infinity) 2^(- norm(lv)_1)\
<= (-1/2)^(d) 2^(- 2norm(lv)_1) norm(u)_(twov, infinity) \
$
这里积分的计算是观察每一个维度上三角形的面积得到的。
]
- 回到定理,先证明全网格的形式。有:
$
norm(u-u_n^((infinity)))_infinity &= norm(sum_(norm(lv) >= n) u_lv)_infinity\
&<= sum_(norm(lv) >= n) norm(u_lv)_infinity\
&<= sum_(norm(lv) >= n)(-1/2)^(d) 2^(- 2norm(lv)_1) norm(u)_(twov, infinity)\
&<= (-1/2)^(d) norm(u)_(twov, infinity) sum_(norm(lv) >= n) 2^(- 2norm(lv)_1) \
$
其中 $sum_(norm(lv) > n) 2^(- 2norm(lv)_1)$ 的多维的等比级数,交换顺序计算可得上式:
$
<= 6^(-d) norm(u)_(twov, infinity) (1-(1-4^(-n))^d) <= 1/6^d 4^(-n) norm(u)_(twov, infinity)
$
上面利用了伯努利不等式,这就是结论
- 再处理稀疏网格的形式,完全类似的过程有:
$
norm(u-u_n^((1)))_infinity <= (-1/2)^(d) norm(u)_(twov, infinity) sum_(norm(lv)_1 >= d+(n-1)) 2^(- 2norm(lv)_1)
$
这里我们再次利用分球的组合技巧,有:
$
sum_(norm(lv)_1 >= d+(n-1)) 2^(- 2norm(lv)_1) &= sum_(i >= d+(n-1)) 2^(- 2i) C_(i - 1)^(d-1)\
&<= 4^(-n-d) dot 2 A(d, n)
$
这里 $A(d, n)$ 是与组合相关的函数,这里不再详细叙述。代回计算可得结论成立
]
从上面的定理可以看出,稀疏网格理所应当的用精度的降低换来了效率的提升。
== 数值积分、Gauss 积分公式
#let xspace(x) = $#x space$
#let Is = $xspace(I)$
#let Rs = $xspace(R)$
#let Qs = $xspace(Q)$
在许多数学分支中,高维积分的计算都是很重要的问题。例如函数的分解往往涉及在若干基上的投影,而投影往往需要设计内积也就是高维函数的积分进行表示。\
通常的积分问题可以表示为:
$
integral_(Omega)^() u(x) w(x) dif x
$
其中 $Omega$ 是积分区域,$w$ 是给定权函数。方便起见,记:
$
Is u = integral_(Omega)^() u(x) w(x) dif x
$<N-integral>
=== 一维情形
我们先考虑如何计算一维的积分
#lemma[][
- 闭区间上黎曼可积函数可被连续函数 $L^1$ 逼近
- 闭区间上连续函数可被多项式函数一致逼近
]
由上面两个引理,我们可以知道只要找到逼近可积函数的多项式函数就可以得到积分的逼近。对于有解析表达式的函数这样的方法非常常见,例如最简单的解析函数可以被泰勒级数展开,再计算级数的积分即可。这种思路可以被称之为*拟合*。
==== 拉格朗日插值
然而,许多时候函数是由网格点给出的,此时我们需要采用*插值*的思路,我们希望给出插值多项式 $p(x)$ 使得在 $N + 1$ 个点上有 $p(x) = u(x)$,事实上,这样的多项式唯一存在。
#definition[Lagrange 插值][
给定函数 $u$ 和插值点 $x_0, x_1, ..., x_n$,称:
$
h(x) = sum_(i=0)^N u(x_i) h_i (x)\
where h_i (x) = product_(0 <= j <= N, j!= i) (x - x_j)/(x_i - x_j)
$
为 Lagrange 插值,且有 $h(x_i) = u(x_i)$,其中 $h_i (x)$ 也被称为基函数或者形函数
]
#theorem[][
若 $u(x) in C^(N+1) ([a, b])$,则对任意 $x in [a, b]$,存在 $xi in [a, b]$ 使得:
$
u(x) = h(x) + r(x)\
where r(x) = 1/(N+1)! u^((N+1)) (xi) product_(i=0)^N (x - x_i)
$
其中 $r(x)$ 也称作残量
]
#proof[
反复使用罗尔定理即可,具体参考数学分析课程
]
#definition[数值积分公式][
用上式估计@N-integral 可得:
$
integral_(a)^(b) u(x) w(x) dif x\
= integral_(a)^(b) h(x) w(x) dif x + integral_(a)^(b) r(x) w(x) dif x\
= sum_(i=0)^N u(x_i) integral_(a)^(b) h_i (x) w(x) dif x + integral_(a)^(b) r(x) w(x) dif x\
$
令:
$
w_i = integral_(a)^(b) h_i (x) w(x) dif x\
Q u := sum_(i=0)^N u(x_i) w_i dif x\
R u := integral_(a)^(b) r(x) w(x) dif x
$
用 $Q u$ 计算 $I u$ 的方法称为数值积分公式。
]<Lang-integral>
为了衡量数值积分公式的好坏,一种方式是所谓的*代数精度*,它利用了试验函数的方法,利用公式在某种具体函数上的表现来衡量精度
#definition[代数精度][
对于一般的数值积分公式,设其逼近函数 $u$ 产生残量为 $R u$,若自然数 $m$ 使得:
- 任意不高于 $m$ 次的多项式 $f(x)$ 都有 $R f = 0$
- 存在 $m+1$ 次多项式使得 $R f != 0$
则称该数值积分公式有 $m$ 阶代数精度
]<algebra-precision>
#proposition[][
@Lang-integral 具有至少 $N$ 阶代数精度,且精度不超过 $2 N + 1$
]
#proof[
- 一方面,显然不高于 $N$ 阶的多项式都可以被拉格朗日插值精确逼近,因此对这些 $f$ 一定有 $Q f = 0$,换言之公式至少具有 $N$ 阶代数精度
- 另一方面,考虑 $u := product_(0 <= i <= N) (x-x_i)^2$,显然 $I u > 0, Q u = 0 => R u != 0$,这是 $2 N +2 $ 次代数精度,因此代数精度不超过 $2 N + 1$
]
注意到在 @Lang-integral 中,$w_i$ 事实上只与 $x_i$ 有关,因此自然的想法是选取更加合适的 $x_i$ 以获得更好的代数精度。
==== 高斯积分
#theorem[][
设 $P_(N+1)$ 是 $N+1$ 次(在给定的区间和权函数下的)正交多项式,取 $x_i$ 是 $P_(N+1)$ 的某个零点,则这样的零点恰有 $N+1$ 个,且 @Lang-integral 的数值精度恰为 $2N + 1$
]<Gauss-integral>
#proof[
任取不高于 $2N + 1$ 次多项式 $p$,利用辗转相除法有:
$
p = a(x) P_(N+1) (x) + b(x)
$
其中 $deg b(x) <= N, deg a(x) <= N$
此时有:
$
I p &= integral_(a)^(b) a(x) P_(N+1) (x) + b(x) dif x\
&= integral_(a)^(b) b(x) dif x\
&"(正交多项式比次数更低的多项式都正交)"\
&= Q b\
&= sum_i b(x_i) w_i\
&= sum_i (p(x_i) - a(x_i) P_(N+1) (x_i)) w_i\
&= Q p
$
至于零点个数,设 $x_1, x_2, ..., x_m$ 是所有不同的奇数次零点,则:
$
integral p_(N+1) (x) (x-x_1) (x-x_2) ... (x - x_m) dif x > 0
$
表明 $(x-x_1) (x-x_2) ... (x - x_m)$ 至少 $N+1$ 次,进而 $m = N + 1$,当然这些零点只能是一重零点并且没有其他的偶次零点
]
从实用性角度,我们希望正交多项式是便于计算的,之后无论利用何者方法,只需求出该多项式的零点,对于任何函数在给定区间上的加权积分都可以直接计算。
#lemma[][
给定区间和权函数,则存在唯一首一正交多项式列 ${p_n}$ 使得 $deg p_n = n, n = 0, 1, 2, ...$
]
#proof[
- 对于存在性,直接对 $generatedBy(1\, x\, ...\, x^n\, ... )$ 从低次到高次进行施密特正交化,观察施密特正交化的算法可得次数的条件也是满足的。
这里我们也可以采用与一般的施密特正交化在形式上略微不同的三项递推形式。事实上,假设 $p_(n), p_(n-1)$ 已经求得,由带余除法我们希望有如下的形式:
$
p_(n+1) = (x + a_n) p_n + r_n (x)
$
不难看出 $r_n (x)$ 将与 $1, x, ..., x^(n-1)$ 都正交,继而不妨取 $r_n = b_n p_(n-1) (x)$,有:
$
p_(n+1) = (x + a_n) p_n + b_n p_(n-1) (x)
$<recurrence>
为了求出待定的 $a, b$,直接做内积可得:
$
inner(p_(n+1), p_n) = 0 = inner(x p_n, p_n) + a_n inner(p_n, p_n) \
inner(p_(n+1), p_(n-1)) = 0 = inner(x p_n, p_(n-1)) + b_n inner(p_(n-1), p_(n-1))
$
反解出对应的 $a_n, b_n$ 即可
- 对于唯一性,注意到 $p_n$ 落在 $generatedBy(1\, x\, ...\, x^n)$,且与 $1, x, ..., x^(n-1)$ 都正交,继而落在 $generatedBy(1\, x\, ...\, x^(n-1))$ 的正交补空间之中,这个正交补空间仅有一维,因此两两之间只差常数,继而其中首一的多项式唯一
]
#lemma[][
正交多项式 $p_(n+1)$ 的根恰好是对称三对角矩阵:
$
mat(alpha_0, beta_1, 0, ..., 0;
beta_1, alpha_1, beta_2, ..., 0;
0, beta_2, alpha_3, ..., 0;
dots.v, dots.v, dots.v, ..., dots.v;
0, ..., 0, beta_(n), alpha_n)
$
的所有特征值,其中:
$
alpha_i = - a_i, beta_j = sqrt(inner(p_j, p_j)/inner(p_(j-1), p_(j-1)))
$
($a_i, b_i$ 是上面证明中定义的对应系数,也即@recurrence 中的相应系数)
]
#proof[
#let tp = $tilde(p)$
#lemmaLinear[][
$
-b_j norm(p_(j-1))/norm(p_j) = beta_j
$
]
#proof[
即是证明:
$
b_j = - inner(p_j, p_j)/inner(p_(j-1), p_(j-1))
$
事实上,在@recurrence 两边做内积立得:
$
inner(p_(n+1), p_(n+1)) = inner(p_(n+1), x p_n), forall n
$
因此:
$
b_j &= - inner(x p_j, p_(j-1)) / inner(p_(j-1), p_(j-1)) \
&= - inner(p_j, x p_(j-1)) / inner(p_(j-1), p_(j-1))\
&= - inner(p_j, p_j) / inner(p_(j-1), p_(j-1))\
$
证毕
]
设 $tp_j = 1/sqrt(inner(p_j, p_j)) p_j$,显有 $norm(tp_j) = 1$,上面证明中的递推式变成:
$
norm(p_(j+1)) tp_(j+1) &= x norm(p_j) tp_j + a_j norm(p_j) tp_j + b_j norm(p_(j-1)) tp_(j-1) \
x tp_j &= norm(p_(j+1))/norm(p_j) tp_(j+1) - a_j tp_j - b_j norm(p_(j-1))/norm(p_j) tp_(j-1)\
&= beta_(j+1) tp_(j+1) + alpha_j tp_j - b_j norm(p_(j-1))/norm(p_j) tp_(j-1)\
&= beta_(j+1) tp_(j+1) + alpha_j tp_j + beta_j tp_(j-1)
$
将上式排成向量,(再检查 $p_0$ 的特殊情形)即得:
$
x vec(tp_0, tp_1, tp_2, dots.v, tp_n) = mat(alpha_0, beta_1, 0, ..., 0;
beta_1, alpha_1, beta_2, ..., 0;
0, beta_2, alpha_3, ..., 0;
dots.v, dots.v, dots.v, ..., dots.v;
0, ..., 0, beta_(n), alpha_n) vec(tp_0, tp_1, tp_2, dots.v, tp_n) + beta_(n+1) tp_(n+1) vec(0, dots.v, 0, 1)
$
任取 $p_(n+1)$ 的根 $x_j$ 将有:
$
x_j vec(tp_0 (x_j), tp_1 (x_j), tp_2 (x_j), dots.v, tp_n (x_j)) = mat(alpha_0, beta_1, 0, ..., 0;
beta_1, alpha_1, beta_2, ..., 0;
0, beta_2, alpha_3, ..., 0;
dots.v, dots.v, dots.v, ..., dots.v;
0, ..., 0, beta_(n), alpha_n) vec(tp_0 (x_j), tp_1 (x_j), tp_2 (x_j), dots.v, tp_n (x_j))
$
表明对所有 $N + 1$ 个 $j$,$x_j$ 都是特征值,证毕
]
使用 @Gauss-integral 的方法计算积分便称为 *Gauss 积分公式*
=== 高维情形
Gauss 积分公式已经能很好地解决一维积分的问题,然而更高维的数值积分至今仍是比较困难的问题。高维积分的方式大致可以分为两种方案:
+ 仍然基于多项式(仍是通过巧妙选择格点获得好的代数精度,它类似于谱方法利用正交性获得方便的全局逼近)
+ 基于数论的方法,如 Monte Carlo, Quasi-Monte Carlo (类似于网格点方法)
==== 多项式方法
#let pnd(n) = $PP_(#n)^d$
在这节,我们约定序号从 $1$ 开始,并记 $pnd(n)$ 为所有不超过 $n$ 次的 $d$ 维多项式全体。类似 @algebra-precision 定义:
#definition[代数精度,高维][
对于一般的数值积分公式,设其逼近函数 $u$ 产生残量为 $R u$,若自然数 $m$ 使得:
- $Rs pnd(m) = {0}$
- $Rs pnd(m+1) != {0}$
则称该数值积分公式有 $m$ 阶代数精度
]
我们希望获得类似 Gauss 公式的结果,令 $Q f$ 具有 $2 n - 1$ 阶代数精度,需要解决:
- 此时需要多少个积分点
- 积分点如何选取
下设积分点个数为 $N$,分别为 $x_1, x_2, ..., x_N$
#proposition[][
若 $Q f$ 有 $2n-1$ 阶代数精度,则 $N >= dim pnd(n-1)$
]
#let dm = $dim pnd(n-1)$
#proof[
#let sumi = $sum_(i=1)^dm$
如若不然,设 $N < dm$,取 $pnd(n-1)$ 的一组基 $p_1, p_2, ..., p_dm$\
我们希望 $p in pnd(n-1)$ 使得 $x_1, x_2, ..., x_N$ 都是它的零点,先设:
$
p(x) = sumi c_i p_i (x)
$
代入得:
$
sumi c_i p_i (x_j) = 0\
$
将其看成 $c_i$ 的线性方程,由于 $N < dm$,未知数的个数小于方程的个数,因此一定有非零解 $c_i$,这组解便产生了 $p$ 使得 $x_1, x_2, ..., x_N$ 都是零点。类似之前的操作,有:
$
I p^2 > 0\
Q p^2 = 0
$
表明代数精度将小于 $2 deg p = 2 n - 2$ ,矛盾!
]
然而,利用组合方法可以计算得到 $dim pnd(n-1) = C_(n-1+d)^d = O(n^d)$ ,这已经是非常巨大的数字。即便如此,下面也将证明这样的的下界也难以取得。
#definition[Gauss 公式,高维][
称 $Q f$ 是 $d$ 维 Gauss 公式,如果取 $N = dim pnd(n-1)$ 时有 $2 n -1$ 阶代数精度。
]
#let tpnd(n) = $tilde(pnd(n))$
#definition[正交多项式,高维][
设:
$
tpnd(n) = {f in pnd(n) | forall g in pnd(n-1), inner(f, g) = 0}
$
为 $n$ 次 $d$ 维正交多项式的全体,也即与所有次数不超过 $n-1$ 的多项式都正交的多项式。显然 $tpnd(n)$ 中所有多项式都是 $n$ 次(否则与自己正交)
]
#proposition[][
$d$ 维 Gauss 公式存在当且仅当所有的 $n$ 次 $d$ 维正交多项式拥有 $dim pnd(n-1)$ 个共同零点
]
#proof[
#let pndo(n, d) = $tilde(PP)_(#n)^(#d)$
记所有的 $n$ 次 $d$ 维正交多项式为 $pndo(n, d)$
- 假设高斯公式存在,对 $pnd(n-1)$ 中所有(不超过 $n-1$ 次的单项式)做 Schmidt 正交化和归一化,可以得到 $N = dm$ 个标准正交的多项式。此时当然有 $inner(q_i, q_j) = delta_(i, j)$\
注意到:
$
inner(q_i, q_j) = integral q_i q_j w
$
被积函数至多 $2 n - 2$ 次,因此不超过高斯公式的代数精度,进而:
$
sum_(k=1)^N w_k q_i (x_k) q_j (x_k) = Q q_i q_j = delta_(i, j)
$
将其写成矩阵的形式,将有:
$
A^T W A = I, where A_(i, j) = q_j (x_i)\ W = "diag"(w_1, ..., w_dm)
$
立得 $A$ 可逆。设:
$
Inv(A) = (c_1, ..., c_dm)
$
设 $p_i (x_k) = A(x_k) c_i = delta_(i, k)$,它是 $n-1$ 次多项式,因此任取 $f in pndo(n, d)$:
$
0 = integral p_i f
$
同时,上式不超过高斯公式的代数精度,继而:
$
0 = Q p_i f = sum_(k=1)^dm w_k p_i (x_k) f(x_k) = w_i f(x_i)
$
当然 $w_i != 0$,故 $f(x_i) = 0$,取遍 $i$ 即得结论成立
- 假设有共同零点 $x_1, ..., x_(dm)$,同样考虑类似上面的矩阵 $A$,任取非零向量 $c$ 并令:
$
g(x) = (q_1 (x), ..., q_(dm) (x)) c
$
注意到 $g$ 是 $n-1$ 次多项式,由假设 $x_1, ..., x_dm$ 不全为其零点,这就表明 $A c != 0$,进而 $A$ 是满秩矩阵,下面的线性方程:
$
A^T vec(w_1, dots.v, w_dm) = vec(integral q_1 w, dots.v, integral q_dm w)
$
有唯一解。这个解对应的积分公式至少 $n - 1$ 阶代数精度,而任取不超过 $2 n - 1$ 阶的 $d$ 维多项式 $f$,可将 $f(x)$ 分解为:
$
sum_(i = 1)^K h_i (x) g_i (x) + r(x)
$
其中 $g_i (x) in pndo(n, d), h_i (x) in pnd(n)$,类似一维情形简单计算可得具有积分公式在 $f$ 上准确,因此具有 $2 n - 1$ 阶代数精度
]
#corollary[][
若上述高斯公式存在,则系数 $w_i > 0$
]
#proof[
证明过程给出 $A^T "diag"(w_1, ..., w_dm) A = I$,由矩阵合同的惯性定理立得
]
上面命题表明扩展一维构造高斯积分公式的方式是非常困难的。当然,构造 $m$ 阶代数精度的数值逼近公式也可以通过直接列方程的方式。设 $D$ 是所有不超过 $m$ 阶单项式构成的集合,考虑:
$
sum_(d in D) c_d d (x_i) = integral_()^() d , i = 1, 2, ..., N
$
假设可以找到 $x_i$ 和 $c_d$ 使得上式成立,对应便给出具有 $m$ 阶代数精度的数值积分公式。上面的方程的未知量包括 $N$ 个 $d$ 维向量和 $N$ 个一维系数,总计 $N(d + 1)$ 维未知量,$m$ 个(多项式)方程,这当然是不好解决的。
==== 基于数论方法的高维积分公式
#let sumn0(i) = $sum_(#i = 0)^(n-1)$
上一节的内容表明对于高维积分强求精确的代数精度(对于多项式精确求解)是困难的,我们希望退一步舍弃一些精度。本节讨论的内容都默认积分是不带权函数的,同时设积分区域为:
$
Omega = [0, 1]^d
$
也就是只考虑标准的积分:
$
I f = integral_(Omega = [0, 1]^d)^() f(x) dif x
$
一般的积分可以通过各种变换得到,在此略去。
我们的数值积分公式仍然形如:
$
Q f = sumn0(i) c_i f(x_i)
$
由于积分是均匀的,不妨设 $c_i = 1/n$,进而公式形如:
$
Q f = 1/n sumn0(i) f(x_i)
$<Qf2>
#theorem[Monte Carlo 的均方根误差][
设 $x_i$ 独立服从 $[0, 1]^d$ 上的均匀分布,则对所有平方可积函数 $f(x)$ 有:
$
E (Q f) = I f\
sigma(R f) := sqrt(E (I f - Q f)^2) = (sigma(f))/sqrt(n) where sigma(f) = sqrt(I f^2 - (I f)^2)
$
]
#proof[
$
E (I f - Q f)^2 = E (Q f)^2 - 2 I f E (Q f) + (I f)^2
$
有:
-
$
E (Q f)
&= integral Q f dif t\
&= 1/n sumn0(i) integral f(t_i) dif t\
&= 1/n sumn0(i) integral f(t_i) dif t_i\
&= I f\
$
-
$
E (Q f)^2
&= integral (Q f)^2 dif t\
&= 1/n^2 sumn0(i) sumn0(j) integral f(t_i)f(t_j) dif t\
&= 1/n^2 (sumn0(i) integral f(t_i)^2 dif t + sumn0(i) sum_(j != i) integral f(t_i)f(t_j) dif t)\
&= 1/n^2 (n I f^2 + (n(n-1)) (I f)^2)\
&= (I f^2)/n + (n-1)/n (I f)^2
$
代入得:
$
E (I f - Q f)^2
&= E (Q f)^2 - 2 (I f)^2 + (I f)^2 \
&= (I f^2)/n + (n-1)/n (I f)^2 - (I f)^2 \
&= (I f^2 - (I f)^2)/n
$
证毕
]
定理表明这确实可以逼近,并且这里与 $d$ 是无关的,没有维度灾难的问题。然而,$sqrt(n)$ 的收敛阶有些过于糟糕,并且已经证明收敛阶对于平方可积函数、连续函数不能够再改进了。因此,优化 Monte Carlo 公式的方向是:
- 减小 $f$ 的方差以降低误差的系数。
- 提高 $f$ 的光滑性要求,并利用之前确定性网格方法的思想给出更好的随机取点方法。
#example[Quasi-Monte Carlo,一维情形][
先在一维情形下找到思路,我们先假设 $f in C^r$,之后视需要决定 $r$\
注意到:
$
f(x) = f(1) - integral_(x)^(1) f'(y) dif y\
= f(1) - integral_(0)^(1) i_(y > x) f'(y) dif y
$
从而:
$
I f - Q f = f(1) - integral_0^1 dif x integral_(0)^(1) i_(y > x) f'(y) dif y - 1/n sumn0(i) f(x_i)\
= f(1) - integral_0^1 dif x integral_(0)^(1) i_(y > x) f'(y) dif y - 1/n sumn0(i) f(x_i)\
= f(1) - integral_0^1 dif x integral_(0)^(1) i_(y > x) f'(y) dif y - 1/n sumn0(i) f(1) - integral_(0)^(1) i_(y > x_i) dif y\
= integral_(0)^(1) (1/n sumn0(i) 1_(y > x_i) - integral_(0)^(1) 1_(y > x) dif x) f'(y) dif y
$
设 $P = {t_0, ..., t_(n-1)}$ 是一个取点方案,记:
$
(1/n sumn0(i) 1_(y > x_i) - integral_(0)^(1) 1_(y > x) dif x) := Delta_p (y)
$
则有:
$
abs(I f - Q f) &<= integral_0^1 abs(Delta_p (y)) abs(f'(y)) dif y\
&<= sup_y abs(Delta_p (y)) integral_0^1 abs(f'(y)) dif y\
&= sup_y abs(Delta_p (y)) V(f)
$
]
#theorem[Koksma-Hlawka 不等式][
设 $f(x)$ 满足:
$
(diff^d)/(diff x_1 diff x_2 ... diff x_n) f in C(Omega)
$
则对任意取点方案 $P$ 均有:
$
abs(I f - Q f) <= sup_y abs(Delta_p (y)) V(f) := D_n^* (P) V(f)
$
其中 $V(f)$ 是 Koksma-Hlawka 变差
]
#proof[
思路与上面的例子类似,证明略
]
接下来的任务是尽可能改进 $D_n^* (P)$,回顾定义:
$
1/n sumn0(i) 1_(y > x_i) - integral_(0)^(1) 1_(y > x) dif x
$
后者是 $[0, y]$ 的长度,前者是在某种取点方法下 $x_i$ 落在 $[0, y]$ 中的个数的比例。显然假如 $x_i$ 是任取的,则前者的期望就是后者。高维情形这些长度都换成体积,定义为:
$
1/n sumn0(i) 1_(y > x_i) - product_(j=1)^d y_j
$
#let j0inf = $sum_(j = 0)^infinity$
#definition[低偏差序列,Halton 序列][
$d = 1$ 时,任取正整数 $b >= 2$,令:
$
z_b = {0, 1, ..., b-1}
$
是模 $b$ 剩余类,对于任意正整数 $n$,定义 $n$ 的 $b$ 进制表示为:
$
n = j0inf a_j (n) b^j
$
(本质是有限和,只是写成了无限的形式)\
令:
$
Phi_b (n) = j0inf a_j (n) b^(- j - 1)
$
也就是将 $b$ 进制关于小数点取对称\
令:
$
(x_0, x_1, ..., x_n) := (Phi_b (0), Phi_b (1), ..., Phi_b (n - 1)) in [0, 1]^n
$
称为一维 Halton 序列
对 $d >= 2$,取 $b_1, b_2, ..., b_d >= 2$,令:
$
x_i = (Phi_(b_1) (i), Phi_(b_2) (i), ..., Phi_(b_d) (i)) in [0, 1]^d, forall i = 0, 1, 2, ..., n-1
$
为 $d$ 维 Halton 序列
]
作业题将证明,如果 $x_i$ 就取 Halton 序列,可以保证:
$
D_n^* (P) = O((log n)^d/n)
$
收敛阶比之前的 $1/sqrt(n)$ 好不少
== 有效维数
看似 QMC 对高维积分的效果也并不理想,然而历史上人们发现它对某个特定的 360 维积分有着出乎意料的表现,引发了人们对于高维积分是否可以某种意义上降低维度的有效维度问题。
=== 方差分析|Analysis Of Variants
本节中:
- 记 $ZZ_d = {1, 2, ..., d}$
- 设 $u subset ZZ_d$,$abs(u)$ 表示 $u$ 中个数
- $xv_u := (x_j)_(j in u)$
- $ZZ_d - u := -u$
#theorem[ANOVA][
给定 $Omega = [0, 1]^d, Omega$ 上的函数有 ANOVA 分解:
$
f(xv) = sum_(u subset ZZ_d) f_u (xv)
$
其中 $f_u$ 仅依赖于 $xv_u$
]
#proof[
递归定义:
- $abs(u) = 0$ 时,令 $f_(emptyset) (xv) = integral_(Omega)^() f(xv) dif xv := mu$
- $abs(u) = 1$ 时,设 $u = {j}$,令:
$
f_{j} (xv) = integral_([0,1]^(d-1)) (f(xv) - mu) dif xv_(-u)
$
也就是把除了 $j$ 之外的维度全部积分掉,这样便只依赖于 $j$ 分量
- 一般的,令:
$
f_u (xv) = integral_([0,1]^(d - abs(u))) (f(xv) - sum_(v subset.neq u) f_v (xv)) dif xv_(-u)
$
观察到它事实上等于:
$
integral_([0,1]^(d - abs(u))) f(xv) dif xv_(-u) - sum_(v subset.neq u) f_v (xv)
$
这是因为积分变元和后者无关,因此可以直接积分出来。这便给出了:
$
f_(ZZ_d) (xv) &= 0 - sum_(v subset.neq ZZ_d) f_v (xv) = f(xv)\
f(xv) &= f_(ZZ_d) (xv) + sum_(u subset.not ZZ_d) f_u (xv)\
&= sum_(u subset ZZ_d) f_u (xv)
$
]
#proposition[正交性][
+ $j in u => integral_0^1 f_u (xv) dif x_j = 0$
+ $u != v => integral_(Omega)^() f_u (xv) g_u (xv) dif xv = 0 $
]
#proof[
+
- $abs(u) = 1$ 时,有:
$
integral_0^1 f_{j} (xv) dif x_j &= integral_0^1 integral_([0, 1]^(d-1))^() (f(xv) - mu) dif xv_(-{j}) dif x_j\
&= integral_(Omega)^() f(xv) dif xv - mu\
&= 0
$
- 对一般情形递归验证:
$
integral_0^1 f_u (xv) dif x_j &= integral_0^1 (integral_([0,1]^(d - abs(u))) f(xv) dif xv_(-u) - sum_(v subset.neq u) f_v (xv)) dif x_j\
&= integral_([0,1]^(d - abs(u) + 1)) f(xv) dif xv_(-u union {j}) - sum_(v subset.neq u) integral_0^1 f_v (xv) dif x_j
$
注意到,若 $j in v$ 则由归纳假设后项积分为零,上式化简为:
$
&integral_([0,1]^(d - abs(u) + 1)) f(xv) dif xv_(-u union {j}) - sum_(v subset.neq u, j in.not v) integral_0^1 f_v (xv) dif x_j\
=&integral_([0,1]^(d - abs(u) + 1)) f(xv) dif xv_(-u union {j}) - sum_(v subset.neq u, j in.not v) f_v (xv) \
=&integral_([0,1]^(d - abs(u) + 1)) f(xv) dif xv_(-(u - {j})) - sum_(v subset (u - {j})) f_v (xv) \
=&integral_([0,1]^(d - abs(u) + 1)) f(xv) dif xv_(-(u - {j})) - sum_(v subset.neq (u - {j})) f_v (xv) + f_(u - {j}) (xv) \
=&f_(u - {j}) (xv) - f_(u - {j}) (xv) \
=&0
$
这里是代入了 $f_(u - {j}) (xv)$ 的定义,进而结论成立。
+
由 $u != v$ 不妨设 $j in u - v$,将有:
$
integral_(Omega)^() f_u (xv) f_v (xv) dif xv &= integral_([0, 1]^(d-1))^() integral_(0)^(1) f_u (xv) f_v (xv) dif xv_j dif xv_(-j)\
&= integral_([0, 1]^(d-1))^() f_v (xv) (integral_(0)^(1) f_u (xv) dif xv_j) dif xv_(-j)\
&= 0
$
最后一步利用了之前的命题
]
#definition[方差][
定义函数 $f$ 的方差:
$
sigma^2 (f) = integral_(Omega)^() (f(xv) - mu)^2 dif xv where mu = integral_(Omega)^() f(xv) dif xv
$
同时在上面的方差分解中,定义:
$
sigma^2_u (f) = cases(
integral_([0, 1]^d)^() f^2_u (xv) dif xv quad u != emptyset,
0 quad u = emptyset
)
$
]
#theorem[][
$
sigma^2 (f) = sum_(u subset.neq ZZ_d) sigma^2_u (f)
$
]
#proof[
$
integral_(Omega)^() (f(xv) - mu)^2 dif xv = integral_(Omega)^() (sum_(u subset.neq ZZ_d, u != emptyset) f_u (xv) )^2 dif xv
$
由前面命题的正交性,上式就是:
$
sum_(u subset.neq ZZ_d, u != emptyset) integral_(Omega)^() f_u^2 (xv) dif xv = sum_(u subset.neq ZZ_d) sigma^2_u (f)
$
]
=== 有效维数
#definition[有效维数][
称 $d_0$ 是函数 $f(xv)$ 的有效维数,如果 $d_0$ 是使:
$
sum_(abs(u) <= d_0) sigma^2_u (f) >= p sigma^2 (f)
$
最小正整数,其中 $p in [0, 1]$ 是给定的精度
]
#let err = math.op("err")
#theorem[][
给定 $p in [0, 1], f(xv)$ 的有效维数为 $d_p$,记:
$
h(xv) = sum_(abs(u) < d_p) f_u (xv)
$
则:
$
err(f, h) &< 1- p \
where err(f, h) &= 1/(sigma^2 (f)) integral_(Omega)^() (f - h)^2 dif xv
$
]
#proof[
$
f(xv) - h(xv) &= sum_(abs(u) > d_p) f_u (xv)\
integral_(Omega)^() (f - h)^2 dif xv &= sum_(abs(u) > d_p) integral_(Omega)^() f_u^2 (xv) dif xv\
&= sum_(abs(u) > d_p) sigma^2_u (f) > (1 - p) sigma^2 (f)
$
证毕
]
#theorem[][
在 QMC(Quasi Monte-Carlo) 中,有:
$
abs(I f - Q f) &<= sum_(u subset ZZ_d, u != emptyset) alpha_u norm(f_u)\
where &norm(f_u)^2 = integral_([0, 1]^(abs(u)))^() abs((diff^(abs(u)) f_u) / (diff xv_u) ) dif xv_u\
&alpha_u "是只依赖于积分点投影的正常数"
$
]
#proof[
略
]
#remark[][
上面的定理表明,当有效维度较小时,我们可以期待 QMC 有较小的误差。既然:
$
f &= h + (f - h)\
abs(I f - Q f) &<= abs(I h - Q h) + abs(I (f - h) - Q (f - h))
$
前项维数较低,而后项能够很好地被有效维数所控制。更深入的,对于任意的 $u in ZZ_d$,可以设置一个 $gamma_u$ 称为该方向的重要性并对 $gamma_u$ 进行排序 $gamma_1 >= gamma_2 >= ... $,可以证明 QMC 的误差不依赖于维度的充分必要条件是:
$
sum_(j=1)^(+infinity) gamma_j < +infinity
$
假如该条件能成立,QMC 就一定程度上避免了维度灾难。
]
== 序列函数逼近
在实际工程上,往往遇到大量高维函数,此时对效率的需求超过对精度的需求。我们需要一些可能精度不佳但更加高效的方式。
#proposition[随机 Kazmart 算法][
对于线性方程组 $A x = b$,可以用以下的迭代方法求解:
- 任取 $x_0$
- 随机取 $A$ 的一行,设为 $i$ 行,更新 $x_k$ 为 $x_(k+1)$,仅用该行更新 $x_(k+1)$ 其余分量不变
可以证明,算法的结果逼近于某个参考解(未必是真解)。该算法用于当 $A$ 非常大以致超过(内存)存储能力时,以时间换空间的策略。
]
= 电子模型和疾病模型
本节中涉及两个具体的模型,医学上的疾病模型采取的是典型的自上而下的建模方式,而电子模型是自下而上的建模方式。
== 白癜风的 ODE 模型
医学上可以假设白癜风的发生过程满足微分方程:
$
cases(
der(phi, t) = k_phi sigma(I, M) - lambda_phi phi,
der(I, t) = k_I phi - lambda_I I,
der(M, t) = - lambda_M sigma(I, M),
sigma(I, M) = M / (1 + e^(- beta(I - I_0)))
)
$
其中 $phi$ 表示趋化因子浓度,$I$ 表示 T 细胞浓度,$M$ 表示黑色素浓度(都是某个点处的浓度),$k, lambda, I_0$ 是常数。\
为了找出其平衡点,先设 $M = 1$ 并令 $der(phi, t) = der(I, t) = 0$,可以求出其在相平面上的若干平衡点,再计算 Jacobi 矩阵的特征值来判断其稳定性。\
之后,再考虑 $M$ 的衰减,发现随着 $M$ 降低稳态也会降低。
== 扩散效应与 Laplace 算子
#let Jv = $bold(J)$
为了完整描述白癜风的的过程,还需要考虑每点处的浓度平衡破坏如何扩散到周围。可以用扩散模型描述。设区域 $V$ 内有物质,其浓度为 $c$,有以下几个方程:
- 守恒方程:
$
(diff)/(diff t) integral_(V)^() c dif v = - integral_(partial V)^() Jv dot dif S
$
其中 $Jv$ 是扩散通量,表示通过单位面积的粒子速率
- Gauss-Green 公式:
$
- integral_(partial V)^() Jv dot dif S = - integral_(V)^() nabla dot Jv dif v
$
- Fick's first law:
$
Jv = - D nabla c
$
其中 $D$ 为扩散系数,可能依赖于空间位置
最终得到:
$
(diff)/(diff t) integral_(V)^() c dif v = integral_(V)^() nabla (D nabla c) dif v
$
由区域的任意性可得:
$
der(c, t) = nabla (D nabla c)
$
若 $D$ 与位置无关,则上式变为:
$
der(c, t) = D Delta c
$
将扩散与 ODE 模型结合,可以得到更加完整的模型。
$
cases(
partialDer(phi, t) = D_I Delta + phi k_phi sigma(I, M) - lambda_phi phi,
partialDer(I, t) = D_I Delta + I k_I phi - lambda_I I,
partialDer(M, t) = - lambda_M sigma(I, M),
sigma(I, M) = M / (1 + e^(- beta(I - I_0)))
)
$
== 图灵斑与反应扩散
上面给出了模型与图灵提出的用反应扩散解释动物斑纹的模型。考虑一种简单情形,在一维有界区域中:
$
cases(
partialDer(u, t) = D Delta u + f(u),
u(0, t) = u(1, t) = 0,
u(x, 0) = u_0 (x)
)
$
考虑关于偏差 $hat(u)$ 的线性微分方程:
$
partialDer(hat(u), t) = D Delta hat(u) + hat(u) f'(u),
$
对于这个线性方程,可以利用傅里叶级数求解并分析。
对于一般的非线性模型,往往只能采用数值模拟的方式。实际发现图灵扩散模型对参数和初值非常敏感,由此可以引出很多深入的讨论。
== 电子模型
=== 薛定谔方程
考虑 $N$ 个粒子构成的体系,假设函数 $phi(xv_1, xv_2, ..., xv_N) in C(RR^(3 N))$ 表示了它们的状态。定义交换算子:
$
P_(i j) phi(xv_1, xv_2, ..., xv_N) = phi(sigma(xv_1, xv_2, ..., xv_N)) where sigma = (xv_i. xv_j) in S_N
$
在微观世界,我们往往假设粒子难以分辨。换言之,态函数应该在 $P_(i j)$ 作用后至多与原来差一个常数 $c$,而交换算子是幂等的,这个常数当然需要满足 $c^2 = 1, c = plus.minus 1$\
物理上,$c = 1$ 表示玻色子,$c = -1$ 表示费米子。电子是一种费米子,研究表明费米子都具有自旋,电子可以进一步分为自旋向上和自旋向下(自旋的名词来自于在磁场下表现出向上偏或者向下偏,类比洛伦兹力将其称为两种自旋),同时有以下基本属性:
- 泡利不相容原理意味着两个电子不可能处于相同的态,也可以理解为既然态函数是反交换的,当然电子有相同的态意味着态为零。
- 电子当然带电,有库伦力:
$
1/(4 pi epsilon) (q_1 q_2)/r^2
$
在实践上,在出现上式的公式中令 $r = 0$ 往往是可行的且事实上不会发散(称为 cusp 条件)。同时,电子确实可以出现在相同的位置,只要自旋不同即可。
- 轨道性:电子只能出现在固定的轨道上
一个理想的模型应该能够演绎或者描述出上面几个属性和理论。薛定谔将电子分轨道分布对应着微分方程中 Sturm-Liouville 问题,也就是微分方程的特征值问题,具体而言:一个经典粒子应当满足色散关系:
$
E = 1/2 m norm(v)^2
$<E>
#let hb = $overline(h)$
#let vv = $bold(v)$
使用一次量子化,也即用 $i hb diff/(diff t)$ 代替 $E$,用 $-i hb gradient$ 替换动量 $m vv$:
$
i hb diff/(diff t) = (-i hb gradient)^2/(2 m)
$
两边乘以 $psi(vv, t)$(称为波函数),有:
$
i hb diff/(diff t) psi(xv, t) = (-i hb gradient)^2/(2 m) psi(xv, t) = - hb/(2m) laplace psi(xv, t)
$
这就是薛定谔方程(Schrödinger equation)。假设考虑氢原子周围电子,补充势能项,也即:
$
E = p^2/(2 m) - 1/(4 pi epsilon_0) e^2/r
$
并无妨设中心为零,将有:
$
i hb diff/(diff t) psi(xv, t) = - (hb/(2m) + 1/(4 pi epsilon_0) e^2/norm(x)) laplace psi(xv, t)
$
同时还可以得到不含时间的方程:
$
- (hb/(2m) + 1/(4 pi epsilon_0) e^2/norm(x)) phi(xv) = epsilon phi(xv)
$
对其使用微分方程的理论进行分析,确实可以得到特征向量与电子轨道的对应性。例如可以计算出,上面方程中最小的特征值就是 $-1/2$,进而可以得到与实验非常相符的结果。然而,这个方程暂时无法描述自旋,之后的内容是解释如何引入自旋,这在历史上由狄拉克完成。
=== 狄拉克方程
之前提到过色散关系@E,这是没有引入相对论效应的结果。事实上,如果速度非常快,应该引入相对论效应,质能关系变成:
$
E^2 = c^2 p^2 +m_0^2 c^4
$
做与之前类似的操作,得到:
$
1/c^2 (diff^2)/(diff t^2) psi - gradient^2 psi + (m^2 c^2)/hb psi = 0
$
然而,这个方程可能导致 $psi^2$ 可能取负值,当时人们并不接受这个观点。狄拉克认为,应该使用:
$
E = sqrt(c^2 p^2 +m_0^2 c^4) = c sqrt(p^2 + m_0^2 c^2)
$
然而微分算子如何开根号是一个模糊的问题。狄拉克认为应该可以写成:
$
c bold(alpha dot beta) + m c^2 beta
$
使得:
$
(c bold(alpha dot beta) + m c^2 beta)^2 = c^2 p^2 +m_0^2 c^4
$
先令 $p$ 是一维的,可以待定系数得到:
$
alpha^2 = beta^2 = 1, alpha beta + beta alpha = 0
$
取实数难以得到结论,但是可以取矩阵,也即:
$
sigma_1 = mat(0, 1;1, 0), sigma_2 = mat(0, -i;i, 0), sigma_3 = mat(1, 0;0, -1)
$
(这些矩阵称为泡利矩阵)\
其中 $alpha$ 取 $sigma_1$ 或 $sigma_2$,$beta$ 取 $sigma_3$ 即可\
对于三维情形,可以证明可取:
$
alpha = mat(0, (sigma_1, sigma_2, sigma_3); (sigma_1, sigma_2, sigma_3), 0), beta = mat(I, 0;0, -I)
$
最后得到方程:
$
i hb (diff)/(diff t) psi = (- i hb c alpha dot gradient + m c^2 beta) psi
$
同样分裂出空间部分,可以得到类似的特征值问题 $H phi = epsilon phi$,其中 $H in M_(4 times 4)(CC), phi in CC^4$,也即是一个矩阵方程。注意到 $phi$ 有四个分量,狄拉克认为,前两个分量对应自旋,后两个分量描述的是所谓“反电子”,而带正电的电子确实被实验证明存在。
狄拉克认为一般而言相对论效应应该是可以忽略的,然而后面的计算和实验表明,处理金、铅等重金属的电子时,电子必须速度非常快,相对论效应是不可忽略的。
=== 多电子
之前考虑的都是单电子情形,下面讨论多电子。方便起见假设使用薛定谔方程 $H phi = epsilon phi$,有 $n$ 个电子,有:
#let sumf1 = (sumf.with(lower: $1$, upper: $N$, var: $i$))()
$
H = - sumf1 1/2 gradient^2_i - sumf1 sum_(A = 1)^N Z_A/(R_(i A)) + sum_(1 <= i < j <= N) 1/(r_(i j)) - sum_(A = 1)^N 1/(2 m_A) gradient_A^2 + sum_(1 = A < B <= M) (Z_A Z_B)/(R_(A, B))
$
//(其中 $r_i$ 代表电子的位置,$R_i$ 代表原子核)
上个世纪的数学家给出了这个方程的解存在或者存在唯一的条件,然而考虑狄拉克方程给出的类似方程,其解的存在性至今仍是一个开放问题。为了解决这个方程,总共有三种途径:
- 密度泛函理论
- 波函数方法
- 随机方法
这里主要介绍的是密度泛函理论。首先对方程中做玻恩-奥本海默近似,也即假设:
$
phi(r_1, .., r_N, R_1, ..., R_M) = psi(r_1, r_2, ..., r_N) psi'(R_1, ..., R_M)
$
其中 $r$ 是电子部分,$R$ 是原子核部分。这个分离来源于电子的运动远比原子核部分快,并且考虑方程:
$
H psi = epsilon psi
$
解这个方程时,假设 $R$ 已经固定,解出来之后再考虑 $R$ 的变化。这里有:
$
H = - sumf1 1/2 gradient^2_i - sumf1 v(r_i) + sum_(1 <= i < j <= N) 1/(r_(i j))
$
其中 $v(r_i)$ 是电子的势能,依赖于固定的 $R$
#theorem[Hohenberg-Kohn][
设 $rho(r)$ 是基态下单位体积内电子的个数:
$
rho(r) = integral_()^() phi^* (sumf1 delta(r - r_i)) phi dif r_i
$
则 $rho(r)$ 可以与 $v(r) = sumf1 v(r_i)$ 在差一个常数的意义下一一对应。
]
上面的定理表明,$rho(r)$ 就可以确定该体系的性质。下面的目标是试图推导 $rho$ 满足的方程,这是一个相当困难的问题,常用的是所谓 Kohn-Sham 方法,大致思想是找一个人造体系,这个体系内无相互作用,且其中的 $rho$ 与所求的 $rho$ 一致。希望构造出方程:
$
H_(k s) psi_(k s) &= epsilon_(k s) psi_(k s)\
where H_(k s) &= sumf1 h_i^(k s)
$
其中 $h$ 是哈密顿量,以及满足:
$
E (rho) = T_(k s) (rho_(k s)) + W_(k s) (rho_(k s)) + integral rho(r) v(r) dif r \
+ T(rho) - T_(k s) (rho_(k s)) + W(rho) - W_(k s) (rho_(k s))
$
其中 $T, W$ 分别是动能和势能。经过一些假设和变分,可以得到 Kohn-Sham 方程:
$
h_i phi_i = epsilon_i phi_i
$
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/attach-p1_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test basics, prescripts. Notably, the upper and lower prescripts' content need to be
// aligned on the right edge of their bounding boxes, not on the left as in postscripts.
$
attach(upright(O), bl: 8, tl: 16, br: 2, tr: 2-),
attach("Pb", bl: 82, tl: 207) + attach(upright(e), bl: -1, tl: 0) + macron(v)_e \
$
|
https://github.com/HiiGHoVuTi/requin | https://raw.githubusercontent.com/HiiGHoVuTi/requin/main/math/ordinaux.typ | typst | #import "../lib.typ": *
#show heading: heading_fct
#import "@preview/gloss-awe:0.0.5": gls
#show figure.where(kind: "jkrb_glossary"): it => {it.body}
#import "@preview/cetz:0.2.2"
On dit qu'une relation $cal(R)$ sur $E$ est un ordre strict si :
- $forall x in E, not (x cal(R) x) $ (*$cal(R)$ est antiréfléxif*)
- $forall x,y,z in E, x cal(R) y and y cal(R) z => x cal(R) z$ (*$cal(R)$ est transitif*)
On dit qu'une relation d'ordre strict $cal(R)$ sur $E$ est un _bon ordre_ strict si pour toute partie $S subset.eq E$ non vide, $S$ admet un plus petit élément. On dit qu'un ensemble $E$ est _transitif_ si $forall X in E, X subset.eq E$.
Un _ordinal_ est un ensemble transitif $alpha$ tel que $(alpha, in)$ est un bon ordre strict
=== Introduction
On défini $[0] := emptyset$ et pour tout $n$ on pose $$
=== Construction de $omega_1$
=== Alephs
=== Calcul de cardinaux
=== Axiome de régularité |
|
https://github.com/ENIB-Community/ENIB_Typst_Internship_Template | https://raw.githubusercontent.com/ENIB-Community/ENIB_Typst_Internship_Template/main/template.typ | typst | MIT License | #import "@preview/glossarium:0.2.6": *
#import "@preview/codelst:1.0.0": sourcecode, codelst-styles, sourcefile
#import "@preview/showybox:2.0.1": showybox
// somewhat bizare typst thingy here
#let codelst-sourcefile = sourcefile
#let sourcefile(filename, ..args) = codelst-sourcefile(
read(filename),
file: filename,
..args,
)
#let remark(body) = {
showybox(
title-style: (
weight: 900,
color: blue.darken(50%),
sep-thickness: 0pt,
align: center + horizon,
),
frame: (
title-color: blue.lighten(80%),
border-color: blue.darken(50%),
thickness: (left: 1pt),
radius: 0pt,
),
title: "Remarque",
body,
)
}
// Print content if not on first page
#let not_on_first_page(body: []) = {
locate(
loc => {
let page_number = counter(page).at(loc).first()
if page_number != 1 {
body
}
},
)
}
// ENIB template.
#let enib-template(
title: none,
sous-titre: none,
nom: "<NAME>",
tuteur_academique: "",
maitre_de_stage: "",
type_stage: [],
dates: [],
mail: "",
logo_company: none,
img_illustration: none,
logo_enib: none,
body,
) = {
show: make-glossary
show: codelst-styles
set document(title: title, author: nom)
set page(paper: "a4")
set text(
lang: "fr",
size: 11.2pt,
font: "Linux Libertine",
)
// Configure equation numbering and spacing.
set math.equation(numbering: "(1)")
show math.equation: set block(spacing: 0.65em)
show heading: set block(spacing: 3%)
// Configure lists.
set enum(indent: 15pt, body-indent: 5pt)
set list(indent: 10pt, body-indent: 9pt)
// Configure heading numbering
set heading(numbering: "1.1.1.1")
// Configure paragraph
set par(
first-line-indent: 0.8em, // The indent the first line of a paragraph.
justify: true, // justify the text.
leading: 0.8em, // The spacing between lines.
)
// Style heading of level 1.
show heading.where(level: 1): it => {
set block(below: 20pt, above: 10pt)
set text(font: "QTPalatine", weight: "black")
set align(center)
underline(smallcaps(it), offset: 4pt)
}
show heading.where(level: 2): it => {
set block(below: 15pt, above: 10pt)
underline(it, offset: 3pt)
}
show heading.where(level: 3): it => {
set block(below: 10pt, above: 5pt)
it
}
show figure: set block(above: 4%, below: 5%)
// link are blue
show link: set text(fill: blue.darken(70%))
// Configure the page.
set page(
paper: "a4",
numbering: "1",
margin: (
x: 2cm,
top: 3.2cm,
bottom: 3cm,
),
background: image("/assets/front-background.svg"),
footer: locate(
loc => {
let page_number = counter(page).at(loc).first()
let total_pages = counter(page).final(loc).last()
if page_number != 1 {
text(
12pt,
grid(
rows: 2,
row-gutter: 5pt,
line(
length: 100%,
stroke: (paint: black.lighten(75%)),
),
grid(
columns: (1fr, auto, 1fr),
align(horizon + left, link("mailto:" + mail)),
align(horizon + center, title),
align(horizon + right)[ #page_number/#total_pages],
),
),
)
}
},
),
header: not_on_first_page(
body: [
#v(45pt)
#grid(
columns: (1fr, 1fr),
align(
horizon + left,
box(height: 35pt, logo_company),
),
align(
horizon + right,
box(height: 40pt, logo_enib),
),
)
#line(length: 100%)
],
),
)
grid(
column-gutter: 40%,
columns: (30%, 30%),
align(
center + horizon,
logo_enib,
),
align(center + horizon, logo_company),
)
v(3.5cm)
if img_illustration != none{
img_illustration
}
text(
size: 14pt,
align(center)[Rapport de #type_stage],
)
v(2cm)
line(length: 100%)
v(0.3cm)
text(
size: 12pt,
align(center)[Stage du #dates],
)
text(
size: 20pt,
align(center)[#smallcaps(title)],
)
v(0.5cm)
line(length: 100%)
v(1.5cm)
align(center)[#nom]
v(1fr)
align(
center,
)[Tuteur Académique : #tuteur_academique (ENIB) & Maitre de stage: #maitre_de_stage]
v(0.5cm)
pagebreak()
body
}
#let todo(it) = [
#set text(weight: "bold", fill: red.darken(25%))
TODO: #it
] |
https://github.com/An-314/Note-of-Quantum_Mechanics | https://raw.githubusercontent.com/An-314/Note-of-Quantum_Mechanics/main/chap3.typ | typst | #import "@preview/physica:0.9.2": *
#import "@local/mytemplate:1.0.0": *
= 一维运动问题的一般分析
一维定态Schrödinger方程为:
$
- hbar^2/(2m) dd(""^2psi)/dd(x^2) + V(x) psi = E psi
$
写成二阶齐次线性微分方程的标准形式:
$
dd(""^2psi)/dd(x^2) + (2m)/hbar^2(E - V(x)) psi = 0
$
其中,$psi$是波函数,$V(x)$是势能函数,$E$是能量。
在经典力学的意义上$E = T + V$,因此$E - V >= 0$(*经典允许区*)。而在量子力学中,由于不确定关系,无法谈粒子“在某点处的动能”因此,$E - V < 0$(*经典禁戒区*)区的波函数仍然有非零解,粒子仍然会在这些区域出现。
方程重写为
$
1/psi dd(""^2psi)/dd(x^2) = -(2m)/hbar^2(E - V)
$
- 在经典允许区,$psi''$与$psi$符号相反,呈现振荡解。
- 在经典禁戒区,$psi''$与$psi$符号相同,呈现单调解。
== 一维定态Schrödinger方程解的性质
一维定态Schrödinger方程是:
$
dd(""^2psi)/dd(x^2) + (2m)/hbar^2(E - V(x)) psi = 0
$
=== Wronskian定理
设$psi_1$和$psi_2$是方程同一能量的两个解,且$Delta = W(psi_1, psi_2) = psi_1 psi_2' - psi_1' psi_2$是它们的Wronskian,则
$
W(psi_1, psi_2) = C
$
其中$C$是常数。
_证明:_
$
&W(psi_1, psi_2)' \
=& psi_1 psi_2^'' - psi_1^'' psi_2 \
=& - psi_1 (((2m)/hbar^2)(E - V(x)) psi_2) + psi_2 (((2m)/hbar^2)(E - V(x)) psi_1) \
=& 0
$
当$Delta = 0$时, $phi_(1,2)(x)$ 是线性相关的,即它们只相差一个常数因子(同一个波函数);当$Delta != 0$时,$phi_(1,2)(x)$ 是线性无关的。
=== 共轭定理
设$psi$是定态Schrödinger方程的一个解,$psi^*$是它的共轭,则$psi^*$也是也是该方程的解(且能量相同)。
=== 反射定理
设势能函数$U(x)$是关于原点对称的,即它满足
$
U(-x) = U(x)
$
那么若$psi(x)$是定态Schrödinger方程的解,则$psi(-x)$也是该方程的解(且能量相同)。
== 一维束缚态的一般性质
=== 一维定态的分类
*束缚态与非束缚态*
如果
$
psi(x) -> 0, x -> plus.minus oo
$
从而粒子在无穷远处出现的几率为零,那么这样的量子状态就称为*束缚态*,否则如
$
psi(x) -> plus.minus oo, x != 0
$
就称为*非束缚态*,或者称为*散射态*。
粒子处于束缚态还是非束缚态的另一判据:
假设 $U(x)$ 在 $x-> plus.minus oo$ 时有确定的极限,那么当
$
E < U(+oo, -oo)
$
时粒子处于束缚态,否则处于非束缚态。
=== 不简并定理
*简并度*:如果对一个给定的能量$E$,只有一个线性独立的波函数存在,则称该能级是非简并的,否则称它是简并的,其线性独立的波函数的个数称为它的*简并度*。
*不简并定理:一维束缚态必是非简并态*
_证明:_
设$psi_1$和$psi_2$是方程同一能量的两个解,且$Delta = W(psi_1, psi_2) = psi_1 psi_2' - psi_1' psi_2$是它们的Wronskian,则
$
W(psi_1, psi_2) = C = W(psi_1, psi_2) |_oo = 0
$
所以
$
psi_1 = A psi_2
$
而这就表示 $psi_1,psi_2$ 代表相同的量子状态,所以它是非简并态。
注意:这个定理的两个前提*“一维”和“束缚态”*是缺一不可的。
波函数是复函数,可以写成下面的形式:
$
psi(x) = rho(x) e^(i theta(x))
$
其中,$rho(x)$为波函数的模,$theta(x)$为波函数的相位。
=== 一维束缚定态波函数的相位
*推论1:一维束缚定态波函数的相位必是常数*
_证明:显然。_
如果波函数$psi(x)$满足$psi(-x) = plus.minus psi(x)$,则称$psi(x)$有*正/负宇称*。
=== 宇称定理
*推论2(宇称定理):如果 $U(-x) = U(x)$,则一维束缚定态波函数必有确定的宇称*
_证明:显然。_
束缚态(不只是一维束缚态)还有一个更重要的特征:它的能级是不连续地(离散地)变化的,即仅仅当取某些离散的数值时,定态Schrödinger方程才有符合单值、有限、连续条件的解。这就是通常意义的“量子化”。
#pagebreak(weak: true)
= ⼀维运动问题的解
== 一维自由粒子
一维自由粒子($U=0$)的定态方程:
$
- hbar^2/(2m) dd(""^2psi)/dd(x^2)psi(x) = E psi(x)
$
解为:
$
psi(x) = c_1 e^(i/hbar p x) + c_2 e^(-i/hbar p x)
$
其中,$p = sqrt(2m E)$。
== 一维无限深方势阱
一维无限深方势阱的势能函数为:
$
U(x) = cases(
0 &|x| < a,
oo &|x| > a
)
$
定态薛定谔方程的形式:
$
cases(
- hbar^2/(2m) dd(""^2psi)/dd(x^2)psi(x) = E psi(x) &|x| < a,
- hbar^2/(2m) dd(""^2psi)/dd(x^2)psi(x) + U_0 psi(x) = E psi(x) &|x| > a
)
$
#newpara()
阱外:$U=oo$要求$psi=0$粒子被束缚在势阱内——束缚态。
阱内:$U=0$,方程的形式类似于一维自由粒子。
解为:
$
psi(x) = cases(
c_1 e^(i/hbar p x) + c_2 e^(-i/hbar p x) &|x| < a,
0 &|x| > a
)
$
其中,$p = sqrt(2m E)$。
$c_1, c_2$为待定常数,由波函数应满足的“单值、有限、连续”条件决定。“单值、有限”已经满足,下面看*连续条件*:
$
psi(-a) &= 0 &=> &c_1 e^(-i/hbar p a) + c_2 e^(i/hbar p a) = 0\
psi(a) &= 0 &=> &c_1 e^(i/hbar p a) + c_2 e^(-i/hbar p a) = 0
$
得到:
$
4i /hbar p a = 2 i pi n, n = 1, 2, 3, ...
$
得到能级:
$
E_n = p^2/(2m) = (n^2 pi^2 hbar^2) / (8 m a^2), n = 1, 2, 3, ...
$
称作*一维无限深势阱能量本征值*。其中$n$称为量子数,$n=1$代表基态,取其它值代表激发态。这表明,一维无限深方势阱中运动粒子的能量是量子化的。
得到波函数:
$
psi_n (x) = sqrt(1/a) sin(n pi (x+a)/(2a))
$
是*驻波形式*。如果加上时间项:
$
Psi_n (x)= sqrt(1/a) sin(n pi (x+a)/(2a)) e^(-i/hbar E_n t)
$
在势能无穷大的地方,一阶导数可以不连续,这个波函数就是例子。
*能级间隔*:
$
Delta E_n = E_(n+1) - E_n = (pi^2 hbar^2 (2n+1)) / (8 m a^2) prop 1/(m a^2)
$
$
Delta E_n/ E_n = (2n+1)/n^2 prop 1/n
$
宏观情况(能级变化$>>Delta E_n$)或量子数很大时$(n>>1)$,可认为能量连续。
*
最低能量(基态能量)*:$E_1 = pi^2 hbar^2 / (8 m a^2) >0$零点能——真空不空。
态的宇称是偶奇相间,基态为偶宇称。
波函数的节点数为 $n -1$。
*玻尔对应原理*:量子数$n$很大时,经典力学与量子力学的结果相近。
波函数的正交归一:
$
integral psi_n^* (x) psi_m (x) dd(x) = delta_(n,m)
$
其中,$delta_(n,m)$是Kronecker delta,当$n=m$时为1,否则为0。
波函数的完备性:
$
Psi(x) = sum_(n=1)^oo c_n psi_n (x)
$
其中,$c_n = integral psi_n^* (x) Psi(x) dd(x)$。
== 非对称无限深势阱
非对称无限深势阱的势能函数为:
$
U(x) = cases(
0 & 0<x<a,
oo & x < 0 x> a
)
$
能级是:
$
E_n = (n^2 pi^2 hbar^2) / (2 m a^2), n = 1, 2, 3, ...
$
== 对称有限深方势阱
对称有限深方势阱的势能函数为:
$
U(x) = cases(
0 & |x| < a,
U_0 & |x| > a
)
$
定态薛定谔方程的形式:
$
cases(
dd(""^2psi)/dd(x^2)psi(x) + k^2 psi(x) = 0 &|x| < a,\
dd(""^2psi)/dd(x^2)psi(x) - alpha^2 psi(x) = 0 &|x| > a
)
$
其中,$k = sqrt(2m E/hbar^2)$,$alpha = sqrt(2m (U_0 - E)/hbar^2)$。
有限解为
$
psi(x) = cases(
C e^(alpha x) &x<-a,\
A cos(k x) + B sin(k x) &|x| < a,\
D e^(-alpha x) &x > a
)
$
1. 偶宇称解
$
psi(x) = psi(-x) , B = 0, C = D
$
在$x=a$处$psi$和$psi'$连续,得到
$
k tan(k a) = alpha
$
2. 奇宇称解
$
psi(x) = -psi(-x) , A = D = 0
$
在$x=a$处$psi$和$psi'$连续,得到
$
k cot(k a) = -alpha
$
#newpara()
采用图解法,令
$
xi = k a, eta = alpha a (xi, eta > 0)
$
得到
$
cases(
xi tan(xi) = plus.minus eta,
xi^2+eta^2 = (2 mu U_0 a^2) / hbar^2
)
$
#figure(
image("pic/2024-03-20-13-39-33.png", width: 40%),
caption: [
对称有限深方势阱的解
],
)
找出这两族曲线的交点,记交点的$xi$值为$xi_1,xi_2,...,$则能级就是
$
E_n = (hbar^2 xi_n^2) / (2 m a^2)
$
_讨论:_
- 能级的宇称是偶奇相间,最低的能级是偶宇称
- $0 < xi_1 < pi/2 < xi_2 < pi < xi_3 < ...$。每个能级都比无限深势阱的相应能级低一些。
$U_0 -> oo $时,$xi_n -> n pi/2$,能级趋近于无限深势阱的能级。在$|x|>=a$处,波函数趋于0。
- 不论势阱多浅或多窄,至少存在一个束缚态,并且宇称为偶。
- 对于偶宇称,当
$
eta^2 + xi^2 = (2 mu U_0 a^2) / hbar^2 >= pi^2
$
时,才能出现第一个偶宇称的激发态。
- 对于奇宇称,当
$
eta^2 + xi^2 = (2 mu U_0 a^2) / hbar^2 >= (pi/2)^2
$
时,才能出现第一个奇宇称的激发态。
- 在给定的势阱中,能级的个数是
$
ceil((8 mu U_0 a^2) / (pi^2 hbar^2))
$
== $delta$势阱
考虑$delta$势阱的势能:
$
V(x) = - gamma delta(x)
$
其中$gamma > 0$。
定态Schrödinger方程:
$
dd(""^2psi)/dd(x^2) + (2m)/hbar^2(E + gamma delta(x)) psi(x) = 0
$
在$x≠0$处:
$
dd(""^2psi)/dd(x^2) + (2m)/hbar^2 E psi(x) = 0
$
结合束缚态的要求,得到一般解为:
$
psi(x) = cases(
C_1 e^(beta x) &x<0,
C_2 e^(-beta x) &x>0
)
$
其中
$
beta = sqrt(2m |E|)/hbar
$
且在$x=0$处$psi$连续,得到:
$
C_1 = C_2
$
归一化条件:
$
integral |psi(x)|^2 dd(x) &= 1
$
令$beta = 1/L$,得到:
$
psi(x) = 1/sqrt(L) e^(-(|x|)/L)
$
$L$被称为特征长度。
进一步地,对Schrodinger方程两边积分,得到:
$
dd(psi)/dd(x) |_0^0 &= - (2m)/hbar^2 gamma psi(0)\
psi'(0^+) - psi'(0^-) &= - (2m)/hbar^2 gamma psi(0)\
-2 beta &= - (2m gamma)/hbar^2
$
得到束缚态基态的能量:
$
E = - (gamma^2 m)/(2 hbar^2)
$
束缚态能级有且只有一个。
== 线性谐振子
线性谐振子的势能函数是:
$
U(x) = 1/2 mu omega^2 x^2
$
其中,$omega$是谐振子的角频率。
定态Schrödinger方程:
$
- hbar^2/(2m) dd(""^2psi)/dd(x^2) + 1/2 mu omega^2 x^2 psi = E psi
$
做如下的无量纲化变换:
$
cases(
xi = sqrt((mu omega)/hbar) x = alpha x,\
lambda = (2 E)/(hbar omega)
)
$
得到:
$
dd(""^2psi)/dd(xi^2) + (lambda - xi^2) psi = 0
$
束缚态的解的要求:
$
psi(xi) -> 0, xi -> plus.minus oo
$
在$xi -> plus.minus oo$时,方程近似为:
$
dd(""^2psi)/dd(xi^2) - xi^2 psi = 0
$
有近似解:
$
psi(xi) = e^(-xi^2/2)
$
进行变换:
$
psi(xi) = e^(-xi^2/2) H(xi)
$
得到*Hermite方程*:
$
dd(""^2H)/dd(xi^2) - 2 xi dd(H)/dd(xi) + (lambda - xi^2) H = 0
$
可以用级数解法求解Hermite方程,得到*Hermite多项式*。
$
H(xi) = sum_(n=0)^oo c_n xi^n
$
带入方程得到递推关系:
$
c_(k+2) = (2k + 1 - lambda)/((k+1)(k+2)) c_k
$
可以分析:
$
c_k tilde.op 1/(k/2)!, H(xi) tilde.op~ e^(xi^2)
$
这会使得
$
psi(xi) tilde.op~ e^(xi^2/2)
$
发散!这是不可能的,所以*级数必须截断*,即存在一个最大的$n$,使得$c_n = 0$。*这就对$lambda$有了限制:*
$
lambda = 2n + 1, n = 0, 1, 2, ...
$
首先得到了能量本征值:
$
E_n = (n + 1/2) hbar omega, n = 0, 1, 2, ...
$
这就是*线性谐振子的能级*。
*Hermite方程对于本征值$lambda$的多项式解就是Hermite多项式*。
$
H_0 (xi) &= 1,\
H_1 (xi) &= 2 xi,\
H_2 (xi) &= 4 xi^2 - 2,\
$
一般形式:
$
H_n (xi) &= (-1)^n e^(xi^2) dd(""^n )/dd(xi^n)e^(-xi^2)
$
正交归一:
$
integral e^(-xi^2) H_n (xi) H_m (xi) dd(xi) = sqrt(pi) 2^n n! delta_(n,m)
$
正交归一化常数为:
$
N_n = sqrt(alpha/(2^n n! sqrt(pi)))
$
#newpara()
得到的波函数为:
$
psi_n (x) = N_n e^(-xi^2/2) H_n (xi) = N_n H_n (alpha x) e^(-alpha^2 x^2/2)
$
$n$的奇偶性决定了谐振子波函数的奇偶性,即宇称的奇偶:
$
psi_n (-x) = (-1)^n psi_n (x)
$
#figure(
image("pic/2024-03-20-14-34-15.png", width: 50%),
caption: [
粒子具有一定的概率处在经典允许区之外
],
)
经典情况下:
$
xi = a sin(omega t + delta)\
v = a omega cos(omega t + delta) = a omega sqrt(1 - xi^2/a^2)\
w(xi) prop 1/v prop 1/sqrt(1 - xi^2/a^2)
$
#figure(
image("pic/2024-03-20-14-36-21.png", width: 40%),
caption: [
实线(虚线)表示谐振子在量子(经典)情况下的概率密度分布
],
)
_讨论:_
- $n$较大时能谱连续:
$
(Delta E_n)/E_n = 1/(n + 1/2) ->0
$
- $n$较小时,量子效应明显。比如在$n=0$时,量子力学告诉我们粒子在$x=0$处出现几率最大,但在经典力学中,粒子在此处速度极大,出现几率反而最小。
- $n$较大时,空间几率趋于经典分布(量子态$n$对应的典运动振幅为$a = sqrt(2n +1)$。
- 在$xi>a$的经典力学粒子不能达到的区域,量子世界中仍有分布
- 同势阱问题一样,振子*基态能量(零点能)*不为0($E_0 = 1/2 hbar omega$)。零点能的实验现象:Casimir效应。
- 由于谐振子势有空间反射不变性,所以有确定的宇称。能级的宇称偶奇相间,基态是偶宇称。
- $psi_n (x)$有$n$个节点。
== 一维散射问题
为简单可以假设:
$
U(+ oo) = U(- oo) = 0, E>0
$
所以这时的量子状态是非束缚态,也就是散射态。
在$x -> plus.minus oo$时,$U = 0$
$
dd(""^2psi)/dd(x^2) + k^2 psi = 0
$
其中$k = sqrt((2m E)/hbar^2)$。
解为:
$
psi(x) = c_1 e^(i/hbar p x) + c_2 e^(-i/hbar p x)
$
在$psi = A e^(i/hbar p x)$时,几率流密度为:
$
j = (hbar p)/(2mu) (psi dd(psi^*)/dd(x) - psi^* dd(psi)/dd(x)) = (hbar p)/(mu) |psi|^2 = |A|^2 nu
$
其中,$nu = (hbar k)/mu = p/mu$是粒子的经典速度。
*散射情况*是:粒子从一边入射,被势场散射而分成了反射和透射两个部分。这给方程提出了一定的条件。以左方入射为例,边界条件是:
$
cases(
psi(x) =A e^(i/hbar p x) + B e^(-i/hbar p x) & "入射加反射" &x -> -oo,\
psi(x) = C e^(i/hbar p x) & "只有透射" &x -> +oo
)
$
由此定义*反射系数*和*透射系数*:
$
R = J_R/J_I = (|B|^2)/(|A|^2),\
D = J_T/J_I = (|C|^2)/(|A|^2)
$
#newpara()
*方势垒的穿透*
方势垒的势能函数为:
$
U(x) = cases(
U_0 &0 < x < a,
0 &x < 0 or x>a
)
$
定态Schrödinger方程:
$
cases(
dd(""^2psi)/dd(x^2)psi(x) + (2m)/hbar^2(E - U_0) psi(x) = 0 &(0 < x < a),\
dd(""^2psi)/dd(x^2)psi(x) + (2m)/hbar^2(E) psi(x) = 0 &(x < 0 or x>a)
)
$
解为:
$
psi_1 &= A e^(i k_1 x) + A' e^(-i k_1 x) &(x < 0),\
psi_2 &= B e^(i k_2 x) + B' e^(-i k_2 x) &(0 < x < a),\
psi_3 &= C e^(i k_1 x) &(x > a)
$
其中,$k_1 = sqrt(2m E/hbar^2), k_2 = sqrt(2m (E - U_0)/hbar^2)$。表达式中第一项(第二项)代表从左向右(从右向左)传播的平面波。在$x>a$的区域只有向右的透射波,所以$C'=0$。
利用波函数及其导数在边界处的连续性,得出波函数中各系数的关系式:
$
psi_1 (0) = psi_2 (0), psi_1 ' (0) = psi_2 ' (0), psi_2 (a) = psi_3 (a), psi_2 ' (a) = psi_3 ' (a)
$
得到:
$
A' = (2i(k_1^2 - k_2^2) sin(k_2 a))/((k_1 - k_2)^2 e^(i k_2 a) - (k_1 + k_2)^2 e^(-i k_2 a)) A,\
C = (4k_1 k_2 e^(- i k_1 a))/((k_1 + k_2)^2 e^(- i k_2 a) - (k_1 - k_2)^2 e^(i k_2 a)) A
$
计算入射波($A$项),反射波($A'$项)和透射波($C$项)的概率流密度得:
$
J_I = (hbar k_1)/mu |A|^2,\
J_R = (hbar k_1)/mu |A'|^2,\
J_D = (hbar k_1)/mu |C|^2
$
接着可以得到粒子的*反射系数和透射系数*:
$
R = abs(J_R)/abs(J_I) = ((k_1^2 - k_2^2)^2 sin^2(k_2 a))/((k_1^2-k_2^2)^2 sin^2(k_2 a) + 4k_1^2 k_2^2 ),\
D = abs(J_D)/abs(J_I) = (4k_1^2 k_2^2)/((k_1^2-k_2^2)^2 sin^2(k_2 a) + 4k_1^2 k_2^2 )
$
很容易看出$R+D=1$,这是粒子流守恒的必然结果。
$E<U_0$情形下,$k_2$是虚数,令$k_2 = i k_3 $,则
$
D = (4k_1^2 k_3^2)/((k_1^2+k_3^2)^2 sinh^2(k_3 a) + 4k_1^2 k_3^2 ) > 0
$
当$U_0$很大时时,$k_3a>>1$,透射系数可近似为:
$
D &= D_0 (k_1, k_3) e^(-2k_3 a)\
&= D_0 (k_1, k_3) e^(-2 sqrt(2mu(U_0 - E)/hbar^2) a)
$
$E<U_0$时$D>0$,这就是*量子隧穿效应*。
#figure(
image("pic/2024-03-22-13-32-46.png", width: 20%),
caption: [
量子隧穿效应
],
)
量子隧穿效应随着$a$的上升指数下降,在宏观尺度上是充分小的。理解量子隧道效应 – 在势垒内部,根据总能量守恒,粒子的动能将变为负数:
$
E_"kin" = E - U < 0
$
这在经典力学中是不可能的。
在量子力学里,粒子动能与势能不能同时具有确定值。而且,力学量的平均值是一个全域的积分平均,在某个局域内讨论是没有意义的。一旦讨论限制在某一局域(势垒内部),粒子动量就在某一范围内不确定。
== 方势阱的共振隧穿
如果把方势垒改为方势阱,整个实轴都是经典允许区不存在势垒的隧穿,发生共振隧穿。
对于势阱情况下的透射系数:
$
T= (4k_1^2 k'^2)/((k_1^2-k'^2)^2 sin^2(k' a) + 4k_1^2 k'^2 )
$
其中$k' = sqrt(2m (V_0 + E)/hbar^2)$。
共振透射,共振能量的位置:
$
E = - V_0 + (n pi hbar)^2 / (2m a^2), n = 1, 2, 3, ...
$
以$-V_0$为势能起点宽度为$a$的无线深势阱中的能级表达式。
#figure(
image("pic/2024-03-22-13-52-52.png", width: 80%),
caption: [
共振隧穿
],
) |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/vec-02.typ | typst | Other | // Error: 22-25 expected "(", "[", "{", "|", "||", or none
#set math.vec(delim: "%")
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/footnote-table_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set page(height: 100pt)
= Tables
#table(
columns: 2,
[Hello footnote #footnote[This is a footnote.]],
[This is more text],
[This cell
#footnote[This footnote is not on the same page]
breaks over multiple pages.],
image("/assets/files/tiger.jpg"),
)
#table(
columns: 3,
..range(1, 10)
.map(numbering.with("a"))
.map(v => upper(v) + footnote(v))
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/statastic/0.1.0/lib.typ | typst | Apache License 2.0 | /// Extracts a specific column from the given dataset based on the column.
///
/// - data (array): The dataset.
/// - colId (int): The identifier for the column to be extracted.
/// -> array
#let extractColumn(data, colId) = {
let column = ()
for row in data {
column.push(row.at(colId))
}
column
}
/// Converts an array's elements to floating point numbers.
///
/// - arr (array): Array with elements to be converted.
/// -> array
#let tofloatArray(arr) = {
let res = ()
for el in arr {
if el == "" {
res.push(0.0)
} else {
res.push(float(el))
}
}
res
}
/// Converts an array's elements to integers.
///
/// - arr (array): Array with elements to be converted.
/// -> array
#let toIntArray(arr) = {
let res = ()
for el in arr {
if el == "" {
res.push(0)
} else {
res.push(int(el))
}
}
res
}
/// Determines if a given value is an integer.
///
/// - val (mixed): The value to be checked.
/// -> boolean
#let isInt(val) = {
let f = float(val)
let i = int(f)
val == i
}
/// Calculates a value between two numbers at a specific fraction.
///
/// - lower (float): The lower number.
/// - upper (float): The upper number.
/// - fraction (float): The fraction between the two numbers.
/// -> float
#let lerp(lower, upper, fraction) = {
let diff = upper - lower
lower + (diff * fraction)
}
/// Calculates the average of an array's elements.
///
/// - arr (array): Array of numbers.
/// -> float
#let arrayAvg(arr) = {
let col = tofloatArray(arr)
col.sum() / col.len()
}
/// Calculates the average of a specific column in a dataset.
///
/// - data (array): The dataset.
/// - colId (int): The identifier for the column.
/// -> float
#let avg(data, colId) = {
arrayAvg(extractColumn(data, colId))
}
/// Calculates the median of an array's elements.
///
/// - arr (array): Array of numbers.
/// -> float
#let arrayMedian(arr) = {
let col = tofloatArray(arr).sorted()
let len = col.len()
if (calc.rem(len, 2) == 0) {
let middle = calc.quo(len, 2)
(col.at(middle - 1) + col.at(middle)) / 2
} else {
let middle = calc.quo(len, 2) - 1
col.at(middle-1)
}
}
/// Calculates the median of a specific column in a dataset.
///
/// - data (array): The dataset.
/// - colId (int): The identifier for the column.
/// -> float
#let median(data, colId) = {
arrayMedian(extractColumn(data, colId))
}
/// Calculates the mode of an integer array.
/// Converts all floats to integers.
///
/// - arr (array): Array of integers.
/// -> array
#let arrayIntMode(arr) = {
let col = arr
let unique = col.dedup()
let counts = (:)
for k in unique {
counts.insert(str(k), 0)
}
for k in col {
counts.at(str(k)) += 1
}
let highestModeCount = 0
for (k, v) in counts.pairs() {
if (v > highestModeCount) {
highestModeCount = v
}
}
let modes = ()
for (k, v) in counts.pairs() {
if (v == highestModeCount) {
modes.push(int(k))
}
}
modes
}
/// Calculates the integer mode of a specific column in a dataset.
/// Converts all floats to integers.
///
/// - data (array): The dataset.
/// - colId (int): The identifier for the column.
/// -> array
#let intMode(data, colId) = {
arrayIntMode(toIntArray(tofloatArray((extractColumn(data, colId)))))
}
/// Calculates the variance of an array's elements.
///
/// - arr (array): Array of numbers.
/// -> float
#let arrayVar(arr) = {
let col = tofloatArray(arr)
let len = col.len()
let mean = col.sum() / len
let varSum = 0
for el in col {
varSum += calc.pow(el - mean, 2)
}
varSum / (len - 1)
}
/// Calculates the variance of a specific column in a dataset.
///
/// - data (array): The dataset.
/// - colId (int): The identifier for the column.
/// -> float
#let var(data, colId) = {
arrayVar(extractColumn(data, colId))
}
/// Calculates the standard deviation of an array's elements.
///
/// - arr (array): Array of numbers.
/// -> float
#let arrayStd(arr) = {
let var = arrayVar(arr)
calc.sqrt(var)
}
/// Calculates the standard deviation of a specific column in a dataset.
///
/// - data (array): The dataset.
/// - colId (int): The identifier for the column.
/// -> float
#let std(data, colId) = {
arrayStd(extractColumn(data, colId))
}
/// Calculates a specific percentile of an array's elements.
///
/// - arr (array): Array of numbers.
/// - p (float): The desired percentile (between 0 and 1).
/// -> float
#let arrayPercentile(arr, p) = {
let col = tofloatArray(arr).sorted()
let n = col.len() - 1
let pos = p * n
if (isInt(pos)) {
col.at(int(pos))
} else {
let low = col.at(calc.floor(pos))
let high = col.at(calc.ceil(pos))
lerp(low, high, calc.fract(pos))
}
}
/// Calculates a specific percentile of a column in a dataset.
///
/// - data (array): The dataset.
/// - colId (int): The identifier for the column.
/// - p (float): The desired percentile (between 0 and 1).
/// -> float
#let percentile(data, colId, p) = {
arrayPercentile(extractColumn(data, colId), p)
}
/// Computes a set of statistical measures for an array.
/// Includes: average, median, integer mode, variance, standard deviation, and some percentiles.
///
/// - arr (array): Array of numbers.
/// -> dictionary
#let arrayStats(arr) = {
(
"avg": arrayAvg(arr),
"median": arrayMedian(arr),
"intMode": arrayIntMode(arr),
"var": arrayVar(arr),
"std": arrayStd(arr),
"25percentile": arrayPercentile(arr, 0.25),
"50percentile": arrayPercentile(arr, 0.50),
"75percentile": arrayPercentile(arr, 0.75),
"95percentile": arrayPercentile(arr, 0.95),
)
}
/// Computes a set of statistical measures for a specific column in a dataset.
/// Includes: average, median, integer mode, variance, standard deviation, and some percentiles.
///
/// - data (array): The dataset.
/// - colId (int): The identifier for the column.
/// -> dictionary
#let stats(data, colId) = {
(
"avg": avg(data, colId),
"median": median(data, colId),
"intMode": intMode(data, colId),
"var": var(data, colId),
"std": std(data, colId),
"25percentile": percentile(data, colId, 0.25),
"50percentile": percentile(data, colId, 0.50),
"75percentile": percentile(data, colId, 0.75),
"95percentile": percentile(data, colId, 0.95),
)
}
|
https://github.com/0x1B05/algorithm-journey | https://raw.githubusercontent.com/0x1B05/algorithm-journey/main/practice/note/content/杂题.typ | typst | #import "../template.typ": *
#pagebreak()
= 杂题(1)
== 一个数据流中,最快可以取得中位数
```java
import java.util.Comparator;
import java.util.PriorityQueue;
public class MadianQuick {
public static class MedianQuick{
private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(new MaxHeapComparator());
private PriorityQueue<Integer> minHeap = new PriorityQueue<>(new MinHeapComparator());
private void modifyTwoHeapsSize(){
if (this.maxHeap.size() == this.minHeap.size() +2){
this.maxHeap.add(this.minHeap.poll());
}
if (this.minHeap.size() == this.maxHeap.size() + 2) {
this.maxHeap.add(this.minHeap.poll());
}
}
public void addNumber(int num) {
if (this.maxHeap.isEmpty()) {
this.maxHeap.add(num);
return;
}
if (this.maxHeap.peek() >= num) {
this.maxHeap.add(num);
} else {
if (this.minHeap.isEmpty()) {
this.minHeap.add(num);
return;
}
if (this.minHeap.peek() > num) {
this.maxHeap.add(num);
} else {
this.minHeap.add(num);
}
}
modifyTwoHeapsSize();
}
public Integer getMedian() {
int maxHeapSize = this.maxHeap.size();
int minHeapSize = this.minHeap.size();
if (maxHeapSize + minHeapSize == 0) {
return null;
}
Integer maxHeapHead = this.maxHeap.peek();
Integer minHeapHead = this.minHeap.peek();
if (((maxHeapSize + minHeapSize) & 1) == 0) { //偶数
return (maxHeapHead + minHeapHead) / 2;
}
return maxHeapSize > minHeapSize ? maxHeapHead : minHeapHead;
}
}
public static class MaxHeapComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
if (o2 > o1) {
return 1;
} else {
return -1;
}
}
}
public static class MinHeapComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
if (o2 < o1) {
return 1;
} else {
return -1;
}
}
}
}
```
== N 皇后问题
N 皇后问题是指在 N\*N 的棋盘上要摆 N
个皇后,要求任何两个皇后不同行、不同列,也不在同一条斜线上。 给定一个整数
n,返回 n 皇后的摆法有多少种 n = 1,返回 1 n = 2 或 3,2 皇后和 3
皇后问题怎么摆都不行,返回 0 n = 8,返回 92
```java
public static int num1(int n){
if(n < 0){
return 0;
}
//record[0]代表第0行的皇后放在哪一列
int[] record = new int[n];
return process1(0,record,n);
}
//record[0..i-1]的皇后,任意两个皇后一定不共行,不共列,不共斜线
//当前来到第i行,
//record[0...i-1]表示之前的行,放了的皇后位置
//n代表整体一共有多少行
//返回值是,摆完所有的皇后,合理的摆法有多少种
public static int process1(int i,int[] record,int n){
//终止行
if(i == n){
return 1;
}
int res = 0;
//当前行在i行,尝试所有的列j
for(int j = 0;j < n;j++){
//当前i行的皇后,放在j列,会不会和之前的(0...i-1)的皇后,共行共列或者共斜线
//如果是,认为无效
//如果不是,认为有效
if(isValid(record,i,j){
record[i] = j;
res += process1(i+1,record,n);
}
}
return res;
}
//record[0...i-1]需要看,后续的不需要
//返回i行皇后,放在j列,是否有效
public static boolean isValid(int[] record,int i,int j){
for(int k = 0; k < i; k++){
//共列和共斜线返回false
if(j == record[k] || Math.abs(record[k] - j) == Math.abs(i-k)){
return false;
}
}
return true;
}
```
|
|
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/flywheel/program.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator, codetastic
#import notebookinator: *
#import themes.radial.components: *
#import codetastic: qrcode
#show: create-body-entry.with(
title: "Program: Flywheel",
type: "program",
date: datetime(year: 2023, month: 12, day: 11),
author: "<NAME>",
witness: "<NAME>",
)
= PID Control
When we were programming our flywheel we wanted the velocity to be as consistent
as possible. In order to do this we decided to use a library called Sylib #footnote(qrcode("https://github.com/sy1vi3/sylib", size: 2pt)) which
was commonly used during the Spin Up season. It contains a workaround to a bug
in the V5 firmware that allows us to more accurately measure the velocity of the
flywheel.
With Sylib installed, we need to configure our PID constants.
```cpp
inline sylib::SpeedControllerInfo flywheel_speed_controller(
[](double rpm) { return 5; }, // kV function
1, // kP
1, // kI
1, // kD
1, // kH
false, // anti-windup enabled
0, // anti-windup range
false, // p controller bounds threshold enabled
0, // p controller bounds cutoff enabled
1, // kP2 for when over threshold
0 // range to target to apply max voltage
);
```
With this set up the code to maintain the flywheel speed is extremely simple.
```cpp
switch (get_state()) {
case FlywheelState::Idle:
motor->stop();
break;
case FlywheelState::Spinning:
motor->set_velocity_custom_controller(600);
break;
}
```
We've set up the flywheel to be toggled with the L2 button, replacing the
catapult. ```cpp
// Flywheel control
if (controller.get_digital_new_press(pros::E_CONTROLLER_DIGITAL_L2)) {
controller.rumble(".");
flywheel.toggle();
}
``` This is overall easier for the driver, it means they don't have to think
about holding down a button the whole time the flywheel is running.
This PID output can be graphed with the Loginator. This allows for easy
debugging and testing.
#figure(
image("./loginator-output.png"),
caption: [Grafana, displaying PID output from the flywheel],
)
The dips represent the output of the controller as the flywheel was toggled on
and off.
= LED Indicator
When we were match loading during our Hereford tournament we noticed that it was
very difficult for the match loaders to know when the flywheel was back up to
speed again. This lead to very inconsistent trajectories.
We decided to add an LED indicator light to show the match loaders when the
flywheel was spinning fast enough.
Implementing this was simple enough, Sylib also provides built in LED control.
These 5 lines of code were all we needed to get this working. ```cpp
if (motor->get_velocity_error() > 50) {
led->set_all(RED);
} else {
led->set_all(GREEN);
}
```
|
https://github.com/topdeoo/NENU-Thesis-Typst | https://raw.githubusercontent.com/topdeoo/NENU-Thesis-Typst/master/layout/document.typ | typst | /// 文档总体设置
/// 设置部分包括:
/// 1. 整体字体与字号
/// 2. 页面布局(页边距)
/// 3. pdf 元信息
#let doc(
info: (:),
thesis-type: "bachelor",
fallback: false,
lang: "zh",
it,
) = {
//! 初始化
info = (
title: "基于 Typst 的学位论文",
author: "张三",
) + info
//! 设置样式
set text(fallback: fallback, lang: lang)
// if thesis-type == "bachelor" {
set page(margin: (top: 2.54cm, bottom: 2.54cm, left: 3.18cm, right: 3.18cm))
// } else {
// panic("Not Imp")
// }
//! 设置 pdf 信息
set document(
title: info.title,
author: info.author,
)
it
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.