2025年4月8日 星期二

修改HUB 8735 Ultra內建範例來控制JQ 6500來播放MP3音樂

 前篇文章:國產WiFi晶片8735 Ultra初體驗


範例一、內建範例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
 This sketch shows how to use GPIO interrupt and doing task in interrupt handler

 At first we light on LED.
 As button pin meets voltage rise signal, then interrupt happen and invoke interrupt handler.
 Then we change LED state.
    If LED was light on, then turn it off.
    If LED was light off, then turn it on.

 Example guide:
 https://www.amebaiot.com/en/amebapro2-arduino-gpio-interrupt/
 */

int button = PUSH_BTN;
int led = LED_BUILTIN;

int ledState = 1;

void button_handler(uint32_t id, uint32_t event)
{
    if (ledState == 0) {
        // turn on LED
        ledState = 1;
        digitalWrite(led, ledState);
    } else {
        // turn off LED
        ledState = 0;
        digitalWrite(led, ledState);
    }
}

void setup()
{
    pinMode(led, OUTPUT);
    digitalWrite(led, ledState);

    pinMode(button, INPUT_IRQ_RISE);
    digitalSetIrqHandler(button, button_handler);
}

void loop()
{
    delay(1000);
}


範例二、把LED控制接腳改成AMB_D0(PF_2 G)

接腳:

JQ6500 SPK+、SPK-接至喇叭的正負極。
JQ6500 Vcc、GND接至HUB 8735 Ultra Vcc和GND
JQ6500 K1接至PF_2

程式:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
 This sketch shows how to use GPIO interrupt and doing task in interrupt handler

 At first we light on LED.
 As button pin meets voltage rise signal, then interrupt happen and invoke interrupt handler.
 Then we change LED state.
    If LED was light on, then turn it off.
    If LED was light off, then turn it on.

 Example guide:
 https://www.amebaiot.com/en/amebapro2-arduino-gpio-interrupt/
 */

int button = PUSH_BTN;
int led = AMB_D0;

int ledState = 1;

void button_handler(uint32_t id, uint32_t event)
{
    if (ledState == 0) {
        // turn on LED
        ledState = 1;
        digitalWrite(led, ledState);
    } else {
        // turn off LED
        ledState = 0;
        digitalWrite(led, ledState);
    }
}

void setup()
{
    pinMode(led, OUTPUT);
    digitalWrite(led, ledState);

    pinMode(button, INPUT_IRQ_RISE);
    digitalSetIrqHandler(button, button_handler);
}

void loop()
{
    delay(1000);
}


傾聽作品:拍掌牛擺頭外也能啟閉鳥叫聲

上一篇文章:彩虹鳥和行動牛



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def on_button_pressed_a():
    radio.send_string("action cow")
input.on_button_pressed(Button.A, on_button_pressed_a)

def on_button_pressed_b():
    radio.send_string("rainbow bird")
input.on_button_pressed(Button.B, on_button_pressed_b)

def on_sound_loud():
    global mode
    if listen == 1:
        mode = (mode + 1) % 2
        basic.show_icon(IconNames.HEART)
        servos.P1.set_angle(60)
        basic.pause(500)
        servos.P1.set_angle(120)
        basic.pause(500)
        servos.P1.set_angle(90)
        basic.show_icon(IconNames.ANGRY)
input.on_sound(DetectedSound.LOUD, on_sound_loud)

listen = 0
mode = 0
strip = neopixel.create(DigitalPin.P2, 4, NeoPixelMode.RGB)
strip.show_rainbow(1, 360)
strip.show()
servos.P1.set_angle(90)
mode = 0
radio.set_group(88)
basic.show_icon(IconNames.ANGRY)
listen = 1
mode = 0

def on_every_interval():
    if mode == 1:
        strip.rotate(1)
        strip.show()
loops.every_interval(500, on_every_interval)

