Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
from tomatopy import Pizza, PizzaDough, PizzaSauce
# Create pizza components
dough = PizzaDough(
thickness="medium",
size="12inch",
style="neapolitan"
)
sauce = PizzaSauce(
base="tomato",
consistency="smooth",
seasoning_level="medium"
)
# Create a pizza
pizza = Pizza(
dough=dough,
sauce=sauce,
size="12inch",
style="neapolitan"
)from tomatopy import Topping
# Create toppings
mozzarella = Topping(
name="mozzarella",
amount=200, # grams
distribution="even"
)
basil = Topping(
name="basil",
amount=10, # leaves
distribution="scattered"
)
# Add toppings to pizza
pizza.add_topping(mozzarella)
pizza.add_topping(basil)# Create custom dough
custom_dough = PizzaDough(
thickness="thin",
size="14inch",
style="new_york",
hydration=0.65, # 65% hydration
fermentation_time="24h",
flour_type="00",
salt_content=0.02 # 2% salt
)# Create custom sauce
custom_sauce = PizzaSauce(
base="tomato",
consistency="chunky",
seasoning_level="high",
herbs=["basil", "oregano"],
garlic_content=0.05, # 5% garlic
sugar_content=0.02 # 2% sugar
)from tomatopy import PizzaOven
# Set up pizza oven
oven = PizzaOven(
temperature=450, # Celsius
heat_source="wood",
humidity=0.65
)
# Bake pizza
baked_pizza = oven.bake(
pizza,
duration="2m",
rotation_frequency="30s"
)# Configure advanced baking
baked_pizza = oven.bake(
pizza,
duration="2m",
rotation_frequency="30s",
heat_zones={
"center": 450,
"edges": 480,
"top": 460
},
steam_injection=True,
crust_development="high"
)# Analyze pizza quality
analysis = pizza.analyze()
print(f"Crust crispness: {analysis.crust_crispness}")
print(f"Cheese melt: {analysis.cheese_melt}")
print(f"Topping distribution: {analysis.topping_distribution}")# Get detailed quality metrics
metrics = pizza.get_quality_metrics()
print(f"Overall score: {metrics.overall_score}")
print(f"Balance score: {metrics.balance_score}")
print(f"Texture score: {metrics.texture_score}")# Create authentic Neapolitan pizza
neapolitan = Pizza.create_neapolitan(
size="12inch",
toppings=["san_marzano_tomatoes", "mozzarella", "basil"]
)# Create New York style pizza
ny_style = Pizza.create_ny_style(
size="18inch",
thickness="thin",
toppings=["tomato_sauce", "mozzarella", "pepperoni"]
)# Create Chicago deep dish
chicago = Pizza.create_chicago_style(
size="10inch",
thickness="deep",
toppings=["tomato_sauce", "mozzarella", "sausage"]
)# Cut pizza into slices
slices = pizza.cut(
method="standard",
slices=8,
slice_size="equal"
)# Custom pizza cutting
slices = pizza.cut(
method="custom",
slice_sizes=["large", "medium", "small"],
pattern="radial"
)try:
# Attempt invalid topping
pizza.add_topping("invalid_topping")
except ToppingError as e:
print(f"Error: {e}") # "Invalid topping type"
try:
# Attempt invalid baking temperature
oven.set_temperature(1000) # Too hot!
except TemperatureError as e:
print(f"Error: {e}") # "Temperature exceeds safe range"# Ensure proper dough fermentation
if dough.fermentation_time < "24h":
print("Warning: Dough may not be fully fermented")# Check topping distribution
if pizza.get_topping_distribution() < 0.8:
print("Warning: Toppings may not be evenly distributed")# Monitor oven temperature
with oven.temperature_monitor() as monitor:
pizza = oven.bake(...)
if monitor.get_max() > 500:
print("Warning: Oven temperature too high")from tomatopy import Ingredient
# Create a basic ingredient
tomato = Ingredient(
name="tomato",
amount=1,
unit="whole",
properties={
"ripeness": 0.8,
"water_content": 0.95,
"sugar_content": 0.03
}
)from tomatopy import Tomato, Garlic, Basil
# Create specialized ingredients
san_marzano = Tomato(
ripeness=0.8,
variety="San Marzano",
weight=150
)
fresh_garlic = Garlic(
cloves=3,
freshness=0.9,
size="medium"
)
sweet_basil = Basil(
leaves=10,
freshness=0.95,
variety="Genovese"
)# Update ingredient properties
tomato.properties["ripeness"] = 0.9
tomato.properties["water_content"] = 0.92
# Batch update properties
tomato.update_properties({
"ripeness": 0.9,
"water_content": 0.92,
"sugar_content": 0.04
})# Convert between units
tomato.convert_to_imperial() # Converts metric to imperial
tomato.convert_volume("ml", "cups") # Converts between volume units
# Get measurements in different units
print(tomato.get_weight("g")) # 150
print(tomato.get_weight("oz")) # 5.29# Get physical properties
print(tomato.get_density()) # 1.02 g/ml
print(tomato.get_volume()) # 147 ml
print(tomato.get_surface_area()) # 150 cm²# Analyze chemical properties
print(tomato.get_ph()) # 4.5
print(tomato.get_water_content()) # 0.95
print(tomato.get_sugar_content()) # 0.03# Cut ingredients
diced_tomato = tomato.cut(
method="dice",
size="medium",
consistency="uniform"
)
# Chop ingredients
chopped_garlic = fresh_garlic.chop(
fineness="medium",
method="mince"
)# Combine ingredients
mixture = tomato.combine(
fresh_garlic,
sweet_basil,
method="mix",
consistency="chunky"
)# Check ingredient freshness
if tomato.is_fresh():
print("Ingredient is fresh")
else:
print("Ingredient may be past its prime")
# Get freshness score
freshness_score = tomato.get_freshness_score() # 0.85# Assess ingredient quality
quality_report = tomato.assess_quality()
print(quality_report.overall_score) # 0.92
print(quality_report.recommendations) # ["Consider using within 2 days"]try:
# Attempt invalid operation
tomato.cut(method="invalid_method")
except IngredientError as e:
print(f"Error: {e}") # "Invalid cutting method"
try:
# Attempt invalid property update
tomato.update_properties({"invalid_property": 1.0})
except PropertyError as e:
print(f"Error: {e}") # "Invalid property name"if tomato.state == "fresh":
# Proceed with operationfrom typing import Dict, Any
def create_ingredient(
name: str,
properties: Dict[str, Any]
) -> Ingredient:
return Ingredient(name=name, properties=properties)# Always specify units explicitly
weight_grams = tomato.get_weight("g")
weight_ounces = tomato.get_weight("oz")# Adjust oven temperature and baking time
baked_pizza = oven.bake(
pizza,
temperature=480, # Higher temperature
duration="1m30s" # Shorter duration
)# Redistribute toppings
pizza.redistribute_toppings(
method="even",
target_distribution=0.9
)# Adjust cheese layer
pizza.adjust_cheese_layer(
thickness="medium",
distribution="even"
)# Check fermentation
if dough.fermentation_time < "24h":
print("Warning: Dough may not be fully fermented")# Monitor oven temperature
with oven.temperature_monitor() as monitor:
if monitor.get_max() > 500:
print("Warning: Oven temperature too high")# Check topping balance
if pizza.get_topping_balance() < 0.8:
print("Warning: Toppings may not be balanced")from tomatopy import Kitchen, KitchenHardware
# Initialize kitchen
kitchen = Kitchen()
# Set up hardware
hardware = KitchenHardware()
oven = hardware.get_oven()
# Configure pizza oven
oven.configure(
temperature=450, # Celsius
heat_source="wood",
humidity=0.65,
heat_zones={
"center": 450,
"edges": 480,
"top": 460
}
)from tomatopy import PizzaDough
# Create pizza dough
dough = PizzaDough(
thickness="medium",
size="14inch",
style="neapolitan",
hydration=0.65, # 65% hydration
fermentation_time="24h",
flour_type="00",
salt_content=0.02 # 2% salt
)
# Check dough properties
print(f"Dough hydration: {dough.get_hydration()}")
print(f"Fermentation status: {dough.get_fermentation_status()}")from tomatopy import PizzaSauce, Tomato, Garlic, Basil
# Create sauce ingredients
tomatoes = Tomato(
ripeness=0.9,
variety="San Marzano",
weight=400 # grams
)
garlic = Garlic(
cloves=3,
freshness=0.95,
size="medium"
)
basil = Basil(
leaves=10,
freshness=0.95,
variety="Genovese"
)
# Create pizza sauce
sauce = PizzaSauce(
base="tomato",
consistency="smooth",
seasoning_level="medium",
herbs=["basil", "oregano"],
garlic_content=0.05, # 5% garlic
sugar_content=0.02 # 2% sugar
)from tomatopy import Topping
# Create toppings
mozzarella = Topping(
name="mozzarella",
amount=200, # grams
distribution="even",
moisture_content=0.52
)
pepperoni = Topping(
name="pepperoni",
amount=100, # grams
distribution="scattered",
spiciness="medium"
)
basil = Topping(
name="basil",
amount=10, # leaves
distribution="scattered",
freshness=0.95
)from tomatopy import Pizza
# Create pizza
pizza = Pizza(
dough=dough,
sauce=sauce,
size="14inch",
style="neapolitan"
)
# Add toppings
pizza.add_topping(mozzarella)
pizza.add_topping(pepperoni)
pizza.add_topping(basil)
# Check topping distribution
distribution = pizza.get_topping_distribution()
print(f"Topping distribution score: {distribution}")# Pre-heat oven
oven.preheat(
temperature=450,
duration="30m",
heat_zones={
"center": 450,
"edges": 480,
"top": 460
}
)
# Bake pizza
baked_pizza = oven.bake(
pizza,
duration="2m",
rotation_frequency="30s",
steam_injection=True,
crust_development="high"
)
# Monitor baking process
with oven.temperature_monitor() as monitor:
print(f"Center temperature: {monitor.get_center_temp()}°C")
print(f"Edge temperature: {monitor.get_edge_temp()}°C")from tomatopy import TasteTester
# Create taste tester
tester = TasteTester()
# Analyze pizza
profile = tester.analyze(baked_pizza)
# Check quality metrics
print(f"Crust crispness: {profile.crust_crispness}")
print(f"Cheese melt: {profile.cheese_melt}")
print(f"Topping distribution: {profile.topping_distribution}")
# Get texture analysis
texture = tester.analyze_texture(baked_pizza)
print(f"Crust texture: {texture.crust_texture}")
print(f"Cheese texture: {texture.cheese_texture}")# Cut pizza into slices
slices = baked_pizza.cut(
method="standard",
slices=8,
slice_size="equal"
)
# Analyze slice quality
for i, slice in enumerate(slices):
print(f"Slice {i+1} quality: {slice.get_quality_score()}")# Create batch of pizzas
pizzas = [
Pizza.create_neapolitan(size="12inch"),
Pizza.create_ny_style(size="18inch"),
Pizza.create_chicago_style(size="10inch")
]
# Bake batch
baked_pizzas = oven.bake_batch(
pizzas,
rotation_frequency="30s",
steam_injection=True
)# Configure advanced crust development
baked_pizza = oven.bake(
pizza,
crust_development={
"bottom": "crispy",
"edges": "chewy",
"top": "golden"
}
)from tomatopy import Ingredient
# Create a basic ingredient
tomato = Ingredient(
name="tomato",
amount=1,
unit="whole",
properties={
"ripeness": 0.8,
"water_content": 0.95,
"sugar_content": 0.03
}
)from tomatopy import Kitchen
kitchen = Kitchen()
kitchen.set_temperature(180) # Celsius
kitchen.set_humidity(65) # Percentagefrom tomatopy import Recipe
# Create a recipe
marinara = Recipe("Classic Marinara")
marinara.add_ingredient(tomato)
marinara.set_cooking_method("simmer")
marinara.set_duration("30m")# Access and modify properties
print(tomato.properties["water_content"]) # 0.95
tomato.properties["ripeness"] = 0.9# Perform cooking operations
sauce = kitchen.cook(
tomato,
method="simmer",
temperature=100,
duration="30m"
)# Check ingredient state
print(tomato.state) # "raw"
sauce = kitchen.cook(tomato, method="simmer")
print(sauce.state) # "cooked"from tomatopy import TasteTester
tester = TasteTester()
profile = tester.analyze(sauce)
# Access flavor components
print(profile.acidity) # 0.7
print(profile.sweetness) # 0.3
print(profile.umami) # 0.8# Convert between units
tomato.convert_to_imperial() # Converts metric to imperial
sauce.convert_volume("ml", "cups") # Converts between volume unitstry:
kitchen.cook(tomato, temperature=1000) # Too hot!
except TemperatureError as e:
print(f"Error: {e}") # "Temperature exceeds safe cooking range"python -m venv tomatopy-env
source tomatopy-env/bin/activate # or `tomatopy-env\Scripts\activate` on Windowsif tomato.properties["ripeness"] < 0.5:
print("Warning: Tomato may be too unripe for optimal results")from typing import Dict, Any
def create_ingredient(name: str, properties: Dict[str, Any]) -> Ingredient:
return Ingredient(name=name, properties=properties)from tomatopy import Kitchen, KitchenHardware
# Initialize kitchen with basic settings
kitchen = Kitchen(
temperature=22, # Celsius
humidity=0.65,
ventilation="standard",
lighting="bright"
)
# Configure hardware
hardware = KitchenHardware()
hardware.configure(
oven={"type": "convection", "capacity": "large"},
stove={"burners": 4, "type": "gas"},
refrigerator={"capacity": "medium", "temperature": 4}
)# Configure advanced settings
kitchen.configure(
temperature_control={
"precision": 0.1,
"zones": ["prep", "cooking", "storage"]
},
humidity_control={
"precision": 0.05,
"zones": ["prep", "cooking", "storage"]
},
ventilation={
"type": "smart",
"zones": ["prep", "cooking", "storage"],
"filters": ["grease", "smoke", "odor"]
}
)# Good: Efficient equipment allocation
class KitchenManager:
def __init__(self):
self.equipment_pool = {}
self.allocations = {}
def allocate_equipment(self, recipe):
required = recipe.get_required_equipment()
available = self.get_available_equipment()
for item in required:
if item in available:
self.allocations[recipe.id] = item
return True
return False
# Bad: No equipment management
def cook_recipe(recipe):
# No equipment allocation
pass# Good: Optimize kitchen space
class KitchenLayout:
def __init__(self):
self.workstations = {}
self.workflow = {}
def optimize_layout(self, recipes):
for recipe in recipes:
required_space = recipe.get_required_space()
available_space = self.get_available_space()
if self.can_fit(required_space, available_space):
self.allocate_space(recipe, available_space)
# Bad: No space optimization
def prepare_recipe(recipe):
# No space management
pass# Good: Efficient task scheduling
class KitchenScheduler:
def __init__(self):
self.tasks = []
self.resources = {}
def schedule_tasks(self, recipes):
for recipe in recipes:
tasks = recipe.get_tasks()
for task in tasks:
if self.can_schedule(task):
self.tasks.append(task)
else:
self.handle_scheduling_conflict(task)
# Bad: No task scheduling
def process_recipes(recipes):
for recipe in recipes:
# No scheduling
process_recipe(recipe)# Good: Optimize workflow
class WorkflowOptimizer:
def optimize_workflow(self, tasks):
# Sort tasks by priority and dependencies
sorted_tasks = self.topological_sort(tasks)
# Group compatible tasks
task_groups = self.group_tasks(sorted_tasks)
# Schedule groups efficiently
return self.schedule_groups(task_groups)
# Bad: No workflow optimization
def process_tasks(tasks):
for task in tasks:
# No optimization
process_task(task)# Good: Manage temperature zones
class TemperatureManager:
def __init__(self):
self.zones = {}
self.controllers = {}
def manage_zones(self):
for zone, settings in self.zones.items():
current_temp = self.get_zone_temperature(zone)
target_temp = settings["target"]
if abs(current_temp - target_temp) > settings["tolerance"]:
self.adjust_zone_temperature(zone, target_temp)
# Bad: No zone management
def set_temperature(temp):
# No zone control
pass# Good: Monitor temperatures
class TemperatureMonitor:
def __init__(self):
self.sensors = {}
self.alerts = []
def monitor_temperatures(self):
for zone, sensor in self.sensors.items():
temp = sensor.read()
if self.is_temperature_unsafe(temp, zone):
self.trigger_alert(zone, temp)
# Bad: No temperature monitoring
def check_temperature():
# No monitoring
pass# Good: Implement safety protocols
class SafetyManager:
def __init__(self):
self.protocols = {}
self.violations = []
def enforce_safety(self, operation):
if not self.check_safety_protocols(operation):
self.handle_safety_violation(operation)
return False
return True
# Bad: No safety protocols
def perform_operation(operation):
# No safety checks
pass# Good: Handle emergencies
class EmergencyManager:
def __init__(self):
self.procedures = {}
self.emergency_contacts = []
def handle_emergency(self, emergency_type):
if emergency_type in self.procedures:
self.execute_procedure(emergency_type)
self.notify_emergency_contacts(emergency_type)
# Bad: No emergency handling
def handle_problem(problem):
# No emergency procedures
pass# Good: Manage equipment maintenance
class MaintenanceManager:
def __init__(self):
self.schedule = {}
self.maintenance_history = []
def schedule_maintenance(self, equipment):
if equipment.needs_maintenance():
self.add_to_schedule(equipment)
self.notify_maintenance_team(equipment)
# Bad: No maintenance scheduling
def fix_equipment(equipment):
# No maintenance management
pass# Good: Implement cleaning protocols
class CleaningManager:
def __init__(self):
self.protocols = {}
self.cleaning_schedule = []
def manage_cleaning(self):
for area in self.get_areas():
if area.needs_cleaning():
self.schedule_cleaning(area)
self.notify_cleaning_staff(area)
# Bad: No cleaning management
def clean_area(area):
# No cleaning protocols
passfrom tomatopy import KitchenHardware
# Initialize kitchen hardware
hardware = KitchenHardware()
# Initialize specific equipment
oven = hardware.get_oven()
stove = hardware.get_stove()
blender = hardware.get_blender()# Control oven
oven.set_temperature(180) # Celsius
oven.set_mode("bake")
oven.set_timer("30m")
# Control stove
stove.set_burner(1, temperature=100) # Celsius
stove.set_burner(2, temperature=200)
# Control blender
blender.set_speed("high")
blender.set_duration("1m")# Configure advanced oven settings
oven.configure(
temperature=180,
mode="convection",
humidity=0.65,
fan_speed="high",
steam_injection=True,
heat_zones={
"top": 190,
"bottom": 170,
"rear": 180
}
)# Configure advanced stove settings
stove.configure(
burners={
1: {"temperature": 100, "size": "small"},
2: {"temperature": 200, "size": "large"},
3: {"temperature": 150, "size": "medium"},
4: {"temperature": 180, "size": "medium"}
},
griddle_temperature=200,
ventilation="high"
)# Configure advanced blender settings
blender.configure(
speed="high",
duration="1m",
pulse_pattern="intermittent",
container_size="1.5L",
blade_type="multi-purpose"
)# Monitor equipment status
print(f"Oven temperature: {oven.get_temperature()}°C")
print(f"Stove burner 1: {stove.get_burner_status(1)}")
print(f"Blender speed: {blender.get_speed()}")# Set up comprehensive monitoring
with hardware.monitor() as monitor:
# Monitor multiple parameters
monitor.track_temperature(oven)
monitor.track_power_usage(stove)
monitor.track_vibration(blender)
# Get monitoring data
data = monitor.get_data()
print(f"Temperature history: {data.temperature_history}")
print(f"Power usage: {data.power_usage}")
print(f"Vibration levels: {data.vibration_levels}")# Perform safety checks
if hardware.check_safety():
# Proceed with operation
oven.start()
else:
print("Safety check failed")# Set up safety monitoring
hardware.set_safety_monitoring(
temperature_limits={
"max": 300, # Celsius
"min": 50
},
power_limits={
"max": 5000, # Watts
"min": 0
},
ventilation_required=True,
emergency_shutdown=True
)# Check equipment status
status = hardware.check_status()
# Perform basic maintenance
if status.needs_cleaning:
hardware.clean_equipment()
if status.needs_calibration:
hardware.calibrate_equipment()# Schedule maintenance
hardware.schedule_maintenance(
oven,
tasks=["clean", "calibrate", "inspect"],
frequency="weekly"
)
# Get maintenance history
history = hardware.get_maintenance_history()
print(f"Last cleaning: {history.last_cleaning}")
print(f"Last calibration: {history.last_calibration}")try:
# Attempt invalid temperature
oven.set_temperature(1000) # Too hot!
except TemperatureError as e:
print(f"Error: {e}") # "Temperature exceeds safe range"
try:
# Attempt invalid operation
blender.set_speed("invalid_speed")
except OperationError as e:
print(f"Error: {e}") # "Invalid speed setting"# Check status before use
if hardware.check_status().is_ready:
# Proceed with operation
oven.start()
else:
print("Equipment not ready")# Monitor temperature during operation
with hardware.temperature_monitor() as monitor:
oven.start()
if monitor.get_max() > safety_threshold:
print("Warning: Temperature too high")# Schedule regular maintenance
hardware.schedule_maintenance(
equipment,
tasks=["clean", "calibrate"],
frequency="daily"
)pip install tomatopygit clone https://github.com/tomatopy/tomatopy.git
cd tomatopy
pip install -e .# Create a virtual environment
python -m venv tomatopy-env
# Activate the virtual environment
# On Windows:
tomatopy-env\Scripts\activate
# On macOS/Linux:
source tomatopy-env/bin/activate
# Install TomatoPy
pip install tomatopyimport tomatopy
print(tomatopy.__version__) # Should print the installed versionfrom tomatopy import Kitchen
# Initialize a kitchen
kitchen = Kitchen()
# Configure basic settings
kitchen.set_temperature(180) # Celsius
kitchen.set_humidity(65) # Percentage
kitchen.set_pressure(101.3) # kPa (atmospheric pressure)# Configure advanced settings
kitchen.set_ventilation("high")
kitchen.set_lighting("bright")
kitchen.set_equipment({
"stove": {"type": "gas", "burners": 4},
"oven": {"type": "convection", "capacity": "large"},
"blender": {"type": "high_speed", "capacity": "1.5L"}
})# Simmer ingredients
sauce = kitchen.cook(
tomato,
method="simmer",
temperature=100,
duration="30m",
stirring_frequency="occasional"
)# Boil ingredients
pasta = kitchen.cook(
spaghetti,
method="boil",
temperature=100,
duration="8m",
salt_concentration=0.02 # 2% salt
)# Roast ingredients
roasted_tomatoes = kitchen.cook(
tomatoes,
method="roast",
temperature=200,
duration="45m",
turning_frequency="every_15m"
)# Pressure cook ingredients
beans = kitchen.cook(
dried_beans,
method="pressure_cook",
pressure=103.4, # kPa
temperature=121, # Celsius
duration="30m"
)# Sous vide cooking
steak = kitchen.cook(
beef,
method="sous_vide",
temperature=55,
duration="2h",
vacuum_sealed=True
)# Smoke ingredients
smoked_tomatoes = kitchen.cook(
tomatoes,
method="smoke",
temperature=100,
duration="4h",
wood_type="hickory",
smoke_intensity="medium"
)from tomatopy import Recipe
# Create a recipe
marinara = Recipe("Classic Marinara")
marinara.add_ingredient(tomato)
marinara.add_ingredient(garlic)
marinara.add_ingredient(basil)
# Set cooking parameters
marinara.set_cooking_method("simmer")
marinara.set_duration("30m")
marinara.set_temperature(100)# Cook multiple recipes
recipes = [marinara, pizza_sauce, tomato_soup]
results = kitchen.cook_batch(recipes)
# Process results
for recipe, result in zip(recipes, results):
print(f"{recipe.name}: {result.consistency}")# Monitor temperature during cooking
with kitchen.temperature_monitor() as monitor:
sauce = kitchen.cook(tomato, method="simmer")
temperature_history = monitor.get_history()
print(f"Average temperature: {monitor.get_average()}°C")# Set up temperature alerts
kitchen.set_temperature_alert(
min_temp=95,
max_temp=105,
callback=lambda temp: print(f"Temperature alert: {temp}°C")
)# Perform safety checks
if kitchen.validate_cooking_parameters(
temperature=200,
duration="2h",
pressure=103.4
):
# Proceed with cooking
result = kitchen.cook(...)
else:
print("Invalid cooking parameters")# Assess cooking results
quality_report = kitchen.assess_cooking_result(sauce)
print(f"Overall quality: {quality_report.score}")
print(f"Recommendations: {quality_report.recommendations}")try:
# Attempt invalid cooking operation
kitchen.cook(
tomato,
method="invalid_method",
temperature=1000 # Too hot!
)
except CookingError as e:
print(f"Error: {e}") # "Invalid cooking method"
try:
# Attempt unsafe temperature
kitchen.set_temperature(500) # Too hot!
except TemperatureError as e:
print(f"Error: {e}") # "Temperature exceeds safe range"if kitchen.validate_cooking_parameters(
temperature=temp,
duration=duration,
pressure=pressure
):
# Proceed with cookingwith kitchen.temperature_monitor() as monitor:
result = kitchen.cook(...)
if monitor.get_max() > safety_threshold:
print("Warning: Temperature exceeded safety threshold")# Choose method based on ingredient
if ingredient.requires_gentle_cooking:
method = "simmer"
else:
method = "boil"from tomatopy import Kitchen, KitchenHardware
# Initialize kitchen
kitchen = Kitchen()
# Set up hardware
hardware = KitchenHardware()
stove = hardware.get_stove()
blender = hardware.get_blender()
# Configure stove
stove.configure(
burners={
1: {"temperature": 100, "size": "medium"}, # For simmering
2: {"temperature": 200, "size": "large"} # For initial cooking
}
)from tomatopy import Tomato, Garlic, Basil, OliveOil
# Create San Marzano tomatoes
tomatoes = Tomato(
ripeness=0.9,
variety="San Marzano",
weight=800 # grams
)
# Create fresh garlic
garlic = Garlic(
cloves=4,
freshness=0.95,
size="medium"
)
# Create fresh basil
basil = Basil(
leaves=20,
freshness=0.95,
variety="Genovese"
)
# Create olive oil
olive_oil = OliveOil(
amount=60, # ml
quality="extra_virgin",
acidity=0.3 # %
)from tomatopy import Recipe
# Create marinara recipe
marinara = Recipe("Classic Marinara")
# Add ingredients
marinara.add_ingredient(tomatoes)
marinara.add_ingredient(garlic)
marinara.add_ingredient(basil)
marinara.add_ingredient(olive_oil)
# Set cooking parameters
marinara.set_cooking_method("simmer")
marinara.set_duration("45m")
marinara.set_temperature(100) # Celsius# Step 1: Heat oil and garlic
garlic_oil = kitchen.cook(
[olive_oil, garlic],
method="sauté",
temperature=160,
duration="5m",
stirring_frequency="constant"
)
# Step 2: Add and cook tomatoes
tomato_mixture = kitchen.cook(
[garlic_oil, tomatoes],
method="simmer",
temperature=100,
duration="30m",
stirring_frequency="occasional"
)
# Step 3: Blend the sauce
sauce = blender.blend(
tomato_mixture,
speed="medium",
duration="1m",
consistency="smooth"
)
# Step 4: Add basil and finish
final_sauce = kitchen.cook(
[sauce, basil],
method="simmer",
temperature=90,
duration="10m",
stirring_frequency="occasional"
)from tomatopy import TasteTester
# Create taste tester
tester = TasteTester()
# Analyze sauce
profile = tester.analyze(final_sauce)
# Check quality metrics
print(f"Sweetness: {profile.sweetness}")
print(f"Acidity: {profile.acidity}")
print(f"Umami: {profile.umami}")
print(f"Overall balance: {profile.balance}")
# Get texture analysis
texture = tester.analyze_texture(final_sauce)
print(f"Consistency: {texture.consistency}")
print(f"Smoothness: {texture.smoothness}")# If too acidic, add a pinch of sugar
if profile.acidity > 0.7:
final_sauce = kitchen.adjust(
final_sauce,
ingredient="sugar",
amount=5, # grams
method="stir"
)
# If too thick, add some water
if texture.consistency > 0.8:
final_sauce = kitchen.adjust(
final_sauce,
ingredient="water",
amount=50, # ml
method="stir"
)# Get comprehensive quality report
quality_report = tester.assess_quality(final_sauce)
# Print quality metrics
print(f"Overall quality: {quality_report.overall_score}")
print(f"Balance score: {quality_report.balance_score}")
print(f"Texture score: {quality_report.texture_score}")
# Get recommendations
print("Recommendations:")
for rec in quality_report.recommendations:
print(f"- {rec}")# Add sugar to balance acidity
sauce = kitchen.adjust(sauce, ingredient="sugar", amount=5)# Add water to thin sauce
sauce = kitchen.adjust(sauce, ingredient="water", amount=50)# Add more garlic or basil
sauce = kitchen.adjust(sauce, ingredient="garlic", amount=2)if not all(ing.is_fresh() for ing in [tomatoes, garlic, basil]):
print("Warning: Some ingredients may not be fresh")with kitchen.temperature_monitor() as monitor:
sauce = kitchen.cook(...)
if monitor.get_max() > 110:
print("Warning: Temperature too high")# Set up automatic stirring
kitchen.set_stirring_frequency("every_5m")# Good: Create ingredients with minimal memory usage
tomato = Tomato(
ripeness=0.8,
variety="San Marzano",
weight=150
)
# Bad: Creating unnecessary copies
tomato_copy = tomato.copy() # Unnecessary memory usage# Good: Process ingredients in batches
def process_ingredients(ingredients, batch_size=100):
for i in range(0, len(ingredients), batch_size):
batch = ingredients[i:i + batch_size]
process_batch(batch)
# Bad: Processing one at a time
for ingredient in ingredients:
process_single(ingredient) # Less efficientfrom functools import lru_cache
# Good: Cache expensive computations
@lru_cache(maxsize=128)
def analyze_ingredient(ingredient):
return TasteTester().analyze(ingredient)
# Bad: Recomputing every time
def analyze_ingredient(ingredient):
return TasteTester().analyze(ingredient) # No caching# Good: Use appropriate data structures
from collections import defaultdict
class Recipe:
def __init__(self):
self.ingredients = defaultdict(float) # Efficient for ingredient tracking
# Bad: Using inefficient structures
class Recipe:
def __init__(self):
self.ingredients = [] # Less efficient for lookups# Good: Use context managers for resource cleanup
with kitchen.temperature_monitor() as monitor:
result = kitchen.cook(ingredient)
data = monitor.get_data()
# Bad: Manual resource management
monitor = kitchen.temperature_monitor()
try:
result = kitchen.cook(ingredient)
data = monitor.get_data()
finally:
monitor.cleanup() # More error-prone# Good: Use connection pooling
from tomatopy import ConnectionPool
pool = ConnectionPool(max_connections=10)
with pool.get_connection() as conn:
conn.execute_operation()
# Bad: Creating new connections each time
conn = create_connection() # Less efficient
conn.execute_operation()
conn.close()# Good: Use binary search for sorted data
def find_optimal_temperature(sorted_temps, target):
left, right = 0, len(sorted_temps) - 1
while left <= right:
mid = (left + right) // 2
if sorted_temps[mid] == target:
return mid
elif sorted_temps[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# Bad: Linear search
def find_optimal_temperature(temps, target):
for i, temp in enumerate(temps):
if temp == target:
return i
return -1from concurrent.futures import ThreadPoolExecutor
# Good: Process multiple ingredients in parallel
def process_ingredients_parallel(ingredients):
with ThreadPoolExecutor(max_workers=4) as executor:
results = list(executor.map(process_ingredient, ingredients))
return results
# Bad: Sequential processing
def process_ingredients_sequential(ingredients):
results = []
for ingredient in ingredients:
results.append(process_ingredient(ingredient))
return results# Good: Modular code structure
class IngredientProcessor:
def process(self, ingredient):
self.validate(ingredient)
self.prepare(ingredient)
self.analyze(ingredient)
# Bad: Monolithic functions
def process_ingredient(ingredient):
# All processing in one function
validate_ingredient(ingredient)
prepare_ingredient(ingredient)
analyze_ingredient(ingredient)# Good: Clean interface design
class Kitchen:
def cook(self, ingredient, **kwargs):
self._validate_parameters(kwargs)
self._prepare_environment()
return self._execute_cooking(ingredient, kwargs)
# Bad: Complex interface
def cook(ingredient, temperature=None, duration=None, method=None,
stirring_frequency=None, humidity=None, pressure=None):
# Too many parameters
pass# Good: Graceful error recovery
def process_recipe(recipe):
try:
result = kitchen.cook_recipe(recipe)
return result
except TemperatureError:
# Handle temperature error
return adjust_temperature(recipe)
except IngredientError:
# Handle ingredient error
return substitute_ingredients(recipe)
finally:
cleanup_resources()
# Bad: No error recovery
def process_recipe(recipe):
result = kitchen.cook_recipe(recipe)
return result # No error handling# Good: Proper resource cleanup
class Kitchen:
def __init__(self):
self.resources = []
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.cleanup()
# Bad: Manual cleanup
def use_kitchen():
kitchen = Kitchen()
try:
# Use kitchen
pass
finally:
kitchen.cleanup()# Good: Performance testing
import time
import cProfile
def profile_operation(func):
def wrapper(*args, **kwargs):
profiler = cProfile.Profile()
result = profiler.runcall(func, *args, **kwargs)
profiler.print_stats()
return result
return wrapper
# Bad: No performance testing
def operation():
# No performance monitoring
pass# Good: Memory profiling
from memory_profiler import profile
@profile
def memory_intensive_operation():
# Operation to profile
pass
# Bad: No memory profiling
def memory_intensive_operation():
# No memory monitoring
passfrom tomatopy import TasteTester, TasteProfile
# Initialize taste tester
tester = TasteTester()
# Configure testing environment
tester.configure(
temperature=22, # Celsius
humidity=0.65,
lighting="standard",
background_noise="minimal"
)# Create a test ingredient
from tomatopy import Tomato
test_tomato = Tomato(
ripeness=0.9,
variety="San Marzano",
weight=150 # grams
)
# Perform comprehensive analysis
profile = tester.analyze(
test_tomato,
depth="comprehensive",
include_aroma=True,
include_texture=True
)
# Access basic metrics
print(f"Sweetness: {profile.sweetness}")
print(f"Acidity: {profile.acidity}")
print(f"Umami: {profile.umami}")# Get detailed aroma profile
aroma_profile = tester.analyze_aroma(
test_tomato,
include_secondary_notes=True,
include_tertiary_notes=True
)
# Access aroma metrics
print("Primary Notes:")
for note in aroma_profile.primary_notes:
print(f"- {note.name}: {note.intensity}")
print("\nSecondary Notes:")
for note in aroma_profile.secondary_notes:
print(f"- {note.name}: {note.intensity}")
print("\nTertiary Notes:")
for note in aroma_profile.tertiary_notes:
print(f"- {note.name}: {note.intensity}")# Get detailed texture profile
texture_profile = tester.analyze_texture(
test_tomato,
include_mouthfeel=True,
include_structural_analysis=True
)
# Access texture metrics
print(f"Firmness: {texture_profile.firmness}")
print(f"Juiciness: {texture_profile.juiciness}")
print(f"Mouthfeel: {texture_profile.mouthfeel}")
print(f"Structural integrity: {texture_profile.structural_integrity}")# Analyze flavor balance
balance = tester.analyze_balance(test_tomato)
# Access balance metrics
print(f"Overall balance: {balance.overall_score}")
print(f"Sweet-sour ratio: {balance.sweet_sour_ratio}")
print(f"Umami enhancement: {balance.umami_enhancement}")
print(f"Flavor complexity: {balance.complexity}")# Create multiple test ingredients
tomato1 = Tomato(ripeness=0.8, variety="San Marzano")
tomato2 = Tomato(ripeness=0.9, variety="Roma")
tomato3 = Tomato(ripeness=0.7, variety="Cherry")
# Perform comparative analysis
comparison = tester.compare(
[tomato1, tomato2, tomato3],
metrics=["sweetness", "acidity", "umami", "aroma"]
)
# Access comparison results
print("\nSweetness Comparison:")
for tomato, score in comparison.get_rankings("sweetness"):
print(f"- {tomato.variety}: {score}")
print("\nAcidity Comparison:")
for tomato, score in comparison.get_rankings("acidity"):
print(f"- {tomato.variety}: {score}")# Create a target profile
target_profile = TasteProfile(
sweetness=0.7,
acidity=0.6,
umami=0.8,
aroma_intensity=0.75
)
# Analyze current profile
current_profile = tester.analyze(test_tomato)
# Get optimization recommendations
recommendations = tester.get_optimization_recommendations(
current_profile,
target_profile
)
# Print recommendations
print("\nOptimization Recommendations:")
for rec in recommendations:
print(f"- {rec}")# Create basic visualization
viz = tester.visualize_profile(profile)
# Customize visualization
viz.set_color_scheme("tomato")
viz.set_scale("logarithmic")
viz.set_style("radar")
# Add additional metrics
viz.add_metrics(["aroma", "texture"])
# Display visualization
viz.show()# Perform multi-dimensional analysis
analysis = tester.analyze_multi_dimensional(
test_tomato,
dimensions=[
"taste",
"aroma",
"texture",
"mouthfeel",
"aftertaste"
]
)
# Access multi-dimensional results
print("\nMulti-Dimensional Analysis:")
for dimension, metrics in analysis.items():
print(f"\n{dimension.upper()}:")
for metric, value in metrics.items():
print(f"- {metric}: {value}")# Analyze flavor development over time
time_analysis = tester.analyze_time_development(
test_tomato,
duration="5m",
interval="30s"
)
# Plot time-based development
viz = tester.visualize_time_development(time_analysis)
viz.show()# Perform statistical analysis
stats = tester.analyze_statistics(
[tomato1, tomato2, tomato3],
metrics=["sweetness", "acidity", "umami"]
)
# Access statistical results
print("\nStatistical Analysis:")
print(f"Mean sweetness: {stats.mean('sweetness')}")
print(f"Standard deviation: {stats.std('sweetness')}")
print(f"Correlation matrix: {stats.correlation_matrix}")# Ensure consistent sample preparation
if not tester.validate_sample(test_tomato):
print("Warning: Sample may not be suitable for analysis")# Use comprehensive analysis for detailed results
profile = tester.analyze(
ingredient,
depth="comprehensive",
include_all_metrics=True
)# Validate analysis results
if profile.is_valid():
# Proceed with analysis
print(profile.get_summary())
else:
print("Warning: Analysis may be incomplete")Get up and running with TomatoPy in minutes! This guide will walk you through the basics of creating and manipulating virtual ingredients.
from tomatopy import Tomato
# Create a fresh tomato
my_tomato = Tomato(
ripeness=0.8, # 80% ripe
variety="San Marzano",
weight=150 # grams
)
# Check tomato properties
print(my_tomato.ripeness) # 0.8
print(my_tomato.variety) # "San Marzano"from tomatopy import Kitchen
# Initialize your kitchen
kitchen = Kitchen()
# Configure kitchen settings
kitchen.set_temperature(180) # Celsius
kitchen.set_humidity(65) # Percentage# Create a sauce from your tomato
sauce = kitchen.cook(
my_tomato,
method="simmer",
duration="30m",
temperature=100
)
# Check sauce properties
print(sauce.consistency) # "smooth"
print(sauce.volume) # 250 # mlfrom tomatopy import Ingredient, Recipe
# Create additional ingredients
garlic = Ingredient("garlic", amount=3, unit="cloves")
basil = Ingredient("basil", amount=10, unit="leaves")
# Create a recipe
marinara = Recipe("Classic Marinara")
marinara.add_ingredient(my_tomato)
marinara.add_ingredient(garlic)
marinara.add_ingredient(basil)
# Cook the recipe
sauce = kitchen.cook_recipe(marinara)from tomatopy import TasteTester
# Create a taste tester
tester = TasteTester()
# Analyze your sauce
profile = tester.analyze(sauce)
# Get taste metrics
print(profile.acidity) # 0.7
print(profile.sweetness) # 0.3
print(profile.umami) # 0.8my_tomato.debug() # Prints detailed information about the tomatofrom tomatopy import TasteTester
# Create a taste tester
tester = TasteTester()
# Analyze a basic ingredient
profile = tester.analyze(tomato)
# Get basic taste metrics
print(f"Sweetness: {profile.sweetness}")
print(f"Acidity: {profile.acidity}")
print(f"Umami: {profile.umami}")# Get detailed taste profile
profile = tester.analyze(
ingredient,
depth="comprehensive",
include_aroma=True,
include_texture=True
)
# Access detailed metrics
print(f"Sweetness: {profile.sweetness}")
print(f"Acidity: {profile.acidity}")
print(f"Umami: {profile.umami}")
print(f"Aroma intensity: {profile.aroma.intensity}")
print(f"Texture score: {profile.texture.score}")# Compare multiple ingredients
comparison = tester.compare(
[tomato1, tomato2, tomato3],
metrics=["sweetness", "acidity", "umami"]
)
# Get comparison results
print(f"Sweetest: {comparison.get_highest('sweetness')}")
print(f"Most acidic: {comparison.get_highest('acidity')}")
print(f"Most umami: {comparison.get_highest('umami')}")# Analyze taste balance
balance = tester.analyze_balance(sauce)
# Get balance metrics
print(f"Overall balance: {balance.overall_score}")
print(f"Sweet-sour ratio: {balance.sweet_sour_ratio}")
print(f"Umami enhancement: {balance.umami_enhancement}")# Analyze aroma
aroma_profile = tester.analyze_aroma(tomato)
# Get aroma metrics
print(f"Aroma intensity: {aroma_profile.intensity}")
print(f"Aroma complexity: {aroma_profile.complexity}")
print(f"Primary notes: {aroma_profile.primary_notes}")# Get detailed aroma profile
aroma_profile = tester.analyze_aroma(
ingredient,
include_secondary_notes=True,
include_tertiary_notes=True
)
# Access detailed aroma metrics
print(f"Primary notes: {aroma_profile.primary_notes}")
print(f"Secondary notes: {aroma_profile.secondary_notes}")
print(f"Tertiary notes: {aroma_profile.tertiary_notes}")# Analyze texture
texture_profile = tester.analyze_texture(tomato)
# Get texture metrics
print(f"Firmness: {texture_profile.firmness}")
print(f"Juiciness: {texture_profile.juiciness}")
print(f"Overall texture: {texture_profile.overall_score}")# Get detailed texture profile
texture_profile = tester.analyze_texture(
ingredient,
include_mouthfeel=True,
include_structural_analysis=True
)
# Access detailed texture metrics
print(f"Firmness: {texture_profile.firmness}")
print(f"Juiciness: {texture_profile.juiciness}")
print(f"Mouthfeel: {texture_profile.mouthfeel}")
print(f"Structural integrity: {texture_profile.structural_integrity}")# Assess quality
quality = tester.assess_quality(tomato)
# Get quality metrics
print(f"Overall quality: {quality.overall_score}")
print(f"Freshness: {quality.freshness}")
print(f"Ripeness: {quality.ripeness}")# Get comprehensive quality assessment
quality = tester.assess_quality(
ingredient,
include_safety=True,
include_shelf_life=True
)
# Access detailed quality metrics
print(f"Overall quality: {quality.overall_score}")
print(f"Safety score: {quality.safety_score}")
print(f"Shelf life estimate: {quality.shelf_life}")# Create taste profile visualization
viz = tester.visualize_profile(profile)
# Display visualization
viz.show()# Create detailed visualization
viz = tester.visualize_profile(
profile,
include_aroma=True,
include_texture=True,
style="radar"
)
# Customize visualization
viz.set_color_scheme("tomato")
viz.set_scale("logarithmic")
viz.show()try:
# Attempt invalid analysis
tester.analyze("invalid_ingredient")
except TasteError as e:
print(f"Error: {e}") # "Invalid ingredient type"
try:
# Attempt invalid comparison
tester.compare([], metrics=["sweetness"])
except ComparisonError as e:
print(f"Error: {e}") # "No ingredients provided for comparison"# Choose analysis depth based on needs
if needs_detailed_analysis:
profile = tester.analyze(ingredient, depth="comprehensive")
else:
profile = tester.analyze(ingredient, depth="basic")# Check result validity
if profile.is_valid():
# Proceed with analysis
print(profile.get_summary())
else:
print("Warning: Analysis may be incomplete")# Handle special cases
if ingredient.is_overripe():
print("Warning: Ingredient may affect taste analysis")