我目前正在研究一些氣體混合物的特性。用不同的輸入測驗我的代碼,我遇到了一個我無法解釋的錯誤(?)。基本上,它涉及在 for 回圈中對 numpy 陣列的計算。當它計算 for 回圈時,它會產生與手動構造結果不同的(和錯誤的)結果,它使用與 for 回圈中相同的代碼片段,但手動索引。我不知道為什么會發生這種情況,以及這是我自己的錯誤,還是 numpy.xml 中的錯誤。
非常奇怪的是,所需輸入物件的某些實體在整個 for 回圈中運行沒有任何問題,而另一些則完美地運行到某個索引,而另一些則甚至無法計算第一個回圈。
例如,一個輸入總是在索引 16 處停止,拋出一個:
ValueError: could not broadcast input array from shape (25,) into shape (32,)
經過進一步調查,我可以確認,前 15 個回圈拋出了正確的結果,索引 16 的回圈中的結果是錯誤的,甚至不是正確的大小。通過控制臺手動運行回圈 16 時,沒有發生錯誤...
下面的陣列顯示了索引 16 在回圈中運行時的結果。 這些是索引 16 的結果,當在控制臺中手動運行 for 回圈中的代碼時。這些是人們期望得到的。
代碼的重要部分實際上只是 for 回圈中的 np.multiply() - 我將其余部分留作背景關系,但我很確定它不應該干擾我的意圖。
def thermic_dissociation(input_gas, pressure):
# Copy of the input_gas object, which may not be altered out of scope
gas = copy.copy(input_gas)
# Temperature range
T = np.logspace(2.473, 4.4, 1000)
# Matrix containing the data over the whole range of interest
moles = np.zeros((gas.gas_cantera.n_species, len(T)))
# Array containing other property of interest
sum_particles = np.zeros(len(T))
# The troublesome for-loop:
for index in range(len(T)):
print(str(index) ' start')
# Set temperature and pressure of the gas
gas.gas_cantera.TP = T[index], pressure
# Set gas mixture to a state of chemical equilibrium
gas.gas_cantera.equilibrate('TP')
# Sum of particles = Molar Density * Avogadro constant for every temperature
sum_particles[index] = gas.gas_cantera.density_mole * ct.avogadro
#This multiplication is doing the weird stuff, printed it to see what's computed before it puts it into the result matrix and throwing the error
print(np.multiply(list(gas.gas_cantera.mole_fraction_dict().values()), sum_particles[index]))
# This is where the error is thrown, as the resulting array is of smaller size, than it should be and thus resulting in the error
moles[:, index] = np.multiply(list(gas.gas_cantera.mole_fraction_dict().values()), sum_particles[index])
print(str(index) ' end')
# An array helping to handle the results
molecule_order = list(gas.gas_cantera.mole_fraction_dict().keys())
return [moles, sum_particles, T, molecule_order]
幫助將不勝感激!
uj5u.com熱心網友回復:
如果你想要所有物種摩爾分數的陣列,你應該使用物件的X屬性cantera.Solution,它總是直接回傳完整的陣列。您可以查看該方法的檔案:cantera.Solution.X`。
該mole_fraction_dict方法特別適用于您希望通過名稱而不是它們在Solution物件中的順序來參考物種的情況,例如當關聯Solution定義不同物種集的兩個不同物件時。
uj5u.com熱心網友回復:
此特定問題與 numpy 無關。呼叫mole_fraction_dict回傳一個標準的 Python 字典。字典中元素的數量取決于可選threshold引數,其默認值為 0.0。
可以檢查 Cantera 的源代碼以了解究竟發生了什么。
mole_fraction_dict
getMoleFractionsByName
換句話說,一個值最終會出現在字典中 if x > threshold。如果>=在這里使用而不是>. 也許這會阻止您的情況出現意外結果。
正如評論中所確認的,您可以使用mole_fraction_dict(threshold=-np.inf)來獲取字典中的所有所需值。或者-float('inf')也可以使用。
在您的代碼中,您繼續呼叫.values()字典,但如果不能保證值的順序,這將是有問題的。我不確定是否是這種情況。通過使用它們的鍵從字典中檢索值來明確順序可能會更好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/461734.html
