I've been working on a small weather station for APRS using Direwolf and some python scripts on my RPi 3.
My dilemma seems simple, but I'm lacking in python knowledge.
I have my main code for my BMP180 sensor that outputs data in a specific format for the temp and pressure. However, I added a humidity sensor but I've been unable to combine the code to get the outputted format that I need.
Here's my main code with the code at the bottom that I need added in to get the desired output (also shown at the bottom for the print job)
i.e.
#050501z000/000g000t042r000p000P000h42b9999 RPI
Where
h42=h+humidity percentage.
#Main BMP180 code
-----------------------------------------------------------------------------
import smbus
import time
import sys
from ctypes import c_short
DEVICE = 0x77 # Default device I2C address
bus = smbus.SMBus(1) # Rev 2 Pi uses 1
def convertToString(data):
# Simple function to convert binary data into
# a string
return str((data[1] + (256 * data[0])) / 1.2)
def getShort(data, index):
# return two bytes from data as a signed 16-bit value
return c_short((data[index] << 8) + data[index + 1]).value
def getUshort(data, index):
# return two bytes from data as an unsigned 16-bit value
return (data[index] << 8) + data[index + 1]
def readBmp180Id(addr=DEVICE):
# Chip ID Register Address
REG_ID = 0xD0
(chip_id, chip_version) = bus.read_i2c_block_data(addr, REG_ID, 2)
return (chip_id, chip_version)
def readBmp180(addr=DEVICE):
# Register Addresses
REG_CALIB = 0xAA
REG_MEAS = 0xF4
REG_MSB = 0xF6
REG_LSB = 0xF7
# Control Register Address
CRV_TEMP = 0x2E
CRV_PRES = 0x34
# Oversample setting
OVERSAMPLE = 3 # 0 - 3
# Read calibration data
# Read calibration data from EEPROM
cal = bus.read_i2c_block_data(addr, REG_CALIB, 22)
# Convert byte data to word values
AC1 = getShort(cal, 0)
AC2 = getShort(cal, 2)
AC3 = getShort(cal, 4)
AC4 = getUshort(cal, 6)
AC5 = getUshort(cal, 8)
AC6 = getUshort(cal, 10)
B1 = getShort(cal, 12)
B2 = getShort(cal, 14)
MB = getShort(cal, 16)
MC = getShort(cal, 18)
MD = getShort(cal, 20)
# Read temperature
bus.write_byte_data(addr, REG_MEAS, CRV_TEMP)
time.sleep(0.005)
(msb, lsb) = bus.read_i2c_block_data(addr, REG_MSB, 2)
UT = (msb << 8) + lsb
# Read pressure
bus.write_byte_data(addr, REG_MEAS, CRV_PRES + (OVERSAMPLE << 6))
time.sleep(0.04)
(msb, lsb, xsb) = bus.read_i2c_block_data(addr, REG_MSB, 3)
UP = ((msb << 16) + (lsb << 8) + xsb) >> (8 - OVERSAMPLE)
# Refine temperature
X1 = ((UT - AC6) * AC5) >> 15
X2 = (MC << 11) / (X1 + MD)
B5 = X1 + X2
temperature = (B5 + 8) >> 4
# Refine pressure
B6 = B5 - 4000
B62 = B6 * B6 >> 12
X1 = (B2 * B62) >> 11
X2 = AC2 * B6 >> 11
X3 = X1 + X2
B3 = (((AC1 * 4 + X3) << OVERSAMPLE) + 2) >> 2
X1 = AC3 * B6 >> 13
X2 = (B1 * B62) >> 16
X3 = ((X1 + X2) + 2) >> 2
B4 = (AC4 * (X3 + 32768)) >> 15
B7 = (UP - B3) * (50000 >> OVERSAMPLE)
P = (B7 * 2) / B4
X1 = (P >> 8) * (P >> 8)
X1 = (X1 * 3038) >> 16
X2 = (-7357 * P) >> 16
pressure = P + ((X1 + X2 + 3791) >> 4)
return (temperature/10.0 * 9/5 +32,pressure/10)
def main():
(chip_id, chip_version) = readBmp180Id()
# print "Chip ID :", chip_id
# print "Version :", chip_version
(temperature,pressure)=readBmp180()
print time.strftime("#%d%H%Mz")+('000g000t0{0:0.0f}r000p000P000h00b{1:0.0f} RPI'.format(temperature, pressure))
if __name__=="__main__":
main()
#Code that needs to be added
import Adafruit_DHT
humidity = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 17)
if humidity <= 99:
print('{0:0.0f}'.format(humidity))
else:
print('00')
#Desired output of print
#print time.strftime("#%d%H%Mz")+('000g000t0{0:0.0f}r000p000P000h00b{1:0.0f} RPI'.format(temperature, pressure))
#Where h00 = h(humidity output of the sensor)
Put import at the beginning of script and rest in main()
You can use {:02.0f} to get always two digits - ie. h09
import Adafruit_DHT
def main():
chip_id, chip_version = readBmp180Id()
temperature, pressure = readBmp180()
humidity = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 17)
if humidity > 99:
huminidy = 0
print time.strftime("#%d%H%Mz") + '000g000t0{:0.0f}r000p000P000h{:02.0f}b{:0.0f} RPI'.format(temperature, huminidy, pressure)
if __name__=="__main__":
main()
Related
I'm trying solve a system of coupled ordinary differential equations, formed by 7 ODEs in python, using solve_ivp or either implement a fuction for RK4.
The general physical problem is as follows:
Cooling of photovoltaic modules with heat exchanger coupling to the module. In this way, the module generates electrical energy and thermal energy.
I have a polynomial function, G(t) = 9.8385e-13*t^4 - 1.82918e-8*t^3 + 5.991355e-05*t^2 + 2.312059e-1*t + 25, which works for an approximate range of 0 < t < 9000, which represents solar radiation as a function of time of day.
This function was obtained through a "polyfit" applied to real data (file upload here. Its a CSV - https://files.fm/u/9y4evkf6c).
This function is used as input for the ODEs, which represent an electrical and a thermal system as a function of time.
To solve the electrical model, I created some scripts that solve the diode equation for the photovoltaic module in question, and the output of this script is the photovoltaic power (called in the PPV thermal model) generated as a function of the module temperature and radiation. This script works great and solves part of my problem.
My difficulty lies in solving the equations of the thermal model, which receives as input parameters G(t) and PPV.
The equations result in this system:
System of EDOS
Labels:
Tvidro = Tglass = T1
Tcel = Tpv = T2
Ttedlar = T3
Tabs = Tabsorber = T4
Ttubo = Ttube = T5
Tfsai = Tfluid_out = T6
Tiso = Tinsulation = T7
Using method/function for RK4, the complete code is like this (you can go direct to part "#DEFINE MODEL EQUATIONS - ODES)" :
import numpy as np
import matplotlib.pyplot as plt
import csv
from numpy.polynomial.polynomial import polyval
############################################################
with open('directory of data called teste_dados_radiacao',"r") as i:
rawdata = list(csv.reader(i, delimiter = ";"))
exampledata = np.array(rawdata[1:], dtype=float)
xdata = exampledata[:,0]
ydata = exampledata[:,1]
curve = np.array(np.polyfit(xdata, ydata, 4))
rev_curve = np.array(list(reversed(curve)), dtype=float)
print(rev_curve)
#G_ajustado = polyval(xdata, rev_curve)
""" plt.plot(xdata, ydata, label = "dados experimentais")
plt.plot(xdata, model, label = "model")
plt.legend()
plt.show() """
#############################################################
#CONSTANTS
Tamb = 25 #°C #ambient temperatura
SIGMA = 5.67e-8 #W/m2K4
E_VIDRO = 0.90 #between 0.85 e 0.83 #nasrin2017 0.04
VENTO = 2 #m/s
T_GROUND = Tamb + 2 #°C
T_CEU = 0.00552*Tamb**1.5
Vf = 1 #m/s
Do = 10e-3 #m
Di = 8e-3 #m
NS = 6*10 #number of cells
T_F_ENT = 20 #°C
#INPUTS
Tcel = 25
Tv = 25
Tiso = 30
Av = 1.638*0.982
ALPHA_VIDRO = 0.9
L_VIDRO = 3e-3 #m
RHO_VIDRO = 2500 #kg/m3
M_VIDRO = Av*L_VIDRO*RHO_VIDRO #kg
CP_VIDRO = 500 #j/kgK
K_VIDRO = 2 #W/mK
TAU_VIDRO = 0.95
Pac = 0.85
H_CELL = 0.156 #m
A_CELL = NS*H_CELL**2
ALPHA_CELL = 0.9
L_CEL = 3e-3
RHO_CEL = 2330
M_CEL = A_CELL*L_CEL*RHO_CEL #kg - estimated
CP_CEL = 900 #J/kgK
K_CEL = 140 #W/mK
BETA_T = 0.43/100 # %/°C
N_ELE_REF = 0.1368 #13.68%
N_ELE = N_ELE_REF*(1 - BETA_T*(Tcel - 25)) #273 + 25 - tcel kelvin
A_tedlar = Av
L_TEDLAR = 0.33e-3
RHO_TEDLAR = 1500
M_TEDLAR = Av*L_TEDLAR*RHO_TEDLAR
CP_TEDLAR = 1090 #1090 OU 2090
K_TEDLAR = 0.35
ALPHA_TEDLAR = 0.34 #doc nasa ou zero
#parameters
RHO_ABS = 2700
A_ABS = Av
CP_ABS =900
L_ABS = 3e-3 #mm
M_ABS = A_ABS*RHO_ABS*L_ABS
K_ABS = 300
A_ABS_TUBO = 10*1.60*0.01+0.154*9*0.01
A_ABS_ISO = Av-A_ABS_TUBO
RHO_TUBO = 2700
CP_TUBO = 900
N_TUBOS = 10
L_TUBO = N_TUBOS*1.6
M_TUBO = RHO_TUBO*L_TUBO*(3.1415/4)*(Do**2 - Di**2)
K_TUBO = 300
A_TUBO_F = 0.387 #pi*Di*(L*10 VOLTAS + R(156MM)*9)
A_TUBO_ISO = 0.484 #pi*Do*(L*10 VOLTAS + R(156MM)*9)
A_ISO = Av
RHO_ISO = 50
L_ISO = 40e-3
M_ISO = A_ISO*RHO_ISO*L_ISO
CP_ISO = 670
K_ISO = 0.0375
E_ISO = 0.75 #ESTIMATED
RHO_FLUIDO = 997
M_FLUIDO = L_TUBO*(3.1415/4)*Di**2*RHO_FLUIDO
CP_FLUIDO = 4186 #j/kgK
MI_FLUIDO = 0.890e-3 #Pa*s ou N/m2 * s
K_FLUIDO = 0.607
M_PONTO = 0.05 #kg/s ou 0.5 kg/m3
#DIMENSIONLESS
Pr = CP_FLUIDO*MI_FLUIDO/K_FLUIDO #water 25°C
Re = RHO_FLUIDO*Vf*Di/MI_FLUIDO
if (Re<=2300):
Nuf = 4.364
else:
Nuf = 0.023*(Re**0.8)*(Pr*0.4)*Re
#COEFFICIENTS
h_rad_vidro_ceu = SIGMA*E_VIDRO*(Tv**2 - T_CEU)*(Tv + T_CEU)
h_conv_vidro_amb = 2.8 + 3*VENTO
h_conv_tubo_fluido = 0.5*30#Nuf
h_cond_vidro_cel = 1/((L_VIDRO/K_VIDRO) + (L_CEL/K_CEL))
h_cond_cel_tedlar = 1/((L_TEDLAR/K_TEDLAR) + (L_CEL/K_CEL))
h_cond_tedlar_abs = 1/((L_TEDLAR/K_TEDLAR) + (L_ABS/K_ABS))
h_cond_abs_tubo = 1/((L_TUBO/K_TUBO) + (L_ABS/K_ABS))
h_cond_abs_iso = 1/((L_ISO/K_ISO) + (L_ABS/K_ABS))
h_cond_tubo_iso = 1/((L_ISO/K_ISO) + (L_TUBO/K_TUBO))
h_conv_iso_amb = h_conv_vidro_amb
h_rad_iso_ground = SIGMA*E_ISO*(Tiso**2 - T_GROUND**2)*(Tiso + T_GROUND)
#GROUPS
A1 = (1/(M_VIDRO*CP_VIDRO))*(ALPHA_VIDRO*Av)#*G(t)) G_ajustado = polyval(dt,rev_curve)
A2 = (1/(M_VIDRO*CP_VIDRO))*(Av*(h_rad_vidro_ceu + h_conv_vidro_amb + h_cond_vidro_cel))
A3 = (1/(M_VIDRO*CP_VIDRO))*Av*h_cond_vidro_cel
A4 = (1/(M_VIDRO*CP_VIDRO))*Av*(h_conv_vidro_amb + h_rad_vidro_ceu)
A5 = (1/(M_CEL*CP_CEL))*(Pac*A_CELL*TAU_VIDRO*ALPHA_CELL) #*G(t)
A6 = -1*A5*N_ELE #*G(t)
A7 = (1/(M_CEL*CP_CEL))*A_CELL*h_cond_vidro_cel
A8 = (1/(M_CEL*CP_CEL))*A_CELL*(h_cond_vidro_cel + h_cond_cel_tedlar)
A9 = (1/(M_CEL*CP_CEL))*A_CELL*h_cond_cel_tedlar
A10 = (1/(M_TEDLAR*CP_TEDLAR))*A_tedlar*(1 - Pac)*TAU_VIDRO*ALPHA_TEDLAR#G(t)
A11 = (1/(M_TEDLAR*CP_TEDLAR))*A_tedlar*(h_cond_cel_tedlar + h_cond_tedlar_abs)
A12 = (1/(M_TEDLAR*CP_TEDLAR))*A_tedlar*h_cond_cel_tedlar
A13 = (1/(M_TEDLAR*CP_TEDLAR))*A_tedlar*h_cond_tedlar_abs
A14 = (1/(M_ABS*CP_ABS))*A_ABS*h_cond_tedlar_abs
A15 = (1/(M_ABS*CP_ABS))*(A_ABS*h_cond_tedlar_abs + A_ABS_TUBO*h_cond_abs_tubo + A_ABS_ISO*h_cond_abs_iso)
A16 = (1/(M_ABS*CP_ABS))*A_ABS_TUBO*h_cond_abs_tubo
A17 = (1/(M_ABS*CP_ABS))*A_ABS_ISO*h_cond_abs_iso
A18 = (1/(M_TUBO*CP_TUBO))*A_ABS_TUBO*h_cond_abs_tubo
A19 = (1/(M_TUBO*CP_TUBO))*(A_ABS_TUBO*h_cond_abs_tubo + A_TUBO_F*h_conv_tubo_fluido + A_TUBO_ISO*h_cond_tubo_iso)
A20 = (1/(M_TUBO*CP_TUBO))*A_TUBO_F*h_conv_tubo_fluido*0.5
A21 = (1/(M_TUBO*CP_TUBO))*A_TUBO_ISO*h_cond_tubo_iso
A22 = (1/(M_FLUIDO*CP_FLUIDO))*A_TUBO_F*h_conv_tubo_fluido
A23 = (1/(M_FLUIDO*CP_FLUIDO))*(A_TUBO_F*h_conv_tubo_fluido*0.5 + M_PONTO*CP_FLUIDO)
A24 = (1/(M_FLUIDO*CP_FLUIDO))*(T_F_ENT*(M_PONTO*CP_FLUIDO - h_conv_tubo_fluido*A_TUBO_F*0.5))
A25 = (1/(M_ISO*CP_ISO))*A_ABS_ISO*h_cond_abs_iso
A26 = (1/(M_ISO*CP_ISO))*(A_ABS_ISO*h_cond_abs_iso + A_TUBO_ISO*h_cond_tubo_iso + A_ISO*h_conv_iso_amb + A_ISO*h_rad_iso_ground)
A27 = (1/(M_ISO*CP_ISO))*A_TUBO_ISO*h_cond_tubo_iso
A28 = (1/(M_ISO*CP_ISO))*A_ISO*(h_conv_iso_amb*Tamb + h_rad_iso_ground*T_GROUND)
#DEFINE MODEL EQUATIONS - ODES - (GLASS, PV CELL, TEDLAR, ABSORBER, TUBE, FLUID, INSULATION) # dT1dt = A1*G_ajustado - A2*x[0] + A3*x[1] + A4 # dT2dt = A5*G_ajustado - A6*G_ajustado + A7*x[0] - A8*x[1] + A9*x[2]# dT3dt = A10*G_ajustado - A11*x[2] + A12*x[1] +A13*x[3]
def SysEdo(x, k):#tv-x[0] tcel-x[1] ttedlar-x[2] tabs-x[3] ttubo-x[4] tiso-x[5] tfs-x[6]
dT1dt = A1*polyval(k,rev_curve) - A2*x[0] + A3*x[1] + A4
dT2dt = A5*polyval(k,rev_curve) - A6*polyval(k,rev_curve) + A7*x[0] - A8*x[1] + A9*x[2]
dT3dt = A10*polyval(k,rev_curve) - A11*x[2] + A12*x[1] +A13*x[3]
dT4dt = A14*x[2] - A15*x[3] + A16*x[4] + A17*x[5]
dT5dt = A18*x[3] - A19*x[4] + A20*x[6] + A20*T_F_ENT + A21*x[5]
dT6dt = A22*x[4] - A23*x[6] + A24
dT7dt = A25*x[3] - A26*x[5] + A27*x[4] + A28
Tdot = np.array([dT1dt, dT2dt, dT3dt, dT4dt, dT5dt, dT6dt, dT7dt])
return Tdot
#RungeKutta4
def RK4(f, x0, t0, tf, dt):
t = np.arange(t0, tf, dt) #time vector
nt = t.size #lenght of time vector
nx = x0.size #length of state variables?
x = np.zeros((nx,nt)) #initialize 2D vector
x[:,0] = x0 #initial conditions
#RK4 constants
for k in range(nt-1):
k1 = dt*f(t[k], x[:,k],k)
k2 = dt*f(t[k] + dt/2, x[:,k] + k1/2, k)
k3 = dt*f(t[k] + dt/2, x[:,k] + k2/2, k)
k4 = dt*f(t[k] + dt, x[:,k] + k3, k)
dx = (k1 + 2*k2 + 2*k2 + k4)/6
x[:,k+1] = x[:,k] + dx
return x,t
#Define problems
f = lambda t, x, k : SysEdo(x, k)
#initial state - t0 is initial time - tf is final time - dt is time step
x0 = np.array([30, 30, 30, 30, 30, 30, 30])
t0 = 0
tf = 1000
dt = 1
#EDO SOLVE
x, t = RK4(f, x0, t0, tf, dt)
plt.figure()
plt.plot(t, x[0], '-', label='Tvidro')
"""
plt.plot(t, x[1], '-', label='Tpv')
plt.plot(t, x[2], '-', label='Ttedlar')
plt.plot(t, x[3], '-', label='Tabs')
plt.plot(t, x[4], '-', label='Tiso')
plt.plot(t, x[5], '-', label='Ttubo')
plt.plot(t, x[6], '-', label='Tfsai')"""
plt.title('Gráfico')
plt.legend(['Tvidro', 'Tpv', 'Ttedlar', 'Tabs', 'Tiso', 'Ttubo', 'Tfsai'], shadow=False)
plt.xlabel('t (s)')
plt.ylabel('Temperatura (°C)')
plt.xlim(0,20)
plt.ylim(0,150)
plt.grid('on')
plt.show()
Thank you in advance, I am also open to completely start the implementation from scratch if there is a better way to do this with python or matlab.
You can just replace
x, t = RK4(f, x0, t0, tf, dt)
with
t = arange(t0,tf+0.5*dt,dt)
res = solve_ivp(f,(t0,tf),x0,t_eval=t,args=(k,), method="DOP853", atol=1e-6,rtol=1e-8)
x = res.y[0]
Adapt the last 3 parameters to your liking.
I am writing a SHA256 Hash function and it's mostly complete but when I run the code the hash is way to high and it's not correct. What is wrong with my code that's making it far off from the actual value to be? Now keep in mind I do not have a chunk loop so it might look a bit different. This also A GUI as well.
#VARIABLES
FF = (1 >> 32)-1
#Right rotate
def rr(a,b):
return((a >> b) | (a << (32 - b))) & FF
h0 = 0x6a09e667
h1 = 0xbb67ae85
h2 = 0x3c6ef372
h3 = 0xa54ff53a
h4 = 0x510e527f
h5 = 0x9b05688c
h6 = 0x1f83d9ab
h7 = 0x5be0cd19
#Messages
word_Hash = "1: Please write below what\n word you would like to hash."
words = []
playerinput = []
varwords = [word_Hash]
#FUNCTIONS
count = 0
def SHA256():
global playerinput, wordtohash, A, B, C, D, E, F, G, H
#get input
wordtohash = playerinput.pop(0)
#convert to binary
BinaryConversion = ''.join(format(ord(i), '08b') for i in wordtohash) + "1"
#pad helped by Dr.Glynn, Maple
if len(BinaryConversion) <= 512:
count = len(BinaryConversion)
while count <= 448:
BinaryConversion = BinaryConversion + "0"
count += 1
wordtohash = len(wordtohash)
endofpad = int(wordtohash) * 8
numberofzeros = 0
while numberofzeros < 63 - int(len(bin(endofpad)[2:])):
BinaryConversion = BinaryConversion + "0"
numberofzeros += 1
#BinaryConversion = (BinaryConversion) + str(endofpad)
BinaryConversion = str(BinaryConversion) + str(bin(endofpad)[2:])
#numbers = len(BinaryConversion)
#print(BinaryConversion)
#first 16 messages
w = [int('0b'+BinaryConversion[0:31], 2),
int('0b'+BinaryConversion[32:63], 2),
int('0b'+BinaryConversion[64:95],2),
int('0b'+BinaryConversion[96:127],2),
int('0b'+BinaryConversion[128:159],2),
int('0b'+BinaryConversion[160:191],2),
int('0b'+BinaryConversion[192:223],2),
int('0b'+BinaryConversion[224:255],2),
int('0b'+BinaryConversion[256:287],2),
int('0b'+BinaryConversion[288:319],2),
int('0b'+BinaryConversion[320:351],2),
int('0b'+BinaryConversion[352:383],2),
int('0b'+BinaryConversion[384:415],2),
int('0b'+BinaryConversion[416:447],2),
int('0b'+BinaryConversion[448:479],2),
int('0b'+BinaryConversion[480:511],2)]
#Message Scedule
#rest of the messages
for c in range(16,64):
S0 = rr(w[c-15], 7) ^ rr(w[c-15], 18) ^ (w[c-15] >> 3)
S1 = rr(w[c - 2], 17) ^ rr(w[c - 2], 19) ^ (w[c - 2] >> 10)
w.append((w[c - 16] + S0 + w[c-7] + S1) & FF)
print(w)
A = h0
B = h1
C = h2
D = h3
E = h4
F = h5
G = h6
H = h7
for i in range(64):
s1 = rr(E, 6) ^ rr(E, 11) ^ rr(E, 25)
ch = (E & F) ^ (~E & G)
temp1 = H + s1 + ch + K[i] + w[i]
s0 = rr(A, 2) ^ rr(A, 13) ^ rr(A, 22)
maj = (A & B) ^ (A & C) ^ (B & C)
temp2 = s0 + maj
H = G
G = F
F = E
E = D + temp1
D = C
C = B
B = A
A = temp1 + temp2
A = hex(A)[2:]
B = hex(B)[2:]
C = hex(C)[2:]
D = hex(D)[2:]
E = hex(E)[2:]
F = hex(F)[2:]
G = hex(G)[2:]
H = hex(H)[2:]
print(A)
def finish():
global count, varwords, playerinput, words
if count >= 1:
screenframe1.pack_forget()
frm_screen2.pack()
SHA256()
lbl_story["text"] = "Your word is {}\n Your hash value is {}{}{}{}{}{}{}{}".format(wordtohash,A,B,C,D,E,F,G,H)
I have this relation to which I write the code using python to compute it , I am not sure if the code is right or not. Could you please give me any advice if it is true or how I can improve the code??, thanks
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import comb
from scipy.constants import k
from numpy import arange
p12 = 1 # system initial state 12
w0 = 1 # system
wn = 0 # wb/w0 bath
U = 0.1
N = 50
n = (N/2)
a =0.007
t = 1000# Time
Z = 2**N * (np.cosh(U*wn/2))**N
q12 = []
f11 = []
def Jrange(start, n, step):
numelements = int((stop-start)/float(step))
for i in range(numelements+1):
yield start + i*step
def trange(tstart,tstop,tstep):
tnumelements = int((tstop-tstart)/float(tstep))
for i in range(tnumelements+1):
yield tstart + i*tstep
for t in trange(tstart,tstop,tstep):
roh2 = 0
roh12 = 0
roh1 = 0
roh11 = 0
for J in Jrange (0,stop,1) :
Nj = (comb (N,(n+J))) - (comb (N,(n+J+1)))
for m in arange (-J,J+1):
r1 = np.sqrt (J*(J + 1) - m*(m + 1)) #r+
r2 = np.sqrt (J*(J + 1) - m*(m - 1)) #r-
Omega1 = (w0 - wn) + (4 *a*(m + (1/2)))/(np.sqrt(N)) #Omeg+
gamma1 = np.sqrt( (Omega1**2 /4)+ (4*a**2 * r1**2)/N) # gamma+
Omega2 =-(w0 - wn) - (4 *a*(m - (1/2)))/(np.sqrt(N)) #Omega-
gamma2 = np.sqrt( (Omega2**2 /4)+ (4*a**2 * r2**2)/N)#gamma-
A1 = np.cos(gamma1*t)
B1 = np.sin(gamma1*t)
A2 = np.cos(gamma2*t)
B2 = np.sin(gamma2*t)
C = np.exp(-m*U*wn)
H12 = C * (A1 - 1j*B1*Omega1/(2*gamma1)) * ((A2 +1j*B2*Omega2/(2*gamma2))
H2 = r2**2 * B2**2 * ((4*a**2)/ (gamma2**2 * N))
H1 = A1**2 + B1**2 *((Omega1**2)/ (4 * gamma1**2))
H11 = C * ((p11*H1) + (p22*H2))
roh11 = roh11+H11
roh12 = roh12 + H12
roh2= roh2 +roh12*Nj
roh1 = roh1 + roh11*Nj
Roh12 = roh2*D *p12*np.exp(1j*(w0-wn)*t)
Roh11 = roh1 *D
q12.append(Roh12)
f11.append(Roh11)
So, the intent here is to evaluate a long series of equations that change as a function of height, and finally combine them at the very end. The end goal is to approximate an integration w/ respect to height (that part is still in the works). Right now, I just need to make the last equation here work.
I'm getting "TypeError: can't multiply sequence by non-int of type 'float'", in reference to attempting to evaluate "a5" as the final step here. I can only assume that this is an issue with iterating through the dictionary d_gamox (which is a series of int:float pairs), but having done something similar elsewhere with no issue, I'm totally baffled. Maybe I've just been staring at this code so long I'm missing something obvious, so what do you guys think?
(Also I'm sure this code is a mess, but rn it just needs to work...)
import numpy as np
from math import exp, sin, cos, sqrt
theta = 1 #Elevation angle in degrees
f = 1000 #Frequency in MHz
r = 200 #Range to target in km
h_ant = 100 #Height of antenna + terrain in m
###############
#Constants
r_0 = 6370 #radius of Earth in km
T_0 = 300 #Sea-level temp in K
P_0 = 1013.25 #Sea-level pressure in mbar
N_s = 313 #Avg sea-level refractivity
C_e = 0.1439 #constant for refractivity
C = 2.0058 #for Gam_ox
alpha = 5.2561222 #constants for pressure
beta = 0.034164794
gamma = 11.388265
f_r = 22.235 #for water vapor
rad = np.radians(theta) #Elevation angle in rad
r_m = r * 1000 #Range in meters
f_GHz = f / 1000 #Frequency in GHz
h_ant_km = h_ant/1000 #Antenna height in km
n_0 = 1 + (N_s / (10**6)) #Refractive index
###############
d_gamox = {}
d_fNp = {
1 : 56.2648,
3 : 58.4466,
5 : 59.5910,
7 : 60.4348,
9 : 61.1506,
11 : 61.8002,
13 : 62.4112,
15 : 62.9980,
17 : 63.5685,
19 : 64.1272,
21 : 64.6779,
23 : 65.2240,
25 : 65.7626,
27 : 66.2978,
29 : 66.8313,
31 : 67.3627,
33 : 67.8923,
35 : 68.4205,
37 : 68.9478,
39 : 69.4741,
41 : 70,
43 : 70.5249,
45 : 71.0497
}
d_fNm = {
1 : 118.7505,
3 : 62.4863,
5 : 60.3061,
7 : 59.1642,
9 : 58.3239,
11 : 57.6125,
13 : 56.9682,
15 : 56.3634,
17 : 55.7839,
19 : 55.2214,
21 : 54.6728,
23 : 54.1294,
25 : 53.5960,
27 : 53.0695,
29 : 52.5458,
31 : 52.0259,
33 : 51.5091,
35 : 50.9949,
37 : 50.4830,
39 : 49.9730,
41 : 49.4648,
43 : 48.9582,
45 : 48.4530
}
d1 = {
0 : 5.947,
2 : 2.946,
4 : 1.074,
6 : 0.3779,
8 : 0.1172,
10 : 0.01834,
12 : 0.003708,
14 : 0.0008413,
16 : 0.0006138,
18 : 0.0004449,
20 : 0.0004490,
22 : 0.0005230,
24 : 0.0006138,
26 : 0.0007191,
28 : 0.0005230,
30 : 0.0003778,
32 : 0.0002710
}
uNp = list()
uNm = list()
uN0 = list()
for i , j in d_fNp.items():
Np = (i*(2*i+3))/(i+1)
Nm = (i+1)*(2*i-1)/i
N0 = (2*(i**2+i+1)*(2*i+1))/(i*(i+1))
uNp.append(Np)
uNm.append(Nm)
uN0.append(N0)
T_h = r_m*sin(rad)+(r_m*cos(rad))**2/(2*((4/3)*(r_0*1000))) #Height of target using 4/3 Earth radius
def target_height(T_h):
if T_h > 47000:
return 47000 / 1000
else:
return T_h / 1000
h = target_height(T_h) + h_ant/1000 # Target height in km
for h1 in np.linspace(h_ant_km,h,400):
geo_h = (r_0 * h1) / (r_0 + h1) # Geopotential height
def T(geo_h):
if geo_h*1000 <= 11000:
return 288.16 - 0.0065*(geo_h*1000)
elif geo_h*1000 > 11000 and geo_h*1000 <= 25000:
return 216.66
else:
return 216.66 + 0.003*((geo_h*1000) - 25000)
def P(geo_h):
if geo_h*1000 <= 11000:
return 1013.25*(T(geo_h)/288.16)**alpha
elif geo_h*1000 > 11000 and geo_h*1000 <= 25000:
return 226.32*exp((-beta/T(geo_h))*((geo_h*1000) - 11000))
else:
return 24.886*(216.66/T(geo_h))**gamma
def n_h(h1):
return 1 + (n_0-1)*exp(-C_e*h1) #Refractive index
def g_h(h1):
if h1 >= 0 and h1 <= 8:
return 0.640
elif h1 > 8 and h1 <= 25:
return 0.640 + 0.04218*(h-8)
else:
return 1.357
def del_f(g_h,P,T):
return g_h(h1) * (P(geo_h)/P_0)*(T_0/T(geo_h)) #Line-breadth constant
#Calculate FN+/-
FNp = list()
FNm = list()
for i , j in d_fNp.items():
a1 = (del_f(g_h,P,T) / ((j - f_GHz)**2 + (del_f(g_h,P,T))**2)) + (del_f(g_h,P,T) / ((j + f_GHz)**2 + (del_f(g_h,P,T))**2))
FNp.append(a1)
for i , j in d_fNm.items():
b1 = (del_f(g_h,P,T) / ((j - f_GHz)**2 + (del_f(g_h,P,T))**2)) + (del_f(g_h,P,T) / ((j + f_GHz)**2 + (del_f(g_h,P,T))**2))
FNm.append(b1)
def F_0(del_f):
return del_f(g_h,P,T)/(f_GHz**2+(del_f(g_h,P,T))**2) #Non-resonant component
#Calculate A_N
x = np.multiply(FNp, uNp)
y = np.multiply(FNm, uNm)
z = list()
for i in uN0:
x1 = i*F_0(del_f)
z.append(x1)
Enk = list()
for i, j in d_fNp.items():
x2 = 2.06844*i*(i+1)
Enk.append(x2)
a2 = np.add(x, y)
a3 = np.add(a2,z)
a4 = list()
for i in Enk:
b2 = exp(-i/T(geo_h))
a4.append(b2)
A_N = np.multiply(a3,a4)
def gam_ox(P,T,A_N):
return C * P(geo_h) * (T(geo_h)**-3)*(f_GHz**2)*(sum(A_N))
d_gamox[h1] = [gam_ox(P,T,A_N)]
intlist = list()
for i, j in d_gamox.items():
a5 = ((1 + (n_0 - 1) * exp(-C_e * i)) * j) / sqrt(1 - ((n_0 * cos(rad)) / ((1 + (n_0 - 1) * exp(-C_e * i)) * (1 + i / r_0)))**2)
intlist.append(a5)
I1 = sum(intlist)
print(I1)
The error happens in this line:
a5 = ((1 + (n_0 - 1) * exp(-C_e * i)) * j) / sqrt(1 - ((n_0 * cos(rad)) / ((1 + (n_0 - 1) * exp(-C_e * i)) * (1 + i / r_0)))**2)
The error message means that you have a sequence amongst your factors, which can't me multiplied by non-ints. In this case, it is j, which is a list of one element: [0.005631212879043453]. If you specify j[0] to access the float inside the list instead of j, it works.
Currently I am using a barometric sensor with a raspberry pi. I am using a time delay and my code looks something like this,
import smbus
import time
while True:
try:
# Get I2C bus
bus = smbus.SMBus(1)
# BMP280 address, 0x76(118)
# Read data back from 0x88(136), 24 bytes
b1 = bus.read_i2c_block_data(0x76, 0x88, 24)
# Convert the data
# Temp coefficents
dig_T1 = b1[1] * 256 + b1[0]
dig_T2 = b1[3] * 256 + b1[2]
if dig_T2 > 32767 :
dig_T2 -= 65536
dig_T3 = b1[5] * 256 + b1[4]
if dig_T3 > 32767 :
dig_T3 -= 65536
# Pressure coefficents
dig_P1 = b1[7] * 256 + b1[6]
dig_P2 = b1[9] * 256 + b1[8]
if dig_P2 > 32767 :
dig_P2 -= 65536
dig_P3 = b1[11] * 256 + b1[10]
if dig_P3 > 32767 :
dig_P3 -= 65536
dig_P4 = b1[13] * 256 + b1[12]
if dig_P4 > 32767 :
dig_P4 -= 65536
dig_P5 = b1[15] * 256 + b1[14]
if dig_P5 > 32767 :
dig_P5 -= 65536
dig_P6 = b1[17] * 256 + b1[16]
if dig_P6 > 32767 :
dig_P6 -= 65536
dig_P7 = b1[19] * 256 + b1[18]
if dig_P7 > 32767 :
dig_P7 -= 65536
dig_P8 = b1[21] * 256 + b1[20]
if dig_P8 > 32767 :
dig_P8 -= 65536
dig_P9 = b1[23] * 256 + b1[22]
if dig_P9 > 32767 :
dig_P9 -= 65536
# BMP280 address, 0x76(118)
# Select Control measurement register, 0xF4(244)
# 0x27(39) Pressure and Temperature Oversampling rate = 1
# Normal mode
bus.write_byte_data(0x76, 0xF4, 0x27)
# BMP280 address, 0x76(118)
# Select Configuration register, 0xF5(245)
# 0xA0(00) Stand_by time = 1000 ms
bus.write_byte_data(0x76, 0xF5, 0xA0)
time.sleep(0.5)
# BMP280 address, 0x76(118)
# Read data back from 0xF7(247), 8 bytes
# Pressure MSB, Pressure LSB, Pressure xLSB, Temperature MSB, Temperature LSB
# Temperature xLSB, Humidity MSB, Humidity LSB
data = bus.read_i2c_block_data(0x76, 0xF7, 8)
# Convert pressure and temperature data to 19-bits
adc_p = ((data[0] * 65536) + (data[1] * 256) + (data[2] & 0xF0)) / 16
adc_t = ((data[3] * 65536) + (data[4] * 256) + (data[5] & 0xF0)) / 16
# Temperature offset calculations
var1 = ((adc_t) / 16384.0 - (dig_T1) / 1024.0) * (dig_T2)
var2 = (((adc_t) / 131072.0 - (dig_T1) / 8192.0) * ((adc_t)/131072.0 - (dig_T1)/8192.0)) * (dig_T3)
t_fine = (var1 + var2)
cTemp = (var1 + var2) / 5120.0
fTemp = cTemp * 1.8 + 32
# Pressure offset calculations
var1 = (t_fine / 2.0) - 64000.0
var2 = var1 * var1 * (dig_P6) / 32768.0
var2 = var2 + var1 * (dig_P5) * 2.0
var2 = (var2 / 4.0) + ((dig_P4) * 65536.0)
var1 = ((dig_P3) * var1 * var1 / 524288.0 + ( dig_P2) * var1) / 524288.0
var1 = (1.0 + var1 / 32768.0) * (dig_P1)
p = 1048576.0 - adc_p
p = (p - (var2 / 4096.0)) * 6250.0 / var1
var1 = (dig_P9) * p * p / 2147483648.0
var2 = p * (dig_P8) / 32768.0
pressure = (p + (var1 + var2 + (dig_P7)) / 16.0) / 100
# Output data to screen
print "Temperature in Celsius : %.2f C" %cTemp
print "Temperature in Fahrenheit : %.2f F" %fTemp
print "Pressure : %.2f hPa " %pressure
# add a short sleep here at the end...
sleep(1)
except KeyboardInterrupt:
# quit
sys.exit()
The above code gives me outputs of temperature in Celsius, temperature in Fahrenheit and pressure with a delay of one second in the following format.
Temp in C
Temp in F
Pressure
Temp in C
Temp in F
Pressure
Temp in C
Temp in F
Pressure
I want to put a gap (and I want to control this gap) between each sets of outputs when I use a loop and a time delay in this case (something like a line break). My output should look something like this,
Temp in C
Temp in F
Pressure
Temp in C
Temp in F
Pressure
Temp in C
Temp in F
Pressure
I can understand that by putting print (") will give a line space but is there any way to adjust the size of this line space? For example if the line space is of 1 cm, then how can we change it/ make it to 0.5 cm or 2 cm? Any guidance will be helpful.
Thanks.
you can print empty line right before or after sleep(1) print()