{
  "schemaVersion": "1.0",
  "item": {
    "slug": "cwicr-cost-calculator",
    "name": "Cwicr Cost Calculator",
    "source": "tencent",
    "type": "skill",
    "category": "数据分析",
    "sourceUrl": "https://clawhub.ai/datadrivenconstruction/cwicr-cost-calculator",
    "canonicalUrl": "https://clawhub.ai/datadrivenconstruction/cwicr-cost-calculator",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/cwicr-cost-calculator",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=cwicr-cost-calculator",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "claw.json",
      "instructions.md",
      "SKILL.md"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-23T16:43:11.935Z",
      "expiresAt": "2026-04-30T16:43:11.935Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=4claw-imageboard",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=4claw-imageboard",
        "contentDisposition": "attachment; filename=\"4claw-imageboard-1.0.1.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/cwicr-cost-calculator"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/cwicr-cost-calculator",
    "agentPageUrl": "https://openagent3.xyz/skills/cwicr-cost-calculator/agent",
    "manifestUrl": "https://openagent3.xyz/skills/cwicr-cost-calculator/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/cwicr-cost-calculator/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "Problem Statement",
        "body": "Traditional cost estimation often produces \"black box\" estimates with hidden markups. Stakeholders need:\n\nTransparent cost breakdowns\nTraceable pricing logic\nAuditable calculations\nResource-level detail"
      },
      {
        "title": "Solution",
        "body": "Resource-based cost calculation using CWICR methodology that separates physical norms (labor hours, material quantities) from volatile prices, enabling transparent and auditable estimates."
      },
      {
        "title": "Business Value",
        "body": "Full transparency - Every cost component visible\nAuditable - Traceable calculation logic\nFlexible - Update prices without changing norms\nAccurate - Based on 55,000+ validated work items"
      },
      {
        "title": "Prerequisites",
        "body": "pip install pandas numpy"
      },
      {
        "title": "Python Implementation",
        "body": "import pandas as pd\nimport numpy as np\nfrom typing import Dict, Any, List, Optional, Tuple\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom datetime import datetime\n\n\nclass CostComponent(Enum):\n    \"\"\"Cost breakdown components.\"\"\"\n    LABOR = \"labor\"\n    MATERIAL = \"material\"\n    EQUIPMENT = \"equipment\"\n    OVERHEAD = \"overhead\"\n    PROFIT = \"profit\"\n    TOTAL = \"total\"\n\n\nclass CostStatus(Enum):\n    \"\"\"Cost calculation status.\"\"\"\n    CALCULATED = \"calculated\"\n    ESTIMATED = \"estimated\"\n    MISSING_DATA = \"missing_data\"\n    ERROR = \"error\"\n\n\n@dataclass\nclass CostBreakdown:\n    \"\"\"Detailed cost breakdown for a work item.\"\"\"\n    work_item_code: str\n    description: str\n    unit: str\n    quantity: float\n\n    labor_cost: float = 0.0\n    material_cost: float = 0.0\n    equipment_cost: float = 0.0\n    overhead_cost: float = 0.0\n    profit_cost: float = 0.0\n\n    unit_price: float = 0.0\n    total_cost: float = 0.0\n\n    labor_hours: float = 0.0\n    labor_rate: float = 0.0\n\n    resources: List[Dict[str, Any]] = field(default_factory=list)\n    status: CostStatus = CostStatus.CALCULATED\n\n    def to_dict(self) -> Dict[str, Any]:\n        return {\n            'work_item_code': self.work_item_code,\n            'description': self.description,\n            'unit': self.unit,\n            'quantity': self.quantity,\n            'labor_cost': self.labor_cost,\n            'material_cost': self.material_cost,\n            'equipment_cost': self.equipment_cost,\n            'overhead_cost': self.overhead_cost,\n            'profit_cost': self.profit_cost,\n            'total_cost': self.total_cost,\n            'status': self.status.value\n        }\n\n\n@dataclass\nclass CostSummary:\n    \"\"\"Summary of cost estimate.\"\"\"\n    total_cost: float\n    labor_total: float\n    material_total: float\n    equipment_total: float\n    overhead_total: float\n    profit_total: float\n\n    item_count: int\n    currency: str\n    calculated_at: datetime\n\n    breakdown_by_category: Dict[str, float] = field(default_factory=dict)\n\n\nclass CWICRCostCalculator:\n    \"\"\"Resource-based cost calculator using CWICR methodology.\"\"\"\n\n    DEFAULT_OVERHEAD_RATE = 0.15  # 15% overhead\n    DEFAULT_PROFIT_RATE = 0.10   # 10% profit\n\n    def __init__(self, cwicr_data: pd.DataFrame,\n                 overhead_rate: float = None,\n                 profit_rate: float = None,\n                 currency: str = \"USD\"):\n        \"\"\"Initialize calculator with CWICR data.\"\"\"\n        self.data = cwicr_data\n        self.overhead_rate = overhead_rate or self.DEFAULT_OVERHEAD_RATE\n        self.profit_rate = profit_rate or self.DEFAULT_PROFIT_RATE\n        self.currency = currency\n\n        # Index data for fast lookup\n        self._index_data()\n\n    def _index_data(self):\n        \"\"\"Create index for fast work item lookup.\"\"\"\n        if 'work_item_code' in self.data.columns:\n            self._code_index = self.data.set_index('work_item_code')\n        else:\n            self._code_index = None\n\n    def calculate_item_cost(self, work_item_code: str,\n                            quantity: float,\n                            price_overrides: Dict[str, float] = None) -> CostBreakdown:\n        \"\"\"Calculate cost for single work item.\"\"\"\n\n        # Find work item in database\n        if self._code_index is not None and work_item_code in self._code_index.index:\n            item = self._code_index.loc[work_item_code]\n        else:\n            # Try partial match\n            matches = self.data[\n                self.data['work_item_code'].str.contains(work_item_code, case=False, na=False)\n            ]\n            if matches.empty:\n                return CostBreakdown(\n                    work_item_code=work_item_code,\n                    description=\"NOT FOUND\",\n                    unit=\"\",\n                    quantity=quantity,\n                    status=CostStatus.MISSING_DATA\n                )\n            item = matches.iloc[0]\n\n        # Get base costs\n        labor_unit = float(item.get('labor_cost', 0) or 0)\n        material_unit = float(item.get('material_cost', 0) or 0)\n        equipment_unit = float(item.get('equipment_cost', 0) or 0)\n\n        # Apply price overrides if provided\n        if price_overrides:\n            if 'labor_rate' in price_overrides:\n                labor_norm = float(item.get('labor_norm', 0) or 0)\n                labor_unit = labor_norm * price_overrides['labor_rate']\n            if 'material_factor' in price_overrides:\n                material_unit *= price_overrides['material_factor']\n            if 'equipment_factor' in price_overrides:\n                equipment_unit *= price_overrides['equipment_factor']\n\n        # Calculate component costs\n        labor_cost = labor_unit * quantity\n        material_cost = material_unit * quantity\n        equipment_cost = equipment_unit * quantity\n\n        # Direct costs\n        direct_cost = labor_cost + material_cost + equipment_cost\n\n        # Overhead and profit\n        overhead_cost = direct_cost * self.overhead_rate\n        profit_cost = (direct_cost + overhead_cost) * self.profit_rate\n\n        # Total\n        total_cost = direct_cost + overhead_cost + profit_cost\n\n        # Unit price\n        unit_price = total_cost / quantity if quantity > 0 else 0\n\n        return CostBreakdown(\n            work_item_code=work_item_code,\n            description=str(item.get('description', '')),\n            unit=str(item.get('unit', '')),\n            quantity=quantity,\n            labor_cost=labor_cost,\n            material_cost=material_cost,\n            equipment_cost=equipment_cost,\n            overhead_cost=overhead_cost,\n            profit_cost=profit_cost,\n            unit_price=unit_price,\n            total_cost=total_cost,\n            labor_hours=float(item.get('labor_norm', 0) or 0) * quantity,\n            labor_rate=float(item.get('labor_rate', 0) or 0),\n            status=CostStatus.CALCULATED\n        )\n\n    def calculate_estimate(self, items: List[Dict[str, Any]],\n                          group_by_category: bool = True) -> CostSummary:\n        \"\"\"Calculate cost estimate for multiple items.\"\"\"\n\n        breakdowns = []\n        for item in items:\n            code = item.get('work_item_code') or item.get('code')\n            qty = item.get('quantity', 0)\n            overrides = item.get('price_overrides')\n\n            breakdown = self.calculate_item_cost(code, qty, overrides)\n            breakdowns.append(breakdown)\n\n        # Aggregate totals\n        labor_total = sum(b.labor_cost for b in breakdowns)\n        material_total = sum(b.material_cost for b in breakdowns)\n        equipment_total = sum(b.equipment_cost for b in breakdowns)\n        overhead_total = sum(b.overhead_cost for b in breakdowns)\n        profit_total = sum(b.profit_cost for b in breakdowns)\n        total_cost = sum(b.total_cost for b in breakdowns)\n\n        # Group by category if requested\n        breakdown_by_category = {}\n        if group_by_category:\n            for b in breakdowns:\n                # Extract category from work item code prefix\n                category = b.work_item_code.split('-')[0] if '-' in b.work_item_code else 'Other'\n                if category not in breakdown_by_category:\n                    breakdown_by_category[category] = 0\n                breakdown_by_category[category] += b.total_cost\n\n        return CostSummary(\n            total_cost=total_cost,\n            labor_total=labor_total,\n            material_total=material_total,\n            equipment_total=equipment_total,\n            overhead_total=overhead_total,\n            profit_total=profit_total,\n            item_count=len(breakdowns),\n            currency=self.currency,\n            calculated_at=datetime.now(),\n            breakdown_by_category=breakdown_by_category\n        )\n\n    def calculate_from_qto(self, qto_df: pd.DataFrame,\n                          code_column: str = 'work_item_code',\n                          quantity_column: str = 'quantity') -> pd.DataFrame:\n        \"\"\"Calculate costs from Quantity Takeoff DataFrame.\"\"\"\n\n        results = []\n        for _, row in qto_df.iterrows():\n            code = row[code_column]\n            qty = row[quantity_column]\n\n            breakdown = self.calculate_item_cost(code, qty)\n            result = breakdown.to_dict()\n\n            # Add original QTO columns\n            for col in qto_df.columns:\n                if col not in result:\n                    result[f'qto_{col}'] = row[col]\n\n            results.append(result)\n\n        return pd.DataFrame(results)\n\n    def apply_regional_factors(self, base_costs: pd.DataFrame,\n                               region_factors: Dict[str, float]) -> pd.DataFrame:\n        \"\"\"Apply regional adjustment factors.\"\"\"\n        adjusted = base_costs.copy()\n\n        if 'labor_cost' in adjusted.columns and 'labor' in region_factors:\n            adjusted['labor_cost'] *= region_factors['labor']\n\n        if 'material_cost' in adjusted.columns and 'material' in region_factors:\n            adjusted['material_cost'] *= region_factors['material']\n\n        if 'equipment_cost' in adjusted.columns and 'equipment' in region_factors:\n            adjusted['equipment_cost'] *= region_factors['equipment']\n\n        # Recalculate totals\n        adjusted['direct_cost'] = (\n            adjusted.get('labor_cost', 0) +\n            adjusted.get('material_cost', 0) +\n            adjusted.get('equipment_cost', 0)\n        )\n        adjusted['total_cost'] = adjusted['direct_cost'] * (1 + self.overhead_rate) * (1 + self.profit_rate)\n\n        return adjusted\n\n    def compare_estimates(self, estimate1: CostSummary,\n                         estimate2: CostSummary) -> Dict[str, Any]:\n        \"\"\"Compare two cost estimates.\"\"\"\n        return {\n            'total_difference': estimate2.total_cost - estimate1.total_cost,\n            'total_percent_change': (\n                (estimate2.total_cost - estimate1.total_cost) /\n                estimate1.total_cost * 100 if estimate1.total_cost > 0 else 0\n            ),\n            'labor_difference': estimate2.labor_total - estimate1.labor_total,\n            'material_difference': estimate2.material_total - estimate1.material_total,\n            'equipment_difference': estimate2.equipment_total - estimate1.equipment_total,\n            'item_count_difference': estimate2.item_count - estimate1.item_count\n        }\n\n\nclass CostReportGenerator:\n    \"\"\"Generate cost reports from calculations.\"\"\"\n\n    def __init__(self, calculator: CWICRCostCalculator):\n        self.calculator = calculator\n\n    def generate_summary_report(self, items: List[Dict[str, Any]]) -> Dict[str, Any]:\n        \"\"\"Generate summary cost report.\"\"\"\n        summary = self.calculator.calculate_estimate(items)\n\n        return {\n            'report_date': datetime.now().isoformat(),\n            'currency': summary.currency,\n            'total_cost': round(summary.total_cost, 2),\n            'breakdown': {\n                'labor': round(summary.labor_total, 2),\n                'material': round(summary.material_total, 2),\n                'equipment': round(summary.equipment_total, 2),\n                'overhead': round(summary.overhead_total, 2),\n                'profit': round(summary.profit_total, 2)\n            },\n            'percentages': {\n                'labor': round(summary.labor_total / summary.total_cost * 100, 1) if summary.total_cost > 0 else 0,\n                'material': round(summary.material_total / summary.total_cost * 100, 1) if summary.total_cost > 0 else 0,\n                'equipment': round(summary.equipment_total / summary.total_cost * 100, 1) if summary.total_cost > 0 else 0,\n            },\n            'item_count': summary.item_count,\n            'by_category': summary.breakdown_by_category\n        }\n\n    def generate_detailed_report(self, items: List[Dict[str, Any]]) -> pd.DataFrame:\n        \"\"\"Generate detailed line-item report.\"\"\"\n        results = []\n\n        for item in items:\n            code = item.get('work_item_code') or item.get('code')\n            qty = item.get('quantity', 0)\n\n            breakdown = self.calculator.calculate_item_cost(code, qty)\n            results.append(breakdown.to_dict())\n\n        df = pd.DataFrame(results)\n\n        # Add totals row\n        totals = df[['labor_cost', 'material_cost', 'equipment_cost',\n                     'overhead_cost', 'profit_cost', 'total_cost']].sum()\n        totals['description'] = 'TOTAL'\n        totals['work_item_code'] = ''\n\n        df = pd.concat([df, pd.DataFrame([totals])], ignore_index=True)\n\n        return df\n\n\n# Convenience functions\ndef calculate_cost(cwicr_data: pd.DataFrame,\n                   work_item_code: str,\n                   quantity: float) -> float:\n    \"\"\"Quick cost calculation.\"\"\"\n    calc = CWICRCostCalculator(cwicr_data)\n    breakdown = calc.calculate_item_cost(work_item_code, quantity)\n    return breakdown.total_cost\n\n\ndef estimate_project_cost(cwicr_data: pd.DataFrame,\n                         items: List[Dict[str, Any]]) -> Dict[str, Any]:\n    \"\"\"Quick project cost estimate.\"\"\"\n    calc = CWICRCostCalculator(cwicr_data)\n    report = CostReportGenerator(calc)\n    return report.generate_summary_report(items)"
      },
      {
        "title": "Quick Start",
        "body": "import pandas as pd\nfrom cwicr_data_loader import CWICRDataLoader\n\n# Load CWICR data\nloader = CWICRDataLoader()\ncwicr = loader.load(\"ddc_cwicr_en.parquet\")\n\n# Initialize calculator\ncalc = CWICRCostCalculator(cwicr)\n\n# Calculate single item\nbreakdown = calc.calculate_item_cost(\"CONC-001\", quantity=150)\nprint(f\"Total: ${breakdown.total_cost:,.2f}\")\nprint(f\"  Labor: ${breakdown.labor_cost:,.2f}\")\nprint(f\"  Material: ${breakdown.material_cost:,.2f}\")\nprint(f\"  Equipment: ${breakdown.equipment_cost:,.2f}\")"
      },
      {
        "title": "1. Project Estimate",
        "body": "items = [\n    {'work_item_code': 'CONC-001', 'quantity': 150},\n    {'work_item_code': 'EXCV-002', 'quantity': 200},\n    {'work_item_code': 'REBAR-003', 'quantity': 15000}  # kg\n]\n\nsummary = calc.calculate_estimate(items)\nprint(f\"Project Total: ${summary.total_cost:,.2f}\")"
      },
      {
        "title": "2. QTO Integration",
        "body": "# Load BIM quantities\nqto = pd.read_excel(\"quantities.xlsx\")\n\n# Calculate costs\ncosts = calc.calculate_from_qto(qto,\n    code_column='work_item',\n    quantity_column='quantity'\n)\nprint(costs[['description', 'quantity', 'total_cost']])"
      },
      {
        "title": "3. Regional Adjustment",
        "body": "# Apply Berlin pricing\nberlin_factors = {\n    'labor': 1.15,      # 15% higher labor\n    'material': 0.95,   # 5% lower materials\n    'equipment': 1.0\n}\n\nadjusted = calc.apply_regional_factors(costs, berlin_factors)"
      },
      {
        "title": "Resources",
        "body": "GitHub: OpenConstructionEstimate-DDC-CWICR\nDDC Book: Chapter 3.1 - Construction Cost Estimation"
      }
    ],
    "body": "CWICR Cost Calculator\nBusiness Case\nProblem Statement\n\nTraditional cost estimation often produces \"black box\" estimates with hidden markups. Stakeholders need:\n\nTransparent cost breakdowns\nTraceable pricing logic\nAuditable calculations\nResource-level detail\nSolution\n\nResource-based cost calculation using CWICR methodology that separates physical norms (labor hours, material quantities) from volatile prices, enabling transparent and auditable estimates.\n\nBusiness Value\nFull transparency - Every cost component visible\nAuditable - Traceable calculation logic\nFlexible - Update prices without changing norms\nAccurate - Based on 55,000+ validated work items\nTechnical Implementation\nPrerequisites\npip install pandas numpy\n\nPython Implementation\nimport pandas as pd\nimport numpy as np\nfrom typing import Dict, Any, List, Optional, Tuple\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom datetime import datetime\n\n\nclass CostComponent(Enum):\n    \"\"\"Cost breakdown components.\"\"\"\n    LABOR = \"labor\"\n    MATERIAL = \"material\"\n    EQUIPMENT = \"equipment\"\n    OVERHEAD = \"overhead\"\n    PROFIT = \"profit\"\n    TOTAL = \"total\"\n\n\nclass CostStatus(Enum):\n    \"\"\"Cost calculation status.\"\"\"\n    CALCULATED = \"calculated\"\n    ESTIMATED = \"estimated\"\n    MISSING_DATA = \"missing_data\"\n    ERROR = \"error\"\n\n\n@dataclass\nclass CostBreakdown:\n    \"\"\"Detailed cost breakdown for a work item.\"\"\"\n    work_item_code: str\n    description: str\n    unit: str\n    quantity: float\n\n    labor_cost: float = 0.0\n    material_cost: float = 0.0\n    equipment_cost: float = 0.0\n    overhead_cost: float = 0.0\n    profit_cost: float = 0.0\n\n    unit_price: float = 0.0\n    total_cost: float = 0.0\n\n    labor_hours: float = 0.0\n    labor_rate: float = 0.0\n\n    resources: List[Dict[str, Any]] = field(default_factory=list)\n    status: CostStatus = CostStatus.CALCULATED\n\n    def to_dict(self) -> Dict[str, Any]:\n        return {\n            'work_item_code': self.work_item_code,\n            'description': self.description,\n            'unit': self.unit,\n            'quantity': self.quantity,\n            'labor_cost': self.labor_cost,\n            'material_cost': self.material_cost,\n            'equipment_cost': self.equipment_cost,\n            'overhead_cost': self.overhead_cost,\n            'profit_cost': self.profit_cost,\n            'total_cost': self.total_cost,\n            'status': self.status.value\n        }\n\n\n@dataclass\nclass CostSummary:\n    \"\"\"Summary of cost estimate.\"\"\"\n    total_cost: float\n    labor_total: float\n    material_total: float\n    equipment_total: float\n    overhead_total: float\n    profit_total: float\n\n    item_count: int\n    currency: str\n    calculated_at: datetime\n\n    breakdown_by_category: Dict[str, float] = field(default_factory=dict)\n\n\nclass CWICRCostCalculator:\n    \"\"\"Resource-based cost calculator using CWICR methodology.\"\"\"\n\n    DEFAULT_OVERHEAD_RATE = 0.15  # 15% overhead\n    DEFAULT_PROFIT_RATE = 0.10   # 10% profit\n\n    def __init__(self, cwicr_data: pd.DataFrame,\n                 overhead_rate: float = None,\n                 profit_rate: float = None,\n                 currency: str = \"USD\"):\n        \"\"\"Initialize calculator with CWICR data.\"\"\"\n        self.data = cwicr_data\n        self.overhead_rate = overhead_rate or self.DEFAULT_OVERHEAD_RATE\n        self.profit_rate = profit_rate or self.DEFAULT_PROFIT_RATE\n        self.currency = currency\n\n        # Index data for fast lookup\n        self._index_data()\n\n    def _index_data(self):\n        \"\"\"Create index for fast work item lookup.\"\"\"\n        if 'work_item_code' in self.data.columns:\n            self._code_index = self.data.set_index('work_item_code')\n        else:\n            self._code_index = None\n\n    def calculate_item_cost(self, work_item_code: str,\n                            quantity: float,\n                            price_overrides: Dict[str, float] = None) -> CostBreakdown:\n        \"\"\"Calculate cost for single work item.\"\"\"\n\n        # Find work item in database\n        if self._code_index is not None and work_item_code in self._code_index.index:\n            item = self._code_index.loc[work_item_code]\n        else:\n            # Try partial match\n            matches = self.data[\n                self.data['work_item_code'].str.contains(work_item_code, case=False, na=False)\n            ]\n            if matches.empty:\n                return CostBreakdown(\n                    work_item_code=work_item_code,\n                    description=\"NOT FOUND\",\n                    unit=\"\",\n                    quantity=quantity,\n                    status=CostStatus.MISSING_DATA\n                )\n            item = matches.iloc[0]\n\n        # Get base costs\n        labor_unit = float(item.get('labor_cost', 0) or 0)\n        material_unit = float(item.get('material_cost', 0) or 0)\n        equipment_unit = float(item.get('equipment_cost', 0) or 0)\n\n        # Apply price overrides if provided\n        if price_overrides:\n            if 'labor_rate' in price_overrides:\n                labor_norm = float(item.get('labor_norm', 0) or 0)\n                labor_unit = labor_norm * price_overrides['labor_rate']\n            if 'material_factor' in price_overrides:\n                material_unit *= price_overrides['material_factor']\n            if 'equipment_factor' in price_overrides:\n                equipment_unit *= price_overrides['equipment_factor']\n\n        # Calculate component costs\n        labor_cost = labor_unit * quantity\n        material_cost = material_unit * quantity\n        equipment_cost = equipment_unit * quantity\n\n        # Direct costs\n        direct_cost = labor_cost + material_cost + equipment_cost\n\n        # Overhead and profit\n        overhead_cost = direct_cost * self.overhead_rate\n        profit_cost = (direct_cost + overhead_cost) * self.profit_rate\n\n        # Total\n        total_cost = direct_cost + overhead_cost + profit_cost\n\n        # Unit price\n        unit_price = total_cost / quantity if quantity > 0 else 0\n\n        return CostBreakdown(\n            work_item_code=work_item_code,\n            description=str(item.get('description', '')),\n            unit=str(item.get('unit', '')),\n            quantity=quantity,\n            labor_cost=labor_cost,\n            material_cost=material_cost,\n            equipment_cost=equipment_cost,\n            overhead_cost=overhead_cost,\n            profit_cost=profit_cost,\n            unit_price=unit_price,\n            total_cost=total_cost,\n            labor_hours=float(item.get('labor_norm', 0) or 0) * quantity,\n            labor_rate=float(item.get('labor_rate', 0) or 0),\n            status=CostStatus.CALCULATED\n        )\n\n    def calculate_estimate(self, items: List[Dict[str, Any]],\n                          group_by_category: bool = True) -> CostSummary:\n        \"\"\"Calculate cost estimate for multiple items.\"\"\"\n\n        breakdowns = []\n        for item in items:\n            code = item.get('work_item_code') or item.get('code')\n            qty = item.get('quantity', 0)\n            overrides = item.get('price_overrides')\n\n            breakdown = self.calculate_item_cost(code, qty, overrides)\n            breakdowns.append(breakdown)\n\n        # Aggregate totals\n        labor_total = sum(b.labor_cost for b in breakdowns)\n        material_total = sum(b.material_cost for b in breakdowns)\n        equipment_total = sum(b.equipment_cost for b in breakdowns)\n        overhead_total = sum(b.overhead_cost for b in breakdowns)\n        profit_total = sum(b.profit_cost for b in breakdowns)\n        total_cost = sum(b.total_cost for b in breakdowns)\n\n        # Group by category if requested\n        breakdown_by_category = {}\n        if group_by_category:\n            for b in breakdowns:\n                # Extract category from work item code prefix\n                category = b.work_item_code.split('-')[0] if '-' in b.work_item_code else 'Other'\n                if category not in breakdown_by_category:\n                    breakdown_by_category[category] = 0\n                breakdown_by_category[category] += b.total_cost\n\n        return CostSummary(\n            total_cost=total_cost,\n            labor_total=labor_total,\n            material_total=material_total,\n            equipment_total=equipment_total,\n            overhead_total=overhead_total,\n            profit_total=profit_total,\n            item_count=len(breakdowns),\n            currency=self.currency,\n            calculated_at=datetime.now(),\n            breakdown_by_category=breakdown_by_category\n        )\n\n    def calculate_from_qto(self, qto_df: pd.DataFrame,\n                          code_column: str = 'work_item_code',\n                          quantity_column: str = 'quantity') -> pd.DataFrame:\n        \"\"\"Calculate costs from Quantity Takeoff DataFrame.\"\"\"\n\n        results = []\n        for _, row in qto_df.iterrows():\n            code = row[code_column]\n            qty = row[quantity_column]\n\n            breakdown = self.calculate_item_cost(code, qty)\n            result = breakdown.to_dict()\n\n            # Add original QTO columns\n            for col in qto_df.columns:\n                if col not in result:\n                    result[f'qto_{col}'] = row[col]\n\n            results.append(result)\n\n        return pd.DataFrame(results)\n\n    def apply_regional_factors(self, base_costs: pd.DataFrame,\n                               region_factors: Dict[str, float]) -> pd.DataFrame:\n        \"\"\"Apply regional adjustment factors.\"\"\"\n        adjusted = base_costs.copy()\n\n        if 'labor_cost' in adjusted.columns and 'labor' in region_factors:\n            adjusted['labor_cost'] *= region_factors['labor']\n\n        if 'material_cost' in adjusted.columns and 'material' in region_factors:\n            adjusted['material_cost'] *= region_factors['material']\n\n        if 'equipment_cost' in adjusted.columns and 'equipment' in region_factors:\n            adjusted['equipment_cost'] *= region_factors['equipment']\n\n        # Recalculate totals\n        adjusted['direct_cost'] = (\n            adjusted.get('labor_cost', 0) +\n            adjusted.get('material_cost', 0) +\n            adjusted.get('equipment_cost', 0)\n        )\n        adjusted['total_cost'] = adjusted['direct_cost'] * (1 + self.overhead_rate) * (1 + self.profit_rate)\n\n        return adjusted\n\n    def compare_estimates(self, estimate1: CostSummary,\n                         estimate2: CostSummary) -> Dict[str, Any]:\n        \"\"\"Compare two cost estimates.\"\"\"\n        return {\n            'total_difference': estimate2.total_cost - estimate1.total_cost,\n            'total_percent_change': (\n                (estimate2.total_cost - estimate1.total_cost) /\n                estimate1.total_cost * 100 if estimate1.total_cost > 0 else 0\n            ),\n            'labor_difference': estimate2.labor_total - estimate1.labor_total,\n            'material_difference': estimate2.material_total - estimate1.material_total,\n            'equipment_difference': estimate2.equipment_total - estimate1.equipment_total,\n            'item_count_difference': estimate2.item_count - estimate1.item_count\n        }\n\n\nclass CostReportGenerator:\n    \"\"\"Generate cost reports from calculations.\"\"\"\n\n    def __init__(self, calculator: CWICRCostCalculator):\n        self.calculator = calculator\n\n    def generate_summary_report(self, items: List[Dict[str, Any]]) -> Dict[str, Any]:\n        \"\"\"Generate summary cost report.\"\"\"\n        summary = self.calculator.calculate_estimate(items)\n\n        return {\n            'report_date': datetime.now().isoformat(),\n            'currency': summary.currency,\n            'total_cost': round(summary.total_cost, 2),\n            'breakdown': {\n                'labor': round(summary.labor_total, 2),\n                'material': round(summary.material_total, 2),\n                'equipment': round(summary.equipment_total, 2),\n                'overhead': round(summary.overhead_total, 2),\n                'profit': round(summary.profit_total, 2)\n            },\n            'percentages': {\n                'labor': round(summary.labor_total / summary.total_cost * 100, 1) if summary.total_cost > 0 else 0,\n                'material': round(summary.material_total / summary.total_cost * 100, 1) if summary.total_cost > 0 else 0,\n                'equipment': round(summary.equipment_total / summary.total_cost * 100, 1) if summary.total_cost > 0 else 0,\n            },\n            'item_count': summary.item_count,\n            'by_category': summary.breakdown_by_category\n        }\n\n    def generate_detailed_report(self, items: List[Dict[str, Any]]) -> pd.DataFrame:\n        \"\"\"Generate detailed line-item report.\"\"\"\n        results = []\n\n        for item in items:\n            code = item.get('work_item_code') or item.get('code')\n            qty = item.get('quantity', 0)\n\n            breakdown = self.calculator.calculate_item_cost(code, qty)\n            results.append(breakdown.to_dict())\n\n        df = pd.DataFrame(results)\n\n        # Add totals row\n        totals = df[['labor_cost', 'material_cost', 'equipment_cost',\n                     'overhead_cost', 'profit_cost', 'total_cost']].sum()\n        totals['description'] = 'TOTAL'\n        totals['work_item_code'] = ''\n\n        df = pd.concat([df, pd.DataFrame([totals])], ignore_index=True)\n\n        return df\n\n\n# Convenience functions\ndef calculate_cost(cwicr_data: pd.DataFrame,\n                   work_item_code: str,\n                   quantity: float) -> float:\n    \"\"\"Quick cost calculation.\"\"\"\n    calc = CWICRCostCalculator(cwicr_data)\n    breakdown = calc.calculate_item_cost(work_item_code, quantity)\n    return breakdown.total_cost\n\n\ndef estimate_project_cost(cwicr_data: pd.DataFrame,\n                         items: List[Dict[str, Any]]) -> Dict[str, Any]:\n    \"\"\"Quick project cost estimate.\"\"\"\n    calc = CWICRCostCalculator(cwicr_data)\n    report = CostReportGenerator(calc)\n    return report.generate_summary_report(items)\n\nQuick Start\nimport pandas as pd\nfrom cwicr_data_loader import CWICRDataLoader\n\n# Load CWICR data\nloader = CWICRDataLoader()\ncwicr = loader.load(\"ddc_cwicr_en.parquet\")\n\n# Initialize calculator\ncalc = CWICRCostCalculator(cwicr)\n\n# Calculate single item\nbreakdown = calc.calculate_item_cost(\"CONC-001\", quantity=150)\nprint(f\"Total: ${breakdown.total_cost:,.2f}\")\nprint(f\"  Labor: ${breakdown.labor_cost:,.2f}\")\nprint(f\"  Material: ${breakdown.material_cost:,.2f}\")\nprint(f\"  Equipment: ${breakdown.equipment_cost:,.2f}\")\n\nCommon Use Cases\n1. Project Estimate\nitems = [\n    {'work_item_code': 'CONC-001', 'quantity': 150},\n    {'work_item_code': 'EXCV-002', 'quantity': 200},\n    {'work_item_code': 'REBAR-003', 'quantity': 15000}  # kg\n]\n\nsummary = calc.calculate_estimate(items)\nprint(f\"Project Total: ${summary.total_cost:,.2f}\")\n\n2. QTO Integration\n# Load BIM quantities\nqto = pd.read_excel(\"quantities.xlsx\")\n\n# Calculate costs\ncosts = calc.calculate_from_qto(qto,\n    code_column='work_item',\n    quantity_column='quantity'\n)\nprint(costs[['description', 'quantity', 'total_cost']])\n\n3. Regional Adjustment\n# Apply Berlin pricing\nberlin_factors = {\n    'labor': 1.15,      # 15% higher labor\n    'material': 0.95,   # 5% lower materials\n    'equipment': 1.0\n}\n\nadjusted = calc.apply_regional_factors(costs, berlin_factors)\n\nResources\nGitHub: OpenConstructionEstimate-DDC-CWICR\nDDC Book: Chapter 3.1 - Construction Cost Estimation"
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/datadrivenconstruction/cwicr-cost-calculator",
    "publisherUrl": "https://clawhub.ai/datadrivenconstruction/cwicr-cost-calculator",
    "owner": "datadrivenconstruction",
    "version": "2.1.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/cwicr-cost-calculator",
    "downloadUrl": "https://openagent3.xyz/downloads/cwicr-cost-calculator",
    "agentUrl": "https://openagent3.xyz/skills/cwicr-cost-calculator/agent",
    "manifestUrl": "https://openagent3.xyz/skills/cwicr-cost-calculator/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/cwicr-cost-calculator/agent.md"
  }
}