-- HH: hier sollen tatsächlich params und ppos getrennt hineingefuehrt werden,
-- damit man die Funktion auch für andere Positionen verwenden kann.

signCorrectedOptimalPowerMatrices ::
  (Ord a, Arith.Sum a, Arith.Constant a, Show node, Ord node,
   Vec.Storage varVec (Maybe (Result a)),
   Vec.FromList varVec) =>
  Params.System node a ->
  ReqsAndDofs.Dofs (TopoIdx.Position node) ->
  Map [a] (Maybe (a, a, Idx.State, Int, EnvResult node a)) ->
  Map (TopoIdx.Position node) (Sig.PSignal2 Vector varVec (Maybe (Result a)))
signCorrectedOptimalPowerMatrices systemParams (ReqsAndDofs.Dofs ppos) m =
  Map.fromList $ map g ppos
  where g pos = (pos, ModUt.to2DMatrix $ Map.map f m)
          where f Nothing = Nothing
                f (Just (_, _, st, _, graph)) =
                  case StateQty.lookup (StateIdx.powerFromPosition st pos) graph of
                       Just sig -> Just $
                         if isFlowDirectionPositive systemParams st pos graph
                            then sig
                            else fmap Arith.negate sig
                       _ -> fmap (const (Determined Arith.zero))
                                 (getEdgeFromPosition st pos graph)


signCorrectedOptimalPowerMatrices ::
  (Ord a, Arith.Sum a, Arith.Constant a, Show node, Ord node,
   Vec.Storage varVec (Maybe (Result a)),
   Vec.FromList varVec) =>
  Params.System node a ->
  ReqsAndDofs.Dofs (TopoIdx.Position node) ->
  Map [a] (Maybe (a, a, Idx.State, Int, EnvResult node a)) ->
  Map (TopoIdx.Position node) (Sig.PSignal2 Vector varVec (Maybe (Result a)))
signCorrectedOptimalPowerMatrices systemParams (ReqsAndDofs.Dofs ppos) m =
  Map.fromList $ map g ppos
  where g pos = (pos, ModUt.to2DMatrix $ Map.map f m)
          where f Nothing = Nothing
                f (Just (_, _, st, _, graph)) =
                  case StateQty.lookup (StateIdx.powerFromPosition st pos) graph of
                       Just sig -> Just $
                         if isFlowDirectionPositive systemParams st pos graph
                            then sig
                            else fmap Arith.negate sig
                       _ -> fmap (const (Determined Arith.zero))
                                 (getEdgeFromPosition st pos graph)
signCorrectedOptimalPowerMatrices systemParams (ReqsAndDofs.Dofs ppos) m =
  Map.fromList $ map g ppos
  where g pos = (pos, ModUt.to2DMatrix $ Map.map f m)
          where f Nothing = Nothing
                f (Just (_, _, st, _, graph)) =
                  case StateQty.lookup (StateIdx.powerFromPosition st pos) graph of
                       Just sig -> Just $
                         if isFlowDirectionPositive systemParams st pos graph
                            then sig
                            else fmap Arith.negate sig
                       _ -> fmap (const (Determined Arith.zero))
                                 (getEdgeFromPosition st pos graph)