Advanced Textile Material Engineering, Optimization & Management System
[Version 7.0] [Python 3.8+] [Production Ready]
- Overview
- Features
- Installation
- Quick Start
- Core Modules
- Complete Tutorials
- Advanced Use Cases
- Optimization Strategies
- API Reference
- Best Practices
- Troubleshooting
- Contributing
===============================================================================
- OVERVIEW ===============================================================================
The Peanut Research Material Engineering Platform is a comprehensive, production-ready system for textile material research, development, and manufacturing optimization. Built with academic rigor and industry standards, it combines advanced material science, statistical analysis, and AI-powered recommendations.
- 378 Materials across 6 major categories
- 3,188 Optimization Results with validated performance data
- 50 Use Case Profiles for diverse applications
- 10 Fiber Types with complete chemistry data
- 15 Treatment Options with environmental impact analysis
- 16 Construction Methods with cost modeling
- 14 Testing Protocols (ASTM/AATCC compliant)
- 5 International Certifications tracked
- ASTM International Testing Standards
- AATCC (American Association of Textile Chemists and Colorists)
- ISO 9001:2015 Quality Management
- OEKO-TEX Standard 100
- Bluesign System
- GOTS (Global Organic Textile Standard)
- Material Specification Builder - Create complete technical specifications
- Multi-Criteria Search - Advanced filtering across 20+ properties
- Treatment Optimization - AI-powered optimization for target properties
- Blend Ratio Optimizer - Predict and optimize fiber blends
- Statistical Process Control (SPC) - Real-time quality monitoring
- Predictive Modeling - Linear regression, time series, Monte Carlo
- Multi-Objective Optimization - Pareto frontier analysis
- Confidence Intervals - Statistical significance testing
- Process Capability - Six Sigma methodology (Cp, Cpk, Pp, Ppk)
- Life Cycle Assessment (LCA) - ISO 14040:2006 carbon footprint
- Eco-Score Calculator - Comprehensive 0-100 sustainability rating
- Water Usage Tracking - Per-kg consumption analysis
- Biodegradability Assessment - End-of-life impact evaluation
- Certification Management - GOTS, Bluesign, OEKO-TEX tracking
- Inventory System - Real-time stock tracking with forecasting
- Quality Control - Defect tracking, batch compliance, SPC
- Supplier Management - Performance scorecards, cost comparison
- Document Generation - Excel, CSV, Markdown, RFQ formats
- Smart Recommendations - Context-aware material suggestions
- Property Prediction - ML-based performance forecasting
- Anomaly Detection - Out-of-control process identification
- Optimization Algorithms - Genetic algorithms for treatments
- Python 3.8 or higher
- Google Colab (recommended) or Jupyter Notebook
- Google Drive account (for data persistence)
Step 1: Clone the Repository
git clone https://github.com/pythpythpython/peanut-research.git
cd peanut-research
Step 2: Mount Google Drive (if using Colab)
from google.colab import drive
drive.mount('/content/drive')
Step 3: Install Dependencies
pip install pandas numpy matplotlib seaborn scipy openpyxl
Step 4: Run the Main System
# Execute the main unified system cell in the notebook
# All modules will initialize automatically
peanut-research/ ├── data/ │ ├── processed/ # Material databases (parquet files) │ ├── results/ # Optimization results │ ├── chemistry/ # Fiber chemistry, treatments, testing │ ├── suppliers/ # Supplier database & pricing │ ├── quality_control/ # QC standards & defect types │ └── inventory/ # Inventory & transaction data ├── config/ │ └── group*_use_cases.json # Use case profiles ├── exports/ # Generated documents ├── visualizations/ # Charts and dashboards ├── README.md # This file └── Clothing_Control_Center.ipynb # Main system notebook
spec = CompleteMaterialSpec('Supima Cotton')
spec.add_treatment('moisture_wicking')
spec.set_construction('jersey_knit')
spec.add_test('colorfastness_washing') spec.add_test('pilling_resistance')
spec.add_certification('oeko_tex_100')
properties = spec.calculate_upgraded_properties() cost = spec.calculate_total_cost(yards=1000)
print(f"Total Cost for 1000 yards: ${cost['total_cost_for_yards']:,.2f}")
search = AdvancedMaterialSearch()
results = search.search( min_softness=85, min_breathability=80, max_price=20, categories=['cotton', 'tencel'], limit=10 )
print(results[['name', 'softness', 'breathability', 'price_per_yard']])
blend = { 'Cotton': 60, 'Polyester': 35, 'Spandex': 5 }
optimizer = BlendOptimizer() predicted = optimizer.predict_blend_properties(blend)
print(f"Predicted Softness: {predicted['softness']:.1f}") print(f"95% CI: [{predicted['softness_ci']['lower']:.1f}, {predicted['softness_ci']['upper']:.1f}]")
requirements = { 'budget': 'medium', 'priorities': ['breathability', 'moisture_wicking'], 'use_case': 'activewear' }
ai = AIRecommendationEngine() recommendations = ai.smart_suggest(requirements)
for i, rec in enumerate(recommendations, 1): print(f"{i}. {rec['name']} - ${rec['price']:.2f}/yard (Score: {rec['ai_score']:.1f})")
- MATERIAL SPECIFICATION SYSTEM
CompleteMaterialSpec - Build comprehensive material specifications
Available Methods:
- spec.add_treatment(treatment_id) - Add finishing treatment
- spec.set_construction(construction_id) - Set fabric construction
- spec.add_test(test_id) - Add testing protocol
- spec.add_certification(cert_id) - Add certification
- spec.calculate_total_cost(yards) - Calculate total cost
- spec.calculate_upgraded_properties() - Calculate final properties
- spec.generate_complete_specification() - Generate full spec document
Available Treatments:
- moisture_wicking - Enhanced moisture management
- antimicrobial - Bacterial growth prevention
- water_repellent - DWR coating
- flame_retardant - Fire resistance
- uv_protection - UV blocking
- wrinkle_resistant - Easy care finish
- softener - Enhanced hand feel
- stain_resistant - Stain repellency
- And 7 more...
Available Construction Methods:
- jersey_knit - Single jersey construction
- french_terry - Loop-backed knit
- interlock - Double knit structure
- rib_knit - Ribbed texture
- waffle_knit - Textured surface
- And 11 more...
- SEARCH & FILTERING
AdvancedMaterialSearch - Intelligent material discovery
search = AdvancedMaterialSearch()
results = search.search( min_softness=None, # Minimum softness score (0-100) min_durability=None, # Minimum durability (0-100) min_breathability=None, # Minimum breathability (0-100) min_moisture_wicking=None, # Minimum moisture wicking (0-100) min_stretch=None, # Minimum stretch (0-100) max_price=None, # Maximum price per yard categories=None, # List: ['cotton', 'polyester'] product_categories=None, # List: ['activewear', 'loungewear'] use_case=None, # Specific use case sort_by='performance_score', # Sort field limit=20 # Number of results )
comparison = search.compare_materials(['Material A', 'Material B', 'Material C'])
- TREATMENT OPTIMIZATION
TreatmentOptimizer - Find optimal treatment combinations
spec = CompleteMaterialSpec('Base Material') optimizer = TreatmentOptimizer(spec)
targets = { 'moisture_wicking': 90, 'durability': 85, 'softness': 80 }
recommendations = optimizer.optimize_for_target( target_properties=targets, max_cost=5.00, # Maximum cost per yard max_treatments=3 # Maximum number of treatments )
- SUSTAINABILITY ANALYSIS
SustainabilityCalculator - Environmental impact assessment
calc = SustainabilityCalculator(spec)
carbon = calc.calculate_carbon_footprint(yards=1000) print(f"Total CO2: {carbon['total_carbon_kg']:.2f} kg")
eco = calc.calculate_eco_score() print(f"Eco Score: {eco['overall_score']:.1f}/100") print(f"Grade: {eco['grade']} - {eco['rating']}")
- ADVANCED STATISTICS
AdvancedStatistics - Statistical analysis toolkit
stats = AdvancedStatistics()
data = [95.2, 96.1, 94.8, 95.9, 96.3, 95.1, 95.7] ci = stats.calculate_confidence_interval(data, confidence=0.95)
regression = stats.linear_regression_analysis(x_data, y_data)
capability = stats.process_capability_analysis(data, lsl=98.0, usl=102.0)
mc_result = stats.monte_carlo_simulation(variables, formula, n_simulations=10000)
=============================================================================== 6. COMPLETE TUTORIALS
Objective: Create a high-performance activewear fabric specification optimized for moisture management and durability.
spec = CompleteMaterialSpec('Performance Polyester')
spec.add_treatment('moisture_wicking') spec.add_treatment('antimicrobial') spec.add_treatment('uv_protection')
spec.set_construction('four_way_stretch_knit')
spec.add_test('moisture_wicking_test') spec.add_test('abrasion_resistance') spec.add_test('colorfastness_washing') spec.add_test('pilling_resistance')
spec.add_certification('oeko_tex_100') spec.add_certification('bluesign')
properties = spec.calculate_upgraded_properties()
print("Final Properties:") for prop, value in properties['final_properties'].items(): base = properties['base_properties'].get(prop, 0) improvement = value - base ci = properties['confidence_intervals'][prop] print(f"{prop}: {value:.1f} (+{improvement:.1f}) [CI: {ci['lower']:.1f}-{ci['upper']:.1f}]")
cost_breakdown = spec.calculate_total_cost(yards=5000) print(f"\nTotal Cost for 5000 yards: ${cost_breakdown['total_cost_for_yards']:,.2f}")
calc = SustainabilityCalculator(spec) eco_score = calc.calculate_eco_score() carbon = calc.calculate_carbon_footprint(yards=5000)
print(f"\nEco Score: {eco_score['overall_score']:.1f}/100 ({eco_score['grade']})") print(f"Carbon Footprint: {carbon['total_carbon_kg']:.1f} kg CO2")
exporter = MaterialSpecExporter(spec) excel_file = exporter.export_to_excel() tech_pack = exporter.generate_tech_pack_markdown()
Objective: Use advanced search to find materials meeting specific criteria.
requirements = { 'min_softness': 85, 'min_breathability': 80, 'min_moisture_wicking': 75, 'max_price': 25, 'categories': ['cotton', 'tencel', 'modal'], 'product_categories': ['loungewear', 'sleepwear'] }
search = AdvancedMaterialSearch() results = search.search(**requirements, sort_by='performance_score', limit=15)
top_3_names = results['name'].head(3).tolist() comparison = search.compare_materials(top_3_names) print(comparison)
ai = AIRecommendationEngine() ai_recs = ai.smart_suggest({ 'budget': 'medium', 'priorities': ['softness', 'breathability'], 'use_case': 'loungewear' })
best_material = results.iloc[0]['name'] final_spec = CompleteMaterialSpec(best_material)
optimizer = TreatmentOptimizer(final_spec) treatment_recs = optimizer.optimize_for_target( target_properties={'softness': 95, 'breathability': 90}, max_cost=3.00, max_treatments=2 )
Objective: Create and optimize a custom fiber blend for specific performance.
blend_recipe = { 'Cotton': 60, 'Polyester': 35, 'Spandex': 5 }
optimizer = BlendOptimizer() predicted = optimizer.predict_blend_properties(blend_recipe)
print("Predicted Properties:") for prop in ['softness', 'durability', 'breathability', 'moisture_wicking']: val = predicted[prop] ci = predicted[f'{prop}_ci'] print(f"{prop}: {val:.1f} [95% CI: {ci['lower']:.1f}-{ci['upper']:.1f}]")
compatibility_matrix = databases['blend_compatibility']
=============================================================================== 7. ADVANCED USE CASES
Problem: Find optimal balance between cost and performance.
stats = AdvancedStatistics()
def cost_objective(cotton_pct, treatment_level): return base_cost + treatment_level * 2
def performance_objective(cotton_pct, treatment_level): return -(cotton_pct * 0.8 + treatment_level * 5)
pareto_result = stats.pareto_optimization( objectives=[cost_objective, performance_objective], bounds=[(50, 100), (0, 5)], n_points=200 )
print(f"Pareto Solutions: {pareto_result['n_pareto_optimal']}")
Problem: Monitor production quality and detect out-of-control conditions.
process_data = [199, 201, 200, 198, 202, 199, 201, 200] * 6
capability = stats.process_capability_analysis( data=process_data, lsl=190, usl=210 )
print(f"Cpk: {capability['cpk']:.3f}") print(f"Interpretation: {capability['interpretation']}")
Problem: Estimate total project cost with uncertainty quantification.
variables = { 'material_price': {'distribution': 'normal', 'params': [18, 2]}, 'treatment_cost': {'distribution': 'triangular', 'params': [2, 3, 5]}, 'quantity_yards': {'distribution': 'normal', 'params': [10000, 500]}, 'waste_percent': {'distribution': 'uniform', 'params': [3, 7]} }
def project_cost(material_price, treatment_cost, quantity_yards, waste_percent): effective_yards = quantity_yards * (1 + waste_percent / 100) return (material_price + treatment_cost) * effective_yards
mc_result = stats.monte_carlo_simulation(variables, project_cost, n_simulations=10000)
print(f"Mean Cost:
=============================================================================== 8. OPTIMIZATION STRATEGIES
quality_requirements = { 'min_softness': 80, 'min_durability': 75, 'min_performance_score': 70 }
search = AdvancedMaterialSearch() candidates = search.search( min_softness=quality_requirements['min_softness'], min_durability=quality_requirements['min_durability'], sort_by='price_per_yard', limit=20 )
for idx, material in candidates.head(5).iterrows(): spec = CompleteMaterialSpec(material['name']) optimizer = TreatmentOptimizer(spec)
treatments = optimizer.optimize_for_target(
target_properties={'performance_score': 80},
max_cost=2.00,
max_treatments=2
)
max_budget_per_yard = 25.00
high_perf = search.search( max_price=max_budget_per_yard, sort_by='performance_score', limit=20 )
best_material = high_perf.iloc[0]['name'] spec = CompleteMaterialSpec(best_material)
remaining_budget = max_budget_per_yard - high_perf.iloc[0]['price_per_yard']
aggressive_treatments = optimizer.optimize_for_target( target_properties={'softness': 95, 'durability': 95, 'moisture_wicking': 95}, max_cost=remaining_budget, max_treatments=4 )
eco_materials = []
for idx, material in df_all_materials.iterrows(): spec = CompleteMaterialSpec(material['name']) calc = SustainabilityCalculator(spec) eco_score = calc.calculate_eco_score()
if eco_score['overall_score'] >= 80:
eco_materials.append({
'name': material['name'],
'eco_score': eco_score['overall_score'],
'grade': eco_score['grade'],
'price': material['price_per_yard']
})
eco_df = pd.DataFrame(eco_materials).sort_values('eco_score', ascending=False)
CompleteMaterialSpec(material_name: str) Methods: * add_treatment(treatment_id: str) * set_construction(construction_id: str) * add_test(test_id: str) * add_certification(cert_id: str) * calculate_total_cost(yards: float = 1.0) -> Dict * calculate_upgraded_properties() -> Dict * generate_complete_specification() -> Dict
AdvancedMaterialSearch() Methods: * search(**criteria) -> pd.DataFrame * compare_materials(material_names: List[str]) -> pd.DataFrame
AdvancedStatistics() Methods: * calculate_confidence_interval(data, confidence=0.95) -> Dict * linear_regression_analysis(x_data, y_data) -> Dict * process_capability_analysis(data, lsl, usl) -> Dict * monte_carlo_simulation(variables, formula, n_simulations=10000) -> Dict * pareto_optimization(objectives, bounds, n_points=100) -> Dict
TreatmentOptimizer(spec: CompleteMaterialSpec) Methods: * optimize_for_target(target_properties, max_cost, max_treatments) -> List[Dict]
SustainabilityCalculator(spec: CompleteMaterialSpec) Methods: * calculate_carbon_footprint(yards: float = 100) -> Dict * calculate_eco_score() -> Dict
BlendOptimizer() Methods: * predict_blend_properties(blend_recipe: Dict[str, float]) -> Dict
TextileScienceEngine() Methods: * calculate_crystallinity_index(fiber_type: str) -> Dict * calculate_moisture_regain(fiber_type: str, relative_humidity: float) -> Dict * calculate_tenacity(fiber_type: str) -> Dict * predict_dye_uptake(fiber_type: str, dye_class: str) -> Dict
MaterialVisualizer() Methods: * create_dashboard(material_specs: List, save: bool = True) * radar_chart_comparison(material_names: List[str])
AIRecommendationEngine() Methods: * smart_suggest(requirements: Dict) -> List[Dict]
QualityControlManager() Methods: * record_test_result(batch_id, test_id, results) -> Dict * calculate_batch_quality_score(batch_id) -> Dict * statistical_process_control(test_id) -> Dict
InventoryManager() Methods: * get_stock_status(item_id: str = None) -> Dict * reserve_stock(item_id, quantity, order_ref) -> Dict * forecast_usage(item_id, days_ahead: int = 30) -> Dict
SupplierManager() Methods: * compare_suppliers(material, quantity) -> List[Dict] * get_best_supplier(material, quantity, priority) -> Dict
DO:
- Use multi-criteria search to explore options
- Compare at least 3-5 materials before deciding
- Consider total cost (material + treatments + construction)
- Check eco-scores for sustainability requirements
- Validate with AI recommendations
DON'T:
- Select based on price alone
- Ignore sustainability metrics
- Skip statistical validation
- Forget to check blend compatibility
DO:
- Start with target properties clearly defined
- Set realistic budget constraints
- Use efficiency ratio to compare options
- Validate durability (wash cycles)
- Check certification requirements
DON'T:
- Over-treat (diminishing returns)
- Ignore treatment compatibility
- Skip cost-benefit analysis
- Forget environmental impact
DO:
- Establish control limits before production
- Monitor Cpk regularly (target >= 1.33)
- Use confidence intervals for predictions
- Document out-of-control events
- Implement corrective actions promptly
DON'T:
- React to single data points
- Ignore trends within limits
- Skip process capability studies
- Forget to update standards
DO:
- Check compatibility matrix first
- Use optimization algorithms
- Predict properties with confidence intervals
- Consider fiber costs
- Test physical samples
DON'T:
- Blend incompatible fibers
- Exceed recommended ratios
- Skip property prediction
- Ignore processing challenges
Error: ValueError: Material 'XYZ' not found
Solution: search = AdvancedMaterialSearch() results = search.materials[search.materials['name'].str.contains('XYZ', case=False, na=False)] print(results['name'].tolist())
Error: Blend must sum to 100%
Solution: blend = {'Cotton': 60, 'Polyester': 38, 'Spandex': 5} total = sum(blend.values()) normalized_blend = {k: (v/total)*100 for k, v in blend.items()}
Error: Need at least N data points
Solution:
import numpy as np synthetic_data = np.random.normal(100, 5, 30).tolist()
We welcome contributions!
git clone https://github.com/pythpythpython/peanut-research.git cd peanut-research
git checkout -b feature/your-feature-name
- Follow PEP 8 style guide
- Add docstrings to all functions
- Include unit tests for new features
- Update documentation
- Ensure backward compatibility
Proprietary License - Copyright 2025 Peanut Research. All rights reserved.
- Documentation: https://docs.peanutresearch.com
- Issues: https://github.com/pythpythpython/peanut-research/issues
- Email: support@peanutresearch.com
- ASTM International for testing standards
- AATCC for textile testing methods
- ISO for quality management frameworks
- Open-source Python community
===============================================================================
Built with love by Peanut Research Team
Last Updated: December 6, 2025
===============================================================================