> For the complete documentation index, see [llms.txt](https://water-strategy.gitbook.io/waterstrategy/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://water-strategy.gitbook.io/waterstrategy/zhong-guo-ren/jiao-cheng/pywr-scenarios-reading-external-dataframe-and-adding-custom-rules/create-custom-rule-transcientdecisionparameter.md).

# 创建自定义规则-TranscientDesicionParameter

## 注册自定义规则-TranscientDesicionParameter

<figure><img src="/files/vOGSlRm2bHeok5Qd4T30" alt=""><figcaption></figcaption></figure>

粘贴以下代码，然后单击 “保存” 按钮 ![](/files/GPKl8U1Sc3A0xyIzNwoD)

```python
类瞬态决策参数（参数）：
    “"” 根据当前的时间步返回两个值之一

    这个 “参数” 可以用来对离散决策事件进行建模
     那发生在给定的日期。在此日期之前，“之前”
     返回值，并在此日期之后返回 “之后” 值。

    参数
    ----------
    decision_date：字符串或 Pandas.Timestamp
        决定的触发日期。
    before_parameter
        在决策日期之前使用的值。
    after_parameter：参数
        决策日期之后要使用的值。
    earliest_date：字符串或 Pandas.Timestamp 或 None
        可以将变量设置为的最早日期。默认为 model.timestepper.start
    latest_date：字符串或 Pandas.Timestamp 或 None
        可以将变量设置为的最新日期。默认为 model.timestepper.end
    decision_freq：熊猫频率字符串（默认为 'AS'）
        确定可行日期。例如，“AS” 每隔一段时间都会创建可行的日期
        介于 “最早” 之间的年份_日期`和`最新_日期`。使用了 `pandas` 函数
        内部用于增量日期计算。

    “”

    def __初始化__（自我、模特、决策_日期，之前_参数，之后_参数，最早_日期 = 无，最新_日期=无，决定_freq='as'，**kwargs）：
        super（瞬态决策参数，自我）。__初始化__（型号，**kwargs）
        自我。_决定_日期 = 无
        自我决定_日期 = 决定_约会

        如果不是 isinstance（before_parameter，参数）：
            raise ValueError（'之前的值应该是参数实例。'）
        before_parameter.parameter.parameter.p
        自我。之前_参数 = 之前_参数

        如果不是 isinstance（after_parameter，参数）：
            raise ValueError（'之后值应该是参数实例。'）
        after_parameter.parameter.parameter.param
        自我。之后_参数 = 之后_参数

        # 如果将该类用作变量，则主要使用这些参数。
        自我。_最早_日期 = 无
        最早的自己_日期 = 最早_约会

        自我。_最新_日期 = 无
        自我。最新_日期 = 最新_约会

        自我决定_频率 = 决定_频率
        自我。_可行_日期 = 无
        self.integer_size = 1  # 此参数只有一个整数变量

    def decision_date ():
        def fget（自我）：
            回归自我。_决定_约会

        def fset（自我，价值）：
            if 是实例（值，PD.Timestamp）：
                自我。_决定_日期 = 值
            否则：
                自我。_决定_日期 = pd.to_datetime（值）

        返回本地人 ()

    决定_日期 = 属性 (**决策日期 ()

    def earliest_date ():
        def fget（自我）：
            如果是自我。_最早_日期不是 “无”：
                回归自我。_最早_约会
            否则：
                返回 self.model.timestepper.start

        def fset（自我，价值）：
            if 是实例（值，PD.Timestamp）：
                自我。_最早_日期 = 值
            否则：
                自我。_最早_日期 = pd.to_datetime（值）

        返回本地人 ()

    最早_日期 = 属性 (**earliest_date ())

    def latest_date ():
        def fget（自我）：
            如果是自我。_最新_日期不是 “无”：
                回归自我。_最新_约会
            否则：
                返回 self.model.timestepper.end

        def fset（自我，价值）：
            if 是实例（值，PD.Timestamp）：
                自我。_最新_日期 = 值
            否则：
                自我。_最新_日期 = pd.to_datetime（值）

        返回本地人 ()

    最新_日期 = 属性 (**latest_date ())

    def 设置（自我）：
        super（瞬态决策参数，自我）.setup ()

        # 现在设置此对象用作变量的可行日期。
        自我。_可行_日期 = pd.date_范围（self.earliest_日期，self.latest_date，
                                                 freq=self.decision_freq)

    def 值（self、ts、scenario_index）：

        如果 ts 为无：
            v = self.before_参数.get_值（场景索引）
        elif ts.datetime >= self.decision_date:
            v = self.after_参数.get_值（场景索引）
        否则：
            v = self.before_参数.get_值（场景索引）
        返回 v

    def get_整数_lower_bounds（自我）：
        返回 np.array ([0,], dtype=np.int)

    def get_整数_upper_bounds（自我）：
        返回 np.array ([len (self._可行_日期)-1,], dtype=np.int)

    def 设置_整数_变量（自我、值）：
        # 使用相应的可行日期更新决策日期
        自我决定_日期 = 自我._feasible_dates [值 [0]]

    def get_整数_变量（自我）：
        返回 np.array ([self._可行_dates.get_loc (self.decision)_日期),], dtype=np.int)

    def dump（自身）：

        数据 = {
            '最早_日期': self.earliess_date.isoformat ()，
            '最新_日期': self.latest_date.isoformat ()，
            '决定_日期': self.decision_date.isoformat ()，
            '决定_频率': self.decision_频率
        }

        返回数据

    @classmethod
    def 负载（cls、模型、数据）：

        以前_参数 = 加载_参数（模型，data.pop（'before_parameter'））
        之后_参数 = 加载_参数（模型，data.pop（'after_parameter'））

        返回 cls（模型，之前_参数=之前_参数，之后_参数=之后_参数，**数据）

