I am having a bit of a struggle with parsing values between these def functions. The base code getSensorData() and main() works fine, values are read from the sensor and sent to thingspeak. However, I wanted to add a calculation function called calcDewPoint() to the original code to calculate dewpoint from the sensor values (RH, T) but it seems that the code gets stuck :/
Output from terminal when I run the code as is:
starting...
sense1
sense2
dewpoint1
gamma1
exiting.
Temperature/Humidity monitor using Raspberry Pi and DHT22. Data is displayed at thingspeak.com
Change list 02/06/2020
Add dewpoint calculations
import sys
import RPi.GPIO as GPIO
from time import sleep
import Adafruit_DHT
import urllib2
import math #(using numPy instead of math lib)
#import numPy as np
#import constant (Create a *.py file to be able to use constant accross multiple projects)
#Constant Variables - Magnus Parameters
m = 17.62 #Mass Constant (Water Vapour)
Tn = 243.12 #Tempreture Constant
Ah = 6.112 #hPa Pressure Constant
Ak = 0.611 #kPa Pressure Constant
K = 273.15 #Kelvin constant
Ta = 216.7 #Tempreture Constant
myAPI = 'FZZHL7N2R2AXXXXX'
def getSensorData():
print 'sense1'
RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 17)
print 'sense2'
return (str(RH), str(T))
def calcDewPoint(RH, T):
print 'dewpoint1'
Td = (K * gamma(RH, T)) / (m - gamma(RH, T))
print 'dewpoint2'
return str(Td)
def gamma(RH, T):
print 'gamma1'
g = math.log(RH/100.0) + ((m * T) / (c + T))
print 'gamma2'
return str(g)
def main():
print 'starting...'
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
while True:
try:
RH, T = getSensorData() #Call function to Read DHT22 sensor conencted to RaspberryPi
Td = calcDewPoint(RH, T) #Call function to calculate dewpoint
f = urllib2.urlopen(baseURL + "&field1=%s&field2=%s&field3=%s" % (RH, T, Td))
print f.read()
f.close()
sleep(60) #uploads DHT22 sensor values every 1 minutes
except:
print 'exiting.'
break
# call main
if __name__ == '__main__':
main()
Your variable c is not defined. When you call calcDewPoint, it then calls gamma, which tries to run your math expression. However, c does not exist at that point.
Everything is running smooth, Code works with the odd exception in the debugger,
File "/usr/lib/python3/dist-packages/thonny/backend.py", line 305, in _custom_import
module = self._original_import(*args, **kw)
ImportError: No module named 'urllib2'
but overall it functions well. We can close up the thread.
"""
dht22.py
Temperature/Humidity monitor using Raspberry Pi and DHT22.
Data is displayed at thingspeak.com
Original author: Mahesh Venkitachalam at electronut.in
Modified by Jacques Kleynhans 06062020
Return rounded string values
Created Temporary variables Hum and Tair
"""
#import sys
import math
#import RPi.GPIO as GPIO
from time import sleep
import Adafruit_DHT
import urllib2
#Constant Variables - Magnus Parameters Max 0.083 Tair Range -20C + 50C
m = 17.62 # g/mol Mass Constant (Water Vapour)
Tn = 240.7263 #Tempreture Constant
Ah = 6.116441 #hPa Pressure Constant
Ak = 0.611 #kPa Pressure Constant
K = 273.15 #Kelvin constant
Ta = 216.7 #Tempreture Constant
#constant for leaf Temperature
Tc = 2.0
myAPI = 'FZZHL7N2R2AXXXXX'
def getSensorData():
RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 17)
return (round(RH,3), round(T,3))
# Define functions to calculate dewpoint, return a rounded string)
def calcDewPoint(Hum,Tair):
#print('dewpoint1')
Td = (Tn * gamma(Hum,Tair)) / (m - gamma(Hum,Tair))
#print('dewpoint2')
return round(Td,3)
def gamma(Hum,Tair):
#print ('gamma1')
g = math.log(Hum/100.0) + ((m * Tair) / (Tn + Tair))
#print('gamma2')
return round(g,3)
# Define functions to calculate VPD, return a rounded integer)
#Vapor pressure deficit control strategies for plant production
#IFAC Control applications and Ergonomics in Agriculture, Athens, Greece, 1998
def satVaporPres(Tair):
es = 6.1078*math.exp((Tair*17.2694)/(Tair+237.3)) #mPa
return round(es,3)
def actVaporPres(Hum, es):
ea = (Hum/100)*es
return round(ea,3)
def leafEs(Tair):
leafTemp = Tair - Tc
les = 6.1078*math.exp((leafTemp*17.2694)/(leafTemp+237.3))
return round(les, 3)
#Partial pressure of water vapour Pw in the air surrounding the plant
def parPressureW(Hum, es, Tair):
Pw = Hum*es*Tair
return(Pw)
def VPD(les, ea): #VPD air / crop
VPD = (les - ea)/10
return round(VPD,3)
def main():
print('starting...')
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
while True:
try:
RH, T = getSensorData()
Hum = RH
Tair = T
Td = calcDewPoint(Hum,Tair)
es = satVaporPres(Tair)
ea = actVaporPres(Hum, es)
les = leafEs(Tair)
TempVPD = VPD(les,ea)
print(Hum, Tair, Td, TempVPD)
f = urllib2.urlopen(baseURL + "&field1=%s&field2=%s&field3=%s&field4=%s" % (RH, T, Td, TempVPD))
print f.read()
f.close()
sleep(60) #uploads DHT22 sensor values every 1 minutes
except:
print('exiting.')
break
# call main
if __name__ == '__main__':
main()
Related
I'm having a few problems.
First, given wind speeds seem to be low, especially compared to other weather stations reporting close by (apparently there are lots of enthusiasts in my area). Just watching the trees, flag, bushes, small animals flying across my yard, I can tell 1.6mph is a wee bit low. Everything tested fine inside, and when I run the test script outside its picking up the signal as it spins.
the 2nd problem is it always reports the "mean" and "max" speeds as exactly the same. I've tried to adjust the intervals, but no matter what length of time I put in, they always report as the same numbers.
from gpiozero import Button
import requests
import time
import math
import statistics
import database
wind_count = 0
radius_cm = 9.0
wind_interval = 5
ADJUSTMENT = 1.18
interval = 60
gust = 0
def spin():
global wind_count
wind_count = wind_count + 1
def calculate_speed(time_sec):
global wind_count
global gust
circumference_cm = (2 * math.pi) * radius_cm
rotations = wind_count / 2.0
dist_cm = circumference_cm * rotations
dist_km = (circumference_cm * rotations) / 100000
dist_mi = dist_km * 0.621371
mi_per_sec = dist_mi / time_sec
mi_per_hour = mi_per_sec * 3600
return mi_per_hour * ADJUSTMENT
def reset_wind():
global wind_count
wind_count = 0
def reset_gust():
global gust
gust = 0
wind_speed_sensor = Button(16)
wind_speed_sensor.when_activated = spin
while True:
print("Starting Weather Sensor Read Loop...")
start_time = time.time()
while time.time() - start_time <= interval:
print("Start timed loop...")
wind_start_time = time.time()
reset_wind()
reset_gust()
store_speeds = []
time.sleep(wind_interval)
final_speed = calculate_speed(wind_interval)
store_speeds.append(final_speed)
wind_gust_speed = (max(store_speeds))
wind_speed = (statistics.mean(store_speeds))
print(wind_average, wind_speed)
When I comment out "store_speeds = [ ]" the first loop the speeds are reported the same, every loop after I get a "max" reading thats "different" than the mean. This still troubles me, because why on the first loop are they the same? Am I wrong for thinking with the wind_interval set at 5, and the interval set to 60, that its taking 5 second samples over a 60 second period, giving me 12 sample to get the mean and max from?
My goal is every time it reports, I get a mean and max for that "loop" if possible, and not a mean/max over the time the script stays running before its interrupted/stopped.
Here is the working and corrected code:
from gpiozero import Button
import time
import math
import statistics
wind_count = 0
radius_cm = 9.0
wind_interval = 5
interval = 30
CM_IN_A_KM = 100000.0
SECS_IN_AN_HOUR = 3600
ADJUSTMENT = 1.18
store_speeds = []
def reset_wind():
global wind_count
wind_count = 0
def spin():
global wind_count
wind_count = wind_count + 1
def calculate_speed(time_sec):
global wind_count
circumference_cm = (2 * math.pi) * radius_cm
rotations = wind_count / 2.0
dist_km = (circumference_cm * rotations) / CM_IN_A_KM
km_per_sec = dist_km / time_sec
km_per_hour = km_per_sec * SECS_IN_AN_HOUR
mi_per_hour = km_per_hour * 0.6214
return mi_per_hour * ADJUSTMENT
wind_speed_sensor = Button(16)
wind_speed_sensor.when_pressed = spin
while True:
store_speeds = []
for _ in range (interval//wind_interval):
reset_wind()
#reset_gust()
time.sleep(wind_interval) # counter is spinning in background
final_speed = calculate_speed(wind_interval)
store_speeds.append(final_speed)
wind_gust = max(store_speeds)
wind_speed = statistics.mean(store_speeds)
print(wind_speed, wind_gust)
I have this script on a Raspberry Pi that runs forever and every minute will get data from my weather station and then post it to a JSON and database. The issue is that after a few days of running, the Python script stops running with the following error:
munmap_chunk(): invalid pointer
Aborted
Here is the code:
from gpiozero import Button
import bme280_sensor
import wind_direction_byo
import ds18b20_therm
import statistics
import time
import math
import json
import database
import gc
CM_IN_A_KM = 100000.0
SECS_IN_AN_HOUR = 3600
ADJUSTMENT = 1.18
BUCKET_SIZE = 0.2794
store_speeds = []
store_directions = []
wind_count = 0
rain_count = 0
radius_cm = 9.0
wind_interval = 5
interval = 60
db = database.weather_database()
def spin():
global wind_count
wind_count = wind_count + 1
# print("spin" + str(wind_count))
def calculate_speed(time_sec):
global wind_count
circumference_cm = (2 * math.pi) * radius_cm
rotations = wind_count / 2.0
dist_km = (circumference_cm * rotations) / CM_IN_A_KM
km_per_sec = dist_km / time_sec
km_per_hour = km_per_sec * SECS_IN_AN_HOUR
return km_per_hour * ADJUSTMENT
wind_speed_sensor = Button(5)
wind_speed_sensor.when_pressed = spin
def reset_wind():
global wind_count
wind_count = 0
def bucket_tipped():
global rain_count
rain_count = rain_count + 1
def reset_rainfall():
global rain_count
rain_count = 0
def updateJsonFile(wind_average, wind_speed, wind_gust, rainfall, humidity, pressure, ambient_temp, ground_temp):
jsonFile = open("/var/www/html/weatherdata.json", "r")
data = json.load(jsonFile)
jsonFile.close()
tmp = data["ambient_temp"]
data["ambient_temp"] = ambient_temp
data["humidity"] = humidity
data["pressure"] = pressure
data["ground_temp"] = ground_temp
data["rainfall"] = rainfall
data["wind_average"] = wind_average
data["wind_speed"] = wind_speed
data["wind_gust"] = wind_gust
data["timestamp"] = time.time()
jsonFile = open("/var/www/html/weatherdata.json", "w+")
jsonFile.write(json.dumps(data))
jsonFile.close()
rain_sensor = Button(6)
rain_sensor.when_pressed = bucket_tipped
temp_probe = ds18b20_therm.DS18B20()
while True:
start_time = time.time()
while time.time() - start_time <= interval:
wind_start_time = time.time()
reset_wind()
#time.sleep(wind_interval)
while time.time() - wind_start_time <= wind_interval:
store_directions.append(wind_direction_byo.get_value())
final_speed = calculate_speed(wind_interval)
store_speeds.append(final_speed)
wind_average = wind_direction_byo.get_average(store_directions)
wind_gust = max(store_speeds)
wind_speed = statistics.mean(store_speeds)
rainfall = rain_count * BUCKET_SIZE
reset_rainfall()
humidity, pressure, ambient_temp = bme280_sensor.read_all()
ground_temp = temp_probe.read_temp()
#print(wind_average, wind_speed, wind_gust, rainfall, humidity, pressure, ambient_temp, ground_temp)
updateJsonFile(wind_average, wind_speed, wind_gust, rainfall, humidity, pressure, ambient_temp, ground_temp)
db.insert(ambient_temp, ground_temp, 0, pressure, humidity, wind_average, wind_speed, wind_gust, rainfall)
store_speeds = []
store_directions = []
gc.collect()
Most of the code is taken from Raspberry Pi's Weather Station guide. My addition is the updateJsonFile function and some other little things to get that to work. The website doesn't mention this problem however there was other errors in the guide they didn't mention.
My guess is that it's running out of memory (despite the garbage collect) considering the timing of when the error happens. I'm going to investigate that but if anyone else has a solution, that would be great.
I am running this code and oddly, nothing happens. There is no error nor does it freeze. It simply just runs the code without storing variables, nothing is printed out and it doesn't open the window that is supposed to show the plot. So it simply does nothing. It is very odd. This worked only a few minutes ago and I did not change anything about it previously. I did make sure that the variable explorer is displaying all the definitions in the script. I intentionally removed the plotting section at the end since it just made the code set longer and the same issue persists here without it.
Code:
#Import libraries
import numpy as np
from scipy.integrate import odeint
#from scipy.integrate import solve_ivp
from time import time
import matplotlib.pyplot as plt
from matplotlib.pyplot import grid
from mpl_toolkits.mplot3d import Axes3D
import numpy, scipy.io
from matplotlib.patches import Circle
'''
import sympy as sy
import random as rand
from scipy import interpolate
'''
'''
Initiate Timer
'''
TimeStart = time()
'''
#User defined inputs
'''
TStep = (17.8E-13)
TFinal = (17.8E-10)
R0 = 0.02
V0X = 1E7
ParticleCount = 1 #No. of particles to generate energies for energy generation
BInput = 0.64 #Magnitude of B field near pole of magnet in experiment
ScaleV0Z = 1
'''
#Defining constants based on user input and nature (Cleared of all errors!)
'''
#Defining Space and Particle Density based on Pressure PV = NkT
k = 1.38E-23 #Boltzman Constant
#Natural Constants
Q_e = -1.602E-19 #Charge of electron
M_e = 9.11E-31 #Mass of electron
JToEv = 6.24E+18 #Joules to eV conversion
EpNaut = 8.854187E-12
u0 = 1.256E-6
k = 1/(4*np.pi*EpNaut)
QeMe = Q_e/M_e
'''
Create zeros matrices to populate later (Cannot create TimeIndex array!)
'''
TimeSpan = np.linspace(0,TFinal,num=round((TFinal/TStep)))
TimeIndex = np.linspace(0,TimeSpan.size,num=TimeSpan.size)
ParticleTrajectoryMat = np.zeros([91,TimeSpan.size,6])
BFieldTracking = np.zeros([TimeSpan.size,3])
InputAngle = np.array([np.linspace(0,90,91)])
OutputAngle = np.zeros([InputAngle.size,1])
OutputRadial = np.zeros([InputAngle.size,1])
'''
Define B-Field
'''
def BField(x,y,z):
InputCoord = np.array([x,y,z])
VolMag = 3.218E-6 #Volume of magnet in experiment in m^3
BR = np.sqrt(InputCoord[0]**2 + InputCoord[1]**2 + InputCoord[2]**2)
MagMoment = np.array([0,0,(BInput*VolMag)/u0])
BDipole = (u0/(4*np.pi))*(((3*InputCoord*np.dot(MagMoment,InputCoord))/BR**5)-(MagMoment/BR**3))
#BVec = np.array([BDipole[0],BDipole[1],BDipole[2]])
#print(BDipole[0],BDipole[1],BDipole[2])
return (BDipole[0],BDipole[1],BDipole[2])
'''
Lorentz Force Differential Equations Definition
'''
def LorentzForce(PosVel,t,Constants):
X,Y,Z,VX,VY,VZ = PosVel
Bx,By,Bz,QeMe = Constants
BFInput = np.array([Bx,By,Bz])
VelInput = np.array([VX,VY,VZ])
Accel = QeMe * (np.cross(VelInput, BFInput))
LFEqs = np.concatenate((VelInput, Accel), axis = 0)
return LFEqs
'''
Cartesean to Spherical coordinates converter function. Returns: [Radius (m), Theta (rad), Phi (rad)]
'''
def Cart2Sphere(xIn,yIn,zIn):
P = np.sqrt(xIn**2 + yIn**2 + zIn**2)
if xIn == 0:
Theta = np.pi/2
else:
Theta = np.arctan(yIn/xIn)
Phi = np.arccos(zIn/np.sqrt(xIn**2 + yIn**2 + zIn**2))
SphereVector = np.array([P,Theta,Phi])
return SphereVector
'''
Main Loop
'''
for angletrack in range(0,InputAngle.size):
MirrorAngle = InputAngle[0,angletrack]
MirrorAngleRad = MirrorAngle*(np.pi/180)
V0Z = np.abs(V0X/np.sin(MirrorAngleRad))*np.sqrt(1-(np.sin(MirrorAngleRad))**2)
V0Z = V0Z*ScaleV0Z
#Define initial conditions
V0 = np.array([[V0X,0,V0Z]])
S0 = np.array([[0,R0,0]])
ParticleTrajectoryMat[0,:] = np.concatenate((S0,V0),axis=None)
for timeplace in range(0,TimeIndex.size-1):
ICs = np.concatenate((S0,V0),axis=None)
Bx,By,Bz = BField(S0[0,0],S0[0,1],S0[0,2])
BFieldTracking[timeplace,:] = np.array([Bx,By,Bz])
AllConstantInputs = [Bx,By,Bz,QeMe]
t = np.array([TimeSpan[timeplace],TimeSpan[timeplace+1]])
ODESolution = odeint(LorentzForce,ICs,t,args=(AllConstantInputs,))
ParticleTrajectoryMat[angletrack,timeplace+1,:] = ODESolution[1,:]
S0[0,0:3] = ODESolution[1,0:3]
V0[0,0:3] = ODESolution[1,3:6]
MatSize = np.array([ParticleTrajectoryMat.shape])
RowNum = MatSize[0,1]
SphereMat = np.zeros([RowNum,3])
SphereMatDeg = np.zeros([RowNum,3])
for cart2sphereplace in range(0,RowNum):
SphereMat[cart2sphereplace,:] = Cart2Sphere(ParticleTrajectoryMat[angletrack,cart2sphereplace,0],ParticleTrajectoryMat[angletrack,cart2sphereplace,1],ParticleTrajectoryMat[angletrack,cart2sphereplace,2])
for rad2deg in range(0,RowNum):
SphereMatDeg[rad2deg,:] = np.array([SphereMat[rad2deg,0],(180/np.pi)*SphereMat[rad2deg,1],(180/np.pi)*SphereMat[rad2deg,2]])
PhiDegVec = np.array([SphereMatDeg[:,2]])
RVec = np.array([SphereMatDeg[:,0]])
MinPhi = np.amin(PhiDegVec)
MinPhiLocationTuple = np.where(PhiDegVec == np.amin(PhiDegVec))
MinPhiLocation = int(MinPhiLocationTuple[1])
RAtMinPhi = RVec[0,MinPhiLocation]
OutputAngle[angletrack,0] = MinPhi
OutputRadial[angletrack,0] = RAtMinPhi
print('Mirror Angle Input (In deg): ',InputAngle[0,angletrack])
print('Mirror Angle Output (In deg): ',MinPhi)
print('R Value at minimum Phi (m): ',RAtMinPhi)
InputAngleTrans = np.matrix.transpose(InputAngle)
CompareMat = np.concatenate((InputAngleTrans,OutputAngle),axis=1)
I am running below code to taking for runHeartBreathRateKraskov, I am facing the issue and below error.
Want to run below code to calculate Transfer Entropy in runHeartBreathRateKraskov program. I am new and not so much knowledge about Entropy transfer and Mutual Information. I also attached my data set for Information.
from jpype import *
^
IndentationError: unexpected indent
# Run e.g. python runHeartBreathRateKraskov.py 2 2 1,2,3,4,5,6,7,8,9,10
from jpype import *
import sys
import os
import random
import math
import string
import numpy
# Import our readFloatsFile utility in the above directory:
sys.path.append(os.path.relpath(".."))
import readFloatsFile
# Change location of jar to match yours:
#jarLocation = "../../../infodynamics.jar"
jarLocation = "/home/humair/Documents/Transfer Entropy/infodynamics-dist-1.5/infodynamics.jar"
# Start the JVM (add the "-Xmx" option with say 1024M if you get crashes due to not enough memory space)
startJVM(getDefaultJVMPath(), "-ea", "-Djava.class.path=" + jarLocation)
# Read in the command line arguments and assign default if required.
# first argument in argv is the filename, so program arguments start from index 1.
if (len(sys.argv) < 2):
kHistory = 1;
else:
kHistory = int(sys.argv[1]);
if (len(sys.argv) < 3):
lHistory = 1;
else:
lHistory = int(sys.argv[2]);
if (len(sys.argv) < 4):
knns = [4];
else:
knnsStrings = sys.argv[3].split(",");
knns = [int(i) for i in knnsStrings]
if (len(sys.argv) < 5):
numSurrogates = 0;
else:
numSurrogates = int(sys.argv[4]);
# Read in the data
datafile = '/home/humair/Documents/Transfer Entropy/SFI-heartRate_breathVol_bloodOx.txt'
rawData = readFloatsFile.readFloatsFile(datafile)
# As numpy array:
data = numpy.array(rawData)
# Heart rate is first column, and we restrict to the samples that Schreiber mentions (2350:3550)
heart = data[2349:3550,0]; # Extracts what Matlab does with 2350:3550 argument there.
# Chest vol is second column
chestVol = data[2349:3550,1];
# bloodOx = data[2349:3550,2];
timeSteps = len(heart);
print("TE for heart rate <-> breath rate for Kraskov estimation with %d samples:" % timeSteps);
# Using a KSG estimator for TE is the least biased way to run this:
teCalcClass = JPackage("infodynamics.measures.continuous.kraskov").TransferEntropyCalculatorKraskov
teCalc = teCalcClass();
teHeartToBreath = [];
teBreathToHeart = [];
for knnIndex in range(len(knns)):
knn = knns[knnIndex];
# Compute a TE value for knn nearest neighbours
# Perform calculation for heart -> breath (lag 1)
teCalc.initialise(kHistory,1,lHistory,1,1);
teCalc.setProperty("k", str(knn));
teCalc.setObservations(JArray(JDouble, 1)(heart),
JArray(JDouble, 1)(chestVol));
teHeartToBreath.append( teCalc.computeAverageLocalOfObservations() );
if (numSurrogates > 0):
teHeartToBreathNullDist = teCalc.computeSignificance(numSurrogates);
teHeartToBreathNullMean = teHeartToBreathNullDist.getMeanOfDistribution();
teHeartToBreathNullStd = teHeartToBreathNullDist.getStdOfDistribution();
# Perform calculation for breath -> heart (lag 1)
teCalc.initialise(kHistory,1,lHistory,1,1);
teCalc.setProperty("k", str(knn));
teCalc.setObservations(JArray(JDouble, 1)(chestVol),
JArray(JDouble, 1)(heart));
teBreathToHeart.append( teCalc.computeAverageLocalOfObservations() );
if (numSurrogates > 0):
teBreathToHeartNullDist = teCalc.computeSignificance(numSurrogates);
teBreathToHeartNullMean = teBreathToHeartNullDist.getMeanOfDistribution();
teBreathToHeartNullStd = teBreathToHeartNullDist.getStdOfDistribution();
print("TE(k=%d,l=%d,knn=%d): h->b = %.3f" % (kHistory, lHistory, knn, teHeartToBreath[knnIndex])), # , for no newline
if (numSurrogates > 0):
print(" (null = %.3f +/- %.3f)" % (teHeartToBreathNullMean, teHeartToBreathNullStd)),
print(", b->h = %.3f nats" % teBreathToHeart[knnIndex]),
if (numSurrogates > 0):
print("(null = %.3f +/- %.3f)" % (teBreathToHeartNullMean, teBreathToHeartNullStd)),
print
# Exercise: plot the results
Dataset is:
The first column is heart rate, the second is chest volume, and the third is blood oxygen concentration.
76.53 8320 7771
76.53 8117 7774
76.15 7620 7788
75.39 6413 7787
75.51 7518 7767
76.67 1247 7773
78.55 -3525 7784
79.96 2388 7764
79.71 8296 7775
78.30 7190 7784
77.02 6024 7777
76.62 5825 7784
76.53 5154 7809
76.65 7464 7805
76.95 5345 7806
78.46 -993 7813
There is my code. I fixed it like this:
# Take 3 digits for significant figures in this code
import numpy as np
from math import *
from astropy.constants import *
import matplotlib.pyplot as plt
import time
start_time = time.time()
"""
G = Gravitational constant
g0 = Standard acceleration of gravity ( 9.8 m/s2)
M_sun = Solar mass
M_earth = Earth mass
R_sun = Solar darius
R_earth = Earth equatorial radius
au = Astronomical unit
Astropy.constants doesn't have any parameter of moon.
So I bring the data from wikipedia(https://en.wikipedia.org/wiki/Moon)
"""
M_moon = 7.342E22
R_moon = 1.737E6
M_earth = M_earth.value
R_earth = R_earth.value
G = G.value
perigee, apogee = 3.626E8, 4.054E8
position_E = np.array([0,0])
position_M = np.array([(perigee+apogee)/2.,0])
position_com = (M_earth*position_E+M_moon*position_M)/(M_earth+M_moon)
rel_pE = position_E - position_com
rel_pM = position_M - position_com
F = G*M_moon*M_earth/(position_M[0]**2)
p_E = {"x":rel_pE[0], "y":rel_pE[1],"v_x":0, "v_y":(float(F*rel_pE[0])/M_earth)**.5}
p_M = {"x":rel_pM[0], "y":rel_pM[1],"v_x":0, "v_y":(float(F*rel_pM[0])/M_moon)**.5}
print(p_E, p_M)
t = range(0,365)
data_E , data_M = [], []
def s(initial_velocity, acceleration, time):
result = initial_velocity*time + 0.5*acceleration*time**2
return result
def v(initial_velocity, acceleration, time):
result = initial_velocity + acceleration*time
return result
dist = float(sqrt((p_E["x"]-p_M['x'])**2 + (p_E["y"]-p_M["y"])**2))
xE=[]
yE=[]
xM=[]
yM=[]
data_E, data_M = [None]*len(t), [None]*len(t)
for i in range(1,366):
data_E[i-1] = p_E
data_M[i-1] = p_M
dist = ((p_E["x"]-p_M["x"])**2 + (p_E["y"]-p_M["y"])**2)**0.5
Fg = G*M_moon*M_earth/(dist**2)
theta_E = np.arctan(p_E["y"]/p_E["x"])
theta_M = theta_E + np.pi #np.arctan(data_M[i-1]["y"]/data_M[i-1]["x"])
Fx_E = Fg*np.cos(theta_E)
Fy_E = Fg*np.sin(theta_E)
Fx_M = Fg*np.cos(theta_M)
Fy_M = Fg*np.sin(theta_M)
a_E = Fg/M_earth
a_M = Fg/M_moon
v_E = (p_E["v_x"]**2+p_E["v_y"]**2)**.5
v_M = (p_M["v_x"]**2+p_M["v_y"]**2)**.5
p_E["v_x"] = v(p_E["v_x"], Fx_E/M_earth, 24*3600)
p_E["v_y"] = v(p_E["v_y"], Fy_E/M_earth, 24*3600)
p_E["x"] += s(p_E['v_x'], Fx_E/M_earth, 24*3600)
p_E["y"] += s(p_E['v_y'], Fy_E/M_earth, 24*3600)
p_M["v_x"] = v(p_M["v_x"], Fx_M/M_moon, 24*3600)
p_M["v_y"] = v(p_M["v_y"], Fy_M/M_moon, 24*3600)
p_M["x"] += s(p_M['v_x'], Fx_M/M_moon, 24*3600)
p_M["y"] += s(p_M['v_y'], Fy_M/M_moon, 24*3600)
for i in range(0,len(t)):
xE += data_E[i]["x"]
yE += data_E[i]["y"]
xM += data_M[i]["x"]
yM += data_M[i]["y"]
print("\n Run time \n --- %d seconds ---" %(time.time()-start_time))
after run this code i tried to print data_E and data_M.
Then I can get data but there is no difference. All of the data is the same.
But when I printed data step by step, it totally different.
I have wrong data problem and increase distance problem. Please help me this problem..
The code exits near line 45, where you are trying to assign p_E by pulling the square root of a negative number on the right hand side (as you've moved the [0] coordinate of the Earth to negative values while shifting Earth and Moon into the coordinate system of their center of mass). In line 45, the value of F*rel_pE[0]/M_earth is negative. So the code never reaches the end of the program using python 2.7.14. That bug needs to be solved before trying to discuss any further aspects.