def on_forever():
    global listen
    if mode == 1:
        listen = 0
        for index in range(randint(10, 200)):
            music.play_sound_effect(music.create_sound_effect(WaveShape.SAWTOOTH,
                    randint(1, 5000),
                    randint(1, 5000),
                    randint(0, 1024),
                    randint(0, 1024),
                    randint(40, 100),
                    SoundExpressionEffect.VIBRATO,
                    InterpolationCurve.CURVE),
                SoundExpressionPlayMode.UNTIL_DONE)
        basic.pause(600)
        listen = 1
        basic.pause(randint(1000, 10000))
basic.forever(on_forever)

2025年4月7日 星期一

傾聽作品:彩虹鳥和行動牛

 


MakeCode程式:


Python程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def on_button_pressed_a():
    radio.send_string("action cow")
input.on_button_pressed(Button.A, on_button_pressed_a)

def on_button_pressed_b():
    radio.send_string("rainbow bird")
input.on_button_pressed(Button.B, on_button_pressed_b)

def on_sound_loud():
    global mode
    mode = (mode + 1) % 2
    basic.show_icon(IconNames.HEART)
    servos.P1.set_angle(60)
    basic.pause(500)
    servos.P1.set_angle(120)
    basic.pause(500)
    servos.P1.set_angle(90)
    basic.show_icon(IconNames.ANGRY)
input.on_sound(DetectedSound.LOUD, on_sound_loud)

mode = 0
strip = neopixel.create(DigitalPin.P2, 4, NeoPixelMode.RGB)
strip.show_rainbow(1, 360)
strip.show()
servos.P1.set_angle(90)
mode = 0
radio.set_group(88)
basic.show_icon(IconNames.ANGRY)

def on_every_interval():
    if mode == 1:
        strip.rotate(1)
        strip.show()
loops.every_interval(500, on_every_interval)

def on_forever():
    for index in range(randint(10, 200)):
        music.play_sound_effect(music.create_sound_effect(WaveShape.SAWTOOTH,
                randint(1, 5000),
                randint(1, 5000),
                randint(0, 1024),
                randint(0, 1024),
                randint(40, 100),
                SoundExpressionEffect.VIBRATO,
                InterpolationCurve.CURVE),
            SoundExpressionPlayMode.UNTIL_DONE)
    basic.pause(randint(1000, 10000))
basic.forever(on_forever)


用micro:bit實作小鳥叫聲

參考資料:Jonny’s Bird

用隨機變數取替加速器資料。


Python程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def on_forever():
    for index in range(randint(10, 200)):
        music.play_sound_effect(music.create_sound_effect(WaveShape.SAWTOOTH,
                randint(1, 5000),
                randint(1, 5000),
                randint(0, 1024),
                randint(0, 1024),
                randint(40, 100),
                SoundExpressionEffect.VIBRATO,
                InterpolationCurve.CURVE),
            SoundExpressionPlayMode.UNTIL_DONE)
    basic.pause(randint(1000, 10000))
basic.forever(on_forever)


2025年4月6日 星期日

加入影響力因子重新計算水井USR的SROI

1.加入無謂因子(Deadweight) 的程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class SROICalculator:
    def __init__(self):
        self.inputs = {}
        self.outcomes = {}

    def add_input(self, item, amount):
        self.inputs[item] = self.inputs.get(item, 0) + amount

    def add_outcome(self, item, amount, deadweight=0):
        adjusted_amount = amount * (1 - deadweight)
        self.outcomes[item] = self.outcomes.get(item, 0) + adjusted_amount

    def calculate_sroi(self):
        total_input = sum(self.inputs.values())
        total_outcome = sum(self.outcomes.values())
        if total_input == 0:
            return float('inf')
        return round((total_outcome - total_input) / total_input, 2)

    def summary(self):
        print("📦 成本投入:")
        for k, v in self.inputs.items():
            print(f"  - {k}: NT${v}")
        print("\n🎯 調整後效益(扣除 Deadweight):")
        for k, v in self.outcomes.items():
            print(f"  - {k}: NT${v}")
        print(f"\n💡 SROI = {self.calculate_sroi()}")

