質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

2回答

468閲覧

関数内での引数の渡しが上手く機能していない

IT_takumin

総合スコア8

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2022/11/30 03:16

前提

エージェントベースモデルのシミュレーションを行う環境を作ろうとしています。

実現したいこと

追加したbrake関数が機能する様にしたい。

発生している問題・エラーメッセージ

TypeError: update() missing 1 required positional argument: 'others'

該当のソースコード

python

1import numpy as np 2import matplotlib.pyplot as plt 3import matplotlib.animation as animation 4from IPython.display import HTML 5import _ctypes 6 7a1 = -0.034298 8b1 = 3.348394 9c1 = 4.252840 10d1 = -0.003423 11 12survival=dict() 13crash=0 14 15 16class Agent: 17 def __init__(self, name = None, pos = None, vel = None, SIZE = 10, VEL = 1, 18 RANGE_SEPARATE = 1.0,color = None): 19 self.name = name if name else 'agent_02' 20 self.pos = pos if pos else np.random.uniform(-SIZE, SIZE, 2) 21 self.vel = vel if vel else np.random.uniform(-VEL, VEL, 2) 22 self.SIZE = SIZE 23 self.VEL = VEL 24 self.RANGE_SEPARATE = RANGE_SEPARATE#分離範囲 25 self.vel_tmp = np.zeros(2)#移動 26 self.color = color if color else 'k' 27 28 29 def distance(self, other):#ユークリッド距離 30 return np.linalg.norm(self.pos - other.pos) 31 32 def ruleSeparate(self, others, ratio = 1): 33 others = [other for other in others if self.distance(other) < self.RANGE_SEPARATE]#範囲内に入ったエージェントの選別 34 v = np.zeros(2) 35 if not others: 36 return 0 37 for other in others: 38 d = self.pos - other.pos#dが-になる時ある? 39 v += d / self.distance(other)#進行方向の単位ベクトル 40 self.vel_tmp += v / len(others) * ratio#平均を出してそれをratio倍する 41 return v / len(others) * ratio 42 43 44 45 def calculate(self, others): 46 self.ruleSeparate(others, 1.0) 47 48 def update(self) -> bool:#返り値の型名 49 self.vel += self.vel_tmp#進行速度ベクトル更新 50 v = np.linalg.norm(self.vel) 51 #壁に当たったら反転 52 if (abs(self.pos + self.vel)[0] > self.SIZE): 53 self.vel[0] = -self.vel[0] 54 if (abs(self.pos + self.vel)[1] > self.SIZE): 55 self.vel[1] = -self.vel[1] 56 57 self.pos += self.vel#位置更新 58 self.vel_tmp = np.zeros(2)##進行速度ベクトル初期化 59 return True 60 61class AgentEdited(Agent): 62 def __init__(self, *args, **kwargs): 63 super(AgentEdited, self).__init__(*args, **kwargs) 64 #クラス(子クラス)で別のクラス(親クラス)を継承できます。継承することで、親クラスのメソッドを子クラスから呼び出せる 65 #super().親クラスのメソッド # python3系での標準の書き方 66 #super(親クラスのオブジェクト, self).親クラスのメソッド # python2系での書き方 67 #不特定多数の引数を受け取ることができる仕組みを作るのが「*args」「**kwargs」 68 self.color = kwargs.get('color', 'r') 69 self.name=kwargs.get('name','agent_01') 70 71 max_distance = 0 72 self.goal = None # 角が一番遠い場所 73 for px in [-self.SIZE, self.SIZE]: 74 for py in [-self.SIZE, self.SIZE]: 75 dist = np.linalg.norm(self.pos - np.array([px, py])) 76 if max_distance < dist: 77 max_distance = dist#最大値の更新 78 self.goal = np.array([px, py]) 79 80 81 82 def ruleSeparate(self, others, ratio = 1): 83 others = [other for other in others if self.distance(other) < self.RANGE_SEPARATE] 84 v = np.zeros(2) 85 if not others: 86 return 0 87 for other in others: 88 d = self.pos - other.pos 89 vel = self.vel - other.vel 90 TTNP = d / (vel + 1e-5) # 0除算防止のため微小値を挿入 91 DINP = self.distance(other) 92 v += 1/(1+np.exp(-(c1+d1*TTNP))) * 1/(1+np.exp(-(b1+a1*DINP))) 93 self.vel_tmp += v / len(others) * ratio 94 return v / len(others) * ratio 95 96 def calculate(self, others): 97 self.ruleSeparate(others) # only separate 98 99def calc_rad(pos2, pos1):#角計算 100 return np.arctan2(pos2[1] - pos1[1], pos2[0] - pos1[0]) 101 102#np.arctan(x)は引数が一つでarctan(x)をラジアンで返す。返り値は-pi / 2からpi / 2(-90度から90度)の間になる。 103#np.arctan2(y, x)は引数が二つで、arctan(y / x)をラジアンで返す。この角度は、極座標平面において原点から座標(x, y)へのベクトルがx軸の正の方向となす角度(偏角)であり、返り値は-piからpi(-180度から180度)の間になる 104#print(np.degrees(np.arctan2(-1, 1))) 105# -45.0 106#print(np.degrees(np.arctan2(1, -1))) 107# 135.0 108 109def rotate_vec(vec, rad):#ベクトル更新 110 return np.dot(vec, np.array([[np.cos(rad), -np.sin(rad)], [np.sin(rad), np.cos(rad)]]).T) 111 112 113class AgentGoForWall(AgentEdited): 114 def __init__(self, *args, **kwargs): 115 super(AgentGoForWall, self).__init__(*args, **kwargs) 116 self.log = [self.pos] # カウント初期化 117 118 self.color = kwargs.get('color', 'b') 119 self.name=kwargs.get('name','agent_03') 120 #kwargsはkeyとvalueの組み合わせを渡す 121 122 max_distance = 0 123 self.goal = None # 角が一番遠い場所 124 for px in [-self.SIZE, self.SIZE]: 125 for py in [-self.SIZE, self.SIZE]: 126 dist = np.linalg.norm(self.pos - np.array([px, py])) 127 if max_distance < dist: 128 max_distance = dist#最大値の更新 129 self.goal = np.array([px, py]) 130 #self.vel = rotate_vec(np.array([self.VEL, 0]), calc_rad(self.goal, self.pos)) 131 132 def brake(self,others): 133 others = [other for other in others if self.distance(other) < self.RANGE_SEPARATE]#範囲内に入ったエージェントの選別 134 v = np.zeros(2) 135 if not others: 136 return 0 137 for other in others: 138 if other.name!='agent_03': 139 self.vel=(0,0) 140 crash+=1#カウント追加 141 142 143 144 145 def update(self,others) -> bool:#"返り値の型名" 146 self.vel = rotate_vec(np.array([self.VEL, 0]), calc_rad(self.goal, self.pos)) 147 148 self.brake() 149 150 151 if abs(self.pos + self.vel)[0] > self.SIZE or abs(self.pos + self.vel)[1] > self.SIZE: 152 return False # deactivate this Agent 153 154 self.pos += self.vel 155 self.log.append(self.pos) # カウントアップ 156 self.vel_tmp = np.zeros(2) 157 return True 158 159 160 161 162class Boids: 163 def __init__(self, AGENT = 20):#Agent数 164 self.active = list() 165 self.every = list() 166 self.go2wall = list() 167 self.Central=list() 168 for _ in range(AGENT): 169 self.add_agent(Agent()) 170 171 def add_agent(self, agent): 172 self.active.append(agent) 173 self.every.append(agent) 174 if isinstance(agent, AgentGoForWall): 175 self.go2wall.append(agent) 176 if isinstance(agent, AgentEdited): 177 self.Central.append(agent) 178 179 def calculate(self): 180 for agent in self.active: 181 agent.calculate([other for other in self.active if agent != other]) 182 183 def update(self): 184 self.active = [agent for agent in self.active if agent.update()] 185 186 def simulation(self): 187 self.calculate() 188 self.update() 189 190 def positions(self):#showimageはpos_arrayを渡してた 191 x, y, c = list(), list(), list() 192 for agent in self.active: 193 x.append(agent.pos[0]) 194 y.append(agent.pos[1]) 195 c.append(agent.color) 196 return (np.array(x), np.array(y)), c 197 198np.random.seed( 0 ) 199B = Boids(0) 200num_central=1 201for i in range(num_central): 202 B.add_agent(AgentEdited()) 203num=100 204for i in range(num): 205 B.add_agent(AgentGoForWall()) 206 207 208fig, ax = plt.subplots(figsize = (6, 6)) 209ax.set_xlim(-10, 10) 210ax.set_ylim(-10, 10) 211ax.grid(True) 212ims = [] 213for t in range(100): 214 B.simulation() 215 plot_data,plot_color = B.positions() 216 im=ax.scatter(*plot_data, marker="o", s=20, c=plot_color) 217 ims.append([im]) 218ani = animation.ArtistAnimation(fig, ims, interval=400, repeat=False) 219HTML(ani.to_jshtml()) 220 221 222x=0 223for agent in B.go2wall: 224 print(f"{agent.name}: {len(agent.log)}") 225 x+=len(agent.log) 226print(x/len(B.go2wall))

