[python] best way to access an attribute

All things Programming
Post Reply
User avatar
Naib
Site Admin
Posts: 659
Joined: Sat Dec 19, 2020 2:20 am

[python] best way to access an attribute

Post by Naib »

so i am building up a library of nice methods for my engineering work: return E-series values, millman's theorem, optimum resistor pair for a given ratio...

I am expanding to add component type classes due to the additional information such parts have...
Simple ADC classes to include DNL,INL etc... (and thus build up a key "database" of a shortlist of IC with common datastructures).

So resistors....

Up until now I would go:

R1 = 10e3
...
Then when I deal with tolerance analysis I would generate R1_m and R1_p to cover component tolerance as well as TCR for a given temperature...

What I am doing now is creating a resistor class

Code: Select all

Class Res():
  def __init__(self,R=None, tol=None, TCR=None, Temp=None):
      self.R = R
      self.m = ...
      self.p = ...
      self.rnd = ...
works well. I can then do:

Code: Select all

R1 = Res(10e3,1,100,80)
R2 = Res(10e3,1,100,80)
V = 15

vo = V*R1.p/(R1.p+R2.m)   
and this will return the worst-case maximum voltage out.

via __repr __? this returns a string and I require a float
via __call__ and then I can do R() to access the nominal? sloppy and isn't in keeping with the style
via R1.R or R1.n or R1.r slightly better but R1.R is viewed as redundant... R1.n (for nominal) is viable... R1.r (lower r) is not too bad.

What I really want is a __repr__ that returns a float

any idea's?
The best argument against democracy is a five-minute conversation with the average voter

Great Britain is a republic, with a hereditary president, while the United States is a monarchy with an elective king
User avatar
notageek
Site Admin
Posts: 445
Joined: Fri Dec 18, 2020 2:28 am
Location: India

Re: [python] best way to access an attribute

Post by notageek »

Code: Select all

Class Res():
     def __init__(self,R=None, tol=None, TCR=None, Temp=None):
            self.R = R
            self.m = ...
            self.p = ...
            self.rnd = ...
     def __repr__(self):
            return str(float(self.R))

R1 = Res(10e3,1,100,80)

>>> R1 
>>> 10000.0 
>>> R1*2 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'Res' and 'int'
>>> float(str(R1))*2 
20000.0
>>> type(R1)
<class '__main__.Res'>
i.e. override the __repr__ function to return the attribute you want in str, then convert (cast) the variable into string (again), then float and do your operations.
"Defeat is a state of mind. No one is ever defeated, until defeat has been accepted as a reality." -- Bruce Lee
User avatar
Naib
Site Admin
Posts: 659
Joined: Sat Dec 19, 2020 2:20 am

Re: [python] best way to access an attribute

Post by Naib »

yes it could be cast back to a float but from a readability perspective it's not great.

the float class is what I want so one option is to inherit float as that returns the value when the reference is used
The best argument against democracy is a five-minute conversation with the average voter

Great Britain is a republic, with a hereditary president, while the United States is a monarchy with an elective king
User avatar
notageek
Site Admin
Posts: 445
Joined: Fri Dec 18, 2020 2:28 am
Location: India

Re: [python] best way to access an attribute

Post by notageek »

__repr__ will always return string and it's not possible to overload.

https://docs.python.org/3/reference/dat ... t.__repr__

Alternate approaches would be 1. Rename "R" to represent what you actually mean. 2. Write a function for max voltage.

Code: Select all

Class Res():
  def __init__(self,R=None, tol=None, TCR=None, Temp=None):
      self.R = R
      self.m = ...
      self.p = ...
      self.rnd = ...
  
  def max_volt(self, v):
      return v*self.p/(self.p+self.m)   


R1 = Res(10e3,1,100,80)
R1.max_volt(15) 
Not sure why you need R2.
"Defeat is a state of mind. No one is ever defeated, until defeat has been accepted as a reality." -- Bruce Lee
User avatar
notageek
Site Admin
Posts: 445
Joined: Fri Dec 18, 2020 2:28 am
Location: India

