DmitrMakeev commited on
Commit
8f645d5
·
verified ·
1 Parent(s): 6c19f61

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -25
app.py CHANGED
@@ -809,11 +809,11 @@ class NutrientCalculator:
809
  'N (NO3-)': 0.0017, 'N (NH4+)': 0.0019
810
  }
811
 
812
- # Веса для компенсации (приоритеты)
813
  self.compensation_weights = {
814
- 'Калий азотнокислый': {'weight': 0.8, 'main_elements': ['K', 'N (NO3-)']},
815
- 'Кальциевая селитра': {'weight': 0.1, 'main_elements': ['Ca', 'N (NO3-)']},
816
- 'Калий сернокислый': {'weight': 0.1, 'main_elements': ['K', 'S']}
817
  }
818
 
819
  def _apply_fertilizer(self, fert_name: str, element: str, ppm: float):
@@ -856,44 +856,42 @@ class NutrientCalculator:
856
  return round(self.total_ec, 2)
857
 
858
  def _compensate_element(self, element: str, needed_ppm: float):
859
- """Исправленная компенсация с правильным учетом весов"""
860
- # Находим все подходящие удобрения
861
  suitable_ferts = []
862
- for fert_name, fert_data in self.fertilizers.items():
863
- if element in fert_data:
864
- weight = self.compensation_weights.get(fert_name, {}).get('weight', 0.1)
865
  suitable_ferts.append({
866
  'name': fert_name,
867
- 'weight': weight,
868
- 'content': fert_data[element]
869
  })
870
 
871
  if not suitable_ferts:
872
  raise ValueError(f"Нет удобрений для элемента {element}")
873
 
874
- # Сортируем по весу (убывание)
875
- suitable_ferts.sort(key=lambda x: x['weight'], reverse=True)
876
-
877
  # Рассчитываем общий вес для нормализации
878
  total_weight = sum(f['weight'] for f in suitable_ferts)
879
 
 
880
  remaining_ppm = needed_ppm
881
  for fert in suitable_ferts:
882
  if remaining_ppm <= 0:
883
  break
884
 
885
- # Рассчитываем долю этого удобрения
886
  share = fert['weight'] / total_weight
887
  ppm_to_apply = remaining_ppm * share
888
 
889
- # Вносим рассчитанную долю
890
  self._apply_fertilizer(fert['name'], element, ppm_to_apply)
891
 
892
- # Обновляем оставшийся дефицит
893
  remaining_ppm = self.target_profile[element] - self.actual_profile[element]
894
 
895
  def calculate(self):
896
- """Основной расчет с исправленной компенсацией"""
897
  try:
898
  # 1. Вносим магний (сульфат магния)
899
  self._apply_fertilizer("Сульфат магния", "Mg", self.target_profile['Mg'])
@@ -901,14 +899,16 @@ class NutrientCalculator:
901
  # 2. Вносим аммонийный азот
902
  self._apply_fertilizer("Аммоний азотнокислый", "N (NH4+)", self.target_profile['N (NH4+)'])
903
 
904
- # 3. Компенсируем нитратный азот с учетом весов
905
- self._compensate_element("N (NO3-)", self.target_profile['N (NO3-)'])
 
906
 
907
  # 4. Вносим фосфор
908
  self._apply_fertilizer("Монофосфат калия", "P", self.target_profile['P'])
909
 
910
- # 5. Компенсируем калий с учетом весов
911
- self._compensate_element("K", self.target_profile['K'])
 
912
 
913
  # 6. Компенсируем кальций (если нужно)
914
  ca_needed = self.target_profile['Ca'] - self.actual_profile['Ca']
@@ -920,7 +920,7 @@ class NutrientCalculator:
920
  except Exception as e:
921
  raise RuntimeError(f"Ошибка расчета: {str(e)}")
922
 
923
- def _prepare_results(self) -> Dict[str, Any]:
924
  """Подготовка результатов для API"""
925
  return {
926
  'actual_profile': {k: round(v, 2) for k, v in self.actual_profile.items()},
@@ -943,8 +943,6 @@ class NutrientCalculator:
943
  }
944
 
945
 