#試した事
該当クラス全体を見直したが、引数にothersを設定しているのでエラーが出ている理由が分からないです。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

ozwk

2022/11/30 03:21

> 引数にothersを設定している どこの部分ですか?
y_waiwai

2022/11/30 03:25

エラーが出たなら、エラーメッセージを提示しましょう エラーメッセージは、よけいな省略翻訳しないで出たそのママをコピペで提示してください
IT_takumin

2022/11/30 14:56

こちらがエラーメッセージになります。 よろしくお願いいたします。 TypeError Traceback (most recent call last) <ipython-input-3-7d2073bfad09> in <module> 5 ims = [] 6 for t in range(100): ----> 7 B.simulation() 8 plot_data,plot_color = B.positions() 9 im=ax.scatter(*plot_data, marker="o", s=20, c=plot_color) <ipython-input-1-911dd7c2a2d1> in simulation(self) 189 def simulation(self): 190 self.calculate() --> 191 self.update() 192 193 def positions(self):#showimageはpos_arrayを渡してた TypeError: update() missing 1 required positional argument: 'others'
guest

回答2

0

自己解決

brake関数の引数を(self,active)とし、 activeを受取りothersをactiveからselfを引くことで定義する事でbrake関数を機能させた

投稿2022/12/06 06:04

IT_takumin

総合スコア8

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

update 関数を利用している部分がこの箇所ですね。

python

1 def update(self): 2 self.active = [agent for agent in self.active if agent.update()]

others を引数に入れていませんね。
agent として入力するものを同一視して同じメソッドを使いたいのであれば、ポリモーフィズムを意識して同じ引数のメソッドを定義しましょう。
例えば全部 def update(self, others): で定義しつつ、クラスによっては others を使っていないケースがあってもいいと思います。

投稿2022/11/30 04:18

mather

総合スコア6753

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

IT_takumin

2022/12/01 01:21

ありがとうございます、引数に入れて試してみたのですが、下記の様なエラーが出てしまいました。その為、brake 関数のother.nameの判別を行っている所で行われている処理が実際にどの様になっているのかを確認したいのですが、その方法が分からないのでもし可能であれば教えていただけないでしょうか。 TypeError Traceback (most recent call last) <ipython-input-9-7d2073bfad09> in <module> 5 ims = [] 6 for t in range(100): ----> 7 B.simulation() 8 plot_data,plot_color = B.positions() 9 im=ax.scatter(*plot_data, marker="o", s=20, c=plot_color) TypeError: simulation() missing 1 required positional argument: 'others'
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問