# ✅ 實例:水井村案例模擬
sroi_calc = SROICalculator()

# 📦 成本投入
sroi_calc.add_input("IoT設備與感測器", 120000)
sroi_calc.add_input("水質淨化系統", 80000)
sroi_calc.add_input("教學與培訓費用", 100000)
sroi_calc.add_input("工藝材料與推廣", 50000)

# 🎯 效益(已考量 Deadweight)
sroi_calc.add_outcome("節省水資源成本", 50000, deadweight=0.15)  # 15%
sroi_calc.add_outcome("減碳社會效益(估算)", 70000, deadweight=0.10)  # 10%
sroi_calc.add_outcome("智慧養殖提升產值", 150000, deadweight=0.25)  # 25%
sroi_calc.add_outcome("地方品牌提升與觀光收益", 60000, deadweight=0.40)  # 40%
sroi_calc.add_outcome("居民生活與文化參與提升(估算)", 30000, deadweight=0.35)  # 35%

# ⏱️ 輸出結果
sroi_calc.summary()

執行結果:
📦 成本投入:
  - IoT設備與感測器: NT$120000
  - 水質淨化系統: NT$80000
  - 教學與培訓費用: NT$100000
  - 工藝材料與推廣: NT$50000

🎯 調整後效益(扣除 Deadweight):
  - 節省水資源成本: NT$42500.0
  - 減碳社會效益(估算): NT$63000.0
  - 智慧養殖提升產值: NT$112500.0
  - 地方品牌提升與觀光收益: NT$36000.0
  - 居民生活與文化參與提升(估算): NT$19500.0

💡 SROI = -0.22

2.再加入歸因因子(Attribution)和衰減因子(Drop-off)的程式(以3年為期):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class SROICalculator:
    def __init__(self):
        self.inputs = {}
        self.outcomes = {}

    def add_input(self, item, amount):
        self.inputs[item] = self.inputs.get(item, 0) + amount

    def add_outcome(self, item, amount, deadweight=0, attribution=0, dropoff=0, years=1):
        adjusted_total = 0
        for year in range(years):
            year_factor = (1 - dropoff) ** year
            adjusted = amount * (1 - deadweight) * (1 - attribution) * year_factor
            adjusted_total += adjusted
        self.outcomes[item] = self.outcomes.get(item, 0) + adjusted_total

    def calculate_sroi(self):
        total_input = sum(self.inputs.values())
        total_outcome = sum(self.outcomes.values())
        if total_input == 0:
            return float('inf')
        return round((total_outcome - total_input) / total_input, 2)

    def summary(self):
        print("📦 成本投入:")
        for k, v in self.inputs.items():
            print(f"  - {k}: NT${v}")
        print("\n🎯 調整後效益(扣除 Deadweight、歸因、遞減):")
        for k, v in self.outcomes.items():
            print(f"  - {k}: NT${round(v, 2)}")
        print(f"\n💡 SROI = {self.calculate_sroi()}")


sroi_calc = SROICalculator()

# 📦 成本投入
sroi_calc.add_input("IoT設備與感測器", 120000)
sroi_calc.add_input("水質淨化系統", 80000)
sroi_calc.add_input("教學與培訓費用", 100000)
sroi_calc.add_input("工藝材料與推廣", 50000)

# 🎯 效益:含 Deadweight、Attribution、Drop-off、years
sroi_calc.add_outcome("節省水資源成本", 50000, deadweight=0.15, attribution=0.1, dropoff=0.05, years=3)
sroi_calc.add_outcome("減碳社會效益(估算)", 70000, deadweight=0.10, attribution=0.1, dropoff=0.05, years=3)
sroi_calc.add_outcome("智慧養殖提升產值", 150000, deadweight=0.25, attribution=0.15, dropoff=0.1, years=3)
sroi_calc.add_outcome("地方品牌提升與觀光收益", 60000, deadweight=0.4, attribution=0.2, dropoff=0.1, years=3)
sroi_calc.add_outcome("居民生活與文化參與提升(估算)", 30000, deadweight=0.35, attribution=0.15, dropoff=0.05, years=3)

