diff --git a/.claude/skills/humanizer/LICENSE b/.claude/skills/humanizer/LICENSE
new file mode 100644
index 0000000..625297f
--- /dev/null
+++ b/.claude/skills/humanizer/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025 Siqi Chen
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/.claude/skills/humanizer/SKILL.md b/.claude/skills/humanizer/SKILL.md
new file mode 100644
index 0000000..e3d5bbe
--- /dev/null
+++ b/.claude/skills/humanizer/SKILL.md
@@ -0,0 +1,464 @@
+---
+name: humanizer
+description: |
+ Rewrite AI-sounding text so it reads naturally without changing what it says.
+ Use when editing or reviewing prose for inflated claims,
+ sales language, vague sources, repetitive structure, stock AI words, passive
+ voice, filler, or chatbot artifacts. Based on Wikipedia's "Signs of AI writing."
+ Dùng khi người dùng nói "viết lại cho tự nhiên", "bỏ giọng AI", "humanize
+ văn bản này", "làm mượt README/docs/commit/PR description", hoặc yêu cầu
+ review prose trước khi publish.
+license: MIT
+metadata:
+ version: "2.11.2"
+ upstream: "https://github.com/blader/humanizer"
+---
+
+> Vendored from [blader/humanizer](https://github.com/blader/humanizer) v2.11.2 (MIT). Body kept verbatim; only the description was extended with Vietnamese trigger phrases for this pack.
+>
+> **Caveman mode does not apply to this skill's output.** The rewritten text is the deliverable — return full prose. Compression applies only to the surrounding commentary.
+
+# Humanizer: remove AI writing patterns
+
+Rewrite AI-sounding text so it reads like the writer, not a chatbot. Do not change what it says or make up details.
+
+The patterns below come from Wikipedia's ["Signs of AI writing"](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing), maintained by WikiProject AI Cleanup.
+
+## What to do
+
+When given text to humanize:
+
+1. **Find AI patterns.** Check the text against the patterns below.
+2. **Keep every claim.** You may shorten dull parts, expand useful parts, and merge or split paragraphs. Keep the information even when you change the structure.
+3. **Do not invent facts.** Do not add a fact, name, number, date, quote, or citation unless it comes from the source or the user. If a sentence needs a missing detail, ask for it or use a simpler sentence. You may add an opinion or reaction when the writer's voice calls for one, but you may not add a factual claim. Fiction is exempt because invented details are part of the task.
+4. **Match the voice.** Use the right tone for the text, such as formal, casual, or technical. Add personality only when the text and the writer call for it.
+
+The input type controls what you return. See [How to return the result](#how-to-return-the-result). Use the same rewrite process in every mode.
+
+## Match the writer's voice
+
+If the user provides a writing sample (their own previous writing), analyze it before rewriting:
+
+1. Read the sample first. Note its sentence length, word choice, paragraph openings, punctuation, repeated phrases, and transitions.
+2. Match those habits. Do not replace casual words with formal ones or remove deliberate quirks.
+3. If there is no sample, use the guidance below.
+
+A writing sample takes priority over these style rules. If the sample uses em dashes, keep them at about the same rate. Do not apply §14 as a ban.
+
+## Add personality only when it fits
+
+Removing AI patterns is only half the job. The result should still sound like a person.
+
+Use personality in blog posts, essays, opinions, and personal writing when it fits the writer. Keep reference, technical, legal, and factual text neutral. Do not add opinions or first-person language where they do not belong.
+
+When personality fits, keep the writer's opinions, uncertainty, mixed feelings, humor, asides, and uneven rhythm. Never invent facts to make the text feel personal.
+
+## Content patterns
+
+### 1. Inflated claims about importance and legacy
+
+**Words to watch:** stands/serves as, is a testament/reminder, a vital/significant/crucial/pivotal/key role/moment, underscores/highlights its importance/significance, reflects broader, symbolizing its ongoing/enduring/lasting, contributing to the, setting the stage for, marking/shaping the, represents/marks a shift, key turning point, evolving landscape, focal point, indelible mark, deeply rooted
+**Problem:** AI writing often claims that ordinary details mark a major change, prove a legacy, or reflect a broad trend.
+**Before:**
+> The Statistical Institute of Catalonia was officially established in 1989, marking a pivotal moment in the evolution of regional statistics in Spain. This initiative was part of a broader movement across Spain to decentralize administrative functions and enhance regional governance.
+**After:**
+> The Statistical Institute of Catalonia was established in 1989, part of a wider decentralization of administrative functions in Spain.
+
+### 2. Name-dropping to prove importance
+
+**Words to watch:** independent coverage, local/regional/national media outlets, written by a leading expert, active social media presence
+**Problem:** AI writing often lists well-known publications or follower counts to prove that a person matters. The list usually gives no useful context.
+**Before:**
+> Her views have been cited in The New York Times, BBC, Financial Times, and The Hindu. She maintains an active social media presence with over 500,000 followers.
+**After:**
+> Her views have been cited in The New York Times and the BBC.
+
+If the source explains what the person said and where, keep that useful citation. Do not invent context for a shorter version.
+
+### 3. Shallow analysis with -ing phrases
+
+**Words to watch:** highlighting/underscoring/emphasizing..., ensuring..., reflecting/symbolizing..., contributing to..., cultivating/fostering..., encompassing..., showcasing...
+**Problem:** AI writing often adds an -ing phrase to make a simple fact sound deeper than it is.
+**Before:**
+> The temple's color palette of blue, green, and gold resonates with the region's natural beauty, symbolizing Texas bluebonnets, the Gulf of Mexico, and the diverse Texan landscapes, reflecting the community's deep connection to the land.
+**After:**
+> The temple is painted blue, green, and gold, colors meant to evoke Texas bluebonnets and the Gulf of Mexico.
+
+### 4. Sales language
+
+**Words to watch:** boasts a, vibrant, rich (figurative), profound, enhancing its, showcasing, exemplifies, commitment to, natural beauty, nestled, in the heart of, groundbreaking (figurative), renowned, breathtaking, must-visit, stunning
+**Problem:** AI writing often sounds like an advertisement, especially when it describes places, culture, products, or organizations.
+**Before:**
+> Nestled within the breathtaking region of Gonder in Ethiopia, Alamata Raya Kobo stands as a vibrant town with a rich cultural heritage and stunning natural beauty.
+**After:**
+> Alamata Raya Kobo is a town in the Gonder region of Ethiopia.
+
+### 5. Vague sources
+
+**Words to watch:** Industry reports, Observers have cited, Experts argue, Some critics argue, several sources/publications (when few cited)
+**Problem:** AI writing often assigns a claim to unnamed experts, critics, reports, or observers.
+**Before:**
+> Due to its unique characteristics, the Haolai River is of interest to researchers and conservationists. Experts believe it plays a crucial role in the regional ecosystem.
+**After:**
+> Researchers and conservationists study the Haolai River for its unusual characteristics.
+
+Name a real source when the source text provides one. Otherwise, remove the unsupported claim. Never invent a source.
+
+### 6. Formulaic challenges and outlook sections
+
+**Words to watch:** Despite its... faces several challenges..., Despite these challenges, Challenges and Legacy, Future Outlook
+**Problem:** AI articles often add a stock section about challenges, future prospects, or continued growth. These sections usually repeat vague claims instead of adding facts.
+**Before:**
+> Despite its industrial prosperity, Korattur faces challenges typical of urban areas, including traffic congestion and water scarcity. Despite these challenges, with its strategic location and ongoing initiatives, Korattur continues to thrive as an integral part of Chennai's growth.
+**After:**
+> Korattur has recurring traffic congestion and water shortages.
+
+Add details such as dates or public actions only when they come from the source or the user.
+
+## Language and grammar patterns
+
+### 7. Overused AI words
+
+**High-frequency AI words:** Actually, additionally, align with, crucial, delve, emphasizing, enduring, enhance, fostering, garner, gate/gated/gating (figurative; preserve established technical usage), highlight (verb), interplay, intricate/intricacies, key (adjective), landscape (abstract noun), pivotal, quietly, showcase, tapestry (abstract noun), testament, underscore (verb), valuable, vibrant
+**Problem:** AI writing uses these words much more often than most people do, especially in groups.
+**Before:**
+> Additionally, a distinctive feature of Somali cuisine is the incorporation of camel meat. An enduring testament to Italian colonial influence is the widespread adoption of pasta in the local culinary landscape, showcasing how these dishes have integrated into the traditional diet.
+**After:**
+> Somali cuisine also includes camel meat, which is considered a delicacy. Pasta dishes, introduced during Italian colonization, remain common, especially in the south.
+
+### 8. Avoiding is and are
+
+**Words to watch:** serves as/stands as/marks/represents [a], boasts/features/offers [a]
+**Problem:** AI writing often replaces simple verbs such as *is*, *are*, and *has* with longer phrases.
+**Before:**
+> Gallery 825 serves as LAAA's exhibition space for contemporary art. The gallery features four separate spaces and boasts over 3,000 square feet.
+**After:**
+> Gallery 825 is LAAA's exhibition space for contemporary art. The gallery has four rooms totaling 3,000 square feet.
+
+### 9. Not X but Y and clipped negative endings
+**Problem:** AI writing overuses forms such as "Not only...but..." and "It's not just X, it's Y."
+
+It also adds clipped endings such as "no guessing" instead of writing a clear clause.
+**Before:**
+> It's not just about the beat riding under the vocals; it's part of the aggression and atmosphere. It's not merely a song, it's a statement.
+**After:**
+> The heavy beat adds to the aggressive tone.
+**Before (tailing negation):**
+> The options come from the selected item, no guessing.
+**After:**
+> The options come from the selected item without forcing the user to guess.
+
+### 10. Forced groups of three
+**Problem:** AI writing often forces ideas into groups of three to sound complete.
+**Before:**
+> The event features keynote sessions, panel discussions, and networking opportunities. Attendees can expect innovation, inspiration, and industry insights.
+**After:**
+> The event includes talks and panels. There's also time for informal networking between sessions.
+
+### 11. Changing names and repeating sentence openings
+**Problem:** AI writing handles repetition by rule instead of by ear. It may keep renaming the same person or thing. It may also start several sentences with the same subject, often *she* or *he*.
+
+Use one clear name for the same subject. For repeated openings, merge sentences, change the subject when that helps, or begin with the action.
+**Before (synonym cycling):**
+> The protagonist faces many challenges. The main character must overcome obstacles. The central figure eventually triumphs. The hero returns home.
+**After:**
+> The protagonist faces many challenges but eventually triumphs and returns home.
+**Before (repeated openings):**
+> She noted the door. She noted the lock on it. She filed both away.
+**After:**
+> She noted the door and its lock, then filed both away.
+
+Do not ban the repeated word. Fix the repeated sentence pattern. The remaining sentence may still start with "She."
+
+### 12. False from X to Y ranges
+**Problem:** AI writing often uses "from X to Y" when X and Y do not form a real range.
+**Before:**
+> Our journey through the universe has taken us from the singularity of the Big Bang to the grand cosmic web, from the birth and death of stars to the enigmatic dance of dark matter.
+**After:**
+> The book covers the Big Bang, star formation, and current theories about dark matter.
+
+### 13. Passive voice and missing subjects
+**Problem:** AI writing often hides who acts or drops the subject. Use active voice when it makes the actor and action clearer.
+**Before:**
+> No configuration file needed. The results are preserved automatically.
+**After:**
+> You do not need a configuration file. The system preserves the results automatically.
+
+## Style patterns
+
+### 14. Em and en dashes
+
+**Rule:** The final rewrite must not contain em dashes (—) or en dashes (–), unless the writer's sample uses them. Replace a dash with a period, comma, colon, or parentheses, or rewrite the sentence. Also check for spaced dashes (` — `) and double hyphens (` -- `) used as dashes.
+**Before:**
+> The term is primarily promoted by Dutch institutions—not by the people themselves. You don't say "Netherlands, Europe" as an address—yet this mislabeling continues—even in official documents.
+**After:**
+> The term is primarily promoted by Dutch institutions, not by the people themselves. You don't say "Netherlands, Europe" as an address, yet this mislabeling continues in official documents.
+**Before:**
+> The new policy — announced without warning — affects thousands of workers. The changes -- long overdue according to critics -- will take effect immediately.
+**After:**
+> The new policy, announced without warning, affects thousands of workers. The changes, long overdue according to critics, will take effect immediately.
+
+Before returning the rewrite, search for `—` and `–`. Remove each one unless the writer's sample uses that mark. In that case, match the sample's rate.
+
+### 15. Too much bold text
+**Problem:** AI chatbots often bold words and phrases without a clear reason.
+**Before:**
+> It blends **OKRs (Objectives and Key Results)**, **KPIs (Key Performance Indicators)**, and visual strategy tools such as the **Business Model Canvas (BMC)** and **Balanced Scorecard (BSC)**.
+**After:**
+> It blends OKRs, KPIs, and visual strategy tools like the Business Model Canvas and Balanced Scorecard.
+
+### 16. Lists with bold mini-headings
+**Problem:** AI writing often uses vertical lists in which every item starts with a bold label and a colon.
+**Before:**
+> - **User Experience:** The user experience has been significantly improved with a new interface.
+> - **Performance:** Performance has been enhanced through optimized algorithms.
+> - **Security:** Security has been strengthened with end-to-end encryption.
+**After:**
+> The update improves the interface, speeds up load times through optimized algorithms, and adds end-to-end encryption.
+
+### 17. Title case in headings
+**Problem:** AI chatbots often capitalize every main word in a heading.
+**Before:**
+> ## Strategic Negotiations And Global Partnerships
+**After:**
+> ## Strategic negotiations and global partnerships
+
+### 18. Emojis
+**Problem:** AI chatbots often add emojis to headings and list items as decoration.
+**Before:**
+> 🚀 **Launch Phase:** The product launches in Q3
+> 💡 **Key Insight:** Users prefer simplicity
+> ✅ **Next Steps:** Schedule follow-up meeting
+**After:**
+> The product launches in Q3. User research showed a preference for simplicity. Next step: schedule a follow-up meeting.
+
+### 19. Curly quotation marks
+**Problem:** ChatGPT often uses curly quotes (“...”) where the writer or target format uses straight quotes ("...").
+**Before:**
+> He said “the project is on track” but others disagreed.
+**After:**
+> He said "the project is on track" but others disagreed.
+
+## Chatbot patterns
+
+### 20. Chatbot text left in the answer
+
+**Words to watch:** I hope this helps, Of course!, Certainly!, You're absolutely right!, Would you like..., Want me to...?, Want me to give examples?, Should I continue?, let me know, here is a...
+**Problem:** A chatbot's greeting, offer, or closing sometimes remains in text that should stand on its own.
+**Before:**
+> Here is an overview of the French Revolution. I hope this helps! Let me know if you'd like me to expand on any section.
+**After:**
+> The French Revolution began in 1789 when financial crisis and food shortages led to widespread unrest.
+
+### 21. Knowledge-limit disclaimers and guesses
+
+**Words to watch:** as of [date], Up to my last training update, While specific details are limited/scarce..., based on available information, not publicly available, maintains a low profile, keeps personal details private, prefers to stay out of the spotlight, likely [grew up/studied/began], it is believed that
+**Problem:** Older models may mention the date when their knowledge ends. A model may also explain that it could not find a source, then fill the gap with a plausible guess. State what the source does not show, or remove the sentence. Do not present a guess as a fact.
+**Before (cutoff disclaimer):**
+> While specific details about the company's founding are not extensively documented in readily available sources, it appears to have been established sometime in the 1990s.
+**After:**
+> The company's founding date is not documented in the available sources. (Or cut the sentence. State a date only if a source provides one.)
+**Before (speculative gap-fill):**
+> Information about her early life is not publicly available, suggesting she maintains a low profile and keeps personal details private. She likely grew up in a middle-class household, which shaped her later interest in education reform.
+**After:**
+> Her early life is not documented in the available sources. (Or omit the section.)
+
+### 22. Overly agreeable tone
+**Problem:** AI assistants often praise the user or agree before giving the answer.
+**Before:**
+> Great question! You're absolutely right that this is a complex topic. That's an excellent point about the economic factors.
+**After:**
+> The economic factors you mentioned are relevant here.
+
+## Filler and hedging
+
+### 23. Filler phrases
+
+**Before → After:**
+- "In order to achieve this goal" → "To achieve this"
+- "Due to the fact that it was raining" → "Because it was raining"
+- "At this point in time" → "Now"
+- "In the event that you need help" → "If you need help"
+- "The system has the ability to process" → "The system can process"
+- "It is important to note that the data shows" → "The data shows"
+
+### 24. Too many qualifiers
+
+**Phrases to watch:** to be fair, it's also possible, could potentially, might arguably, in some cases it may, this is an inference
+**Problem:** Repeated editing can add one qualifier after another until every claim sounds uncertain. Keep a qualifier only when the source supports it and the meaning needs it. Remove caveats that only repair an earlier overstatement.
+**Before:**
+> It could potentially possibly be argued that the policy might have some effect on outcomes.
+**After:**
+> The policy may affect outcomes.
+
+### 25. Generic positive endings
+**Problem:** AI writing often ends with vague optimism instead of the last useful fact.
+**Before:**
+> The future looks bright for the company. Exciting times lie ahead as they continue their journey toward excellence. This represents a major step in the right direction.
+**After:**
+> (Cut the paragraph. End on the last concrete fact instead of a send-off. If the source states real plans, use those.)
+
+### 26. Too many hyphenated word pairs
+
+**Words to watch:** third-party, cross-functional, client-facing, data-driven, decision-making, well-known, high-quality, real-time, long-term, end-to-end
+**Problem:** AI writing often hyphenates these pairs everywhere. Keep the hyphen before a noun when grammar needs it, as in `a high-quality report`. Drop it after the noun, as in `the report is high quality`.
+**Before:**
+> The cross-functional team delivered a high-quality, data-driven report. The team is cross-functional, the report is high-quality, and the methodology is data-driven.
+**After:**
+> The cross-functional team delivered a high-quality, data-driven report. The team is cross functional, the report is high quality, and the methodology is data driven.
+
+### 27. Pretending to reveal a deeper truth
+
+**Phrases to watch:** The real question is, at its core, in reality, what really matters, fundamentally, the deeper issue, the heart of the matter
+**Problem:** AI writing uses these phrases to make an ordinary point sound like a hidden truth.
+**Before:**
+> The real question is whether teams can adapt. At its core, what really matters is organizational readiness.
+**After:**
+> The question is whether teams can adapt. That mostly depends on whether the organization is ready to change its habits.
+
+### 28. Announcing the next point
+
+**Phrases to watch:** Let's dive in, let's explore, let's break this down, here's what you need to know, now let's look at, without further ado, heads up, quick note, before I forget
+**Problem:** AI writing often announces the next point instead of stating it. A casual phrase such as "one thing that bit me" can have the same problem. Remove the announcement, not just its formal tone.
+**Before:**
+> Let's dive into how caching works in Next.js. Here's what you need to know.
+**After:**
+> Next.js caches data at multiple layers, including request memoization, the data cache, and the router cache.
+**Before (casual register):**
+> One thing that bit me hard, so pay attention to this part: the webpack dev server doesn't send the CORS header by default.
+**After:**
+> The webpack dev server doesn't send the CORS header by default.
+
+### 29. A heading repeated in the first sentence
+
+**Signs to watch:** A heading followed by a one-line paragraph that simply restates the heading before the real content begins.
+**Problem:** AI writing often follows a heading with a sentence that only repeats the heading. Remove the repeated sentence.
+**Before:**
+> ## Performance
+>
+> Speed matters.
+>
+> When users hit a slow page, they leave.
+**After:**
+> ## Performance
+>
+> When users hit a slow page, they leave.
+
+### 30. Writing about the previous version
+**Problem:** Documentation and comments should describe the current behavior. Mention the previous version only in change logs, release notes, migration guides, and other documents about change.
+**Before:**
+> This function was added to replace the previous approach of iterating through all items, which caused O(n²) performance.
+**After:**
+> This function uses a hash map for O(1) lookups, avoiding the O(n²) cost of naive iteration.
+
+### 31. Forced punchlines and dramatic fragments
+**Problem:** AI writing often turns each sentence into a dramatic closing line. One short sentence can add emphasis. A row of short fragments usually feels forced.
+**Before:**
+> Then AlphaEvolve arrived. It had no preference for symmetry. No aesthetic prior. No nostalgia for human taste. The old rules were gone.
+**After:**
+> AlphaEvolve changed the search because it did not favor symmetry or human-looking designs. That made some of the older assumptions less useful.
+
+### 32. Formulaic sayings
+
+**Words to watch:** X is the Y of Z, X becomes a trap, X is not a tool but a mirror, the language of, the currency of, the architecture of
+**Problem:** AI writing often turns an ordinary claim into a saying that sounds deep but adds no detail. Replace the saying with the specific claim.
+**Before:**
+> Symmetry is the language of trust. Efficiency becomes a trap when teams forget the human layer.
+**After:**
+> Symmetric layouts often feel more predictable to users. Teams can over-optimize workflows and miss how people actually use them.
+
+### 33. Fake-candid openings
+
+**Phrases to watch:** Honestly?, Look, Here's the thing, The thing is, Let's be honest, Real talk, when used as standalone hooks or fake-candid pauses before an ordinary point.
+**Problem:** AI writing often starts with a staged pause or claim of honesty before making a routine point. State the point directly.
+**Before:**
+> Is it worth the price? Honestly? It depends on how often you'll use it.
+**After:**
+> Whether it's worth the price depends on how often you'll use it.
+
+### 34. Answering objections no one raised
+
+**Phrases to watch:** This isn't (mainly/really) about, I'm not saying/arguing/trying to, To be clear, Don't get me wrong, This is not to say, You could argue/frame this differently but, Some might say... but
+**Problem:** AI writing may answer an objection that does not appear in the text. Watch for an unattributed statement about what the writer does not mean, especially when the topic appears nowhere else. A direct claim such as "the API is not thread-safe" is not this pattern.
+**Before:**
+> This isn't mainly about prompt length, and I'm not arguing that documentation doesn't matter. You could categorize the problem another way, but the issue is whether the agent can use the instruction when it acts.
+**After:**
+> The issue is whether the agent can use the instruction when it acts.
+
+Remove only the unsupported defense. If it contains a real claim, state that claim directly. Keep an objection when the text names its source or answers it in full.
+
+### 35. Rejecting fake alternatives
+
+**Phrases to watch:** A tempting option/approach would be, One might be tempted to, An obvious approach would be, You might think... but, It would be easy to just, Some would suggest
+**Problem:** AI writing may introduce an option that no reader would consider, reject it in a clause, and never mention it again. This often leaves an old drafting idea in the final text. Remove the fake option and state the real constraint directly.
+**Before:**
+> Session tokens are rotated every 24 hours. A tempting approach would be to rotate them by restarting the auth service on a cron job, but that would drop every active session. Rotation happens in place, and clients refresh transparently.
+**After:**
+> Session tokens are rotated every 24 hours, in place, and clients refresh transparently.
+
+One rejected option may be valid. Several short, unrelated rejections are a stronger sign. Ask what new information each sentence adds. If it only records an earlier edit, rewrite the paragraph around its main point.
+
+## Check for false positives
+
+### What not to flag
+
+A person may use some of these patterns. Do not treat any item below as proof by itself:
+
+- **Perfect grammar and consistent style.** Many writers are professionals or have been edited. Polish does not equal AI.
+- **Mixed casual and formal styles.** This can reflect the writer's field, age, or personal habits.
+- **"Bland" or "robotic" prose.** AI prose has *specific* tells. Generic dryness without those tells is just dry writing.
+- **Formal or academic words.** §7 lists specific words that AI writing overuses. Do not simplify every formal word.
+- **Letter-style opening or closing on a comment.** Salutations and sign-offs predate ChatGPT by centuries.
+- **Common transition words in isolation.** *Additionally*, *moreover*, *consequently* are AI-coded only when piled up. One *however* is not a tell.
+- **Curly quotes alone.** macOS, Word, Google Docs, and most CMSes auto-curl by default. Curly quotes only count when stacked with other tells.
+- **Em dashes alone.** Many editors and journalists use them often. Em dashes are evidence only when paired with formulaic sales-y rhythm.
+- **One short sentence for emphasis.** Flag dramatic fragments only when several appear in a row.
+- **Deliberate repeated openings.** Writers may repeat an opening to build rhythm or pressure, as in "She came. She saw. She conquered." Change it only when the repetition adds nothing.
+- **"Honestly" or "look" mid-sentence.** These are ordinary in casual writing. The tell is the standalone theatrical opener, not the word itself.
+- **Useful limits and disclaimers.** Keep scope statements, legal and safety notices, real corrections, named objections, replies, and FAQ answers.
+- **Real alternatives.** Keep options that a reader may consider in a design document, tutorial, or argument. Remove only an unlikely option that the text dismisses and never uses again.
+- **Unsourced claims.** Most of the web is unsourced. Lack of citations doesn't prove anything.
+- **Correct, complex formatting.** Visual editors and templates produce clean output without any AI.
+- **Secondhand text.** Do not rewrite watched phrases inside quotations, titles, proper names, or examples where the phrase is being discussed rather than used.
+
+When unsure, look for several patterns together. One em dash proves nothing. Several stock patterns in the same passage are stronger evidence.
+
+### Human details to keep
+
+These details often carry the writer's voice. Keep them unless they hurt the meaning:
+
+- **Specific, unusual details.** Keep a real address, an odd quote, or a phrase such as "the lawyer who used to work upstairs from my dentist."
+- **Mixed feelings and unresolved tension.** Keep lines such as "I think this is mostly good, but it bothers me, and I can't fully explain why."
+- **Dated, era-bound references.** Slang, memes, or in-jokes that map to a specific year and subculture. Models lag by a year or more.
+- **Deliberate first-person choices.** Keep a cut or word choice when the writer can explain why it belongs.
+- **Variety in sentence length.** Real writing alternates short and long. AI writing tends toward an even, mid-length cadence.
+- **Genuine asides, parentheticals, or self-corrections.** "(I keep wanting to say 'almost' here, but it really was certain.)" Models rarely interrupt themselves like this.
+- **Edits made before November 30, 2022.** ChatGPT's public launch. Anything older than that is, with very rare exceptions, not AI-written.
+
+---
+
+## How to return the result
+
+**Pasted text (default).** Return the draft, a short list of remaining AI patterns, and the final rewrite.
+
+**File mode.** When the user names a file, run the full rewrite process but write only the final text to the file. Change prose only. Keep code blocks, YAML metadata, data, and link targets unchanged. Then give the user a short summary.
+
+**Embedded mode.** When another task uses this skill for a pull request, commit message, or document, return only the final text.
+
+## Rewrite process
+
+1. Read the source and mark each AI pattern.
+2. Write a draft. Read it aloud. Check the rhythm, details, simple verbs such as *is* and *has*, and the right level of formality.
+3. Ask two questions:
+ - **"What still sounds AI-generated?"**
+ - **"Did the rewrite add or remove any fact, name, number, date, quote, citation, ranking, or other claim?"**
+ Treat any unsupported addition or lost claim as an error.
+4. Write the final version. State each point naturally instead of patching one flagged phrase at a time. If a sentence stays awkward, rewrite the paragraph around its main point. Apply the dash rule in §14.
+
+Return the result required by [How to return the result](#how-to-return-the-result).
+
+## Source
+
+This skill is based on [Wikipedia: Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing), maintained by WikiProject AI Cleanup. Its patterns come from reviews of AI-generated text on Wikipedia.
+
+Wikipedia's main point: "LLMs use statistical algorithms to guess what should come next. The result tends toward the most statistically likely result that applies to the widest variety of cases."
diff --git a/PROJECT_CONTEXT.md b/PROJECT_CONTEXT.md
index 25973dc..7a6e9a8 100644
--- a/PROJECT_CONTEXT.md
+++ b/PROJECT_CONTEXT.md
@@ -64,7 +64,7 @@ Use this file for verified target-repository facts only. Keep unknown values as
## Sensors And Hardware
- Cameras: Intel RealSense **D410**, Product Id `0AD2`, FW `5.17.0.10`, USB 3.2 — verified via `rs-enumerate-devices` (2026-08). **No RGB** (Stereo Module only), **no built-in IMU**, no alternating-emitter mode, rolling shutter, 69° FOV. Configured 640×480 @ 30 Hz for depth + infra1 + infra2; emitter fixed at `1` (Laser), never `2` (Laser Auto). Min-Z **estimated** ~22 cm at this resolution — not yet measured.
-- LiDAR: RICHBEAM 2D ToF. **Driver not yet obtained** — `richbeam.launch` launches nothing; the real node is commented out pending the vendor package. Four properties still unverified: interface (Ethernet vs USB), whether the device supplies its own timestamp, true FOV (270° vs 360°), scan rate/angular resolution. Gazebo stands in with `gpu_ray`: 960 samples, FOV ±120° (deliberately 240°, not 270°, so rays do not hit the robot body), 15 Hz, range 0.05–30 m.
+- LiDAR: **RICHBEAM LakiBeam 1L** — verified from datasheet (2026-09). FOV 270°, range ≥40 m @70% reflectivity / ≥20 m @10%, ±2 cm, scan freq **only** 10/20/25/30 Hz, angular resolution 0.1° **only** at 10 Hz else 0.25°, 43.2 kHz sampling, **940 nm** Class 1, RJ45 UDP 100 Mbps, 9–36 V ≤2 W, 160 g, 60×60×80 mm, IP65, 100 kLux immunity. Configured at **25 Hz / 0.25° → 1081 samples over 270°**. Device is purchased but has not been powered on yet. Driver is `RichbeamTechnology/Lakibeam_ROS1_Driver` (catkin package name is literally `lidar`, node type `lidar_scan_node`, Noetic supported, manifest license is `TODO`) — it has **three verified bugs**: host-side `ros::Time::now()` stamping, `angle_min/max` hardcoded to ±180° regardless of the true 270° FOV, and `range_min`/`range_max` hardcoded to 0.0/100.0. Therefore the driver publishes `/scan_raw` and a `laser_filters` chain sanitises it into `/scan`. Gazebo stands in with `gpu_ray` at the same honest 270°/1081/25 Hz/0.05–40 m and feeds the same filter chain. Body self-occlusion beyond ±120.5° (laser at x=0.24 vs body front x=0.14, half-width 0.17) is cut at ±118°, leaving ~236° effective.
- IMU: **not purchased**. Planned ICM-42688-P or BMI088 read by an MCU (STM32F4/Teensy 4.0/RP2040) over serial at 921600 baud, timestamped at sample time. Barometer BMP390/BMP581 planned in the same module. Gazebo stands in with `libgazebo_ros_imu_sensor` @ 200 Hz using datasheet-derived noise.
- Compute target: development on i5-14500 + RTX 4060. Deployment target is an industrial PC (IPC) — model not chosen (`docs/ROADMAP.md` GĐ8).
- Accelerators: RTX 4060, used only for Gazebo `gpu_ray`. No inference accelerator in the pipeline.
@@ -102,7 +102,7 @@ Use this file for verified target-repository facts only. Keep unknown values as
- Verified files: `README.md`; `docs/ARCHITECTURE.md`; `docs/HARDWARE.md`; all 8 `package.xml`; all launch files in `robot_bringup`, `robot_drivers`, `robot_sim`, `perception_3d`, `slam_core`, `robot_safety`, `localization_ops`; `robot.urdf.xacro`; `sensors.xacro`; `gazebo_sensors.xacro`; `robot.yaml`; `ekf_odom.yaml`; `slam_core.yaml`; `safety.yaml`; `depth_filter.yaml`; `floors.yaml`; `topics_to_record.yaml`; `record_bag.sh`; `src/third_party/{README.md,.rosinstall}`; publisher/subscriber declarations in every `.cpp` and `.py` node
- Open questions:
1. `slam_core` is passthrough — GTSAM is not installed, so there is no optimization, no scan matching, no loop closure, and pose **will drift**. This is expected until GĐ5.
- 2. RICHBEAM driver absent; the four LiDAR properties in `docs/HARDWARE.md` §2 are unverified, so `/scan` on real hardware is not yet characterized.
+ 2. LiDAR specs and driver are now known (see Sensors), but the device has **not been powered on**. Two things remain measurable only on hardware, both via `slam_eval/scripts/check_scan.py`: what fills the ~90° arc the driver fabricates but the device never scans (if it is `inf`, `inf_is_valid: true` in `costmap_common.yaml` would raytrace-clear through walls), and whether host-side timestamp jitter is within budget (5 ms ≈ 4 cm at 10 m is tolerable; 20 ms ≈ 16 cm is not). Also unverified: which physical direction is the driver's 0°, which decides `angle_offset`.
3. IMU, barometer, bumper, and ultrasonic sensors are unpurchased. With `ultrasonic_topics: []`, glass and mirrors cannot be detected at all.
4. Every covariance in `slam_core.yaml`, `ekf_odom.yaml`, `robot.yaml`, and `imu_bridge.launch` is a datasheet guess pending calibration.
5. librealsense version conflict (Intel 2.58.3 vs ROS 2.50.0 with wrapper 2.3.2) blocks running the real camera. Does not affect simulation.
diff --git a/ROS_TOPIC_MAP.md b/ROS_TOPIC_MAP.md
index d390f05..9759c64 100644
--- a/ROS_TOPIC_MAP.md
+++ b/ROS_TOPIC_MAP.md
@@ -10,7 +10,8 @@ Parity rule (`docs/ARCHITECTURE.md` §6): simulation and real hardware publish t
| Topic | ROS 1/ROS 2 | Message Type | Publishers | Subscribers | Rate | QoS/Queue | Notes |
| --- | --- | --- | --- | --- | --- | --- | --- |
-| `/scan` | ROS 1 | `sensor_msgs/LaserScan` | sim: `richbeam_lidar` gpu_ray plugin (`libgazebo_ros_gpu_laser.so`); real: RICHBEAM driver — **absent** | `safety_monitor` (1), `slam_core` (10), `move_base` obstacle_layer | 15 Hz *(sim)* | sub 1 / 10 | frame `laser_link`. Sim FOV is ±120° / 960 samples — deliberately narrower than 270° so rays do not hit the robot body (at 270°, 71.7% of rays returned <0.35 m). Real FOV, scan rate and timestamp source all unverified. |
+| `/scan_raw` | ROS 1 | `sensor_msgs/LaserScan` | sim: `richbeam_lidar` gpu_ray plugin (`libgazebo_ros_gpu_laser.so`); real: `lidar_scan_node` (pkg `lidar`, RichbeamTechnology driver) | `scan_filter` only | 25 Hz | 10 | **Raw, untrusted.** Nothing else may subscribe. Sim publishes an honest 270° / 1081 samples; the real driver publishes a scan that *claims* ±180° with `range_min=0.0` / `range_max=100.0` regardless of the device's true 270° / 0.05–40 m. See `docs/HARDWARE.md` §2 for the three driver bugs. |
+| `/scan` | ROS 1 | `sensor_msgs/LaserScan` | `scan_filter` (`laser_filters/scan_to_scan_filter_chain`) | `safety_monitor` (1), `slam_core` (10), `move_base` obstacle_layer, RTAB-Map | 25 Hz | sub 1 / 10 | frame `laser_link`. **Sanitised**: header `range_min`/`range_max` corrected to 0.05 / 40.0, zero returns → NaN, body-occluded arc beyond ±118° blanked to `range_max+1`. Effective FOV ~236° of the device's 270°. Identical chain in sim and on hardware. |
| `/imu/data_raw` | ROS 1 | `sensor_msgs/Imu` | sim: `libgazebo_ros_imu_sensor`; real: `imu_bridge_node.py` (MCU over serial) | `wheel_odom` (100), `gravity_align` (200), `slam_core` (200), `ekf_odom` (20) | 200 Hz *(sim)* | pub 100 (real) | frame `imu_link`. `ekf_odom` fuses **only** angular velocity Z — linear acceleration is deliberately excluded. Roll/pitch are consumed by `gravity_align`, never estimated. |
| `/joint_states` | ROS 1 | `sensor_msgs/JointState` | sim: `diff_drive_controller` (`publishWheelJointState`); L0: `joint_state_publisher` (fake); real: MCU firmware | `wheel_odom` (50), `robot_state_publisher` | ~50 Hz *(sim)* | sub 50 | Joints `left_wheel_joint` / `right_wheel_joint` are **the encoder interface** — identical name in all three sources so `wheel_odom_node` cannot tell where it is running. |
| `/camera/depth/image_rect_raw` | ROS 1 | `sensor_msgs/Image` | sim: `libgazebo_ros_openni_kinect`; real: `realsense2_camera` | `depth_to_cloud` nodelet | 30 Hz | — | 640×480. Resolution chosen for Min-Z ~22 cm over 848×480's ~30 cm. |
@@ -23,7 +24,7 @@ Parity rule (`docs/ARCHITECTURE.md` §6): simulation and real hardware publish t
| `/baro/pressure` | ROS 1 | `sensor_msgs/FluidPressure` | sim: `baro_sim`; real: `imu_bridge` (BMP390) | `floor_detector` (10) | 25 Hz *(sim)* | pub 10 | Only short-term *differences* are usable — absolute pressure drifts hundreds of Pa/hour with weather while one floor is ~40–45 Pa. |
| `/baro/temperature` | ROS 1 | `sensor_msgs/Temperature` | `imu_bridge` — **real only** | none in-repo | Unknown / needs confirmation | pub 10 | `baro_sim` does not publish this. |
| `/bumper` | ROS 1 | `std_msgs/Bool` | **no publisher** — hardware not purchased | `safety_monitor` (1) | — | sub 1 | Covers the depth camera's Min-Z blind zone. Ideally cuts motor power in hardware, not through ROS. |
-| `/ultrasonic/*` | ROS 1 | `sensor_msgs/Range` | **no publisher** — hardware not purchased | `safety_monitor`, one sub per entry in `ultrasonic_topics` | — | sub 1 each | ⚠️ `ultrasonic_topics` is currently `[]`. Ultrasound is the **only** sensor in this set that detects glass and mirrors (905 nm LiDAR and IR depth both pass through). Empty list = glass is invisible to the robot. |
+| `/ultrasonic/*` | ROS 1 | `sensor_msgs/Range` | **no publisher** — hardware not purchased | `safety_monitor`, one sub per entry in `ultrasonic_topics` | — | sub 1 each | ⚠️ `ultrasonic_topics` is currently `[]`. Ultrasound is the **only** sensor in this set that detects glass and mirrors (940 nm LiDAR and IR depth both pass through). Empty list = glass is invisible to the robot. |
## Odometry And State Estimation
@@ -48,10 +49,10 @@ Parity rule (`docs/ARCHITECTURE.md` §6): simulation and real hardware publish t
| Topic | ROS 1/ROS 2 | Message Type | Publishers | Subscribers | Rate | QoS/Queue | Notes |
| --- | --- | --- | --- | --- | --- | --- | --- |
-| `/map` | ROS 1 | `nav_msgs/OccupancyGrid` | **three mutually exclusive sources**: `octomap_server` (`projected_map` remapped, mapping/L3+), `map_server` (localization mode), `multi_map_manager` (multi-floor, latched) | `amcl`, `move_base` global_costmap `static_layer` | on update / latched | latched for `map_server` and `multi_map_manager` | The remap exists so `move_base` and the costmaps never need to know which mode is running. Exactly one publisher must be active. |
+| `/map` | ROS 1 | `nav_msgs/OccupancyGrid` | **three mutually exclusive sources**: `rtabmap` (`grid_map` remapped, mapping + localization), `map_server`, `multi_map_manager` (multi-floor, latched) | `move_base` global_costmap `static_layer` | on update / latched | latched for `map_server` and `multi_map_manager` | The remap exists so `move_base` and the costmaps never need to know which mode is running. Exactly one publisher must be active. ⚠️ `octomap_server` does **not** publish here — its `projected_map` is remapped to `/octomap_grid` (debug only); see `docs/SIM_VS_REAL.md` §5 for why a projected octomap grid is unusable for navigation. |
| `/map_metadata` | ROS 1 | `nav_msgs/MapMetaData` | `map_server`, `multi_map_manager` | standard consumers | latched | 1 | |
| `/map_name` | ROS 1 | `std_msgs/String` | `multi_map_manager` | none in-repo | latched | 1 | Which floor map is currently loaded. |
-| `/initialpose` | ROS 1 | `geometry_msgs/PoseWithCovarianceStamped` | `dock_init`, RViz "2D Pose Estimate" | `amcl` | on demand (`delay: 3.0` after start) | — | frame `map`. Startup pose comes from the charging dock — a *known* pose — so global relocalization is not needed for ~95% of real starts. ⚠️ Dock pose in `floors.yaml` is still `0,0,0` and must be measured after a real map exists. |
+| `/initialpose` | ROS 1 | `geometry_msgs/PoseWithCovarianceStamped` | `dock_init`, `global_scan_init`, RViz "2D Pose Estimate" | `rtabmap` (via `initialpose` → `/initialpose` remap) | on demand (`delay: 3.0` after start) | — | frame `map`. ⚠️ There is **no `amcl`** in this system — RTAB-Map does localization itself; see `localization.launch` for why. Startup pose comes from the charging dock — a *known* pose — so global relocalization is not needed for ~95% of real starts. ⚠️ Dock pose in `floors.yaml` is still `0,0,0` and must be measured after a real map exists. |
| `/floor/current` | ROS 1 | `std_msgs/Int32` | `floor_detector` | `multi_map_manager` (1) | on change | 1, latched | |
| `/floor/status` | ROS 1 | `std_msgs/String` | `floor_detector` | none in-repo | on change | 1, latched | |
| `/floor/tag_hint` | ROS 1 | `std_msgs/Int32` | `apriltag_ros` — **not installed** | `floor_detector` (5) | — | sub 5 | Barometer says *that* the floor changed; AprilTag says *which* floor. Hotel floors look identical, so geometric and visual recognition both fail — this is the absolute identity source. `tag_to_floor` mapping is in `floors.yaml`. |
diff --git a/agent_skills_claude_code b/agent_skills_claude_code
new file mode 160000
index 0000000..7428150
--- /dev/null
+++ b/agent_skills_claude_code
@@ -0,0 +1 @@
+Subproject commit 74281503912851d6bec3d461de8c8b9e0b17a62d
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 95c18a0..b931055 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -271,7 +271,7 @@ cả nhận dạng hình học lẫn nhận dạng ảnh đều sẽ nhầm.
| Vấn đề | Vì sao SLAM bó tay | Giải pháp thật |
|---|---|---|
-| **Cửa kính** | LiDAR ToF 905nm **xuyên qua** kính; depth IR cũng vậy | **Siêu âm** (sóng âm phản xạ tốt trên kính) + virtual wall vẽ tay vào map |
+| **Cửa kính** | LiDAR ToF 940nm **xuyên qua** kính; depth IR cũng vậy | **Siêu âm** (sóng âm phản xạ tốt trên kính) + virtual wall vẽ tay vào map |
| **Gương** | Tạo hình học ảo và feature ảo → map bị bơm thêm "căn phòng không tồn tại" | Virtual wall |
| **Vùng mù Min-Z ~22cm** | Depth stereo không có dữ liệu gần hơn ngưỡng | **Bumper cơ khí** |
| **Bề mặt đen** (ghế da, thảm sẫm) | ToF dựa vào photon phản xạ; vật đen hấp thụ gần hết | Test tại chỗ; nếu nặng thì đổi model LiDAR |
diff --git a/docs/HARDWARE.md b/docs/HARDWARE.md
index e7394b3..84f7c84 100644
--- a/docs/HARDWARE.md
+++ b/docs/HARDWARE.md
@@ -59,30 +59,104 @@ xứng rủi ro).
---
-## 2. RICHBEAM 2D ToF LiDAR
+## 2. RICHBEAM LakiBeam 1L — đã xác minh
ToF hơn hẳn LiDAR tam giác (RPLidar A1/A2, YDLidar): tầm xa hơn, độ chính xác ổn
định theo khoảng cách, ít bị nhiễu bởi ánh sáng môi trường.
-### ⚠️ 4 điều phải xác minh khi có driver
+### Thông số (datasheet)
-| # | Câu hỏi | Ảnh hưởng |
+| Mục | Giá trị |
+|---|---|
+| FOV | **270°** |
+| Tầm | **≥40 m @70% reflectivity**, ≥20 m @10% |
+| Độ chính xác | ±2 cm |
+| Scan frequency | **chỉ 10 / 20 / 25 / 30 Hz** |
+| Angular resolution | **0.1° chỉ ở 10 Hz**; 0.25° ở 20/25/30 Hz |
+| Sampling rate | 43.2 kHz |
+| Bước sóng | **940 nm**, Class 1, <1 mW |
+| Interface | RJ45 / Type-C, **UDP/IP 100 Mbps** |
+| Nguồn | 9–36 V, ≤2 W |
+| Khối lượng / kích thước | 160 g / 60×60×80 mm |
+| Nhiệt độ | −25…60 °C |
+| Chống sáng | 100 kLux |
+| IP | IP65 |
+
+### Cấu hình chốt: 25 Hz / 0.25° → 1081 mẫu trên 270°
+
+Angular resolution và scan freq **ràng buộc cứng** với nhau — không chọn được cả
+hai. Chọn 25 Hz vì:
+
+- `Icp/VoxelSize = 0.05` trong `rtabmap.launch` đã nuốt hết lợi thế của 0.1°
+ (ở 10 m: 0.1° → 1.7 cm, 0.25° → 4.4 cm, voxel 5 cm gộp cả hai)
+- Méo do chuyển động: 10 Hz = 100 ms/scan, xoay 1.2 rad/s quét **6.9°** trong một
+ scan; 25 Hz = 40 ms → **2.75°**. Driver không deskew.
+
+### 4 câu hỏi cũ — đã trả lời
+
+| # | Câu hỏi | Trả lời |
|---|---|---|
-| 1 | **Interface: Ethernet hay USB?** | Ethernet → jitter thấp, có thể timestamp trên thiết bị. USB → timestamp gán ở driver, jitter 10–50 ms |
-| 2 | **LiDAR có tự cấp timestamp không?** | Nếu có → dùng nó. **Tuyệt đối không dùng `ros::Time::now()` trong driver** |
-| 3 | **FOV 270° hay 360°?** | 270° thì phía sau mù → ảnh hưởng scan matching khi lùi và ảnh hưởng an toàn |
-| 4 | **Scan rate & angular resolution?** | Tối thiểu 10Hz / 0.25° để scan matching hoạt động tốt |
+| 1 | Interface? | **Ethernet UDP** (RJ45). Jitter thấp ✅ |
+| 2 | Thiết bị tự cấp timestamp? | **KHÔNG** — xem bug 1 dưới ⚠️ |
+| 3 | FOV 270° hay 360°? | **270°** |
+| 4 | Scan rate / angular res? | 10–30 Hz, ghép cặp với resolution |
-Kiểm tra #2: `rostopic echo /scan/header` so với `date +%s.%N`.
+### ⚠️ 3 bug trong driver chính hãng
-Sau khi có số thật, cập nhật `robot_sim/urdf/gazebo_sensors.xacro` cho khớp.
+Driver: [`RichbeamTechnology/Lakibeam_ROS1_Driver`](https://github.com/RichbeamTechnology/Lakibeam_ROS1_Driver)
+— package tên là `lidar`, node type `lidar_scan_node`, hỗ trợ Noetic.
+License trong manifest là `TODO` → **phải xin license bằng văn bản trước khi
+thương mại hoá**.
+
+1. **Host-side timestamp.** `scan_begin = ros::Time::now()` tại azimuth-zero.
+ Đúng quy ước LaserScan (stamp = tia đầu), nhưng mang jitter của host.
+ → Time offset LiDAR↔IMU ở GĐ2 là **bắt buộc**, không phải tuỳ chọn.
+2. **Khai 360° cho thiết bị 270°.** `angle_min/max = ±180°` vô điều kiện, kể cả
+ khi `scan_range_start/stop` thu hẹp. Cái gì lấp vào cung bịa ra thì **chưa
+ biết, phải đo** — nếu là `inf` thì costmap (`inf_is_valid: true`) sẽ
+ raytrace-clear xuyên tường mỗi scan.
+3. **`range_min = 0.0`, `range_max = 100.0`** hardcoded (thật: 0.05 / 40).
+ `range_min = 0` vô hiệu hoá bộ lọc chuẩn `r < range_min` ở mọi consumer.
+
+Phụ: `time_increment = duration / n / 2` — chỗ `/2` sai so với REP.
+
+→ Driver **không** publish thẳng lên `/scan`. Nó publish `/scan_raw`, và
+`robot_drivers/launch/scan_filter.launch` vệ sinh rồi mới ra `/scan`.
+
+### Tự che thân robot
+
+LiDAR gắn ở `x = 0.24`, thân trước `x = 0.14`, nửa rộng `y = ±0.17`:
+
+```
+atan2(0.17, 0.14 - 0.24) = 120.5°
+```
+
+Tia ngoài **±120.5°** đâm vào thân → 29° trong 270° là rác (10.7%).
+Cắt ở `laser_filters` tại **±118°** (chừa 2.5° dung sai gá), không cắt ở driver:
+bug 2 khiến `scan_range_start/stop` không sửa được `angle_min/max` nói dối.
+
+### Mạng
+
+| | |
+|---|---|
+| IP LiDAR | `192.168.198.2` (param `sensorip`) |
+| IP host | `192.168.198.1`, hoặc `hostip: 0.0.0.0` để bind mọi interface |
+| Netmask | `255.255.255.0` |
+| Port UDP | `2368` |
+
+IPC cần **một cổng Ethernet rảnh** cho LiDAR, cộng USB3 cho D410 và serial cho
+MCU IMU. Tính vào cấu hình IPC ở GĐ8.
+
+⚠️ Mọi param của driver khai `type="string"`, **kể cả số**. Bỏ `type` đi thì
+roslaunch đặt int, `getParam(std::string&)` thất bại, và driver **âm thầm rơi về
+30 Hz** — cũng là tần số hợp lệ nên không có gì báo lỗi.
### ⚠️ Hai điểm yếu của ToF
1. **Bề mặt đen, nhám** — ghế da đen, thảm sẫm, bàn gỗ đen **rất phổ biến trong
nhà hàng/khách sạn cao cấp**. ToF dựa vào photon phản xạ; bề mặt đen hấp thụ
gần hết → **dropout, không thấy vật**.
-2. **Kính** — bước sóng 905nm **xuyên qua kính**. Không thuật toán nào cứu được;
+2. **Kính** — bước sóng 940nm **xuyên qua kính**. Không thuật toán nào cứu được;
phải giải bằng siêu âm + virtual wall.
---
@@ -96,11 +170,47 @@ Sau khi có số thật, cập nhật `robot_sim/urdf/gazebo_sensors.xacro` cho
| **MCU đọc IMU** | STM32F4 / Teensy 4.0 / RP2040 | Đọc SPI @200–400Hz, **timestamp ngay lúc lấy mẫu** |
| **Bumper cơ khí** | — | Bắt buộc: bịt vùng mù Min-Z. Lý tưởng nhất là cắt nguồn motor **bằng phần cứng**, không qua ROS |
| **Siêu âm** | 2–3 cảm biến phía trước | **Cách duy nhất phát hiện kính** |
+| **Cảm biến vực** | 2–3 ToF/IR chúc xuống ở mép trước | ~$3/con. **Bắt buộc, ngang hàng bumper** — xem §3.1 |
| **AprilTag** | In giấy | Dán mỗi tầng + trong thang máy |
**Phương án thay thế cho khối IMU+baro+MCU:** một flight controller F4/F7 giá rẻ
đã tích hợp sẵn ICM42688 + BMP390 + firmware timestamping đã kiểm thử.
+### 3.1. ⚠️ Cảm biến vực — vì sao camera không thay thế được
+
+Đã có `perception_3d/CliffDetectNodelet` phát hiện vực từ ảnh depth, **nhưng nó
+mù hoàn toàn dưới ~1.1 m**. Đây là giới hạn hình học, không phải lỗi cài đặt:
+
+```
+camera z = 0.80 m, chúc 15°, nửa FOV dọc 27.3°
+→ tia thấp nhất chúc 42.3°
+→ chỉ thấy sàn từ x = 0.80/tan(42.3°) + 0.19 ≈ 1.07 m
+```
+
+Robot phát hiện từ 1.1–2.5 m rồi dừng thì **đủ khi tiến thẳng tới mép**, nhưng
+không đủ khi:
+
+- xoay tại chỗ sát mép
+- tiến tiếp sau khi đã dừng sẵn trong vùng mù
+- tiếp cận mép theo góc chéo
+
+Ba trường hợp này chỉ cảm biến chúc xuống ở mép trước mới phủ được. Đây cũng là
+cách **mọi robot dịch vụ thương mại và mọi robot hút bụi** đều làm.
+
+⚠️ **Phân cực ngược với siêu âm.** Siêu âm kích khi `range < ngưỡng` (có vật
+chắn); cảm biến vực kích khi `range > ngưỡng` (sàn biến mất). Trong
+`robot_safety/config/safety.yaml` chúng là **hai danh sách riêng**
+(`ultrasonic_topics` và `cliff_topics`). Cắm nhầm danh sách là đảo ngược logic
+một cách âm thầm — robot sẽ lao thẳng xuống cầu thang.
+
+Ba lý do nữa khiến bản dựa trên depth không thể là lớp an toàn duy nhất:
+
+| Vấn đề | Số đo |
+|---|---|
+| Mark **sau** mép thật | mép ở 1.2 m → lệch 0.26 m; ở 4 m → lệch 0.85 m. Đã xử lý bằng cách mark tại giao điểm tia × mặt sàn, nhưng vùng mù thì không xử lý được |
+| Cầu thang tối **không trả depth** | trả lỗ (NaN), nên phải chạy trên ảnh depth chứ không trên cloud |
+| Sai số pitch chưa hiệu chuẩn | 1° ở 3 m → sàn hiện ra ở −52 mm → báo vực giả. Đang bù bằng ngưỡng nở theo tầm 2° |
+
### Nguyên tắc quan trọng hơn cả việc chọn chip
> **Cách gắn timestamp cho IMU quan trọng hơn chất lượng IMU.**
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 471fb9a..70a55f2 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -57,7 +57,7 @@ nặng trên nội thất đen, cần xét lại lựa chọn LiDAR.
| URDF & TF tree | ✅ `robot_bringup/urdf/` |
| Wheel odometry + slip detection | ✅ `robot_drivers/src/wheel_odom_node.cpp` |
| Recipe ghi rosbag | ✅ `slam_eval/scripts/record_bag.sh` |
-| **Driver RICHBEAM** | ❌ Chờ hãng — xem 4 điều phải xác minh trong `richbeam.launch` |
+| **Driver RICHBEAM** | ⚠️ Driver CÓ SẴN, không phải chờ hãng — `RichbeamTechnology/Lakibeam_ROS1_Driver`, hỗ trợ Noetic. 4 câu hỏi cũ đã trả lời, nhưng driver có **3 bug** phải bọc lại: xem `HARDWARE.md` §2 |
| **Firmware MCU cho IMU** | ❌ Chờ phần cứng — giao thức đã định nghĩa trong `imu_bridge_node.py` |
**Nghiệm thu:** tất cả topic publish ổn định, `rqt_tf_tree` không đứt gãy, ghi
diff --git a/docs/SIM_VS_REAL.md b/docs/SIM_VS_REAL.md
index a183270..1c5a083 100644
--- a/docs/SIM_VS_REAL.md
+++ b/docs/SIM_VS_REAL.md
@@ -39,11 +39,22 @@ LiDAR gá ở x=0.18 trong khi thân trải x = −0.225…+0.225.
**Triệu chứng:** **71.7%** tia báo khoảng cách < 0.35 m, `range` nhỏ nhất chạm
đúng `range_min` = 0.050 m. Toàn bộ là thân robot, không phải môi trường.
-**Sửa:** lùi thân (`body_offset_x = -0.06`), đẩy LiDAR ra trước (x=0.24), và
-giảm FOV 270° → 240° cho khớp cung không bị che.
+**Sửa ban đầu:** lùi thân (`body_offset_x = -0.06`), đẩy LiDAR ra trước (x=0.24),
+và giảm FOV sim 270° → 240° cho khớp cung không bị che.
-→ Trên robot thật, dùng `laser_filters` (angular bounds / footprint filter) để
-cắt cung bị thân che, thay vì để scan matching ăn dữ liệu rác.
+**Sửa hiện tại (sau khi có spec thật):** sim publish **FOV THẬT 270°** lên
+`/scan_raw`, và `robot_drivers/launch/scan_filter.launch` cắt cung bị thân che
+tại ±118° rồi mới ra `/scan`. Cùng một filter, cùng bounds, **sim và thật giống
+hệt nhau**.
+
+Với hình học hiện tại, cung bị che nhỏ hơn con số 71.7% đo ngày đó nhiều:
+`atan2(0.17, 0.14 − 0.24) = 120.5°` → chỉ 2×14.5° = **29° (10.7%)**.
+Con số 71.7% có trước `body_offset_x = -0.06` và `laser_x = 0.24`.
+
+⚠️ Sim **KHÔNG** bắt chước chỗ driver thật nói dối (nó khai `angle_min/max = ±180°`
+cho thiết bị 270° — xem `HARDWARE.md` §2 bug 2). Sim trung thực 270°, thật nói dối
+360°, và filter là nơi hấp thụ bất đối xứng đó. Cả hai hội tụ về cùng cung ~236°.
+Đừng "sửa" sim cho khớp driver.
### 3. Độ cứng tiếp xúc đặt ngược → bánh mất lực kéo
@@ -180,7 +191,7 @@ Sim thấy mọi vật như nhau. Thực tế:
Gazebo coi kính là **vật cản đặc** hoặc **vô hình** — cả hai đều sai.
-Thực tế: LiDAR ToF 905nm **xuyên qua** kính, depth IR cũng vậy. Gương tạo **hình
+Thực tế: LiDAR ToF 940nm **xuyên qua** kính, depth IR cũng vậy. Gương tạo **hình
học ảo** trong LiDAR và **feature ảo** trong camera → map bị bơm thêm "căn phòng
không tồn tại".
@@ -203,6 +214,57 @@ xuống ~0.3 để mô phỏng sàn dầu mỡ), nhưng động lực học trư
World hiện tại **hoàn toàn tĩnh**. Nhà hàng thật có 30 khách đi lại, ghế bị kéo
ra, bàn được xếp lại.
+### 9. Hấp thụ IR của vực tối — `cliff_test.world` chỉ kiểm được một nửa
+
+`robot_sim/worlds/cliff_test.world` có hai tình huống, và chúng **không ngang
+giá trị nhau**:
+
+| Tình huống | Sim kiểm được? |
+|---|---|
+| **Mép hở**, có sàn dưới ở −1.0 m → depth xa hơn kỳ vọng | ✅ đúng vật lý |
+| **Hố tối**, thành phủ vật liệu đen → depth biến mất | ❌ **không** |
+
+Gazebo không mô phỏng hấp thụ IR. Vật liệu đen trong world chỉ làm ảnh tối đi,
+**không làm depth trả về NaN** như ngoài đời. Mà nhánh "lỗ" mới là trường hợp
+thật của cầu thang tối, và chính là lý do `CliffDetectNodelet` phải chạy trên
+ảnh depth thay vì trên cloud.
+
+→ Nhánh "sụt" nghiệm thu được trong sim. Nhánh "lỗ" **chỉ kiểm được trên phần
+cứng thật**, và phải kiểm ở đúng cầu thang của toà nhà mục tiêu.
+
+Thêm nữa: không world nào mô phỏng được vùng mù 0–1.1 m một cách có ý nghĩa,
+vì trong sim robot luôn "thấy" mép từ xa rồi dừng. Ngoài đời robot có thể bị
+đẩy, bị trượt, hoặc khởi động ngay cạnh mép.
+
+### 10. `intensities` và `scan_time` của LaserScan — sim trả 0
+
+Đo trực tiếp trên `/scan_raw` (2026-09-11, `check_scan.py`):
+
+```
+scan_time : 0.0 <- libgazebo_ros_gpu_laser.so khong dien
+time_increment : 0.0
+intensities : [0.0, 0.0, ...] toan bo 1081 tia
+```
+
+LakiBeam 1L thật thì **ngược lại**: driver publish RSSI vào `intensities`, và
+`scan_time` có giá trị đo được.
+
+Hai hệ quả, cả hai đều là loại hỏng im lặng:
+
+1. **Deskew sẽ không làm gì trong sim mà vẫn chạy trên phần cứng.**
+ `ScanHeaderFixFilter` sửa `time_increment = scan_time / n` (gỡ lỗi chia 2 của
+ driver). Trong sim `scan_time = 0` nên kết quả vẫn là 0. Nếu sau này bật
+ deskew, sim sẽ cho kết quả "ổn" vì nó không bù gì cả, còn phần cứng mới thực
+ sự bù — sai lệch giữa hai bên không ai báo.
+
+2. **Không test được bất kỳ bộ lọc nào dựa trên cường độ.**
+ `LaserScanIntensityFilter` và nhánh intensity của speckle filter vô dụng
+ trong sim. Đáng lưu ý vì **dropout của ToF trên bề mặt đen** (mục 4 ở trên)
+ là rủi ro chính đã ghi trong `HARDWARE.md`, mà RSSI chính là tín hiệu để
+ phát hiện nó. Tức công cụ chống rủi ro đó chỉ tune được trên phần cứng thật.
+
+→ Đã thêm vào checklist bên dưới.
+
---
## Checklist: phải test lại trên phần cứng thật
@@ -210,6 +272,13 @@ ra, bàn được xếp lại.
Đánh dấu khi đã kiểm chứng ngoài đời — **không được tin kết quả sim cho các mục này**:
- [ ] Đồng bộ thời gian giữa camera / LiDAR / IMU (đo offset và jitter thật)
+- [ ] **Hướng 0° thật của LakiBeam sau khi gá** — `check_scan.py --topic /scan_raw`,
+ xem cung mù có đối xứng quanh 180° không. Lệch thì `angle_offset` sai và
+ mọi bounds trong `scan_filter.yaml` sai theo
+- [ ] **Cái gì lấp vào ~90° driver bịa ra** — nếu là `inf` thì costmap
+ (`inf_is_valid: true`) sẽ raytrace-clear xuyên tường mỗi scan
+- [ ] **`intensities` / RSSI thật** — sim trả 0 hết, nên mọi bộ lọc theo cường
+ độ (chống dropout trên bề mặt đen) chỉ tune được ở đây
- [ ] Min-Z thật của D410 (đẩy hộp lại gần đến khi depth mất)
- [ ] Depth trên thùng trắng trơn, chậu nhựa bóng, vali
- [ ] LiDAR ToF trên ghế da đen, thảm sẫm, bàn gỗ đen
diff --git a/reloc_hosp.sh b/reloc_hosp.sh
new file mode 100755
index 0000000..384be4f
--- /dev/null
+++ b/reloc_hosp.sh
@@ -0,0 +1,97 @@
+#!/usr/bin/env bash
+#
+# reloc_hosp.sh - Chay bai kidnapped-robot tren ban do hospital.
+#
+# ============ VI SAO CAN FILE NAY ============
+# localization.launch GHI pose dinh vi cuoi cung vao database (opt_last_localization),
+# ke ca o che do Mem/IncrementalMemory=false. Nen lan chay thu hai tren CUNG file
+# se khoi dong voi dap an cua lan truoc -> lech kidnap bang 0 -> phep do vo nghia.
+#
+# Da dinh that hai lan:
+# correction = xyz=-2.009,-18.903 trung khit diem tha (-2.11,-18.91)
+# correction = xyz=-1.432, -1.922 sot lai tu lan chay khac
+#
+# Script nay chep ban do sach TRUOC moi lan chay, khong the quen.
+#
+# ============ DUNG ============
+# ./reloc_hosp.sh -11.46 13.22 # yaw 3.14, Icp/MaxTranslation 0.3
+# ./reloc_hosp.sh -11.46 13.22 1.57
+# ./reloc_hosp.sh -11.46 13.22 3.14 1.0 # noi Icp/MaxTranslation len 1.0 m
+# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 15 # ha Vis/MinInliers xuong 15
+#
+# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 20 true # bat global_scan_init
+# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 20 true true # + dinh vi CHU DONG
+# ./reloc_hosp.sh -11.46 13.22 3.14 0.3 20 true true true # + GICP tren depth
+#
+# Tham so 4 = Icp/MaxTranslation. Noi len de proximity hoi phuc duoc sau va cham.
+# Tham so 5 = Vis/MinInliers. Ha xuong de de nhan ra cho hon.
+# Tham so 6 = enable_global_init. Bat node khop scan LiDAR (khuyen dung: true).
+# Tham so 7 = enable_active_reloc. Khi bi NHAP NHANG, tinh va NOI RA phai di dau
+# de phan biet, thay vi de nguoi van hanh mo. Xem /reloc/suggested_motion.
+# Khong publish /initialpose nen khong the lam xau do chinh xac.
+#
+# ⚠️ Ha tham so 5 co RUI RO NHAN NHAM CHO. Chi danh gia bang check_reloc.py
+# (sai so tuyet doi so ground truth), TUYET DOI khong danh gia bang so lan
+# dong vong trong log.
+#
+# ============ KICH BAN DO: CHI XOAY TAI CHO ============
+# Yeu cau van hanh: tha robot xuong, XOAY TAI CHO la phai dinh vi duoc.
+# Lai di trong moi truong chua biet minh o dau la khong dung duoc that.
+# Nen khi do: dung yen, chi xoay. Cot `da di(m)` phai o gan 0.
+#
+# Terminal 2: rosrun slam_eval check_reloc.py --map-origin 4.0 14.0 0.0
+# Terminal 3: roslaunch robot_bringup teleop_joystick.launch
+#
+# ============ KIEM PHEP DO CO HOP LE KHONG ============
+# grep -m1 "correction = xyz" /tmp/reloc_hosp.log
+# Phai ra xyz=-6.709041,-28.870140 = pose cuoi phien quet.
+# Ra so nao khac -> ban do bi nhiem -> bo ket qua, chay lai.
+# Va dong t=0.0 trong check_reloc phai hien sai so ~30 m.
+
+set -euo pipefail
+
+WS="$HOME/projects/vSLAM_ws"
+SRC="$WS/maps/map_hospital.db"
+DST="$WS/maps/reloc_hosp.db"
+
+if [ $# -lt 2 ]; then
+ echo "Dung: $0 X Y [YAW]"
+ echo
+ echo "Bon diem da chon (xa pose khoi tao nhat, thua nhat):"
+ echo " -0.62 14.79 lech 29.7 m 22 quan sat/1m"
+ echo " -11.46 13.22 lech 29.4 m 19 quan sat/1m"
+ echo " 11.64 10.43 lech 29.1 m 18 quan sat/1m"
+ echo " -10.43 4.81 lech 21.1 m 31 quan sat/1m"
+ exit 1
+fi
+
+X="$1"; Y="$2"; YAW="${3:-3.14}"; ICPT="${4:-0.3}"; MININL="${5:-20}"
+GLOBAL="${6:-false}"
+ACTIVE="${7:-false}"
+GICP="${8:-false}"
+
+[ -f "$SRC" ] || { echo "KHONG THAY ban do goc: $SRC"; exit 1; }
+
+cp "$SRC" "$DST"
+echo "=================================================================="
+echo " da chep ban do SACH : $(du -h "$DST" | cut -f1)"
+echo " diem tha (Gazebo) : x=$X y=$Y yaw=$YAW"
+echo " goc ban do : 4.0 14.0 0.0"
+echo "=================================================================="
+echo
+echo " Cho ~25 s cho database nap xong (2716 node) roi moi bat T2."
+echo " T2: rosrun slam_eval check_reloc.py --map-origin 4.0 14.0 0.0"
+echo " T3: roslaunch robot_bringup teleop_joystick.launch"
+echo
+echo " Kiem sau khi chay:"
+echo " grep -m1 'correction = xyz' /tmp/reloc_hosp.log"
+echo " -> phai ra xyz=-6.709041,-28.870140"
+echo
+
+exec roslaunch robot_bringup localization.launch world:=hospital \
+ database_path:="$DST" \
+ visual_loop:=true start_at_origin:=false enable_dock_init:=false \
+ x:="$X" y:="$Y" yaw:="$YAW" icp_max_translation:="$ICPT" \
+ vis_min_inliers:="$MININL" enable_global_init:="$GLOBAL" \
+ enable_active_reloc:="$ACTIVE" \
+ enable_gicp:="$GICP"
diff --git a/src/localization_ops/CMakeLists.txt b/src/localization_ops/CMakeLists.txt
index a1a76b0..198453a 100644
--- a/src/localization_ops/CMakeLists.txt
+++ b/src/localization_ops/CMakeLists.txt
@@ -1,12 +1,30 @@
cmake_minimum_required(VERSION 3.0.2)
project(localization_ops)
-find_package(catkin REQUIRED)
+find_package(catkin REQUIRED COMPONENTS
+ roscpp geometry_msgs sensor_msgs std_msgs
+ tf2_ros tf2_geometry_msgs pcl_ros pcl_conversions
+)
+find_package(PCL REQUIRED COMPONENTS common filters registration kdtree)
+find_package(RTABMap 0.21 REQUIRED COMPONENTS core)
catkin_package()
+include_directories(
+ ${catkin_INCLUDE_DIRS} ${PCL_INCLUDE_DIRS} ${RTABMap_INCLUDE_DIRS})
+
+add_executable(reloc_gicp_node src/reloc_gicp_node.cpp)
+add_dependencies(reloc_gicp_node ${catkin_EXPORTED_TARGETS})
+target_link_libraries(reloc_gicp_node
+ ${catkin_LIBRARIES} ${PCL_LIBRARIES} ${RTABMap_LIBRARIES})
+
+install(TARGETS reloc_gicp_node
+ RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
+
catkin_install_python(PROGRAMS
scripts/dock_init.py
+ scripts/global_scan_init.py
+ scripts/reloc_active.py
scripts/floor_detector.py
scripts/multi_map_manager.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
diff --git a/src/localization_ops/launch/localization_ops.launch b/src/localization_ops/launch/localization_ops.launch
index 781da27..62786ba 100644
--- a/src/localization_ops/launch/localization_ops.launch
+++ b/src/localization_ops/launch/localization_ops.launch
@@ -10,11 +10,69 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/localization_ops/package.xml b/src/localization_ops/package.xml
index 7de439c..7b74f06 100644
--- a/src/localization_ops/package.xml
+++ b/src/localization_ops/package.xml
@@ -11,6 +11,14 @@
catkin
+ roscpp
+ tf2_ros
+ tf2_geometry_msgs
+ pcl_ros
+ pcl_conversions
+ libpcl-all-dev
+ rtabmap
+
rospysensor_msgsnav_msgs
diff --git a/src/localization_ops/scripts/global_scan_init.py b/src/localization_ops/scripts/global_scan_init.py
new file mode 100755
index 0000000..090aaa1
--- /dev/null
+++ b/src/localization_ops/scripts/global_scan_init.py
@@ -0,0 +1,823 @@
+#!/usr/bin/env python3
+"""
+global_scan_init - Dinh vi toan cuc bang khop scan LiDAR voi luoi chiem dung.
+
+============ BAI TOAN ============
+Tha robot xuong mot cho bat ky tren ban do da quet, KHONG cho no biet dang o
+dau. Robot xoay tai cho mot vong. Phai suy ra duoc pose trong ban do.
+
+Lai vong quanh trong moi truong chua biet minh o dau la KHONG dung duoc that -
+do la yeu cau van hanh, khong phai so thich.
+
+============ VI SAO KHONG DUNG TUI TU (bag-of-words) ============
+Da do tren ban do hospital (2716 node):
+
+ 194 lan tui tu de xuat ung vien, 0 lan qua duoc kiem chung hinh hoc
+ matches trung vi 43 <- mo ta ORB khop rat nhieu
+ inliers trung vi 0, cao nhat 19 tren nguong Vis/MinInliers=20
+ 186/194 lan co DUNG 0 inlier
+
+Thu ca hai huong noi long, deu khong cuu duoc:
+ Icp/MaxTranslation 0.3 -> 1.0 van phai lai 60 m moi ra
+ Vis/MinInliers 20 -> 15 van phai lai
+
+Nguyen nhan: TRUNG LAP TRI GIAC. Hanh lang benh vien giong nhau, mo ta noi
+"cho nay toi tung qua", hinh hoc noi "khong, hanh lang khac trong giong het".
+Tren ban do house (khong co hanh lang lap) thi cung he do dat 14m -> 0.038m
+trong 1.7 giay, dung yen.
+
+============ VI SAO KHOP SCAN GIAI QUYET DUOC ============
+Tui tu de xuat TUNG ung vien roi de hinh hoc loai tung cai mot - no khong bao
+gio SO SANH cac ung vien voi nhau.
+
+Cho nay tinh diem MOI gia thuyet (x,y,theta) cung mot luc, nen so sanh duoc.
+Hai hanh lang giong nhau se cho hai diem gan bang nhau -> phat hien duoc su
+nhap nhang va IM LANG, thay vi chon bua.
+
+Bat bien theo goc quay la do QUET HET moi theta, khong phai do huan luyen.
+
+============ VI SAO KHONG DUNG VPR HOC SAU ============
+ librtabmap_core.so.0.21 KHONG link libpython
+ chuoi nam san trong .so:
+ "PyDescriptor cannot be used as rtabmap is not built with Python3 support."
+
+Phai bien dich lai RTAB-Map tu nguon + PyTorch + CUDA. Tren Orin Nano 8 GB
+dung chung CPU/GPU thi rieng CUDA context da ~1 GB. Va mo hinh VPR huan luyen
+tren anh RGB trong khi D410 chi co IR.
+
+Node nay chi can numpy + cv2, chay CPU, duoi 1 giay moi lan truy van.
+
+============ NODE NAY KHONG DUNG VAO RTAB-MAP ============
+No chi publish /initialpose - dung topic ma dock_init.py dang dung va
+rtabmap.launch:252 da remap san. RTAB-Map nhan pose khoi tao roi tinh chinh
+cuc bo bang ICP, phan do von da chay tot.
+
+Quan he voi dock_init: BO SUNG, khong thay the. Khoi dong tu dock thi dung
+dock_init (pose da biet chinh xac). Node nay cho truong hop bi be di hoac mat
+track giua ca.
+
+============ DUNG ============
+ roslaunch robot_bringup localization.launch enable_global_init:=true
+
+Goi tay:
+ rosservice call /global_scan_init/relocalize
+"""
+
+import math
+import threading
+
+import numpy as np
+import rospy
+import tf2_ros
+from geometry_msgs.msg import Pose, PoseArray, PoseWithCovarianceStamped
+from nav_msgs.msg import OccupancyGrid, Odometry
+from sensor_msgs.msg import LaserScan
+from std_srvs.srv import Trigger, TriggerResponse
+
+try:
+ import cv2
+except ImportError:
+ cv2 = None
+
+
+def yaw_of(q):
+ """Yaw tu quaternion. Chi can thanh phan z vi he la SE(2)."""
+ return math.atan2(2.0 * (q.w * q.z + q.x * q.y),
+ 1.0 - 2.0 * (q.y * q.y + q.z * q.z))
+
+
+def maxpool(a, k):
+ """Gop khoi k x k lay gia tri LON NHAT.
+
+ Phai la max chu khong phai trung binh: muc tho dung de SANG LOC, bo sot mot
+ dinh that o day thi khong con co hoi tinh chinh no nua. Max thi rong rai,
+ giu lai moi ung vien dang xet."""
+ h, w = a.shape
+ h2, w2 = (h // k) * k, (w // k) * k
+ if h2 == 0 or w2 == 0:
+ return a.copy()
+ return a[:h2, :w2].reshape(h2 // k, k, w2 // k, k).max(axis=(1, 3))
+
+
+class GlobalScanInit(object):
+ def __init__(self):
+ self.map_frame = rospy.get_param('~map_frame', 'map')
+ self.odom_frame = rospy.get_param('~odom_frame', 'odom')
+ self.base_frame = rospy.get_param('~base_frame', 'base_footprint')
+
+ # Do rong ham khoang cach. 0.15 m ~ 3 o luoi o CellSize=0.05, du de
+ # chiu sai so luoi ma khong lam nhoe het dac trung hinh hoc.
+ self.sigma = rospy.get_param('~sigma', 0.15)
+
+ # ⚠️ Khop den 12 m thoi. Grid/RangeMax=12.0 trong rtabmap.launch, tuc
+ # ban do CHI duoc dung tu tia <= 12 m. Dung tia xa hon la khop vao vung
+ # ban do chua tung ghi -> diem thap oan cho dung vi tri.
+ self.max_range = rospy.get_param('~max_range', 12.0)
+
+ self.coarse_res = rospy.get_param('~coarse_res', 0.80)
+ self.angle_step = math.radians(rospy.get_param('~angle_step', 5.0))
+ self.top_k = rospy.get_param('~top_k', 24)
+
+ # Nguong chong nhan nham: diem cao nhat phai hon diem cao nhat NGOAI
+ # ban kinh reject_radius bao nhieu lan.
+ self.min_ratio = rospy.get_param('~min_ratio', 1.30)
+ self.reject_radius = rospy.get_param('~reject_radius', 2.0)
+
+ # ⚠️ CONG KIEM THEO TRUC GOC.
+ #
+ # min_ratio/reject_radius chi loc doi thu theo VI TRI. Mot gia thuyet o
+ # DUNG vi tri do nhung KHAC HUONG bi loai khoi danh sach doi thu (ca o
+ # buoc gom ung vien, dong ~356, lan buoc tim doi thu, dong ~386/393),
+ # nen ty le s1/s2 KHONG BAO GIO do duoc tinh da nghia ve huong.
+ #
+ # Da do tren ban do hospital, diem tha (7.47,-29.97) huong 180 do:
+ # xoay 301 do -> khop ra -139.2 do (sai 40.8 do) ty le 1.66
+ # xoay 181 do -> khop ra -20.4 do (sai 159.6 do) ty le 1.59
+ # xoay 0 do -> khop ra 180.0 do (sai 0.0 do) ty le 1.57
+ # Ca ba deu vuot min_ratio 1.30. Vi tri luon dung 0.17-0.21 m.
+ # Odometry da duoc loai tru: xoay 3 vong lech tong 0.1 do.
+ #
+ # Nguyen nhan: mot scan don la cung 236 do bat doi xung -> huong co mot
+ # nghiem. Dam may tich luy 360 do doi xung quay hon nhieu -> da cuc tri
+ # theo goc, dung luc cong kiem khong nhin huong.
+ self.min_ratio_yaw = rospy.get_param('~min_ratio_yaw', 1.30)
+ # Doi thu goc phai lech it nhat ngan nay moi tinh la "khac huong".
+ self.min_angle_sep = math.radians(
+ rospy.get_param('~min_angle_sep_deg', 25.0))
+
+ # ============ CHAY LIEN TUC ============
+ # Truoc day node la MOT LAN: bi tu choi vi nhap nhang la nam im, phai
+ # goi tay `rosservice call /global_scan_init/relocalize`.
+ # Da do tren ban do hospital: 3/4 lan thu bi tu choi (ty le 1.04, 1.18,
+ # 1.24 < 1.30) - tuc hanh lang lap, node tu choi DUNG. Nhung nguoi van
+ # hanh khong the ngoi goi service moi lan robot doi cho.
+ #
+ # Tu nap lai sau khi bi tu choi. 0 = tat.
+ self.retry_period = rospy.get_param('~retry_period', 10.0)
+
+ # ⚠️ TU PHAT HIEN DA LAC - BAT BUOC di kem retry_period.
+ #
+ # Thieu no thi node se bom /initialpose DE LEN ket qua dung cua RTAB-Map
+ # moi chu ky, tuc pha hoai dung luc he dang chay tot.
+ #
+ # Cach do: lay mot scan, chieu vao ban do bang pose DANG TIN (map->base
+ # tu TF), roi cham diem tren cung truong likelihood dung de khop.
+ # Pose dung thi scan chong khit tuong -> diem cao. Bi be di thi diem sut
+ # ngay. Hoan toan doc lap voi RTAB-Map: no tu hoi "pose toi dang tin co
+ # giai thich duoc cai toi dang thay khong".
+ self.watch_lost = rospy.get_param('~watch_lost', True)
+ # Diem tut duoi ty le nay so voi diem luc khop thanh cong -> nghi lac.
+ self.lost_score_ratio = rospy.get_param('~lost_score_ratio', 0.55)
+ # Phai tut LIEN TUC ngan nay giay moi kich hoat. Chong nhieu nhat thoi
+ # khi co nguoi di ngang qua LiDAR.
+ self.lost_hold = rospy.get_param('~lost_hold', 3.0)
+ self.lost_period = rospy.get_param('~lost_period', 1.0)
+
+ # ============ ⚠️ CHO ROBOT CHAM LAI ROI MOI PUBLISH ============
+ # T_map_odom tim duoc la TINH va DUNG. Nhung compose() ghep no voi
+ # odom->base tra o Time(0) - ban moi nhat CO SAN trong bo dem TF, von
+ # tre ~0.5s so voi thuc tai - roi dong dau ban tin bang now().
+ # Ben nhan hieu la "bay gio" -> lech = omega * do_tre.
+ #
+ # Da do tren ban do hospital:
+ # khop luc DUNG YEN (omega=0) -> sai huong 0.07-0.09 do
+ # khop luc dang quay ~20 do/s -> sai huong 15-22 do
+ #
+ # Vi T_map_odom khong doi theo thoi gian, chi can CHO robot cham lai
+ # roi tra lai odom->base la ra pose chinh xac. Khong phai ngoai suy,
+ # khong phai doan do tre.
+ self.settle_omega = rospy.get_param('~settle_omega', 0.05) # rad/s
+ self.settle_timeout = rospy.get_param('~settle_timeout', 8.0)
+ self.omega = 0.0
+ rospy.Subscriber(rospy.get_param('~odom_topic', '/odometry/filtered'),
+ Odometry, self.on_odom, queue_size=5)
+
+ self.ref_score = None # diem/diem-do luc khop thanh cong gan nhat
+ self.lost_since = None
+ self.last_scan = None
+ self.pose_stamp = None
+
+ # Goc quet tich luy truoc khi khop.
+ #
+ # FOV huu dung la 236 do: thiet bi quet 270 do, va chuoi filter cat cung
+ # bi than robot che tai +-118 do.
+ # Nguon: robot_drivers/config/scan_filter.yaml (KHONG con o
+ # gazebo_sensors.xacro - sim gio publish dung 270 do cua thiet bi va
+ # cung duoc cat o chuoi filter, giong het duong phan cung that).
+ #
+ # Mot scan thieu 360 - 236 = 124 do, nen ve ly thuyet xoay 124 do la du
+ # phu kin. De 300 do la CHON DU AN TOAN, khong phai con so suy ra:
+ # bu cho odometry troi trong luc xoay va cho trung lap giua cac scan.
+ self.yaw_sweep = math.radians(rospy.get_param('~yaw_sweep', 300.0))
+ self.timeout = rospy.get_param('~timeout', 30.0)
+
+ self.max_points = rospy.get_param('~max_points', 1500)
+ self.auto = rospy.get_param('~auto', True)
+ self.delay = rospy.get_param('~delay', 5.0)
+
+ self.lock = threading.Lock()
+ self.grid = None # (L_fine, free_fine, res, ox, oy)
+ self.pts = [] # diem tich luy, he odom
+ self.yaw_acc = 0.0
+ self.yaw_prev = None
+ self.active = False
+ self.t_start = 0.0
+
+ self.buf = tf2_ros.Buffer()
+ tf2_ros.TransformListener(self.buf)
+
+ self.pub = rospy.Publisher('/initialpose', PoseWithCovarianceStamped,
+ queue_size=1, latch=True)
+
+ # ⚠️ Lo ra TAP GIA THUYET, ke ca khi khong du tu tin de publish.
+ #
+ # Truoc day khi nhap nhang (ty le < min_ratio) node vut het va im lang.
+ # Nhung chinh luc do no BIET ro co may cho dang canh nhau va o dau - do
+ # la thong tin quy nhat de mot lop tren tinh xem PHAI DI DAU de phan
+ # biet. Vut di la bat nguoi van hanh mo lai tu dau.
+ #
+ # /initialpose VAN chi ra khi mot gia thuyet ap dao. Topic nay khong
+ # thay doi hanh vi dinh vi, chi cong bo thu dang co.
+ self.hyp_pub = rospy.Publisher('/reloc/hypotheses', PoseArray,
+ queue_size=1, latch=True)
+ rospy.Subscriber('map', OccupancyGrid, self.on_map, queue_size=1)
+ rospy.Subscriber('scan', LaserScan, self.on_scan, queue_size=5)
+ self.srv = rospy.Service('~relocalize', Trigger, self.on_trigger)
+
+ if cv2 is None:
+ rospy.logerr('global_scan_init: thieu cv2. '
+ 'sudo apt install python3-opencv')
+
+ if self.watch_lost:
+ rospy.Timer(rospy.Duration(self.lost_period), self.on_watch)
+
+ rospy.loginfo('global_scan_init: san sang. Xoay robot tai cho.')
+ if self.auto:
+ rospy.Timer(rospy.Duration(self.delay), self.on_timer, oneshot=True)
+
+ # ---------------- ban do ----------------
+
+ def on_map(self, msg):
+ if cv2 is None:
+ return
+ w, h = msg.info.width, msg.info.height
+ g = np.asarray(msg.data, dtype=np.int8).reshape(h, w)
+
+ # OccupancyGrid: 0 = trong, 100 = co vat can, -1 = chua biet.
+ occ = (g >= 50).astype(np.uint8)
+ free = (g == 0)
+
+ # distanceTransform do khoang cach tu diem KHAC 0 toi diem 0 gan nhat,
+ # nen phai dao: vung khong co vat can = 255.
+ inv = np.where(occ > 0, 0, 255).astype(np.uint8)
+ dist = cv2.distanceTransform(inv, cv2.DIST_L2, 5) * msg.info.resolution
+
+ lf = np.exp(-(dist ** 2) / (2.0 * self.sigma ** 2)).astype(np.float32)
+
+ with self.lock:
+ self.grid = dict(L=lf, free=free, res=msg.info.resolution,
+ ox=msg.info.origin.position.x,
+ oy=msg.info.origin.position.y,
+ w=w, h=h)
+ rospy.loginfo_once('global_scan_init: nhan ban do %dx%d @ %.3f m',
+ w, h, msg.info.resolution)
+
+ # ---------------- gom scan ----------------
+
+ def on_odom(self, msg):
+ self.omega = msg.twist.twist.angular.z
+
+ def on_scan(self, msg):
+ # Luon giu ban moi nhat: bo tu kiem "da lac" can scan ngay ca khi
+ # khong dang gom.
+ self.last_scan = msg
+ with self.lock:
+ if not self.active or self.grid is None:
+ return
+ try:
+ tr = self.buf.lookup_transform(self.odom_frame, msg.header.frame_id,
+ msg.header.stamp,
+ rospy.Duration(0.2))
+ except Exception:
+ return
+
+ t = tr.transform.translation
+ th = yaw_of(tr.transform.rotation)
+
+ r = np.asarray(msg.ranges, dtype=np.float32)
+ ok = np.isfinite(r) & (r > msg.range_min) & (r < min(msg.range_max,
+ self.max_range))
+ if not ok.any():
+ return
+ idx = np.nonzero(ok)[0]
+ ang = msg.angle_min + idx * msg.angle_increment
+ rr = r[idx]
+
+ # laser_link -> odom
+ ca, sa = math.cos(th), math.sin(th)
+ lx, ly = rr * np.cos(ang), rr * np.sin(ang)
+ ox = t.x + ca * lx - sa * ly
+ oy = t.y + sa * lx + ca * ly
+
+ with self.lock:
+ self.pts.append(np.stack([ox, oy], axis=1))
+
+ # Do goc da quet bang chinh TF cua LiDAR - xoay tai cho thi
+ # odometry rat chinh xac nen phep gom nay sach.
+ if self.yaw_prev is not None:
+ d = math.atan2(math.sin(th - self.yaw_prev),
+ math.cos(th - self.yaw_prev))
+ self.yaw_acc += abs(d)
+ self.yaw_prev = th
+
+ done = self.yaw_acc >= self.yaw_sweep
+ late = (rospy.Time.now().to_sec() - self.t_start) > self.timeout
+
+ if done or late:
+ self.finish(timed_out=late and not done)
+
+ # ---------------- khop ----------------
+
+ def finish(self, timed_out):
+ with self.lock:
+ self.active = False
+ pts = np.concatenate(self.pts) if self.pts else None
+ sweep = math.degrees(self.yaw_acc)
+ g = self.grid
+ if pts is None or len(pts) < 50 or g is None:
+ rospy.logwarn('global_scan_init: khong du diem (%s). Bo qua.',
+ 0 if pts is None else len(pts))
+ return
+ if timed_out:
+ rospy.logwarn('global_scan_init: het %.0fs ma moi quet %.0f do '
+ '(can %.0f). Van thu khop voi nhung gi co.',
+ self.timeout, sweep, math.degrees(self.yaw_sweep))
+
+ pts = self.downsample(pts, g['res'])
+ rospy.loginfo('global_scan_init: khop %d diem, da quet %.0f do...',
+ len(pts), sweep)
+
+ t0 = rospy.Time.now().to_sec()
+ res = self.match(pts, g)
+ dt = rospy.Time.now().to_sec() - t0
+
+ if res is None:
+ rospy.logwarn('global_scan_init: THAT BAI - khong tim duoc dinh '
+ 'nao du manh (%.2fs).', dt)
+ self.arm_retry()
+ return
+
+ x, y, th, s1, s2, s2_yaw, tx, ty, bth, hyps = res
+
+ # Cong bo TRUOC moi cong kiem: du bi tu choi, tap gia thuyet van co gia
+ # tri cho lop dinh vi chu dong o tren.
+ self.publish_hypotheses(hyps)
+ ratio = s1 / max(s2, 1e-6)
+
+ # ⚠️ Cong kiem thu hai: doi thu CUNG vi tri, KHAC huong.
+ # Xem khoi ghi chu o min_ratio_yaw. Khong co cong nay thi node tra ve
+ # vi tri dung voi huong sai 40-160 do ma van bao ty le 1.6.
+ ratio_yaw = s1 / max(s2_yaw, 1e-6)
+ if ratio_yaw < self.min_ratio_yaw:
+ rospy.logwarn('global_scan_init: NHAP NHANG VE HUONG - ty le goc '
+ '%.2f < %.2f (ty le vi tri %.2f - CHUA xet, cong goc '
+ 'chan truoc). KHONG publish. '
+ 'Vi tri co the dung nhung huong khong tin duoc.',
+ ratio_yaw, self.min_ratio_yaw, ratio)
+ self.arm_retry()
+ return
+
+ if ratio < self.min_ratio:
+ # ⚠️ Day la truong hop QUAN TRONG NHAT, khong phai loi.
+ # Hai cho khac nhau cho diem gan bang nhau -> hanh lang lap.
+ # Tra loi sai tu tin te hon nhieu so voi im lang: tren robot that
+ # khong co ground truth de ma biet minh dang sai.
+ rospy.logwarn('global_scan_init: NHAP NHANG - ty le %.2f < %.2f. '
+ 'KHONG publish. Di chuyen vai met roi thu lai.',
+ ratio, self.min_ratio)
+ self.arm_retry()
+ return
+
+ # ⚠️ Cho robot cham lai roi COMPOSE LAI. Xem settle_omega o onInit.
+ if abs(self.omega) > self.settle_omega:
+ rospy.loginfo('global_scan_init: dang quay %.1f do/s - cho dung roi '
+ 'moi publish (toi da %.0fs).',
+ math.degrees(self.omega), self.settle_timeout)
+ t_wait = rospy.Time.now().to_sec()
+ rate = rospy.Rate(20)
+ while (not rospy.is_shutdown()
+ and abs(self.omega) > self.settle_omega
+ and rospy.Time.now().to_sec() - t_wait < self.settle_timeout):
+ rate.sleep()
+ if abs(self.omega) > self.settle_omega:
+ rospy.logwarn('global_scan_init: van quay %.1f do/s sau %.0fs. '
+ 'Publish luon - huong se lech ~%.0f do.',
+ math.degrees(self.omega), self.settle_timeout,
+ math.degrees(abs(self.omega)) * 0.5)
+ # T_map_odom khong doi; chi can odom->base moi hon.
+ x, y, th = self.compose(tx, ty, bth)
+
+ self.publish(x, y, th, ratio)
+
+ # Moc tham chieu cho bo canh "da lac". Cho TF ngam pose moi roi moi do,
+ # neu khong se do trung pose CU va tuong la dang lac.
+ rospy.sleep(0.5)
+ self.ref_score = self.score_current_pose()
+ self.lost_since = None
+ if self.ref_score is not None:
+ rospy.loginfo('global_scan_init: diem tham chieu %.3f - se tu kich '
+ 'hoat lai neu tut duoi %.0f%% trong %.1fs.',
+ self.ref_score, 100.0 * self.lost_score_ratio,
+ self.lost_hold)
+ rospy.loginfo('global_scan_init: TIM DUOC (%.3f, %.3f, %.1f do) '
+ 'ty le vi tri %.2f / goc %.2f trong %.2fs',
+ x, y, math.degrees(th), ratio, ratio_yaw, dt)
+
+ def downsample(self, pts, res):
+ """Gop diem ve luoi do phan giai ban do. Nhieu tia cung roi vao mot o
+ thi khong them thong tin, chi lam cham FFT."""
+ k = np.round(pts / res).astype(np.int64)
+ _, keep = np.unique(k, axis=0, return_index=True)
+ pts = pts[np.sort(keep)]
+ if len(pts) > self.max_points:
+ step = int(math.ceil(len(pts) / float(self.max_points)))
+ pts = pts[::step]
+ return pts
+
+ def match(self, pts, g):
+ """Quet tho bang FFT roi tinh chinh cuc bo.
+
+ Meo chinh: voi mot theta co dinh, tinh diem cho TOAN BO cac phep tinh
+ tien (x,y) = tuong quan cheo giua truong kha nang va mat na diem. Mot
+ phep FFT lam xong ca luoi, thay vi lap tung o."""
+ res = g['res']
+ k = max(1, int(round(self.coarse_res / res)))
+ Lc = maxpool(g['L'], k)
+ Fc = maxpool(g['free'].astype(np.float32), k) > 0.5
+ rc = res * k
+ H, W = Lc.shape
+
+ # Dem bien bang tam quet: tuong quan vong (circular) se cuon diem tu
+ # canh nay sang canh kia neu khong dem.
+ pad = int(math.ceil(self.max_range / rc)) + 1
+ Lp = np.zeros((H + 2 * pad, W + 2 * pad), dtype=np.float32)
+ Lp[pad:pad + H, pad:pad + W] = Lc
+ Hp, Wp = Lp.shape
+ FL = np.fft.rfft2(Lp)
+
+ c = pts.mean(axis=0)
+ P = pts - c # xoay quanh tam cho on dinh so hoc
+
+ best = []
+ n_ang = int(round(2.0 * math.pi / self.angle_step))
+ for i in range(n_ang):
+ th = i * self.angle_step
+ ct, st = math.cos(th), math.sin(th)
+ qx = ct * P[:, 0] - st * P[:, 1]
+ qy = st * P[:, 0] + ct * P[:, 1]
+
+ M = np.zeros_like(Lp)
+ cr = np.round(qy / rc).astype(np.int64) % Hp
+ cc = np.round(qx / rc).astype(np.int64) % Wp
+ np.add.at(M, (cr, cc), 1.0)
+
+ sc = np.fft.irfft2(FL * np.conj(np.fft.rfft2(M)), s=(Hp, Wp))
+ sc = sc[pad:pad + H, pad:pad + W]
+ sc[~Fc] = 0.0 # robot phai nam trong vung TRONG
+
+ r, cidx = np.unravel_index(int(np.argmax(sc)), sc.shape)
+ best.append((float(sc[r, cidx]), r, cidx, th, sc))
+
+ best.sort(key=lambda t: -t[0])
+ if not best or best[0][0] <= 0.0:
+ return None
+
+ # Gom TOP-K dinh tho, loai trung nhau trong ban kinh reject_radius.
+ # Phai xet nhieu dinh chu khong chi cai cao nhat: muc tho dung max-pool
+ # nen rat rong rai, thu tu o day chua chac dung.
+ rad_c = self.reject_radius / rc
+ cand = []
+ for sv, r0, c0, th0, _ in best[:self.top_k]:
+ if all((r0 - r) ** 2 + (c0 - cx0) ** 2 > rad_c * rad_c
+ for _, r, cx0, _ in cand):
+ cand.append((sv, r0, c0, th0))
+ if len(cand) >= 8:
+ break
+ if not cand:
+ return None
+
+ # ⚠️ Tinh chinh TUNG ung vien roi moi so diem voi nhau.
+ # Ban dau toi so diem o muc tho - do la sai. Muc tho co max-pool nen
+ # gan nhu moi cho canh tuong deu diem cao, hai gia thuyet tot/xau chi
+ # cach nhau 1.18 lan -> cong chan nham loai ca truong hop DUNG.
+ # O muc tinh, khop dung sac net hon han khop sai.
+ refined = [self.refine(P, g, r0, c0, th0, rc, res)
+ for _, r0, c0, th0 in cand]
+ refined = [r for r in refined if r is not None]
+ if not refined:
+ return None
+ refined.sort(key=lambda t: -t[0])
+
+ bs, bx, by, bth = refined[0]
+
+ # ⚠️ Doi thu phai LUON tim duoc, ke ca khi khong co trong top-K.
+ # Ban dau toi chi lay s2 tu cac ung vien da tinh chinh. Tren ban do nho
+ # (house 16x17 m) ca 8 ung vien co the nam gon trong ban kinh 2 m cua
+ # nhau -> khong co doi thu xa -> s2 = 0 -> ty le no len vo cuc va node
+ # publish bua. Do duoc: ty le max 201.217.651 va 9.3% duong tinh gia
+ # voi sai so 9-13 m. Nen phai quet lai truong diem THO o vung xa.
+ s2 = 0.0
+ for sv, x2, y2, _ in refined[1:]:
+ if math.hypot(x2 - bx, y2 - by) > self.reject_radius:
+ s2 = max(s2, sv)
+
+ rw = int(round((by - rc / 2.0) / rc))
+ cw = int(round((bx - rc / 2.0) / rc))
+ rad_f = self.reject_radius / rc
+ rr, cc = np.ogrid[:H, :W]
+ far = ((rr - rw) ** 2 + (cc - cw) ** 2) > rad_f * rad_f
+ fv, fr, fc, fth = -1.0, None, None, 0.0
+ for _, _, _, th_, sc in best:
+ m = np.where(far, sc, 0.0)
+ v = float(m.max())
+ if v > fv:
+ fv = v
+ fr, fc = np.unravel_index(int(np.argmax(m)), m.shape)
+ fth = th_
+ if fr is not None:
+ alt = self.refine(P, g, fr, fc, fth, rc, res)
+ if alt is not None:
+ s2 = max(s2, alt[0])
+
+ # ---- Doi thu theo GOC: CUNG vi tri, KHAC huong ----
+ # Cung khuon mau voi doi thu vi tri o tren: tim dinh tho roi TINH CHINH
+ # truoc khi so diem. So o muc tho la sai - xem ghi chu dong ~364.
+ near = ~far
+ gv, gr, gc2, gth = -1.0, None, None, 0.0
+ for _, _, _, th_, sc in best:
+ dth = abs(math.atan2(math.sin(th_ - bth), math.cos(th_ - bth)))
+ if dth < self.min_angle_sep:
+ continue
+ m = np.where(near, sc, 0.0)
+ v = float(m.max())
+ if v > gv:
+ gv = v
+ gr, gc2 = np.unravel_index(int(np.argmax(m)), m.shape)
+ gth = th_
+ s2_yaw = 0.0
+ if gr is not None:
+ alt2 = self.refine(P, g, gr, gc2, gth, rc, res)
+ if alt2 is not None:
+ s2_yaw = alt2[0]
+
+ # Ket qua (bx,by,bth) dat TAM c cua dam diem vao cho nao tren ban do.
+ # Doi sang T_map_odom: p_map = R(th)*p_odom + t, voi
+ # t = (bx,by) + goc_ban_do - R(th)*c
+ def to_map(sx, sy, sth):
+ """(bx,by,bth) o luoi -> T_map_odom roi ghep odom->base."""
+ cc_, ss_ = math.cos(sth), math.sin(sth)
+ mx = sx + g['ox'] - (cc_ * c[0] - ss_ * c[1])
+ my = sy + g['oy'] - (ss_ * c[0] + cc_ * c[1])
+ return self.compose(mx, my, sth)
+
+ # Toan bo ung vien da tinh chinh, doi sang he ban do. refined[0] la
+ # nguoi thang; phan con lai la doi thu that su - chung da duoc khu
+ # trung theo reject_radius nen moi cai la MOT CHO khac nhau.
+ hyps = [to_map(hx, hy, hth) + (hs,) for hs, hx, hy, hth in refined]
+
+ ct, st = math.cos(bth), math.sin(bth)
+ tx = bx + g['ox'] - (ct * c[0] - st * c[1])
+ ty = by + g['oy'] - (st * c[0] + ct * c[1])
+
+ return self.compose(tx, ty, bth) + (bs, s2, s2_yaw, tx, ty, bth, hyps)
+
+ def refine(self, P, g, r0, c0, th0, rc, res):
+ """Tinh chinh mot ung vien o do phan giai ban do.
+
+ Quet +-nua o tho quanh dinh (du phu kin o do) va +-mot buoc goc.
+ Tinh truc tiep, khong FFT - vung nho nen re hon FFT."""
+ x0, y0 = c0 * rc + rc / 2.0, r0 * rc + rc / 2.0
+ span = rc / 2.0
+ bs, bx, by, bth = -1.0, None, None, None
+ for dth in np.arange(-self.angle_step, self.angle_step + 1e-9,
+ self.angle_step / 5.0):
+ th = th0 + dth
+ ct, st = math.cos(th), math.sin(th)
+ qx = ct * P[:, 0] - st * P[:, 1]
+ qy = st * P[:, 0] + ct * P[:, 1]
+ for dx in np.arange(-span, span + 1e-9, res * 2):
+ cix = np.round((qx + x0 + dx) / res).astype(np.int64)
+ okx = (cix >= 0) & (cix < g['w'])
+ for dy in np.arange(-span, span + 1e-9, res * 2):
+ ri = np.round((qy + y0 + dy) / res).astype(np.int64)
+ m = okx & (ri >= 0) & (ri < g['h'])
+ if not m.any():
+ continue
+ v = float(g['L'][ri[m], cix[m]].sum())
+ if v > bs:
+ bs, bx, by, bth = v, x0 + dx, y0 + dy, th
+ if bx is None:
+ return None
+ return (bs, bx, by, bth)
+
+ def compose(self, tx, ty, th):
+ """T_map_odom vua tim duoc, ghep voi odom->base HIEN TAI.
+
+ Robot da xoay trong luc gom scan nen pose bay gio khac luc bat dau.
+ Gom o he odom (co dinh) roi ghep o day la cach duy nhat khong bi lech."""
+ try:
+ tr = self.buf.lookup_transform(self.odom_frame, self.base_frame,
+ rospy.Time(0), rospy.Duration(0.5))
+ except Exception as e:
+ rospy.logwarn('global_scan_init: khong lay duoc %s->%s: %s',
+ self.odom_frame, self.base_frame, e)
+ return (tx, ty, th)
+ self.pose_stamp = tr.header.stamp
+ p = tr.transform.translation
+ b = yaw_of(tr.transform.rotation)
+ ct, st = math.cos(th), math.sin(th)
+ return (tx + ct * p.x - st * p.y,
+ ty + st * p.x + ct * p.y,
+ math.atan2(math.sin(th + b), math.cos(th + b)))
+
+ # ---------------- publish ----------------
+
+ def publish_hypotheses(self, hyps):
+ """Cong bo tap gia thuyet len /reloc/hypotheses.
+
+ Thu tu = diem giam dan, nen phan tu [0] la nguoi thang. Diem so KHONG
+ goi kem duoc (PoseArray khong co cho) - lop tren can diem thi doc
+ /reloc/hypotheses cung luc voi log, hoac ta doi sang msg rieng sau.
+ """
+ if not hyps:
+ return
+ msg = PoseArray()
+ msg.header.stamp = rospy.Time.now()
+ msg.header.frame_id = self.map_frame
+ for hx, hy, hth, _score in hyps:
+ p = Pose()
+ p.position.x = hx
+ p.position.y = hy
+ p.orientation.z = math.sin(hth / 2.0)
+ p.orientation.w = math.cos(hth / 2.0)
+ msg.poses.append(p)
+ self.hyp_pub.publish(msg)
+ if len(hyps) > 1:
+ rospy.loginfo('global_scan_init: %d gia thuyet -> /reloc/hypotheses '
+ '(cach nhau >= %.1f m)', len(hyps), self.reject_radius)
+
+ def publish(self, x, y, th, ratio):
+ m = PoseWithCovarianceStamped()
+ # Dong dau bang moc TF that su da dung, khong phai now():
+ # noi that ve thoi diem pose nay co gia tri.
+ m.header.stamp = self.pose_stamp or rospy.Time.now()
+ m.header.frame_id = self.map_frame
+ m.pose.pose.position.x = x
+ m.pose.pose.position.y = y
+ m.pose.pose.orientation.z = math.sin(th / 2.0)
+ m.pose.pose.orientation.w = math.cos(th / 2.0)
+
+ # Cang dut khoat thi cang tin. Khong lay duoi 0.05 m / 0.03 rad: ICP
+ # cua RTAB-Map van phai duoc phep tinh chinh tiep.
+ s_xy = max(0.05, 0.30 / ratio)
+ s_th = max(0.03, 0.15 / ratio)
+ m.pose.covariance[0] = s_xy ** 2
+ m.pose.covariance[7] = s_xy ** 2
+ m.pose.covariance[35] = s_th ** 2
+ self.pub.publish(m)
+
+ # ---------------- kich hoat ----------------
+
+ def start(self):
+ with self.lock:
+ if self.grid is None:
+ return False, 'chua nhan duoc ban do tren topic map'
+ self.pts = []
+ self.yaw_acc = 0.0
+ self.yaw_prev = None
+ self.t_start = rospy.Time.now().to_sec()
+ self.active = True
+ rospy.loginfo('global_scan_init: bat dau gom scan. '
+ 'XOAY ROBOT TAI CHO %.0f do.',
+ math.degrees(self.yaw_sweep))
+ return True, 'dang gom scan, xoay robot tai cho'
+
+ def on_timer(self, _evt):
+ # ⚠️ Phai thu lai, khong duoc bo cuoc.
+ # Ban do hospital 1.76 GB mat ~19 s de RTAB-Map nap het vao bo nho lam
+ # viec (Mem/InitWMWithAllNodes=true). Bat mot lan sau `delay` giay roi
+ # thoi thi /map chua ve, node nam im vinh vien.
+ if self.start()[0]:
+ return
+ rospy.loginfo_throttle(10.0, 'global_scan_init: cho /map...')
+ rospy.Timer(rospy.Duration(2.0), self.on_timer, oneshot=True)
+
+ # ---------------- tu kiem "da lac" ----------------
+
+ def score_current_pose(self):
+ """Cham diem scan moi nhat tai pose DANG TIN (map->base tu TF).
+
+ Tra ve diem trung binh moi diem, hoac None neu chua du dieu kien.
+ Dung CHINH truong likelihood da dung de khop, nen thang do nhat quan
+ voi diem luc khop thanh cong."""
+ msg = self.last_scan
+ with self.lock:
+ g = self.grid
+ if msg is None or g is None:
+ return None
+ try:
+ tr = self.buf.lookup_transform(self.map_frame, msg.header.frame_id,
+ rospy.Time(0), rospy.Duration(0.2))
+ except Exception:
+ return None
+
+ r = np.asarray(msg.ranges, dtype=np.float32)
+ ok = np.isfinite(r) & (r > msg.range_min) & (r < min(msg.range_max,
+ self.max_range))
+ if ok.sum() < 50:
+ return None
+ idx = np.nonzero(ok)[0]
+ ang = msg.angle_min + idx * msg.angle_increment
+ rr = r[idx]
+
+ t = tr.transform.translation
+ th = yaw_of(tr.transform.rotation)
+ ct, st = math.cos(th), math.sin(th)
+ lx, ly = rr * np.cos(ang), rr * np.sin(ang)
+ mx = ct * lx - st * ly + t.x
+ my = st * lx + ct * ly + t.y
+
+ ci = np.round((mx - g['ox']) / g['res']).astype(np.int64)
+ ri = np.round((my - g['oy']) / g['res']).astype(np.int64)
+ m = (ci >= 0) & (ci < g['w']) & (ri >= 0) & (ri < g['h'])
+ if m.sum() < 50:
+ return None
+ return float(g['L'][ri[m], ci[m]].mean())
+
+ def on_watch(self, _evt):
+ """Dinh ky kiem pose dang tin co con giai thich duoc scan khong."""
+ if not self.watch_lost or self.ref_score is None:
+ return
+ with self.lock:
+ if self.active: # dang gom scan roi, khoi kiem
+ self.lost_since = None
+ return
+
+ sc = self.score_current_pose()
+ if sc is None:
+ # ⚠️ Im lang o day la diem mu: khong phan biet duoc "chua do duoc"
+ # voi "do duoc va thay on". Phai noi ro.
+ rospy.logwarn_throttle(5.0,
+ 'global_scan_init[watch]: chua cham duoc diem (thieu scan/ban '
+ 'do, hoac tra TF %s->laser that bai).', self.map_frame)
+ return
+
+ thr = self.ref_score * self.lost_score_ratio
+ rospy.loginfo_throttle(2.0,
+ 'global_scan_init[watch]: diem %.4f | nguong %.4f | tham chieu '
+ '%.4f | %s', sc, thr, self.ref_score,
+ 'ON' if sc >= thr else 'DUOI NGUONG')
+
+ if sc >= thr:
+ self.lost_since = None
+ return
+
+ now = rospy.Time.now().to_sec()
+ if self.lost_since is None:
+ self.lost_since = now
+ return
+ if now - self.lost_since < self.lost_hold:
+ return
+
+ rospy.logwarn('global_scan_init: NGHI DA LAC - diem %.3f < %.0f%% cua '
+ '%.3f trong %.1fs. Tu kich hoat lai.',
+ sc, 100.0 * self.lost_score_ratio, self.ref_score,
+ self.lost_hold)
+ self.lost_since = None
+ self.ref_score = None
+ self.start()
+
+ def arm_retry(self):
+ """Tu nap lai sau khi bi tu choi. Xem retry_period o onInit."""
+ if self.retry_period <= 0.0:
+ rospy.loginfo('global_scan_init: retry_period=0 -> dung. Goi tay: '
+ 'rosservice call /global_scan_init/relocalize')
+ return
+ rospy.loginfo('global_scan_init: thu lai sau %.0fs. Di chuyen robot vai '
+ 'met de doi goc nhin - dung yen thi lan sau cung nhap '
+ 'nhang y het.', self.retry_period)
+ rospy.Timer(rospy.Duration(self.retry_period), self.on_timer,
+ oneshot=True)
+
+ def on_trigger(self, _req):
+ ok, msg = self.start()
+ return TriggerResponse(success=ok, message=msg)
+
+
+if __name__ == '__main__':
+ rospy.init_node('global_scan_init')
+ try:
+ GlobalScanInit()
+ rospy.spin()
+ except rospy.ROSInterruptException:
+ pass
diff --git a/src/localization_ops/scripts/reloc_active.py b/src/localization_ops/scripts/reloc_active.py
new file mode 100755
index 0000000..b327fb8
--- /dev/null
+++ b/src/localization_ops/scripts/reloc_active.py
@@ -0,0 +1,325 @@
+#!/usr/bin/env python3
+"""
+reloc_active - DINH VI CHU DONG: tinh xem phai DI DAU de het nhap nhang.
+
+============ VAN DE ============
+global_scan_init khop rat chinh xac khi khong nhap nhang (da do: 0.155-0.21 m,
+0.07-0.09 do). Nhung o nhieu cho trong benh vien no TU CHOI:
+
+ NHAP NHANG - ty le 1.04 < 1.30. KHONG publish.
+ Di chuyen vai met roi thu lai.
+
+Tu choi la DUNG - hai cho cho diem gan bang nhau thi tra loi bua nguy hiem hon
+im lang. Nhung "di chuyen vai met" bat nguoi van hanh MO: len, xuong, thu lai,
+cho toi khi trung. Da do tren ban do hospital: 3/4 lan thu bi tu choi.
+
+============ Y TUONG ============
+Luc tu choi, he KHONG mu. No biet ro:
+ - co may gia thuyet, o dau (/reloc/hypotheses)
+ - ban do trong nhu the nao (/map)
+
+Tu hai thu do tinh duoc: CHUYEN DONG NAO TACH CAC GIA THUYET NHANH NHAT.
+
+Voi moi chuyen dong ung vien, mo phong scan LiDAR ma TUNG gia thuyet se thay
+sau khi thuc hien. Neu hai gia thuyet du doan hai canh hoan toan khac nhau thi
+chi can di mot lan la biet minh o dau. Chon chuyen dong co do phan ky lon nhat.
+
+ Nhap nhang giua 2 cho. Di THANG 1.8 m se phan biet duoc.
+
+Doi mo hinh tuong tac: tu "doan va thu lai" sang "he chi duong, di mot lan".
+
+============ ⚠️ GIOI HAN ============
+Phu thuoc hoan toan vao chat luong tap gia thuyet. Neu cho DUNG khong nam trong
+/reloc/hypotheses thi chuyen dong de xuat cung vo nghia - no chi phan biet duoc
+cac gia thuyet SAI voi nhau.
+
+=> Node nay KHONG thay the viec kiem tra. Sau khi di, van phai de
+ global_scan_init khop lai va di qua day du cong kiem cua no.
+
+============ CACH DUNG ============
+ roslaunch robot_bringup localization.launch enable_global_init:=true \\
+ enable_active_reloc:=true
+
+ rostopic echo /reloc/suggested_motion
+"""
+
+import math
+
+import numpy as np
+import rospy
+from geometry_msgs.msg import PoseArray, PoseStamped
+from nav_msgs.msg import OccupancyGrid
+from sensor_msgs.msg import LaserScan
+
+
+def yaw_of(q):
+ return math.atan2(2.0 * (q.w * q.z + q.x * q.y),
+ 1.0 - 2.0 * (q.y * q.y + q.z * q.z))
+
+
+class ActiveReloc(object):
+ def __init__(self):
+ self.map_frame = rospy.get_param('~map_frame', 'map')
+ self.base_frame = rospy.get_param('~base_frame', 'base_footprint')
+
+ # ---- Tap chuyen dong ung vien ----
+ # Robot vi sai: khong truot ngang duoc. Nen moi chuyen dong la
+ # "quay tai cho goc phi, roi di thang d met".
+ self.turns = [math.radians(a) for a in
+ rospy.get_param('~turn_options_deg',
+ [0, 45, -45, 90, -90, 135, -135, 180])]
+ self.dists = rospy.get_param('~dist_options', [0.5, 1.0, 1.5, 2.0, 3.0])
+
+ # ⚠️ CHI XET TOP-N GIA THUYET.
+ #
+ # PoseArray den theo thu tu diem giam dan, [0] la nguoi thang.
+ # Da do: o mot diem tha co 7 gia thuyet, va KHONG chuyen dong nao an
+ # toan o ca 7 -> node tu vo hieu hoa dung luc nhap nhang nhat.
+ #
+ # Nhung cac gia thuyet hang duoi co diem thap han; tach chung ra khong
+ # dang de danh mat mot chuyen dong tot. Chi can phan biet nguoi thang
+ # voi vai doi thu SAT NUT.
+ self.max_hyps = rospy.get_param('~max_hyps', 3)
+
+ # ---- Mo phong scan ----
+ # Lay mau thua tia: khong can 1081 tia de biet hai canh co khac nhau
+ # khong, va do phan ky bao hoa rat nhanh theo so tia.
+ self.n_rays = rospy.get_param('~n_rays', 72)
+ self.fov = math.radians(rospy.get_param('~fov_deg', 236.0))
+ self.sim_max_range = rospy.get_param('~sim_max_range', 12.0)
+ self.ray_step = rospy.get_param('~ray_step', 0.10) # m
+
+ # Hai tia coi la KHAC NHAU khi lech qua nguong nay.
+ self.diff_thresh = rospy.get_param('~diff_thresh', 0.5) # m
+
+ # ⚠️ Chuyen dong de xuat phai DI DUOC o MOI gia thuyet.
+ # Neu no dam tuong trong mot gia thuyet thi khong the bao nguoi van hanh
+ # thuc hien - ta chua biet minh dang o gia thuyet nao.
+ self.clearance = rospy.get_param('~clearance', 0.35) # m
+
+ # Duoi muc TANG THEM nay thi di chuyen khong giup gi -> noi that thay
+ # vi de xuat bua mot chuyen dong vo ich.
+ self.min_gain = rospy.get_param('~min_gain', 0.05)
+
+ self.grid = None
+ self.pub = rospy.Publisher('/reloc/suggested_motion', PoseStamped,
+ queue_size=1, latch=True)
+ rospy.Subscriber('map', OccupancyGrid, self.on_map, queue_size=1)
+ rospy.Subscriber('/reloc/hypotheses', PoseArray, self.on_hyps,
+ queue_size=1)
+ rospy.Subscriber('scan', LaserScan, self.on_scan, queue_size=1)
+
+ self._scan_seen = False
+ rospy.loginfo('reloc_active: san sang. Cho /reloc/hypotheses.')
+
+ # ---------------- dau vao ----------------
+
+ def on_scan(self, msg):
+ """Lay thong so LiDAR THAT thay vi doan - chi can mot ban tin."""
+ if self._scan_seen:
+ return
+ self._scan_seen = True
+ span = msg.angle_max - msg.angle_min
+ if 0.1 < span < 2.0 * math.pi + 0.1:
+ self.fov = span
+ if 0.5 < msg.range_max < 100.0:
+ self.sim_max_range = min(self.sim_max_range, msg.range_max)
+ rospy.loginfo('reloc_active: LiDAR that -> FOV %.1f do, mo phong toi %.1f m',
+ math.degrees(self.fov), self.sim_max_range)
+
+ def on_map(self, msg):
+ w, h = msg.info.width, msg.info.height
+ g = np.asarray(msg.data, dtype=np.int8).reshape(h, w)
+ self.grid = dict(occ=(g >= 50), free=(g == 0),
+ res=msg.info.resolution,
+ ox=msg.info.origin.position.x,
+ oy=msg.info.origin.position.y, w=w, h=h)
+ rospy.loginfo_once('reloc_active: nhan ban do %dx%d @ %.3f m', w, h,
+ msg.info.resolution)
+
+ # ---------------- mo phong ----------------
+
+ def cast(self, x, y, th):
+ """Mo phong scan LiDAR tai pose (x,y,th). Tra ve vector tam tia.
+
+ Ray-cast vector hoa: lay mau TAT CA tia o TAT CA buoc cung luc, roi tim
+ buoc dau tien cham vat can tren tung tia. Nhanh hon vong lap tung tia
+ vai chuc lan, va so tia * so buoc o day chi vai nghin."""
+ g = self.grid
+ n_step = int(self.sim_max_range / self.ray_step)
+ ang = th + np.linspace(-self.fov / 2.0, self.fov / 2.0, self.n_rays)
+ d = (np.arange(1, n_step + 1) * self.ray_step)[None, :] # (1,S)
+
+ px = x + np.cos(ang)[:, None] * d # (R,S)
+ py = y + np.sin(ang)[:, None] * d
+
+ ci = np.round((px - g['ox']) / g['res']).astype(np.int64)
+ ri = np.round((py - g['oy']) / g['res']).astype(np.int64)
+ inside = (ci >= 0) & (ci < g['w']) & (ri >= 0) & (ri < g['h'])
+
+ hit = np.zeros(ci.shape, dtype=bool)
+ hit[inside] = g['occ'][ri[inside], ci[inside]]
+ # Ra ngoai ban do cung coi la "het thong tin" -> dung tia o do.
+ hit |= ~inside
+
+ any_hit = hit.any(axis=1)
+ first = np.argmax(hit, axis=1)
+ rng = np.where(any_hit, (first + 1) * self.ray_step, self.sim_max_range)
+ return rng
+
+ def path_clear(self, x, y, th, turn, dist):
+ """Duong di thang sau khi quay co trong khong? Kiem ca le an toan."""
+ g = self.grid
+ a = th + turn
+ n = max(2, int(dist / (g['res'] * 0.5)))
+ t = np.linspace(0.0, dist, n)
+ px = x + math.cos(a) * t
+ py = y + math.sin(a) * t
+ # No rong theo clearance: lay mau them hai ben duong di.
+ offs = np.linspace(-self.clearance, self.clearance, 3)
+ ox_ = -math.sin(a) * offs
+ oy_ = math.cos(a) * offs
+ qx = (px[:, None] + ox_[None, :]).ravel()
+ qy = (py[:, None] + oy_[None, :]).ravel()
+ ci = np.round((qx - g['ox']) / g['res']).astype(np.int64)
+ ri = np.round((qy - g['oy']) / g['res']).astype(np.int64)
+ ok = (ci >= 0) & (ci < g['w']) & (ri >= 0) & (ri < g['h'])
+ if not ok.all():
+ return False
+ return not g['occ'][ri[ok], ci[ok]].any()
+
+ # ---------------- lua chon ----------------
+
+ def on_hyps(self, msg):
+ if self.grid is None:
+ rospy.logwarn_throttle(5.0, 'reloc_active: chua co /map.')
+ return
+ all_hyps = [(p.position.x, p.position.y, yaw_of(p.orientation))
+ for p in msg.poses]
+ if len(all_hyps) < 2:
+ # Mot gia thuyet = khong nhap nhang. global_scan_init tu lo.
+ return
+ n_all = len(all_hyps)
+ hyps = all_hyps[:self.max_hyps] # da sap theo diem giam dan
+
+ t0 = rospy.Time.now().to_sec()
+
+ # ⚠️ NOI LONG DAN, khong phai tat ca-hoac-khong.
+ #
+ # Doi an toan o ca N gia thuyet la ly tuong, nhung neu khong co thi
+ # tha de xuat mot chuyen dong an toan o vai gia thuyet DAU BANG con hon
+ # im lang bat nguoi van hanh mo. Lop an toan vat ly (safety_monitor +
+ # costmap) van la chan cuoi.
+ best, used = None, 0
+ for need in range(len(hyps), 0, -1):
+ best = self.search(hyps[:need])
+ if best is not None:
+ used = need
+ break
+ if best is not None and used < len(hyps):
+ rospy.logwarn('reloc_active: khong co chuyen dong an toan o ca %d '
+ 'gia thuyet dau -> chi bao dam o %d gia thuyet manh '
+ 'nhat. Lop an toan vat ly van chan.', len(hyps), used)
+
+ dt = rospy.Time.now().to_sec() - t0
+ if best is None:
+ rospy.logwarn('reloc_active: %d gia thuyet (xet %d), nhung khong '
+ 'chuyen dong nao an toan ke ca chi voi gia thuyet '
+ 'manh nhat. Can nguoi can thiep.', n_all, len(hyps))
+ return
+
+ gain, turn, dist, sep = best
+ if gain < self.min_gain:
+ rospy.logwarn('reloc_active: %d gia thuyet. Chuyen dong tot nhat chi '
+ 'TANG THEM %.0f%% so tia tach duoc (< %.0f%%) - di quanh '
+ 'day khong giup gi, cac cho nay giong nhau tren ca vung '
+ 'lan can. Can di XA hon %.1f m.',
+ n_all, 100 * gain, 100 * self.min_gain, max(self.dists))
+ return
+
+ self.publish(turn, dist)
+ rospy.logwarn('reloc_active: NHAP NHANG giua %d cho (xet %d manh nhat). '
+ '%s -> tach %.0f%% so tia (tang %+.0f%% so voi dung yen). '
+ '(tinh trong %.2fs)',
+ n_all, used, self.describe(turn, dist),
+ 100 * sep, 100 * gain, dt)
+
+ def separation(self, hyps, turn, dist):
+ """Ty le tia khac nhau giua CAP GIA THUYET TE NHAT, sau chuyen dong."""
+ scans = []
+ for hx, hy, hth in hyps:
+ a = hth + turn
+ scans.append(self.cast(hx + math.cos(a) * dist,
+ hy + math.sin(a) * dist, a))
+ worst = 1.0
+ for i in range(len(scans)):
+ for j in range(i + 1, len(scans)):
+ frac = float(np.mean(np.abs(scans[i] - scans[j])
+ > self.diff_thresh))
+ worst = min(worst, frac)
+ return worst
+
+ def search(self, hyps):
+ """Tim chuyen dong LAM TANG do tach nhieu nhat, an toan o TAT CA hyps.
+
+ ⚠️ Toi da hoa MUC TANG THEM, khong phai do tach tuyet doi.
+
+ Cac gia thuyet von nam o nhung cho KHAC NHAU tren ban do, nen scan cua
+ chung DA khac nhau san truoc khi di chuyen met nao. Cham diem tuyet doi
+ se cho 50-58% ngay ca voi chuyen dong 0.5 m - do la con so cua HIEN
+ TRANG, khong phai loi ich cua viec di.
+ Da do: chon dung 0.5 m (quang ngan nhat) ca ba lan lien tiep.
+
+ Tru di muc tach khi DUNG YEN thi moi do duoc chuyen dong dong gop gi.
+ """
+ if len(hyps) < 2:
+ return None
+ base = self.separation(hyps, 0.0, 0.0)
+ best = None
+ for turn in self.turns:
+ for dist in self.dists:
+ if not all(self.path_clear(hx, hy, hth, turn, dist)
+ for hx, hy, hth in hyps):
+ continue
+
+ # Dung CAP TE NHAT chu khong trung binh: chi can MOT cap khong
+ # tach duoc la van con nhap nhang.
+ sep = self.separation(hyps, turn, dist)
+ gain = sep - base
+ if best is None or gain > best[0]:
+ best = (gain, turn, dist, sep)
+ return best
+
+ @staticmethod
+ def describe(turn, dist):
+ d = math.degrees(turn)
+ if abs(d) < 1.0:
+ return 'Di THANG %.1f m' % dist
+ if abs(abs(d) - 180.0) < 1.0:
+ return 'QUAY DAU roi di %.1f m' % dist
+ return 'Quay %s %.0f do roi di %.1f m' % (
+ 'TRAI' if d > 0 else 'PHAI', abs(d), dist)
+
+ def publish(self, turn, dist):
+ """Muc tieu trong he base_footprint: quay `turn` roi tien `dist`."""
+ m = PoseStamped()
+ m.header.stamp = rospy.Time.now()
+ m.header.frame_id = self.base_frame
+ m.pose.position.x = math.cos(turn) * dist
+ m.pose.position.y = math.sin(turn) * dist
+ m.pose.orientation.z = math.sin(turn / 2.0)
+ m.pose.orientation.w = math.cos(turn / 2.0)
+ self.pub.publish(m)
+
+
+def main():
+ rospy.init_node('reloc_active')
+ ActiveReloc()
+ rospy.spin()
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except rospy.ROSInterruptException:
+ pass
diff --git a/src/localization_ops/src/reloc_gicp_node.cpp b/src/localization_ops/src/reloc_gicp_node.cpp
new file mode 100644
index 0000000..d7d6e7d
--- /dev/null
+++ b/src/localization_ops/src/reloc_gicp_node.cpp
@@ -0,0 +1,409 @@
+/**
+ * reloc_gicp_node - GD3: tinh chinh gia thuyet dinh vi bang GICP tren may depth.
+ *
+ * ============ VI SAO CAN ============
+ * Reg/Strategy=1 nghia la RTAB-Map dang ky CHI bang ICP tren LiDAR - depth cua
+ * D410 khong bao gio duoc dung vao viec chot pose. Node nay bit dung cho do:
+ * global_scan_init cho tap gia thuyet SE(2) tu LiDAR, con day dung cau truc 3D
+ * that (khung cua, ban ghe, thiet bi tuong) de XEP HANG LAI va siet sai so.
+ *
+ * ============ KY VONG DUNG MUC ============
+ * Khop LiDAR da cho 0.155-0.21 m, ma Icp/MaxTranslation = 0.3 nen RTAB-Map con
+ * tu tinh chinh tiep. GICP o day siet xuong vai cm - GIA TRI GIA TANG NHO.
+ * Lam vi no dung kien truc 2.5D, KHONG phai vi no cuu duoc nhap nhang. Nhap
+ * nhang la gioi han THONG TIN, chi chuyen dong moi giai duoc - xem reloc_active.
+ *
+ * ⚠️ MAC DINH KHONG publish /initialpose (~publish_initialpose = false).
+ * global_scan_init van la noi DUY NHAT chot pose. Bat node nay o mac dinh
+ * KHONG THE lam xau do chinh xac - no chi in ra va publish /reloc/gicp_pose.
+ *
+ * ⚠️ TEN FILE NOI "GICP" NHUNG NO CHAY ICP + TransformationEstimation2D.
+ * Giu ten cu vi doi thi phai sua lan sang 3 launch file, khong dang.
+ *
+ * Duong di toi day, ghi lai de khong ai quay lai:
+ * 1. Plan ban dau: GICP + TransformationEstimation2D. Doc pcl/registration/
+ * gicp.h:118 -> GICP gan cung rigid_transformation_estimation_ vao BFGS
+ * rieng ngay trong constructor va override computeTransformation, nen
+ * setTransformationEstimation() BI BO QUA IM LANG. Bien dich tron nhung
+ * cho ra nghiem 6-DoF.
+ * 2. Nen thu: de GICP chay du 3D roi CHIEU nghiem ve SE(2). DA DO va HONG:
+ * may depth song chi 211-429 diem tu mot goc nhin 69 do -> bai toan SUY
+ * BIEN, nghiem troi dz toi 1.03 m va nghieng toi 47.9 do, ca 4 gia thuyet
+ * deu bi cong kiem lech-ngoai-mat-phang loai sach.
+ * 3. Hien tai: ICP + TransformationEstimation2D. ICP CO goi
+ * transformation_estimation_, nen nghiem bi ep ve SE(2) that su.
+ *
+ * Cong kiem lech ngoai mat phang van giu du gio khong con kich hoat duoc:
+ * no la luoi an toan, bat duoc ngay neu ai doi lai sang 6-DoF.
+ */
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include