Search is not available for this dataset
text
stringlengths 75
104k
|
---|
def calculate(self, **state):
"""
Calculate the material physical property at the specified temperature
in the units specified by the object's 'property_units' property.
:param T: [K] temperature
:returns: physical property value
"""
super().calculate(**state)
return np.polyval(self._coeffs, state['T']) |
def prepare_to_run(self, clock, period_count):
"""
Prepare the activity for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to be run for.
"""
if self.start_period_ix == -1 and self.start_datetime != datetime.min:
# Set the Start period index
for i in range(0, period_count):
if clock.get_datetime_at_period_ix(i) > self.start_datetime:
self.start_period_ix = i
break
if self.start_period_ix == -1:
self.start_period_ix = 0
if self.period_count == -1 and self.end_datetime != datetime.max:
# Set the Start date
for i in range(0, period_count):
if clock.get_datetime_at_period_ix(i) > self.end_datetime:
self.period_count = i - self.start_period_ix
break
if self.period_count != -1:
self.end_period_ix = self.start_period_ix + self.period_count
else:
self.end_period_ix = self.start_period_ix + period_count |
def create_component(self, name, description=None):
"""
Create a sub component in the business component.
:param name: The new component's name.
:param description: The new component's description.
:returns: The created component.
"""
new_comp = Component(name, self.gl, description=description)
new_comp.set_parent_path(self.path)
self.components.append(new_comp)
return new_comp |
def remove_component(self, name):
"""
Remove a sub component from the component.
:param name: The name of the component to remove.
"""
component_to_remove = None
for c in self.components:
if c.name == name:
component_to_remove = c
if component_to_remove is not None:
self.components.remove(component_to_remove) |
def get_component(self, name):
"""
Retrieve a child component given its name.
:param name: The name of the component.
:returns: The component.
"""
return [c for c in self.components if c.name == name][0] |
def add_activity(self, activity):
"""
Add an activity to the component.
:param activity: The activity.
"""
self.gl.structure.validate_account_names(
activity.get_referenced_accounts())
self.activities.append(activity)
activity.set_parent_path(self.path) |
def get_activity(self, name):
"""
Retrieve an activity given its name.
:param name: The name of the activity.
:returns: The activity.
"""
return [a for a in self.activities if a.name == name][0] |
def prepare_to_run(self, clock, period_count):
"""
Prepare the component for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to be run for.
"""
for c in self.components:
c.prepare_to_run(clock, period_count)
for a in self.activities:
a.prepare_to_run(clock, period_count) |
def run(self, clock, generalLedger):
"""
Execute the component at the current clock cycle.
:param clock: The clock containing the current execution time and
period information.
:param generalLedger: The general ledger into which to create the
transactions.
"""
for c in self.components:
c.run(clock, generalLedger)
for a in self.activities:
a.run(clock, generalLedger) |
def prepare_to_run(self, clock, period_count):
"""
Prepare the entity for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to be run for.
"""
self.period_count = period_count
self._exec_year_end_datetime = clock.get_datetime_at_period_ix(
period_count)
self._prev_year_end_datetime = clock.start_datetime
self._curr_year_end_datetime = clock.start_datetime + relativedelta(
years=1)
# Remove all the transactions
del self.gl.transactions[:]
for c in self.components:
c.prepare_to_run(clock, period_count)
self.negative_income_tax_total = 0 |
def run(self, clock):
"""
Execute the entity at the current clock cycle.
:param clock: The clock containing the current execution time and
period information.
"""
if clock.timestep_ix >= self.period_count:
return
for c in self.components:
c.run(clock, self.gl)
self._perform_year_end_procedure(clock) |
def count_with_multiplier(groups, multiplier):
""" Update group counts with multiplier
This is for handling atom counts on groups like (OH)2
:param groups: iterable of Group/Element
:param multiplier: the number to multiply by
"""
counts = collections.defaultdict(float)
for group in groups:
for element, count in group.count().items():
counts[element] += count*multiplier
return counts |
def amounts(masses):
"""
Calculate the amounts from the specified compound masses.
:param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}
:returns: [kmol] dictionary
"""
return {compound: amount(compound, masses[compound])
for compound in masses.keys()} |
def amount_fractions(masses):
"""
Calculate the mole fractions from the specified compound masses.
:param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}
:returns: [mole fractions] dictionary
"""
n = amounts(masses)
n_total = sum(n.values())
return {compound: n[compound]/n_total for compound in n.keys()} |
def masses(amounts):
"""
Calculate the masses from the specified compound amounts.
:param masses: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}
:returns: [kg] dictionary
"""
return {compound: mass(compound, amounts[compound])
for compound in amounts.keys()} |
def mass_fractions(amounts):
"""
Calculate the mole fractions from the specified compound amounts.
:param amounts: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}
:returns: [mass fractions] dictionary
"""
m = masses(amounts)
m_total = sum(m.values())
return {compound: m[compound]/m_total for compound in m.keys()} |
def convert_compound(mass, source, target, element):
"""
Convert the specified mass of the source compound to the target using
element as basis.
:param mass: Mass of from_compound. [kg]
:param source: Formula and phase of the original compound, e.g.
'Fe2O3[S1]'.
:param target: Formula and phase of the target compound, e.g. 'Fe[S1]'.
:param element: Element to use as basis for the conversion, e.g. 'Fe' or
'O'.
:returns: Mass of target. [kg]
"""
# Perform the conversion.
target_mass_fraction = element_mass_fraction(target, element)
if target_mass_fraction == 0.0:
# If target_formula does not contain element, just return 0.0.
return 0.0
else:
source_mass_fraction = element_mass_fraction(source, element)
return mass * source_mass_fraction / target_mass_fraction |
def element_mass_fraction(compound, element):
"""
Determine the mass fraction of an element in a chemical compound.
:param compound: Formula of the chemical compound, 'FeCr2O4'.
:param element: Element, e.g. 'Cr'.
:returns: Element mass fraction.
"""
coeff = stoichiometry_coefficient(compound, element)
if coeff == 0.0:
return 0.0
formula_mass = molar_mass(compound)
element_mass = molar_mass(element)
return coeff * element_mass / formula_mass |
def elements(compounds):
"""
Determine the set of elements present in a list of chemical compounds.
The list of elements is sorted alphabetically.
:param compounds: List of compound formulas and phases, e.g.
['Fe2O3[S1]', 'Al2O3[S1]'].
:returns: List of elements.
"""
elementlist = [parse_compound(compound).count().keys()
for compound in compounds]
return set().union(*elementlist) |
def molar_mass(compound=''):
"""Determine the molar mass of a chemical compound.
The molar mass is usually the mass of one mole of the substance, but here
it is the mass of 1000 moles, since the mass unit used in auxi is kg.
:param compound: Formula of a chemical compound, e.g. 'Fe2O3'.
:returns: Molar mass. [kg/kmol]
"""
result = 0.0
if compound is None or len(compound) == 0:
return result
compound = compound.strip()
parsed = parse_compound(compound)
return parsed.molar_mass() |
def stoichiometry_coefficient(compound, element):
"""
Determine the stoichiometry coefficient of an element in a chemical
compound.
:param compound: Formula of a chemical compound, e.g. 'SiO2'.
:param element: Element, e.g. 'Si'.
:returns: Stoichiometry coefficient.
"""
stoichiometry = parse_compound(compound.strip()).count()
return stoichiometry[element] |
def stoichiometry_coefficients(compound, elements):
"""
Determine the stoichiometry coefficients of the specified elements in
the specified chemical compound.
:param compound: Formula of a chemical compound, e.g. 'SiO2'.
:param elements: List of elements, e.g. ['Si', 'O', 'C'].
:returns: List of stoichiometry coefficients.
"""
stoichiometry = parse_compound(compound.strip()).count()
return [stoichiometry[element] for element in elements] |
def add_assay(self, name, assay):
"""
Add an assay to the material.
:param name: The name of the new assay.
:param assay: A numpy array containing the size class mass fractions
for the assay. The sequence of the assay's elements must correspond
to the sequence of the material's size classes.
"""
if not type(assay) is numpy.ndarray:
raise Exception("Invalid assay. It must be a numpy array.")
elif not assay.shape == (self.size_class_count,):
raise Exception(
"Invalid assay: It must have the same number of elements "
"as the material has size classes.")
elif name in self.assays.keys():
raise Exception(
"Invalid assay: An assay with that name already exists.")
self.assays[name] = assay |
def create_package(self, assay=None, mass=0.0, normalise=True):
"""
Create a MaterialPackage based on the specified parameters.
:param assay: The name of the assay based on which the package must be
created.
:param mass: [kg] The mass of the package.
:param normalise: Indicates whether the assay must be normalised before
creating the package.
:returns: The created MaterialPackage.
"""
if assay is None:
return MaterialPackage(self, self.create_empty_assay())
if normalise:
assay_total = self.get_assay_total(assay)
else:
assay_total = 1.0
return MaterialPackage(self, mass * self.assays[assay] / assay_total) |
def extract(self, other):
"""
Extract 'other' from self, modifying self and returning the extracted
material as a new package.
:param other: Can be one of the following:
* float: A mass equal to other is extracted from self. Self is
reduced by other and the extracted package is returned as a new
package.
* tuple (size class, mass): The other tuple specifies the mass
of a size class to be extracted. It is extracted from self and
the extracted mass is returned as a new package.
* string: The 'other' string specifies the size class to be
extracted. All of the mass of that size class will be removed
from self and a new package created with it.
:returns: A new material package containing the material that was
extracted from self.
"""
# Extract the specified mass.
if type(other) is float or \
type(other) is numpy.float64 or \
type(other) is numpy.float32:
if other > self.get_mass():
raise Exception(
"Invalid extraction operation. "
"Cannot extract a mass larger than the package's mass.")
fraction_to_subtract = other / self.get_mass()
result = MaterialPackage(
self.material, self.size_class_masses * fraction_to_subtract)
self.size_class_masses = self.size_class_masses * (
1.0 - fraction_to_subtract)
return result
# Extract the specified mass of the specified size class.
elif self._is_size_class_mass_tuple(other):
index = self.material.get_size_class_index(other[0])
if other[1] > self.size_class_masses[index]:
raise Exception(
"Invalid extraction operation. "
"Cannot extract a size class mass larger than what the "
"package contains.")
self.size_class_masses[index] = \
self.size_class_masses[index] - other[1]
resultarray = self.size_class_masses*0.0
resultarray[index] = other[1]
result = MaterialPackage(self.material, resultarray)
return result
# Extract all of the specified size class.
elif type(other) is str:
index = self.material.get_size_class_index(float(other))
result = self * 0.0
result.size_class_masses[index] = self.size_class_masses[index]
self.size_class_masses[index] = 0.0
return result
# If not one of the above, it must be an invalid argument.
else:
raise TypeError("Invalid extraction argument.") |
def add_to(self, other):
"""
Add another psd material package to this material package.
:param other: The other material package.
"""
# Add another package.
if type(other) is MaterialPackage:
# Packages of the same material.
if self.material == other.material:
self.size_class_masses = \
self.size_class_masses + other.size_class_masses
else: # Packages of different materials.
for size_class in other.material.size_classes:
if size_class not in self.material.size_classes:
raise Exception(
"Packages of '" + other.material.name +
"' cannot be added to packages of '" +
self.material.name +
"'. The size class '" + size_class +
"' was not found in '" + self.material.name + "'.")
self.add_to(
(size_class, other.get_size_class_mass(size_class)))
# Add the specified mass of the specified size class.
elif self._is_size_class_mass_tuple(other):
# Added material variables.
size_class = other[0]
compound_index = self.material.get_size_class_index(size_class)
mass = other[1]
# Create the result package.
self.size_class_masses[compound_index] = \
self.size_class_masses[compound_index] + mass
# If not one of the above, it must be an invalid argument.
else:
raise TypeError("Invalid addition argument.") |
def run(self, clock, generalLedger):
"""
Execute the activity at the current clock cycle.
:param clock: The clock containing the current execution time and
period information.
:param generalLedger: The general ledger into which to create the
transactions.
"""
if not self._meet_execution_criteria(clock.timestep_ix):
return
generalLedger.create_transaction(
self.description if self.description is not None else self.name,
description='',
tx_date=clock.get_datetime(),
dt_account=self.dt_account,
cr_account=self.cr_account,
source=self.path,
amount=self.amount) |
def prepare_to_run(self, clock, period_count):
"""
Prepare the activity for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to be run for.
"""
super(BasicLoanActivity, self).prepare_to_run(clock, period_count)
self._months_executed = 0
self._amount_left = self.amount |
def run(self, clock, generalLedger):
"""
Execute the activity at the current clock cycle.
:param clock: The clock containing the current execution time and
period information.
:param generalLedger: The general ledger into which to create the
transactions.
"""
if not self._meet_execution_criteria(clock.timestep_ix):
return
if self.description is None:
tx_name = self.name
else:
tx_name = self.description
if self._months_executed == 0:
generalLedger.create_transaction(
tx_name,
description='Make a loan',
tx_date=clock.get_datetime(),
dt_account=self.bank_account,
cr_account=self.loan_account,
source=self.path,
amount=self.amount)
else:
curr_interest_amount = (self._amount_left *
self.interest_rate) / 12.0
generalLedger.create_transaction(
tx_name,
description='Consider interest',
tx_date=clock.get_datetime(),
dt_account=self.interest_account,
cr_account=self.loan_account,
source=self.path,
amount=curr_interest_amount)
generalLedger.create_transaction(
tx_name,
description='Pay principle',
tx_date=clock.get_datetime(),
dt_account=self.loan_account,
cr_account=self.bank_account,
source=self.path,
amount=self._monthly_payment)
self._amount_left += curr_interest_amount - self._monthly_payment
self._months_executed += self.interval |
def get_datetime_at_period_ix(self, ix):
"""
Get the datetime at a given period.
:param period: The index of the period.
:returns: The datetime.
"""
if self.timestep_period_duration == TimePeriod.millisecond:
return self.start_datetime + timedelta(milliseconds=ix)
elif self.timestep_period_duration == TimePeriod.second:
return self.start_datetime + timedelta(seconds=ix)
elif self.timestep_period_duration == TimePeriod.minute:
return self.start_datetime + timedelta(minutes=ix)
elif self.timestep_period_duration == TimePeriod.hour:
return self.start_datetime + timedelta(hours=ix)
elif self.timestep_period_duration == TimePeriod.day:
return self.start_datetime + relativedelta(days=ix)
elif self.timestep_period_duration == TimePeriod.week:
return self.start_datetime + relativedelta(days=ix*7)
elif self.timestep_period_duration == TimePeriod.month:
return self.start_datetime + relativedelta(months=ix)
elif self.timestep_period_duration == TimePeriod.year:
return self.start_datetime + relativedelta(years=ix) |
def _get_default_data_path_():
"""
Calculate the default path in which thermochemical data is stored.
:returns: Default path.
"""
module_path = os.path.dirname(sys.modules[__name__].__file__)
data_path = os.path.join(module_path, r'data/rao')
data_path = os.path.abspath(data_path)
return data_path |
def _read_compound_from_factsage_file_(file_name):
"""
Build a dictionary containing the factsage thermochemical data of a
compound by reading the data from a file.
:param file_name: Name of file to read the data from.
:returns: Dictionary containing compound data.
"""
with open(file_name) as f:
lines = f.readlines()
compound = {'Formula': lines[0].split(' ')[1]}
# FIXME: replace with logging
print(compound['Formula'])
compound['Phases'] = phs = {}
started = False
phaseold = 'zz'
recordold = '0'
for line in lines:
if started:
if line.startswith('_'): # line indicating end of data
break
line = line.replace(' 298 ', ' 298.15 ')
line = line.replace(' - ', ' ')
while ' ' in line:
line = line.replace(' ', ' ')
line = line.replace(' \n', '')
line = line.replace('\n', '')
strings = line.split(' ')
if len(strings) < 2: # empty line
continue
phase = strings[0]
if phase != phaseold: # new phase detected
phaseold = phase
ph = phs[phase] = {}
ph['Symbol'] = phase
ph['DHref'] = float(strings[2])
ph['Sref'] = float(strings[3])
cprecs = ph['Cp_records'] = {}
record = strings[1]
if record != recordold: # new record detected
recordold = record
Tmax = float(strings[len(strings) - 1])
cprecs[Tmax] = {}
cprecs[Tmax]['Tmin'] = float(strings[len(strings) - 2])
cprecs[Tmax]['Tmax'] = float(strings[len(strings) - 1])
cprecs[Tmax]['Terms'] = []
t = {'Coefficient': float(strings[4]),
'Exponent': float(strings[5])}
cprecs[Tmax]['Terms'].append(t)
if len(strings) == 10:
t = {'Coefficient': float(strings[6]),
'Exponent': float(strings[7])}
cprecs[Tmax]['Terms'].append(t)
else: # old record detected
t = {'Coefficient': float(strings[2]),
'Exponent': float(strings[3])}
cprecs[Tmax]['Terms'].append(t)
if len(strings) == 8:
t = {'Coefficient': float(strings[4]),
'Exponent': float(strings[5])}
cprecs[Tmax]['Terms'].append(t)
else: # old phase detected
ph = phs[phase]
record = strings[1]
if record != recordold: # new record detected
recordold = record
Tmax = float(strings[len(strings) - 1])
cprecs = ph['Cp_records']
cprecs[Tmax] = {}
cprecs[Tmax]['Tmin'] = float(strings[len(strings) - 2])
cprecs[Tmax]['Tmax'] = float(strings[len(strings) - 1])
cprecs[Tmax]['Terms'] = []
t = {'Coefficient': float(strings[2]),
'Exponent': float(strings[3])}
cprecs[Tmax]['Terms'].append(t)
if len(strings) == 8:
t = {'Coefficient': float(strings[4]),
'Exponent': float(strings[5])}
cprecs[Tmax]['Terms'].append(t)
else: # old record detected
t = {'Coefficient': float(strings[2]),
'Exponent': float(strings[3])}
cprecs[Tmax]['Terms'].append(t)
if len(strings) == 8:
t = {'Coefficient': float(strings[4]),
'Exponent': float(strings[5])}
cprecs[Tmax]['Terms'].append(t)
if line.startswith('_'): # line indicating the start of the data
started = True
for name, ph in phs.items():
cprecs = ph['Cp_records']
first = cprecs[min(cprecs.keys())]
first['Tmin'] = 298.15
return compound |
def _split_compound_string_(compound_string):
"""
Split a compound's combined formula and phase into separate strings for
the formula and phase.
:param compound_string: Formula and phase of a chemical compound, e.g.
'SiO2[S1]'.
:returns: Formula of chemical compound.
:returns: Phase of chemical compound.
"""
formula = compound_string.replace(']', '').split('[')[0]
phase = compound_string.replace(']', '').split('[')[1]
return formula, phase |
def _finalise_result_(compound, value, mass):
"""
Convert the value to its final form by unit conversions and multiplying
by mass.
:param compound: Compound object.
:param value: [J/mol] Value to be finalised.
:param mass: [kg] Mass of compound.
:returns: [kWh] Finalised value.
"""
result = value / 3.6E6 # J/x -> kWh/x
result = result / compound.molar_mass # x/mol -> x/kg
result = result * mass # x/kg -> x
return result |
def write_compound_to_auxi_file(directory, compound):
"""
Writes a compound to an auxi file at the specified directory.
:param dir: The directory.
:param compound: The compound.
"""
file_name = "Compound_" + compound.formula + ".json"
with open(os.path.join(directory, file_name), 'w') as f:
f.write(str(compound)) |
def load_data_factsage(path=''):
"""
Load all the thermochemical data factsage files located at a path.
:param path: Path at which the data files are located.
"""
compounds.clear()
if path == '':
path = default_data_path
if not os.path.exists(path):
warnings.warn('The specified data file path does not exist. (%s)' % path)
return
files = glob.glob(os.path.join(path, 'Compound_*.txt'))
for file in files:
compound = Compound(_read_compound_from_factsage_file_(file))
compounds[compound.formula] = compound |
def load_data_auxi(path=''):
"""
Load all the thermochemical data auxi files located at a path.
:param path: Path at which the data files are located.
"""
compounds.clear()
if path == '':
path = default_data_path
if not os.path.exists(path):
warnings.warn('The specified data file path does not exist. (%s)' % path)
return
files = glob.glob(os.path.join(path, 'Compound_*.json'))
for file in files:
compound = Compound.read(file)
compounds[compound.formula] = compound |
def list_compounds():
"""
List all compounds that are currently loaded in the thermo module, and
their phases.
"""
print('Compounds currently loaded:')
for compound in sorted(compounds.keys()):
phases = compounds[compound].get_phase_list()
print('%s: %s' % (compound, ', '.join(phases))) |
def Cp(compound_string, T, mass=1.0):
"""
Calculate the heat capacity of the compound for the specified temperature
and mass.
:param compound_string: Formula and phase of chemical compound, e.g.
'Fe2O3[S1]'.
:param T: [°C] temperature
:param mass: [kg]
:returns: [kWh/K] Heat capacity.
"""
formula, phase = _split_compound_string_(compound_string)
TK = T + 273.15
compound = compounds[formula]
result = compound.Cp(phase, TK)
return _finalise_result_(compound, result, mass) |
def Cp(self, T):
"""
Calculate the heat capacity of the compound phase.
:param T: [K] temperature
:returns: [J/mol/K] Heat capacity.
"""
result = 0.0
for c, e in zip(self._coefficients, self._exponents):
result += c*T**e
return result |
def H(self, T):
"""
Calculate the portion of enthalpy of the compound phase covered by this
Cp record.
:param T: [K] temperature
:returns: [J/mol] Enthalpy.
"""
result = 0.0
if T < self.Tmax:
lT = T
else:
lT = self.Tmax
Tref = self.Tmin
for c, e in zip(self._coefficients, self._exponents):
# Analytically integrate Cp(T).
if e == -1.0:
result += c * math.log(lT/Tref)
else:
result += c * (lT**(e+1.0) - Tref**(e+1.0)) / (e+1.0)
return result |
def S(self, T):
"""
Calculate the portion of entropy of the compound phase covered by this
Cp record.
:param T: [K] temperature
:returns: Entropy. [J/mol/K]
"""
result = 0.0
if T < self.Tmax:
lT = T
else:
lT = self.Tmax
Tref = self.Tmin
for c, e in zip(self._coefficients, self._exponents):
# Create a modified exponent to analytically integrate Cp(T)/T
# instead of Cp(T).
e_modified = e - 1.0
if e_modified == -1.0:
result += c * math.log(lT/Tref)
else:
e_mod = e_modified + 1.0
result += c * (lT**e_mod - Tref**e_mod) / e_mod
return result |
def Cp(self, T):
"""
Calculate the heat capacity of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol/K] The heat capacity of the compound phase.
"""
# TODO: Fix str/float conversion
for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):
if T < Tmax:
return self._Cp_records[str(Tmax)].Cp(T) + self.Cp_mag(T)
Tmax = max([float(TT) for TT in self._Cp_records.keys()])
return self._Cp_records[str(Tmax)].Cp(Tmax) + self.Cp_mag(T) |
def Cp_mag(self, T):
"""
Calculate the phase's magnetic contribution to heat capacity at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol/K] The magnetic heat capacity of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N
"""
tau = T / self.Tc_mag
if tau <= 1.0:
c = (self._B_mag*(2*tau**3 + 2*tau**9/3 + 2*tau**15/5))/self._D_mag
else:
c = (2*tau**-5 + 2*tau**-15/3 + 2*tau**-25/5)/self._D_mag
result = R*math.log(self.beta0_mag + 1)*c
return result |
def H(self, T):
"""
Calculate the enthalpy of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol] The enthalpy of the compound phase.
"""
result = self.DHref
for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):
result += self._Cp_records[str(Tmax)].H(T)
if T <= Tmax:
return result + self.H_mag(T)
# Extrapolate beyond the upper limit by using a constant heat capacity.
Tmax = max([float(TT) for TT in self._Cp_records.keys()])
result += self.Cp(Tmax)*(T - Tmax)
return result + self.H_mag(T) |
def H_mag(self, T):
"""
Calculate the phase's magnetic contribution to enthalpy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol] The magnetic enthalpy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N
"""
tau = T / self.Tc_mag
if tau <= 1.0:
h = (-self._A_mag/tau +
self._B_mag*(tau**3/2 + tau**9/15 + tau**15/40))/self._D_mag
else:
h = -(tau**-5/2 + tau**-15/21 + tau**-25/60)/self._D_mag
return R*T*math.log(self.beta0_mag + 1)*h |
def S(self, T):
"""
Calculate the entropy of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol/K] The entropy of the compound phase.
"""
result = self.Sref
for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):
result += self._Cp_records[str(Tmax)].S(T)
if T <= Tmax:
return result + self.S_mag(T)
# Extrapolate beyond the upper limit by using a constant heat capacity.
Tmax = max([float(TT) for TT in self._Cp_records.keys()])
result += self.Cp(Tmax)*math.log(T / Tmax)
return result + self.S_mag(T) |
def S_mag(self, T):
"""
Calculate the phase's magnetic contribution to entropy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol/K] The magnetic entropy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N
"""
tau = T / self.Tc_mag
if tau <= 1.0:
s = 1 - (self._B_mag*(2*tau**3/3 + 2*tau**9/27 + 2*tau**15/75)) / \
self._D_mag
else:
s = (2*tau**-5/5 + 2*tau**-15/45 + 2*tau**-25/125)/self._D_mag
return -R*math.log(self.beta0_mag + 1)*s |
def G(self, T):
"""Calculate the heat capacity of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol] The Gibbs free energy of the compound phase.
"""
h = self.DHref
s = self.Sref
for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]):
h = h + self._Cp_records[str(Tmax)].H(T)
s = s + self._Cp_records[str(Tmax)].S(T)
if T <= Tmax:
return h - T * s + self.G_mag(T)
# Extrapolate beyond the upper limit by using a constant heat capacity.
Tmax = max([float(TT) for TT in self._Cp_records.keys()])
h = h + self.Cp(Tmax)*(T - Tmax)
s = s + self.Cp(Tmax)*math.log(T / Tmax)
return h - T * s + self.G_mag(T) |
def G_mag(self, T):
"""
Calculate the phase's magnetic contribution to Gibbs energy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol] The magnetic Gibbs energy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N
"""
tau = T / self.Tc_mag
if tau <= 1.0:
g = 1 - (self._A_mag/tau +
self._B_mag*(tau**3/6 + tau**9/135 + tau**15/600)) /\
self._D_mag
else:
g = -(tau**-5/10 + tau**-15/315 + tau**-25/1500)/self._D_mag
return R*T*math.log(self.beta0_mag + 1)*g |
def Cp(self, phase, T):
"""
Calculate the heat capacity of a phase of the compound at a specified
temperature.
:param phase: A phase of the compound, e.g. 'S', 'L', 'G'.
:param T: [K] temperature
:returns: [J/mol/K] Heat capacity.
"""
if phase not in self._phases:
raise Exception("The phase '%s' was not found in compound '%s'." %
(phase, self.formula))
return self._phases[phase].Cp(T) |
def H(self, phase, T):
"""
Calculate the enthalpy of a phase of the compound at a specified
temperature.
:param phase: A phase of the compound, e.g. 'S', 'L', 'G'.
:param T: [K] temperature
:returns: [J/mol] Enthalpy.
"""
try:
return self._phases[phase].H(T)
except KeyError:
raise Exception("The phase '{}' was not found in compound '{}'."
.format(phase, self.formula)) |
def _create_polynomial_model(
name: str,
symbol: str,
degree: int,
ds: DataSet,
dss: dict):
"""
Create a polynomial model to describe the specified property based on the
specified data set, and save it to a .json file.
:param name: material name.
:param symbol: property symbol.
:param degree: polynomial degree.
:param ds: the source data set.
:param dss: dictionary of all datasets.
"""
ds_name = ds.name.split(".")[0].lower()
file_name = f"{name.lower()}-{symbol.lower()}-polynomialmodelt-{ds_name}"
newmod = PolynomialModelT.create(ds, symbol, degree)
newmod.plot(dss, _path(f"data/{file_name}.pdf"), False)
newmod.write(_path(f"data/{file_name}.json")) |
def _create_air():
"""
Create a dictionary of datasets and a material object for air.
:return: (Material, {str, DataSet})
"""
name = "Air"
namel = name.lower()
mm = 28.9645 # g/mol
ds_dict = _create_ds_dict([
"dataset-air-lienhard2015",
"dataset-air-lienhard2018"])
active_ds = "dataset-air-lienhard2018"
# create polynomial models to describe material properties
# comment it out after model creation is complete, so that it does not
# run every time during use.
# _create_polynomial_model(name, "Cp", 13, ds_dict[active_ds], ds_dict)
# _create_polynomial_model(name, "k", 8, ds_dict[active_ds], ds_dict)
# _create_polynomial_model(name, "mu", 8, ds_dict[active_ds], ds_dict)
# _create_polynomial_model(name, "rho", 14, ds_dict[active_ds], ds_dict)
# IgRhoT(mm, 101325.0).plot(ds_dict, _path(f"data/{namel}-rho-igrhot.pdf"))
model_dict = {
"rho": IgRhoT(mm, 101325.0),
"beta": IgBetaT()}
model_type = "polynomialmodelt"
for property in ["Cp", "mu", "k"]:
name = f"data/{namel}-{property.lower()}-{model_type}-{active_ds}.json"
model_dict[property] = PolynomialModelT.read(_path(name))
material = Material(name, StateOfMatter.gas, model_dict)
return material, ds_dict |
def calculate(self, **state):
"""
Calculate dynamic viscosity at the specified temperature and
composition:
:param T: [K] temperature
:param x: [mole fraction] composition dictionary , e.g.
{'CO': 0.25, 'CO2': 0.25, 'N2': 0.25, 'O2': 0.25}
:returns: [Pa.s] dynamic viscosity
The **state parameter contains the keyword argument(s) specified above
that are used to describe the state of the material.
"""
def phi(i, j, mu_i, mu_j):
M_i = M(i)
M_j = M(j)
result = (1.0 + (mu_i / mu_j)**0.5 * (M_j / M_i)**0.25)**2.0
result /= (4.0 / sqrt(2.0))
result /= (1.0 + M_i / M_j)**0.5
return result
T = state['T']
x = state['x']
# normalise mole fractions
x_total = sum([
x for compound, x in x.items()
if compound in materials])
x = {
compound: x[compound]/x_total
for compound in x.keys()
if compound in materials}
result = 0.0 # Pa.s
mu = {i: materials[i].mu(T=T) for i in x.keys()}
for i in x.keys():
sum_i = 0.0
for j in x.keys():
if j == i: continue
sum_i += x[j] * phi(i, j, mu[i], mu[j])
result += x[i] * mu[i] / (x[i] + sum_i)
return result |
def calculate(self, **state):
"""
Calculate dynamic viscosity at the specified temperature and
composition:
:param T: [K] temperature
:param x: [mole fraction] composition dictionary , e.g.
{'CO': 0.25, 'CO2': 0.25, 'N2': 0.25, 'O2': 0.25}
:returns: [Pa.s] dynamic viscosity
The **state parameter contains the keyword argument(s) specified above
that are used to describe the state of the material.
"""
T = state['T']
x = state['x']
# normalise mole fractions
x_total = sum([
x for compound, x in x.items()
if compound in materials])
x = {
compound: x[compound]/x_total
for compound in x.keys()
if compound in materials}
mu = {i: materials[i].mu(T=T) for i in x.keys()}
result = sum([mu[i] * x[i] * sqrt(M(i)) for i in x.keys()])
result /= sum([x[i] * sqrt(M(i)) for i in x.keys()])
return result |
def render(self, format=ReportFormat.printout):
"""
Render the report in the specified format
:param format: The format. The default format is to print
the report to the console.
:returns: If the format was set to 'string' then a string
representation of the report is returned.
"""
table = self._generate_table_()
if format == ReportFormat.printout:
print(tabulate(table, headers="firstrow", tablefmt="simple"))
elif format == ReportFormat.latex:
self._render_latex_(table)
elif format == ReportFormat.txt:
self._render_txt_(table)
elif format == ReportFormat.csv:
self._render_csv_(table)
elif format == ReportFormat.string:
return str(tabulate(table, headers="firstrow", tablefmt="simple"))
elif format == ReportFormat.matplotlib:
self._render_matplotlib_()
elif format == ReportFormat.png:
if self.output_path is None:
self._render_matplotlib_()
else:
self._render_matplotlib_(True) |
def rgb_to_hex(rgb):
"""
Convert an RGB color representation to a HEX color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: HEX representation of the input RGB value.
:rtype: str
"""
r, g, b = rgb
return "#{0}{1}{2}".format(hex(int(r))[2:].zfill(2), hex(int(g))[2:].zfill(2), hex(int(b))[2:].zfill(2)) |
def rgb_to_yiq(rgb):
"""
Convert an RGB color representation to a YIQ color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: YIQ representation of the input RGB value.
:rtype: tuple
"""
r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255
y = (0.299 * r) + (0.587 * g) + (0.114 * b)
i = (0.596 * r) - (0.275 * g) - (0.321 * b)
q = (0.212 * r) - (0.528 * g) + (0.311 * b)
return round(y, 3), round(i, 3), round(q, 3) |
def rgb_to_hsv(rgb):
"""
Convert an RGB color representation to an HSV color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: HSV representation of the input RGB value.
:rtype: tuple
"""
r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255
_min = min(r, g, b)
_max = max(r, g, b)
v = _max
delta = _max - _min
if _max == 0:
return 0, 0, v
s = delta / _max
if delta == 0:
delta = 1
if r == _max:
h = 60 * (((g - b) / delta) % 6)
elif g == _max:
h = 60 * (((b - r) / delta) + 2)
else:
h = 60 * (((r - g) / delta) + 4)
return round(h, 3), round(s, 3), round(v, 3) |
def hex_to_rgb(_hex):
"""
Convert a HEX color representation to an RGB color representation.
hex :: hex -> [000000, FFFFFF]
:param _hex: The 3- or 6-char hexadecimal string representing the color value.
:return: RGB representation of the input HEX value.
:rtype: tuple
"""
_hex = _hex.strip('#')
n = len(_hex) // 3
if len(_hex) == 3:
r = int(_hex[:n] * 2, 16)
g = int(_hex[n:2 * n] * 2, 16)
b = int(_hex[2 * n:3 * n] * 2, 16)
else:
r = int(_hex[:n], 16)
g = int(_hex[n:2 * n], 16)
b = int(_hex[2 * n:3 * n], 16)
return r, g, b |
def yiq_to_rgb(yiq):
"""
Convert a YIQ color representation to an RGB color representation.
(y, i, q) :: y -> [0, 1]
i -> [-0.5957, 0.5957]
q -> [-0.5226, 0.5226]
:param yiq: A tuple of three numeric values corresponding to the luma and chrominance.
:return: RGB representation of the input YIQ value.
:rtype: tuple
"""
y, i, q = yiq
r = y + (0.956 * i) + (0.621 * q)
g = y - (0.272 * i) - (0.647 * q)
b = y - (1.108 * i) + (1.705 * q)
r = 1 if r > 1 else max(0, r)
g = 1 if g > 1 else max(0, g)
b = 1 if b > 1 else max(0, b)
return round(r * 255, 3), round(g * 255, 3), round(b * 255, 3) |
def hsv_to_rgb(hsv):
"""
Convert an HSV color representation to an RGB color representation.
(h, s, v) :: h -> [0, 360)
s -> [0, 1]
v -> [0, 1]
:param hsv: A tuple of three numeric values corresponding to the hue, saturation, and value.
:return: RGB representation of the input HSV value.
:rtype: tuple
"""
h, s, v = hsv
c = v * s
h /= 60
x = c * (1 - abs((h % 2) - 1))
m = v - c
if h < 1:
res = (c, x, 0)
elif h < 2:
res = (x, c, 0)
elif h < 3:
res = (0, c, x)
elif h < 4:
res = (0, x, c)
elif h < 5:
res = (x, 0, c)
elif h < 6:
res = (c, 0, x)
else:
raise ColorException("Unable to convert from HSV to RGB")
r, g, b = res
return round((r + m)*255, 3), round((g + m)*255, 3), round((b + m)*255, 3) |
def offset_random_rgb(seed, amount=1):
"""
Given a seed color, generate a specified number of random colors (1 color by default) determined by a randomized
offset from the seed.
:param seed:
:param amount:
:return:
"""
r, g, b = seed
results = []
for _ in range(amount):
base_val = ((r + g + b) / 3) + 1 # Add one to eliminate case where the base value would otherwise be 0
new_val = base_val + (random.random() * rgb_max_val / 5) # Randomly offset with an arbitrary multiplier
ratio = new_val / base_val
results.append((min(int(r*ratio), rgb_max_val), min(int(g*ratio), rgb_max_val), min(int(b*ratio), rgb_max_val)))
return results[0] if len(results) > 1 else results |
def color_run(start_color, end_color, step_count, inclusive=True, to_color=True):
"""
Given a start color, end color, and a number of steps, returns a list of colors which represent a 'scale' between
the start and end color.
:param start_color: The color starting the run
:param end_color: The color ending the run
:param step_count: The number of colors to have between the start and end color
:param inclusive: Flag determining whether to include start and end values in run (default True)
:param to_color: Flag indicating return values should be Color objects (default True)
:return: List of colors between the start and end color
:rtype: list
"""
if isinstance(start_color, Color):
start_color = start_color.rgb
if isinstance(end_color, Color):
end_color = end_color.rgb
step = tuple((end_color[i] - start_color[i])/step_count for i in range(3))
add = lambda x, y: tuple(sum(z) for z in zip(x, y))
mult = lambda x, y: tuple(y * z for z in x)
run = [add(start_color, mult(step, i)) for i in range(1, step_count)]
if inclusive:
run = [start_color] + run + [end_color]
return run if not to_color else [Color(c) for c in run] |
def text_color(background, dark_color=rgb_min, light_color=rgb_max):
"""
Given a background color in the form of an RGB 3-tuple, returns the color the text should be (defaulting to white
and black) for best readability. The light (white) and dark (black) defaults can be overridden to return preferred
values.
:param background:
:param dark_color:
:param light_color:
:return:
"""
max_y = rgb_to_yiq(rgb_max)[0]
return light_color if rgb_to_yiq(background)[0] <= max_y / 2 else dark_color |
def minify_hex(_hex):
"""
Given a HEX value, tries to reduce it from a 6 character hex (e.g. #ffffff) to a 3 character hex (e.g. #fff).
If the HEX value is unable to be minified, returns the 6 character HEX representation.
:param _hex:
:return:
"""
size = len(_hex.strip('#'))
if size == 3:
return _hex
elif size == 6:
if _hex[1] == _hex[2] and _hex[3] == _hex[4] and _hex[5] == _hex[6]:
return _hex[0::2]
else:
return _hex
else:
raise ColorException('Unexpected HEX size when minifying: {}'.format(size)) |
def get(self, key, default=None):
""" Get key value, return default if key doesn't exist """
if self.in_memory:
return self._memory_db.get(key, default)
else:
db = self._read_file()
return db.get(key, default) |
def set(self, key, value):
""" Set key value """
if self.in_memory:
self._memory_db[key] = value
else:
db = self._read_file()
db[key] = value
with open(self.db_path, 'w') as f:
f.write(json.dumps(db, ensure_ascii=False, indent=2)) |
def _read_file(self):
"""
read the db file content
:rtype: dict
"""
if not os.path.exists(self.db_path):
return {}
with open(self.db_path, 'r') as f:
content = f.read()
return json.loads(content) |
def attrs_sqlalchemy(maybe_cls=None):
"""
A class decorator that adds ``__repr__``, ``__eq__``, ``__cmp__``, and
``__hash__`` methods according to the fields defined on the SQLAlchemy
model class.
"""
def wrap(cls):
warnings.warn(UserWarning('attrs_sqlalchemy is deprecated'))
these = {
name: attr.ib()
# `__mapper__.columns` is a dictionary mapping field names on the
# model class to table columns. SQLAlchemy provides many ways to
# access the fields/columns, but this works at the time the class
# decorator is called:
#
# - We can't use `cls.__table__.columns` because that directly maps
# the column names rather than the field names on the model. For
# example, given `_my_field = Column('field', ...)`,
# `__table__.columns` will contain 'field' rather than '_my_field'.
#
# - We can't use `cls.__dict__`, where values are
# `InstrumentedAttribute`s, because that includes relationships,
# synonyms, and other features.
#
# - We can't use `cls.__mapper__.column_attrs`
# (or `sqlalchemy.inspect`) because they will attempt to
# initialize mappers for all of the classes in the registry,
# which won't be ready yet.
for name in inspect(cls).columns.keys()
}
return attr.s(cls, these=these, init=False)
# `maybe_cls` depends on the usage of the decorator. It's a class if it's
# used as `@attrs_sqlalchemy` but `None` if it's used as
# `@attrs_sqlalchemy()`
# ref: https://github.com/hynek/attrs/blob/15.2.0/src/attr/_make.py#L195
if maybe_cls is None:
return wrap
else:
return wrap(maybe_cls) |
def paginate_link_tag(item):
"""
Create an A-HREF tag that points to another page usable in paginate.
"""
a_tag = Page.default_link_tag(item)
if item['type'] == 'current_page':
return make_html_tag('li', a_tag, **{'class': 'blue white-text'})
return make_html_tag('li', a_tag) |
def set_state(_id, body):
"""
Set a devices state.
"""
url = DEVICE_URL % _id
if "mode" in body:
url = MODES_URL % _id
arequest = requests.put(url, headers=HEADERS, data=json.dumps(body))
status_code = str(arequest.status_code)
if status_code != '202':
_LOGGER.error("State not accepted. " + status_code)
return False |
def get_modes(_id):
"""
Pull a water heater's modes from the API.
"""
url = MODES_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.json() |
def get_usage(_id):
"""
Pull a water heater's usage report from the API.
"""
url = USAGE_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
try:
return arequest.json()
except ValueError:
_LOGGER.info("Failed to get usage. Not supported by unit?")
return None |
def get_device(_id):
"""
Pull a device from the API.
"""
url = DEVICE_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.json() |
def get_locations():
"""
Pull the accounts locations.
"""
arequest = requests.get(LOCATIONS_URL, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.json() |
def get_vacations():
"""
Pull the accounts vacations.
"""
arequest = requests.get(VACATIONS_URL, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.json() |
def create_vacation(body):
"""
Create a vacation.
"""
arequest = requests.post(VACATIONS_URL, headers=HEADERS, data=json.dumps(body))
status_code = str(arequest.status_code)
if status_code != '200':
_LOGGER.error("Failed to create vacation. " + status_code)
_LOGGER.error(arequest.json())
return False
return arequest.json() |
def delete_vacation(_id):
"""
Delete a vacation by ID.
"""
arequest = requests.delete(VACATIONS_URL + "/" + _id, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code != '202':
_LOGGER.error("Failed to delete vacation. " + status_code)
return False
return True |
def _authenticate(self):
"""
Authenticate with the API and return an authentication token.
"""
auth_url = BASE_URL + "/auth/token"
payload = {'username': self.email, 'password': self.password, 'grant_type': 'password'}
arequest = requests.post(auth_url, data=payload, headers=BASIC_HEADERS)
status = arequest.status_code
if status != 200:
_LOGGER.error("Authentication request failed, please check credintials. " + str(status))
return False
response = arequest.json()
_LOGGER.debug(str(response))
self.token = response.get("access_token")
self.refresh_token = response.get("refresh_token")
_auth = HEADERS.get("Authorization")
_auth = _auth % self.token
HEADERS["Authorization"] = _auth
_LOGGER.info("Authentication was successful, token set.")
return True |
def get_water_heaters(self):
"""
Return a list of water heater devices.
Parses the response from the locations endpoint in to a pyeconet.WaterHeater.
"""
water_heaters = []
for location in self.locations:
_location_id = location.get("id")
for device in location.get("equipment"):
if device.get("type") == "Water Heater":
water_heater_modes = self.api_interface.get_modes(device.get("id"))
water_heater_usage = self.api_interface.get_usage(device.get("id"))
water_heater = self.api_interface.get_device(device.get("id"))
vacations = self.api_interface.get_vacations()
device_vacations = []
for vacation in vacations:
for equipment in vacation.get("participatingEquipment"):
if equipment.get("id") == water_heater.get("id"):
device_vacations.append(EcoNetVacation(vacation, self.api_interface))
water_heaters.append(EcoNetWaterHeater(water_heater, water_heater_modes, water_heater_usage,
_location_id,
device_vacations,
self.api_interface))
return water_heaters |
def get_products(self, latitude, longitude):
"""
Get a list of all Uber products based on latitude and longitude coordinates.
:param latitude: Latitude for which product list is required.
:param longitude: Longitude for which product list is required.
:return: JSON
"""
endpoint = 'products'
query_parameters = {
'latitude': latitude,
'longitude': longitude
}
return self.get_json(endpoint, 'GET', query_parameters, None, None) |
def get_price_estimate(self, start_latitude, start_longitude, end_latitude, end_longitude):
"""
Returns the fare estimate based on two sets of coordinates.
:param start_latitude: Starting latitude or latitude of pickup address.
:param start_longitude: Starting longitude or longitude of pickup address.
:param end_latitude: Ending latitude or latitude of destination address.
:param end_longitude: Ending longitude or longitude of destination address.
:return: JSON
"""
endpoint = 'estimates/price'
query_parameters = {
'start_latitude': start_latitude,
'start_longitude': start_longitude,
'end_latitude': end_latitude,
'end_longitude': end_longitude
}
return self.get_json(endpoint, 'GET', query_parameters, None, None) |
def get_time_estimate(self, start_latitude, start_longitude, customer_uuid=None, product_id=None):
"""
Get the ETA for Uber products.
:param start_latitude: Starting latitude.
:param start_longitude: Starting longitude.
:param customer_uuid: (Optional) Customer unique ID.
:param product_id: (Optional) If ETA is needed only for a specific product type.
:return: JSON
"""
endpoint = 'estimates/time'
query_parameters = {
'start_latitude': start_latitude,
'start_longitude': start_longitude
}
if customer_uuid is not None:
query_parameters['customer_uuid'] = customer_uuid
elif product_id is not None:
query_parameters['product_id'] = product_id
elif customer_uuid is not None and product_id is not None:
query_parameters['customer_uuid'] = customer_uuid
query_parameters['product_id'] = product_id
return self.get_json(endpoint, 'GET', query_parameters, None, None) |
def models_preparing(app):
""" Wrap all sqlalchemy model in settings.
"""
def wrapper(resource, parent):
if isinstance(resource, DeclarativeMeta):
resource = ListResource(resource)
if not getattr(resource, '__parent__', None):
resource.__parent__ = parent
return resource
resources_preparing_factory(app, wrapper) |
def check_status(content, response):
"""
Check the response that is returned for known exceptions and errors.
:param response: Response that is returned from the call.
:raise:
MalformedRequestException if `response.status` is 400
UnauthorisedException if `response.status` is 401
NotFoundException if `response.status` is 404
UnacceptableContentException if `response.status` is 406
InvalidRequestException if `response.status` is 422
RateLimitException if `response.status` is 429
ServerException if `response.status` > 500
"""
if response.status == 400:
raise MalformedRequestException(content, response)
if response.status == 401:
raise UnauthorisedException(content, response)
if response.status == 404:
raise NotFoundException(content, response)
if response.status == 406:
raise UnacceptableContentException(content, response)
if response.status == 422:
raise InvalidRequestException(content, response)
if response.status == 429:
raise RateLimitException(content, response)
if response.status >= 500:
raise ServerException(content, response) |
def build_request(self, path, query_parameters):
"""
Build the HTTP request by adding query parameters to the path.
:param path: API endpoint/path to be used.
:param query_parameters: Query parameters to be added to the request.
:return: string
"""
url = 'https://api.uber.com/v1' + self.sanitise_path(path)
url += '?' + urlencode(query_parameters)
return url |
def get_json(self, uri_path, http_method='GET', query_parameters=None, body=None, headers=None):
"""
Fetches the JSON returned, after making the call and checking for errors.
:param uri_path: Endpoint to be used to make a request.
:param http_method: HTTP method to be used.
:param query_parameters: Parameters to be added to the request.
:param body: Optional body, if required.
:param headers: Optional headers, if required.
:return: JSON
"""
query_parameters = query_parameters or {}
headers = headers or {}
# Add credentials to the request
query_parameters = self.add_credentials(query_parameters)
# Build the request uri with parameters
uri = self.build_request(uri_path, query_parameters)
if http_method in ('POST', 'PUT', 'DELETE') and 'Content-Type' not in headers:
headers['Content-Type'] = 'application/json'
headers['Accept'] = 'application/json'
response, content = self.client.request(
uri=uri,
method=http_method,
body=body,
headers=headers
)
# Check for known errors that could be returned
self.check_status(content, response)
return json.loads(content.decode('utf-8')) |
def _translateCommands(commands):
"""Generate the binary strings for a comma seperated list of commands."""
for command in commands.split(','):
# each command results in 2 bytes of binary data
result = [0, 0]
device, command = command.strip().upper().split(None, 1)
# translate the house code
result[0] = houseCodes[device[0]]
# translate the device number if there is one
if len(device) > 1:
deviceNumber = deviceNumbers[device[1:]]
result[0] |= deviceNumber[0]
result[1] = deviceNumber[1]
# translate the command
result[1] |= commandCodes[command]
# convert 2 bytes to bit strings and yield them
yield ' '.join(map(_strBinary, result)) |
def _strBinary(n):
"""Conert an integer to binary (i.e., a string of 1s and 0s)."""
results = []
for i in range(8):
n, r = divmod(n, 2)
results.append('01'[r])
results.reverse()
return ''.join(results) |
def _sendBinaryData(port, data):
"""Send a string of binary data to the FireCracker with proper timing.
See the diagram in the spec referenced above for timing information.
The module level variables leadInOutDelay and bitDelay represent how
long each type of delay should be in seconds. They may require tweaking
on some setups.
"""
_reset(port)
time.sleep(leadInOutDelay)
for digit in data:
_sendBit(port, digit)
time.sleep(leadInOutDelay) |
def _sendBit(port, bit):
"""Send an individual bit to the FireCracker module usr RTS/DTR."""
if bit == '0':
_setRTSDTR(port, 0, 1)
elif bit == '1':
_setRTSDTR(port, 1, 0)
else:
return
time.sleep(bitDelay)
_setRTSDTR(port, 1, 1)
time.sleep(bitDelay) |
def _setRTSDTR(port, RTS, DTR):
"""Set RTS and DTR to the requested state."""
port.setRTS(RTS)
port.setDTR(DTR) |
def sendCommands(comPort, commands):
"""Send X10 commands using the FireCracker on comPort
comPort should be the name of a serial port on the host platform. On
Windows, for example, 'com1'.
commands should be a string consisting of X10 commands separated by
commas. For example. 'A1 On, A Dim, A Dim, A Dim, A Lamps Off'. The
letter is a house code (A-P) and the number is the device number (1-16).
Possible commands for a house code / device number combination are
'On' and 'Off'. The commands 'Bright' and 'Dim' should be used with a
house code alone after sending an On command to a specific device. The
'All On', 'All Off', 'Lamps On', and 'Lamps Off' commands should also
be used with a house code alone.
# Turn on module A1
>>> sendCommands('com1', 'A1 On')
# Turn all modules with house code A off
>>> sendCommands('com1', 'A All Off')
# Turn all lamp modules with house code B on
>>> sendCommands('com1', 'B Lamps On')
# Turn on module A1 and dim it 3 steps, then brighten it 1 step
>>> sendCommands('com1', 'A1 On, A Dim, A Dim, A Dim, A Bright')
"""
mutex.acquire()
try:
try:
port = serial.Serial(port=comPort)
header = '11010101 10101010'
footer = '10101101'
for command in _translateCommands(commands):
_sendBinaryData(port, header + command + footer)
except serial.SerialException:
print('Unable to open serial port %s' % comPort)
print('')
raise
finally:
mutex.release() |
def main(argv=None):
"""Send X10 commands when module is used from the command line.
This uses syntax similar to sendCommands, for example:
x10.py com2 A1 On, A2 Off, B All Off
"""
if len(argv):
# join all the arguments together by spaces so that quotes
# aren't required on the command line.
commands = ' '.join(argv)
# the comPort is everything leading up to the first space
comPort, commands = commands.split(None, 1)
sendCommands(comPort, commands)
return 0 |
def normalize_housecode(house_code):
"""Returns a normalized house code, i.e. upper case.
Raises exception X10InvalidHouseCode if house code appears to be invalid
"""
if house_code is None:
raise X10InvalidHouseCode('%r is not a valid house code' % house_code)
if not isinstance(house_code, basestring):
raise X10InvalidHouseCode('%r is not a valid house code' % house_code)
if len(house_code) != 1:
raise X10InvalidHouseCode('%r is not a valid house code' % house_code)
house_code = house_code.upper()
if not ('A' <= house_code <= 'P'):
raise X10InvalidHouseCode('%r is not a valid house code' % house_code)
return house_code |
def normalize_unitnumber(unit_number):
"""Returns a normalized unit number, i.e. integers
Raises exception X10InvalidUnitNumber if unit number appears to be invalid
"""
try:
try:
unit_number = int(unit_number)
except ValueError:
raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)
except TypeError:
raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)
if not (1 <= unit_number <= 16):
raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)
return unit_number |
def x10_command(self, house_code, unit_number, state):
"""Send X10 command to ??? unit.
@param house_code (A-P) - example='A'
@param unit_number (1-16)- example=1 (or None to impact entire house code)
@param state - Mochad command/state, See
https://sourceforge.net/p/mochad/code/ci/master/tree/README
examples=OFF, 'OFF', 'ON', ALL_OFF, 'all_units_off', 'xdim 128', etc.
Examples:
x10_command('A', '1', ON)
x10_command('A', '1', OFF)
x10_command('A', '1', 'ON')
x10_command('A', '1', 'OFF')
x10_command('A', None, ON)
x10_command('A', None, OFF)
x10_command('A', None, 'all_lights_off')
x10_command('A', None, 'all_units_off')
x10_command('A', None, ALL_OFF)
x10_command('A', None, 'all_lights_on')
x10_command('A', 1, 'xdim 128')
"""
house_code = normalize_housecode(house_code)
if unit_number is not None:
unit_number = normalize_unitnumber(unit_number)
# else command is intended for the entire house code, not a single unit number
# TODO normalize/validate state
return self._x10_command(house_code, unit_number, state) |
def _x10_command(self, house_code, unit_number, state):
"""Real implementation"""
print('x10_command%r' % ((house_code, unit_number, state), ))
raise NotImplementedError() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.