# ⏱️ 輸出結果
sroi_calc.summary()

執行結果:
📦 成本投入:
  - IoT設備與感測器: NT$120000
  - 水質淨化系統: NT$80000
  - 教學與培訓費用: NT$100000
  - 工藝材料與推廣: NT$50000

🎯 調整後效益(扣除 Deadweight、歸因、遞減):
  - 節省水資源成本: NT$109108.12
  - 減碳社會效益(估算): NT$161736.75
  - 智慧養殖提升產值: NT$259143.75
  - 地方品牌提升與觀光收益: NT$78048.0
  - 居民生活與文化參與提升(估算): NT$47280.19

💡 SROI = 0.87

3.再加入移轉因子(Displacement),其程式如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class SROICalculator:
    def __init__(self):
        self.inputs = {}
        self.outcomes = {}

    def add_input(self, item, amount):
        self.inputs[item] = self.inputs.get(item, 0) + amount

    def add_outcome(self, item, amount, deadweight=0, attribution=0, displacement=0, dropoff=0, years=1):
        adjusted_total = 0
        for year in range(years):
            year_factor = (1 - dropoff) ** year
            adjusted = amount * (1 - deadweight) * (1 - attribution) * (1 - displacement) * year_factor
            adjusted_total += adjusted
        self.outcomes[item] = self.outcomes.get(item, 0) + adjusted_total

    def calculate_sroi(self):
        total_input = sum(self.inputs.values())
        total_outcome = sum(self.outcomes.values())
        if total_input == 0:
            return float('inf')
        return round((total_outcome - total_input) / total_input, 2)

    def summary(self):
        print("📦 成本投入:")
        for k, v in self.inputs.items():
            print(f"  - {k}: NT${v}")
        print("\n🎯 調整後效益(扣除 Deadweight、歸因、移轉、遞減):")
        for k, v in self.outcomes.items():
            print(f"  - {k}: NT${round(v, 2)}")
        print(f"\n💡 SROI = {self.calculate_sroi()}")

sroi_calc = SROICalculator()

# 📦 成本投入
sroi_calc.add_input("IoT設備與感測器", 120000)
sroi_calc.add_input("水質淨化系統", 80000)
sroi_calc.add_input("教學與培訓費用", 100000)
sroi_calc.add_input("工藝材料與推廣", 50000)

# 🎯 效益(含 Deadweight、Attribution、Displacement、Drop-off、Years)
sroi_calc.add_outcome("節省水資源成本", 50000, deadweight=0.15, attribution=0.1, displacement=0.0, dropoff=0.05, years=3)
sroi_calc.add_outcome("減碳社會效益(估算)", 70000, deadweight=0.10, attribution=0.1, displacement=0.0, dropoff=0.05, years=3)
sroi_calc.add_outcome("智慧養殖提升產值", 150000, deadweight=0.25, attribution=0.15, displacement=0.05, dropoff=0.1, years=3)
sroi_calc.add_outcome("地方品牌提升與觀光收益", 60000, deadweight=0.4, attribution=0.2, displacement=0.3, dropoff=0.1, years=3)
sroi_calc.add_outcome("居民生活與文化參與提升", 30000, deadweight=0.35, attribution=0.15, displacement=0.0, dropoff=0.05, years=3)

# ⏱️ 輸出結果
sroi_calc.summary()

執行結果:
📦 成本投入:
  - IoT設備與感測器: NT$120000
  - 水質淨化系統: NT$80000
  - 教學與培訓費用: NT$100000
  - 工藝材料與推廣: NT$50000

🎯 調整後效益(扣除 Deadweight、歸因、移轉、遞減):
  - 節省水資源成本: NT$109108.12
  - 減碳社會效益(估算): NT$161736.75
  - 智慧養殖提升產值: NT$246186.56
  - 地方品牌提升與觀光收益: NT$54633.6
  - 居民生活與文化參與提升: NT$47280.19

💡 SROI = 0.77

2025年4月5日 星期六

依照水井USR目標實作Python模組並計算SROI

水井村智慧減碳節水三生一體社會實踐計畫的整體發展目標是通過低碳智慧養殖、生態節水、以及三生共好永續發展平台的整合,實現水井村的生態環境保護、生產效率提升及生活品質改善,具體目標包括:

  • 環境生態保護:減少碳排放和水資源浪費,發展淨水技術,改善當地生態環境,保護水下和陸上生物。
  • 生產效率提升:發展低成本、低碳和節水的智慧養殖技術,提高養殖業的生產效率和品質,促進當地經濟發展。
  • 生活品質改善:用藝文提高村民的生活品質,通過智慧科技教育和工藝產品設計技術提升水井村的品牌形象。
🌱 一、環境生態保護模組WaterPurificationSyste
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class WaterPurificationSystem:
    def __init__(self, dirty_water_liters):
        self.dirty_water = dirty_water_liters
        self.clean_water = 0
        self.energy_used = 0  # kWh
    
    def purify(self, method='biological'):
        if method == 'biological':
            efficiency = 0.7
            energy = 0.2  # per liter
        elif method == 'filtration':
            efficiency = 0.85
            energy = 0.4
        else:
            efficiency = 0.5
            energy = 0.3
        
        purified = self.dirty_water * efficiency
        self.clean_water += purified
        self.energy_used += purified * energy
        self.dirty_water -= purified
        print(f"使用 {method} 淨化方式,產出 {purified:.2f} 公升的淨水")

# 示例
system = WaterPurificationSystem(100)
system.purify('biological')
system.purify('filtration')

執行結果:
使用 biological 淨化方式,產出 70.00 公升的淨水
使用 filtration 淨化方式,產出 25.50 公升的淨水

🐟 二、生產效率提升模組:SmartAquacultureTank

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class SmartAquacultureTank:
    def __init__(self, fish_count, water_temp):
        self.fish_count = fish_count
        self.water_temp = water_temp  # °C
        self.feeding_amount = 0  # grams
        self.energy_usage = 0  # kWh

    def feed(self, grams):
        self.feeding_amount += grams
        self.energy_usage += 0.1  # 每次投餵耗能
        print(f"餵食 {grams} 克魚飼料,目前總餵食量:{self.feeding_amount} 克")

    def adjust_temperature(self, target_temp):
        energy_needed = abs(self.water_temp - target_temp) * 0.5
        self.water_temp = target_temp
        self.energy_usage += energy_needed
        print(f"水溫調整至 {self.water_temp}°C,耗能 {energy_needed:.2f} kWh")

# 示例
tank = SmartAquacultureTank(50, 26)
tank.feed(300)
tank.adjust_temperature(28)

執行結果:
餵食 300 克魚飼料,目前總餵食量:300 克
水溫調整至 28°C,耗能 1.00 kWh

🎨 三、生活品質改善模組:CraftProduct

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class CraftProduct:
    def __init__(self, name, material, eco_friendly=True):
        self.name = name
        self.material = material
        self.eco_friendly = eco_friendly
        self.price = 0

    def set_price(self, base_price):
        self.price = base_price * (0.9 if self.eco_friendly else 1.2)
        print(f"{self.name} 的定價為 NT${self.price:.0f}")

    def describe(self):
        type_text = "環保材料" if self.eco_friendly else "一般材料"
        print(f"{self.name} 使用 {type_text} 製成,主要材質:{self.material}")

# 示例
flower_lamp = CraftProduct("玉米籜彩燈", "玉米籜")
flower_lamp.set_price(300)
flower_lamp.describe()