946
-
947
-
948
  @app.route('/calculation', methods=['POST'])
949
  def handle_calculation():
950
  try:
 
809
  'N (NO3-)': 0.0017, 'N (NH4+)': 0.0019
810
  }
811
 
812
+ # Новая структура весов для компенсации
813
  self.compensation_weights = {
814
+ 'POTASSIUM_NITRATE': {'weight': 0.5, 'fert': 'Калий азотнокислый', 'main_element': 'K'},
815
+ 'CALCIUM_NITRATE': {'weight': 0.3, 'fert': 'Кальциевая селитра', 'main_element': 'Ca'},
816
+ 'POTASSIUM_SULFATE': {'weight': 0.2, 'fert': 'Калий сернокислый', 'main_element': 'K'}
817
  }
818
 
819
  def _apply_fertilizer(self, fert_name: str, element: str, ppm: float):
 
856
  return round(self.total_ec, 2)
857
 
858
  def _compensate_element(self, element: str, needed_ppm: float):
859
+ """Исправленная компенсация с учетом новых весов и приоритетов азота"""
860
+ # Находим подходящие удобрения для элемента
861
  suitable_ferts = []
862
+ for fert_key, fert_data in self.compensation_weights.items():
863
+ fert_name = fert_data['fert']
864
+ if fert_name in self.fertilizers and element in self.fertilizers[fert_name]:
865
  suitable_ferts.append({
866
  'name': fert_name,
867
+ 'weight': fert_data['weight'],
868
+ 'content': self.fertilizers[fert_name][element]
869
  })
870
 
871
  if not suitable_ferts:
872
  raise ValueError(f"Нет удобрений для элемента {element}")
873
 
 
 
 
874
  # Рассчитываем общий вес для нормализации
875
  total_weight = sum(f['weight'] for f in suitable_ferts)
876
 
877
+ # Распределяем дефицит пропорционально весам
878
  remaining_ppm = needed_ppm
879
  for fert in suitable_ferts:
880
  if remaining_ppm <= 0:
881
  break
882
 
883
+ # Вычисляем долю удобрения
884
  share = fert['weight'] / total_weight
885
  ppm_to_apply = remaining_ppm * share
886
 
887
+ # Вносим удобрение
888
  self._apply_fertilizer(fert['name'], element, ppm_to_apply)
889
 
890
+ # Обновляем остаток дефицита
891
  remaining_ppm = self.target_profile[element] - self.actual_profile[element]
892
 
893
  def calculate(self):
894
+ """Основной расчет с учетом новых приоритетов"""
895
  try:
896
  # 1. Вносим магний (сульфат магния)
897
  self._apply_fertilizer("Сульфат магния", "Mg", self.target_profile['Mg'])
 
899
  # 2. Вносим аммонийный азот
900
  self._apply_fertilizer("Аммоний азотнокислый", "N (NH4+)", self.target_profile['N (NH4+)'])
901
 
902
+ # 3. Компенсируем нитратный азот с учетом новых весов
903
+ if self.target_profile['N (NO3-)'] > 0:
904
+ self._compensate_element("N (NO3-)", self.target_profile['N (NO3-)'])
905
 
906
  # 4. Вносим фосфор
907
  self._apply_fertilizer("Монофосфат калия", "P", self.target_profile['P'])
908
 
909
+ # 5. Компенсируем калий с учетом новых весов
910
+ if self.target_profile['K'] > self.actual_profile['K']:
911
+ self._compensate_element("K", self.target_profile['K'] - self.actual_profile['K'])
912
 
913
  # 6. Компенсируем кальций (если нужно)
914
  ca_needed = self.target_profile['Ca'] - self.actual_profile['Ca']
 
920
  except Exception as e:
921
  raise RuntimeError(f"Ошибка расчета: {str(e)}")
922
 
923
+ def _prepare_results(self) -> dict:
924
  """Подготовка результатов для API"""
925
  return {
926
  'actual_profile': {k: round(v, 2) for k, v in self.actual_profile.items()},
 
943
  }
944
 
945
 
 
 
946
  @app.route('/calculation', methods=['POST'])
947
  def handle_calculation():
948
  try: