techstuff.html


001| '''Tech Stuff -- Various Tech Fun.
001| 
001| Polynomial Graphics:
001| ====================
001|     PolyN (object)      - Polynomial generator class
001|     PolyChart (mlchart) - Polynomial Chart making class
001| 
001| Other Functions:
001| ================
001|     convert_exponent(e, b1, b2) - convert an exponent from base1 to base2
001|     LongitudeDegree_km(a)       - length of one deg. long. at lat. a (in kilometers)
001|     LongitudeDegree_mi(a)       - length of one deg. long. at lat. a (in miles)
001|     Lorentz                     - frame shift
001| 
001|     mass2energy(m)              - various energy values for a given mass
001|     debroglie_wavelength(m,v)   - given mass and velocity
001|     debroglie_waves(m,v)        - given mass and velocity
001|         E(m)                    - E=mc^2
001|         EVolt(e)                - Electron Volts given e
001|         KWh(e)                  - KiloWatt Hours given e
001|         BTU(e)                  - BTU given e
001|         FtLb(e)                 - Foot Pounds given e
001|         Tons(e)                 - Tons (of TNT) given e
001| 
001|     brain_network()             - info dump
001|     brain_volume()              - info dump
001| 
001| Formulas[name] = lambda x:
001| ==========================
001|     m2ft        feet => meters
001|     ft2m        meters => feet
001|     km2mi       miles => kilometers
001|     mi2km       kilometers => miles
001|     energy      frequency => h*f
001|     wavelength  frequency => c/f
001|     frequency   wavelength => c/w
001| 
001|     deBroglie-wavelength (mass, velocity)
001| 
001| Lambda Functions:
001| =================
001|     E       m=> m*(c^2)
001|     EVolt   e=> e/1.60218e-19
001|     KWh     e=> e/3.6e6
001|     BTU     e=> e/1.05505e3
001|     FtLb    e=> e/1.35575
001|     Tons    e=> e/4.184e9
001| 
001| Quantum Gates:
001| ==============
001| Classes:
001|     qc_gate     (matrix2d)  - Quantum Gate base class.
001|     qc_gate_i   (qc_gate)   - Identity Quantum Gate class.
001|     hadamard    (qc_gate)   - Hadamard Quantum Gate class.
001|     pauli_x     (qc_gate)   - Pauli-X  Quantum Gate class.
001|     pauli_y     (qc_gate)   - Pauli-Y  Quantum Gate class.
001|     pauli_z     (qc_gate)   - Pauli-Z  Quantum Gate class.
001| 
001| '''