執行結果:
玉米籜彩燈 的定價為 NT$270
玉米籜彩燈 使用 環保材料 製成,主要材質:玉米籜

🌏 「智慧村落模擬器」專案:smart_village_simulator.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class WaterPurificationSystem:
    def __init__(self, dirty_water_liters):
        self.dirty_water = dirty_water_liters
        self.clean_water = 0
        self.energy_used = 0

    def purify(self, method='biological'):
        if method == 'biological':
            efficiency = 0.7
            energy = 0.2
        elif method == 'filtration':
            efficiency = 0.85
            energy = 0.4
        else:
            efficiency = 0.5
            energy = 0.3

        purified = self.dirty_water * efficiency
        self.clean_water += purified
        self.energy_used += purified * energy
        self.dirty_water -= purified
        print(f"[環境] 使用 {method} 淨化方式,產出 {purified:.2f} 公升淨水。")


class SmartAquacultureTank:
    def __init__(self, fish_count, water_temp):
        self.fish_count = fish_count
        self.water_temp = water_temp
        self.feeding_amount = 0
        self.energy_usage = 0

    def feed(self, grams):
        self.feeding_amount += grams
        self.energy_usage += 0.1
        print(f"[生產] 餵食 {grams} 克,總餵食量:{self.feeding_amount} 克")

    def adjust_temperature(self, target_temp):
        energy_needed = abs(self.water_temp - target_temp) * 0.5
        self.water_temp = target_temp
        self.energy_usage += energy_needed
        print(f"[生產] 水溫調整至 {self.water_temp}°C,耗能 {energy_needed:.2f} kWh")


class CraftProduct:
    def __init__(self, name, material, eco_friendly=True):
        self.name = name
        self.material = material
        self.eco_friendly = eco_friendly
        self.price = 0

    def set_price(self, base_price):
        self.price = base_price * (0.9 if self.eco_friendly else 1.2)
        print(f"[生活] 工藝品 {self.name} 定價:NT${self.price:.0f}")

    def describe(self):
        type_text = "環保材料" if self.eco_friendly else "一般材料"
        print(f"[生活] {self.name} 使用 {type_text} 製成,主要材質:{self.material}")


class SmartVillageSimulator:
    def __init__(self):
        self.water_system = WaterPurificationSystem(200)
        self.aqua_tank = SmartAquacultureTank(100, 25)
        self.craft_products = []

    def run_simulation(self):
        print("📍 模擬啟動:水井村智慧三生實踐")

        # 環境模組
        self.water_system.purify('biological')

        # 生產模組
        self.aqua_tank.feed(500)
        self.aqua_tank.adjust_temperature(27)

        # 生活模組
        lamp = CraftProduct("玉米殼花燈", "玉米殼")
        lamp.set_price(350)
        lamp.describe()
        self.craft_products.append(lamp)

        self.summary()

    def summary(self):
        print("\n📊 【模擬總結】")
        print(f"淨水量:{self.water_system.clean_water:.2f} 公升")
        print(f"淨水耗能:{self.water_system.energy_used:.2f} kWh")
        print(f"養殖耗能:{self.aqua_tank.energy_usage:.2f} kWh")
        print(f"工藝產品數量:{len(self.craft_products)} 項")


# 主程式執行
if __name__ == "__main__":
    sim = SmartVillageSimulator()
    sim.run_simulation()

執行結果:
📍 模擬啟動:水井村智慧三生實踐
[環境] 使用 biological 淨化方式,產出 140.00 公升淨水。
[生產] 餵食 500 克,總餵食量:500 克
[生產] 水溫調整至 27°C,耗能 1.00 kWh
[生活] 工藝品 玉米殼花燈 定價:NT$315
[生活] 玉米殼花燈 使用 環保材料 製成,主要材質:玉米殼

📊 【模擬總結】
淨水量:140.00 公升
淨水耗能:28.00 kWh
養殖耗能:1.10 kWh
工藝產品數量:1 項

