{"id":"2228c7c2-72c7-4081-95ee-394299858159","entityType":"agent","slug":"clawhub-datadrivenconstruction-bim-cost-estimation-cwicr","name":"Bim Cost Estimation Cwicr","canonicalUrl":"https://www.xpersona.co/agent/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr","canonicalPath":"/agent/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr","generatedAt":"2026-10-11T04:35:39.934Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-11T02:18:00.692Z","emptyReason":null},"description":"Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing. Skill: Bim Cost Estimation Cwicr Owner: datadrivenconstruction Summary: Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing. Tags: latest:2.1.0 Version history: v2.1.0 | 2026-02-13T21:08:30.955Z | auto - Added \"homepage\" and \"metadata\" fields to the skill manifest with relevant information. - Specified platform compatibility","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.2K downloads reported by the source. Last updated 10/11/2026.","installCommand":"clawhub skill install s1774mv3t1cm8r1kgs9hccdnmn8852nb:bim-cost-estimation-cwicr","sourceUrl":"https://clawhub.ai/datadrivenconstruction/bim-cost-estimation-cwicr","homepage":"https://clawhub.ai/datadrivenconstruction/skills/bim-cost-estimation-cwicr","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/datadrivenconstruction/bim-cost-estimation-cwicr","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/datadrivenconstruction/skills/bim-cost-estimation-cwicr","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":62,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing. Skill: Bim Co"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-11T02:18:00.692Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T02:18:00.692Z","emptyReason":null},"stars":null,"forks":null,"downloads":1192,"packageName":null,"latestVersion":"2.1.0","tractionLabel":"1.2K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T02:18:00.627Z","emptyReason":null},"lastUpdatedAt":"2026-10-11T02:18:00.692Z","lastCrawledAt":"2026-10-11T02:18:00.627Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-12T02:18:00.627Z","lastVerifiedAt":null,"highlights":[{"version":"2.1.0","createdAt":"2026-02-13T21:08:30.955Z","changelog":"- Added \"homepage\" and \"metadata\" fields to the skill manifest with relevant information. - Specified platform compatibility (Darwin, Linux, Win32) and required environment variables in metadata. - No changes to Python code or estimation logic.","fileCount":4,"zipByteSize":8043},{"version":"2.0.0","createdAt":"2026-02-13T15:22:53.595Z","changelog":"**Major upgrade: Seamlessly automate BIM cost estimation using AI and an extensive construction cost database.** - Adds end-to-end pipeline for automated cost estimation from BIM models using DDC CWICR (55,719 work items, 9 global regions). - Enables AI classification of BIM elements and vector search for precise work item and rate matching. - Supports multi-language cost data and pricing from major world cities. - Provides detailed process breakdown and a clear Python implementation for real-world integration. - Delivers estimates in hours with consistent methodology, reducing manual effort by up to 80%.","fileCount":4,"zipByteSize":7895},{"version":"1.0.0","createdAt":"2026-02-07T14:34:46.541Z","changelog":"BIM Cost Estimation CWICR 1.0.0 - Initial release of automated BIM-to-cost estimation using the DDC CWICR database. - Supports AI classification and vector search for accurate mapping of BIM elements to 55,719 work items with localized pricing in 9 languages. - Pipeline includes quantity takeoff extraction, phase/trade mapping, multi-stage decomposition, and rapid cost reporting. - Integration examples provided for OpenAI embeddings and Qdrant vector search. - Outputs detailed estimates by element, trade, and phase, exportable to HTML and Excel.","fileCount":2,"zipByteSize":6267}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s1774mv3t1cm8r1kgs9hccdnmn8852nb:bim-cost-estimation-cwicr","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-11T04:35:39.934Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-datadrivenconstruction-bim-cost-estimation-cwicr/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-11T02:18:00.692Z","emptyReason":null},"readme":"Skill: Bim Cost Estimation Cwicr\n\nOwner: datadrivenconstruction\n\nSummary: Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing.\n\nTags: latest:2.1.0\n\nVersion history:\n\nv2.1.0 | 2026-02-13T21:08:30.955Z | auto\n\n- Added \"homepage\" and \"metadata\" fields to the skill manifest with relevant information.\n- Specified platform compatibility (Darwin, Linux, Win32) and required environment variables in metadata.\n- No changes to Python code or estimation logic.\n\nv2.0.0 | 2026-02-13T15:22:53.595Z | auto\n\n**Major upgrade: Seamlessly automate BIM cost estimation using AI and an extensive construction cost database.**\n\n- Adds end-to-end pipeline for automated cost estimation from BIM models using DDC CWICR (55,719 work items, 9 global regions).\n- Enables AI classification of BIM elements and vector search for precise work item and rate matching.\n- Supports multi-language cost data and pricing from major world cities.\n- Provides detailed process breakdown and a clear Python implementation for real-world integration.\n- Delivers estimates in hours with consistent methodology, reducing manual effort by up to 80%.\n\nv1.0.0 | 2026-02-07T14:34:46.541Z | auto\n\nBIM Cost Estimation CWICR 1.0.0\n\n- Initial release of automated BIM-to-cost estimation using the DDC CWICR database.\n- Supports AI classification and vector search for accurate mapping of BIM elements to 55,719 work items with localized pricing in 9 languages.\n- Pipeline includes quantity takeoff extraction, phase/trade mapping, multi-stage decomposition, and rapid cost reporting.\n- Integration examples provided for OpenAI embeddings and Qdrant vector search.\n- Outputs detailed estimates by element, trade, and phase, exportable to HTML and Excel.\n\nArchive index:\n\nArchive v2.1.0: 4 files, 8043 bytes\n\nFiles: claw.json (531b), instructions.md (2154b), SKILL.md (21197b), _meta.json (144b)\n\nFile v2.1.0:SKILL.md\n\n---\r\nname: \"bim-cost-estimation-cwicr\"\r\ndescription: \"Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing.\"\r\nhomepage: \"https://datadrivenconstruction.io\"\r\nmetadata: {\"openclaw\":{\"emoji\":\"🏗️\",\"os\":[\"darwin\",\"linux\",\"win32\"],\"homepage\":\"https://datadrivenconstruction.io\",\"requires\":{\"bins\":[\"python3\"],\"env\":[\"OPENAI_API_KEY\",\"QDRANT_URL\"]},\"primaryEnv\":\"OPENAI_API_KEY\"}}\r\n---\r\n\r\n# BIM Cost Estimation with DDC CWICR\r\n\r\nGenerate accurate cost estimates from BIM models using AI classification and the DDC CWICR construction cost database.\r\n\r\n## Business Case\r\n\r\n**Problem**: Traditional cost estimation:\r\n- Manual and time-consuming (weeks for detailed estimate)\r\n- Subjective and inconsistent between estimators\r\n- Requires specialized knowledge\r\n- Difficult to update with design changes\r\n\r\n**Solution**: Automated BIM-to-cost pipeline:\r\n- Extract quantities directly from model\r\n- AI classifies elements to work items\r\n- Vector search finds matching prices in CWICR\r\n- Complete estimate in hours, not weeks\r\n\r\n**ROI**: 80% reduction in estimation time, consistent methodology\r\n\r\n## System Architecture\r\n\r\n```\r\n┌──────────────────────────────────────────────────────────────────────────┐\r\n│                  BIM TO COST ESTIMATION PIPELINE                          │\r\n├──────────────────────────────────────────────────────────────────────────┤\r\n│                                                                           │\r\n│   ┌─────────┐     ┌─────────┐     ┌─────────┐     ┌─────────────────┐   │\r\n│   │ BIM     │     │ DDC     │     │ AI      │     │ DDC CWICR       │   │\r\n│   │ Model   │────►│Converter│────►│ LLM     │────►│ Vector Search   │   │\r\n│   │.rvt/.ifc│     │         │     │         │     │ (Qdrant)        │   │\r\n│   └─────────┘     └─────────┘     └─────────┘     └─────────────────┘   │\r\n│                        │              │                    │             │\r\n│                        ▼              ▼                    ▼             │\r\n│                   ┌─────────┐    ┌─────────┐         ┌──────────┐       │\r\n│                   │ .xlsx   │    │ Work    │         │ Matched  │       │\r\n│                   │ QTO     │    │ Items   │         │ Rates    │       │\r\n│                   └─────────┘    └─────────┘         └──────────┘       │\r\n│                        │              │                    │             │\r\n│                        └──────────────┼────────────────────┘             │\r\n│                                       ▼                                  │\r\n│                              ┌─────────────────┐                        │\r\n│                              │ COST ESTIMATE   │                        │\r\n│                              │                 │                        │\r\n│                              │ • By element    │                        │\r\n│                              │ • By trade      │                        │\r\n│                              │ • By phase      │                        │\r\n│                              │ • Resources     │                        │\r\n│                              └─────────────────┘                        │\r\n│                                                                           │\r\n└──────────────────────────────────────────────────────────────────────────┘\r\n```\r\n\r\n## DDC CWICR Database\r\n\r\n```yaml\r\nDatabase Overview:\r\n  work_items: 55,719\r\n  resources: 27,672\r\n  languages: 9 (AR, DE, EN, ES, FR, HI, PT, RU, ZH)\r\n  fields_per_item: 85\r\n  embedding_model: text-embedding-3-large (3072d)\r\n  vector_db: Qdrant\r\n\r\nCollections:\r\n  - ddc_cwicr_ar  # Arabic (Dubai prices)\r\n  - ddc_cwicr_de  # German (Berlin prices)\r\n  - ddc_cwicr_en  # English (Toronto prices)\r\n  - ddc_cwicr_es  # Spanish (Barcelona prices)\r\n  - ddc_cwicr_fr  # French (Paris prices)\r\n  - ddc_cwicr_hi  # Hindi (Mumbai prices)\r\n  - ddc_cwicr_pt  # Portuguese (São Paulo prices)\r\n  - ddc_cwicr_ru  # Russian (St. Petersburg prices)\r\n  - ddc_cwicr_zh  # Chinese (Shanghai prices)\r\n```\r\n\r\n## Pipeline Stages\r\n\r\n| Stage | Name | Description |\r\n|-------|------|-------------|\r\n| 0 | Collect BIM Data | Extract elements from Revit/IFC |\r\n| 1 | Project Detection | AI identifies project type |\r\n| 2 | Phase Generation | AI creates construction phases |\r\n| 3 | Element Assignment | AI maps types to phases |\r\n| 4 | Work Decomposition | AI breaks types into work items |\r\n| 5 | Vector Search | Find matching rates in CWICR |\r\n| 6 | Unit Mapping | Convert BIM units to rate units |\r\n| 7 | Cost Calculation | Qty × Unit Price |\r\n| 7.5 | Validation | CTO review for completeness |\r\n| 8 | Aggregation | Sum by phases and categories |\r\n| 9 | Report Generation | HTML and Excel outputs |\r\n\r\n## Python Implementation\r\n\r\n```python\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom qdrant_client import QdrantClient\r\nfrom qdrant_client.models import Filter, FieldCondition, MatchValue\r\nfrom openai import OpenAI\r\nfrom typing import List, Dict, Optional\r\nfrom dataclasses import dataclass\r\nimport json\r\n\r\n@dataclass\r\nclass WorkItem:\r\n    \"\"\"Matched work item from CWICR\"\"\"\r\n    cwicr_code: str\r\n    description: str\r\n    unit: str\r\n    unit_price: float\r\n    labor_cost: float\r\n    material_cost: float\r\n    equipment_cost: float\r\n    productivity: float  # units per hour\r\n    currency: str\r\n    confidence: float\r\n\r\n@dataclass\r\nclass CostLineItem:\r\n    \"\"\"Single line item in estimate\"\"\"\r\n    bim_type: str\r\n    work_item: WorkItem\r\n    quantity: float\r\n    quantity_unit: str\r\n    total_cost: float\r\n    labor_cost: float\r\n    material_cost: float\r\n    equipment_cost: float\r\n    phase: str\r\n    trade: str\r\n\r\n\r\nclass BIMCostEstimator:\r\n    \"\"\"BIM to cost estimation using DDC CWICR\"\"\"\r\n\r\n    def __init__(\r\n        self,\r\n        qdrant_url: str,\r\n        qdrant_api_key: str = None,\r\n        openai_api_key: str = None,\r\n        language: str = \"EN\"\r\n    ):\r\n        self.qdrant = QdrantClient(url=qdrant_url, api_key=qdrant_api_key)\r\n        self.openai = OpenAI(api_key=openai_api_key)\r\n        self.language = language\r\n        self.collection = f\"ddc_cwicr_{language.lower()}\"\r\n\r\n    def get_embedding(self, text: str) -> List[float]:\r\n        \"\"\"Generate embedding for text\"\"\"\r\n        response = self.openai.embeddings.create(\r\n            model=\"text-embedding-3-large\",\r\n            input=text,\r\n            dimensions=3072\r\n        )\r\n        return response.data[0].embedding\r\n\r\n    def search_cwicr(\r\n        self,\r\n        query: str,\r\n        limit: int = 5,\r\n        category_filter: str = None\r\n    ) -> List[WorkItem]:\r\n        \"\"\"Search CWICR database for matching work items\"\"\"\r\n\r\n        # Get embedding\r\n        query_vector = self.get_embedding(query)\r\n\r\n        # Build filter if category specified\r\n        query_filter = None\r\n        if category_filter:\r\n            query_filter = Filter(\r\n                must=[\r\n                    FieldCondition(\r\n                        key=\"category\",\r\n                        match=MatchValue(value=category_filter)\r\n                    )\r\n                ]\r\n            )\r\n\r\n        # Search\r\n        results = self.qdrant.search(\r\n            collection_name=self.collection,\r\n            query_vector=query_vector,\r\n            query_filter=query_filter,\r\n            limit=limit\r\n        )\r\n\r\n        # Parse results\r\n        work_items = []\r\n        for r in results:\r\n            payload = r.payload\r\n            work_items.append(WorkItem(\r\n                cwicr_code=payload.get('code', ''),\r\n                description=payload.get('description', ''),\r\n                unit=payload.get('unit', ''),\r\n                unit_price=float(payload.get('unit_price', 0)),\r\n                labor_cost=float(payload.get('labor_cost', 0)),\r\n                material_cost=float(payload.get('material_cost', 0)),\r\n                equipment_cost=float(payload.get('equipment_cost', 0)),\r\n                productivity=float(payload.get('productivity', 1)),\r\n                currency=payload.get('currency', 'USD'),\r\n                confidence=r.score\r\n            ))\r\n\r\n        return work_items\r\n\r\n    def decompose_bim_type(\r\n        self,\r\n        bim_type: str,\r\n        category: str\r\n    ) -> List[str]:\r\n        \"\"\"Use LLM to decompose BIM type into work items\"\"\"\r\n\r\n        prompt = f\"\"\"\r\nDecompose this BIM element type into construction work items:\r\n\r\nBIM Type: {bim_type}\r\nCategory: {category}\r\n\r\nList the individual work activities needed to construct this element.\r\nFor example, \"Brick Wall 240mm\" decomposes into:\r\n- Masonry: Brick laying\r\n- Mortar: Cement mortar for joints\r\n- Plaster: Internal plaster finish\r\n- Paint: Wall painting\r\n\r\nReturn a JSON array of work item descriptions.\r\nExample: [\"Brick masonry laying\", \"Cement mortar for brick joints\", \"Internal cement plaster 15mm\"]\r\n\"\"\"\r\n\r\n        response = self.openai.chat.completions.create(\r\n            model=\"gpt-4o\",\r\n            messages=[{\"role\": \"user\", \"content\": prompt}],\r\n            response_format={\"type\": \"json_object\"}\r\n        )\r\n\r\n        try:\r\n            result = json.loads(response.choices[0].message.content)\r\n            return result.get('work_items', [bim_type])\r\n        except:\r\n            return [bim_type]\r\n\r\n    def estimate_element(\r\n        self,\r\n        bim_type: str,\r\n        category: str,\r\n        quantity: float,\r\n        quantity_unit: str,\r\n        phase: str = \"Construction\"\r\n    ) -> List[CostLineItem]:\r\n        \"\"\"Estimate cost for single BIM element type\"\"\"\r\n\r\n        # Decompose into work items\r\n        work_descriptions = self.decompose_bim_type(bim_type, category)\r\n\r\n        line_items = []\r\n\r\n        for work_desc in work_descriptions:\r\n            # Search CWICR for matching rate\r\n            matches = self.search_cwicr(work_desc, limit=1)\r\n\r\n            if not matches:\r\n                continue\r\n\r\n            best_match = matches[0]\r\n\r\n            # Convert quantity if units don't match\r\n            adjusted_qty = self._convert_units(\r\n                quantity, quantity_unit, best_match.unit\r\n            )\r\n\r\n            # Calculate costs\r\n            total = adjusted_qty * best_match.unit_price\r\n            labor = adjusted_qty * best_match.labor_cost\r\n            material = adjusted_qty * best_match.material_cost\r\n            equipment = adjusted_qty * best_match.equipment_cost\r\n\r\n            line_items.append(CostLineItem(\r\n                bim_type=bim_type,\r\n                work_item=best_match,\r\n                quantity=adjusted_qty,\r\n                quantity_unit=best_match.unit,\r\n                total_cost=total,\r\n                labor_cost=labor,\r\n                material_cost=material,\r\n                equipment_cost=equipment,\r\n                phase=phase,\r\n                trade=self._get_trade(category)\r\n            ))\r\n\r\n        return line_items\r\n\r\n    def estimate_from_qto(\r\n        self,\r\n        qto_data: pd.DataFrame,\r\n        type_column: str = \"Type Name\",\r\n        category_column: str = \"Category\",\r\n        quantity_column: str = \"Volume\"\r\n    ) -> List[CostLineItem]:\r\n        \"\"\"Generate estimate from QTO DataFrame\"\"\"\r\n\r\n        all_line_items = []\r\n\r\n        # Group by type\r\n        grouped = qto_data.groupby([category_column, type_column]).agg({\r\n            quantity_column: 'sum'\r\n        }).reset_index()\r\n\r\n        for _, row in grouped.iterrows():\r\n            items = self.estimate_element(\r\n                bim_type=row[type_column],\r\n                category=row[category_column],\r\n                quantity=row[quantity_column],\r\n                quantity_unit=\"m³\"  # Assume volume, adjust based on category\r\n            )\r\n            all_line_items.extend(items)\r\n\r\n        return all_line_items\r\n\r\n    def _convert_units(\r\n        self,\r\n        value: float,\r\n        from_unit: str,\r\n        to_unit: str\r\n    ) -> float:\r\n        \"\"\"Convert between units\"\"\"\r\n\r\n        # Simplified conversion - expand as needed\r\n        conversions = {\r\n            ('m³', 'm³'): 1.0,\r\n            ('m²', 'm²'): 1.0,\r\n            ('m', 'm'): 1.0,\r\n            ('ft³', 'm³'): 0.0283168,\r\n            ('ft²', 'm²'): 0.092903,\r\n            ('ft', 'm'): 0.3048,\r\n        }\r\n\r\n        key = (from_unit.lower(), to_unit.lower())\r\n        factor = conversions.get(key, 1.0)\r\n\r\n        return value * factor\r\n\r\n    def _get_trade(self, category: str) -> str:\r\n        \"\"\"Map BIM category to trade\"\"\"\r\n        trade_map = {\r\n            'Walls': 'Masonry',\r\n            'Floors': 'Concrete',\r\n            'Structural Columns': 'Concrete',\r\n            'Structural Framing': 'Steel',\r\n            'Doors': 'Carpentry',\r\n            'Windows': 'Glazing',\r\n            'Plumbing Fixtures': 'Plumbing',\r\n            'Electrical Equipment': 'Electrical',\r\n            'Mechanical Equipment': 'HVAC'\r\n        }\r\n        return trade_map.get(category, 'General')\r\n\r\n    def generate_estimate_report(\r\n        self,\r\n        line_items: List[CostLineItem],\r\n        project_name: str,\r\n        output_path: str\r\n    ) -> dict:\r\n        \"\"\"Generate comprehensive estimate report\"\"\"\r\n\r\n        # Convert to DataFrame\r\n        records = []\r\n        for item in line_items:\r\n            records.append({\r\n                'BIM Type': item.bim_type,\r\n                'Work Item': item.work_item.description,\r\n                'CWICR Code': item.work_item.cwicr_code,\r\n                'Quantity': round(item.quantity, 2),\r\n                'Unit': item.quantity_unit,\r\n                'Unit Price': round(item.work_item.unit_price, 2),\r\n                'Labor': round(item.labor_cost, 2),\r\n                'Material': round(item.material_cost, 2),\r\n                'Equipment': round(item.equipment_cost, 2),\r\n                'Total': round(item.total_cost, 2),\r\n                'Phase': item.phase,\r\n                'Trade': item.trade,\r\n                'Currency': item.work_item.currency,\r\n                'Confidence': round(item.work_item.confidence, 2)\r\n            })\r\n\r\n        df = pd.DataFrame(records)\r\n\r\n        # Calculate totals\r\n        total_cost = df['Total'].sum()\r\n        total_labor = df['Labor'].sum()\r\n        total_material = df['Material'].sum()\r\n        total_equipment = df['Equipment'].sum()\r\n\r\n        # Summary by trade\r\n        by_trade = df.groupby('Trade')['Total'].sum().sort_values(ascending=False)\r\n\r\n        # Write Excel\r\n        excel_path = f\"{output_path}/{project_name}_Estimate.xlsx\"\r\n        with pd.ExcelWriter(excel_path, engine='openpyxl') as writer:\r\n            # Summary sheet\r\n            summary_data = {\r\n                'Metric': ['Total Cost', 'Labor Cost', 'Material Cost', 'Equipment Cost'],\r\n                'Value': [total_cost, total_labor, total_material, total_equipment]\r\n            }\r\n            pd.DataFrame(summary_data).to_excel(writer, sheet_name='Summary', index=False)\r\n\r\n            # By Trade\r\n            by_trade.to_frame().to_excel(writer, sheet_name='By Trade')\r\n\r\n            # Detail\r\n            df.to_excel(writer, sheet_name='Detail', index=False)\r\n\r\n        return {\r\n            'excel_path': excel_path,\r\n            'total_cost': total_cost,\r\n            'total_labor': total_labor,\r\n            'total_material': total_material,\r\n            'total_equipment': total_equipment,\r\n            'by_trade': by_trade.to_dict(),\r\n            'line_items': len(df),\r\n            'currency': line_items[0].work_item.currency if line_items else 'USD'\r\n        }\r\n\r\n\r\n# Usage Example\r\ndef estimate_from_bim_model(\r\n    model_path: str,\r\n    qdrant_url: str,\r\n    language: str = \"EN\",\r\n    output_dir: str = \".\"\r\n) -> dict:\r\n    \"\"\"Complete BIM to cost estimation workflow\"\"\"\r\n\r\n    import subprocess\r\n    from pathlib import Path\r\n\r\n    # Step 1: Convert BIM to Excel\r\n    print(\"Converting BIM model...\")\r\n    subprocess.run([\r\n        r\"C:\\DDC\\RvtExporter.exe\",\r\n        model_path,\r\n        \"complete\", \"bbox\"\r\n    ])\r\n\r\n    xlsx_path = Path(model_path).with_suffix('.xlsx')\r\n\r\n    # Step 2: Load QTO data\r\n    print(\"Loading quantity data...\")\r\n    df = pd.read_excel(xlsx_path)\r\n\r\n    # Step 3: Initialize estimator\r\n    estimator = BIMCostEstimator(\r\n        qdrant_url=qdrant_url,\r\n        language=language\r\n    )\r\n\r\n    # Step 4: Generate estimate\r\n    print(\"Generating cost estimate...\")\r\n    line_items = estimator.estimate_from_qto(df)\r\n\r\n    # Step 5: Generate report\r\n    project_name = Path(model_path).stem\r\n    result = estimator.generate_estimate_report(\r\n        line_items=line_items,\r\n        project_name=project_name,\r\n        output_path=output_dir\r\n    )\r\n\r\n    print(f\"\\nEstimate Complete!\")\r\n    print(f\"Total Cost: {result['currency']} {result['total_cost']:,.2f}\")\r\n    print(f\"Excel Report: {result['excel_path']}\")\r\n\r\n    return result\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    result = estimate_from_bim_model(\r\n        model_path=r\"C:\\Projects\\Building.rvt\",\r\n        qdrant_url=\"https://your-qdrant-instance.io\",\r\n        language=\"DE\",\r\n        output_dir=r\"C:\\Projects\\Estimates\"\r\n    )\r\n```\r\n\r\n## n8n Workflow\r\n\r\nSee: `n8n_4_CAD_(BIM)_Cost_Estimation_Pipeline_4D_5D_with_DDC_CWICR.json`\r\n\r\n```yaml\r\nstages:\r\n  - convert: RvtExporter → XLSX\r\n  - detect_project: LLM identifies project type\r\n  - generate_phases: LLM creates construction phases\r\n  - decompose: LLM breaks types into work items\r\n  - vector_search: Qdrant finds CWICR matches\r\n  - calculate: Qty × Unit Price\r\n  - validate: CTO review\r\n  - report: HTML + Excel output\r\n```\r\n\r\n## Output Example\r\n\r\n```\r\n╔══════════════════════════════════════════════════════════════╗\r\n║                    COST ESTIMATE SUMMARY                      ║\r\n║   Project: Office Building Berlin                             ║\r\n║   Date: 2026-01-24                                           ║\r\n╠══════════════════════════════════════════════════════════════╣\r\n\r\nTOTAL PROJECT COST:                    EUR 4,523,678.00\r\n───────────────────────────────────────────────────────────────\r\n  Labor:                               EUR 1,847,234.00 (41%)\r\n  Materials:                           EUR 2,312,456.00 (51%)\r\n  Equipment:                           EUR   363,988.00 ( 8%)\r\n\r\nBY TRADE\r\n───────────────────────────────────────────────────────────────\r\n  Concrete:                            EUR 1,234,567.00 (27%)\r\n  Masonry:                             EUR   876,543.00 (19%)\r\n  Steel Structure:                     EUR   654,321.00 (14%)\r\n  MEP:                                 EUR   543,210.00 (12%)\r\n  Finishes:                            EUR   432,109.00 (10%)\r\n  Other:                               EUR   782,928.00 (18%)\r\n\r\nCONFIDENCE ANALYSIS\r\n───────────────────────────────────────────────────────────────\r\n  High (>0.85):                        78%\r\n  Medium (0.70-0.85):                  18%\r\n  Low (<0.70):                          4%\r\n\r\n╚══════════════════════════════════════════════════════════════╝\r\n```\r\n\r\n## Resources\r\n\r\n- **CWICR Repository**: https://github.com/datadrivenconstruction/OpenConstructionEstimate-DDC-CWICR\r\n- **Live Demo**: https://openconstructionestimate.com\r\n- **Qdrant**: https://qdrant.tech\r\n\r\n---\r\n\r\n*\"Resource-based costing separates physical quantities from volatile prices, enabling transparent and auditable estimates.\"*\n\nFile v2.1.0:_meta.json\n\n{\n  \"ownerId\": \"kn75fhjxn1jz5xbgd9ggj0nrtd80q1dz\",\n  \"slug\": \"bim-cost-estimation-cwicr\",\n  \"version\": \"2.1.0\",\n  \"publishedAt\": 1771016910955\n}\n\nFile v2.1.0:instructions.md\n\nYou are a BIM-to-cost estimation assistant powered by the DDC CWICR database (55,719 work items across 9 languages). You automate the full pipeline from BIM model to cost estimate using AI classification and vector search.\n\nWhen the user asks to estimate costs from a BIM model:\n1. Guide them through the pipeline stages: BIM export -> QTO -> AI classification -> vector search -> cost calculation\n2. Explain the 10-stage pipeline (collect, detect project, generate phases, assign elements, decompose work, vector search, unit mapping, cost calculation, validation, aggregation)\n3. Help configure: language/region (EN, DE, RU, ES, FR, AR, HI, PT, ZH), Qdrant connection, OpenAI API for embeddings\n4. Present results by trade, phase, and element type\n\nWhen the user asks about CWICR database:\n1. Explain the database structure: 55,719 work items, 27,672 resources, 85 fields per item\n2. Help with vector search queries using text-embedding-3-large (3072 dimensions)\n3. Show matching results with confidence scores\n\n## Input Format\n- BIM model path (.rvt or .ifc) or pre-exported QTO data (.xlsx)\n- Target language/region for pricing\n- Qdrant URL and API credentials (environment variables)\n\n## Output Format\n- Cost estimate by trade (Concrete, Masonry, Steel, MEP, etc.)\n- Cost breakdown: labor, material, equipment percentages\n- Confidence analysis (high >0.85, medium 0.70-0.85, low <0.70)\n- Excel report with Summary, By Trade, and Detail sheets\n\n## Pipeline Stages\n| Stage | Description |\n|-------|-------------|\n| 0 | Collect BIM data from Revit/IFC |\n| 1-3 | AI detects project type, generates phases, assigns elements |\n| 4 | AI decomposes element types into work items |\n| 5 | Vector search matches work items to CWICR rates |\n| 6-7 | Unit mapping and cost calculation |\n| 8-9 | Aggregation and report generation |\n\n## Constraints\n- Network permission required for Qdrant vector database and OpenAI embeddings API\n- Filesystem permission required for BIM model reading and Excel export\n- subprocess.run() is used solely for invoking the DDC RvtExporter CAD conversion tool\n- All API keys must be loaded from environment variables, never hardcoded\n\nFile v2.1.0:claw.json\n\n{\n  \"name\": \"bim-cost-estimation-cwicr\",\n  \"version\": \"2.0.0\",\n  \"description\": \"Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing.\",\n  \"author\": \"datadrivenconstruction\",\n  \"license\": \"MIT\",\n  \"permissions\": [\"filesystem\", \"network\"],\n  \"entry\": \"instructions.md\",\n  \"tags\": [\"construction\", \"BIM\", \"estimation\", \"CWICR\", \"vector-search\", \"AI\", \"cost-management\"],\n  \"models\": [\"claude-*\", \"gpt-*\"],\n  \"minOpenClawVersion\": \"0.8.0\"\n}\n\nArchive v2.0.0: 4 files, 7895 bytes\n\nFiles: claw.json (531b), instructions.md (2154b), SKILL.md (20927b), _meta.json (144b)\n\nFile v2.0.0:SKILL.md\n\n---\r\nname: \"bim-cost-estimation-cwicr\"\r\ndescription: \"Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing.\"\r\n---\r\n\r\n# BIM Cost Estimation with DDC CWICR\r\n\r\nGenerate accurate cost estimates from BIM models using AI classification and the DDC CWICR construction cost database.\r\n\r\n## Business Case\r\n\r\n**Problem**: Traditional cost estimation:\r\n- Manual and time-consuming (weeks for detailed estimate)\r\n- Subjective and inconsistent between estimators\r\n- Requires specialized knowledge\r\n- Difficult to update with design changes\r\n\r\n**Solution**: Automated BIM-to-cost pipeline:\r\n- Extract quantities directly from model\r\n- AI classifies elements to work items\r\n- Vector search finds matching prices in CWICR\r\n- Complete estimate in hours, not weeks\r\n\r\n**ROI**: 80% reduction in estimation time, consistent methodology\r\n\r\n## System Architecture\r\n\r\n```\r\n┌──────────────────────────────────────────────────────────────────────────┐\r\n│                  BIM TO COST ESTIMATION PIPELINE                          │\r\n├──────────────────────────────────────────────────────────────────────────┤\r\n│                                                                           │\r\n│   ┌─────────┐     ┌─────────┐     ┌─────────┐     ┌─────────────────┐   │\r\n│   │ BIM     │     │ DDC     │     │ AI      │     │ DDC CWICR       │   │\r\n│   │ Model   │────►│Converter│────►│ LLM     │────►│ Vector Search   │   │\r\n│   │.rvt/.ifc│     │         │     │         │     │ (Qdrant)        │   │\r\n│   └─────────┘     └─────────┘     └─────────┘     └─────────────────┘   │\r\n│                        │              │                    │             │\r\n│                        ▼              ▼                    ▼             │\r\n│                   ┌─────────┐    ┌─────────┐         ┌──────────┐       │\r\n│                   │ .xlsx   │    │ Work    │         │ Matched  │       │\r\n│                   │ QTO     │    │ Items   │         │ Rates    │       │\r\n│                   └─────────┘    └─────────┘         └──────────┘       │\r\n│                        │              │                    │             │\r\n│                        └──────────────┼────────────────────┘             │\r\n│                                       ▼                                  │\r\n│                              ┌─────────────────┐                        │\r\n│                              │ COST ESTIMATE   │                        │\r\n│                              │                 │                        │\r\n│                              │ • By element    │                        │\r\n│                              │ • By trade      │                        │\r\n│                              │ • By phase      │                        │\r\n│                              │ • Resources     │                        │\r\n│                              └─────────────────┘                        │\r\n│                                                                           │\r\n└──────────────────────────────────────────────────────────────────────────┘\r\n```\r\n\r\n## DDC CWICR Database\r\n\r\n```yaml\r\nDatabase Overview:\r\n  work_items: 55,719\r\n  resources: 27,672\r\n  languages: 9 (AR, DE, EN, ES, FR, HI, PT, RU, ZH)\r\n  fields_per_item: 85\r\n  embedding_model: text-embedding-3-large (3072d)\r\n  vector_db: Qdrant\r\n\r\nCollections:\r\n  - ddc_cwicr_ar  # Arabic (Dubai prices)\r\n  - ddc_cwicr_de  # German (Berlin prices)\r\n  - ddc_cwicr_en  # English (Toronto prices)\r\n  - ddc_cwicr_es  # Spanish (Barcelona prices)\r\n  - ddc_cwicr_fr  # French (Paris prices)\r\n  - ddc_cwicr_hi  # Hindi (Mumbai prices)\r\n  - ddc_cwicr_pt  # Portuguese (São Paulo prices)\r\n  - ddc_cwicr_ru  # Russian (St. Petersburg prices)\r\n  - ddc_cwicr_zh  # Chinese (Shanghai prices)\r\n```\r\n\r\n## Pipeline Stages\r\n\r\n| Stage | Name | Description |\r\n|-------|------|-------------|\r\n| 0 | Collect BIM Data | Extract elements from Revit/IFC |\r\n| 1 | Project Detection | AI identifies project type |\r\n| 2 | Phase Generation | AI creates construction phases |\r\n| 3 | Element Assignment | AI maps types to phases |\r\n| 4 | Work Decomposition | AI breaks types into work items |\r\n| 5 | Vector Search | Find matching rates in CWICR |\r\n| 6 | Unit Mapping | Convert BIM units to rate units |\r\n| 7 | Cost Calculation | Qty × Unit Price |\r\n| 7.5 | Validation | CTO review for completeness |\r\n| 8 | Aggregation | Sum by phases and categories |\r\n| 9 | Report Generation | HTML and Excel outputs |\r\n\r\n## Python Implementation\r\n\r\n```python\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom qdrant_client import QdrantClient\r\nfrom qdrant_client.models import Filter, FieldCondition, MatchValue\r\nfrom openai import OpenAI\r\nfrom typing import List, Dict, Optional\r\nfrom dataclasses import dataclass\r\nimport json\r\n\r\n@dataclass\r\nclass WorkItem:\r\n    \"\"\"Matched work item from CWICR\"\"\"\r\n    cwicr_code: str\r\n    description: str\r\n    unit: str\r\n    unit_price: float\r\n    labor_cost: float\r\n    material_cost: float\r\n    equipment_cost: float\r\n    productivity: float  # units per hour\r\n    currency: str\r\n    confidence: float\r\n\r\n@dataclass\r\nclass CostLineItem:\r\n    \"\"\"Single line item in estimate\"\"\"\r\n    bim_type: str\r\n    work_item: WorkItem\r\n    quantity: float\r\n    quantity_unit: str\r\n    total_cost: float\r\n    labor_cost: float\r\n    material_cost: float\r\n    equipment_cost: float\r\n    phase: str\r\n    trade: str\r\n\r\n\r\nclass BIMCostEstimator:\r\n    \"\"\"BIM to cost estimation using DDC CWICR\"\"\"\r\n\r\n    def __init__(\r\n        self,\r\n        qdrant_url: str,\r\n        qdrant_api_key: str = None,\r\n        openai_api_key: str = None,\r\n        language: str = \"EN\"\r\n    ):\r\n        self.qdrant = QdrantClient(url=qdrant_url, api_key=qdrant_api_key)\r\n        self.openai = OpenAI(api_key=openai_api_key)\r\n        self.language = language\r\n        self.collection = f\"ddc_cwicr_{language.lower()}\"\r\n\r\n    def get_embedding(self, text: str) -> List[float]:\r\n        \"\"\"Generate embedding for text\"\"\"\r\n        response = self.openai.embeddings.create(\r\n            model=\"text-embedding-3-large\",\r\n            input=text,\r\n            dimensions=3072\r\n        )\r\n        return response.data[0].embedding\r\n\r\n    def search_cwicr(\r\n        self,\r\n        query: str,\r\n        limit: int = 5,\r\n        category_filter: str = None\r\n    ) -> List[WorkItem]:\r\n        \"\"\"Search CWICR database for matching work items\"\"\"\r\n\r\n        # Get embedding\r\n        query_vector = self.get_embedding(query)\r\n\r\n        # Build filter if category specified\r\n        query_filter = None\r\n        if category_filter:\r\n            query_filter = Filter(\r\n                must=[\r\n                    FieldCondition(\r\n                        key=\"category\",\r\n                        match=MatchValue(value=category_filter)\r\n                    )\r\n                ]\r\n            )\r\n\r\n        # Search\r\n        results = self.qdrant.search(\r\n            collection_name=self.collection,\r\n            query_vector=query_vector,\r\n            query_filter=query_filter,\r\n            limit=limit\r\n        )\r\n\r\n        # Parse results\r\n        work_items = []\r\n        for r in results:\r\n            payload = r.payload\r\n            work_items.append(WorkItem(\r\n                cwicr_code=payload.get('code', ''),\r\n                description=payload.get('description', ''),\r\n                unit=payload.get('unit', ''),\r\n                unit_price=float(payload.get('unit_price', 0)),\r\n                labor_cost=float(payload.get('labor_cost', 0)),\r\n                material_cost=float(payload.get('material_cost', 0)),\r\n                equipment_cost=float(payload.get('equipment_cost', 0)),\r\n                productivity=float(payload.get('productivity', 1)),\r\n                currency=payload.get('currency', 'USD'),\r\n                confidence=r.score\r\n            ))\r\n\r\n        return work_items\r\n\r\n    def decompose_bim_type(\r\n        self,\r\n        bim_type: str,\r\n        category: str\r\n    ) -> List[str]:\r\n        \"\"\"Use LLM to decompose BIM type into work items\"\"\"\r\n\r\n        prompt = f\"\"\"\r\nDecompose this BIM element type into construction work items:\r\n\r\nBIM Type: {bim_type}\r\nCategory: {category}\r\n\r\nList the individual work activities needed to construct this element.\r\nFor example, \"Brick Wall 240mm\" decomposes into:\r\n- Masonry: Brick laying\r\n- Mortar: Cement mortar for joints\r\n- Plaster: Internal plaster finish\r\n- Paint: Wall painting\r\n\r\nReturn a JSON array of work item descriptions.\r\nExample: [\"Brick masonry laying\", \"Cement mortar for brick joints\", \"Internal cement plaster 15mm\"]\r\n\"\"\"\r\n\r\n        response = self.openai.chat.completions.create(\r\n            model=\"gpt-4o\",\r\n            messages=[{\"role\": \"user\", \"content\": prompt}],\r\n            response_format={\"type\": \"json_object\"}\r\n        )\r\n\r\n        try:\r\n            result = json.loads(response.choices[0].message.content)\r\n            return result.get('work_items', [bim_type])\r\n        except:\r\n            return [bim_type]\r\n\r\n    def estimate_element(\r\n        self,\r\n        bim_type: str,\r\n        category: str,\r\n        quantity: float,\r\n        quantity_unit: str,\r\n        phase: str = \"Construction\"\r\n    ) -> List[CostLineItem]:\r\n        \"\"\"Estimate cost for single BIM element type\"\"\"\r\n\r\n        # Decompose into work items\r\n        work_descriptions = self.decompose_bim_type(bim_type, category)\r\n\r\n        line_items = []\r\n\r\n        for work_desc in work_descriptions:\r\n            # Search CWICR for matching rate\r\n            matches = self.search_cwicr(work_desc, limit=1)\r\n\r\n            if not matches:\r\n                continue\r\n\r\n            best_match = matches[0]\r\n\r\n            # Convert quantity if units don't match\r\n            adjusted_qty = self._convert_units(\r\n                quantity, quantity_unit, best_match.unit\r\n            )\r\n\r\n            # Calculate costs\r\n            total = adjusted_qty * best_match.unit_price\r\n            labor = adjusted_qty * best_match.labor_cost\r\n            material = adjusted_qty * best_match.material_cost\r\n            equipment = adjusted_qty * best_match.equipment_cost\r\n\r\n            line_items.append(CostLineItem(\r\n                bim_type=bim_type,\r\n                work_item=best_match,\r\n                quantity=adjusted_qty,\r\n                quantity_unit=best_match.unit,\r\n                total_cost=total,\r\n                labor_cost=labor,\r\n                material_cost=material,\r\n                equipment_cost=equipment,\r\n                phase=phase,\r\n                trade=self._get_trade(category)\r\n            ))\r\n\r\n        return line_items\r\n\r\n    def estimate_from_qto(\r\n        self,\r\n        qto_data: pd.DataFrame,\r\n        type_column: str = \"Type Name\",\r\n        category_column: str = \"Category\",\r\n        quantity_column: str = \"Volume\"\r\n    ) -> List[CostLineItem]:\r\n        \"\"\"Generate estimate from QTO DataFrame\"\"\"\r\n\r\n        all_line_items = []\r\n\r\n        # Group by type\r\n        grouped = qto_data.groupby([category_column, type_column]).agg({\r\n            quantity_column: 'sum'\r\n        }).reset_index()\r\n\r\n        for _, row in grouped.iterrows():\r\n            items = self.estimate_element(\r\n                bim_type=row[type_column],\r\n                category=row[category_column],\r\n                quantity=row[quantity_column],\r\n                quantity_unit=\"m³\"  # Assume volume, adjust based on category\r\n            )\r\n            all_line_items.extend(items)\r\n\r\n        return all_line_items\r\n\r\n    def _convert_units(\r\n        self,\r\n        value: float,\r\n        from_unit: str,\r\n        to_unit: str\r\n    ) -> float:\r\n        \"\"\"Convert between units\"\"\"\r\n\r\n        # Simplified conversion - expand as needed\r\n        conversions = {\r\n            ('m³', 'm³'): 1.0,\r\n            ('m²', 'm²'): 1.0,\r\n            ('m', 'm'): 1.0,\r\n            ('ft³', 'm³'): 0.0283168,\r\n            ('ft²', 'm²'): 0.092903,\r\n            ('ft', 'm'): 0.3048,\r\n        }\r\n\r\n        key = (from_unit.lower(), to_unit.lower())\r\n        factor = conversions.get(key, 1.0)\r\n\r\n        return value * factor\r\n\r\n    def _get_trade(self, category: str) -> str:\r\n        \"\"\"Map BIM category to trade\"\"\"\r\n        trade_map = {\r\n            'Walls': 'Masonry',\r\n            'Floors': 'Concrete',\r\n            'Structural Columns': 'Concrete',\r\n            'Structural Framing': 'Steel',\r\n            'Doors': 'Carpentry',\r\n            'Windows': 'Glazing',\r\n            'Plumbing Fixtures': 'Plumbing',\r\n            'Electrical Equipment': 'Electrical',\r\n            'Mechanical Equipment': 'HVAC'\r\n        }\r\n        return trade_map.get(category, 'General')\r\n\r\n    def generate_estimate_report(\r\n        self,\r\n        line_items: List[CostLineItem],\r\n        project_name: str,\r\n        output_path: str\r\n    ) -> dict:\r\n        \"\"\"Generate comprehensive estimate report\"\"\"\r\n\r\n        # Convert to DataFrame\r\n        records = []\r\n        for item in line_items:\r\n            records.append({\r\n                'BIM Type': item.bim_type,\r\n                'Work Item': item.work_item.description,\r\n                'CWICR Code': item.work_item.cwicr_code,\r\n                'Quantity': round(item.quantity, 2),\r\n                'Unit': item.quantity_unit,\r\n                'Unit Price': round(item.work_item.unit_price, 2),\r\n                'Labor': round(item.labor_cost, 2),\r\n                'Material': round(item.material_cost, 2),\r\n                'Equipment': round(item.equipment_cost, 2),\r\n                'Total': round(item.total_cost, 2),\r\n                'Phase': item.phase,\r\n                'Trade': item.trade,\r\n                'Currency': item.work_item.currency,\r\n                'Confidence': round(item.work_item.confidence, 2)\r\n            })\r\n\r\n        df = pd.DataFrame(records)\r\n\r\n        # Calculate totals\r\n        total_cost = df['Total'].sum()\r\n        total_labor = df['Labor'].sum()\r\n        total_material = df['Material'].sum()\r\n        total_equipment = df['Equipment'].sum()\r\n\r\n        # Summary by trade\r\n        by_trade = df.groupby('Trade')['Total'].sum().sort_values(ascending=False)\r\n\r\n        # Write Excel\r\n        excel_path = f\"{output_path}/{project_name}_Estimate.xlsx\"\r\n        with pd.ExcelWriter(excel_path, engine='openpyxl') as writer:\r\n            # Summary sheet\r\n            summary_data = {\r\n                'Metric': ['Total Cost', 'Labor Cost', 'Material Cost', 'Equipment Cost'],\r\n                'Value': [total_cost, total_labor, total_material, total_equipment]\r\n            }\r\n            pd.DataFrame(summary_data).to_excel(writer, sheet_name='Summary', index=False)\r\n\r\n            # By Trade\r\n            by_trade.to_frame().to_excel(writer, sheet_name='By Trade')\r\n\r\n            # Detail\r\n            df.to_excel(writer, sheet_name='Detail', index=False)\r\n\r\n        return {\r\n            'excel_path': excel_path,\r\n            'total_cost': total_cost,\r\n            'total_labor': total_labor,\r\n            'total_material': total_material,\r\n            'total_equipment': total_equipment,\r\n            'by_trade': by_trade.to_dict(),\r\n            'line_items': len(df),\r\n            'currency': line_items[0].work_item.currency if line_items else 'USD'\r\n        }\r\n\r\n\r\n# Usage Example\r\ndef estimate_from_bim_model(\r\n    model_path: str,\r\n    qdrant_url: str,\r\n    language: str = \"EN\",\r\n    output_dir: str = \".\"\r\n) -> dict:\r\n    \"\"\"Complete BIM to cost estimation workflow\"\"\"\r\n\r\n    import subprocess\r\n    from pathlib import Path\r\n\r\n    # Step 1: Convert BIM to Excel\r\n    print(\"Converting BIM model...\")\r\n    subprocess.run([\r\n        r\"C:\\DDC\\RvtExporter.exe\",\r\n        model_path,\r\n        \"complete\", \"bbox\"\r\n    ])\r\n\r\n    xlsx_path = Path(model_path).with_suffix('.xlsx')\r\n\r\n    # Step 2: Load QTO data\r\n    print(\"Loading quantity data...\")\r\n    df = pd.read_excel(xlsx_path)\r\n\r\n    # Step 3: Initialize estimator\r\n    estimator = BIMCostEstimator(\r\n        qdrant_url=qdrant_url,\r\n        language=language\r\n    )\r\n\r\n    # Step 4: Generate estimate\r\n    print(\"Generating cost estimate...\")\r\n    line_items = estimator.estimate_from_qto(df)\r\n\r\n    # Step 5: Generate report\r\n    project_name = Path(model_path).stem\r\n    result = estimator.generate_estimate_report(\r\n        line_items=line_items,\r\n        project_name=project_name,\r\n        output_path=output_dir\r\n    )\r\n\r\n    print(f\"\\nEstimate Complete!\")\r\n    print(f\"Total Cost: {result['currency']} {result['total_cost']:,.2f}\")\r\n    print(f\"Excel Report: {result['excel_path']}\")\r\n\r\n    return result\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    result = estimate_from_bim_model(\r\n        model_path=r\"C:\\Projects\\Building.rvt\",\r\n        qdrant_url=\"https://your-qdrant-instance.io\",\r\n        language=\"DE\",\r\n        output_dir=r\"C:\\Projects\\Estimates\"\r\n    )\r\n```\r\n\r\n## n8n Workflow\r\n\r\nSee: `n8n_4_CAD_(BIM)_Cost_Estimation_Pipeline_4D_5D_with_DDC_CWICR.json`\r\n\r\n```yaml\r\nstages:\r\n  - convert: RvtExporter → XLSX\r\n  - detect_project: LLM identifies project type\r\n  - generate_phases: LLM creates construction phases\r\n  - decompose: LLM breaks types into work items\r\n  - vector_search: Qdrant finds CWICR matches\r\n  - calculate: Qty × Unit Price\r\n  - validate: CTO review\r\n  - report: HTML + Excel output\r\n```\r\n\r\n## Output Example\r\n\r\n```\r\n╔══════════════════════════════════════════════════════════════╗\r\n║                    COST ESTIMATE SUMMARY                      ║\r\n║   Project: Office Building Berlin                             ║\r\n║   Date: 2026-01-24                                           ║\r\n╠══════════════════════════════════════════════════════════════╣\r\n\r\nTOTAL PROJECT COST:                    EUR 4,523,678.00\r\n───────────────────────────────────────────────────────────────\r\n  Labor:                               EUR 1,847,234.00 (41%)\r\n  Materials:                           EUR 2,312,456.00 (51%)\r\n  Equipment:                           EUR   363,988.00 ( 8%)\r\n\r\nBY TRADE\r\n───────────────────────────────────────────────────────────────\r\n  Concrete:                            EUR 1,234,567.00 (27%)\r\n  Masonry:                             EUR   876,543.00 (19%)\r\n  Steel Structure:                     EUR   654,321.00 (14%)\r\n  MEP:                                 EUR   543,210.00 (12%)\r\n  Finishes:                            EUR   432,109.00 (10%)\r\n  Other:                               EUR   782,928.00 (18%)\r\n\r\nCONFIDENCE ANALYSIS\r\n───────────────────────────────────────────────────────────────\r\n  High (>0.85):                        78%\r\n  Medium (0.70-0.85):                  18%\r\n  Low (<0.70):                          4%\r\n\r\n╚══════════════════════════════════════════════════════════════╝\r\n```\r\n\r\n## Resources\r\n\r\n- **CWICR Repository**: https://github.com/datadrivenconstruction/OpenConstructionEstimate-DDC-CWICR\r\n- **Live Demo**: https://openconstructionestimate.com\r\n- **Qdrant**: https://qdrant.tech\r\n\r\n---\r\n\r\n*\"Resource-based costing separates physical quantities from volatile prices, enabling transparent and auditable estimates.\"*\n\nFile v2.0.0:_meta.json\n\n{\n  \"ownerId\": \"kn75fhjxn1jz5xbgd9ggj0nrtd80q1dz\",\n  \"slug\": \"bim-cost-estimation-cwicr\",\n  \"version\": \"2.0.0\",\n  \"publishedAt\": 1770996173595\n}\n\nFile v2.0.0:instructions.md\n\nYou are a BIM-to-cost estimation assistant powered by the DDC CWICR database (55,719 work items across 9 languages). You automate the full pipeline from BIM model to cost estimate using AI classification and vector search.\n\nWhen the user asks to estimate costs from a BIM model:\n1. Guide them through the pipeline stages: BIM export -> QTO -> AI classification -> vector search -> cost calculation\n2. Explain the 10-stage pipeline (collect, detect project, generate phases, assign elements, decompose work, vector search, unit mapping, cost calculation, validation, aggregation)\n3. Help configure: language/region (EN, DE, RU, ES, FR, AR, HI, PT, ZH), Qdrant connection, OpenAI API for embeddings\n4. Present results by trade, phase, and element type\n\nWhen the user asks about CWICR database:\n1. Explain the database structure: 55,719 work items, 27,672 resources, 85 fields per item\n2. Help with vector search queries using text-embedding-3-large (3072 dimensions)\n3. Show matching results with confidence scores\n\n## Input Format\n- BIM model path (.rvt or .ifc) or pre-exported QTO data (.xlsx)\n- Target language/region for pricing\n- Qdrant URL and API credentials (environment variables)\n\n## Output Format\n- Cost estimate by trade (Concrete, Masonry, Steel, MEP, etc.)\n- Cost breakdown: labor, material, equipment percentages\n- Confidence analysis (high >0.85, medium 0.70-0.85, low <0.70)\n- Excel report with Summary, By Trade, and Detail sheets\n\n## Pipeline Stages\n| Stage | Description |\n|-------|-------------|\n| 0 | Collect BIM data from Revit/IFC |\n| 1-3 | AI detects project type, generates phases, assigns elements |\n| 4 | AI decomposes element types into work items |\n| 5 | Vector search matches work items to CWICR rates |\n| 6-7 | Unit mapping and cost calculation |\n| 8-9 | Aggregation and report generation |\n\n## Constraints\n- Network permission required for Qdrant vector database and OpenAI embeddings API\n- Filesystem permission required for BIM model reading and Excel export\n- subprocess.run() is used solely for invoking the DDC RvtExporter CAD conversion tool\n- All API keys must be loaded from environment variables, never hardcoded\n\nFile v2.0.0:claw.json\n\n{\n  \"name\": \"bim-cost-estimation-cwicr\",\n  \"version\": \"2.0.0\",\n  \"description\": \"Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing.\",\n  \"author\": \"datadrivenconstruction\",\n  \"license\": \"MIT\",\n  \"permissions\": [\"filesystem\", \"network\"],\n  \"entry\": \"instructions.md\",\n  \"tags\": [\"construction\", \"BIM\", \"estimation\", \"CWICR\", \"vector-search\", \"AI\", \"cost-management\"],\n  \"models\": [\"claude-*\", \"gpt-*\"],\n  \"minOpenClawVersion\": \"0.8.0\"\n}\n\nArchive v1.0.0: 2 files, 6267 bytes\n\nFiles: SKILL.md (20970b), _meta.json (144b)\n\nFile v1.0.0:SKILL.md\n\n---\r\nslug: \"bim-cost-estimation-cwicr\"\r\ndisplay_name: \"BIM Cost Estimation CWICR\"\r\ndescription: \"Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing.\"\r\n---\r\n\r\n# BIM Cost Estimation with DDC CWICR\r\n\r\nGenerate accurate cost estimates from BIM models using AI classification and the DDC CWICR construction cost database.\r\n\r\n## Business Case\r\n\r\n**Problem**: Traditional cost estimation:\r\n- Manual and time-consuming (weeks for detailed estimate)\r\n- Subjective and inconsistent between estimators\r\n- Requires specialized knowledge\r\n- Difficult to update with design changes\r\n\r\n**Solution**: Automated BIM-to-cost pipeline:\r\n- Extract quantities directly from model\r\n- AI classifies elements to work items\r\n- Vector search finds matching prices in CWICR\r\n- Complete estimate in hours, not weeks\r\n\r\n**ROI**: 80% reduction in estimation time, consistent methodology\r\n\r\n## System Architecture\r\n\r\n```\r\n┌──────────────────────────────────────────────────────────────────────────┐\r\n│                  BIM TO COST ESTIMATION PIPELINE                          │\r\n├──────────────────────────────────────────────────────────────────────────┤\r\n│                                                                           │\r\n│   ┌─────────┐     ┌─────────┐     ┌─────────┐     ┌─────────────────┐   │\r\n│   │ BIM     │     │ DDC     │     │ AI      │     │ DDC CWICR       │   │\r\n│   │ Model   │────►│Converter│────►│ LLM     │────►│ Vector Search   │   │\r\n│   │.rvt/.ifc│     │         │     │         │     │ (Qdrant)        │   │\r\n│   └─────────┘     └─────────┘     └─────────┘     └─────────────────┘   │\r\n│                        │              │                    │             │\r\n│                        ▼              ▼                    ▼             │\r\n│                   ┌─────────┐    ┌─────────┐         ┌──────────┐       │\r\n│                   │ .xlsx   │    │ Work    │         │ Matched  │       │\r\n│                   │ QTO     │    │ Items   │         │ Rates    │       │\r\n│                   └─────────┘    └─────────┘         └──────────┘       │\r\n│                        │              │                    │             │\r\n│                        └──────────────┼────────────────────┘             │\r\n│                                       ▼                                  │\r\n│                              ┌─────────────────┐                        │\r\n│                              │ COST ESTIMATE   │                        │\r\n│                              │                 │                        │\r\n│                              │ • By element    │                        │\r\n│                              │ • By trade      │                        │\r\n│                              │ • By phase      │                        │\r\n│                              │ • Resources     │                        │\r\n│                              └─────────────────┘                        │\r\n│                                                                           │\r\n└──────────────────────────────────────────────────────────────────────────┘\r\n```\r\n\r\n## DDC CWICR Database\r\n\r\n```yaml\r\nDatabase Overview:\r\n  work_items: 55,719\r\n  resources: 27,672\r\n  languages: 9 (AR, DE, EN, ES, FR, HI, PT, RU, ZH)\r\n  fields_per_item: 85\r\n  embedding_model: text-embedding-3-large (3072d)\r\n  vector_db: Qdrant\r\n\r\nCollections:\r\n  - ddc_cwicr_ar  # Arabic (Dubai prices)\r\n  - ddc_cwicr_de  # German (Berlin prices)\r\n  - ddc_cwicr_en  # English (Toronto prices)\r\n  - ddc_cwicr_es  # Spanish (Barcelona prices)\r\n  - ddc_cwicr_fr  # French (Paris prices)\r\n  - ddc_cwicr_hi  # Hindi (Mumbai prices)\r\n  - ddc_cwicr_pt  # Portuguese (São Paulo prices)\r\n  - ddc_cwicr_ru  # Russian (St. Petersburg prices)\r\n  - ddc_cwicr_zh  # Chinese (Shanghai prices)\r\n```\r\n\r\n## Pipeline Stages\r\n\r\n| Stage | Name | Description |\r\n|-------|------|-------------|\r\n| 0 | Collect BIM Data | Extract elements from Revit/IFC |\r\n| 1 | Project Detection | AI identifies project type |\r\n| 2 | Phase Generation | AI creates construction phases |\r\n| 3 | Element Assignment | AI maps types to phases |\r\n| 4 | Work Decomposition | AI breaks types into work items |\r\n| 5 | Vector Search | Find matching rates in CWICR |\r\n| 6 | Unit Mapping | Convert BIM units to rate units |\r\n| 7 | Cost Calculation | Qty × Unit Price |\r\n| 7.5 | Validation | CTO review for completeness |\r\n| 8 | Aggregation | Sum by phases and categories |\r\n| 9 | Report Generation | HTML and Excel outputs |\r\n\r\n## Python Implementation\r\n\r\n```python\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom qdrant_client import QdrantClient\r\nfrom qdrant_client.models import Filter, FieldCondition, MatchValue\r\nfrom openai import OpenAI\r\nfrom typing import List, Dict, Optional\r\nfrom dataclasses import dataclass\r\nimport json\r\n\r\n@dataclass\r\nclass WorkItem:\r\n    \"\"\"Matched work item from CWICR\"\"\"\r\n    cwicr_code: str\r\n    description: str\r\n    unit: str\r\n    unit_price: float\r\n    labor_cost: float\r\n    material_cost: float\r\n    equipment_cost: float\r\n    productivity: float  # units per hour\r\n    currency: str\r\n    confidence: float\r\n\r\n@dataclass\r\nclass CostLineItem:\r\n    \"\"\"Single line item in estimate\"\"\"\r\n    bim_type: str\r\n    work_item: WorkItem\r\n    quantity: float\r\n    quantity_unit: str\r\n    total_cost: float\r\n    labor_cost: float\r\n    material_cost: float\r\n    equipment_cost: float\r\n    phase: str\r\n    trade: str\r\n\r\n\r\nclass BIMCostEstimator:\r\n    \"\"\"BIM to cost estimation using DDC CWICR\"\"\"\r\n\r\n    def __init__(\r\n        self,\r\n        qdrant_url: str,\r\n        qdrant_api_key: str = None,\r\n        openai_api_key: str = None,\r\n        language: str = \"EN\"\r\n    ):\r\n        self.qdrant = QdrantClient(url=qdrant_url, api_key=qdrant_api_key)\r\n        self.openai = OpenAI(api_key=openai_api_key)\r\n        self.language = language\r\n        self.collection = f\"ddc_cwicr_{language.lower()}\"\r\n\r\n    def get_embedding(self, text: str) -> List[float]:\r\n        \"\"\"Generate embedding for text\"\"\"\r\n        response = self.openai.embeddings.create(\r\n            model=\"text-embedding-3-large\",\r\n            input=text,\r\n            dimensions=3072\r\n        )\r\n        return response.data[0].embedding\r\n\r\n    def search_cwicr(\r\n        self,\r\n        query: str,\r\n        limit: int = 5,\r\n        category_filter: str = None\r\n    ) -> List[WorkItem]:\r\n        \"\"\"Search CWICR database for matching work items\"\"\"\r\n\r\n        # Get embedding\r\n        query_vector = self.get_embedding(query)\r\n\r\n        # Build filter if category specified\r\n        query_filter = None\r\n        if category_filter:\r\n            query_filter = Filter(\r\n                must=[\r\n                    FieldCondition(\r\n                        key=\"category\",\r\n                        match=MatchValue(value=category_filter)\r\n                    )\r\n                ]\r\n            )\r\n\r\n        # Search\r\n        results = self.qdrant.search(\r\n            collection_name=self.collection,\r\n            query_vector=query_vector,\r\n            query_filter=query_filter,\r\n            limit=limit\r\n        )\r\n\r\n        # Parse results\r\n        work_items = []\r\n        for r in results:\r\n            payload = r.payload\r\n            work_items.append(WorkItem(\r\n                cwicr_code=payload.get('code', ''),\r\n                description=payload.get('description', ''),\r\n                unit=payload.get('unit', ''),\r\n                unit_price=float(payload.get('unit_price', 0)),\r\n                labor_cost=float(payload.get('labor_cost', 0)),\r\n                material_cost=float(payload.get('material_cost', 0)),\r\n                equipment_cost=float(payload.get('equipment_cost', 0)),\r\n                productivity=float(payload.get('productivity', 1)),\r\n                currency=payload.get('currency', 'USD'),\r\n                confidence=r.score\r\n            ))\r\n\r\n        return work_items\r\n\r\n    def decompose_bim_type(\r\n        self,\r\n        bim_type: str,\r\n        category: str\r\n    ) -> List[str]:\r\n        \"\"\"Use LLM to decompose BIM type into work items\"\"\"\r\n\r\n        prompt = f\"\"\"\r\nDecompose this BIM element type into construction work items:\r\n\r\nBIM Type: {bim_type}\r\nCategory: {category}\r\n\r\nList the individual work activities needed to construct this element.\r\nFor example, \"Brick Wall 240mm\" decomposes into:\r\n- Masonry: Brick laying\r\n- Mortar: Cement mortar for joints\r\n- Plaster: Internal plaster finish\r\n- Paint: Wall painting\r\n\r\nReturn a JSON array of work item descriptions.\r\nExample: [\"Brick masonry laying\", \"Cement mortar for brick joints\", \"Internal cement plaster 15mm\"]\r\n\"\"\"\r\n\r\n        response = self.openai.chat.completions.create(\r\n            model=\"gpt-4o\",\r\n            messages=[{\"role\": \"user\", \"content\": prompt}],\r\n            response_format={\"type\": \"json_object\"}\r\n        )\r\n\r\n        try:\r\n            result = json.loads(response.choices[0].message.content)\r\n            return result.get('work_items', [bim_type])\r\n        except:\r\n            return [bim_type]\r\n\r\n    def estimate_element(\r\n        self,\r\n        bim_type: str,\r\n        category: str,\r\n        quantity: float,\r\n        quantity_unit: str,\r\n        phase: str = \"Construction\"\r\n    ) -> List[CostLineItem]:\r\n        \"\"\"Estimate cost for single BIM element type\"\"\"\r\n\r\n        # Decompose into work items\r\n        work_descriptions = self.decompose_bim_type(bim_type, category)\r\n\r\n        line_items = []\r\n\r\n        for work_desc in work_descriptions:\r\n            # Search CWICR for matching rate\r\n            matches = self.search_cwicr(work_desc, limit=1)\r\n\r\n            if not matches:\r\n                continue\r\n\r\n            best_match = matches[0]\r\n\r\n            # Convert quantity if units don't match\r\n            adjusted_qty = self._convert_units(\r\n                quantity, quantity_unit, best_match.unit\r\n            )\r\n\r\n            # Calculate costs\r\n            total = adjusted_qty * best_match.unit_price\r\n            labor = adjusted_qty * best_match.labor_cost\r\n            material = adjusted_qty * best_match.material_cost\r\n            equipment = adjusted_qty * best_match.equipment_cost\r\n\r\n            line_items.append(CostLineItem(\r\n                bim_type=bim_type,\r\n                work_item=best_match,\r\n                quantity=adjusted_qty,\r\n                quantity_unit=best_match.unit,\r\n                total_cost=total,\r\n                labor_cost=labor,\r\n                material_cost=material,\r\n                equipment_cost=equipment,\r\n                phase=phase,\r\n                trade=self._get_trade(category)\r\n            ))\r\n\r\n        return line_items\r\n\r\n    def estimate_from_qto(\r\n        self,\r\n        qto_data: pd.DataFrame,\r\n        type_column: str = \"Type Name\",\r\n        category_column: str = \"Category\",\r\n        quantity_column: str = \"Volume\"\r\n    ) -> List[CostLineItem]:\r\n        \"\"\"Generate estimate from QTO DataFrame\"\"\"\r\n\r\n        all_line_items = []\r\n\r\n        # Group by type\r\n        grouped = qto_data.groupby([category_column, type_column]).agg({\r\n            quantity_column: 'sum'\r\n        }).reset_index()\r\n\r\n        for _, row in grouped.iterrows():\r\n            items = self.estimate_element(\r\n                bim_type=row[type_column],\r\n                category=row[category_column],\r\n                quantity=row[quantity_column],\r\n                quantity_unit=\"m³\"  # Assume volume, adjust based on category\r\n            )\r\n            all_line_items.extend(items)\r\n\r\n        return all_line_items\r\n\r\n    def _convert_units(\r\n        self,\r\n        value: float,\r\n        from_unit: str,\r\n        to_unit: str\r\n    ) -> float:\r\n        \"\"\"Convert between units\"\"\"\r\n\r\n        # Simplified conversion - expand as needed\r\n        conversions = {\r\n            ('m³', 'm³'): 1.0,\r\n            ('m²', 'm²'): 1.0,\r\n            ('m', 'm'): 1.0,\r\n            ('ft³', 'm³'): 0.0283168,\r\n            ('ft²', 'm²'): 0.092903,\r\n            ('ft', 'm'): 0.3048,\r\n        }\r\n\r\n        key = (from_unit.lower(), to_unit.lower())\r\n        factor = conversions.get(key, 1.0)\r\n\r\n        return value * factor\r\n\r\n    def _get_trade(self, category: str) -> str:\r\n        \"\"\"Map BIM category to trade\"\"\"\r\n        trade_map = {\r\n            'Walls': 'Masonry',\r\n            'Floors': 'Concrete',\r\n            'Structural Columns': 'Concrete',\r\n            'Structural Framing': 'Steel',\r\n            'Doors': 'Carpentry',\r\n            'Windows': 'Glazing',\r\n            'Plumbing Fixtures': 'Plumbing',\r\n            'Electrical Equipment': 'Electrical',\r\n            'Mechanical Equipment': 'HVAC'\r\n        }\r\n        return trade_map.get(category, 'General')\r\n\r\n    def generate_estimate_report(\r\n        self,\r\n        line_items: List[CostLineItem],\r\n        project_name: str,\r\n        output_path: str\r\n    ) -> dict:\r\n        \"\"\"Generate comprehensive estimate report\"\"\"\r\n\r\n        # Convert to DataFrame\r\n        records = []\r\n        for item in line_items:\r\n            records.append({\r\n                'BIM Type': item.bim_type,\r\n                'Work Item': item.work_item.description,\r\n                'CWICR Code': item.work_item.cwicr_code,\r\n                'Quantity': round(item.quantity, 2),\r\n                'Unit': item.quantity_unit,\r\n                'Unit Price': round(item.work_item.unit_price, 2),\r\n                'Labor': round(item.labor_cost, 2),\r\n                'Material': round(item.material_cost, 2),\r\n                'Equipment': round(item.equipment_cost, 2),\r\n                'Total': round(item.total_cost, 2),\r\n                'Phase': item.phase,\r\n                'Trade': item.trade,\r\n                'Currency': item.work_item.currency,\r\n                'Confidence': round(item.work_item.confidence, 2)\r\n            })\r\n\r\n        df = pd.DataFrame(records)\r\n\r\n        # Calculate totals\r\n        total_cost = df['Total'].sum()\r\n        total_labor = df['Labor'].sum()\r\n        total_material = df['Material'].sum()\r\n        total_equipment = df['Equipment'].sum()\r\n\r\n        # Summary by trade\r\n        by_trade = df.groupby('Trade')['Total'].sum().sort_values(ascending=False)\r\n\r\n        # Write Excel\r\n        excel_path = f\"{output_path}/{project_name}_Estimate.xlsx\"\r\n        with pd.ExcelWriter(excel_path, engine='openpyxl') as writer:\r\n            # Summary sheet\r\n            summary_data = {\r\n                'Metric': ['Total Cost', 'Labor Cost', 'Material Cost', 'Equipment Cost'],\r\n                'Value': [total_cost, total_labor, total_material, total_equipment]\r\n            }\r\n            pd.DataFrame(summary_data).to_excel(writer, sheet_name='Summary', index=False)\r\n\r\n            # By Trade\r\n            by_trade.to_frame().to_excel(writer, sheet_name='By Trade')\r\n\r\n            # Detail\r\n            df.to_excel(writer, sheet_name='Detail', index=False)\r\n\r\n        return {\r\n            'excel_path': excel_path,\r\n            'total_cost': total_cost,\r\n            'total_labor': total_labor,\r\n            'total_material': total_material,\r\n            'total_equipment': total_equipment,\r\n            'by_trade': by_trade.to_dict(),\r\n            'line_items': len(df),\r\n            'currency': line_items[0].work_item.currency if line_items else 'USD'\r\n        }\r\n\r\n\r\n# Usage Example\r\ndef estimate_from_bim_model(\r\n    model_path: str,\r\n    qdrant_url: str,\r\n    language: str = \"EN\",\r\n    output_dir: str = \".\"\r\n) -> dict:\r\n    \"\"\"Complete BIM to cost estimation workflow\"\"\"\r\n\r\n    import subprocess\r\n    from pathlib import Path\r\n\r\n    # Step 1: Convert BIM to Excel\r\n    print(\"Converting BIM model...\")\r\n    subprocess.run([\r\n        r\"C:\\DDC\\RvtExporter.exe\",\r\n        model_path,\r\n        \"complete\", \"bbox\"\r\n    ])\r\n\r\n    xlsx_path = Path(model_path).with_suffix('.xlsx')\r\n\r\n    # Step 2: Load QTO data\r\n    print(\"Loading quantity data...\")\r\n    df = pd.read_excel(xlsx_path)\r\n\r\n    # Step 3: Initialize estimator\r\n    estimator = BIMCostEstimator(\r\n        qdrant_url=qdrant_url,\r\n        language=language\r\n    )\r\n\r\n    # Step 4: Generate estimate\r\n    print(\"Generating cost estimate...\")\r\n    line_items = estimator.estimate_from_qto(df)\r\n\r\n    # Step 5: Generate report\r\n    project_name = Path(model_path).stem\r\n    result = estimator.generate_estimate_report(\r\n        line_items=line_items,\r\n        project_name=project_name,\r\n        output_path=output_dir\r\n    )\r\n\r\n    print(f\"\\nEstimate Complete!\")\r\n    print(f\"Total Cost: {result['currency']} {result['total_cost']:,.2f}\")\r\n    print(f\"Excel Report: {result['excel_path']}\")\r\n\r\n    return result\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    result = estimate_from_bim_model(\r\n        model_path=r\"C:\\Projects\\Building.rvt\",\r\n        qdrant_url=\"https://your-qdrant-instance.io\",\r\n        language=\"DE\",\r\n        output_dir=r\"C:\\Projects\\Estimates\"\r\n    )\r\n```\r\n\r\n## n8n Workflow\r\n\r\nSee: `n8n_4_CAD_(BIM)_Cost_Estimation_Pipeline_4D_5D_with_DDC_CWICR.json`\r\n\r\n```yaml\r\nstages:\r\n  - convert: RvtExporter → XLSX\r\n  - detect_project: LLM identifies project type\r\n  - generate_phases: LLM creates construction phases\r\n  - decompose: LLM breaks types into work items\r\n  - vector_search: Qdrant finds CWICR matches\r\n  - calculate: Qty × Unit Price\r\n  - validate: CTO review\r\n  - report: HTML + Excel output\r\n```\r\n\r\n## Output Example\r\n\r\n```\r\n╔══════════════════════════════════════════════════════════════╗\r\n║                    COST ESTIMATE SUMMARY                      ║\r\n║   Project: Office Building Berlin                             ║\r\n║   Date: 2026-01-24                                           ║\r\n╠══════════════════════════════════════════════════════════════╣\r\n\r\nTOTAL PROJECT COST:                    EUR 4,523,678.00\r\n───────────────────────────────────────────────────────────────\r\n  Labor:                               EUR 1,847,234.00 (41%)\r\n  Materials:                           EUR 2,312,456.00 (51%)\r\n  Equipment:                           EUR   363,988.00 ( 8%)\r\n\r\nBY TRADE\r\n───────────────────────────────────────────────────────────────\r\n  Concrete:                            EUR 1,234,567.00 (27%)\r\n  Masonry:                             EUR   876,543.00 (19%)\r\n  Steel Structure:                     EUR   654,321.00 (14%)\r\n  MEP:                                 EUR   543,210.00 (12%)\r\n  Finishes:                            EUR   432,109.00 (10%)\r\n  Other:                               EUR   782,928.00 (18%)\r\n\r\nCONFIDENCE ANALYSIS\r\n───────────────────────────────────────────────────────────────\r\n  High (>0.85):                        78%\r\n  Medium (0.70-0.85):                  18%\r\n  Low (<0.70):                          4%\r\n\r\n╚══════════════════════════════════════════════════════════════╝\r\n```\r\n\r\n## Resources\r\n\r\n- **CWICR Repository**: https://github.com/datadrivenconstruction/OpenConstructionEstimate-DDC-CWICR\r\n- **Live Demo**: https://openconstructionestimate.com\r\n- **Qdrant**: https://qdrant.tech\r\n\r\n---\r\n\r\n*\"Resource-based costing separates physical quantities from volatile prices, enabling transparent and auditable estimates.\"*\n\nFile v1.0.0:_meta.json\n\n{\n  \"ownerId\": \"kn75fhjxn1jz5xbgd9ggj0nrtd80q1dz\",\n  \"slug\": \"bim-cost-estimation-cwicr\",\n  \"version\": \"1.0.0\",\n  \"publishedAt\": 1770474886541\n}","readmeExcerpt":"Skill: Bim Cost Estimation Cwicr Owner: datadrivenconstruction Summary: Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing. Tags: latest:2.1.0 Version history: v2.1.0 | 2026-02-13T21:08:30.955Z | auto - Added \"homepage\" and \"metadata\" fields to the skill manifest with relevant information. - Specified platform compatibility","codeSnippets":[],"executableExamples":[],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\r\nname: \"bim-cost-estimation-cwicr\"\r\ndescription: \"Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing.\"\r\nhomepage: \"https://datadrivenconstruction.io\"\r\nmetadata: {\"openclaw\":{\"emoji\":\"🏗️\",\"os\":[\"darwin\",\"linux\",\"win32\"],\"homepage\":\"https://datadrivenconstruction.io\",\"requires\":{\"bins\":[\"python3\"],\"env\":[\"OPENAI_API_KEY\",\"QDRANT_URL\"]},\"primaryEnv\":\"OPENAI_API_KEY\"}}\r\n---\r\n\r\n# BIM Cost Estimation with DDC CWICR\r\n\r\nGenerate accurate cost estimates from BIM models using AI classification and the DDC CWICR construction cost database.\r\n\r\n## Business Case\r\n\r\n**Problem**: Traditional cost estimation:\r\n- Manual and time-consuming (weeks for detailed estimate)\r\n- Subjective and inconsistent between estimators\r\n- Requires specialized knowledge\r\n- Difficult to update with design changes\r\n\r\n**Solution**: Automated BIM-to-cost pipeline:\r\n- Extract quantities directly from model\r\n- AI classifies elements to work items\r\n- Vector search finds matching prices in CWICR\r\n- Complete estimate in hours, not weeks\r\n\r\n**ROI**: 80% reduction in estimation time, consistent methodology\r\n\r\n## System Architecture\r\n\r\n```\r\n┌──────────────────────────────────────────────────────────────────────────┐\r\n│                  BIM TO COST ESTIMATION PIPELINE                          │\r\n├──────────────────────────────────────────────────────────────────────────┤\r\n│                                                                           │\r\n│   ┌─────────┐     ┌─────────┐     ┌─────────┐     ┌─────────────────┐   │\r\n│   │ BIM     │     │ DDC     │     │ AI      │     │ DDC CWICR       │   │\r\n│   │ Model   │────►│Converter│────►│ LLM     │────►│ Vector Search   │   │\r\n│   │.rvt/.ifc│     │         │     │         │     │ (Qdrant)        │   │\r\n│   └─────────┘     └─────────┘     └─────────┘     └─────────────────┘   │\r\n│                        │              │                    │             │\r\n│                        ▼              ▼                    ▼             │\r\n│                   ┌─────────┐    ┌─────────┐         ┌──────────┐       │\r\n│                   │ .xlsx   │    │ Work    │         │ Matched  │       │\r\n│                   │ QTO     │    │ Items   │         │ Rates    │       │\r\n│                   └─────────┘    └─────────┘         └──────────┘       │\r\n│                        │              │                    │             │\r\n│                        └──────────────┼────────────────────┘             │\r\n│                                       ▼                                  │\r\n│                              ┌─────────────────┐                        │\r\n│                              │ COST ESTIMATE   │                        │\r\n│                              │                 │                        │\r\n│                              │ • By element    │                        │\r\n│                              │ • By trade      │                        │\r\n│        "},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn75fhjxn1jz5xbgd9ggj0nrtd80q1dz\",\n  \"slug\": \"bim-cost-estimation-cwicr\",\n  \"version\": \"2.1.0\",\n  \"publishedAt\": 1771016910955\n}"},{"path":"instructions.md","content":"You are a BIM-to-cost estimation assistant powered by the DDC CWICR database (55,719 work items across 9 languages). You automate the full pipeline from BIM model to cost estimate using AI classification and vector search.\n\nWhen the user asks to estimate costs from a BIM model:\n1. Guide them through the pipeline stages: BIM export -> QTO -> AI classification -> vector search -> cost calculation\n2. Explain the 10-stage pipeline (collect, detect project, generate phases, assign elements, decompose work, vector search, unit mapping, cost calculation, validation, aggregation)\n3. Help configure: language/region (EN, DE, RU, ES, FR, AR, HI, PT, ZH), Qdrant connection, OpenAI API for embeddings\n4. Present results by trade, phase, and element type\n\nWhen the user asks about CWICR database:\n1. Explain the database structure: 55,719 work items, 27,672 resources, 85 fields per item\n2. Help with vector search queries using text-embedding-3-large (3072 dimensions)\n3. Show matching results with confidence scores\n\n## Input Format\n- BIM model path (.rvt or .ifc) or pre-exported QTO data (.xlsx)\n- Target language/region for pricing\n- Qdrant URL and API credentials (environment variables)\n\n## Output Format\n- Cost estimate by trade (Concrete, Masonry, Steel, MEP, etc.)\n- Cost breakdown: labor, material, equipment percentages\n- Confidence analysis (high >0.85, medium 0.70-0.85, low <0.70)\n- Excel report with Summary, By Trade, and Detail sheets\n\n## Pipeline Stages\n| Stage | Description |\n|-------|-------------|\n| 0 | Collect BIM data from Revit/IFC |\n| 1-3 | AI detects project type, generates phases, assigns elements |\n| 4 | AI decomposes element types into work items |\n| 5 | Vector search matches work items to CWICR rates |\n| 6-7 | Unit mapping and cost calculation |\n| 8-9 | Aggregation and report generation |\n\n## Constraints\n- Network permission required for Qdrant vector database and OpenAI embeddings API\n- Filesystem permission required for BIM model reading and Excel export\n- subprocess.run() is used solely for invoking the DDC RvtExporter CAD conversion tool\n- All API keys must be loaded from environment variables, never hardcoded"},{"path":"claw.json","content":"{\n  \"name\": \"bim-cost-estimation-cwicr\",\n  \"version\": \"2.0.0\",\n  \"description\": \"Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing.\",\n  \"author\": \"datadrivenconstruction\",\n  \"license\": \"MIT\",\n  \"permissions\": [\"filesystem\", \"network\"],\n  \"entry\": \"instructions.md\",\n  \"tags\": [\"construction\", \"BIM\", \"estimation\", \"CWICR\", \"vector-search\", \"AI\", \"cost-management\"],\n  \"models\": [\"claude-*\", \"gpt-*\"],\n  \"minOpenClawVersion\": \"0.8.0\"\n}"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing. Skill: Bim Cost Estimation Cwicr Owner: datadrivenconstruction Summary: Automated cost estimation from BIM models using DDC CWICR database with 55,719 work items. AI classification + vector search for accurate pricing. Tags: latest:2.1.0 Version history: v2.1.0 | 2026-02-13T21:08:30.955Z | auto - Added \"homepage\" and \"metadata\" fields to the skill manifest with relevant information. - Specified platform compatibility","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1141,"uniquenessScore":48,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-11T02:18:00.692Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-11T02:18:00.692Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-11T04:35:39.934Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}