瞬态决策参数 .register ()

```

现在，在 WaterStrategy 中运行这个网络时，将注册 TranscientDecisionParameter。

保存自定义规则后，请确保它显示在左侧，在本例中为 **参数** 部分

<figure><img src="/files/aFAYEsvb2P5YTLJ43xdx" alt=""><figcaption></figcaption></figure>

## 使用 TranscientDesicion 参数

在这种情况下，我们将把最大音量增加一倍 **新水库** storage node 从 `2045-01-01-01-01`开始

前往 **新水库** storage node 和 “编辑” **最大音量**

<figure><img src="/files/hd6J9GSLxB6P2UEJCsB2" alt="" width="446"><figcaption></figcaption></figure>

在里面选择 **选项** 选项卡 **PYWR\_参数**

<figure><img src="/files/BJfdxM9gCSuYbsNMta34" alt="" width="271"><figcaption></figcaption></figure>

粘贴以下代码，然后单击 **保存**

```
{
  	“类型”：“瞬态决策参数”，
	“之后_参数”:”__新水库__:max_之后的音量”，
	“之前_参数”:”__新水库__:max_之前的音量”，
	“决策日期”：“2045-01-01-__1234567890____”，
	“最新日期”：“2045-01-01-__1234567890____”
}
```

TranscientDesicion参数包含 “之前” 的属性\_参数`和`之后\_参数\`我们必须按如下方式创建：

<figure><img src="/files/nExuERoRcuJnNy9UrH6z" alt=""><figcaption></figcaption></figure>

当我们可以写下新名字时，会打开一个小文本框 **PWR\_参数**，在本例中为\
\_\_**新水库\_\_:max\_之前的音量。** 点击 **输入**。\\

<figure><img src="/files/rRsVLHxXNhmk0FuxqcLS" alt="" width="375"><figcaption></figcaption></figure>

WaterStrategy 将打开参数窗口，粘贴以下代码然后 **保存**

**\_\_新水库\_\_:max\_之前的音量：**

```
{
	“类型”：“常量参数”，
	“值”：120000
}
```

<figure><img src="/files/4SCMxDefIKsvl3s2sBHr" alt=""><figcaption></figcaption></figure>

重复操作以创建参数后的最大音量

**\_\_新水库\_\_:max\_之后的音量：**

```
{
	“类型”：“常量参数”，
	“值”：240000
}
```

作为最后一步，`TranscientDesicion参数`需要 **初始体积比例** 对于 storage node 作为参数继承节点的初始值，在这种情况下，我们将设置为 **0.99**

<figure><img src="/files/myzCSbYKJfLyjAW7ag8e" alt="" width="423"><figcaption></figcaption></figure>

## 结果

正如我们在下图中看到的那样，我们正在使用气候变化合并pywr情景，并在1月1日将所选水库的体积从120.000增加到240.2\_\_1234567890\_\_\_\_\_\_\_\_\_\_ml 2045。

<figure><img src="/files/qvRYUlzyzLOyJBz2Q1PC" alt=""><figcaption><p>模拟体积（新水库）</p></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://water-strategy.gitbook.io/waterstrategy/zhong-guo-ren/jiao-cheng/pywr-scenarios-reading-external-dataframe-and-adding-custom-rules/create-custom-rule-transcientdecisionparameter.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