Re: [python] best way to access an attribute

Post by notageek »

Alternative 3

Code: Select all

Class Res():
     def __init__(self,R=None, tol=None, TCR=None, Temp=None):
            self.R = R
            self.m = ...
            self.p = ...
            self.rnd = ...
     def __repr__(self):
            return str(float(self.R))
     def __mul__(self, other):
            return self.R * other

R1 = Res(10e3,1,100,80)

>>> R1 
>>> 10000.0 
>>> R1*2 
20000.0
>>> type(R1)
<class '__main__.Res'>
Operator overloading.

** making a coarse assumptions that you will multiply the class with an integer/float
"Defeat is a state of mind. No one is ever defeated, until defeat has been accepted as a reality." -- Bruce Lee
User avatar
Naib
Site Admin
Posts: 659
Joined: Sat Dec 19, 2020 2:20 am

Re: [python] best way to access an attribute

Post by Naib »

I think overloading all the __add__ __mul__ methods might be the best way to go.
The best argument against democracy is a five-minute conversation with the average voter

Great Britain is a republic, with a hereditary president, while the United States is a monarchy with an elective king
User avatar
notageek
Site Admin
Posts: 445
Joined: Fri Dec 18, 2020 2:28 am
Location: India

Re: [python] best way to access an attribute

Post by notageek »

Yes, you don't need to bother with __repr__ at all.
"Defeat is a state of mind. No one is ever defeated, until defeat has been accepted as a reality." -- Bruce Lee
User avatar
dont_think_twice
Bride Kidnapping Expert
Posts: 343
Joined: Sat Dec 19, 2020 4:15 am

Re: [python] best way to access an attribute

Post by dont_think_twice »

I don't get this. What are _m and _p?

I can imagine what you are trying to do: build a model of an electronic circuit, and then let the computer automatically run through tolerances on each component and tell you how the model output behaves. Since results are coupled, likely in a non-linear way, you need to run through all the values with tolerances together - not just change one at a time.

But that requires either calculating a huge number of cases, probably in some monte-carlo type of analysis.

Alternatively, you could do a local analysis, with something like autodiff - although I would think you would be better off doing that in julia than python. Similarly you could try to formulate your problem using adjoint methods. Both of those types of analysis won't tell you about the global landscape, just the local one though. So probably not good for tolerance analysis.

To me, the monte-carlo formulation seems like the best. Is that what you are going for?
User avatar
Naib
Site Admin
Posts: 659
Joined: Sat Dec 19, 2020 2:20 am

Re: [python] best way to access an attribute

Post by Naib »

_m and _p are the calculated _minus and _plus with regards to worst-case maximum and worst-case minimum based upon a components tolerance, temperature coef and also aging.

There are two sides of tolerance analysis

1) worst-worst analysis ... for this you literally need to understand a circuit and throw its corresponding values in the appropriate direction to produce the worst-case outcome. There is no "computer automatically run through tolerances" this is all via your brain knowing what will throw the circuit one way or another
2) Monte-carlo ...results based upon bound random changes.

Both are needed and #1 more so than #2 because if your design ONLY survives or operates based upon a statistical numbers game, it is poorly designed and certainly will not pass a 6sigma type evaluation, let alone something more hazardous as a living room.

--edit--
lets try a simple example: TPS57150-Q1 Buck converter configured to produce 1v2.
The principal parts that influence the output voltage are

1) R1 of feedback. 4k75, using TNPW resistors provide 0.1% tolerance and 25ppm temperature coef
2) R2 of feedback. 1k5, using TNPW resistors provide 0.1% tolerance and 25ppm temperature coef
3) precision of the internal reference. 0.8V, 1% tolerance worst-worst across tolerance and temp.

Every other tolerances are washed out due to closed-loop control (except ripple and stability but that a bit more advance for this quick lesson)

So across a temperature range of -55C -> 105C

R1 : 4726.2215 -> 4773.7785
R2: 1492.491 -> 1507.509
Vref: 0.792 -> 0.808

