Skip to content

Instantly share code, notes, and snippets.

@unalfaruk
Created July 8, 2022 16:52
Show Gist options
  • Save unalfaruk/e42ffb36743d8ede9c50f75329dfef8e to your computer and use it in GitHub Desktop.
Save unalfaruk/e42ffb36743d8ede9c50f75329dfef8e to your computer and use it in GitHub Desktop.
Weighted Estimation of a Constant
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 23 21:45:31 2022
@author: personF
"""
import numpy as np
import matplotlib.pyplot as plt
class Resistor:
def __init__(self,ohm):
self.ohm = ohm
class Sensor:
def __init__(self,mean,std):
self.inputVal = []
self.outputVal = []
self.err_std = std
self.mean = mean
def measure(self,realVal):
self.inputVal.append(realVal)
self.outputVal.append(realVal+np.random.normal(self.mean,self.err_std))
def meanOfResult(self):
return np.sum(self.outputVal)/len(self.outputVal)
# Create a resistor and sensors
resistor = Resistor(355)
sensorCheap = Sensor(0,11)
sensorExpensive = Sensor(0,3)
numberOfMeasurement = 3
# Measurement:
for i in range(0,numberOfMeasurement):
sensorCheap.measure(resistor.ohm)
sensorExpensive.measure(resistor.ohm)
# The histograph of the measurements
fig, axs = plt.subplots(2)
axs[0].hist(sensorCheap.outputVal)
axs[0].set_title("Cheap Multimeter")
axs[1].hist(sensorExpensive.outputVal)
axs[1].set_title("Expensive Multimeter")
x_lim = (min(sensorCheap.outputVal + sensorExpensive.outputVal)-1,max(sensorCheap.outputVal + sensorExpensive.outputVal)+1)
plt.setp(axs, xlim=x_lim)
plt.show()
# To verify
sensorCheapStd = np.std(sensorCheap.outputVal)
sensorExpensiveStd = np.std(sensorExpensive.outputVal)
# The mean of the measurements
cheapRes = sensorCheap.meanOfResult()
expensiveRes = sensorExpensive.meanOfResult()
###############################################
######### WEIGHTED
allMeasurements = np.concatenate((sensorCheap.outputVal,sensorExpensive.outputVal))
#For print the math equation
str_coeff_measurementWithWeights=[]
str_coeff_sensorsWithWeights=[]
#For math
coeff_measurementWeights=[]
coeff_sensorWeights=[]
coeff_measurementWithWeights=[]
measurementWithWeights = 0
sensorsWithWeights = 0
for i in range(0,len(allMeasurements)):
if i<=(len(allMeasurements)/2)-1:
sensor = sensorCheap
else:
sensor = sensorExpensive
# Keep each step values in a list
coeff_measurementWeights.append(1/(sensor.err_std)**2)
coeff_sensorWeights.append(1/(sensor.err_std**2))
coeff_measurementWithWeights.append(allMeasurements[i]/((sensor.err_std)**2))
tmp = "%.1f/%.1f" % (allMeasurements[i],(sensor.err_std)**2)
str_coeff_measurementWithWeights.append(tmp)
tmp = "1/%d" % (sensor.err_std**2)
str_coeff_sensorsWithWeights.append(tmp)
weightedResult = (sum(coeff_sensorWeights)**(-1))*sum(coeff_measurementWithWeights)
print("The generic equation\t:\t(%s) (%s)" % ("+".join(str_coeff_sensorsWithWeights),"+".join(str_coeff_measurementWithWeights)))
# Calculate and print total coefficients of each measurement
totalCoeff =[x*(sum(coeff_sensorWeights)**-1) for x in coeff_measurementWeights]
str_totalCoeffMeasurement = []
for i in range(0,len(allMeasurements)):
tmp = "%.3f*%.3f" % (totalCoeff[i],allMeasurements[i])
str_totalCoeffMeasurement.append(tmp)
print("Weighted measurements\t:\t%s" % " + ".join(str_totalCoeffMeasurement))
# The bar of the estimations and real value
x = np.array(["Real", "Cheap", "Exp", "Weighted"])
y = np.array([resistor.ohm, cheapRes, expensiveRes, weightedResult])
plt.figure()
plt.axhline(y = resistor.ohm, color = 'k', linestyle = '--') #real
plt.axhline(y = weightedResult, color = 'b', linestyle = 'dashed') #weighted
plt.axhline(y = cheapRes, color = 'r', linestyle = 'dashed') #cheap
plt.axhline(y = expensiveRes, color = 'g', linestyle = 'dashed') #expensive
plt.legend(['real','weighted','cheap','expensive'])
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment