def auxiliary_equations(*, F, T_degC, N_s, T_degC_0, I_sc_A_0, I_rs_A_0, n_0, R_s_Ohm_0, G_p_S_0, E_g_eV_0): """ Computes the auxiliary equations at F and T_degC for the 6-parameter SDM-G. Inputs (any broadcast-compatible combination of scalars and numpy arrays): Same as current_sum_at_diode_node(). Outputs (device-level, at each combination of broadcast inputs, return type is np.float64 when all scalar inputs): dict containing model parameters at operating conditions: I_ph_A photocurrent I_rs_A diode reverse-saturation current n diode ideality factor R_s_Ohm series resistance G_p_S parallel conductance N_s integer number of cells in series in each parallel string T_degC effective diode-junction temperature """ # Temperatures must be in Kelvin. T_K = convert_temperature(T_degC, 'Celsius', 'Kelvin') T_K_0 = convert_temperature(T_degC_0, 'Celsius', 'Kelvin') # Compute variables at operating conditions. # Compute band gap (constant). E_g_eV = E_g_eV_0 # Compute diode ideality factor (constant). n = n_0 # Compute reverse-saturation current at T_degC (this is independent of F, I_sc_A_0, R_s_Ohm_0, and G_p_S_0). I_rs_A = I_rs_A_0 * (T_K / T_K_0)**3 * np.exp(E_g_eV / (n * k_B_eV_per_K) * (1 / T_K_0 - 1 / T_K)) # Compute series resistance (constant). R_s_Ohm = R_s_Ohm_0 # Compute parallel conductance (constant). G_p_S = G_p_S_0 # Compute parallel conductance (photo-conductive shunt). # G_p_S = F * G_p_S_0 # Compute photo-generated current at F and T_degC (V=0 with I=Isc for this). expr1 = I_sc_A_0 * F expr2 = expr1 * R_s_Ohm I_ph_A = expr1 + I_rs_A * np.expm1( q_C * expr2 / (N_s * n * k_B_J_per_K * T_K)) + G_p_S * expr2 return ensure_numpy_scalars( dictionary={ 'N_s': N_s, 'T_degC': T_degC, 'I_ph_A': I_ph_A, 'I_rs_A': I_rs_A, 'n': n, 'R_s_Ohm': R_s_Ohm, 'G_p_S': G_p_S })
def make_temperature_model(df): # Load the temperature dataset ds = load_ds(df, "t") X_train, X_test, y_train, y_test = ds # Convert temperatures into Celsius degrees y_train[:] = [convert_temperature(y, "Kelvin", "Celsius") for y in y_train] y_test[:] = [convert_temperature(y, "Kelvin", "Celsius") for y in y_test] # Build & fit the model model = make_pipeline( PolynomialFeatures(6), StandardScaler(), LinearRegression(), ) model.fit(X_train, y_train) y_pred = model.predict(X_test) plot_regression( "temperature", "Temperature (Celsius)", dataset=(X_train, X_test, y_train, y_test), y_pred=y_pred, ) return model, ds, y_pred
def plot_sounding(sndg_data, yr, day, mo, hr, diablo_sounding): plt.rcParams['figure.figsize'] = (9, 9) skew_evening = SkewT() one_sounding = sndg_data.loc[sndg_data[' Hour'] == hr] T = convert_temperature(one_sounding[' Temp'].values, 'F', 'C') rh = one_sounding[' RH'].values one_sounding[' Dewpt'] = calc_dewpt(T, rh) one_sounding = one_sounding.dropna(subset=(' Temp', ' Dewpt'), how='all').reset_index(drop=True) T = convert_temperature(one_sounding[' Temp'].values, 'F', 'C') * units.degC p = one_sounding[' Pres'].values * units.hPa Td = one_sounding[' Dewpt'].values * units.degC wind_speed = one_sounding[' Spd'].values * units.knots wind_dir = one_sounding[' Dir '].values * units.degrees u, v = mpcalc.get_wind_components(wind_speed, wind_dir) skew_evening.plot(p, T, 'r') skew_evening.plot(p, Td, 'g') skew_evening.plot_barbs(p, u, v) skew_evening.plot_dry_adiabats() skew_evening.plot_moist_adiabats() skew_evening.plot_mixing_lines() skew_evening.ax.set_ylim(1000, 100) plt.title('OAK Sounding: ' + str(int(mo)) + '/' + str(int(day)) + '/' + str(int(yr)) + ': ' + str(int(hr)) + ' UTC') plt.savefig('../Images/20180703/' + diablo_sounding + '/OAK_sounding_eve_' + str(int(mo)) + '_' + str(int(day)) + '_' + str(int(yr)) + '_' + str(int(hr)) + 'UTC.png') plt.close() return one_sounding
def unit_conversion(input_value, unit, dimension): import scipy.constants as sc if dimension == 'length': if unit.lower() == 'nm': value = input_value*sc.nano elif unit.lower() == 'μm' or unit.lower() == 'um': value = input_value*sc.micro elif unit.lower() == 'mm': value = input_value*sc.milli elif unit.lower() == 'cm': value = input_value*sc.centi elif unit.lower() == 'm': value = input_value elif unit.lower() == 'mil': value = input_value*sc.mil elif unit.lower() == 'in': value = input_value*sc.inch elif unit.lower() == 'ft': value = input_value*sc.foot else: raise ValueError elif dimension == 'temperature': if unit.lower() == 'k': value = input_value elif unit.lower() == 'c': value = sc.convert_temperature(input_value,'C','K') elif unit.lower() == 'f': value = sc.convert_temperature(input_value,'F','K') else: raise ValueError elif dimension == 'pressure': if unit.lower() == 'pa': value = input_value elif unit.lower() == 'kpa': value = input_value*sc.kilo elif unit.lower() == 'atm': value = input_value*sc.atm else: raise ValueError elif dimension == 'velocity': if unit.lower() == 'cm/s': value = input_value*sc.centi elif unit.lower() == 'm/s': value = input_value elif unit.lower() == 'ft/min': value = input_value*sc.foot/sc.minute else: raise ValueError return value
def r2c(value): """ converts temperature in R(degrees Rankine) to C(degrees Celsius) :param value: temperature in C(degrees Celsius) :return: temperature in R(degrees Rankine) """ return const.convert_temperature(value, 'R', 'C')
def __init__(self, temperature=20, nf=0.0, bw=0.5, load=50, is_complex=True): """ It requires five parameters to construct: :param temperature: float, Ambient temperature in :math:`^{\circ}C` (defaults to :math:`20^{\circ}C` if not provided) :param nf: float, Noise figure in dB at the point of injection (defaults to 0dB if not provided) :param bw: float, Bandwidth of signal in Hz (defaults to 0.5 Hz if not provided) :param load: float, Load impedance in :math:`\Omega` (defaults to 50 :math:`\Omega` if not provided) :param is_complex: bool, Selects complex vs real noise source (defaults to True if not selected) """ incident_n0 = consts.Boltzmann * consts.convert_temperature(float(temperature), 'C', 'K') incident_n = incident_n0 * float(2*bw) n = incident_n * (10.0 ** (float(nf)/10.0)) self.v_rms = math.sqrt(n * float(load)) """ float RMS value of noise voltage as if the signal was a real RF signal. The RMS value of each component of a complex baseband noise sample is :math:`\\frac{1}{\\sqrt{2}}` times RMS value. """ self.is_complex = is_complex """
def f2k(value): """ converts temperature in F(degrees Fahrenheit) to K(Kelvins) :param value: temperature in F(degrees Fahrenheit) :return: temperature in K(Kelvins) """ return const.convert_temperature(value, 'F', 'K')
def k2c(value): """ converts temperature in K(Kelvins) to C(degrees Celsius) :param value: temperature in K(Kelvins) :return: temperature in C(degrees Celsius) """ return const.convert_temperature(value, 'K', 'C')
def f2c(value): """ converts temperature in F(degrees Fahrenheit) to C(degrees Celsius) :param value: temperature in F(degrees Fahrenheit) :return: temperature in C(degrees Celsius) """ return const.convert_temperature(value, 'F', 'K')
def c2f(value): """ converts temperature in C(degrees Celsius) to F(degrees Fahrenheit) :param value: temperature in C(degrees Celsius) :return: temperature in F(degrees Fahrenheit) """ return const.convert_temperature(value, 'C', 'F')
def readOverflowInputFile(basename, radius): parser = f90nml.Parser() overflow_input = parser.read(basename) alpha = overflow_input[u'floinp'][u'alpha'] # DEGREES beta = overflow_input[u'floinp'][u'beta'] # DEGREES fsmach = overflow_input[u'floinp'][u'fsmach'] rey = overflow_input[u'floinp'][u'rey'] # RE/(GRID-UNIT) if u'tinf' in overflow_input[u'floinp']: tinf_tmp = overflow_input[u'floinp'][u'tinf'] # RANKINE else: tinf_tmp = 518.7 if u'refmach' in overflow_input[u'floinp']: refmach = overflow_input[u'floinp'][u'refmach'] else: refmach = fsmach # CALCULATE OMEGA AND VINF BASED ON NON-DIMENSIONAL INPUTS tinf = convert_temperature(tinf_tmp, u'Rankine', u'Kelvin') a = math.sqrt(gamma * gas_constant * tinf) # M/S omega = refmach * a / radius # RAD/S vinf = fsmach * a # M/S vref = refmach * a nu = (1E-03 / rey) * (refmach * a) # CALCULATE THE DENSITY USING SUTHERLAND'S FORMULA FOR VISCOSITY mu0 = 1.716E-05 # lb-s/ft^2 T0 = 273.15 # Rankine mu = mu0 * (tinf / T0)**1.5 * ((T0 + 110.4) / (tinf + 110.4)) rho = mu / nu print u"rho = " + str(rho) return vinf, vref, alpha, beta, omega, a, tinf, rho
def r2k(value): """ converts temperature in R(degrees Rankine) to K(Kelvins) :param value: temperature in R(degrees Rankine) :return: temperature in K(Kelvins) """ return const.convert_temperature(value, 'R', 'K')
def r2f(value): """ converts temperature in R(degrees Rankine) to F(degrees Fahrenheit) :param value: temperature in R(degrees Rankine) :return: temperature in F(degrees Fahrenheit) """ return const.convert_temperature(value, 'R', 'F')
def convert(value, format): collector = list() for to_format in ("celsius", "fahrenheit", "kelvin", "rankine"): collector.append( value if format == to_format else convert_temperature( value, format, to_format), ) return collector
def electro_migration(temperature): """ Generates the scaling value for the Weibull distribution based on Black's equation. :param temperature: float - temperature of component in Celsius :return: float - Scale parameter for the Weibull distribution based on the temperature """ temp = convert_temperature(temperature, 'C', 'K') # temperature in Kelvin return (CONST_A0 * (np.power(CONST_JMJCRIT, (-CONST_N))) * np.exp(ACTIVATION_ENERGY / (BOLTZMAN_CONSTANT * temp))) / CONST_ERRF
def __init__(self, temperature_values, pressure_values): self.temperature = convert_temperature( temperature_values, 'c', 'k') #C2K(np.array(temperature_values)) self.pressure = np.array([pressure_values]) * 1.0E6 self.grain_size = [] self.fugacity = [] self.differential_stress = [] self.strain_rate = [] self.slip_rate = [] self.width = []
def clean_weather(data): data['Temperature'] = convert_temperature(data['Temperature'], 'Kelvin', 'Fahrenheit').round(0) data = data.rename(columns={"# Date": "Date"}) data['Date'] = data['Date'] + ' ' + data['UT time'] data['Date'] = data['Date'].str.replace(r'\b24:00\b', '00:00') data['Date'] = data['Date'].astype('datetime64[ns]') del data['UT time'] return data
def current_sum_at_diode_node(*, V_V, I_A, N_s, T_degC, I_ph_A, I_rs_A, n, R_s_Ohm, G_p_S): """ Computes the sum of the currents at the high-voltage diode node in the implicit 5-parameter local single-diode equivalent-circuit model (SDM-L). Inputs (any broadcast-compatible combination of python/numpy scalars and numpy arrays): Observables at operating conditions (device-level): V_V terminal voltage I_A terminal current Model parameters at operating conditions (device-level): N_s integer number of cells in series in each parallel string T_degC effective diode-junction temperature I_ph_A photocurrent I_rs_A diode reverse-saturation current n diode ideality factor R_s_Ohm series resistance G_p_S parallel conductance Outputs (device-level, at each combination of broadcast inputs, return type is np.float64 when all scalar inputs): dict containing: I_sum_A sum of currents at high-voltage diode node T_K effective diode-junction temperature V_diode_V voltage at high-voltage diode node n_mod_V modified ideality factor """ # Temperature in Kelvin. T_K = convert_temperature(T_degC, 'Celsius', 'Kelvin') # Voltage at diode node. V_diode_V = V_V + I_A * R_s_Ohm # Modified ideality factor. n_mod_V = (N_s * n * k_B_J_per_K * T_K) / q_C # Sum of currents at diode node. np.expm1() returns a np.float64 when arguments are all python/numpy scalars. I_sum_A = I_ph_A - I_rs_A * np.expm1( V_diode_V / n_mod_V) - G_p_S * V_diode_V - I_A result = { 'I_sum_A': I_sum_A, 'T_K': T_K, 'V_diode_V': V_diode_V, 'n_mod_V': n_mod_V } return ensure_numpy_scalars(dictionary=result)
def fugacity_grid_plot(self): self.tC = convert_temperature(self.temperature, 'k', 'c') self.pM = np.array(self.pressure)/1.0E6 fo_v = np.vectorize(self.fugacity_grid_optimizer) result_array = fo_v(self.T, self.P) self.extent = [self.tC.min(), self.tC.max(), self.pM.max(), self.pM.min()] im = plt.imshow(result_array, cmap=plt.cm.jet, aspect="auto",extent=self.extent)#interpolation="none", plt.xlabel('Temperature (C)') plt.ylabel('Pressure (MPa)') plt.colorbar(im, label='Fugacity (MPa)') plt.show()
def fugacity_grid_optimizer(self, temperature, pressure): self.temperature = convert_temperature(np.array(temperature), 'c', 'k') self.pressure = np.array(pressure)*1.0E6 calculate_coefficient_table(self.temperature) def volume_limits(v): return eos(self.temperature, v)- self.pressure volume = opt.brentq(volume_limits, 5, 30) #Volume in cc/mo self.fugacity = PSfug(self.pressure, self.temperature, volume)#Calculate fugacity return self.fugacity
def __init__(self, A, B, C): assert A[:4]==[17, 218, 39, 0], A[:4] assert B[:4]==[17, 218, 39, 0], B[:4] assert C[:4]==[17, 218, 39, 0], C[:4] T = B[6]&7 T <<= 8 T |= B[5] H, M = divmod(T, 60) self.time = time(H, M) self.power = Power(C[5]&1) self.mode = Mode((C[5]>>4)&7) self.temp = int(round(convert_temperature(C[6]/2.0, 'C', 'F'),0)) self.fan = Fan(C[8]>>4)
def solderFatigue( localTime , cell_Temp , reversalTemp): """ Get the Thermomechanical Fatigue of flat plate photovoltaic module solder joints. Damage will be returned as the rate of solder fatigue for one year. Based on: Bosco, N., Silverman, T. and Kurtz, S. (2020). Climate specific thermomechanical fatigue of flat plate photovoltaic module solder joints. [online] Available at: https://www.sciencedirect.com/science/article/pii/S0026271416300609 [Accessed 12 Feb. 2020]. Parameters ------------ localTime : timestamp series Local time of specific site by the hour year-month-day hr:min:sec (Example) 2002-01-01 01:00:00 cell_Temp : float series Photovoltaic module cell temperature(Celsius) for every hour of a year reversalTemp : float Temperature threshold to cross above and below Returns -------- damage : float series Solder fatigue damage for a time interval depending on localTime (kPa) """ #TODO Make this function have more utility. People want to run all the scenarios from the bosco paper. # Currently have everything hard coded for hourly calculation # i.e. 405.6, 1.9, .33, .12 # Get the 1) Average of the Daily Maximum Cell Temperature (C) # 2) Average of the Daily Maximum Temperature change avg(daily max - daily min) # 3) Number of times the temperaqture crosses above or below the reversal Temperature MeanDailyMaxCellTempChange , dailyMaxCellTemp_Average = energyCalcs._avgDailyTempChange( localTime , cell_Temp ) #Needs to be in Kelvin for equation specs dailyMaxCellTemp_Average = convert_temperature( dailyMaxCellTemp_Average , 'Celsius', 'Kelvin') numChangesTempHist = energyCalcs._timesOverReversalNumber( cell_Temp, reversalTemp ) #k = Boltzmann's Constant damage = 405.6 * (MeanDailyMaxCellTempChange **1.9) * \ (numChangesTempHist**.33) * \ np.exp(-(.12/(.00008617333262145*dailyMaxCellTemp_Average))) #Convert pascals to kilopascals damage = damage/1000 return damage
def compute_thermal_noise_densities(self, temp): n0_incident = 10*np.log10((consts.Boltzmann * consts.convert_temperature(float(temp), 'C', 'K')) / 1e-3) print(n0_incident) n0_rf = n0_incident + self.rx_attrib_.nf_rf_path print(n0_rf) n0_rf_gain = n0_rf + 20*np.log10(self.pre_cc_return_path_gain_ * self.post_cc_rf_gain_) print(n0_rf_gain) n0_rf_lin = (10 ** (n0_rf_gain/10)) * 1e-3 print(n0_rf_lin) spectral_density_rf = np.sqrt(n0_rf_lin * self.common_attrib_.impedance_) * 1e9 print(spectral_density_rf) spectral_density_demod = spectral_density_rf * ut.db2lin(self.rx_attrib_.rf_demod_gain_db_) print(spectral_density_demod) spectral_density_filter1_input = np.sqrt((spectral_density_demod ** 2) + (self.rx_attrib_.filter1_psd_ ** 2)) spectral_density_preamp = self.rx_attrib_.preamp_psd_ * ut.db2lin(self.rx_attrib_.preamp_gain_db_) spectral_density_filter2 = np.sqrt((spectral_density_preamp ** 2) + (self.rx_attrib_.filter2_psd_ ** 2)) * \ ut.db2lin(self.rx_attrib_.filter2_gain_db_) spectral_density_driver = np.sqrt((spectral_density_filter2 ** 2) + (self.rx_attrib_.driver_psd_ ** 2)) * \ ut.db2lin(self.rx_attrib_.driver_gain_db_) spectral_density_rx_adc = np.sqrt((spectral_density_driver ** 2) + (self.rx_attrib_.adc_psd_ ** 2)) * \ ut.db2lin(self.rx_attrib_.adc_gain_db_) self.filter1_input_noise_spectral_density = spectral_density_filter1_input self.rx_adc_noise_spectral_density = spectral_density_rx_adc print('n0_incident: ' + str(n0_incident)) print('n0_rf: ' + str(n0_rf)) print('RF Gain: ' + str(20 * np.log10(self.pre_cc_return_path_gain_ * self.post_cc_rf_gain_))) print('n0_rf_gain: ' + str(n0_rf_gain)) print('Spectral Density at RF: ' + str(spectral_density_rf)) print('Spectral Density at Demod: ' + str(spectral_density_demod)) print('Spectral Density at Filter1 Input: ' + str(spectral_density_filter1_input)) print('Spectral Density at Preamp: ' + str(spectral_density_preamp)) print('Spectral Density at Filter2: ' + str(spectral_density_filter2)) print('Spectral Density at Driver: ' + str(spectral_density_driver)) print('Spectral Density at ADC: ' + str(spectral_density_rx_adc))
def convert_temp_to_celsius_rounded(temp_kelvin): temp_celsius = convert_temperature(temp_kelvin, 'K', 'C') return int(temp_celsius.round())
# Nur lokal ausführen. Datei ist nicht in der Makefile import numpy as np import scipy.constants as const from uncertainties import ufloat from uncertainties import unumpy as unp import math t, T1, T2, T5, T6 = np.genfromtxt('../../content/values/messungdyn80s_val.txt', unpack=True) t *= 2 T1 = const.convert_temperature(T1, 'c', 'K') T2 = const.convert_temperature(T2, 'c', 'K') T5 = const.convert_temperature(T5, 'c', 'K') T6 = const.convert_temperature(T6, 'c', 'K') n = len(T1) # Alle Arrays haben dieselbe laenge #berechnen der Minima bzw Maxima i = 10 searchmax = True T1max = [] T1min = [] t1max = [] while (i < (n - 1)): while (i < (n - 1)) and searchmax: if T1[i] >= T1[i - 1] and T1[i] >= T1[i + 1]: searchmax = False T1max.append(T1[i])
print('{} {} {}'.format('nano = ', scipy.constants.nano, '')) ##====================================================================== ## Angle (default is radian, which is dimensionless) ## degree arcmin arcsec ## 1 deg = pi/180 ## 1 arcsec = 1/60 arcmin = 1/60/60 degree ##====================================================================== print("\n") print('{} {} {}'.format('degree = ', scipy.constants.degree, '')) print('{} {} {}'.format('degree/3600 = ', scipy.constants.degree / 3600, '')) print('{} {} {}'.format('arcsec = ', scipy.constants.arcsec, '')) ##====================================================================== ## Speed ## kmh mph mach speed_of_sound knot ##====================================================================== print("\n") print('{} {} {}'.format('degree = ', scipy.constants.degree, '')) print('{} {} {}'.format('degree/3600 = ', scipy.constants.degree / 3600, '')) print('{} {} {}'.format('arcsec = ', scipy.constants.arcsec, '')) ###====================================================================== ### convert_temperature DOES NOT WORK! ###====================================================================== import scipy from scipy.constants import convert_temperature a = convert_temperature(np.array([0, 100.0]), 'C', 'K') print('\n') print(a)
cols = ['Year', ' Month', ' Day', ' Hour', ' Hgt', ' Pres', ' Temp', ' Dewpt', ' RH', ' Spd', ' Dir ','JD'] fall_soundings = pickle.load(open('pickles/Fall_OAK_soundings.p','rb')) summer_soundings = pickle.load(open('pickles/Summer_OAK_soundings.p','rb')) mo = 9 day = 12 yr = 2015 if mo>=6 & mo<=8: sounding_data = summer_soundings.loc[ (summer_soundings[cols[1]]==mo) & (summer_soundings[cols[0]]==yr) & (summer_soundings[cols[2]]==day)] if mo>=9 & mo<=11: sounding_data = fall_soundings.loc[ (fall_soundings[cols[1]]==mo) & (fall_soundings[cols[0]]==yr) & (fall_soundings[cols[2]]==day)] T = convert_temperature(sounding_data[cols[6]].values,'F','C') rh = sounding_data[cols[8]].values sounding_data[cols[7]] = calc_dewpt(T,rh) sounding_data = sounding_data.dropna(subset = (' Temp', ' Dewpt'),how='all').reset_index(drop=True) hours = [np.min(sounding_data[cols[3]]), np.max(sounding_data[cols[3]])] for i in range(len(hours)): one_sounding = sounding_data.loc[sounding_data[cols[3]]==hours[i]] T = convert_temperature(one_sounding[cols[6]].values,'F','C') * units.degC p = one_sounding[cols[5]].values * units.hPa Td = one_sounding[cols[7]].values * units.degC wind_speed = one_sounding[cols[-3]].values * units.knots wind_dir = one_sounding[cols[-2]].values * units.degrees u, v = mpcalc.get_wind_components(wind_speed, wind_dir) plt.rcParams['figure.figsize'] = (9, 9)
def strava_power_model(activity, cyclist_weight, bike_weight=6.8, coef_roll_res=0.0045, pressure=101325.0, temperature=15.0, coef_drag=1, surface_rider=0.32, use_acceleration=False): """Strava model used to estimate power. It corresponds the mathematical formulation which add all forces applied to a cyclist in movement. Read more in the :ref:`User Guide <strava>`. Parameters ---------- activity : DataFrame The activity containing the ride information. cyclist_weight : float The cyclist weight in kg. bike_weight : float, default=6.8 The bike weight in kg. coef_roll_res : float, default=0.0045 Rolling resistance coefficient. pressure : float, default=101325.0 Pressure in Pascal. temperature : float, default=15.0 Temperature in Celsius. coef_drag : float, default=1 The drag coefficient also known as Cx. surface_rider : float, default=0.32 Surface area of the rider facing wind also known as S. The unit is m^2. use_acceleration : bool, default=False Either to add the power required to accelerate. This estimation can become unstable if the acceleration varies for reason which are not linked to power changes (i.e., braking, bends, etc.) Returns ------- power : Series The power estimated. References ---------- .. [1] How Strava Calculates Power https://support.strava.com/hc/en-us/articles/216917107-How-Strava-Calculates-Power Examples -------- >>> from skcycling.datasets import load_fit >>> from skcycling.io import bikeread >>> from skcycling.model import strava_power_model >>> ride = bikeread(load_fit()[0]) >>> power = strava_power_model(ride, cyclist_weight=72) >>> print(power['2014-05-07 12:26:28': ... '2014-05-07 12:26:38']) # Show 10 sec of estimated power 2014-05-07 12:26:28 196.567898 2014-05-07 12:26:29 198.638094 2014-05-07 12:26:30 191.444894 2014-05-07 12:26:31 26.365864 2014-05-07 12:26:32 89.826104 2014-05-07 12:26:33 150.842325 2014-05-07 12:26:34 210.083958 2014-05-07 12:26:35 331.573965 2014-05-07 12:26:36 425.013711 2014-05-07 12:26:37 428.806914 2014-05-07 12:26:38 425.410451 Freq: S, dtype: float64 """ if 'gradient-elevation' not in activity.columns: activity = gradient_elevation(activity) if use_acceleration and 'acceleration' not in activity.columns: activity = acceleration(activity) temperature_kelvin = constants.convert_temperature( temperature, 'Celsius', 'Kelvin') total_weight = cyclist_weight + bike_weight # kg speed = activity['speed'] # m.s^-1 power_roll_res = coef_roll_res * constants.g * total_weight * speed # air density at 0 degree Celsius and a standard atmosphere molar_mass_dry_air = 28.97 / 1000 # kg.mol^-1 standard_atmosphere = constants.physical_constants[ 'standard atmosphere'][0] # Pa zero_celsius_kelvin = constants.convert_temperature( 0, 'Celsius', 'Kelvin') # 273.15 K air_density_ref = ( (standard_atmosphere * molar_mass_dry_air) / (constants.gas_constant * zero_celsius_kelvin)) # kg.m^-3 air_density = air_density_ref * ( (pressure * zero_celsius_kelvin) / (standard_atmosphere * temperature_kelvin)) # kg.m^-3 power_wind = 0.5 * air_density * surface_rider * coef_drag * speed**3 slope = activity['gradient-elevation'] # grade power_gravity = (total_weight * constants.g * np.sin(np.arctan(slope)) * speed) power_total = power_roll_res + power_wind + power_gravity if use_acceleration: acc = activity['acceleration'] # m.s^-1 power_acceleration = total_weight * acc * speed power_total = power_total + power_acceleration return power_total.clip(0)
def test_convert_temperature(): assert_equal(sc.convert_temperature(32, 'f', 'Celsius'), 0) assert_equal(sc.convert_temperature([0, 0], 'celsius', 'Kelvin'), [273.15, 273.15]) assert_equal(sc.convert_temperature([0, 0], 'kelvin', 'c'), [-273.15, -273.15]) assert_equal(sc.convert_temperature([32, 32], 'f', 'k'), [273.15, 273.15]) assert_equal(sc.convert_temperature([273.15, 273.15], 'kelvin', 'F'), [32, 32]) assert_equal(sc.convert_temperature([0, 0], 'C', 'fahrenheit'), [32, 32]) assert_allclose(sc.convert_temperature([0, 0], 'c', 'r'), [491.67, 491.67], rtol=0., atol=1e-13) assert_allclose(sc.convert_temperature([491.67, 491.67], 'Rankine', 'C'), [0., 0.], rtol=0., atol=1e-13) assert_allclose(sc.convert_temperature([491.67, 491.67], 'r', 'F'), [32., 32.], rtol=0., atol=1e-13) assert_allclose(sc.convert_temperature([32, 32], 'fahrenheit', 'R'), [491.67, 491.67], rtol=0., atol=1e-13) assert_allclose(sc.convert_temperature([273.15, 273.15], 'K', 'R'), [491.67, 491.67], rtol=0., atol=1e-13) assert_allclose(sc.convert_temperature([491.67, 0.], 'rankine', 'kelvin'), [273.15, 0.], rtol=0., atol=1e-13)
def Talbot_Sayer(x, a, b, c, x0, **kwargs): # t = 33 * pq.degC, o = 2.5 * pq.mM): """ Talbot & Sayer model for voltage-gated Ca2+ channels I-V relationship. Boltzman squared, multiplied by Goldman-Hogdkin-Katz, see Talbot & Sayer 1996, J. Neurophysiol. 76(3):2120-2124 Positional parameters: ===================== x = 1D numpy array (vector): definition domain (e.g. membrane voltage) a = real: initial value for Boltzman slope factor b = real: initial scale value c = real: initial value for internal Ca2+ concentration (in mM) x0 = real: initial value of onset ("shift") Var-keyword parameters ====================== t = python quantity: temperature in degrees Celsius (degC); default: 33 degC o = python quantity: external Ca2+ concentration in mM; default: 2.5 mM Returns: ======= A realization of the I-V model function in Talbot & Sayer 1996, J. Neurophysiol. 76(3):2120-2124 as a numpy vector NOTE: Do not use directly in curve fitting, as it expects more arguments that the model parameters. The extra arguments are given as keyword arguments. If used directly in fitting, then expected keyword arguments WILL get their default values. """ from scipy import constants # default values t_ = 33 o = 2.5 * pq.mM if len(kwargs) > 0: if "t" in kwargs: t = kwargs["t"] if isinstance(t, pq.Quantity) and t.dimensionality == ( 1 * pq.degC).dimensionality: t_ = t.magnitude elif isinstance(t, numbers.Real): t_ = t else: raise TypeError( "Was expecting 't' (temperature) as a real scalar or a python quantity in degC. got %s instead" % type(t).__name__) if "o" in kwargs: o = kwargs["o"] if isinstance(o, numbers.Real): o *= pq.mM else: if not isinstance(o, pq.Quantity) or o.dimensionality != ( 1 * pq.mM).dimensionality: raise TypeError( "Was expecting 'o' (external Ca2+ concentration) as a real scalar or a python quantity in mM; got %s instead" % type(o).__name__) T = constants.convert_temperature(t_, "Celsius", "Kelvin") * pq.degK F = constants.physical_constants["Faraday constant"][0] * pq.C / pq.mol R = constants.physical_constants["molar gas constant"][0] * pq.J / ( pq.mol * pq.degK) k = F / (R * T) # NOTE: this is in C/J i.e. 1/V, because 1V = 1J/C k = k.rescale(1 / pq.mV) # because x is in mV #print(k) #k = 0.0379 boltzman = 1 / (1 + np.exp(-a * k.magnitude * (x - x0)))**2 ghkexp = np.exp(-2 * x * k.magnitude) ghk = x * b * (c - o.magnitude * ghkexp) / (1 - ghkexp) return boltzman * ghk
import matplotlib.pyplot as plt import numpy as np import scipy.constants as const t, T7, T8 = np.genfromtxt('content/values/messungdyn200s_val.txt', unpack=True) t *= 2 T7 = const.convert_temperature(T7, 'c', 'K') T8 = const.convert_temperature(T8, 'c', 'K') plt.plot(t, T7, 'r-', label="Edelstahl anfang") plt.plot(t, T8, 'b-', label="Edelstahl ende") plt.xlabel('t/s') plt.ylabel('T/K') plt.legend(loc="best") # in matplotlibrc leider (noch) nicht möglich plt.savefig('build/dyn200.pdf') # plt.savefig('build/plot.pdf')