五、計算SROI值
SROI = (總社會效益價值 - 投入成本) / 投入成本


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class SROICalculator:
    def __init__(self):
        self.inputs = {}       # 成本投入(項目:金額)
        self.outcomes = {}     # 效益產出(項目:金額)
    
    def add_input(self, item, amount):
        self.inputs[item] = self.inputs.get(item, 0) + amount

    def add_outcome(self, item, amount):
        self.outcomes[item] = self.outcomes.get(item, 0) + amount

    def calculate_sroi(self):
        total_input = sum(self.inputs.values())
        total_outcome = sum(self.outcomes.values())
        if total_input == 0:
            return float('inf')  # 無投入代表SROI無限大
        sroi = (total_outcome - total_input) / total_input
        return round(sroi, 2)

    def summary(self):
        print("📦 成本投入項目:")
        for k, v in self.inputs.items():
            print(f"  - {k}: NT${v}")
        print("\n🎯 效益產出項目:")
        for k, v in self.outcomes.items():
            print(f"  - {k}: NT${v}")
        print(f"\n💡 SROI = {self.calculate_sroi()}")

# 實例:水井村案例模擬
sroi_calc = SROICalculator()

# 📦 成本投入
sroi_calc.add_input("IoT設備與感測器", 120000)
sroi_calc.add_input("水質淨化系統", 80000)
sroi_calc.add_input("教學與培訓費用", 100000)
sroi_calc.add_input("工藝材料與推廣", 50000)

# 🎯 效益(將社會效益轉換為估算金額)
sroi_calc.add_outcome("節省水資源成本", 50000)
sroi_calc.add_outcome("減碳社會效益(估算)", 70000)
sroi_calc.add_outcome("智慧養殖提升產值", 150000)
sroi_calc.add_outcome("地方品牌提升與觀光收益", 60000)
sroi_calc.add_outcome("居民生活與文化參與提升(估算)", 30000)

# ⏱️ 輸出結果
sroi_calc.summary()

執行結果:
📦 成本投入項目:
  - IoT設備與感測器: NT$120000
  - 水質淨化系統: NT$80000
  - 教學與培訓費用: NT$100000
  - 工藝材料與推廣: NT$50000

🎯 效益產出項目:
  - 節省水資源成本: NT$50000
  - 減碳社會效益(估算): NT$70000
  - 智慧養殖提升產值: NT$150000
  - 地方品牌提升與觀光收益: NT$60000
  - 居民生活與文化參與提升(估算): NT$30000

💡 SROI = 0.03

註:表示每投入 1 元,社會可獲得 1.18 元的價值回報。

USR教材:用水井三寶設計python類別


參考資料:水井姻緣花1

用水井三寶做為提問ChatGPT,獲得下列程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 定義一個基礎寶物類別
class Treasure:
    def __init__(self, name, meaning, age):
        self.name = name
        self.meaning = meaning
        self.age = age

    def describe(self):
        return f"{self.name}:象徵 {self.meaning},已有 {self.age} 年歷史。"

    def __str__(self):
        return self.describe()

# 三寶:烏龜、白馬、番花

class Turtle(Treasure):
    def __init__(self):
        super().__init__("烏龜", "風水與守護", 300)

class WhiteHorse(Treasure):
    def __init__(self):
        super().__init__("白馬", "信仰與傳說", 150)

class Frangipani(Treasure):  # 雞蛋花的英文名稱
    def __init__(self):
        super().__init__("番花", "歷史與生命", 300)

# 建立物件
turtle = Turtle()
horse = WhiteHorse()
flower = Frangipani()

# 顯示介紹(透過 print(object) 直接呼叫 __str__)
print(turtle)
print(horse)
print(flower)

執行結果:
烏龜:象徵 風水與守護,已有 300 年歷史。
白馬:象徵 信仰與傳說,已有 150 年歷史。
番花:象徵 歷史與生命,已有 300 年歷史。

註:這些歷史時間只是ChatGPT對程式的預設值,需要再考證。