002| ####################################################################################################
003| from os import path
004| from math import pi, cos,radians
005| from cmath import sqrt
006| from goodies import KWARG, intervals, add_commas
007| from facts import Planets, Constants
008| from matrix import matrix2d
009| from mlchart import mlchart
010| ####################################################################################################
011| 
012| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
013| class PolyN (object):
014|     '''Polynomial generator class.'''
015|     def __init__ (self, coeffs):
016|         ''''Create a new polynomial object.'''
017|         # Function to generate one term...
018|         poly = lambda c,e:lambda x:(c*pow(x,e))
019|         # Keep a copy of the coefficients...
020|         self.coeffs = coeffs
021|         # Generate a list of terms...
022|         terms = [poly(c,ix) for ix,c in enumerate(reversed(coeffs))]
023|         # Bind the list of terms in a function...
024|         self.expr = lambda x:[f(x) for f in reversed(terms)]
025|         # Evaluate f(0) for default values...
026|         self(0)
027| 
028|     def __call__ (self, x):
029|         '''Evaluate f(x); return result.'''
030|         # Generate a list of values...
031|         self.vals = self.expr(x)
032|         # Sum the values to get (and return) a result...
033|         self.result = sum(self.vals)
034|         return self.result
035| 
036|     def derivative (self):
037|         '''Return a new PolyN instance that's a derivative of this.'''
038|         # Generate a new list of coefficients...
039|         # (Note: The tail term always ends up zero.)
040|         dx = [(t[0]*t[1]) for t in enumerate(reversed(self.coeffs))]
041|         # Return a new instance...
042|         # (Truncating that zero tail term.)
043|         # ((The truncation auto-decrements the exponents b/c they're positional!))
044|         return PolyN([t for t in reversed(dx[1:])])
045| 
046|     def __str__ (self):
047|         '''Pretty print the polynomial.'''
048|         # Treat an empty coefficients list as a special case...
049|         if len(self.coeffs) == 0:
050|             return '<zero>'
051|         # Generate a list of string versions of the terms...
052|         ts = ['(%+.2f)x^%d' % (c,ix) for ix,c in enumerate(reversed(self.coeffs))]
053|         # Join and return the strings...
054|         return ' '.join(reversed(ts))
055| 
056|     def __repr__ (self):
057|         '''Return the coefficients as a string.'''
058|         return str(self.coeffs)
059| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
060| class PolyChart (mlchart):
061|     '''Polynomial Chart making class.'''
062|     colors = ['#ff0000', '#009f00', '#0000cc', '#9f9f00', '#009f9f', '#9f009f', '#7f7f7f']
063| 
064|     def __init__ (self, coeffs_list, **kwargs):
065|         ''''Create a new polynomial chart object.'''
066|         super().__init__()
067|         self.ftns = [PolyN(cs) for cs in coeffs_list]
068|         self.incr = KWARG('step', 0.1, str, kwargs)
069|         self.title = 'Polynomial Curves by PolyN'
070|         self.x_title = 'X Axis'
071|         self.y_title = 'Y Axis'
072|         self.dims = kwargs['dims'] if 'dims' in kwargs else (6.0, 6.0)
073|         self.x_limit = kwargs['xlim'] if 'xlim' in kwargs else (-10.0, +10.0)
074|         self.y_limit = kwargs['ylim'] if 'ylim' in kwargs else (-10.0, +10.0)
075|         self.x_grids = kwargs['xt'] if 'xt' in kwargs else (5.0, 1.00)
076|         self.y_grids = kwargs['yt'] if 'yt' in kwargs else (5.0, 1.00)
077|         self.x_tickf = '%+.1f'
078|         self.y_tickf = '%+.1f'
079|         self.margins = dict(left=0.130, right=0.975, bottom=0.12, top=0.92) #ATTN: use kwargs?
080|         self.fpath = KWARG('fpath', r'C:\CJS\www\_dat', str, kwargs)
081|         self.fname = KWARG('fname', 'polyn.png', str, kwargs)
082| 
083|     def plotter (self):
084|         xs = list(intervals(self.x_limit[0], self.x_limit[1], self.incr))
085|         for ix,ftn in enumerate(self.ftns):
086|             ys = [ftn(x) for x in xs]
087|             self.ax.plot(xs,ys, c=self.colors[ix], lw=2.0, alpha=0.8, zorder=11+ix)
088|         #self.ax.legend(loc='lower right', shadow=True)
089| 
090|     def make_x_axis_spcl (self):
091|         for tick in self.ax.xaxis.get_major_ticks():
092|             tick.label1.set_rotation('vertical')
093|             tick.label1.set_size(9)
094| 
095| 
096| ##================================================================================================##
097| def convert_exponent (expon, base1, base2=None, prn=False):
098|     '''Convert an exponent from base1 to base2. [A^x = B^(x * logB(A))] Uses natural log as default base2.'''
099|     retv = (expon*log(base1,base2) if base2 else (expon*log(base1)))
100|     if prn:
101|         print('%s^%s = %s^%s' % (base1,expon, (base2 if base2 else 'e'),retv))
102|     return
103| 
104| ##================================================================================================##
105| '''Return correct distance of one degree of longitude at a given latitude.'''
106| LongitudeDegree_km = lambda a: ((pi/180.0) * (Planets['earth']['radius']['km'] * cos(radians(a))))
107| LongitudeDegree_mi = lambda a: ((pi/180.0) * (Planets['earth']['radius']['mi'] * cos(radians(a))))
108| 
109| ##================================================================================================##
110| '''Lorentz. v=[1.0-0.0] (fraction of c)'''
111| Lorentz = lambda v: 1.0 / sqrt(1.0 - pow(v,2))
112| 
113| 
114| ####################################################################################################
115| Formulas = {
116|     'ft2m':lambda m:(Constants['distance']['m/ft']*m),
117|     'm2ft':lambda ft:(Constants['distance']['ft/m']*ft),
118|     'mi2km':lambda km:(Constants['distance']['km/mi']*km),
119|     'km2mi':lambda mi:(Constants['distance']['mi/km']*mi),
120|     'energy':lambda f:(Constants['planck']['h']*f),
121|     'wavelength':lambda f:(Constants['c']['m/s']/f),
122|     'frequency':lambda w:(Constants['c']['m/s']/w),
123|     'deBroglie-wavelength':lambda m,v:(Constants['planck']['h']/(m*v)),
124| }
125| 
126| ##================================================================================================##
127| light = Constants['c']['m/s']
128| light2 = pow(light,2)
129| 
130| E = lambda m: (float(m)*float(light2))
131| EVolt = lambda e: (float(e)/1.60218e-19)
132| KWh = lambda e: (float(e)/3.6e6)
133| BTU = lambda e: (float(e)/1.05505e3)
134| FtLb = lambda e: (float(e)/1.35575)
135| Tons = lambda e: (float(e)/4.184e9)
136| 
137| ##================================================================================================##
138| def mass2energy (mass=1.0):
139|     '''Convert kilograms to energy per E=mc2.'''
140|     energy = E(mass)
141|     volts = EVolt(energy)
142|     watts = KWh(energy)
143|     btu = BTU(energy)
144|     ftlbs = FtLb(energy)
145|     tons = Tons(energy)
146|     print('%12.5e kg' % mass)
147|     print('%12.5e joules' % energy)
148|     print('%12.5e eVolts' % volts)
149|     print('%12.5e KW hours' % watts)
150|     print('%12.5e BTU' % btu)
151|     print('%12.5e foot-pounds' % ftlbs)
152|     print('%12.5e tons TNT' % tons)
153|     print()
154|     return (energy, volts, watts, btu, ftlbs, tons)
155| 
156| ##================================================================================================##
157| def debroglie_wavelength (mass, velocity):
158|     '''Returns (wavelength, momentum, mass, velocity) given (velocity, mass).'''
159|     h = 6.6261e-34
160|     p = mass*velocity
161|     w = h/p
162|     print('Mass: %e kg' % mass)
163|     print('Velocity: %e m/s' % velocity)
164|     print('Momentum: %e kg-m/s' % p)
165|     print('Wavelength: %e m' % w)
166|     print()
167|     return (w, p, mass, velocity)
168| 
169| ##================================================================================================##
170| EV = Constants['energy']['Ev']
171| m2ft = Formulas['m2ft']
172| ft2m = Formulas['ft2m']
173| km2mi = Formulas['km2mi']
174| mi2km = Formulas['mi2km']
175| 
176| debroglie = Formulas['deBroglie-wavelength']
177| wavelen2freq = Formulas['frequency']
178| freq2energy = Formulas['energy']
179| 
180| freq2evolt = lambda freq: (freq2energy(freq)/EV)
181| deBroglie = lambda m,v: (m,v, debroglie(m,v))
182| 
183| ##================================================================================================##
184| def debroglie_waves (mass=1.0, velocity=1.0):
185|     '''Calculate de Broglie wavelength and frequency for a mass and velocity.'''
186|     mass_wl = deBroglie(mass,velocity)[2]
187|     mass_f = wavelen2freq(mass_wl)
188|     gamma_f = 300e18
189|     xray_f = 300e15
190|     micr_f = wavelen2freq(10e-6)
191|     mili_f = wavelen2freq(10e-3)
192|     onem_f = wavelen2freq(1.0)
193|     tenm_f = wavelen2freq(10.0)
194|     red,blue = (680e-9, 470e-9)
195|     red_f,blue_f = (wavelen2freq(red), wavelen2freq(blue))
196|     print('10 meter wavelength: %.2e Hz (%.2e Ev)' % (tenm_f, freq2evolt(tenm_f)))
197|     print('1 meter wavelength: %.2e Hz (%.2e Ev)' % (onem_f, freq2evolt(onem_f)))
198|     print('Millimeter wavelength: %.2e Hz (%.2e Ev)' % (mili_f, freq2evolt(mili_f)))
199|     print('Micrometer wavelength: %.2e Hz (%.2e Ev)' % (micr_f, freq2evolt(micr_f)))
200|     print()
201|     print('Red light (680nm): %.2e Hz (%.2e Ev)' % (red_f, freq2evolt(red_f)))
202|     print('Blue light (470nm): %.2e Hz (%.2e Ev)' % (blue_f, freq2evolt(blue_f)))
203|     print()
204|     print('X-Rays (1nm): %.2e Hz (%.2e Ev)' % (xray_f, freq2evolt(xray_f)))
205|     print('Gamma Rays (1pm): %.2e Hz (%.2e Ev)' % (gamma_f, freq2evolt(gamma_f)))
206|     print()
207|     print('freq[WL[m,v]] (%.2em): %.2e Hz (%.2e Ev)' % (mass_wl, mass_f, freq2evolt(mass_f)))
208|     print()
209|     return (mass_wl, mass_f, mass,velocity)
210| 
211| 
212| ##================================================================================================##
213| def brain_network ():
214|     '''Digital requirements of human brain networks.'''
215|     neurons = int(1e11)
216|     synapses = int(1e15)
217|     print()
218|     print('%s (1e11) neurons requires %.2f bits' % (add_commas(neurons),11*d2b))
219|     print('%s (1e15) synapses requires %.2f bits' % (add_commas(synapses),15*d2b))
220|     print()
221|     print('two-way synapse map: %s bytes' % add_commas(synapses*16))
222|     print()
223|     return (neurons, synapses)
224| ##================================================================================================##
225| def brain_volume ():
226|     '''Volume of the human brain.'''
227|     volume = lambda r: ((4/3.0)*pi*pow(r,3))
228|     r = m_in * 4        # r = radius in meters
229|     v = volume(1e9 * r) # v = volume in nano-meters
230|     print()
231|     print(f'volume: %.2e nm^3 @ r=%.2f m (%.2f in)' % (v,r,r*in_m))
232|     print()
233|     return (v, r)
234| 
235| 
236| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
237| class qc_gate (matrix2d):
238|     '''Quantum Gate base class.'''
239|     def __init__ (self, kind):
240|         super().__init__()
241|         self.kind = kind
242| 
243|     def __str__ (self):
244|         buf = []
245|         for cs in self.m:
246|             row = []
247|             for c in cs:
248|                 row.append('(%+.2f,%+.2fi)' % (c.real, c.imag))
249|             buf.append(', '.join(row))
250|         s = '[%s]' % '\n '.join(buf)
251|         return s
252| 
253| 
254| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
255| class qc_gate_i (qc_gate):
256|     '''Identity Quantum Gate class.'''
257|     def __init__ (self):
258|         super().__init__('Iden')
259|         self.m[0][0] = complex(1, 0)
260|         self.m[0][1] = complex(0, 0)
261|         self.m[1][0] = complex(0, 0)
262|         self.m[1][1] = complex(1, 0)
263| 
264| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
265| class hadamard (qc_gate):
266|     '''Hadamard Quantum Gate class.'''
267|     def __init__ (self):
268|         super().__init__('Had')
269|         f = 1.0/sqrt(2.0)
270|         self.m[0][0] = complex(+f, 0)
271|         self.m[0][1] = complex(+f, 0)
272|         self.m[1][0] = complex(+f, 0)
273|         self.m[1][1] = complex(-f, 0)
274| 
275| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
276| class pauli_x (qc_gate):
277|     '''Pauli-X Quantum Gate class.'''
278|     def __init__ (self):
279|         super().__init__('SX')
280|         self.m[0][0] = complex(0, 0)
281|         self.m[0][1] = complex(1, 0)
282|         self.m[1][0] = complex(1, 0)
283|         self.m[1][1] = complex(0, 0)
284| 
285| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
286| class pauli_y (qc_gate):
287|     '''Pauli-Y Quantum Gate class.'''
288|     def __init__ (self):
289|         super().__init__('SY')
290|         self.m[0][0] = complex(0,  0)
291|         self.m[0][1] = complex(0, -1)
292|         self.m[1][0] = complex(0, +1)
293|         self.m[1][1] = complex(0,  0)
294| 
295| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
296| class pauli_z (qc_gate):
297|     '''Pauli-Z  Quantum Gate class.'''
298|     def __init__ (self):
299|         super().__init__('SZ')
300|         self.m[0][0] = complex(+1, 0)
301|         self.m[0][1] = complex( 0, 0)
302|         self.m[1][0] = complex( 0, 0)
303|         self.m[1][1] = complex(-1, 0)
304| 
305| 
306| ####################################################################################################
307| '''eof'''
308|