[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6FK432X1EP1SRKB80MFM7H8":3,"skill-same:01M6FK432X1EP1SRKB80MFM7H8":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":27,"linkOnly":28,"markdownContent":29,"markdownBody":30,"frontMatter":31,"refName":33,"commitSha":34,"skillDirectory":35,"forksCount":36,"repositoryHtmlUrl":37,"repositoryHomepageUrl":6,"ownerHtmlUrl":38,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":39,"install":40,"resources":53},"01M6FK432X1EP1SRKB80MFM7H8","resource-allocation-optimizer",null,"Optimize construction resource allocation across activities. Level resources, resolve over-allocations, and balance workload while minimizing schedule impact.","kbarbel640-del\u002Fskills","kbarbel640-del","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F255315490?v=4","01M6CJPPQGCCESXMG3K7BBGQ5J","01M6CJPPX2PB2BCZERFVM2C2B3",1,"MIT","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fresource-allocation-optimizer\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26],"optimizer","resource allocation","resource allocation optimizer","workload","schedule","optimize","across","impact","resources","2026-11-10 10:12:30",false,"---\r\nslug: \"resource-allocation-optimizer\"\r\ndisplay_name: \"Resource Allocation Optimizer\"\r\ndescription: \"Optimize construction resource allocation across activities. Level resources, resolve over-allocations, and balance workload while minimizing schedule impact.\"\r\n---\r\n\r\n# Resource Allocation Optimizer\r\n\r\n## Overview\r\n\r\nOptimize resource allocation in construction schedules. Level workforce and equipment utilization, resolve over-allocations, and balance workload across the project duration.\r\n\r\n> \"Resource leveling reduces peak demand by 30% and improves productivity\" — DDC Community\r\n\r\n## Resource Leveling Concept\r\n\r\n```\r\nBefore Leveling:                    After Leveling:\r\nWorkers                             Workers\r\n  20│    ████                         15│  ████████████\r\n  15│  ████████                        10│████████████████\r\n  10│████████████                       5│████████████████████\r\n   5│██████████████████                 0└──────────────────────\r\n   0└────────────────────                  Week 1  2  3  4  5  6\r\n      Week 1  2  3  4  5\r\n                                       Peak reduced, duration extended\r\n```\r\n\r\n## Technical Implementation\r\n\r\n```python\r\nfrom dataclasses import dataclass, field\r\nfrom typing import List, Dict, Optional, Tuple\r\nfrom datetime import datetime, timedelta\r\nfrom collections import defaultdict\r\nimport heapq\r\n\r\n@dataclass\r\nclass Resource:\r\n    id: str\r\n    name: str\r\n    resource_type: str  # labor, equipment, material\r\n    capacity: float  # units available per day\r\n    cost_per_unit: float = 0.0\r\n    skills: List[str] = field(default_factory=list)\r\n\r\n@dataclass\r\nclass ResourceAssignment:\r\n    activity_id: str\r\n    resource_id: str\r\n    units: float  # units required per day\r\n    start_day: int\r\n    end_day: int\r\n\r\n@dataclass\r\nclass Activity:\r\n    id: str\r\n    name: str\r\n    duration: int\r\n    early_start: int\r\n    late_start: int\r\n    total_float: int\r\n    resource_requirements: Dict[str, float] = field(default_factory=dict)\r\n    is_critical: bool = False\r\n\r\n@dataclass\r\nclass ResourceProfile:\r\n    resource_id: str\r\n    daily_usage: Dict[int, float]  # day -> units used\r\n    peak_usage: float\r\n    average_usage: float\r\n    utilization_rate: float\r\n\r\n@dataclass\r\nclass LevelingResult:\r\n    original_duration: int\r\n    new_duration: int\r\n    activities_shifted: List[Tuple[str, int, int]]  # (id, old_start, new_start)\r\n    resource_profiles: Dict[str, ResourceProfile]\r\n    peak_reduction: Dict[str, float]\r\n\r\nclass ResourceOptimizer:\r\n    \"\"\"Optimize construction resource allocation.\"\"\"\r\n\r\n    def __init__(self):\r\n        self.resources: Dict[str, Resource] = {}\r\n        self.activities: Dict[str, Activity] = {}\r\n        self.assignments: List[ResourceAssignment] = []\r\n\r\n    def add_resource(self, id: str, name: str, resource_type: str,\r\n                    capacity: float, cost_per_unit: float = 0.0,\r\n                    skills: List[str] = None) -> Resource:\r\n        \"\"\"Add resource to pool.\"\"\"\r\n        resource = Resource(\r\n            id=id,\r\n            name=name,\r\n            resource_type=resource_type,\r\n            capacity=capacity,\r\n            cost_per_unit=cost_per_unit,\r\n            skills=skills or []\r\n        )\r\n        self.resources[id] = resource\r\n        return resource\r\n\r\n    def add_activity(self, id: str, name: str, duration: int,\r\n                    early_start: int, late_start: int,\r\n                    resource_requirements: Dict[str, float] = None,\r\n                    is_critical: bool = False) -> Activity:\r\n        \"\"\"Add activity with resource requirements.\"\"\"\r\n        activity = Activity(\r\n            id=id,\r\n            name=name,\r\n            duration=duration,\r\n            early_start=early_start,\r\n            late_start=late_start,\r\n            total_float=late_start - early_start,\r\n            resource_requirements=resource_requirements or {},\r\n            is_critical=is_critical\r\n        )\r\n        self.activities[id] = activity\r\n\r\n        # Create assignments\r\n        for res_id, units in activity.resource_requirements.items():\r\n            assignment = ResourceAssignment(\r\n                activity_id=id,\r\n                resource_id=res_id,\r\n                units=units,\r\n                start_day=early_start,\r\n                end_day=early_start + duration\r\n            )\r\n            self.assignments.append(assignment)\r\n\r\n        return activity\r\n\r\n    def calculate_resource_profile(self, resource_id: str,\r\n                                  activity_starts: Dict[str, int] = None) -> ResourceProfile:\r\n        \"\"\"Calculate daily resource usage profile.\"\"\"\r\n        if resource_id not in self.resources:\r\n            raise ValueError(f\"Resource {resource_id} not found\")\r\n\r\n        resource = self.resources[resource_id]\r\n        daily_usage = defaultdict(float)\r\n\r\n        # Use provided starts or early starts\r\n        starts = activity_starts or {act.id: act.early_start for act in self.activities.values()}\r\n\r\n        for assignment in self.assignments:\r\n            if assignment.resource_id != resource_id:\r\n                continue\r\n\r\n            act_start = starts.get(assignment.activity_id, assignment.start_day)\r\n            act = self.activities[assignment.activity_id]\r\n\r\n            for day in range(act_start, act_start + act.duration):\r\n                daily_usage[day] += assignment.units\r\n\r\n        usage_values = list(daily_usage.values()) if daily_usage else [0]\r\n        project_duration = max(daily_usage.keys()) + 1 if daily_usage else 0\r\n\r\n        return ResourceProfile(\r\n            resource_id=resource_id,\r\n            daily_usage=dict(daily_usage),\r\n            peak_usage=max(usage_values),\r\n            average_usage=sum(usage_values) \u002F len(usage_values) if usage_values else 0,\r\n            utilization_rate=sum(usage_values) \u002F (project_duration * resource.capacity) if project_duration else 0\r\n        )\r\n\r\n    def identify_overallocations(self) -> Dict[str, List[Tuple[int, float]]]:\r\n        \"\"\"Identify days where resources are over-allocated.\"\"\"\r\n        overallocations = {}\r\n\r\n        for resource in self.resources.values():\r\n            profile = self.calculate_resource_profile(resource.id)\r\n            over_days = [\r\n                (day, usage - resource.capacity)\r\n                for day, usage in profile.daily_usage.items()\r\n                if usage > resource.capacity\r\n            ]\r\n            if over_days:\r\n                overallocations[resource.id] = over_days\r\n\r\n        return overallocations\r\n\r\n    def level_resources(self, resource_ids: List[str] = None,\r\n                       allow_duration_extension: bool = True,\r\n                       max_extension_days: int = 30) -> LevelingResult:\r\n        \"\"\"Level resources by shifting non-critical activities.\"\"\"\r\n        resource_ids = resource_ids or list(self.resources.keys())\r\n\r\n        # Store original starts\r\n        original_starts = {act.id: act.early_start for act in self.activities.values()}\r\n        original_duration = max(act.early_start + act.duration for act in self.activities.values())\r\n\r\n        # Current activity starts (will be modified)\r\n        current_starts = dict(original_starts)\r\n\r\n        # Sort activities by float (most float = most flexibility)\r\n        sorted_activities = sorted(\r\n            [a for a in self.activities.values() if not a.is_critical],\r\n            key=lambda a: -a.total_float\r\n        )\r\n\r\n        activities_shifted = []\r\n\r\n        # Iteratively resolve overallocations\r\n        for _ in range(100):  # Max iterations\r\n            overallocations = self._check_overallocations(current_starts, resource_ids)\r\n\r\n            if not overallocations:\r\n                break\r\n\r\n            # Find activity to shift\r\n            shifted = False\r\n            for act in sorted_activities:\r\n                if act.id in [o[0] for o in overallocations]:\r\n                    # Try to shift this activity\r\n                    new_start = self._find_valid_start(\r\n                        act, current_starts, resource_ids,\r\n                        allow_duration_extension, max_extension_days\r\n                    )\r\n\r\n                    if new_start is not None and new_start != current_starts[act.id]:\r\n                        old_start = current_starts[act.id]\r\n                        current_starts[act.id] = new_start\r\n                        activities_shifted.append((act.id, old_start, new_start))\r\n                        shifted = True\r\n                        break\r\n\r\n            if not shifted:\r\n                break\r\n\r\n        # Calculate new duration and profiles\r\n        new_duration = max(\r\n            current_starts[act.id] + act.duration\r\n            for act in self.activities.values()\r\n        )\r\n\r\n        resource_profiles = {}\r\n        peak_reduction = {}\r\n\r\n        for res_id in resource_ids:\r\n            original_profile = self.calculate_resource_profile(res_id, original_starts)\r\n            new_profile = self.calculate_resource_profile(res_id, current_starts)\r\n            resource_profiles[res_id] = new_profile\r\n            peak_reduction[res_id] = original_profile.peak_usage - new_profile.peak_usage\r\n\r\n        return LevelingResult(\r\n            original_duration=original_duration,\r\n            new_duration=new_duration,\r\n            activities_shifted=activities_shifted,\r\n            resource_profiles=resource_profiles,\r\n            peak_reduction=peak_reduction\r\n        )\r\n\r\n    def _check_overallocations(self, starts: Dict[str, int],\r\n                               resource_ids: List[str]) -> List[Tuple[str, int, str]]:\r\n        \"\"\"Check for overallocations with given starts.\"\"\"\r\n        overallocations = []\r\n\r\n        for res_id in resource_ids:\r\n            resource = self.resources[res_id]\r\n            daily_usage = defaultdict(list)\r\n\r\n            for assignment in self.assignments:\r\n                if assignment.resource_id != res_id:\r\n                    continue\r\n\r\n                act = self.activities[assignment.activity_id]\r\n                act_start = starts[assignment.activity_id]\r\n\r\n                for day in range(act_start, act_start + act.duration):\r\n                    daily_usage[day].append((assignment.activity_id, assignment.units))\r\n\r\n            for day, activities in daily_usage.items():\r\n                total = sum(units for _, units in activities)\r\n                if total > resource.capacity:\r\n                    for act_id, _ in activities:\r\n                        overallocations.append((act_id, day, res_id))\r\n\r\n        return overallocations\r\n\r\n    def _find_valid_start(self, activity: Activity, current_starts: Dict[str, int],\r\n                         resource_ids: List[str], allow_extension: bool,\r\n                         max_extension: int) -> Optional[int]:\r\n        \"\"\"Find valid start day that doesn't cause overallocation.\"\"\"\r\n        min_start = activity.early_start\r\n        max_start = activity.late_start if not allow_extension else activity.late_start + max_extension\r\n\r\n        for start in range(min_start, max_start + 1):\r\n            # Check if this start causes overallocation\r\n            test_starts = dict(current_starts)\r\n            test_starts[activity.id] = start\r\n\r\n            overallocations = self._check_overallocations(test_starts, resource_ids)\r\n            activity_over = [o for o in overallocations if o[0] == activity.id]\r\n\r\n            if not activity_over:\r\n                return start\r\n\r\n        return None\r\n\r\n    def optimize_for_cost(self, target_duration: int = None) -> Dict:\r\n        \"\"\"Optimize resource allocation for minimum cost.\"\"\"\r\n        # Calculate baseline cost\r\n        baseline_cost = self._calculate_total_cost()\r\n\r\n        # Try different allocation strategies\r\n        strategies = []\r\n\r\n        # Strategy 1: Minimize overtime\r\n        overtime_result = self._minimize_overtime()\r\n        strategies.append({\r\n            \"strategy\": \"Minimize Overtime\",\r\n            \"cost\": overtime_result[\"cost\"],\r\n            \"duration\": overtime_result[\"duration\"]\r\n        })\r\n\r\n        # Strategy 2: Level resources\r\n        level_result = self.level_resources()\r\n        level_cost = self._calculate_total_cost(\r\n            {act.id: act.early_start for act in self.activities.values()}\r\n        )\r\n        strategies.append({\r\n            \"strategy\": \"Level Resources\",\r\n            \"cost\": level_cost,\r\n            \"duration\": level_result.new_duration\r\n        })\r\n\r\n        return {\r\n            \"baseline_cost\": baseline_cost,\r\n            \"strategies\": strategies,\r\n            \"recommended\": min(strategies, key=lambda s: s[\"cost\"])\r\n        }\r\n\r\n    def _calculate_total_cost(self, starts: Dict[str, int] = None) -> float:\r\n        \"\"\"Calculate total resource cost.\"\"\"\r\n        starts = starts or {act.id: act.early_start for act in self.activities.values()}\r\n        total_cost = 0.0\r\n\r\n        for res_id, resource in self.resources.items():\r\n            profile = self.calculate_resource_profile(res_id, starts)\r\n\r\n            for day, usage in profile.daily_usage.items():\r\n                # Regular cost\r\n                regular_units = min(usage, resource.capacity)\r\n                total_cost += regular_units * resource.cost_per_unit\r\n\r\n                # Overtime cost (1.5x)\r\n                overtime_units = max(0, usage - resource.capacity)\r\n                total_cost += overtime_units * resource.cost_per_unit * 1.5\r\n\r\n        return total_cost\r\n\r\n    def _minimize_overtime(self) -> Dict:\r\n        \"\"\"Minimize overtime by resource leveling.\"\"\"\r\n        result = self.level_resources(allow_duration_extension=True)\r\n        cost = self._calculate_total_cost(\r\n            {act.id: act.early_start for act in self.activities.values()}\r\n        )\r\n        return {\"cost\": cost, \"duration\": result.new_duration}\r\n\r\n    def generate_resource_histogram(self, resource_id: str,\r\n                                   starts: Dict[str, int] = None) -> str:\r\n        \"\"\"Generate ASCII histogram of resource usage.\"\"\"\r\n        profile = self.calculate_resource_profile(resource_id, starts)\r\n        resource = self.resources[resource_id]\r\n\r\n        if not profile.daily_usage:\r\n            return \"No usage data\"\r\n\r\n        max_day = max(profile.daily_usage.keys())\r\n        max_usage = max(profile.daily_usage.values())\r\n\r\n        lines = [\r\n            f\"# Resource Histogram: {resource.name}\",\r\n            f\"Capacity: {resource.capacity} | Peak: {profile.peak_usage}\",\r\n            \"\"\r\n        ]\r\n\r\n        # Scale for display\r\n        scale = 20 \u002F max_usage if max_usage > 0 else 1\r\n\r\n        for day in range(max_day + 1):\r\n            usage = profile.daily_usage.get(day, 0)\r\n            bar_len = int(usage * scale)\r\n            over = \"!\" if usage > resource.capacity else \" \"\r\n            lines.append(f\"Day {day:3d}: {'█' * bar_len}{over} ({usage:.1f})\")\r\n\r\n        return \"\\n\".join(lines)\r\n```\r\n\r\n## Quick Start\r\n\r\n```python\r\n# Initialize optimizer\r\noptimizer = ResourceOptimizer()\r\n\r\n# Add resources\r\noptimizer.add_resource(\"CARP\", \"Carpenters\", \"labor\", capacity=10, cost_per_unit=450)\r\noptimizer.add_resource(\"IRON\", \"Ironworkers\", \"labor\", capacity=8, cost_per_unit=550)\r\noptimizer.add_resource(\"CRANE\", \"Tower Crane\", \"equipment\", capacity=1, cost_per_unit=2500)\r\n\r\n# Add activities with resource requirements\r\noptimizer.add_activity(\r\n    \"A\", \"Foundation Forms\", duration=10,\r\n    early_start=0, late_start=0,\r\n    resource_requirements={\"CARP\": 8},\r\n    is_critical=True\r\n)\r\noptimizer.add_activity(\r\n    \"B\", \"Rebar Installation\", duration=8,\r\n    early_start=5, late_start=10,\r\n    resource_requirements={\"IRON\": 6, \"CRANE\": 1}\r\n)\r\noptimizer.add_activity(\r\n    \"C\", \"Steel Erection\", duration=15,\r\n    early_start=10, late_start=10,\r\n    resource_requirements={\"IRON\": 10, \"CRANE\": 1},\r\n    is_critical=True\r\n)\r\n\r\n# Check for overallocations\r\noverallocations = optimizer.identify_overallocations()\r\nfor res_id, days in overallocations.items():\r\n    print(f\"{res_id} over-allocated on days: {[d[0] for d in days]}\")\r\n\r\n# Level resources\r\nresult = optimizer.level_resources()\r\nprint(f\"Duration change: {result.original_duration} → {result.new_duration} days\")\r\nprint(f\"Activities shifted: {len(result.activities_shifted)}\")\r\n\r\nfor res_id, reduction in result.peak_reduction.items():\r\n    print(f\"{res_id} peak reduced by: {reduction:.1f} units\")\r\n\r\n# Generate histogram\r\nprint(optimizer.generate_resource_histogram(\"IRON\"))\r\n```\r\n\r\n## Requirements\r\n\r\n```bash\r\npip install (no external dependencies)\r\n```\r\n","# Resource Allocation Optimizer\r\n\r\n## Overview\r\n\r\nOptimize resource allocation in construction schedules. Level workforce and equipment utilization, resolve over-allocations, and balance workload across the project duration.\r\n\r\n> \"Resource leveling reduces peak demand by 30% and improves productivity\" — DDC Community\r\n\r\n## Resource Leveling Concept\r\n\r\n```\r\nBefore Leveling:                    After Leveling:\r\nWorkers                             Workers\r\n  20│    ████                         15│  ████████████\r\n  15│  ████████                        10│████████████████\r\n  10│████████████                       5│████████████████████\r\n   5│██████████████████                 0└──────────────────────\r\n   0└────────────────────                  Week 1  2  3  4  5  6\r\n      Week 1  2  3  4  5\r\n                                       Peak reduced, duration extended\r\n```\r\n\r\n## Technical Implementation\r\n\r\n```python\r\nfrom dataclasses import dataclass, field\r\nfrom typing import List, Dict, Optional, Tuple\r\nfrom datetime import datetime, timedelta\r\nfrom collections import defaultdict\r\nimport heapq\r\n\r\n@dataclass\r\nclass Resource:\r\n    id: str\r\n    name: str\r\n    resource_type: str  # labor, equipment, material\r\n    capacity: float  # units available per day\r\n    cost_per_unit: float = 0.0\r\n    skills: List[str] = field(default_factory=list)\r\n\r\n@dataclass\r\nclass ResourceAssignment:\r\n    activity_id: str\r\n    resource_id: str\r\n    units: float  # units required per day\r\n    start_day: int\r\n    end_day: int\r\n\r\n@dataclass\r\nclass Activity:\r\n    id: str\r\n    name: str\r\n    duration: int\r\n    early_start: int\r\n    late_start: int\r\n    total_float: int\r\n    resource_requirements: Dict[str, float] = field(default_factory=dict)\r\n    is_critical: bool = False\r\n\r\n@dataclass\r\nclass ResourceProfile:\r\n    resource_id: str\r\n    daily_usage: Dict[int, float]  # day -> units used\r\n    peak_usage: float\r\n    average_usage: float\r\n    utilization_rate: float\r\n\r\n@dataclass\r\nclass LevelingResult:\r\n    original_duration: int\r\n    new_duration: int\r\n    activities_shifted: List[Tuple[str, int, int]]  # (id, old_start, new_start)\r\n    resource_profiles: Dict[str, ResourceProfile]\r\n    peak_reduction: Dict[str, float]\r\n\r\nclass ResourceOptimizer:\r\n    \"\"\"Optimize construction resource allocation.\"\"\"\r\n\r\n    def __init__(self):\r\n        self.resources: Dict[str, Resource] = {}\r\n        self.activities: Dict[str, Activity] = {}\r\n        self.assignments: List[ResourceAssignment] = []\r\n\r\n    def add_resource(self, id: str, name: str, resource_type: str,\r\n                    capacity: float, cost_per_unit: float = 0.0,\r\n                    skills: List[str] = None) -> Resource:\r\n        \"\"\"Add resource to pool.\"\"\"\r\n        resource = Resource(\r\n            id=id,\r\n            name=name,\r\n            resource_type=resource_type,\r\n            capacity=capacity,\r\n            cost_per_unit=cost_per_unit,\r\n            skills=skills or []\r\n        )\r\n        self.resources[id] = resource\r\n        return resource\r\n\r\n    def add_activity(self, id: str, name: str, duration: int,\r\n                    early_start: int, late_start: int,\r\n                    resource_requirements: Dict[str, float] = None,\r\n                    is_critical: bool = False) -> Activity:\r\n        \"\"\"Add activity with resource requirements.\"\"\"\r\n        activity = Activity(\r\n            id=id,\r\n            name=name,\r\n            duration=duration,\r\n            early_start=early_start,\r\n            late_start=late_start,\r\n            total_float=late_start - early_start,\r\n            resource_requirements=resource_requirements or {},\r\n            is_critical=is_critical\r\n        )\r\n        self.activities[id] = activity\r\n\r\n        # Create assignments\r\n        for res_id, units in activity.resource_requirements.items():\r\n            assignment = ResourceAssignment(\r\n                activity_id=id,\r\n                resource_id=res_id,\r\n                units=units,\r\n                start_day=early_start,\r\n                end_day=early_start + duration\r\n            )\r\n            self.assignments.append(assignment)\r\n\r\n        return activity\r\n\r\n    def calculate_resource_profile(self, resource_id: str,\r\n                                  activity_starts: Dict[str, int] = None) -> ResourceProfile:\r\n        \"\"\"Calculate daily resource usage profile.\"\"\"\r\n        if resource_id not in self.resources:\r\n            raise ValueError(f\"Resource {resource_id} not found\")\r\n\r\n        resource = self.resources[resource_id]\r\n        daily_usage = defaultdict(float)\r\n\r\n        # Use provided starts or early starts\r\n        starts = activity_starts or {act.id: act.early_start for act in self.activities.values()}\r\n\r\n        for assignment in self.assignments:\r\n            if assignment.resource_id != resource_id:\r\n                continue\r\n\r\n            act_start = starts.get(assignment.activity_id, assignment.start_day)\r\n            act = self.activities[assignment.activity_id]\r\n\r\n            for day in range(act_start, act_start + act.duration):\r\n                daily_usage[day] += assignment.units\r\n\r\n        usage_values = list(daily_usage.values()) if daily_usage else [0]\r\n        project_duration = max(daily_usage.keys()) + 1 if daily_usage else 0\r\n\r\n        return ResourceProfile(\r\n            resource_id=resource_id,\r\n            daily_usage=dict(daily_usage),\r\n            peak_usage=max(usage_values),\r\n            average_usage=sum(usage_values) \u002F len(usage_values) if usage_values else 0,\r\n            utilization_rate=sum(usage_values) \u002F (project_duration * resource.capacity) if project_duration else 0\r\n        )\r\n\r\n    def identify_overallocations(self) -> Dict[str, List[Tuple[int, float]]]:\r\n        \"\"\"Identify days where resources are over-allocated.\"\"\"\r\n        overallocations = {}\r\n\r\n        for resource in self.resources.values():\r\n            profile = self.calculate_resource_profile(resource.id)\r\n            over_days = [\r\n                (day, usage - resource.capacity)\r\n                for day, usage in profile.daily_usage.items()\r\n                if usage > resource.capacity\r\n            ]\r\n            if over_days:\r\n                overallocations[resource.id] = over_days\r\n\r\n        return overallocations\r\n\r\n    def level_resources(self, resource_ids: List[str] = None,\r\n                       allow_duration_extension: bool = True,\r\n                       max_extension_days: int = 30) -> LevelingResult:\r\n        \"\"\"Level resources by shifting non-critical activities.\"\"\"\r\n        resource_ids = resource_ids or list(self.resources.keys())\r\n\r\n        # Store original starts\r\n        original_starts = {act.id: act.early_start for act in self.activities.values()}\r\n        original_duration = max(act.early_start + act.duration for act in self.activities.values())\r\n\r\n        # Current activity starts (will be modified)\r\n        current_starts = dict(original_starts)\r\n\r\n        # Sort activities by float (most float = most flexibility)\r\n        sorted_activities = sorted(\r\n            [a for a in self.activities.values() if not a.is_critical],\r\n            key=lambda a: -a.total_float\r\n        )\r\n\r\n        activities_shifted = []\r\n\r\n        # Iteratively resolve overallocations\r\n        for _ in range(100):  # Max iterations\r\n            overallocations = self._check_overallocations(current_starts, resource_ids)\r\n\r\n            if not overallocations:\r\n                break\r\n\r\n            # Find activity to shift\r\n            shifted = False\r\n            for act in sorted_activities:\r\n                if act.id in [o[0] for o in overallocations]:\r\n                    # Try to shift this activity\r\n                    new_start = self._find_valid_start(\r\n                        act, current_starts, resource_ids,\r\n                        allow_duration_extension, max_extension_days\r\n                    )\r\n\r\n                    if new_start is not None and new_start != current_starts[act.id]:\r\n                        old_start = current_starts[act.id]\r\n                        current_starts[act.id] = new_start\r\n                        activities_shifted.append((act.id, old_start, new_start))\r\n                        shifted = True\r\n                        break\r\n\r\n            if not shifted:\r\n                break\r\n\r\n        # Calculate new duration and profiles\r\n        new_duration = max(\r\n            current_starts[act.id] + act.duration\r\n            for act in self.activities.values()\r\n        )\r\n\r\n        resource_profiles = {}\r\n        peak_reduction = {}\r\n\r\n        for res_id in resource_ids:\r\n            original_profile = self.calculate_resource_profile(res_id, original_starts)\r\n            new_profile = self.calculate_resource_profile(res_id, current_starts)\r\n            resource_profiles[res_id] = new_profile\r\n            peak_reduction[res_id] = original_profile.peak_usage - new_profile.peak_usage\r\n\r\n        return LevelingResult(\r\n            original_duration=original_duration,\r\n            new_duration=new_duration,\r\n            activities_shifted=activities_shifted,\r\n            resource_profiles=resource_profiles,\r\n            peak_reduction=peak_reduction\r\n        )\r\n\r\n    def _check_overallocations(self, starts: Dict[str, int],\r\n                               resource_ids: List[str]) -> List[Tuple[str, int, str]]:\r\n        \"\"\"Check for overallocations with given starts.\"\"\"\r\n        overallocations = []\r\n\r\n        for res_id in resource_ids:\r\n            resource = self.resources[res_id]\r\n            daily_usage = defaultdict(list)\r\n\r\n            for assignment in self.assignments:\r\n                if assignment.resource_id != res_id:\r\n                    continue\r\n\r\n                act = self.activities[assignment.activity_id]\r\n                act_start = starts[assignment.activity_id]\r\n\r\n                for day in range(act_start, act_start + act.duration):\r\n                    daily_usage[day].append((assignment.activity_id, assignment.units))\r\n\r\n            for day, activities in daily_usage.items():\r\n                total = sum(units for _, units in activities)\r\n                if total > resource.capacity:\r\n                    for act_id, _ in activities:\r\n                        overallocations.append((act_id, day, res_id))\r\n\r\n        return overallocations\r\n\r\n    def _find_valid_start(self, activity: Activity, current_starts: Dict[str, int],\r\n                         resource_ids: List[str], allow_extension: bool,\r\n                         max_extension: int) -> Optional[int]:\r\n        \"\"\"Find valid start day that doesn't cause overallocation.\"\"\"\r\n        min_start = activity.early_start\r\n        max_start = activity.late_start if not allow_extension else activity.late_start + max_extension\r\n\r\n        for start in range(min_start, max_start + 1):\r\n            # Check if this start causes overallocation\r\n            test_starts = dict(current_starts)\r\n            test_starts[activity.id] = start\r\n\r\n            overallocations = self._check_overallocations(test_starts, resource_ids)\r\n            activity_over = [o for o in overallocations if o[0] == activity.id]\r\n\r\n            if not activity_over:\r\n                return start\r\n\r\n        return None\r\n\r\n    def optimize_for_cost(self, target_duration: int = None) -> Dict:\r\n        \"\"\"Optimize resource allocation for minimum cost.\"\"\"\r\n        # Calculate baseline cost\r\n        baseline_cost = self._calculate_total_cost()\r\n\r\n        # Try different allocation strategies\r\n        strategies = []\r\n\r\n        # Strategy 1: Minimize overtime\r\n        overtime_result = self._minimize_overtime()\r\n        strategies.append({\r\n            \"strategy\": \"Minimize Overtime\",\r\n            \"cost\": overtime_result[\"cost\"],\r\n            \"duration\": overtime_result[\"duration\"]\r\n        })\r\n\r\n        # Strategy 2: Level resources\r\n        level_result = self.level_resources()\r\n        level_cost = self._calculate_total_cost(\r\n            {act.id: act.early_start for act in self.activities.values()}\r\n        )\r\n        strategies.append({\r\n            \"strategy\": \"Level Resources\",\r\n            \"cost\": level_cost,\r\n            \"duration\": level_result.new_duration\r\n        })\r\n\r\n        return {\r\n            \"baseline_cost\": baseline_cost,\r\n            \"strategies\": strategies,\r\n            \"recommended\": min(strategies, key=lambda s: s[\"cost\"])\r\n        }\r\n\r\n    def _calculate_total_cost(self, starts: Dict[str, int] = None) -> float:\r\n        \"\"\"Calculate total resource cost.\"\"\"\r\n        starts = starts or {act.id: act.early_start for act in self.activities.values()}\r\n        total_cost = 0.0\r\n\r\n        for res_id, resource in self.resources.items():\r\n            profile = self.calculate_resource_profile(res_id, starts)\r\n\r\n            for day, usage in profile.daily_usage.items():\r\n                # Regular cost\r\n                regular_units = min(usage, resource.capacity)\r\n                total_cost += regular_units * resource.cost_per_unit\r\n\r\n                # Overtime cost (1.5x)\r\n                overtime_units = max(0, usage - resource.capacity)\r\n                total_cost += overtime_units * resource.cost_per_unit * 1.5\r\n\r\n        return total_cost\r\n\r\n    def _minimize_overtime(self) -> Dict:\r\n        \"\"\"Minimize overtime by resource leveling.\"\"\"\r\n        result = self.level_resources(allow_duration_extension=True)\r\n        cost = self._calculate_total_cost(\r\n            {act.id: act.early_start for act in self.activities.values()}\r\n        )\r\n        return {\"cost\": cost, \"duration\": result.new_duration}\r\n\r\n    def generate_resource_histogram(self, resource_id: str,\r\n                                   starts: Dict[str, int] = None) -> str:\r\n        \"\"\"Generate ASCII histogram of resource usage.\"\"\"\r\n        profile = self.calculate_resource_profile(resource_id, starts)\r\n        resource = self.resources[resource_id]\r\n\r\n        if not profile.daily_usage:\r\n            return \"No usage data\"\r\n\r\n        max_day = max(profile.daily_usage.keys())\r\n        max_usage = max(profile.daily_usage.values())\r\n\r\n        lines = [\r\n            f\"# Resource Histogram: {resource.name}\",\r\n            f\"Capacity: {resource.capacity} | Peak: {profile.peak_usage}\",\r\n            \"\"\r\n        ]\r\n\r\n        # Scale for display\r\n        scale = 20 \u002F max_usage if max_usage > 0 else 1\r\n\r\n        for day in range(max_day + 1):\r\n            usage = profile.daily_usage.get(day, 0)\r\n            bar_len = int(usage * scale)\r\n            over = \"!\" if usage > resource.capacity else \" \"\r\n            lines.append(f\"Day {day:3d}: {'█' * bar_len}{over} ({usage:.1f})\")\r\n\r\n        return \"\\n\".join(lines)\r\n```\r\n\r\n## Quick Start\r\n\r\n```python\r\n# Initialize optimizer\r\noptimizer = ResourceOptimizer()\r\n\r\n# Add resources\r\noptimizer.add_resource(\"CARP\", \"Carpenters\", \"labor\", capacity=10, cost_per_unit=450)\r\noptimizer.add_resource(\"IRON\", \"Ironworkers\", \"labor\", capacity=8, cost_per_unit=550)\r\noptimizer.add_resource(\"CRANE\", \"Tower Crane\", \"equipment\", capacity=1, cost_per_unit=2500)\r\n\r\n# Add activities with resource requirements\r\noptimizer.add_activity(\r\n    \"A\", \"Foundation Forms\", duration=10,\r\n    early_start=0, late_start=0,\r\n    resource_requirements={\"CARP\": 8},\r\n    is_critical=True\r\n)\r\noptimizer.add_activity(\r\n    \"B\", \"Rebar Installation\", duration=8,\r\n    early_start=5, late_start=10,\r\n    resource_requirements={\"IRON\": 6, \"CRANE\": 1}\r\n)\r\noptimizer.add_activity(\r\n    \"C\", \"Steel Erection\", duration=15,\r\n    early_start=10, late_start=10,\r\n    resource_requirements={\"IRON\": 10, \"CRANE\": 1},\r\n    is_critical=True\r\n)\r\n\r\n# Check for overallocations\r\noverallocations = optimizer.identify_overallocations()\r\nfor res_id, days in overallocations.items():\r\n    print(f\"{res_id} over-allocated on days: {[d[0] for d in days]}\")\r\n\r\n# Level resources\r\nresult = optimizer.level_resources()\r\nprint(f\"Duration change: {result.original_duration} → {result.new_duration} days\")\r\nprint(f\"Activities shifted: {len(result.activities_shifted)}\")\r\n\r\nfor res_id, reduction in result.peak_reduction.items():\r\n    print(f\"{res_id} peak reduced by: {reduction:.1f} units\")\r\n\r\n# Generate histogram\r\nprint(optimizer.generate_resource_histogram(\"IRON\"))\r\n```\r\n\r\n## Requirements\r\n\r\n```bash\r\npip install (no external dependencies)\r\n```\r\n",{"slug":5,"description":7,"display_name":32},"Resource Allocation Optimizer","main","e7e336ac628c3e3bd771aff1aaa469c93778f94a","skills\u002Fdatadrivenconstruction\u002Fresource-allocation-optimizer",0,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del","2026-08-23 22:39:37",{"source":8,"skillName":5,"commands":41,"prompt":51,"zipAvailable":52},[42,45,48],{"tool":43,"command":44},"npx","npx skills add kbarbel640-del\u002Fskills --skill resource-allocation-optimizer",{"tool":46,"command":47},"bunx","bunx skills add kbarbel640-del\u002Fskills --skill resource-allocation-optimizer",{"tool":49,"command":50},"pnpm","pnpm dlx skills add kbarbel640-del\u002Fskills --skill resource-allocation-optimizer","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fresource-allocation-optimizer\u002FSKILL.md",true,[54],{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"_meta.json","REFERENCE","参考文档",326,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fresource-allocation-optimizer\u002F_meta.json",[61,87,111,129,134,154],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":27},"01M6G8J55967D6281ACMKAKTEQ","crowd-prompting","A marketplace where AI agents improve prompts, system instructions, tool descriptions, and other text-based content with domain expertise from real-world operations — and earn tokens for valuable contributions.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzzadrian\u002Fcrowd-prompting\u002FSKILL.md",[],[68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86],"crowd prompting","prompting","api","with","tokens","domain","world","prompts","operations","instructions","text","tool","system","improve","productivity","marketplace","https","content","ai agents",{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":27},"01M6G8J0PKPAYVET6BWE8W4C26","dilemm-ai","Compete in DilemmAI, the prisoner's dilemma AI arena at dilemm.ai. Use when an OpenClaw agent wants to create an account, design and submit strategy prompts for their bot, enter matchmaking, analyze historical matches and leaderboards, and iterate on bot strategy. Requires headless browser automation (no API available yet).","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzyori\u002Fdilemm-ai\u002FSKILL.md",[],[94,70,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,75,110],"dilemm ai","arena","analyze","browser","openclaw agent","create","automation","browser automation","bot","openclaw","design","strategy","headless","compete","submit","matchmaking","use",{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":27},"01M6G8HWAF3K9SW7NP3Z83CPJ6","arxiv-paper-reviews","Interact with arXiv Crawler API to fetch papers, read reviews, and submit comments. Use when working with arXiv papers, fetching paper lists by date\u002Fcategory\u002Finterest, viewing paper details with comments, or submitting paper reviews via API at http:\u002F\u002F150.158.152.82:8000.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Fweak-accept\u002FSKILL.md",[],[118,119,120,121,122,123,124,71,125,108,110,126,70,127,128],"arxiv paper reviews","reviews","arxiv","paper","crawler","papers","comments","fetch","read","http","via",{"skillNo":130,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":131,"categories":132,"keywords":133,"publishedAt":27},"01M6G8HQJ7N7WMY6YV7D7SSJ16","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Farxiv-paper-reviews\u002FSKILL.md",[],[121,120,119,118,128,123,124,71,122,108,110,125,126,70,127],{"skillNo":135,"name":136,"nameZh":6,"description":137,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":138,"categories":139,"keywords":140,"publishedAt":27},"01M6G8HM95Y64JNVFC2HN4E2BG","git-summary","Get a quick summary of the current Git repository including status, recent commits, branches, and contributors.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzweack\u002Fgit-summary\u002FSKILL.md",[],[141,142,143,144,145,146,147,148,149,150,151,152,153],"git","summary","git summary","commits","repository","win32","status","linux","contributors","true","quick","get","branches",{"skillNo":155,"name":156,"nameZh":6,"description":157,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":158,"categories":159,"keywords":160,"publishedAt":27},"01M6G8HGEGF05CNEJCGVYFSC4R","agent-constitution","Interact with AgentConstitution governance contracts on Base Sepolia. Check compliance, read rules, log actions, query governance state.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fztsalexey\u002Fagent-constitution\u002FSKILL.md",[],[161,162,163,164,71,165,166,33,167,126,168,169,170,171,172,84,173,174,175],"agent constitution","constitution","contracts","tree","query","base","log","check","Rules","projects","compliance","actions","state","governance","github"]