LOWEST output occurs when R1 is high, R2 is low and Vref is low. Likewise HIGEST output occurs when R1 is low, R2 is High and Vreg is high:

Vout MAXIMA: 1.2161
Vout MINIMA: 1.1841

Now executing a 1million point monte-carlo with a normal distribution produces:


now checking the resultant numpy array containing the monte-carlo:
print(vo_rnd.max(), vo_rnd.min())

1.210950546941486 1.1880381179310826

close... but not close enough for the worst-worse analysis and thus *IF* you were to use the maximum and minimum from the monte-carlo it would be "almost" the worst-case but isn't
bUt ThAt CaSe WoUlD nOt OcCuR iN pRaCtIcE ... so what? this is why my stuff works for decades, why I pass audits etc...


Oh and if I could be arsed I could write a machine learning algo to find the worst-worst combination rather than waste 5min per circuit to figure out which way would produce the extreme outputs
The best argument against democracy is a five-minute conversation with the average voter

Great Britain is a republic, with a hereditary president, while the United States is a monarchy with an elective king
User avatar
dont_think_twice
Bride Kidnapping Expert
Posts: 343
Joined: Sat Dec 19, 2020 4:15 am

Re: [python] best way to access an attribute

Post by dont_think_twice »

(1) It is easy to do a WCCA by hand when you only have three components. When you have 50 components though, it must be much harder? If you looked at the tails of distribution of your monte-carlo analysis, I'm sure they would make it pretty obvious which bounds each variable is up against? That works when the extreme outcomes occur at limits for each component - if they occur when the component is somewhere in the middle, then it isn't so easy. But if the extreme outcomes do occur somewhere away from the component limits, that means the WCCA by hand is probably pretty hard to do. Which are the cases in which monte-carlo analysis is critical as backup (at least).

(2) I still don't get what you are trying to do. If you are planning to do the math by hand, why do you need fancy python functions to store the values? If all your math is getting put into your python program, I say use jax, or something like that, to do autodifferentiate and do a sensitivity analysis, to estimate where the worst case occurs. You could probably do a pseudo-newton's-method from there to find the worst case.

(3) Or use an "optimization" algorithm - something good at finding global min/max, such as simulated annealing or genetic algorithm, to find the limits.

(4) Your million point monte-carlo analysis only has ~10k counts in it, for some reason.

(5) What python problem are you trying to solve? Your initially proposed code works fine for what it seems like you are doing. What am I missing?
User avatar
Naib
Site Admin
Posts: 659
Joined: Sat Dec 19, 2020 2:20 am

Re: [python] best way to access an attribute

Post by Naib »

1) not really. Circuits are made up of subcircuits and most subcircuits vary between 2-10 components which is still trivial by hand. Even 30 isn't that hard, just takes longer... Insight into how a circuit works makes this quicker

2) the reason for "fancy python functions" is to ensure consistency in the trivial parts of the tolerance analysis to remove errors

3) that is my plan but first was to adapt what is typically done to then permit a simple brute force or genetic algorithm to "hunt" for the combination that produces the extreme Maxima/minima output. 10 components is only 1million combinations

4) it's not, this is a seaborn hystergram with a calculated KDE and a minimum binwidth to produce a plot that can be read

5) consistency. Part of analysis need the nominal, part needs Maxima, minima and part needs rnd BUT all are applied to a transfer function so providing a consistent way values are used, possible error are removed


Why do this? If a design is show to meet worst-worst against stress and variation AND meets requirements then the discussion is over.. if not lots more review and 5whys
Why do the monte-carlo if worst-worst is what needed? Because worst-worst is the designer showing their design is robust while monte-carlo feeds into production to drive ESS and 6sigma variation limits
The best argument against democracy is a five-minute conversation with the average voter

Great Britain is a republic, with a hereditary president, while the United States is a monarchy with an elective king
User avatar
dont_think_twice
Bride Kidnapping Expert
Posts: 343
Joined: Sat Dec 19, 2020 4:15 am

Re: [python] best way to access an attribute

Post by dont_think_twice »

Thanks for explaining this Naib.

I appreciate your insight.
Post Reply