repository_name stringclasses 316 values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1 value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1 value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
masfaraud/BMSpy | bms/core.py | DynamicSystem._AddVariable | python | def _AddVariable(self, variable):
if isinstance(variable, Signal):
if not variable in self.signals:
self.signals.append(variable)
elif isinstance(variable, Variable):
if not variable in self.variables:
self.variables.append(variable)
else:
raise TypeError
self._utd_graph = False | Add a variable to the model. Should not be used by end-user | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L222-L234 | null | class DynamicSystem:
"""
Defines a dynamic system that can simulate itself
:param te: time of simulation's end
:param ns: number of steps
:param blocks: (optional) list of blocks defining the model
"""
def __init__(self, te, ns, blocks=[]):
self.te = te
self.ns = ns
self.ts = self.te/float(self.ns) # time step
self.t = np.linspace(0, self.te, num=ns+1) # Time vector
self.blocks = []
self.variables = []
self.signals = []
self.max_order = 0
for block in blocks:
self.AddBlock(block)
self._utd_graph = False # True if graph is up-to-date
def AddBlock(self, block):
"""
Add the given block to the model and also its input/output variables
"""
if isinstance(block, Block):
self.blocks.append(block)
self.max_order = max(self.max_order, block.max_input_order-1)
self.max_order = max(self.max_order, block.max_output_order)
for variable in block.inputs+block.outputs:
self._AddVariable(variable)
else:
print(block)
raise TypeError
self._utd_graph = False
def _get_Graph(self):
if not self._utd_graph:
# Generate graph
self._graph = nx.DiGraph()
for variable in self.variables:
self._graph.add_node(variable, bipartite=0)
for block in self.blocks:
self._graph.add_node(block, bipartite=1)
for variable in block.inputs:
self._graph.add_edge(variable, block)
for variable in block.outputs:
self._graph.add_edge(block, variable)
self._utd_graph = True
return self._graph
graph = property(_get_Graph)
def _ResolutionOrder(self, variables_to_solve):
"""
return a list of lists of tuples (block,output,ndof) to be solved
"""
# Gp=nx.DiGraph()
#
# for i in range(nvar):
# Gp.add_node('v'+str(i),bipartite=0)
#
# for i in range(neq):
# Gp.add_node('e'+str(i),bipartite=1)
# for j in range(nvar):
# if Mo[i,j]==1:
# Gp.add_edge('e'+str(i),'v'+str(j))
Gp = nx.DiGraph()
for variable in self.variables:
Gp.add_node(variable, bipartite=0)
for block in self.blocks:
for iov, output_variable in enumerate(block.outputs):
Gp.add_node((block, iov), bipartite=1)
Gp.add_edge((block, iov), output_variable)
Gp.add_edge(output_variable, (block, iov))
for input_variable in block.inputs:
if not isinstance(input_variable, Signal):
Gp.add_edge(input_variable, (block, iov))
# for n1,n2 in M.items():
# Gp.add_edge(n1,n2)
sinks = []
sources = []
for node in Gp.nodes():
if Gp.out_degree(node) == 0:
sinks.append(node)
elif Gp.in_degree(node) == 0:
sources.append(node)
G2 = sources[:]
for node in sources:
for node2 in nx.descendants(Gp, node):
if node2 not in G2:
G2.append(node2)
if G2 != []:
print(G2)
raise ModelError('Overconstrained variables')
G3 = sinks[:]
for node in sinks:
for node2 in nx.ancestors(Gp, node):
if node2 not in G3:
G3.append(node2)
if G3 != []:
raise ModelError('Underconstrained variables')
# vars_resolvables=[]
# for var in vars_resoudre:
# if not 'v'+str(var) in G2+G3:
# vars_resolvables.append(var)
# G1=Gp.copy()
# G1.remove_nodes_from(G2+G3)
#
# M1=nx.bipartite.maximum_matching(G1)
# G1p=nx.DiGraph()
#
# G1p.add_nodes_from(G1.nodes())
# for e in G1.edges():
# # equation vers variable
# if e[0][0]=='v':
# G1p.add_edge(e[0],e[1])
# else:
# G1p.add_edge(e[1],e[0])
# # print(len(M))
# for n1,n2 in M1.items():
# # print(n1,n2)
# if n1[0]=='e':
# G1p.add_edge(n1,n2)
# else:
# G1p.add_edge(n2,n1)
scc = list(nx.strongly_connected_components(Gp))
# pos=nx.spring_layout(G1p)
# plt.figure()
# nx.draw(G1p,pos)
# nx.draw_networkx_labels(G1p,pos)
# print(scc)
if scc != []:
C = nx.condensation(Gp, scc)
isc_vars = []
for isc, sc in enumerate(scc):
for var in variables_to_solve:
if var in sc:
isc_vars.append(isc)
break
ancestors_vars = isc_vars[:]
for isc_var in isc_vars:
for ancetre in nx.ancestors(C, isc_var):
if ancetre not in ancestors_vars:
ancestors_vars.append(ancetre)
order_sc = [sc for sc in nx.topological_sort(
C) if sc in ancestors_vars]
order_ev = []
for isc in order_sc:
# liste d'équations et de variables triées pour être séparées
evs = list(scc[isc])
# print(evs)
# levs=int(len(evs)/2)
eqs = []
var = []
for element in evs:
if type(element) == tuple:
eqs.append(element)
else:
var.append(element)
order_ev.append((len(eqs), eqs, var))
return order_ev
raise ModelError
def Simulate(self, variables_to_solve=None):
if variables_to_solve == None:
variables_to_solve = [
variable for variable in self.variables if not variable.hidden]
order = self._ResolutionOrder(variables_to_solve)
# Initialisation of variables values
for variable in self.variables+self.signals:
variable._InitValues(self.ns, self.ts, self.max_order)
# ==============================================================================
# Enhancement to do: defining functions out of loop (copy args)s
# ==============================================================================
# print(order)
residue = []
for it, t in enumerate(self.t[1:]):
for neqs, equations, variables in order:
if neqs == 1:
equations[0][0].Solve(it+self.max_order+1, self.ts)
else:
# x0=np.zeros(neqs)
x0 = [equations[i][0].outputs[equations[i][1]]._values[it +
self.max_order] for i in range(len(equations))]
# print('===========')
def r(x, equations=equations[:]):
# Writing variables values proposed by optimizer
for i, xi in enumerate(x):
equations[i][0].outputs[equations[i][1]
]._values[it+self.max_order+1] = xi
# Computing regrets
r = []
# s=0
for ieq, (block, neq) in enumerate(equations):
# print(block,it)
# print(block.Evaluate(it+self.max_order+1,self.ts).shape)
# print(block.Evaluate(it+self.max_order+1,self.ts),block)
r.append(x[ieq]-block.Evaluate(it +
self.max_order+1, self.ts)[neq])
# print(block)
# print('xproposed:',x[ieq])
# print('block eval',block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print('value', x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# s+=abs(x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print(x[ieq],block.Evaluate(it+self.max_order+1,self.ts)[neq])
return r
def f(x, equations=equations[:]):
# Writing variables values proposed by optimizer
for i, xi in enumerate(x):
equations[i][0].outputs[equations[i][1]
]._values[it+self.max_order+1] = xi
# Computing regrets
# r=[]
s = 0
for ieq, (block, neq) in enumerate(equations):
# print(block,it)
# print(block.Evaluate(it+self.max_order+1,self.ts).shape)
# print(block.Evaluate(it+self.max_order+1,self.ts),block)
# r.append(x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print(block)
s += abs(x[ieq]-block.Evaluate(it +
self.max_order+1, self.ts)[neq])
# print(x[ieq],block.Evaluate(it+self.max_order+1,self.ts)[neq])
# return r
# print(s)
return s
x, d, i, m = fsolve(r, x0, full_output=True)
# res=root(f,x0,method='anderson')
# x=res.x
# res=minimize(f,x0,method='powell')
# if res.fun>1e-3:
# x0=[equations[i][0].outputs[equations[i][1]]._values[it+self.max_order] for i in range(len(equations))]
# x0+=np.random.random(len(equations))
# print('restart')
# res=minimize(f,x0,method='powell')
#
# residue.append(f(res.x))
# print(r(x),i)
# print(f(res.x),res.fun)
# f(x)
# print(r)
# if i!=1:
# print(equations)
# print(i,r(x))
# options={'tolfun':1e-3,'verbose':-9,'ftarget':1e-3}
# res=cma.fmin(f,x0,1,options=options)
# print(f(res[0]),r(res[0]))
# print(equations)
#
# print(m)
# if res.fun>1e-3:
# print('fail',res.fun)
# options={'tolfun':1e-3,'verbose':-9}
# res=cma.fmin(f,x0,1,options=options)
# else:
# print('ok')
# return residue
def VariablesValues(self, variables, t):
"""
Returns the value of given variables at time t.
Linear interpolation is performed between two time steps.
:param variables: one variable or a list of variables
:param t: time of evaluation
"""
# TODO: put interpolation in variables
if (t < self.te) | (t > 0):
i = t//self.ts # time step
ti = self.ts*i
if type(variables) == list:
values = []
for variable in variables:
# interpolation
values.append(
variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts)
return values
else:
# interpolation
return variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts
else:
raise ValueError
def PlotVariables(self, subplots_variables=None):
if subplots_variables == None:
subplots_variables = [self.signals+self.variables]
subplots_variables = [
[variable for variable in self.signals+self.variables if not variable.hidden]]
# plt.figure()
fig, axs = plt.subplots(len(subplots_variables), sharex=True)
if len(subplots_variables) == 1:
axs = [axs]
for isub, subplot in enumerate(subplots_variables):
legend = []
for variable in subplot:
axs[isub].plot(self.t, variable.values)
legend.append(variable.name)
axs[isub].legend(legend, loc='best')
axs[isub].margins(0.08)
axs[isub].grid()
plt.xlabel('Time')
plt.show()
def DrawModel(self):
from .interface import ModelDrawer
ModelDrawer(self)
def Save(self, name_file):
"""
name_file: name of the file without extension.
The extension .bms is added by function
"""
with open(name_file+'.bms', 'wb') as file:
model = dill.dump(self, file)
def __getstate__(self):
dic = self.__dict__.copy()
return dic
def __setstate__(self, dic):
self.__dict__ = dic
|
masfaraud/BMSpy | bms/core.py | DynamicSystem._ResolutionOrder | python | def _ResolutionOrder(self, variables_to_solve):
# Gp=nx.DiGraph()
#
# for i in range(nvar):
# Gp.add_node('v'+str(i),bipartite=0)
#
# for i in range(neq):
# Gp.add_node('e'+str(i),bipartite=1)
# for j in range(nvar):
# if Mo[i,j]==1:
# Gp.add_edge('e'+str(i),'v'+str(j))
Gp = nx.DiGraph()
for variable in self.variables:
Gp.add_node(variable, bipartite=0)
for block in self.blocks:
for iov, output_variable in enumerate(block.outputs):
Gp.add_node((block, iov), bipartite=1)
Gp.add_edge((block, iov), output_variable)
Gp.add_edge(output_variable, (block, iov))
for input_variable in block.inputs:
if not isinstance(input_variable, Signal):
Gp.add_edge(input_variable, (block, iov))
# for n1,n2 in M.items():
# Gp.add_edge(n1,n2)
sinks = []
sources = []
for node in Gp.nodes():
if Gp.out_degree(node) == 0:
sinks.append(node)
elif Gp.in_degree(node) == 0:
sources.append(node)
G2 = sources[:]
for node in sources:
for node2 in nx.descendants(Gp, node):
if node2 not in G2:
G2.append(node2)
if G2 != []:
print(G2)
raise ModelError('Overconstrained variables')
G3 = sinks[:]
for node in sinks:
for node2 in nx.ancestors(Gp, node):
if node2 not in G3:
G3.append(node2)
if G3 != []:
raise ModelError('Underconstrained variables')
# vars_resolvables=[]
# for var in vars_resoudre:
# if not 'v'+str(var) in G2+G3:
# vars_resolvables.append(var)
# G1=Gp.copy()
# G1.remove_nodes_from(G2+G3)
#
# M1=nx.bipartite.maximum_matching(G1)
# G1p=nx.DiGraph()
#
# G1p.add_nodes_from(G1.nodes())
# for e in G1.edges():
# # equation vers variable
# if e[0][0]=='v':
# G1p.add_edge(e[0],e[1])
# else:
# G1p.add_edge(e[1],e[0])
# # print(len(M))
# for n1,n2 in M1.items():
# # print(n1,n2)
# if n1[0]=='e':
# G1p.add_edge(n1,n2)
# else:
# G1p.add_edge(n2,n1)
scc = list(nx.strongly_connected_components(Gp))
# pos=nx.spring_layout(G1p)
# plt.figure()
# nx.draw(G1p,pos)
# nx.draw_networkx_labels(G1p,pos)
# print(scc)
if scc != []:
C = nx.condensation(Gp, scc)
isc_vars = []
for isc, sc in enumerate(scc):
for var in variables_to_solve:
if var in sc:
isc_vars.append(isc)
break
ancestors_vars = isc_vars[:]
for isc_var in isc_vars:
for ancetre in nx.ancestors(C, isc_var):
if ancetre not in ancestors_vars:
ancestors_vars.append(ancetre)
order_sc = [sc for sc in nx.topological_sort(
C) if sc in ancestors_vars]
order_ev = []
for isc in order_sc:
# liste d'équations et de variables triées pour être séparées
evs = list(scc[isc])
# print(evs)
# levs=int(len(evs)/2)
eqs = []
var = []
for element in evs:
if type(element) == tuple:
eqs.append(element)
else:
var.append(element)
order_ev.append((len(eqs), eqs, var))
return order_ev
raise ModelError | return a list of lists of tuples (block,output,ndof) to be solved | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L254-L379 | null | class DynamicSystem:
"""
Defines a dynamic system that can simulate itself
:param te: time of simulation's end
:param ns: number of steps
:param blocks: (optional) list of blocks defining the model
"""
def __init__(self, te, ns, blocks=[]):
self.te = te
self.ns = ns
self.ts = self.te/float(self.ns) # time step
self.t = np.linspace(0, self.te, num=ns+1) # Time vector
self.blocks = []
self.variables = []
self.signals = []
self.max_order = 0
for block in blocks:
self.AddBlock(block)
self._utd_graph = False # True if graph is up-to-date
def AddBlock(self, block):
"""
Add the given block to the model and also its input/output variables
"""
if isinstance(block, Block):
self.blocks.append(block)
self.max_order = max(self.max_order, block.max_input_order-1)
self.max_order = max(self.max_order, block.max_output_order)
for variable in block.inputs+block.outputs:
self._AddVariable(variable)
else:
print(block)
raise TypeError
self._utd_graph = False
def _AddVariable(self, variable):
"""
Add a variable to the model. Should not be used by end-user
"""
if isinstance(variable, Signal):
if not variable in self.signals:
self.signals.append(variable)
elif isinstance(variable, Variable):
if not variable in self.variables:
self.variables.append(variable)
else:
raise TypeError
self._utd_graph = False
def _get_Graph(self):
if not self._utd_graph:
# Generate graph
self._graph = nx.DiGraph()
for variable in self.variables:
self._graph.add_node(variable, bipartite=0)
for block in self.blocks:
self._graph.add_node(block, bipartite=1)
for variable in block.inputs:
self._graph.add_edge(variable, block)
for variable in block.outputs:
self._graph.add_edge(block, variable)
self._utd_graph = True
return self._graph
graph = property(_get_Graph)
def Simulate(self, variables_to_solve=None):
if variables_to_solve == None:
variables_to_solve = [
variable for variable in self.variables if not variable.hidden]
order = self._ResolutionOrder(variables_to_solve)
# Initialisation of variables values
for variable in self.variables+self.signals:
variable._InitValues(self.ns, self.ts, self.max_order)
# ==============================================================================
# Enhancement to do: defining functions out of loop (copy args)s
# ==============================================================================
# print(order)
residue = []
for it, t in enumerate(self.t[1:]):
for neqs, equations, variables in order:
if neqs == 1:
equations[0][0].Solve(it+self.max_order+1, self.ts)
else:
# x0=np.zeros(neqs)
x0 = [equations[i][0].outputs[equations[i][1]]._values[it +
self.max_order] for i in range(len(equations))]
# print('===========')
def r(x, equations=equations[:]):
# Writing variables values proposed by optimizer
for i, xi in enumerate(x):
equations[i][0].outputs[equations[i][1]
]._values[it+self.max_order+1] = xi
# Computing regrets
r = []
# s=0
for ieq, (block, neq) in enumerate(equations):
# print(block,it)
# print(block.Evaluate(it+self.max_order+1,self.ts).shape)
# print(block.Evaluate(it+self.max_order+1,self.ts),block)
r.append(x[ieq]-block.Evaluate(it +
self.max_order+1, self.ts)[neq])
# print(block)
# print('xproposed:',x[ieq])
# print('block eval',block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print('value', x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# s+=abs(x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print(x[ieq],block.Evaluate(it+self.max_order+1,self.ts)[neq])
return r
def f(x, equations=equations[:]):
# Writing variables values proposed by optimizer
for i, xi in enumerate(x):
equations[i][0].outputs[equations[i][1]
]._values[it+self.max_order+1] = xi
# Computing regrets
# r=[]
s = 0
for ieq, (block, neq) in enumerate(equations):
# print(block,it)
# print(block.Evaluate(it+self.max_order+1,self.ts).shape)
# print(block.Evaluate(it+self.max_order+1,self.ts),block)
# r.append(x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print(block)
s += abs(x[ieq]-block.Evaluate(it +
self.max_order+1, self.ts)[neq])
# print(x[ieq],block.Evaluate(it+self.max_order+1,self.ts)[neq])
# return r
# print(s)
return s
x, d, i, m = fsolve(r, x0, full_output=True)
# res=root(f,x0,method='anderson')
# x=res.x
# res=minimize(f,x0,method='powell')
# if res.fun>1e-3:
# x0=[equations[i][0].outputs[equations[i][1]]._values[it+self.max_order] for i in range(len(equations))]
# x0+=np.random.random(len(equations))
# print('restart')
# res=minimize(f,x0,method='powell')
#
# residue.append(f(res.x))
# print(r(x),i)
# print(f(res.x),res.fun)
# f(x)
# print(r)
# if i!=1:
# print(equations)
# print(i,r(x))
# options={'tolfun':1e-3,'verbose':-9,'ftarget':1e-3}
# res=cma.fmin(f,x0,1,options=options)
# print(f(res[0]),r(res[0]))
# print(equations)
#
# print(m)
# if res.fun>1e-3:
# print('fail',res.fun)
# options={'tolfun':1e-3,'verbose':-9}
# res=cma.fmin(f,x0,1,options=options)
# else:
# print('ok')
# return residue
def VariablesValues(self, variables, t):
"""
Returns the value of given variables at time t.
Linear interpolation is performed between two time steps.
:param variables: one variable or a list of variables
:param t: time of evaluation
"""
# TODO: put interpolation in variables
if (t < self.te) | (t > 0):
i = t//self.ts # time step
ti = self.ts*i
if type(variables) == list:
values = []
for variable in variables:
# interpolation
values.append(
variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts)
return values
else:
# interpolation
return variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts
else:
raise ValueError
def PlotVariables(self, subplots_variables=None):
if subplots_variables == None:
subplots_variables = [self.signals+self.variables]
subplots_variables = [
[variable for variable in self.signals+self.variables if not variable.hidden]]
# plt.figure()
fig, axs = plt.subplots(len(subplots_variables), sharex=True)
if len(subplots_variables) == 1:
axs = [axs]
for isub, subplot in enumerate(subplots_variables):
legend = []
for variable in subplot:
axs[isub].plot(self.t, variable.values)
legend.append(variable.name)
axs[isub].legend(legend, loc='best')
axs[isub].margins(0.08)
axs[isub].grid()
plt.xlabel('Time')
plt.show()
def DrawModel(self):
from .interface import ModelDrawer
ModelDrawer(self)
def Save(self, name_file):
"""
name_file: name of the file without extension.
The extension .bms is added by function
"""
with open(name_file+'.bms', 'wb') as file:
model = dill.dump(self, file)
def __getstate__(self):
dic = self.__dict__.copy()
return dic
def __setstate__(self, dic):
self.__dict__ = dic
|
masfaraud/BMSpy | bms/core.py | DynamicSystem.VariablesValues | python | def VariablesValues(self, variables, t):
# TODO: put interpolation in variables
if (t < self.te) | (t > 0):
i = t//self.ts # time step
ti = self.ts*i
if type(variables) == list:
values = []
for variable in variables:
# interpolation
values.append(
variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts)
return values
else:
# interpolation
return variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts
else:
raise ValueError | Returns the value of given variables at time t.
Linear interpolation is performed between two time steps.
:param variables: one variable or a list of variables
:param t: time of evaluation | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L488-L512 | null | class DynamicSystem:
"""
Defines a dynamic system that can simulate itself
:param te: time of simulation's end
:param ns: number of steps
:param blocks: (optional) list of blocks defining the model
"""
def __init__(self, te, ns, blocks=[]):
self.te = te
self.ns = ns
self.ts = self.te/float(self.ns) # time step
self.t = np.linspace(0, self.te, num=ns+1) # Time vector
self.blocks = []
self.variables = []
self.signals = []
self.max_order = 0
for block in blocks:
self.AddBlock(block)
self._utd_graph = False # True if graph is up-to-date
def AddBlock(self, block):
"""
Add the given block to the model and also its input/output variables
"""
if isinstance(block, Block):
self.blocks.append(block)
self.max_order = max(self.max_order, block.max_input_order-1)
self.max_order = max(self.max_order, block.max_output_order)
for variable in block.inputs+block.outputs:
self._AddVariable(variable)
else:
print(block)
raise TypeError
self._utd_graph = False
def _AddVariable(self, variable):
"""
Add a variable to the model. Should not be used by end-user
"""
if isinstance(variable, Signal):
if not variable in self.signals:
self.signals.append(variable)
elif isinstance(variable, Variable):
if not variable in self.variables:
self.variables.append(variable)
else:
raise TypeError
self._utd_graph = False
def _get_Graph(self):
if not self._utd_graph:
# Generate graph
self._graph = nx.DiGraph()
for variable in self.variables:
self._graph.add_node(variable, bipartite=0)
for block in self.blocks:
self._graph.add_node(block, bipartite=1)
for variable in block.inputs:
self._graph.add_edge(variable, block)
for variable in block.outputs:
self._graph.add_edge(block, variable)
self._utd_graph = True
return self._graph
graph = property(_get_Graph)
def _ResolutionOrder(self, variables_to_solve):
"""
return a list of lists of tuples (block,output,ndof) to be solved
"""
# Gp=nx.DiGraph()
#
# for i in range(nvar):
# Gp.add_node('v'+str(i),bipartite=0)
#
# for i in range(neq):
# Gp.add_node('e'+str(i),bipartite=1)
# for j in range(nvar):
# if Mo[i,j]==1:
# Gp.add_edge('e'+str(i),'v'+str(j))
Gp = nx.DiGraph()
for variable in self.variables:
Gp.add_node(variable, bipartite=0)
for block in self.blocks:
for iov, output_variable in enumerate(block.outputs):
Gp.add_node((block, iov), bipartite=1)
Gp.add_edge((block, iov), output_variable)
Gp.add_edge(output_variable, (block, iov))
for input_variable in block.inputs:
if not isinstance(input_variable, Signal):
Gp.add_edge(input_variable, (block, iov))
# for n1,n2 in M.items():
# Gp.add_edge(n1,n2)
sinks = []
sources = []
for node in Gp.nodes():
if Gp.out_degree(node) == 0:
sinks.append(node)
elif Gp.in_degree(node) == 0:
sources.append(node)
G2 = sources[:]
for node in sources:
for node2 in nx.descendants(Gp, node):
if node2 not in G2:
G2.append(node2)
if G2 != []:
print(G2)
raise ModelError('Overconstrained variables')
G3 = sinks[:]
for node in sinks:
for node2 in nx.ancestors(Gp, node):
if node2 not in G3:
G3.append(node2)
if G3 != []:
raise ModelError('Underconstrained variables')
# vars_resolvables=[]
# for var in vars_resoudre:
# if not 'v'+str(var) in G2+G3:
# vars_resolvables.append(var)
# G1=Gp.copy()
# G1.remove_nodes_from(G2+G3)
#
# M1=nx.bipartite.maximum_matching(G1)
# G1p=nx.DiGraph()
#
# G1p.add_nodes_from(G1.nodes())
# for e in G1.edges():
# # equation vers variable
# if e[0][0]=='v':
# G1p.add_edge(e[0],e[1])
# else:
# G1p.add_edge(e[1],e[0])
# # print(len(M))
# for n1,n2 in M1.items():
# # print(n1,n2)
# if n1[0]=='e':
# G1p.add_edge(n1,n2)
# else:
# G1p.add_edge(n2,n1)
scc = list(nx.strongly_connected_components(Gp))
# pos=nx.spring_layout(G1p)
# plt.figure()
# nx.draw(G1p,pos)
# nx.draw_networkx_labels(G1p,pos)
# print(scc)
if scc != []:
C = nx.condensation(Gp, scc)
isc_vars = []
for isc, sc in enumerate(scc):
for var in variables_to_solve:
if var in sc:
isc_vars.append(isc)
break
ancestors_vars = isc_vars[:]
for isc_var in isc_vars:
for ancetre in nx.ancestors(C, isc_var):
if ancetre not in ancestors_vars:
ancestors_vars.append(ancetre)
order_sc = [sc for sc in nx.topological_sort(
C) if sc in ancestors_vars]
order_ev = []
for isc in order_sc:
# liste d'équations et de variables triées pour être séparées
evs = list(scc[isc])
# print(evs)
# levs=int(len(evs)/2)
eqs = []
var = []
for element in evs:
if type(element) == tuple:
eqs.append(element)
else:
var.append(element)
order_ev.append((len(eqs), eqs, var))
return order_ev
raise ModelError
def Simulate(self, variables_to_solve=None):
if variables_to_solve == None:
variables_to_solve = [
variable for variable in self.variables if not variable.hidden]
order = self._ResolutionOrder(variables_to_solve)
# Initialisation of variables values
for variable in self.variables+self.signals:
variable._InitValues(self.ns, self.ts, self.max_order)
# ==============================================================================
# Enhancement to do: defining functions out of loop (copy args)s
# ==============================================================================
# print(order)
residue = []
for it, t in enumerate(self.t[1:]):
for neqs, equations, variables in order:
if neqs == 1:
equations[0][0].Solve(it+self.max_order+1, self.ts)
else:
# x0=np.zeros(neqs)
x0 = [equations[i][0].outputs[equations[i][1]]._values[it +
self.max_order] for i in range(len(equations))]
# print('===========')
def r(x, equations=equations[:]):
# Writing variables values proposed by optimizer
for i, xi in enumerate(x):
equations[i][0].outputs[equations[i][1]
]._values[it+self.max_order+1] = xi
# Computing regrets
r = []
# s=0
for ieq, (block, neq) in enumerate(equations):
# print(block,it)
# print(block.Evaluate(it+self.max_order+1,self.ts).shape)
# print(block.Evaluate(it+self.max_order+1,self.ts),block)
r.append(x[ieq]-block.Evaluate(it +
self.max_order+1, self.ts)[neq])
# print(block)
# print('xproposed:',x[ieq])
# print('block eval',block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print('value', x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# s+=abs(x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print(x[ieq],block.Evaluate(it+self.max_order+1,self.ts)[neq])
return r
def f(x, equations=equations[:]):
# Writing variables values proposed by optimizer
for i, xi in enumerate(x):
equations[i][0].outputs[equations[i][1]
]._values[it+self.max_order+1] = xi
# Computing regrets
# r=[]
s = 0
for ieq, (block, neq) in enumerate(equations):
# print(block,it)
# print(block.Evaluate(it+self.max_order+1,self.ts).shape)
# print(block.Evaluate(it+self.max_order+1,self.ts),block)
# r.append(x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print(block)
s += abs(x[ieq]-block.Evaluate(it +
self.max_order+1, self.ts)[neq])
# print(x[ieq],block.Evaluate(it+self.max_order+1,self.ts)[neq])
# return r
# print(s)
return s
x, d, i, m = fsolve(r, x0, full_output=True)
# res=root(f,x0,method='anderson')
# x=res.x
# res=minimize(f,x0,method='powell')
# if res.fun>1e-3:
# x0=[equations[i][0].outputs[equations[i][1]]._values[it+self.max_order] for i in range(len(equations))]
# x0+=np.random.random(len(equations))
# print('restart')
# res=minimize(f,x0,method='powell')
#
# residue.append(f(res.x))
# print(r(x),i)
# print(f(res.x),res.fun)
# f(x)
# print(r)
# if i!=1:
# print(equations)
# print(i,r(x))
# options={'tolfun':1e-3,'verbose':-9,'ftarget':1e-3}
# res=cma.fmin(f,x0,1,options=options)
# print(f(res[0]),r(res[0]))
# print(equations)
#
# print(m)
# if res.fun>1e-3:
# print('fail',res.fun)
# options={'tolfun':1e-3,'verbose':-9}
# res=cma.fmin(f,x0,1,options=options)
# else:
# print('ok')
# return residue
def PlotVariables(self, subplots_variables=None):
if subplots_variables == None:
subplots_variables = [self.signals+self.variables]
subplots_variables = [
[variable for variable in self.signals+self.variables if not variable.hidden]]
# plt.figure()
fig, axs = plt.subplots(len(subplots_variables), sharex=True)
if len(subplots_variables) == 1:
axs = [axs]
for isub, subplot in enumerate(subplots_variables):
legend = []
for variable in subplot:
axs[isub].plot(self.t, variable.values)
legend.append(variable.name)
axs[isub].legend(legend, loc='best')
axs[isub].margins(0.08)
axs[isub].grid()
plt.xlabel('Time')
plt.show()
def DrawModel(self):
from .interface import ModelDrawer
ModelDrawer(self)
def Save(self, name_file):
"""
name_file: name of the file without extension.
The extension .bms is added by function
"""
with open(name_file+'.bms', 'wb') as file:
model = dill.dump(self, file)
def __getstate__(self):
dic = self.__dict__.copy()
return dic
def __setstate__(self, dic):
self.__dict__ = dic
|
masfaraud/BMSpy | bms/core.py | DynamicSystem.Save | python | def Save(self, name_file):
with open(name_file+'.bms', 'wb') as file:
model = dill.dump(self, file) | name_file: name of the file without extension.
The extension .bms is added by function | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/core.py#L539-L545 | null | class DynamicSystem:
"""
Defines a dynamic system that can simulate itself
:param te: time of simulation's end
:param ns: number of steps
:param blocks: (optional) list of blocks defining the model
"""
def __init__(self, te, ns, blocks=[]):
self.te = te
self.ns = ns
self.ts = self.te/float(self.ns) # time step
self.t = np.linspace(0, self.te, num=ns+1) # Time vector
self.blocks = []
self.variables = []
self.signals = []
self.max_order = 0
for block in blocks:
self.AddBlock(block)
self._utd_graph = False # True if graph is up-to-date
def AddBlock(self, block):
"""
Add the given block to the model and also its input/output variables
"""
if isinstance(block, Block):
self.blocks.append(block)
self.max_order = max(self.max_order, block.max_input_order-1)
self.max_order = max(self.max_order, block.max_output_order)
for variable in block.inputs+block.outputs:
self._AddVariable(variable)
else:
print(block)
raise TypeError
self._utd_graph = False
def _AddVariable(self, variable):
"""
Add a variable to the model. Should not be used by end-user
"""
if isinstance(variable, Signal):
if not variable in self.signals:
self.signals.append(variable)
elif isinstance(variable, Variable):
if not variable in self.variables:
self.variables.append(variable)
else:
raise TypeError
self._utd_graph = False
def _get_Graph(self):
if not self._utd_graph:
# Generate graph
self._graph = nx.DiGraph()
for variable in self.variables:
self._graph.add_node(variable, bipartite=0)
for block in self.blocks:
self._graph.add_node(block, bipartite=1)
for variable in block.inputs:
self._graph.add_edge(variable, block)
for variable in block.outputs:
self._graph.add_edge(block, variable)
self._utd_graph = True
return self._graph
graph = property(_get_Graph)
def _ResolutionOrder(self, variables_to_solve):
"""
return a list of lists of tuples (block,output,ndof) to be solved
"""
# Gp=nx.DiGraph()
#
# for i in range(nvar):
# Gp.add_node('v'+str(i),bipartite=0)
#
# for i in range(neq):
# Gp.add_node('e'+str(i),bipartite=1)
# for j in range(nvar):
# if Mo[i,j]==1:
# Gp.add_edge('e'+str(i),'v'+str(j))
Gp = nx.DiGraph()
for variable in self.variables:
Gp.add_node(variable, bipartite=0)
for block in self.blocks:
for iov, output_variable in enumerate(block.outputs):
Gp.add_node((block, iov), bipartite=1)
Gp.add_edge((block, iov), output_variable)
Gp.add_edge(output_variable, (block, iov))
for input_variable in block.inputs:
if not isinstance(input_variable, Signal):
Gp.add_edge(input_variable, (block, iov))
# for n1,n2 in M.items():
# Gp.add_edge(n1,n2)
sinks = []
sources = []
for node in Gp.nodes():
if Gp.out_degree(node) == 0:
sinks.append(node)
elif Gp.in_degree(node) == 0:
sources.append(node)
G2 = sources[:]
for node in sources:
for node2 in nx.descendants(Gp, node):
if node2 not in G2:
G2.append(node2)
if G2 != []:
print(G2)
raise ModelError('Overconstrained variables')
G3 = sinks[:]
for node in sinks:
for node2 in nx.ancestors(Gp, node):
if node2 not in G3:
G3.append(node2)
if G3 != []:
raise ModelError('Underconstrained variables')
# vars_resolvables=[]
# for var in vars_resoudre:
# if not 'v'+str(var) in G2+G3:
# vars_resolvables.append(var)
# G1=Gp.copy()
# G1.remove_nodes_from(G2+G3)
#
# M1=nx.bipartite.maximum_matching(G1)
# G1p=nx.DiGraph()
#
# G1p.add_nodes_from(G1.nodes())
# for e in G1.edges():
# # equation vers variable
# if e[0][0]=='v':
# G1p.add_edge(e[0],e[1])
# else:
# G1p.add_edge(e[1],e[0])
# # print(len(M))
# for n1,n2 in M1.items():
# # print(n1,n2)
# if n1[0]=='e':
# G1p.add_edge(n1,n2)
# else:
# G1p.add_edge(n2,n1)
scc = list(nx.strongly_connected_components(Gp))
# pos=nx.spring_layout(G1p)
# plt.figure()
# nx.draw(G1p,pos)
# nx.draw_networkx_labels(G1p,pos)
# print(scc)
if scc != []:
C = nx.condensation(Gp, scc)
isc_vars = []
for isc, sc in enumerate(scc):
for var in variables_to_solve:
if var in sc:
isc_vars.append(isc)
break
ancestors_vars = isc_vars[:]
for isc_var in isc_vars:
for ancetre in nx.ancestors(C, isc_var):
if ancetre not in ancestors_vars:
ancestors_vars.append(ancetre)
order_sc = [sc for sc in nx.topological_sort(
C) if sc in ancestors_vars]
order_ev = []
for isc in order_sc:
# liste d'équations et de variables triées pour être séparées
evs = list(scc[isc])
# print(evs)
# levs=int(len(evs)/2)
eqs = []
var = []
for element in evs:
if type(element) == tuple:
eqs.append(element)
else:
var.append(element)
order_ev.append((len(eqs), eqs, var))
return order_ev
raise ModelError
def Simulate(self, variables_to_solve=None):
if variables_to_solve == None:
variables_to_solve = [
variable for variable in self.variables if not variable.hidden]
order = self._ResolutionOrder(variables_to_solve)
# Initialisation of variables values
for variable in self.variables+self.signals:
variable._InitValues(self.ns, self.ts, self.max_order)
# ==============================================================================
# Enhancement to do: defining functions out of loop (copy args)s
# ==============================================================================
# print(order)
residue = []
for it, t in enumerate(self.t[1:]):
for neqs, equations, variables in order:
if neqs == 1:
equations[0][0].Solve(it+self.max_order+1, self.ts)
else:
# x0=np.zeros(neqs)
x0 = [equations[i][0].outputs[equations[i][1]]._values[it +
self.max_order] for i in range(len(equations))]
# print('===========')
def r(x, equations=equations[:]):
# Writing variables values proposed by optimizer
for i, xi in enumerate(x):
equations[i][0].outputs[equations[i][1]
]._values[it+self.max_order+1] = xi
# Computing regrets
r = []
# s=0
for ieq, (block, neq) in enumerate(equations):
# print(block,it)
# print(block.Evaluate(it+self.max_order+1,self.ts).shape)
# print(block.Evaluate(it+self.max_order+1,self.ts),block)
r.append(x[ieq]-block.Evaluate(it +
self.max_order+1, self.ts)[neq])
# print(block)
# print('xproposed:',x[ieq])
# print('block eval',block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print('value', x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# s+=abs(x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print(x[ieq],block.Evaluate(it+self.max_order+1,self.ts)[neq])
return r
def f(x, equations=equations[:]):
# Writing variables values proposed by optimizer
for i, xi in enumerate(x):
equations[i][0].outputs[equations[i][1]
]._values[it+self.max_order+1] = xi
# Computing regrets
# r=[]
s = 0
for ieq, (block, neq) in enumerate(equations):
# print(block,it)
# print(block.Evaluate(it+self.max_order+1,self.ts).shape)
# print(block.Evaluate(it+self.max_order+1,self.ts),block)
# r.append(x[ieq]-block.Evaluate(it+self.max_order+1,self.ts)[neq])
# print(block)
s += abs(x[ieq]-block.Evaluate(it +
self.max_order+1, self.ts)[neq])
# print(x[ieq],block.Evaluate(it+self.max_order+1,self.ts)[neq])
# return r
# print(s)
return s
x, d, i, m = fsolve(r, x0, full_output=True)
# res=root(f,x0,method='anderson')
# x=res.x
# res=minimize(f,x0,method='powell')
# if res.fun>1e-3:
# x0=[equations[i][0].outputs[equations[i][1]]._values[it+self.max_order] for i in range(len(equations))]
# x0+=np.random.random(len(equations))
# print('restart')
# res=minimize(f,x0,method='powell')
#
# residue.append(f(res.x))
# print(r(x),i)
# print(f(res.x),res.fun)
# f(x)
# print(r)
# if i!=1:
# print(equations)
# print(i,r(x))
# options={'tolfun':1e-3,'verbose':-9,'ftarget':1e-3}
# res=cma.fmin(f,x0,1,options=options)
# print(f(res[0]),r(res[0]))
# print(equations)
#
# print(m)
# if res.fun>1e-3:
# print('fail',res.fun)
# options={'tolfun':1e-3,'verbose':-9}
# res=cma.fmin(f,x0,1,options=options)
# else:
# print('ok')
# return residue
def VariablesValues(self, variables, t):
"""
Returns the value of given variables at time t.
Linear interpolation is performed between two time steps.
:param variables: one variable or a list of variables
:param t: time of evaluation
"""
# TODO: put interpolation in variables
if (t < self.te) | (t > 0):
i = t//self.ts # time step
ti = self.ts*i
if type(variables) == list:
values = []
for variable in variables:
# interpolation
values.append(
variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts)
return values
else:
# interpolation
return variables.values[i]*((ti-t)/self.ts+1)+variables.values[i+1]*(t-ti)/self.ts
else:
raise ValueError
def PlotVariables(self, subplots_variables=None):
if subplots_variables == None:
subplots_variables = [self.signals+self.variables]
subplots_variables = [
[variable for variable in self.signals+self.variables if not variable.hidden]]
# plt.figure()
fig, axs = plt.subplots(len(subplots_variables), sharex=True)
if len(subplots_variables) == 1:
axs = [axs]
for isub, subplot in enumerate(subplots_variables):
legend = []
for variable in subplot:
axs[isub].plot(self.t, variable.values)
legend.append(variable.name)
axs[isub].legend(legend, loc='best')
axs[isub].margins(0.08)
axs[isub].grid()
plt.xlabel('Time')
plt.show()
def DrawModel(self):
from .interface import ModelDrawer
ModelDrawer(self)
def __getstate__(self):
dic = self.__dict__.copy()
return dic
def __setstate__(self, dic):
self.__dict__ = dic
|
masfaraud/BMSpy | bms/physical/mechanical.py | ThermalEngine.PartialDynamicSystem | python | def PartialDynamicSystem(self, ieq, variable):
if ieq == 0:
# U1=0
if variable == self.variables[0]:
b1 = FunctionBlock(
self.physical_nodes[0].variable, self.max_torque, self.Tmax)
b2 = Saturation(self.commands[0], self.throttle, 0, 1)
b3 = Product(self.max_torque, self.throttle, variable)
return[b1, b2, b3] | returns dynamical system blocks associated to output variable | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/physical/mechanical.py#L74-L85 | null | class ThermalEngine(PhysicalBlock):
"""
Simple thermal engine
"""
def __init__(self, node1, wmin, wmax, Tmax_map, fuel_flow_map, name='Thermal engine'):
occurence_matrix = np.array([[0, 1]])
command = Variable('Requested engine throttle')
self.wmin = wmin
self.wmax = wmax
self.Tmax = Tmax_map
self.fuel_flow_map = fuel_flow_map
self.max_torque = Variable('max torque')
self.throttle = Variable('Engine throttle')
PhysicalBlock.__init__(
self, [node1], [0], occurence_matrix, [command], name)
|
masfaraud/BMSpy | bms/physical/mechanical.py | Brake.PartialDynamicSystem | python | def PartialDynamicSystem(self, ieq, variable):
if ieq == 0:
# U1=0
if variable == self.variables[0]:
return[Gain(self.commands[0], variable, -self.Tmax)] | returns dynamical system blocks associated to output variable | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/physical/mechanical.py#L100-L107 | null | class Brake(PhysicalBlock):
"""
Simple brake, must be improved with non linearity of equilibrium
"""
def __init__(self, node1, Tmax, name='Brake'):
occurence_matrix = np.array([[0, 1]])
command = Variable('Brake command')
self.Tmax = Tmax
PhysicalBlock.__init__(
self, [node1], [0], occurence_matrix, [command], name)
|
masfaraud/BMSpy | bms/physical/mechanical.py | Clutch.PartialDynamicSystem | python | def PartialDynamicSystem(self, ieq, variable):
if ieq == 0:
# C1=-f*Tmax*sign(w1-w2)
if variable == self.variables[0]:
ut = Variable('unsigned clutch friction torque', hidden=True)
b1 = Gain(self.commands[0], ut, self.Tmax)
dw = Variable('Delta rotationnal speed', hidden=True)
sdw = Variable('Sign of delta rotationnal speed')
b2 = WeightedSum(
[self.physical_nodes[0].variable, self.physical_nodes[1].variable], dw, [-1, 1])
b3 = Sign(dw, sdw)
b4 = Product(ut, sdw, variable)
return[b1, b2, b3, b4]
elif ieq == 1:
# C1=-C2
if variable == self.variables[0]:
return [Gain(self.variables[1], variable, -1)]
if variable == self.variables[1]:
return [Gain(self.variables[0], variable, -1)] | returns dynamical system blocks associated to output variable | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/physical/mechanical.py#L122-L143 | null | class Clutch(PhysicalBlock):
"""
Simple clutch
"""
def __init__(self, node1, node2, Tmax, name='Clutch'):
occurence_matrix = np.array([[0, 1, 0, 0], [0, 1, 0, 1]])
command = Variable('Clutch command')
self.Tmax = Tmax
PhysicalBlock.__init__(self, [node1, node2], [
0, 1], occurence_matrix, [command], name)
|
masfaraud/BMSpy | bms/physical/mechanical.py | GearRatio.PartialDynamicSystem | python | def PartialDynamicSystem(self, ieq, variable):
if ieq == 0:
# w2=Rw1
if variable == self.physical_nodes[0].variable:
# w1=w2/R
return[Gain(self.physical_nodes[1].variable, variable, 1/self.ratio)]
elif variable == self.physical_nodes[1].variable:
# w2=Rw1
return[Gain(self.physical_nodes[0].variable, variable, self.ratio)]
elif ieq == 1:
# C1=-RC2
if variable == self.variables[0]:
# C1=-RC2
return[Gain(self.variables[1], variable, -self.ratio)]
elif variable == self.variables[1]:
# C2=-C1/R
return[Gain(self.variables[0], variable, -1/self.ratio)] | returns dynamical system blocks associated to output variable | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/physical/mechanical.py#L158-L177 | null | class GearRatio(PhysicalBlock):
"""
Allow to model all components that impose a fixed ratio between two
rotational nodes such as gear sets
"""
def __init__(self, node1, node2, ratio, name='Gear ratio'):
occurence_matrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1]])
self.ratio = ratio
PhysicalBlock.__init__(self, [node1, node2], [
0, 1], occurence_matrix, [], name)
|
masfaraud/BMSpy | bms/physical/mechanical.py | Wheel.PartialDynamicSystem | python | def PartialDynamicSystem(self, ieq, variable):
if ieq == 0:
# v=Rw
if variable == self.physical_nodes[0].variable:
# W=V/r
return[Gain(self.physical_nodes[1].variable, variable, 1/self.wheels_radius)]
elif variable == self.physical_nodes[1].variable:
# V=rw
return[Gain(self.physical_nodes[0].variable, variable, self.wheels_radius)]
elif ieq == 1:
# C=-FR
if variable == self.variables[0]:
# C=-FR
return[Gain(self.variables[1], variable, -self.wheels_radius)]
elif variable == self.variables[1]:
# F=-C/R
return[Gain(self.variables[0], variable, -1/self.wheels_radius)] | returns dynamical system blocks associated to output variable | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/physical/mechanical.py#L191-L210 | null | class Wheel(PhysicalBlock):
"""
"""
def __init__(self, node_rotation, node_translation, wheels_radius, name='Wheel'):
occurence_matrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1]])
self.wheels_radius = wheels_radius
PhysicalBlock.__init__(self, [node_rotation, node_translation], [
0, 1], occurence_matrix, [], name)
|
masfaraud/BMSpy | bms/physical/electrical.py | Ground.PartialDynamicSystem | python | def PartialDynamicSystem(self, ieq, variable):
if ieq == 0:
# U1=0
if variable == self.physical_nodes[0].variable:
v = Step('Ground', 0)
return[Gain(v, variable, 1)] | returns dynamical system blocks associated to output variable | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/physical/electrical.py#L25-L33 | null | class Ground(PhysicalBlock):
def __init__(self, node1, name='Ground'):
occurence_matrix = np.array([[1, 0]]) # U1=0
PhysicalBlock.__init__(self, [node1], [], occurence_matrix, [], name)
|
masfaraud/BMSpy | bms/physical/electrical.py | Resistor.PartialDynamicSystem | python | def PartialDynamicSystem(self, ieq, variable):
# print(ieq,variable.name)
if ieq == 0:
# U1-U2=R(i1)
if variable == self.physical_nodes[0].variable:
# U1 is output
# U1=R(i1)+U2
return [WeightedSum([self.physical_nodes[1].variable, self.variables[0]], variable, [1, self.R])]
elif variable == self.physical_nodes[1].variable:
# U2 is output
# U2=-R(i1)+U2
return [WeightedSum([self.physical_nodes[0].variable, self.variables[0]], variable, [1, -self.R])]
elif variable == self.variables[0]:
# i1 is output
# i1=(U1-U2)/R
return [WeightedSum([self.physical_nodes[0].variable, self.physical_nodes[1].variable], variable, [1/self.R, -1/self.R])]
elif ieq == 1:
# i1=-i2
if variable == self.variables[0]:
# i1 as output
return [Gain(self.variables[1], self.variables[0], -1)]
elif variable == self.variables[1]:
# i2 as output
return [Gain(self.variables[0], self.variables[1], -1)] | returns dynamical system blocks associated to output variable | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/physical/electrical.py#L44-L70 | null | class Resistor(PhysicalBlock):
def __init__(self, node1, node2, R, name='Resistor'):
# 1st eq: (U1-U2)=R(i1-i2) 2nd: i1=-i2
occurence_matrix = np.array([[1, 1, 1, 0], [0, 1, 0, 1]])
PhysicalBlock.__init__(self, [node1, node2], [
0, 1], occurence_matrix, [], name)
self.R = R
|
masfaraud/BMSpy | bms/physical/electrical.py | Generator.PartialDynamicSystem | python | def PartialDynamicSystem(self, ieq, variable):
if ieq == 0:
# U2-U1=signal
if variable == self.physical_nodes[0].variable:
# U1 is output
# U1=U2-signal
return [WeightedSum([self.physical_nodes[1].variable, self.voltage_signal], variable, [1, -1])]
elif variable == self.physical_nodes[1].variable:
# U2 is output
# U2=U1+signal
return [WeightedSum([self.physical_nodes[0].variable, self.voltage_signal], variable, [1, 1])] | returns dynamical system blocks associated to output variable | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/physical/electrical.py#L84-L97 | null | class Generator(PhysicalBlock):
"""
:param voltage_signal: BMS signal to be input function of voltage (Step,Sinus...)
"""
def __init__(self, node1, node2, voltage_signal, name='GeneratorGround'):
occurence_matrix = np.array([[1, 0, 1, 0]]) # 1st eq: U2=signal, U1=0
PhysicalBlock.__init__(self, [node1, node2], [
0, 1], occurence_matrix, [], name)
self.voltage_signal = voltage_signal
|
masfaraud/BMSpy | bms/physical/electrical.py | Capacitor.PartialDynamicSystem | python | def PartialDynamicSystem(self, ieq, variable):
if ieq == 0:
if variable == self.physical_nodes[0].variable:
print('1')
# U1 is output
# U1=i1/pC+U2
Uc = Variable(hidden=True)
block1 = ODE(self.variables[0], Uc, [1], [0, self.C])
sub1 = Sum([self.physical_nodes[1].variable, Uc], variable)
return [block1, sub1]
elif variable == self.physical_nodes[1].variable:
print('2')
# U2 is output
# U2=U1-i1/pC
Uc = Variable(hidden=True)
block1 = ODE(self.variables[0], Uc, [-1], [0, self.C])
sum1 = Sum([self.physical_nodes[0].variable, Uc], variable)
return [block1, sum1]
# elif variable==self.variables[0]:
# print('3')
# # i1 is output
# # i1=pC(U1-U2)
# ic=Variable(hidden=True)
# subs1=Subtraction(self.physical_nodes[0].variable,self.physical_nodes[1].variable,ic)
# block1=ODE(ic,variable,[0,self.C],[1])
# return [block1,subs1]
elif ieq == 1:
# i1=-i2
if variable == self.variables[0]:
# i1 as output
# print('Bat1#0')
return [Gain(self.variables[1], self.variables[0], -1)]
elif variable == self.variables[1]:
# i2 as output
# print('Bat1#1')
return [Gain(self.variables[0], self.variables[1], -1)] | returns dynamical system blocks associated to output variable | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/physical/electrical.py#L166-L206 | null | class Capacitor(PhysicalBlock):
def __init__(self, node1, node2, C, name='Capacitor'):
# 1st eq: (U1-U2)=R(i1-i2) 2nd: i1=-i2
occurence_matrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1]])
PhysicalBlock.__init__(self, [node1, node2], [
0, 1], occurence_matrix, [], name)
self.C = C
|
masfaraud/BMSpy | bms/physical/electrical.py | Inductor.PartialDynamicSystem | python | def PartialDynamicSystem(self, ieq, variable):
if ieq == 0:
# if variable==self.physical_nodes[0].variable:
# print('1')
# # U1 is output
# # U1=i1/pC+U2
# Uc=Variable(hidden=True)
# block1=ODE(self.variables[0],Uc,[1],[0,self.C])
# sub1=Sum([self.physical_nodes[1].variable,Uc],variable)
# return [block1,sub1]
# elif variable==self.physical_nodes[1].variable:
# print('2')
# # U2 is output
# # U2=U1-i1/pC
# Uc=Variable(hidden=True)
# block1=ODE(self.variables[0],Uc,[-1],[0,self.C])
# sum1=Sum([self.physical_nodes[0].variable,Uc],variable)
# return [block1,sum1]
if variable == self.variables[0]: # i1=(u1-u2)/Lp
print('3')
# i1 is output
# i1=pC(U1-U2)
Uc = Variable(hidden=True)
subs1 = Subtraction(
self.physical_nodes[0].variable, self.physical_nodes[1].variable, Uc)
block1 = ODE(Uc, variable, [1], [0, self.L])
return [block1, subs1]
elif ieq == 1:
# i1=-i2
if variable == self.variables[0]:
# i1 as output
return [Gain(self.variables[1], self.variables[0], -1)]
elif variable == self.variables[1]:
# i2 as output
return [Gain(self.variables[0], self.variables[1], -1)] | returns dynamical system blocks associated to output variable | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/physical/electrical.py#L217-L256 | null | class Inductor(PhysicalBlock):
def __init__(self, node1, node2, L, name='Inductor'):
# 1st eq: (U1-U2)=Ldi1/dt 2nd: i1=-i2
occurence_matrix = np.array([[1, 1, 1, 0], [0, 1, 0, 1]])
PhysicalBlock.__init__(self, [node1, node2], [
0, 1], occurence_matrix, [], name)
self.L = L
|
masfaraud/BMSpy | bms/interface.py | ModelDrawer.on_release_event | python | def on_release_event(self, event):
" Update text position and redraw"
element = self.element_from_artist[self.selected_patch]
self.position[element] = [event.xdata, event.ydata]
# Signal is a variable! therefore must be tested before
if isinstance(element, bms.Signal):
artists = self.artists_from_element[element]
points = np.array((5, 2))
xp, yp = self.position[element]
points = np.array([[xp-1.5*self.l, yp-0.5*self.l], [xp-0.5*self.l, yp-0.5*self.l], [
xp, yp], [xp-0.5*self.l, yp+0.5*self.l], [xp-1.5*self.l, yp+0.5*self.l]])
artists[0].set_xy(xy=points)
artists[1].set(x=xp-1*self.l, y=yp)
for artist in artists[3]: # update out arrows
artist.set_positions((xp, yp), None)
elif isinstance(element, bms.Variable):
artists = self.artists_from_element[element]
pos = self.position[element]
artists[0].set(x=pos[0], y=pos[1])
for artist in artists[2]: # update in arrows
artist.set_positions(None, pos)
for artist in artists[3]: # update out arrows
artist.set_positions(pos, None)
elif isinstance(element, bms.Block):
artists = self.artists_from_element[element]
pb = self.position[element][:]
hb = 0.5*(1+max(len(element.inputs), len(element.outputs)))*self.l
artists[0].set(xy=(pb[0]-0.5*self.l, pb[1]-hb/2))
artists[1].set(x=pb[0], y=pb[1])
li = len(element.inputs)
# lo=len(element.outputs)
for i in range(2, li+2):
artists[i].set_positions(
None, (pb[0]-0.5*self.l, pb[1]+hb/2-0.5*(i+1-2)*self.l))
for i in range(2+li, len(artists)):
artists[i].set_positions(
(pb[0]+0.5*self.l, pb[1]+hb/2-0.5*(i+1-2-li)*self.l), None)
plt.draw()
return True | Update text position and redraw | train | https://github.com/masfaraud/BMSpy/blob/5ac6b9539c1141dd955560afb532e6b915b77bdc/bms/interface.py#L201-L242 | null | class ModelDrawer:
def __init__(self, model):
""" Create a new drag handler and connect it to the figure's event system.
If the figure handler is not given, the current figure is used instead
"""
import matplotlib.pyplot as plt
self.l = 0.05
# plt.figure()
self.dragged = None
self.model = model
self.element_from_artist = {} # patch->block
self.artists_from_element = {}
self.noeud_clic = None
# Initialisation of positions
# networkx positionning
self.position = nx.spring_layout(self.model.graph)
# self.position={}
# # Random positionning
# for block in self.model.blocks:
# self.position[block]=[random.random(),random.random()]
# for variable in self.model.variables+self.model.signals:
# self.position[variable]=[random.random(),random.random()]
# # optimized positionning
# lx=# len
# dof={}
# # Parametrizing
# i=0
# for block in self.model.blocks:
# dof[block]=[i,i+1]
# i+=2
# for variables in self.model.variables+self.model.signals:
# dof[variables]=[i,i+1]
# i+=2
#
# print(len(list(dof.keys())))
#
# # function definition
# cp=100000# penalty coefficient
# dt=self.l*5# target distance between stuff
# def f(x,verbose=False):
# if verbose:
# print('======================')
# r=0# result
# for block in self.model.blocks:
# db=dof[block]
# # each block must have its inputs at its left
# for variable in block.inputs:
# dv=dof[variable]
# xb=x[db]
# xv=x[dv]
# if xb[0]<xv[0]:
# r+=cp*(xv[0]-xb[0])**2
# # minimize distance between block and connections
# d=math.sqrt((xb[0]-xv[0])**2+(xb[1]-xv[1])**2)
# if d>dt:
# r+=d-dt
# if verbose:
# print('dbc: ',d-dt)
# # connection must be as horizontal as possible
# if verbose:
# print('hz: ',abs(xb[1]-xv[1]))
# r+=abs(xb[1]-xv[1])
# # each block must have its outputs at its right
# for variable in block.outputs:
# dv=dof[variable]
# xb=x[db]
# xv=x[dv]
# if xb[0]>xv[0]:
# r+=cp*(xb[0]-xv[0])**2
# if verbose:
# print('output right: ',cp*(xb[0]-xv[0])**2)
#
# # minimize distance between block and connections
# d=math.sqrt((xb[0]-xv[0])**2+(xb[1]-xv[1])**2)
# if d>dt:
# r+=d-dt
# # connection must be as horizontal as possible
# r+=abs(xb[1]-xv[1])
# if verbose:
# print(abs(xb[1]-xv[1]))
#
# # Avoid closeness of elements:
# for e1,e2 in itertools.combinations(self.model.signals+self.model.blocks+self.model.variables,2):
# xe1=dof[e1]
# xe2=dof[e2]
# de12=math.sqrt((xe1[0]-xe2[0])**2+(xe1[1]-xe2[1])**2)
# if de12<dt:
# r+=abs((dt-de12)*cp)
# if verbose:
# print(abs((dt-de12)*cp))
# print(r)
# return r
#
# options={'bounds':[-50*self.l,50*self.l],'ftarget':0}#,'tolfun':1e-4,'ftarget':-ndemuls*(1-0.07),'verbose':-9}
# res=cma.fmin(f,np.random.random(2*len(list(dof.keys()))),2*dt,options=options)
# xopt=res[0]
# f_opt=-res[1]
# print(xopt)
# f(xopt,True)
# for element in self.model.signals+self.model.blocks+self.model.variables:
# de=dof[element]
# self.position[element]=(xopt[de[0]],xopt[de[1]])
# Drawing
plt.ioff()
self.fig, self.ax = plt.subplots(1, 1)
for variable in self.model.signals:
points = np.array((5, 2))
xp, yp = self.position[variable]
points = np.array([[xp-1.5*self.l, yp-0.5*self.l], [xp-0.5*self.l, yp-0.5*self.l], [
xp, yp], [xp-0.5*self.l, yp+0.5*self.l], [xp-1.5*self.l, yp+0.5*self.l]])
p = mpatches.Polygon(points, facecolor='white',
edgecolor='black', picker=10)
self.ax.add_patch(p)
t = self.ax.text(xp-1*self.l, yp, variable.short_name, color='black',
ha='center', multialignment='center', verticalalignment='center')
self.element_from_artist[p] = variable
# polygon, text, arrows in, arrows out
self.artists_from_element[variable] = [p, t, [], []]
for variable in self.model.variables:
# p=mpatches.Circle(self.position[variable],radius=0.025,facecolor='white',edgecolor='black')
# p=mpatches.FancyBboxPatch((bb.xmin, bb.ymin),2*l,l,boxstyle="round,pad=0.",ec="k", fc="none", zorder=10.)
# self.ax.add_patch(p)
pos = self.position[variable]
t = self.ax.text(pos[0], pos[1], variable.short_name, color='black', ha='center', picker=10,
multialignment='center', bbox=dict(facecolor='white', edgecolor='black', boxstyle='round'))
self.element_from_artist[t] = variable
# text,arrows in arrows out None stands for standard
self.artists_from_element[variable] = [t, None, [], []]
for block in self.model.blocks:
hb = 0.5*(1+max(len(block.inputs), len(block.outputs)))*self.l
pb = self.position[block][:]
p = mpatches.Rectangle((pb[0]-0.5*self.l, pb[1]-hb/2), height=hb,
width=self.l, edgecolor='black', facecolor='#CCCCCC', picker=10)
self.ax.add_patch(p)
t = self.ax.text(pb[0], pb[1], block.LabelBlock(
), color='black', multialignment='center', verticalalignment='center')
self.element_from_artist[p] = block
self.artists_from_element[block] = [p, t]
# Block connections
for iv, variable in enumerate(block.inputs):
pv = self.position[variable]
pcb = self.position[block][:] # Position connection on block
a = mpatches.FancyArrowPatch(
pv, (pb[0]-0.5*self.l, pb[1]+hb/2-0.5*(iv+1)*self.l), arrowstyle='-|>')
self.ax.add_patch(a)
self.artists_from_element[block].append(a)
self.artists_from_element[variable][3].append(a)
for iv, variable in enumerate(block.outputs):
pv = self.position[variable]
pb = self.position[block]
a = mpatches.FancyArrowPatch(
(pb[0]+0.5*self.l, pb[1]+hb/2-0.5*(iv+1)*self.l), pv, arrowstyle='-|>')
self.ax.add_patch(a)
self.artists_from_element[block].append(a)
self.artists_from_element[variable][2].append(a)
plt.axis('equal')
plt.margins(0.05)
# Connect events and callbacks
# self.fig.canvas.mpl_connect("button_release_event", self.on_release_event)
self.fig.canvas.mpl_connect("pick_event", self.on_pick_event)
self.fig.canvas.mpl_connect(
"button_release_event", self.on_release_event)
plt.show()
def on_pick_event(self, event):
# print(event.artist)
# print(self.artists[event.artist])
self.selected_patch = event.artist
|
dranjan/python-plyfile | examples/plot.py | plot | python | def plot(ply):
'''
Plot vertices and triangles from a PlyData instance. Assumptions:
`ply' has a 'vertex' element with 'x', 'y', and 'z'
properties;
`ply' has a 'face' element with an integral list property
'vertex_indices', all of whose elements have length 3.
'''
vertex = ply['vertex']
(x, y, z) = (vertex[t] for t in ('x', 'y', 'z'))
mlab.points3d(x, y, z, color=(1, 1, 1), mode='point')
if 'face' in ply:
tri_idx = ply['face']['vertex_indices']
idx_dtype = tri_idx[0].dtype
triangles = numpy.fromiter(tri_idx, [('data', idx_dtype, (3,))],
count=len(tri_idx))['data']
mlab.triangular_mesh(x, y, z, triangles,
color=(1, 0, 0.4), opacity=0.5) | Plot vertices and triangles from a PlyData instance. Assumptions:
`ply' has a 'vertex' element with 'x', 'y', and 'z'
properties;
`ply' has a 'face' element with an integral list property
'vertex_indices', all of whose elements have length 3. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/examples/plot.py#L27-L51 | null | '''
Example script illustrating plotting of PLY data using Mayavi. Mayavi
is not a dependency of plyfile, but you will need to install it in order
to run this script. Failing to do so will immediately result in
ImportError.
'''
from argparse import ArgumentParser
import numpy
from mayavi import mlab
from plyfile import PlyData
def main():
parser = ArgumentParser()
parser.add_argument('ply_filename')
args = parser.parse_args()
plot(PlyData.read(args.ply_filename))
mlab.show()
main()
|
dranjan/python-plyfile | plyfile.py | make2d | python | def make2d(array, cols=None, dtype=None):
'''
Make a 2D array from an array of arrays. The `cols' and `dtype'
arguments can be omitted if the array is not empty.
'''
if not len(array):
if cols is None or dtype is None:
raise RuntimeError(
"cols and dtype must be specified for empty array"
)
return _np.empty((0, cols), dtype=dtype)
return _np.vstack(array) | Make a 2D array from an array of arrays. The `cols' and `dtype'
arguments can be omitted if the array is not empty. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L91-L103 | null | # Copyright 2014 Darsh Ranjan
#
# This file is part of python-plyfile.
#
# python-plyfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# python-plyfile is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with python-plyfile. If not, see
# <http://www.gnu.org/licenses/>.
from itertools import islice as _islice
import numpy as _np
from sys import byteorder as _byteorder
try:
_range = xrange
except NameError:
_range = range
# Many-many relation
_data_type_relation = [
('int8', 'i1'),
('char', 'i1'),
('uint8', 'u1'),
('uchar', 'b1'),
('uchar', 'u1'),
('int16', 'i2'),
('short', 'i2'),
('uint16', 'u2'),
('ushort', 'u2'),
('int32', 'i4'),
('int', 'i4'),
('uint32', 'u4'),
('uint', 'u4'),
('float32', 'f4'),
('float', 'f4'),
('float64', 'f8'),
('double', 'f8')
]
_data_types = dict(_data_type_relation)
_data_type_reverse = dict((b, a) for (a, b) in _data_type_relation)
_types_list = []
_types_set = set()
for (_a, _b) in _data_type_relation:
if _a not in _types_set:
_types_list.append(_a)
_types_set.add(_a)
if _b not in _types_set:
_types_list.append(_b)
_types_set.add(_b)
_byte_order_map = {
'ascii': '=',
'binary_little_endian': '<',
'binary_big_endian': '>'
}
_byte_order_reverse = {
'<': 'binary_little_endian',
'>': 'binary_big_endian'
}
_native_byte_order = {'little': '<', 'big': '>'}[_byteorder]
def _lookup_type(type_str):
if type_str not in _data_type_reverse:
try:
type_str = _data_types[type_str]
except KeyError:
raise ValueError("field type %r not in %r" %
(type_str, _types_list))
return _data_type_reverse[type_str]
class _PlyHeaderParser(object):
def __init__(self):
self.format = None
self.elements = []
self.comments = []
self.obj_info = []
self.lines = 0
self._allowed = ['ply']
def consume(self, raw_line):
self.lines += 1
if not raw_line:
self._error("early end-of-file")
line = raw_line.decode('ascii').strip()
try:
keyword = line.split(None, 1)[0]
except IndexError:
self._error()
if keyword not in self._allowed:
self._error("expected one of {%s}" %
", ".join(self._allowed))
getattr(self, 'parse_' + keyword)(line[len(keyword)+1:])
return self._allowed
def _error(self, message="parse error"):
raise PlyHeaderParseError(message, self.lines)
def parse_ply(self, data):
if data:
self._error("unexpected characters after 'ply'")
self._allowed = ['format', 'comment', 'obj_info']
def parse_format(self, data):
fields = data.strip().split()
if len(fields) != 2:
self._error("expected \"format {format} 1.0\"")
self.format = fields[0]
if self.format not in _byte_order_map:
self._error("don't understand format %r" % format)
if fields[1] != '1.0':
self._error("expected version '1.0'")
self._allowed = ['element', 'comment', 'obj_info', 'end_header']
def parse_comment(self, data):
if not self.elements:
self.comments.append(data)
else:
self.elements[-1][3].append(data)
def parse_obj_info(self, data):
self.obj_info.append(data)
def parse_element(self, data):
fields = data.strip().split()
if len(fields) != 2:
self._error("expected \"element {name} {count}\"")
name = fields[0]
try:
count = int(fields[1])
except ValueError:
self._error("expected integer count")
self.elements.append((name, [], count, []))
self._allowed = ['element', 'comment', 'property', 'end_header']
def parse_property(self, data):
properties = self.elements[-1][1]
fields = data.strip().split()
if len(fields) < 2:
self._error("bad 'property' line")
if fields[0] == 'list':
if len(fields) != 4:
self._error("expected \"property list "
"{len_type} {val_type} {name}\"")
try:
properties.append(
PlyListProperty(fields[3], fields[1], fields[2])
)
except ValueError as e:
self._error(str(e))
else:
if len(fields) != 2:
self._error("expected \"property {type} {name}\"")
try:
properties.append(
PlyProperty(fields[1], fields[0])
)
except ValueError as e:
self._error(str(e))
def parse_end_header(self, data):
if data:
self._error("unexpected data after 'end_header'")
self._allowed = []
class PlyParseError(Exception):
'''
Base class for PLY parsing errors.
'''
pass
class PlyElementParseError(PlyParseError):
'''
Raised when a PLY element cannot be parsed.
The attributes `element', `row', `property', and `message' give
additional information.
'''
def __init__(self, message, element=None, row=None, prop=None):
self.message = message
self.element = element
self.row = row
self.prop = prop
s = ''
if self.element:
s += 'element %r: ' % self.element.name
if self.row is not None:
s += 'row %d: ' % self.row
if self.prop:
s += 'property %r: ' % self.prop.name
s += self.message
Exception.__init__(self, s)
def __repr__(self):
return ('%s(%r, element=%r, row=%r, prop=%r)' %
(self.__class__.__name__,
self.message, self.element, self.row, self.prop))
class PlyHeaderParseError(PlyParseError):
'''
Raised when a PLY header cannot be parsed.
The attribute `line' provides additional information.
'''
def __init__(self, message, line=None):
self.message = message
self.line = line
s = ''
if self.line:
s += 'line %r: ' % self.line
s += self.message
Exception.__init__(self, s)
def __repr__(self):
return ('%s(%r, line=%r)' %
(self.__class__.__name__,
self.message, self.line))
class PlyData(object):
'''
PLY file header and data.
A PlyData instance is created in one of two ways: by the static
method PlyData.read (to read a PLY file), or directly from __init__
given a sequence of elements (which can then be written to a PLY
file).
'''
def __init__(self, elements=[], text=False, byte_order='=',
comments=[], obj_info=[]):
'''
elements: sequence of PlyElement instances.
text: whether the resulting PLY file will be text (True) or
binary (False).
byte_order: '<' for little-endian, '>' for big-endian, or '='
for native. This is only relevant if `text' is False.
comments: sequence of strings that will be placed in the header
between the 'ply' and 'format ...' lines.
obj_info: like comments, but will be placed in the header with
"obj_info ..." instead of "comment ...".
'''
if byte_order == '=' and not text:
byte_order = _native_byte_order
self.byte_order = byte_order
self.text = text
self.comments = comments
self.obj_info = obj_info
self.elements = elements
def _get_elements(self):
return self._elements
def _set_elements(self, elements):
self._elements = tuple(elements)
self._index()
elements = property(_get_elements, _set_elements)
def _get_byte_order(self):
return self._byte_order
def _set_byte_order(self, byte_order):
if byte_order not in ['<', '>', '=']:
raise ValueError("byte order must be '<', '>', or '='")
self._byte_order = byte_order
byte_order = property(_get_byte_order, _set_byte_order)
def _index(self):
self._element_lookup = dict((elt.name, elt) for elt in
self._elements)
if len(self._element_lookup) != len(self._elements):
raise ValueError("two elements with same name")
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _get_obj_info(self):
return list(self._obj_info)
def _set_obj_info(self, obj_info):
_check_comments(obj_info)
self._obj_info = list(obj_info)
obj_info = property(_get_obj_info, _set_obj_info)
@staticmethod
def _parse_header(stream):
'''
Parse a PLY header from a readable file-like stream.
'''
parser = _PlyHeaderParser()
while parser.consume(stream.readline()):
pass
return PlyData(
[PlyElement(*e) for e in parser.elements],
parser.format == 'ascii',
_byte_order_map[parser.format],
parser.comments,
parser.obj_info
)
@staticmethod
def read(stream):
'''
Read PLY data from a readable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'read')
try:
data = PlyData._parse_header(stream)
for elt in data:
elt._read(stream, data.text, data.byte_order)
finally:
if must_close:
stream.close()
return data
def write(self, stream):
'''
Write PLY data to a writeable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'write')
try:
stream.write(self.header.encode('ascii'))
stream.write(b'\n')
for elt in self:
elt._write(stream, self.text, self.byte_order)
finally:
if must_close:
stream.close()
@property
def header(self):
'''
Provide PLY-formatted metadata for the instance.
'''
lines = ['ply']
if self.text:
lines.append('format ascii 1.0')
else:
lines.append('format ' +
_byte_order_reverse[self.byte_order] +
' 1.0')
# Some information is lost here, since all comments are placed
# between the 'format' line and the first element.
for c in self.comments:
lines.append('comment ' + c)
for c in self.obj_info:
lines.append('obj_info ' + c)
lines.extend(elt.header for elt in self.elements)
lines.append('end_header')
return '\n'.join(lines)
def __iter__(self):
return iter(self.elements)
def __len__(self):
return len(self.elements)
def __contains__(self, name):
return name in self._element_lookup
def __getitem__(self, name):
return self._element_lookup[name]
def __str__(self):
return self.header
def __repr__(self):
return ('PlyData(%r, text=%r, byte_order=%r, '
'comments=%r, obj_info=%r)' %
(self.elements, self.text, self.byte_order,
self.comments, self.obj_info))
def _open_stream(stream, read_or_write):
if hasattr(stream, read_or_write):
return (False, stream)
try:
return (True, open(stream, read_or_write[0] + 'b'))
except TypeError:
raise RuntimeError("expected open file or filename")
class PlyElement(object):
'''
PLY file element.
A client of this library doesn't normally need to instantiate this
directly, so the following is only for the sake of documenting the
internals.
Creating a PlyElement instance is generally done in one of two ways:
as a byproduct of PlyData.read (when reading a PLY file) and by
PlyElement.describe (before writing a PLY file).
'''
def __init__(self, name, properties, count, comments=[]):
'''
This is not part of the public interface. The preferred methods
of obtaining PlyElement instances are PlyData.read (to read from
a file) and PlyElement.describe (to construct from a numpy
array).
'''
_check_name(name)
self._name = str(name)
self._count = count
self._properties = tuple(properties)
self._index()
self.comments = comments
self._have_list = any(isinstance(p, PlyListProperty)
for p in self.properties)
@property
def count(self):
return self._count
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data
self._count = len(data)
self._check_sanity()
data = property(_get_data, _set_data)
def _check_sanity(self):
for prop in self.properties:
if prop.name not in self._data.dtype.fields:
raise ValueError("dangling property %r" % prop.name)
def _get_properties(self):
return self._properties
def _set_properties(self, properties):
self._properties = tuple(properties)
self._check_sanity()
self._index()
properties = property(_get_properties, _set_properties)
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _index(self):
self._property_lookup = dict((prop.name, prop)
for prop in self._properties)
if len(self._property_lookup) != len(self._properties):
raise ValueError("two properties with same name")
def ply_property(self, name):
return self._property_lookup[name]
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
'''
return _np.dtype([(prop.name, prop.dtype(byte_order))
for prop in self.properties])
@staticmethod
def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt
def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity()
def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data)
def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k)
def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n')
def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop)
def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order)
@property
def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __str__(self):
return self.header
def __repr__(self):
return ('PlyElement(%r, %r, count=%d, comments=%r)' %
(self.name, self.properties, self.count,
self.comments))
def _check_comments(comments):
for comment in comments:
for char in comment:
if not 0 <= ord(char) < 128:
raise ValueError("non-ASCII character in comment")
if char == '\n':
raise ValueError("embedded newline in comment")
class PlyProperty(object):
'''
PLY property description. This class is pure metadata; the data
itself is contained in PlyElement instances.
'''
def __init__(self, name, val_dtype):
_check_name(name)
self._name = str(name)
self.val_dtype = val_dtype
def _get_val_dtype(self):
return self._val_dtype
def _set_val_dtype(self, val_dtype):
self._val_dtype = _data_types[_lookup_type(val_dtype)]
val_dtype = property(_get_val_dtype, _set_val_dtype)
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype description for this property (as a tuple
of strings).
'''
return byte_order + self.val_dtype
def _from_fields(self, fields):
'''
Parse from generator. Raise StopIteration if the property could
not be read.
'''
return _np.dtype(self.dtype()).type(next(fields))
def _to_fields(self, data):
'''
Return generator over one item.
'''
yield _np.dtype(self.dtype()).type(data)
def _read_bin(self, stream, byte_order):
'''
Read data from a binary stream. Raise StopIteration if the
property could not be read.
'''
try:
return _read_array(stream, self.dtype(byte_order), 1)[0]
except IndexError:
raise StopIteration
def _write_bin(self, data, stream, byte_order):
'''
Write data to a binary stream.
'''
_write_array(stream, _np.dtype(self.dtype(byte_order)).type(data))
def __str__(self):
val_str = _data_type_reverse[self.val_dtype]
return 'property %s %s' % (val_str, self.name)
def __repr__(self):
return 'PlyProperty(%r, %r)' % (self.name,
_lookup_type(self.val_dtype))
class PlyListProperty(PlyProperty):
'''
PLY list property description.
'''
def __init__(self, name, len_dtype, val_dtype):
PlyProperty.__init__(self, name, val_dtype)
self.len_dtype = len_dtype
def _get_len_dtype(self):
return self._len_dtype
def _set_len_dtype(self, len_dtype):
self._len_dtype = _data_types[_lookup_type(len_dtype)]
len_dtype = property(_get_len_dtype, _set_len_dtype)
def dtype(self, byte_order='='):
'''
List properties always have a numpy dtype of "object".
'''
return '|O'
def list_dtype(self, byte_order='='):
'''
Return the pair (len_dtype, val_dtype) (both numpy-friendly
strings).
'''
return (byte_order + self.len_dtype,
byte_order + self.val_dtype)
def _from_fields(self, fields):
(len_t, val_t) = self.list_dtype()
n = int(_np.dtype(len_t).type(next(fields)))
data = _np.loadtxt(list(_islice(fields, n)), val_t, ndmin=1)
if len(data) < n:
raise StopIteration
return data
def _to_fields(self, data):
'''
Return generator over the (numerical) PLY representation of the
list data (length followed by actual data).
'''
(len_t, val_t) = self.list_dtype()
data = _np.asarray(data, dtype=val_t).ravel()
yield _np.dtype(len_t).type(data.size)
for x in data:
yield x
def _read_bin(self, stream, byte_order):
(len_t, val_t) = self.list_dtype(byte_order)
try:
n = _read_array(stream, _np.dtype(len_t), 1)[0]
except IndexError:
raise StopIteration
data = _read_array(stream, _np.dtype(val_t), n)
if len(data) < n:
raise StopIteration
return data
def _write_bin(self, data, stream, byte_order):
'''
Write data to a binary stream.
'''
(len_t, val_t) = self.list_dtype(byte_order)
data = _np.asarray(data, dtype=val_t).ravel()
_write_array(stream, _np.array(data.size, dtype=len_t))
_write_array(stream, data)
def __str__(self):
len_str = _data_type_reverse[self.len_dtype]
val_str = _data_type_reverse[self.val_dtype]
return 'property list %s %s %s' % (len_str, val_str, self.name)
def __repr__(self):
return ('PlyListProperty(%r, %r, %r)' %
(self.name,
_lookup_type(self.len_dtype),
_lookup_type(self.val_dtype)))
def _check_name(name):
for char in name:
if not 0 <= ord(char) < 128:
raise ValueError("non-ASCII character in name %r" % name)
if char.isspace():
raise ValueError("space character(s) in name %r" % name)
def _read_array(stream, dtype, n):
try:
size = int(_np.dtype(dtype).itemsize * n)
return _np.frombuffer(stream.read(size), dtype)
except Exception:
raise StopIteration
def _write_array(stream, array):
stream.write(array.tostring())
def _can_mmap(stream):
try:
pos = stream.tell()
try:
_np.memmap(stream, 'u1', 'c')
stream.seek(pos)
return True
except Exception as e:
stream.seek(pos)
return False
except Exception as e:
return False
|
dranjan/python-plyfile | plyfile.py | PlyData._parse_header | python | def _parse_header(stream):
'''
Parse a PLY header from a readable file-like stream.
'''
parser = _PlyHeaderParser()
while parser.consume(stream.readline()):
pass
return PlyData(
[PlyElement(*e) for e in parser.elements],
parser.format == 'ascii',
_byte_order_map[parser.format],
parser.comments,
parser.obj_info
) | Parse a PLY header from a readable file-like stream. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L367-L382 | [
"def consume(self, raw_line):\n self.lines += 1\n if not raw_line:\n self._error(\"early end-of-file\")\n\n line = raw_line.decode('ascii').strip()\n try:\n keyword = line.split(None, 1)[0]\n except IndexError:\n self._error()\n\n if keyword not in self._allowed:\n self._error(\"expected one of {%s}\" %\n \", \".join(self._allowed))\n\n getattr(self, 'parse_' + keyword)(line[len(keyword)+1:])\n return self._allowed\n"
] | class PlyData(object):
'''
PLY file header and data.
A PlyData instance is created in one of two ways: by the static
method PlyData.read (to read a PLY file), or directly from __init__
given a sequence of elements (which can then be written to a PLY
file).
'''
def __init__(self, elements=[], text=False, byte_order='=',
comments=[], obj_info=[]):
'''
elements: sequence of PlyElement instances.
text: whether the resulting PLY file will be text (True) or
binary (False).
byte_order: '<' for little-endian, '>' for big-endian, or '='
for native. This is only relevant if `text' is False.
comments: sequence of strings that will be placed in the header
between the 'ply' and 'format ...' lines.
obj_info: like comments, but will be placed in the header with
"obj_info ..." instead of "comment ...".
'''
if byte_order == '=' and not text:
byte_order = _native_byte_order
self.byte_order = byte_order
self.text = text
self.comments = comments
self.obj_info = obj_info
self.elements = elements
def _get_elements(self):
return self._elements
def _set_elements(self, elements):
self._elements = tuple(elements)
self._index()
elements = property(_get_elements, _set_elements)
def _get_byte_order(self):
return self._byte_order
def _set_byte_order(self, byte_order):
if byte_order not in ['<', '>', '=']:
raise ValueError("byte order must be '<', '>', or '='")
self._byte_order = byte_order
byte_order = property(_get_byte_order, _set_byte_order)
def _index(self):
self._element_lookup = dict((elt.name, elt) for elt in
self._elements)
if len(self._element_lookup) != len(self._elements):
raise ValueError("two elements with same name")
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _get_obj_info(self):
return list(self._obj_info)
def _set_obj_info(self, obj_info):
_check_comments(obj_info)
self._obj_info = list(obj_info)
obj_info = property(_get_obj_info, _set_obj_info)
@staticmethod
@staticmethod
def read(stream):
'''
Read PLY data from a readable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'read')
try:
data = PlyData._parse_header(stream)
for elt in data:
elt._read(stream, data.text, data.byte_order)
finally:
if must_close:
stream.close()
return data
def write(self, stream):
'''
Write PLY data to a writeable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'write')
try:
stream.write(self.header.encode('ascii'))
stream.write(b'\n')
for elt in self:
elt._write(stream, self.text, self.byte_order)
finally:
if must_close:
stream.close()
@property
def header(self):
'''
Provide PLY-formatted metadata for the instance.
'''
lines = ['ply']
if self.text:
lines.append('format ascii 1.0')
else:
lines.append('format ' +
_byte_order_reverse[self.byte_order] +
' 1.0')
# Some information is lost here, since all comments are placed
# between the 'format' line and the first element.
for c in self.comments:
lines.append('comment ' + c)
for c in self.obj_info:
lines.append('obj_info ' + c)
lines.extend(elt.header for elt in self.elements)
lines.append('end_header')
return '\n'.join(lines)
def __iter__(self):
return iter(self.elements)
def __len__(self):
return len(self.elements)
def __contains__(self, name):
return name in self._element_lookup
def __getitem__(self, name):
return self._element_lookup[name]
def __str__(self):
return self.header
def __repr__(self):
return ('PlyData(%r, text=%r, byte_order=%r, '
'comments=%r, obj_info=%r)' %
(self.elements, self.text, self.byte_order,
self.comments, self.obj_info))
|
dranjan/python-plyfile | plyfile.py | PlyData.read | python | def read(stream):
'''
Read PLY data from a readable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'read')
try:
data = PlyData._parse_header(stream)
for elt in data:
elt._read(stream, data.text, data.byte_order)
finally:
if must_close:
stream.close()
return data | Read PLY data from a readable file-like object or filename. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L385-L399 | [
"def _open_stream(stream, read_or_write):\n if hasattr(stream, read_or_write):\n return (False, stream)\n try:\n return (True, open(stream, read_or_write[0] + 'b'))\n except TypeError:\n raise RuntimeError(\"expected open file or filename\")\n",
"def _parse_header(stream):\n '''\n Parse a PLY header from a readable file-like stream.\n\n '''\n parser = _PlyHeaderParser()\n while parser.consume(stream.readline()):\n pass\n\n return PlyData(\n [PlyElement(*e) for e in parser.elements],\n parser.format == 'ascii',\n _byte_order_map[parser.format],\n parser.comments,\n parser.obj_info\n )\n"
] | class PlyData(object):
'''
PLY file header and data.
A PlyData instance is created in one of two ways: by the static
method PlyData.read (to read a PLY file), or directly from __init__
given a sequence of elements (which can then be written to a PLY
file).
'''
def __init__(self, elements=[], text=False, byte_order='=',
comments=[], obj_info=[]):
'''
elements: sequence of PlyElement instances.
text: whether the resulting PLY file will be text (True) or
binary (False).
byte_order: '<' for little-endian, '>' for big-endian, or '='
for native. This is only relevant if `text' is False.
comments: sequence of strings that will be placed in the header
between the 'ply' and 'format ...' lines.
obj_info: like comments, but will be placed in the header with
"obj_info ..." instead of "comment ...".
'''
if byte_order == '=' and not text:
byte_order = _native_byte_order
self.byte_order = byte_order
self.text = text
self.comments = comments
self.obj_info = obj_info
self.elements = elements
def _get_elements(self):
return self._elements
def _set_elements(self, elements):
self._elements = tuple(elements)
self._index()
elements = property(_get_elements, _set_elements)
def _get_byte_order(self):
return self._byte_order
def _set_byte_order(self, byte_order):
if byte_order not in ['<', '>', '=']:
raise ValueError("byte order must be '<', '>', or '='")
self._byte_order = byte_order
byte_order = property(_get_byte_order, _set_byte_order)
def _index(self):
self._element_lookup = dict((elt.name, elt) for elt in
self._elements)
if len(self._element_lookup) != len(self._elements):
raise ValueError("two elements with same name")
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _get_obj_info(self):
return list(self._obj_info)
def _set_obj_info(self, obj_info):
_check_comments(obj_info)
self._obj_info = list(obj_info)
obj_info = property(_get_obj_info, _set_obj_info)
@staticmethod
def _parse_header(stream):
'''
Parse a PLY header from a readable file-like stream.
'''
parser = _PlyHeaderParser()
while parser.consume(stream.readline()):
pass
return PlyData(
[PlyElement(*e) for e in parser.elements],
parser.format == 'ascii',
_byte_order_map[parser.format],
parser.comments,
parser.obj_info
)
@staticmethod
def write(self, stream):
'''
Write PLY data to a writeable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'write')
try:
stream.write(self.header.encode('ascii'))
stream.write(b'\n')
for elt in self:
elt._write(stream, self.text, self.byte_order)
finally:
if must_close:
stream.close()
@property
def header(self):
'''
Provide PLY-formatted metadata for the instance.
'''
lines = ['ply']
if self.text:
lines.append('format ascii 1.0')
else:
lines.append('format ' +
_byte_order_reverse[self.byte_order] +
' 1.0')
# Some information is lost here, since all comments are placed
# between the 'format' line and the first element.
for c in self.comments:
lines.append('comment ' + c)
for c in self.obj_info:
lines.append('obj_info ' + c)
lines.extend(elt.header for elt in self.elements)
lines.append('end_header')
return '\n'.join(lines)
def __iter__(self):
return iter(self.elements)
def __len__(self):
return len(self.elements)
def __contains__(self, name):
return name in self._element_lookup
def __getitem__(self, name):
return self._element_lookup[name]
def __str__(self):
return self.header
def __repr__(self):
return ('PlyData(%r, text=%r, byte_order=%r, '
'comments=%r, obj_info=%r)' %
(self.elements, self.text, self.byte_order,
self.comments, self.obj_info))
|
dranjan/python-plyfile | plyfile.py | PlyData.write | python | def write(self, stream):
'''
Write PLY data to a writeable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'write')
try:
stream.write(self.header.encode('ascii'))
stream.write(b'\n')
for elt in self:
elt._write(stream, self.text, self.byte_order)
finally:
if must_close:
stream.close() | Write PLY data to a writeable file-like object or filename. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L401-L414 | [
"def _open_stream(stream, read_or_write):\n if hasattr(stream, read_or_write):\n return (False, stream)\n try:\n return (True, open(stream, read_or_write[0] + 'b'))\n except TypeError:\n raise RuntimeError(\"expected open file or filename\")\n"
] | class PlyData(object):
'''
PLY file header and data.
A PlyData instance is created in one of two ways: by the static
method PlyData.read (to read a PLY file), or directly from __init__
given a sequence of elements (which can then be written to a PLY
file).
'''
def __init__(self, elements=[], text=False, byte_order='=',
comments=[], obj_info=[]):
'''
elements: sequence of PlyElement instances.
text: whether the resulting PLY file will be text (True) or
binary (False).
byte_order: '<' for little-endian, '>' for big-endian, or '='
for native. This is only relevant if `text' is False.
comments: sequence of strings that will be placed in the header
between the 'ply' and 'format ...' lines.
obj_info: like comments, but will be placed in the header with
"obj_info ..." instead of "comment ...".
'''
if byte_order == '=' and not text:
byte_order = _native_byte_order
self.byte_order = byte_order
self.text = text
self.comments = comments
self.obj_info = obj_info
self.elements = elements
def _get_elements(self):
return self._elements
def _set_elements(self, elements):
self._elements = tuple(elements)
self._index()
elements = property(_get_elements, _set_elements)
def _get_byte_order(self):
return self._byte_order
def _set_byte_order(self, byte_order):
if byte_order not in ['<', '>', '=']:
raise ValueError("byte order must be '<', '>', or '='")
self._byte_order = byte_order
byte_order = property(_get_byte_order, _set_byte_order)
def _index(self):
self._element_lookup = dict((elt.name, elt) for elt in
self._elements)
if len(self._element_lookup) != len(self._elements):
raise ValueError("two elements with same name")
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _get_obj_info(self):
return list(self._obj_info)
def _set_obj_info(self, obj_info):
_check_comments(obj_info)
self._obj_info = list(obj_info)
obj_info = property(_get_obj_info, _set_obj_info)
@staticmethod
def _parse_header(stream):
'''
Parse a PLY header from a readable file-like stream.
'''
parser = _PlyHeaderParser()
while parser.consume(stream.readline()):
pass
return PlyData(
[PlyElement(*e) for e in parser.elements],
parser.format == 'ascii',
_byte_order_map[parser.format],
parser.comments,
parser.obj_info
)
@staticmethod
def read(stream):
'''
Read PLY data from a readable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'read')
try:
data = PlyData._parse_header(stream)
for elt in data:
elt._read(stream, data.text, data.byte_order)
finally:
if must_close:
stream.close()
return data
@property
def header(self):
'''
Provide PLY-formatted metadata for the instance.
'''
lines = ['ply']
if self.text:
lines.append('format ascii 1.0')
else:
lines.append('format ' +
_byte_order_reverse[self.byte_order] +
' 1.0')
# Some information is lost here, since all comments are placed
# between the 'format' line and the first element.
for c in self.comments:
lines.append('comment ' + c)
for c in self.obj_info:
lines.append('obj_info ' + c)
lines.extend(elt.header for elt in self.elements)
lines.append('end_header')
return '\n'.join(lines)
def __iter__(self):
return iter(self.elements)
def __len__(self):
return len(self.elements)
def __contains__(self, name):
return name in self._element_lookup
def __getitem__(self, name):
return self._element_lookup[name]
def __str__(self):
return self.header
def __repr__(self):
return ('PlyData(%r, text=%r, byte_order=%r, '
'comments=%r, obj_info=%r)' %
(self.elements, self.text, self.byte_order,
self.comments, self.obj_info))
|
dranjan/python-plyfile | plyfile.py | PlyData.header | python | def header(self):
'''
Provide PLY-formatted metadata for the instance.
'''
lines = ['ply']
if self.text:
lines.append('format ascii 1.0')
else:
lines.append('format ' +
_byte_order_reverse[self.byte_order] +
' 1.0')
# Some information is lost here, since all comments are placed
# between the 'format' line and the first element.
for c in self.comments:
lines.append('comment ' + c)
for c in self.obj_info:
lines.append('obj_info ' + c)
lines.extend(elt.header for elt in self.elements)
lines.append('end_header')
return '\n'.join(lines) | Provide PLY-formatted metadata for the instance. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L417-L441 | null | class PlyData(object):
'''
PLY file header and data.
A PlyData instance is created in one of two ways: by the static
method PlyData.read (to read a PLY file), or directly from __init__
given a sequence of elements (which can then be written to a PLY
file).
'''
def __init__(self, elements=[], text=False, byte_order='=',
comments=[], obj_info=[]):
'''
elements: sequence of PlyElement instances.
text: whether the resulting PLY file will be text (True) or
binary (False).
byte_order: '<' for little-endian, '>' for big-endian, or '='
for native. This is only relevant if `text' is False.
comments: sequence of strings that will be placed in the header
between the 'ply' and 'format ...' lines.
obj_info: like comments, but will be placed in the header with
"obj_info ..." instead of "comment ...".
'''
if byte_order == '=' and not text:
byte_order = _native_byte_order
self.byte_order = byte_order
self.text = text
self.comments = comments
self.obj_info = obj_info
self.elements = elements
def _get_elements(self):
return self._elements
def _set_elements(self, elements):
self._elements = tuple(elements)
self._index()
elements = property(_get_elements, _set_elements)
def _get_byte_order(self):
return self._byte_order
def _set_byte_order(self, byte_order):
if byte_order not in ['<', '>', '=']:
raise ValueError("byte order must be '<', '>', or '='")
self._byte_order = byte_order
byte_order = property(_get_byte_order, _set_byte_order)
def _index(self):
self._element_lookup = dict((elt.name, elt) for elt in
self._elements)
if len(self._element_lookup) != len(self._elements):
raise ValueError("two elements with same name")
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _get_obj_info(self):
return list(self._obj_info)
def _set_obj_info(self, obj_info):
_check_comments(obj_info)
self._obj_info = list(obj_info)
obj_info = property(_get_obj_info, _set_obj_info)
@staticmethod
def _parse_header(stream):
'''
Parse a PLY header from a readable file-like stream.
'''
parser = _PlyHeaderParser()
while parser.consume(stream.readline()):
pass
return PlyData(
[PlyElement(*e) for e in parser.elements],
parser.format == 'ascii',
_byte_order_map[parser.format],
parser.comments,
parser.obj_info
)
@staticmethod
def read(stream):
'''
Read PLY data from a readable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'read')
try:
data = PlyData._parse_header(stream)
for elt in data:
elt._read(stream, data.text, data.byte_order)
finally:
if must_close:
stream.close()
return data
def write(self, stream):
'''
Write PLY data to a writeable file-like object or filename.
'''
(must_close, stream) = _open_stream(stream, 'write')
try:
stream.write(self.header.encode('ascii'))
stream.write(b'\n')
for elt in self:
elt._write(stream, self.text, self.byte_order)
finally:
if must_close:
stream.close()
@property
def __iter__(self):
return iter(self.elements)
def __len__(self):
return len(self.elements)
def __contains__(self, name):
return name in self._element_lookup
def __getitem__(self, name):
return self._element_lookup[name]
def __str__(self):
return self.header
def __repr__(self):
return ('PlyData(%r, text=%r, byte_order=%r, '
'comments=%r, obj_info=%r)' %
(self.elements, self.text, self.byte_order,
self.comments, self.obj_info))
|
dranjan/python-plyfile | plyfile.py | PlyElement.dtype | python | def dtype(self, byte_order='='):
'''
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
'''
return _np.dtype([(prop.name, prop.dtype(byte_order))
for prop in self.properties]) | Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.) | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L560-L569 | null | class PlyElement(object):
'''
PLY file element.
A client of this library doesn't normally need to instantiate this
directly, so the following is only for the sake of documenting the
internals.
Creating a PlyElement instance is generally done in one of two ways:
as a byproduct of PlyData.read (when reading a PLY file) and by
PlyElement.describe (before writing a PLY file).
'''
def __init__(self, name, properties, count, comments=[]):
'''
This is not part of the public interface. The preferred methods
of obtaining PlyElement instances are PlyData.read (to read from
a file) and PlyElement.describe (to construct from a numpy
array).
'''
_check_name(name)
self._name = str(name)
self._count = count
self._properties = tuple(properties)
self._index()
self.comments = comments
self._have_list = any(isinstance(p, PlyListProperty)
for p in self.properties)
@property
def count(self):
return self._count
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data
self._count = len(data)
self._check_sanity()
data = property(_get_data, _set_data)
def _check_sanity(self):
for prop in self.properties:
if prop.name not in self._data.dtype.fields:
raise ValueError("dangling property %r" % prop.name)
def _get_properties(self):
return self._properties
def _set_properties(self, properties):
self._properties = tuple(properties)
self._check_sanity()
self._index()
properties = property(_get_properties, _set_properties)
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _index(self):
self._property_lookup = dict((prop.name, prop)
for prop in self._properties)
if len(self._property_lookup) != len(self._properties):
raise ValueError("two properties with same name")
def ply_property(self, name):
return self._property_lookup[name]
@property
def name(self):
return self._name
@staticmethod
def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt
def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity()
def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data)
def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k)
def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n')
def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop)
def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order)
@property
def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __str__(self):
return self.header
def __repr__(self):
return ('PlyElement(%r, %r, count=%d, comments=%r)' %
(self.name, self.properties, self.count,
self.comments))
|
dranjan/python-plyfile | plyfile.py | PlyElement.describe | python | def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt | Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer). | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L572-L630 | null | class PlyElement(object):
'''
PLY file element.
A client of this library doesn't normally need to instantiate this
directly, so the following is only for the sake of documenting the
internals.
Creating a PlyElement instance is generally done in one of two ways:
as a byproduct of PlyData.read (when reading a PLY file) and by
PlyElement.describe (before writing a PLY file).
'''
def __init__(self, name, properties, count, comments=[]):
'''
This is not part of the public interface. The preferred methods
of obtaining PlyElement instances are PlyData.read (to read from
a file) and PlyElement.describe (to construct from a numpy
array).
'''
_check_name(name)
self._name = str(name)
self._count = count
self._properties = tuple(properties)
self._index()
self.comments = comments
self._have_list = any(isinstance(p, PlyListProperty)
for p in self.properties)
@property
def count(self):
return self._count
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data
self._count = len(data)
self._check_sanity()
data = property(_get_data, _set_data)
def _check_sanity(self):
for prop in self.properties:
if prop.name not in self._data.dtype.fields:
raise ValueError("dangling property %r" % prop.name)
def _get_properties(self):
return self._properties
def _set_properties(self, properties):
self._properties = tuple(properties)
self._check_sanity()
self._index()
properties = property(_get_properties, _set_properties)
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _index(self):
self._property_lookup = dict((prop.name, prop)
for prop in self._properties)
if len(self._property_lookup) != len(self._properties):
raise ValueError("two properties with same name")
def ply_property(self, name):
return self._property_lookup[name]
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
'''
return _np.dtype([(prop.name, prop.dtype(byte_order))
for prop in self.properties])
@staticmethod
def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity()
def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data)
def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k)
def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n')
def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop)
def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order)
@property
def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __str__(self):
return self.header
def __repr__(self):
return ('PlyElement(%r, %r, count=%d, comments=%r)' %
(self.name, self.properties, self.count,
self.comments))
|
dranjan/python-plyfile | plyfile.py | PlyElement._read | python | def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity() | Read the actual data from a PLY file. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L632-L658 | null | class PlyElement(object):
'''
PLY file element.
A client of this library doesn't normally need to instantiate this
directly, so the following is only for the sake of documenting the
internals.
Creating a PlyElement instance is generally done in one of two ways:
as a byproduct of PlyData.read (when reading a PLY file) and by
PlyElement.describe (before writing a PLY file).
'''
def __init__(self, name, properties, count, comments=[]):
'''
This is not part of the public interface. The preferred methods
of obtaining PlyElement instances are PlyData.read (to read from
a file) and PlyElement.describe (to construct from a numpy
array).
'''
_check_name(name)
self._name = str(name)
self._count = count
self._properties = tuple(properties)
self._index()
self.comments = comments
self._have_list = any(isinstance(p, PlyListProperty)
for p in self.properties)
@property
def count(self):
return self._count
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data
self._count = len(data)
self._check_sanity()
data = property(_get_data, _set_data)
def _check_sanity(self):
for prop in self.properties:
if prop.name not in self._data.dtype.fields:
raise ValueError("dangling property %r" % prop.name)
def _get_properties(self):
return self._properties
def _set_properties(self, properties):
self._properties = tuple(properties)
self._check_sanity()
self._index()
properties = property(_get_properties, _set_properties)
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _index(self):
self._property_lookup = dict((prop.name, prop)
for prop in self._properties)
if len(self._property_lookup) != len(self._properties):
raise ValueError("two properties with same name")
def ply_property(self, name):
return self._property_lookup[name]
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
'''
return _np.dtype([(prop.name, prop.dtype(byte_order))
for prop in self.properties])
@staticmethod
def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt
def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data)
def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k)
def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n')
def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop)
def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order)
@property
def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __str__(self):
return self.header
def __repr__(self):
return ('PlyElement(%r, %r, count=%d, comments=%r)' %
(self.name, self.properties, self.count,
self.comments))
|
dranjan/python-plyfile | plyfile.py | PlyElement._write | python | def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data) | Write the data to a PLY file. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L660-L676 | null | class PlyElement(object):
'''
PLY file element.
A client of this library doesn't normally need to instantiate this
directly, so the following is only for the sake of documenting the
internals.
Creating a PlyElement instance is generally done in one of two ways:
as a byproduct of PlyData.read (when reading a PLY file) and by
PlyElement.describe (before writing a PLY file).
'''
def __init__(self, name, properties, count, comments=[]):
'''
This is not part of the public interface. The preferred methods
of obtaining PlyElement instances are PlyData.read (to read from
a file) and PlyElement.describe (to construct from a numpy
array).
'''
_check_name(name)
self._name = str(name)
self._count = count
self._properties = tuple(properties)
self._index()
self.comments = comments
self._have_list = any(isinstance(p, PlyListProperty)
for p in self.properties)
@property
def count(self):
return self._count
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data
self._count = len(data)
self._check_sanity()
data = property(_get_data, _set_data)
def _check_sanity(self):
for prop in self.properties:
if prop.name not in self._data.dtype.fields:
raise ValueError("dangling property %r" % prop.name)
def _get_properties(self):
return self._properties
def _set_properties(self, properties):
self._properties = tuple(properties)
self._check_sanity()
self._index()
properties = property(_get_properties, _set_properties)
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _index(self):
self._property_lookup = dict((prop.name, prop)
for prop in self._properties)
if len(self._property_lookup) != len(self._properties):
raise ValueError("two properties with same name")
def ply_property(self, name):
return self._property_lookup[name]
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
'''
return _np.dtype([(prop.name, prop.dtype(byte_order))
for prop in self.properties])
@staticmethod
def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt
def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity()
def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k)
def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n')
def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop)
def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order)
@property
def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __str__(self):
return self.header
def __repr__(self):
return ('PlyElement(%r, %r, count=%d, comments=%r)' %
(self.name, self.properties, self.count,
self.comments))
|
dranjan/python-plyfile | plyfile.py | PlyElement._read_txt | python | def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k) | Load a PLY element from an ASCII-format PLY file. The element
may contain list properties. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L678-L709 | null | class PlyElement(object):
'''
PLY file element.
A client of this library doesn't normally need to instantiate this
directly, so the following is only for the sake of documenting the
internals.
Creating a PlyElement instance is generally done in one of two ways:
as a byproduct of PlyData.read (when reading a PLY file) and by
PlyElement.describe (before writing a PLY file).
'''
def __init__(self, name, properties, count, comments=[]):
'''
This is not part of the public interface. The preferred methods
of obtaining PlyElement instances are PlyData.read (to read from
a file) and PlyElement.describe (to construct from a numpy
array).
'''
_check_name(name)
self._name = str(name)
self._count = count
self._properties = tuple(properties)
self._index()
self.comments = comments
self._have_list = any(isinstance(p, PlyListProperty)
for p in self.properties)
@property
def count(self):
return self._count
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data
self._count = len(data)
self._check_sanity()
data = property(_get_data, _set_data)
def _check_sanity(self):
for prop in self.properties:
if prop.name not in self._data.dtype.fields:
raise ValueError("dangling property %r" % prop.name)
def _get_properties(self):
return self._properties
def _set_properties(self, properties):
self._properties = tuple(properties)
self._check_sanity()
self._index()
properties = property(_get_properties, _set_properties)
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _index(self):
self._property_lookup = dict((prop.name, prop)
for prop in self._properties)
if len(self._property_lookup) != len(self._properties):
raise ValueError("two properties with same name")
def ply_property(self, name):
return self._property_lookup[name]
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
'''
return _np.dtype([(prop.name, prop.dtype(byte_order))
for prop in self.properties])
@staticmethod
def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt
def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity()
def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data)
def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n')
def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop)
def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order)
@property
def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __str__(self):
return self.header
def __repr__(self):
return ('PlyElement(%r, %r, count=%d, comments=%r)' %
(self.name, self.properties, self.count,
self.comments))
|
dranjan/python-plyfile | plyfile.py | PlyElement._write_txt | python | def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n') | Save a PLY element to an ASCII-format PLY file. The element may
contain list properties. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L711-L722 | null | class PlyElement(object):
'''
PLY file element.
A client of this library doesn't normally need to instantiate this
directly, so the following is only for the sake of documenting the
internals.
Creating a PlyElement instance is generally done in one of two ways:
as a byproduct of PlyData.read (when reading a PLY file) and by
PlyElement.describe (before writing a PLY file).
'''
def __init__(self, name, properties, count, comments=[]):
'''
This is not part of the public interface. The preferred methods
of obtaining PlyElement instances are PlyData.read (to read from
a file) and PlyElement.describe (to construct from a numpy
array).
'''
_check_name(name)
self._name = str(name)
self._count = count
self._properties = tuple(properties)
self._index()
self.comments = comments
self._have_list = any(isinstance(p, PlyListProperty)
for p in self.properties)
@property
def count(self):
return self._count
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data
self._count = len(data)
self._check_sanity()
data = property(_get_data, _set_data)
def _check_sanity(self):
for prop in self.properties:
if prop.name not in self._data.dtype.fields:
raise ValueError("dangling property %r" % prop.name)
def _get_properties(self):
return self._properties
def _set_properties(self, properties):
self._properties = tuple(properties)
self._check_sanity()
self._index()
properties = property(_get_properties, _set_properties)
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _index(self):
self._property_lookup = dict((prop.name, prop)
for prop in self._properties)
if len(self._property_lookup) != len(self._properties):
raise ValueError("two properties with same name")
def ply_property(self, name):
return self._property_lookup[name]
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
'''
return _np.dtype([(prop.name, prop.dtype(byte_order))
for prop in self.properties])
@staticmethod
def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt
def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity()
def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data)
def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k)
def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop)
def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order)
@property
def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __str__(self):
return self.header
def __repr__(self):
return ('PlyElement(%r, %r, count=%d, comments=%r)' %
(self.name, self.properties, self.count,
self.comments))
|
dranjan/python-plyfile | plyfile.py | PlyElement._read_bin | python | def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop) | Load a PLY element from a binary PLY file. The element may
contain list properties. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L724-L739 | null | class PlyElement(object):
'''
PLY file element.
A client of this library doesn't normally need to instantiate this
directly, so the following is only for the sake of documenting the
internals.
Creating a PlyElement instance is generally done in one of two ways:
as a byproduct of PlyData.read (when reading a PLY file) and by
PlyElement.describe (before writing a PLY file).
'''
def __init__(self, name, properties, count, comments=[]):
'''
This is not part of the public interface. The preferred methods
of obtaining PlyElement instances are PlyData.read (to read from
a file) and PlyElement.describe (to construct from a numpy
array).
'''
_check_name(name)
self._name = str(name)
self._count = count
self._properties = tuple(properties)
self._index()
self.comments = comments
self._have_list = any(isinstance(p, PlyListProperty)
for p in self.properties)
@property
def count(self):
return self._count
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data
self._count = len(data)
self._check_sanity()
data = property(_get_data, _set_data)
def _check_sanity(self):
for prop in self.properties:
if prop.name not in self._data.dtype.fields:
raise ValueError("dangling property %r" % prop.name)
def _get_properties(self):
return self._properties
def _set_properties(self, properties):
self._properties = tuple(properties)
self._check_sanity()
self._index()
properties = property(_get_properties, _set_properties)
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _index(self):
self._property_lookup = dict((prop.name, prop)
for prop in self._properties)
if len(self._property_lookup) != len(self._properties):
raise ValueError("two properties with same name")
def ply_property(self, name):
return self._property_lookup[name]
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
'''
return _np.dtype([(prop.name, prop.dtype(byte_order))
for prop in self.properties])
@staticmethod
def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt
def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity()
def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data)
def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k)
def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n')
def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order)
@property
def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __str__(self):
return self.header
def __repr__(self):
return ('PlyElement(%r, %r, count=%d, comments=%r)' %
(self.name, self.properties, self.count,
self.comments))
|
dranjan/python-plyfile | plyfile.py | PlyElement._write_bin | python | def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order) | Save a PLY element to a binary PLY file. The element may
contain list properties. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L741-L749 | null | class PlyElement(object):
'''
PLY file element.
A client of this library doesn't normally need to instantiate this
directly, so the following is only for the sake of documenting the
internals.
Creating a PlyElement instance is generally done in one of two ways:
as a byproduct of PlyData.read (when reading a PLY file) and by
PlyElement.describe (before writing a PLY file).
'''
def __init__(self, name, properties, count, comments=[]):
'''
This is not part of the public interface. The preferred methods
of obtaining PlyElement instances are PlyData.read (to read from
a file) and PlyElement.describe (to construct from a numpy
array).
'''
_check_name(name)
self._name = str(name)
self._count = count
self._properties = tuple(properties)
self._index()
self.comments = comments
self._have_list = any(isinstance(p, PlyListProperty)
for p in self.properties)
@property
def count(self):
return self._count
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data
self._count = len(data)
self._check_sanity()
data = property(_get_data, _set_data)
def _check_sanity(self):
for prop in self.properties:
if prop.name not in self._data.dtype.fields:
raise ValueError("dangling property %r" % prop.name)
def _get_properties(self):
return self._properties
def _set_properties(self, properties):
self._properties = tuple(properties)
self._check_sanity()
self._index()
properties = property(_get_properties, _set_properties)
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _index(self):
self._property_lookup = dict((prop.name, prop)
for prop in self._properties)
if len(self._property_lookup) != len(self._properties):
raise ValueError("two properties with same name")
def ply_property(self, name):
return self._property_lookup[name]
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
'''
return _np.dtype([(prop.name, prop.dtype(byte_order))
for prop in self.properties])
@staticmethod
def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt
def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity()
def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data)
def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k)
def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n')
def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop)
@property
def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __str__(self):
return self.header
def __repr__(self):
return ('PlyElement(%r, %r, count=%d, comments=%r)' %
(self.name, self.properties, self.count,
self.comments))
|
dranjan/python-plyfile | plyfile.py | PlyElement.header | python | def header(self):
'''
Format this element's metadata as it would appear in a PLY
header.
'''
lines = ['element %s %d' % (self.name, self.count)]
# Some information is lost here, since all comments are placed
# between the 'element' line and the first property definition.
for c in self.comments:
lines.append('comment ' + c)
lines.extend(list(map(str, self.properties)))
return '\n'.join(lines) | Format this element's metadata as it would appear in a PLY
header. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L752-L767 | null | class PlyElement(object):
'''
PLY file element.
A client of this library doesn't normally need to instantiate this
directly, so the following is only for the sake of documenting the
internals.
Creating a PlyElement instance is generally done in one of two ways:
as a byproduct of PlyData.read (when reading a PLY file) and by
PlyElement.describe (before writing a PLY file).
'''
def __init__(self, name, properties, count, comments=[]):
'''
This is not part of the public interface. The preferred methods
of obtaining PlyElement instances are PlyData.read (to read from
a file) and PlyElement.describe (to construct from a numpy
array).
'''
_check_name(name)
self._name = str(name)
self._count = count
self._properties = tuple(properties)
self._index()
self.comments = comments
self._have_list = any(isinstance(p, PlyListProperty)
for p in self.properties)
@property
def count(self):
return self._count
def _get_data(self):
return self._data
def _set_data(self, data):
self._data = data
self._count = len(data)
self._check_sanity()
data = property(_get_data, _set_data)
def _check_sanity(self):
for prop in self.properties:
if prop.name not in self._data.dtype.fields:
raise ValueError("dangling property %r" % prop.name)
def _get_properties(self):
return self._properties
def _set_properties(self, properties):
self._properties = tuple(properties)
self._check_sanity()
self._index()
properties = property(_get_properties, _set_properties)
def _get_comments(self):
return list(self._comments)
def _set_comments(self, comments):
_check_comments(comments)
self._comments = list(comments)
comments = property(_get_comments, _set_comments)
def _index(self):
self._property_lookup = dict((prop.name, prop)
for prop in self._properties)
if len(self._property_lookup) != len(self._properties):
raise ValueError("two properties with same name")
def ply_property(self, name):
return self._property_lookup[name]
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype of the in-memory representation of the
data. (If there are no list properties, and the PLY format is
binary, then this also accurately describes the on-disk
representation of the element.)
'''
return _np.dtype([(prop.name, prop.dtype(byte_order))
for prop in self.properties])
@staticmethod
def describe(data, name, len_types={}, val_types={},
comments=[]):
'''
Construct a PlyElement from an array's metadata.
len_types and val_types can be given as mappings from list
property names to type strings (like 'u1', 'f4', etc., or
'int8', 'float32', etc.). These can be used to define the length
and value types of list properties. List property lengths
always default to type 'u1' (8-bit unsigned integer), and value
types default to 'i4' (32-bit integer).
'''
if not isinstance(data, _np.ndarray):
raise TypeError("only numpy arrays are supported")
if len(data.shape) != 1:
raise ValueError("only one-dimensional arrays are "
"supported")
count = len(data)
properties = []
descr = data.dtype.descr
for t in descr:
if not isinstance(t[1], str):
raise ValueError("nested records not supported")
if not t[0]:
raise ValueError("field with empty name")
if len(t) != 2 or t[1][1] == 'O':
# non-scalar field, which corresponds to a list
# property in PLY.
if t[1][1] == 'O':
if len(t) != 2:
raise ValueError("non-scalar object fields not "
"supported")
len_str = _data_type_reverse[len_types.get(t[0], 'u1')]
if t[1][1] == 'O':
val_type = val_types.get(t[0], 'i4')
val_str = _lookup_type(val_type)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyListProperty(t[0], len_str, val_str)
else:
val_str = _lookup_type(t[1][1:])
prop = PlyProperty(t[0], val_str)
properties.append(prop)
elt = PlyElement(name, properties, count, comments)
elt.data = data
return elt
def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will memory map
# the file in copy-on-write mode.
num_bytes = self.count * dtype.itemsize
offset = stream.tell()
stream.seek(0, 2)
max_bytes = stream.tell() - offset
if max_bytes < num_bytes:
raise PlyElementParseError("early end-of-file", self,
max_bytes // dtype.itemsize)
self._data = _np.memmap(stream, dtype,
'c', offset, self.count)
# Fix stream position
stream.seek(offset + self.count * dtype.itemsize)
else:
# A simple load is impossible.
self._read_bin(stream, byte_order)
self._check_sanity()
def _write(self, stream, text, byte_order):
'''
Write the data to a PLY file.
'''
if text:
self._write_txt(stream)
else:
if self._have_list:
# There are list properties, so serialization is
# slightly complicated.
self._write_bin(stream, byte_order)
else:
# no list properties, so serialization is
# straightforward.
stream.write(self.data.astype(self.dtype(byte_order),
copy=False).data)
def _read_txt(self, stream):
'''
Load a PLY element from an ASCII-format PLY file. The element
may contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype())
k = 0
for line in _islice(iter(stream.readline, b''), self.count):
fields = iter(line.strip().split())
for prop in self.properties:
try:
self._data[prop.name][k] = prop._from_fields(fields)
except StopIteration:
raise PlyElementParseError("early end-of-line",
self, k, prop)
except ValueError:
raise PlyElementParseError("malformed input",
self, k, prop)
try:
next(fields)
except StopIteration:
pass
else:
raise PlyElementParseError("expected end-of-line",
self, k)
k += 1
if k < self.count:
del self._data
raise PlyElementParseError("early end-of-file", self, k)
def _write_txt(self, stream):
'''
Save a PLY element to an ASCII-format PLY file. The element may
contain list properties.
'''
for rec in self.data:
fields = []
for prop in self.properties:
fields.extend(prop._to_fields(rec[prop.name]))
_np.savetxt(stream, [fields], '%.18g', newline='\n')
def _read_bin(self, stream, byte_order):
'''
Load a PLY element from a binary PLY file. The element may
contain list properties.
'''
self._data = _np.empty(self.count, dtype=self.dtype(byte_order))
for k in _range(self.count):
for prop in self.properties:
try:
self._data[prop.name][k] = \
prop._read_bin(stream, byte_order)
except StopIteration:
raise PlyElementParseError("early end-of-file",
self, k, prop)
def _write_bin(self, stream, byte_order):
'''
Save a PLY element to a binary PLY file. The element may
contain list properties.
'''
for rec in self.data:
for prop in self.properties:
prop._write_bin(rec[prop.name], stream, byte_order)
@property
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __str__(self):
return self.header
def __repr__(self):
return ('PlyElement(%r, %r, count=%d, comments=%r)' %
(self.name, self.properties, self.count,
self.comments))
|
dranjan/python-plyfile | plyfile.py | PlyProperty._from_fields | python | def _from_fields(self, fields):
'''
Parse from generator. Raise StopIteration if the property could
not be read.
'''
return _np.dtype(self.dtype()).type(next(fields)) | Parse from generator. Raise StopIteration if the property could
not be read. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L826-L832 | null | class PlyProperty(object):
'''
PLY property description. This class is pure metadata; the data
itself is contained in PlyElement instances.
'''
def __init__(self, name, val_dtype):
_check_name(name)
self._name = str(name)
self.val_dtype = val_dtype
def _get_val_dtype(self):
return self._val_dtype
def _set_val_dtype(self, val_dtype):
self._val_dtype = _data_types[_lookup_type(val_dtype)]
val_dtype = property(_get_val_dtype, _set_val_dtype)
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype description for this property (as a tuple
of strings).
'''
return byte_order + self.val_dtype
def _to_fields(self, data):
'''
Return generator over one item.
'''
yield _np.dtype(self.dtype()).type(data)
def _read_bin(self, stream, byte_order):
'''
Read data from a binary stream. Raise StopIteration if the
property could not be read.
'''
try:
return _read_array(stream, self.dtype(byte_order), 1)[0]
except IndexError:
raise StopIteration
def _write_bin(self, data, stream, byte_order):
'''
Write data to a binary stream.
'''
_write_array(stream, _np.dtype(self.dtype(byte_order)).type(data))
def __str__(self):
val_str = _data_type_reverse[self.val_dtype]
return 'property %s %s' % (val_str, self.name)
def __repr__(self):
return 'PlyProperty(%r, %r)' % (self.name,
_lookup_type(self.val_dtype))
|
dranjan/python-plyfile | plyfile.py | PlyProperty._read_bin | python | def _read_bin(self, stream, byte_order):
'''
Read data from a binary stream. Raise StopIteration if the
property could not be read.
'''
try:
return _read_array(stream, self.dtype(byte_order), 1)[0]
except IndexError:
raise StopIteration | Read data from a binary stream. Raise StopIteration if the
property could not be read. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L841-L850 | null | class PlyProperty(object):
'''
PLY property description. This class is pure metadata; the data
itself is contained in PlyElement instances.
'''
def __init__(self, name, val_dtype):
_check_name(name)
self._name = str(name)
self.val_dtype = val_dtype
def _get_val_dtype(self):
return self._val_dtype
def _set_val_dtype(self, val_dtype):
self._val_dtype = _data_types[_lookup_type(val_dtype)]
val_dtype = property(_get_val_dtype, _set_val_dtype)
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype description for this property (as a tuple
of strings).
'''
return byte_order + self.val_dtype
def _from_fields(self, fields):
'''
Parse from generator. Raise StopIteration if the property could
not be read.
'''
return _np.dtype(self.dtype()).type(next(fields))
def _to_fields(self, data):
'''
Return generator over one item.
'''
yield _np.dtype(self.dtype()).type(data)
def _write_bin(self, data, stream, byte_order):
'''
Write data to a binary stream.
'''
_write_array(stream, _np.dtype(self.dtype(byte_order)).type(data))
def __str__(self):
val_str = _data_type_reverse[self.val_dtype]
return 'property %s %s' % (val_str, self.name)
def __repr__(self):
return 'PlyProperty(%r, %r)' % (self.name,
_lookup_type(self.val_dtype))
|
dranjan/python-plyfile | plyfile.py | PlyProperty._write_bin | python | def _write_bin(self, data, stream, byte_order):
'''
Write data to a binary stream.
'''
_write_array(stream, _np.dtype(self.dtype(byte_order)).type(data)) | Write data to a binary stream. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L852-L857 | null | class PlyProperty(object):
'''
PLY property description. This class is pure metadata; the data
itself is contained in PlyElement instances.
'''
def __init__(self, name, val_dtype):
_check_name(name)
self._name = str(name)
self.val_dtype = val_dtype
def _get_val_dtype(self):
return self._val_dtype
def _set_val_dtype(self, val_dtype):
self._val_dtype = _data_types[_lookup_type(val_dtype)]
val_dtype = property(_get_val_dtype, _set_val_dtype)
@property
def name(self):
return self._name
def dtype(self, byte_order='='):
'''
Return the numpy dtype description for this property (as a tuple
of strings).
'''
return byte_order + self.val_dtype
def _from_fields(self, fields):
'''
Parse from generator. Raise StopIteration if the property could
not be read.
'''
return _np.dtype(self.dtype()).type(next(fields))
def _to_fields(self, data):
'''
Return generator over one item.
'''
yield _np.dtype(self.dtype()).type(data)
def _read_bin(self, stream, byte_order):
'''
Read data from a binary stream. Raise StopIteration if the
property could not be read.
'''
try:
return _read_array(stream, self.dtype(byte_order), 1)[0]
except IndexError:
raise StopIteration
def __str__(self):
val_str = _data_type_reverse[self.val_dtype]
return 'property %s %s' % (val_str, self.name)
def __repr__(self):
return 'PlyProperty(%r, %r)' % (self.name,
_lookup_type(self.val_dtype))
|
dranjan/python-plyfile | plyfile.py | PlyListProperty._to_fields | python | def _to_fields(self, data):
'''
Return generator over the (numerical) PLY representation of the
list data (length followed by actual data).
'''
(len_t, val_t) = self.list_dtype()
data = _np.asarray(data, dtype=val_t).ravel()
yield _np.dtype(len_t).type(data.size)
for x in data:
yield x | Return generator over the (numerical) PLY representation of the
list data (length followed by actual data). | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L915-L927 | null | class PlyListProperty(PlyProperty):
'''
PLY list property description.
'''
def __init__(self, name, len_dtype, val_dtype):
PlyProperty.__init__(self, name, val_dtype)
self.len_dtype = len_dtype
def _get_len_dtype(self):
return self._len_dtype
def _set_len_dtype(self, len_dtype):
self._len_dtype = _data_types[_lookup_type(len_dtype)]
len_dtype = property(_get_len_dtype, _set_len_dtype)
def dtype(self, byte_order='='):
'''
List properties always have a numpy dtype of "object".
'''
return '|O'
def list_dtype(self, byte_order='='):
'''
Return the pair (len_dtype, val_dtype) (both numpy-friendly
strings).
'''
return (byte_order + self.len_dtype,
byte_order + self.val_dtype)
def _from_fields(self, fields):
(len_t, val_t) = self.list_dtype()
n = int(_np.dtype(len_t).type(next(fields)))
data = _np.loadtxt(list(_islice(fields, n)), val_t, ndmin=1)
if len(data) < n:
raise StopIteration
return data
def _read_bin(self, stream, byte_order):
(len_t, val_t) = self.list_dtype(byte_order)
try:
n = _read_array(stream, _np.dtype(len_t), 1)[0]
except IndexError:
raise StopIteration
data = _read_array(stream, _np.dtype(val_t), n)
if len(data) < n:
raise StopIteration
return data
def _write_bin(self, data, stream, byte_order):
'''
Write data to a binary stream.
'''
(len_t, val_t) = self.list_dtype(byte_order)
data = _np.asarray(data, dtype=val_t).ravel()
_write_array(stream, _np.array(data.size, dtype=len_t))
_write_array(stream, data)
def __str__(self):
len_str = _data_type_reverse[self.len_dtype]
val_str = _data_type_reverse[self.val_dtype]
return 'property list %s %s %s' % (len_str, val_str, self.name)
def __repr__(self):
return ('PlyListProperty(%r, %r, %r)' %
(self.name,
_lookup_type(self.len_dtype),
_lookup_type(self.val_dtype)))
|
dranjan/python-plyfile | plyfile.py | PlyListProperty._write_bin | python | def _write_bin(self, data, stream, byte_order):
'''
Write data to a binary stream.
'''
(len_t, val_t) = self.list_dtype(byte_order)
data = _np.asarray(data, dtype=val_t).ravel()
_write_array(stream, _np.array(data.size, dtype=len_t))
_write_array(stream, data) | Write data to a binary stream. | train | https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L943-L953 | null | class PlyListProperty(PlyProperty):
'''
PLY list property description.
'''
def __init__(self, name, len_dtype, val_dtype):
PlyProperty.__init__(self, name, val_dtype)
self.len_dtype = len_dtype
def _get_len_dtype(self):
return self._len_dtype
def _set_len_dtype(self, len_dtype):
self._len_dtype = _data_types[_lookup_type(len_dtype)]
len_dtype = property(_get_len_dtype, _set_len_dtype)
def dtype(self, byte_order='='):
'''
List properties always have a numpy dtype of "object".
'''
return '|O'
def list_dtype(self, byte_order='='):
'''
Return the pair (len_dtype, val_dtype) (both numpy-friendly
strings).
'''
return (byte_order + self.len_dtype,
byte_order + self.val_dtype)
def _from_fields(self, fields):
(len_t, val_t) = self.list_dtype()
n = int(_np.dtype(len_t).type(next(fields)))
data = _np.loadtxt(list(_islice(fields, n)), val_t, ndmin=1)
if len(data) < n:
raise StopIteration
return data
def _to_fields(self, data):
'''
Return generator over the (numerical) PLY representation of the
list data (length followed by actual data).
'''
(len_t, val_t) = self.list_dtype()
data = _np.asarray(data, dtype=val_t).ravel()
yield _np.dtype(len_t).type(data.size)
for x in data:
yield x
def _read_bin(self, stream, byte_order):
(len_t, val_t) = self.list_dtype(byte_order)
try:
n = _read_array(stream, _np.dtype(len_t), 1)[0]
except IndexError:
raise StopIteration
data = _read_array(stream, _np.dtype(val_t), n)
if len(data) < n:
raise StopIteration
return data
def __str__(self):
len_str = _data_type_reverse[self.len_dtype]
val_str = _data_type_reverse[self.val_dtype]
return 'property list %s %s %s' % (len_str, val_str, self.name)
def __repr__(self):
return ('PlyListProperty(%r, %r, %r)' %
(self.name,
_lookup_type(self.len_dtype),
_lookup_type(self.val_dtype)))
|
sibson/vncdotool | vncdotool/api.py | connect | python | def connect(server, password=None,
factory_class=VNCDoToolFactory, proxy=ThreadedVNCClientProxy, timeout=None):
if not reactor.running:
global _THREAD
_THREAD = threading.Thread(target=reactor.run, name='Twisted',
kwargs={'installSignalHandlers': False})
_THREAD.daemon = True
_THREAD.start()
observer = PythonLoggingObserver()
observer.start()
factory = factory_class()
if password is not None:
factory.password = password
family, host, port = command.parse_server(server)
client = proxy(factory, timeout)
client.connect(host, port=port, family=family)
return client | Connect to a VNCServer and return a Client instance that is usable
in the main thread of non-Twisted Python Applications, EXPERIMENTAL.
>>> from vncdotool import api
>>> with api.connect('host') as client
>>> client.keyPress('c')
You may then call any regular VNCDoToolClient method on client from your
application code.
If you are using a GUI toolkit or other major async library please read
http://twistedmatrix.com/documents/13.0.0/core/howto/choosing-reactor.html
for a better method of intergrating vncdotool. | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/api.py#L121-L156 | [
"def parse_server(server):\n split = server.split(':')\n\n if not split[0]:\n host = '127.0.0.1'\n else:\n host = split[0]\n\n if os.path.exists(host):\n address_family = socket.AF_UNIX\n else:\n address_family = socket.AF_INET\n\n if len(split) == 3: # ::port\n port = int(split[2])\n elif len(split) == 2: # :display\n port = int(split[1]) + 5900\n else:\n port = 5900\n\n return address_family, host, port\n",
"def connect(self, host, port=5900, family=socket.AF_INET):\n def capture_protocol(protocol):\n self.protocol = protocol\n return protocol\n self.factory.deferred.addCallback(capture_protocol)\n reactor.callWhenRunning(\n factory_connect, self.factory, host, port, family)\n"
] | """ Helpers to allow vncdotool to be intergrated into other applications.
This feature is under development, your help testing and
debugging is appreciated.
"""
import sys
import socket
import threading
try:
import queue
except ImportError:
import Queue as queue
import logging
from twisted.internet import reactor
from twisted.internet.defer import maybeDeferred
from twisted.python.log import PythonLoggingObserver
from twisted.python.failure import Failure
from . import command
from .client import VNCDoToolFactory, factory_connect
__all__ = ['connect']
log = logging.getLogger('vncdotool.api')
_THREAD = None
class VNCDoException(Exception):
pass
if sys.version_info.major == 2:
class TimeoutError(OSError):
pass
def shutdown():
if not reactor.running:
return
reactor.callFromThread(reactor.stop)
_THREAD.join()
class ThreadedVNCClientProxy(object):
def __init__(self, factory, timeout=60 * 60):
self.factory = factory
self.queue = queue.Queue()
self._timeout = timeout
self.protocol = None
def __enter__(self):
return self
def __exit__(self, *_):
self.disconnect()
@property
def timeout(self):
"""Timeout in seconds for API requests."""
return self._timeout
@timeout.setter
def timeout(self, timeout):
"""Timeout in seconds for API requests."""
self._timeout = timeout
def connect(self, host, port=5900, family=socket.AF_INET):
def capture_protocol(protocol):
self.protocol = protocol
return protocol
self.factory.deferred.addCallback(capture_protocol)
reactor.callWhenRunning(
factory_connect, self.factory, host, port, family)
def disconnect(self):
def disconnector(protocol):
protocol.transport.loseConnection()
reactor.callFromThread(self.factory.deferred.addCallback, disconnector)
def __getattr__(self, attr):
method = getattr(self.factory.protocol, attr)
def errback(reason, *args, **kwargs):
self.queue.put(Failure(reason))
def callback(protocol, *args, **kwargs):
def result_callback(result):
self.queue.put(result)
return result
d = maybeDeferred(method, protocol, *args, **kwargs)
d.addBoth(result_callback)
return d
def proxy_call(*args, **kwargs):
reactor.callFromThread(self.factory.deferred.addCallbacks,
callback, errback, args, kwargs)
try:
result = self.queue.get(timeout=self._timeout)
except queue.Empty:
raise TimeoutError("Timeout while waiting for client response")
if isinstance(result, Failure):
raise VNCDoException(result)
return result
if callable(method):
return proxy_call
else:
return getattr(self.protocol, attr)
def __dir__(self):
return dir(self.__class__) + dir(self.factory.protocol)
if __name__ == '__main__':
import sys
logging.basicConfig(level=logging.DEBUG)
server = sys.argv[1]
password = sys.argv[2]
client1 = connect(server, password)
client2 = connect(server, password)
client1.captureScreen('screenshot.png')
for key in 'username':
client2.keyPress(key)
for key in 'passw0rd':
client1.keyPress(key)
client1.disconnect()
client2.disconnect()
shutdown()
|
sibson/vncdotool | vncdotool/pyDes.py | des.__String_to_BitList | python | def __String_to_BitList(self, data):
if isinstance(data[0], str):
# Turn the strings into integers. Python 3 uses a bytes
# class, which already has this behaviour.
data = [ord(c) for c in data]
l = len(data) * 8
result = [0] * l
pos = 0
for ch in data:
i = 7
while i >= 0:
if ch & (1 << i) != 0:
result[pos] = 1
else:
result[pos] = 0
pos += 1
i -= 1
return result | Turn the string data, into a list of bits (1, 0)'s | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/pyDes.py#L416-L435 | null | class des(_baseDes):
"""DES encryption/decrytpion class
Supports ECB (Electronic Code Book) and CBC (Cypher Block Chaining) modes.
pyDes.des(key,[mode], [IV])
key -> Bytes containing the encryption key, must be exactly 8 bytes
mode -> Optional argument for encryption type, can be either pyDes.ECB
(Electronic Code Book), pyDes.CBC (Cypher Block Chaining)
IV -> Optional Initial Value bytes, must be supplied if using CBC mode.
Must be 8 bytes in length.
pad -> Optional argument, set the pad character (PAD_NORMAL) to use
during all encrypt/decrpt operations done with this instance.
padmode -> Optional argument, set the padding mode (PAD_NORMAL or
PAD_PKCS5) to use during all encrypt/decrpt operations done
with this instance.
"""
# Permutation and translation tables for DES
__pc1 = [56, 48, 40, 32, 24, 16, 8,
0, 57, 49, 41, 33, 25, 17,
9, 1, 58, 50, 42, 34, 26,
18, 10, 2, 59, 51, 43, 35,
62, 54, 46, 38, 30, 22, 14,
6, 61, 53, 45, 37, 29, 21,
13, 5, 60, 52, 44, 36, 28,
20, 12, 4, 27, 19, 11, 3
]
# number left rotations of pc1
__left_rotations = [
1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
]
# permuted choice key (table 2)
__pc2 = [
13, 16, 10, 23, 0, 4,
2, 27, 14, 5, 20, 9,
22, 18, 11, 3, 25, 7,
15, 6, 26, 19, 12, 1,
40, 51, 30, 36, 46, 54,
29, 39, 50, 44, 32, 47,
43, 48, 38, 55, 33, 52,
45, 41, 49, 35, 28, 31
]
# initial permutation IP
__ip = [57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7,
56, 48, 40, 32, 24, 16, 8, 0,
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6
]
# Expansion table for turning 32 bit blocks into 48 bits
__expansion_table = [
31, 0, 1, 2, 3, 4,
3, 4, 5, 6, 7, 8,
7, 8, 9, 10, 11, 12,
11, 12, 13, 14, 15, 16,
15, 16, 17, 18, 19, 20,
19, 20, 21, 22, 23, 24,
23, 24, 25, 26, 27, 28,
27, 28, 29, 30, 31, 0
]
# The (in)famous S-boxes
__sbox = [
# S1
[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
# S2
[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
# S3
[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
# S4
[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
# S5
[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
# S6
[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
# S7
[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
# S8
[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],
]
# 32-bit permutation function P used on the output of the S-boxes
__p = [
15, 6, 19, 20, 28, 11,
27, 16, 0, 14, 22, 25,
4, 17, 30, 9, 1, 7,
23,13, 31, 26, 2, 8,
18, 12, 29, 5, 21, 10,
3, 24
]
# final permutation IP^-1
__fp = [
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25,
32, 0, 40, 8, 48, 16, 56, 24
]
# Type of crypting being done
ENCRYPT = 0x00
DECRYPT = 0x01
# Initialisation
def __init__(self, key, mode=ECB, IV=None, pad=None, padmode=PAD_NORMAL):
# Sanity checking of arguments.
if len(key) != 8:
raise ValueError("Invalid DES key size. Key must be exactly 8 bytes long.")
_baseDes.__init__(self, mode, IV, pad, padmode)
self.key_size = 8
self.L = []
self.R = []
self.Kn = [ [0] * 48 ] * 16 # 16 48-bit keys (K1 - K16)
self.final = []
self.setKey(key)
def setKey(self, key):
"""Will set the crypting key for this object. Must be 8 bytes."""
_baseDes.setKey(self, key)
self.__create_sub_keys()
def __BitList_to_String(self, data):
"""Turn the list of bits -> data, into a string"""
result = []
pos = 0
c = 0
while pos < len(data):
c += data[pos] << (7 - (pos % 8))
if (pos % 8) == 7:
result.append(c)
c = 0
pos += 1
if _pythonMajorVersion < 3:
return ''.join([ chr(c) for c in result ])
else:
return bytes(result)
def __permutate(self, table, block):
"""Permutate this block with the specified table"""
return list(map(lambda x: block[x], table))
# Transform the secret key, so that it is ready for data processing
# Create the 16 subkeys, K[1] - K[16]
def __create_sub_keys(self):
"""Create the 16 subkeys K[1] to K[16] from the given key"""
key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey()))
i = 0
# Split into Left and Right sections
self.L = key[:28]
self.R = key[28:]
while i < 16:
j = 0
# Perform circular left shifts
while j < des.__left_rotations[i]:
self.L.append(self.L[0])
del self.L[0]
self.R.append(self.R[0])
del self.R[0]
j += 1
# Create one of the 16 subkeys through pc2 permutation
self.Kn[i] = self.__permutate(des.__pc2, self.L + self.R)
i += 1
# Main part of the encryption algorithm, the number cruncher :)
def __des_crypt(self, block, crypt_type):
"""Crypt the block of data through DES bit-manipulation"""
block = self.__permutate(des.__ip, block)
self.L = block[:32]
self.R = block[32:]
# Encryption starts from Kn[1] through to Kn[16]
if crypt_type == des.ENCRYPT:
iteration = 0
iteration_adjustment = 1
# Decryption starts from Kn[16] down to Kn[1]
else:
iteration = 15
iteration_adjustment = -1
i = 0
while i < 16:
# Make a copy of R[i-1], this will later become L[i]
tempR = self.R[:]
# Permutate R[i - 1] to start creating R[i]
self.R = self.__permutate(des.__expansion_table, self.R)
# Exclusive or R[i - 1] with K[i], create B[1] to B[8] whilst here
self.R = list(map(lambda x, y: x ^ y, self.R, self.Kn[iteration]))
B = [self.R[:6], self.R[6:12], self.R[12:18], self.R[18:24], self.R[24:30], self.R[30:36], self.R[36:42], self.R[42:]]
# Optimization: Replaced below commented code with above
#j = 0
#B = []
#while j < len(self.R):
# self.R[j] = self.R[j] ^ self.Kn[iteration][j]
# j += 1
# if j % 6 == 0:
# B.append(self.R[j-6:j])
# Permutate B[1] to B[8] using the S-Boxes
j = 0
Bn = [0] * 32
pos = 0
while j < 8:
# Work out the offsets
m = (B[j][0] << 1) + B[j][5]
n = (B[j][1] << 3) + (B[j][2] << 2) + (B[j][3] << 1) + B[j][4]
# Find the permutation value
v = des.__sbox[j][(m << 4) + n]
# Turn value into bits, add it to result: Bn
Bn[pos] = (v & 8) >> 3
Bn[pos + 1] = (v & 4) >> 2
Bn[pos + 2] = (v & 2) >> 1
Bn[pos + 3] = v & 1
pos += 4
j += 1
# Permutate the concatination of B[1] to B[8] (Bn)
self.R = self.__permutate(des.__p, Bn)
# Xor with L[i - 1]
self.R = list(map(lambda x, y: x ^ y, self.R, self.L))
# Optimization: This now replaces the below commented code
#j = 0
#while j < len(self.R):
# self.R[j] = self.R[j] ^ self.L[j]
# j += 1
# L[i] becomes R[i - 1]
self.L = tempR
i += 1
iteration += iteration_adjustment
# Final permutation of R[16]L[16]
self.final = self.__permutate(des.__fp, self.R + self.L)
return self.final
# Data to be encrypted/decrypted
def crypt(self, data, crypt_type):
"""Crypt the data in blocks, running it through des_crypt()"""
# Error check the data
if not data:
return ''
if len(data) % self.block_size != 0:
if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks
raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n.")
if not self.getPadding():
raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n. Try setting the optional padding character")
else:
data += (self.block_size - (len(data) % self.block_size)) * self.getPadding()
# print "Len of data: %f" % (len(data) / self.block_size)
if self.getMode() == CBC:
if self.getIV():
iv = self.__String_to_BitList(self.getIV())
else:
raise ValueError("For CBC mode, you must supply the Initial Value (IV) for ciphering")
# Split the data into blocks, crypting each one seperately
i = 0
dict = {}
result = []
#cached = 0
#lines = 0
while i < len(data):
# Test code for caching encryption results
#lines += 1
#if dict.has_key(data[i:i+8]):
#print "Cached result for: %s" % data[i:i+8]
# cached += 1
# result.append(dict[data[i:i+8]])
# i += 8
# continue
block = self.__String_to_BitList(data[i:i+8])
# Xor with IV if using CBC mode
if self.getMode() == CBC:
if crypt_type == des.ENCRYPT:
block = list(map(lambda x, y: x ^ y, block, iv))
#j = 0
#while j < len(block):
# block[j] = block[j] ^ iv[j]
# j += 1
processed_block = self.__des_crypt(block, crypt_type)
if crypt_type == des.DECRYPT:
processed_block = list(map(lambda x, y: x ^ y, processed_block, iv))
#j = 0
#while j < len(processed_block):
# processed_block[j] = processed_block[j] ^ iv[j]
# j += 1
iv = block
else:
iv = processed_block
else:
processed_block = self.__des_crypt(block, crypt_type)
# Add the resulting crypted block to our list
#d = self.__BitList_to_String(processed_block)
#result.append(d)
result.append(self.__BitList_to_String(processed_block))
#dict[data[i:i+8]] = d
i += 8
# print "Lines: %d, cached: %d" % (lines, cached)
# Return the full crypted string
if _pythonMajorVersion < 3:
return ''.join(result)
else:
return bytes.fromhex('').join(result)
def encrypt(self, data, pad=None, padmode=None):
"""encrypt(data, [pad], [padmode]) -> bytes
data : Bytes to be encrypted
pad : Optional argument for encryption padding. Must only be one byte
padmode : Optional argument for overriding the padding mode.
The data must be a multiple of 8 bytes and will be encrypted
with the already specified key. Data does not have to be a
multiple of 8 bytes if the padding character is supplied, or
the padmode is set to PAD_PKCS5, as bytes will then added to
ensure the be padded data is a multiple of 8 bytes.
"""
data = self._guardAgainstUnicode(data)
if pad is not None:
pad = self._guardAgainstUnicode(pad)
data = self._padData(data, pad, padmode)
return self.crypt(data, des.ENCRYPT)
def decrypt(self, data, pad=None, padmode=None):
"""decrypt(data, [pad], [padmode]) -> bytes
data : Bytes to be encrypted
pad : Optional argument for decryption padding. Must only be one byte
padmode : Optional argument for overriding the padding mode.
The data must be a multiple of 8 bytes and will be decrypted
with the already specified key. In PAD_NORMAL mode, if the
optional padding character is supplied, then the un-encrypted
data will have the padding characters removed from the end of
the bytes. This pad removal only occurs on the last 8 bytes of
the data (last data block). In PAD_PKCS5 mode, the special
padding end markers will be removed from the data after decrypting.
"""
data = self._guardAgainstUnicode(data)
if pad is not None:
pad = self._guardAgainstUnicode(pad)
data = self.crypt(data, des.DECRYPT)
return self._unpadData(data, pad, padmode)
|
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.keyPress | python | def keyPress(self, key):
log.debug('keyPress %s', key)
self.keyDown(key)
self.keyUp(key)
return self | Send a key press to the server
key: string: either [a-z] or a from KEYMAP | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L165-L174 | null | class VNCDoToolClient(rfb.RFBClient):
encoding = rfb.RAW_ENCODING
x = 0
y = 0
buttons = 0
screen = None
image_mode = "RGBX"
deferred = None
cursor = None
cmask = None
SPECIAL_KEYS_US = "~!@#$%^&*()_+{}|:\"<>?"
def connectionMade(self):
rfb.RFBClient.connectionMade(self)
if self.transport.addressFamily == socket.AF_INET:
self.transport.setTcpNoDelay(True)
def _decodeKey(self, key):
if self.factory.force_caps:
if key.isupper() or key in self.SPECIAL_KEYS_US:
key = 'shift-%c' % key
if len(key) == 1:
keys = [key]
else:
keys = key.split('-')
keys = [KEYMAP.get(k) or ord(k) for k in keys]
return keys
def pause(self, duration):
d = Deferred()
reactor.callLater(duration, d.callback, self)
return d
def keyDown(self, key):
log.debug('keyDown %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=1)
return self
def keyUp(self, key):
log.debug('keyUp %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=0)
return self
def mousePress(self, button):
""" Send a mouse click at the last set position
button: int: [1-n]
"""
log.debug('mousePress %s', button)
buttons = self.buttons | (1 << (button - 1))
self.mouseDown(button)
self.mouseUp(button)
return self
def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
"""
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def mouseUp(self, button):
""" Send mouse button released at the last set position
button: int: [1-n]
"""
log.debug('mouseUp %s', button)
self.buttons &= ~(1 << (button - 1))
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def captureScreen(self, filename):
""" Save the current display to filename
"""
log.debug('captureScreen %s', filename)
return self._capture(filename)
def captureRegion(self, filename, x, y, w, h):
""" Save a region of the current display to filename
"""
log.debug('captureRegion %s', filename)
return self._capture(filename, x, y, x+w, y+h)
def refreshScreen(self, incremental=0):
d = self.deferred = Deferred()
self.framebufferUpdateRequest(incremental=incremental)
return d
def _capture(self, filename, *args):
d = self.refreshScreen()
d.addCallback(self._captureSave, filename, *args)
return d
def _captureSave(self, data, filename, *args):
log.debug('captureSave %s', filename)
if args:
capture = self.screen.crop(args)
else:
capture = self.screen
capture.save(filename)
return self
def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image
"""
log.debug('expectScreen %s', filename)
return self._expectFramebuffer(filename, 0, 0, maxrms)
def expectRegion(self, filename, x, y, maxrms=0):
""" Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height)
"""
log.debug('expectRegion %s (%s, %s)', filename, x, y)
return self._expectFramebuffer(filename, x, y, maxrms)
def _expectFramebuffer(self, filename, x, y, maxrms):
self.framebufferUpdateRequest(incremental=1)
image = Image.open(filename)
w, h = image.size
self.expected = image.histogram()
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, (x, y, x + w, y + h), maxrms)
return self.deferred
def _expectCompare(self, data, box, maxrms):
image = self.screen.crop(box)
hist = image.histogram()
if len(hist) == len(self.expected):
sum_ = 0
for h, e in zip(hist, self.expected):
sum_ += (h - e) ** 2
rms = math.sqrt(sum_ / len(hist))
log.debug('rms:%s maxrms: %s', int(rms), int(maxrms))
if rms <= maxrms:
return self
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, box, maxrms)
self.framebufferUpdateRequest(incremental=1) # use box ~(x, y, w - x, h - y)?
return self.deferred
def mouseMove(self, x, y):
""" Move the mouse pointer to position (x, y)
"""
log.debug('mouseMove %d,%d', x, y)
self.x, self.y = x, y
self.pointerEvent(x, y, self.buttons)
return self
def mouseDrag(self, x, y, step=1):
""" Move the mouse point to position (x, y) in increments of step
"""
log.debug('mouseDrag %d,%d', x, y)
if x < self.x:
xsteps = [self.x - i for i in range(step, self.x - x + 1, step)]
else:
xsteps = range(self.x, x, step)
if y < self.y:
ysteps = [self.y - i for i in range(step, self.y - y + 1, step)]
else:
ysteps = range(self.y, y, step)
for ypos in ysteps:
time.sleep(.2)
self.mouseMove(self.x, ypos)
for xpos in xsteps:
time.sleep(.2)
self.mouseMove(xpos, self.y)
self.mouseMove(x, y)
return self
def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax = 63, bluemax = 31,
redshift = 11, greenshift = 5, blueshift = 0
)
self.image_mode = "BGR;16"
elif (self.truecolor and (not self.bigendian) and self.depth == 24
and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):
pixel = ["X"] * self.bypp
offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
for offset, color in zip(offsets, "RGB"):
pixel[offset] = color
self.image_mode = "".join(pixel)
else:
self.setPixelFormat()
#
# base customizations
#
def vncRequestPassword(self):
if self.factory.password is None:
self.transport.loseConnection()
self.factory.clientConnectionFailed(self, AuthenticationError('password required, but none provided'))
return
self.sendPassword(self.factory.password)
def vncConnectionMade(self):
self.setImageMode()
encodings = [self.encoding]
if self.factory.pseudocursor or self.factory.nocursor:
encodings.append(rfb.PSEUDO_CURSOR_ENCODING)
if self.factory.pseudodesktop:
encodings.append(rfb.PSEUDO_DESKTOP_SIZE_ENCODING)
self.setEncodings(encodings)
self.factory.clientConnectionMade(self)
def bell(self):
print('ding')
def copy_text(self, text):
print('clipboard copy', repr(text))
def paste(self, message):
self.clientCutText(message)
return self
def updateRectangle(self, x, y, width, height, data):
# ignore empty updates
if not data:
return
size = (width, height)
update = Image.frombytes('RGB', size, data, 'raw', self.image_mode)
if not self.screen:
self.screen = update
# track upward screen resizes, often occurs during os boot of VMs
# When the screen is sent in chunks (as observed on VMWare ESXi), the canvas
# needs to be resized to fit all existing contents and the update.
elif self.screen.size[0] < (x+width) or self.screen.size[1] < (y+height):
new_size = (max(x+width, self.screen.size[0]), max(y+height, self.screen.size[1]))
new_screen = Image.new("RGB", new_size, "black")
new_screen.paste(self.screen, (0, 0))
new_screen.paste(update, (x, y))
self.screen = new_screen
else:
self.screen.paste(update, (x, y))
self.drawCursor()
def commitUpdate(self, rectangles):
if self.deferred:
d = self.deferred
self.deferred = None
d.callback(self)
def updateCursor(self, x, y, width, height, image, mask):
if self.factory.nocursor:
return
if not width or not height:
self.cursor = None
self.cursor = Image.frombytes('RGBX', (width, height), image)
self.cmask = Image.frombytes('1', (width, height), mask)
self.cfocus = x, y
self.drawCursor()
def drawCursor(self):
if not self.cursor:
return
if not self.screen:
return
x = self.x - self.cfocus[0]
y = self.y - self.cfocus[1]
self.screen.paste(self.cursor, (x, y), self.cmask)
def updateDesktopSize(self, width, height):
new_screen = Image.new("RGB", (width, height), "black")
if self.screen:
new_screen.paste(self.screen, (0, 0))
self.screen = new_screen
|
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.mousePress | python | def mousePress(self, button):
log.debug('mousePress %s', button)
buttons = self.buttons | (1 << (button - 1))
self.mouseDown(button)
self.mouseUp(button)
return self | Send a mouse click at the last set position
button: int: [1-n] | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L192-L203 | null | class VNCDoToolClient(rfb.RFBClient):
encoding = rfb.RAW_ENCODING
x = 0
y = 0
buttons = 0
screen = None
image_mode = "RGBX"
deferred = None
cursor = None
cmask = None
SPECIAL_KEYS_US = "~!@#$%^&*()_+{}|:\"<>?"
def connectionMade(self):
rfb.RFBClient.connectionMade(self)
if self.transport.addressFamily == socket.AF_INET:
self.transport.setTcpNoDelay(True)
def _decodeKey(self, key):
if self.factory.force_caps:
if key.isupper() or key in self.SPECIAL_KEYS_US:
key = 'shift-%c' % key
if len(key) == 1:
keys = [key]
else:
keys = key.split('-')
keys = [KEYMAP.get(k) or ord(k) for k in keys]
return keys
def pause(self, duration):
d = Deferred()
reactor.callLater(duration, d.callback, self)
return d
def keyPress(self, key):
""" Send a key press to the server
key: string: either [a-z] or a from KEYMAP
"""
log.debug('keyPress %s', key)
self.keyDown(key)
self.keyUp(key)
return self
def keyDown(self, key):
log.debug('keyDown %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=1)
return self
def keyUp(self, key):
log.debug('keyUp %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=0)
return self
def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
"""
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def mouseUp(self, button):
""" Send mouse button released at the last set position
button: int: [1-n]
"""
log.debug('mouseUp %s', button)
self.buttons &= ~(1 << (button - 1))
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def captureScreen(self, filename):
""" Save the current display to filename
"""
log.debug('captureScreen %s', filename)
return self._capture(filename)
def captureRegion(self, filename, x, y, w, h):
""" Save a region of the current display to filename
"""
log.debug('captureRegion %s', filename)
return self._capture(filename, x, y, x+w, y+h)
def refreshScreen(self, incremental=0):
d = self.deferred = Deferred()
self.framebufferUpdateRequest(incremental=incremental)
return d
def _capture(self, filename, *args):
d = self.refreshScreen()
d.addCallback(self._captureSave, filename, *args)
return d
def _captureSave(self, data, filename, *args):
log.debug('captureSave %s', filename)
if args:
capture = self.screen.crop(args)
else:
capture = self.screen
capture.save(filename)
return self
def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image
"""
log.debug('expectScreen %s', filename)
return self._expectFramebuffer(filename, 0, 0, maxrms)
def expectRegion(self, filename, x, y, maxrms=0):
""" Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height)
"""
log.debug('expectRegion %s (%s, %s)', filename, x, y)
return self._expectFramebuffer(filename, x, y, maxrms)
def _expectFramebuffer(self, filename, x, y, maxrms):
self.framebufferUpdateRequest(incremental=1)
image = Image.open(filename)
w, h = image.size
self.expected = image.histogram()
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, (x, y, x + w, y + h), maxrms)
return self.deferred
def _expectCompare(self, data, box, maxrms):
image = self.screen.crop(box)
hist = image.histogram()
if len(hist) == len(self.expected):
sum_ = 0
for h, e in zip(hist, self.expected):
sum_ += (h - e) ** 2
rms = math.sqrt(sum_ / len(hist))
log.debug('rms:%s maxrms: %s', int(rms), int(maxrms))
if rms <= maxrms:
return self
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, box, maxrms)
self.framebufferUpdateRequest(incremental=1) # use box ~(x, y, w - x, h - y)?
return self.deferred
def mouseMove(self, x, y):
""" Move the mouse pointer to position (x, y)
"""
log.debug('mouseMove %d,%d', x, y)
self.x, self.y = x, y
self.pointerEvent(x, y, self.buttons)
return self
def mouseDrag(self, x, y, step=1):
""" Move the mouse point to position (x, y) in increments of step
"""
log.debug('mouseDrag %d,%d', x, y)
if x < self.x:
xsteps = [self.x - i for i in range(step, self.x - x + 1, step)]
else:
xsteps = range(self.x, x, step)
if y < self.y:
ysteps = [self.y - i for i in range(step, self.y - y + 1, step)]
else:
ysteps = range(self.y, y, step)
for ypos in ysteps:
time.sleep(.2)
self.mouseMove(self.x, ypos)
for xpos in xsteps:
time.sleep(.2)
self.mouseMove(xpos, self.y)
self.mouseMove(x, y)
return self
def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax = 63, bluemax = 31,
redshift = 11, greenshift = 5, blueshift = 0
)
self.image_mode = "BGR;16"
elif (self.truecolor and (not self.bigendian) and self.depth == 24
and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):
pixel = ["X"] * self.bypp
offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
for offset, color in zip(offsets, "RGB"):
pixel[offset] = color
self.image_mode = "".join(pixel)
else:
self.setPixelFormat()
#
# base customizations
#
def vncRequestPassword(self):
if self.factory.password is None:
self.transport.loseConnection()
self.factory.clientConnectionFailed(self, AuthenticationError('password required, but none provided'))
return
self.sendPassword(self.factory.password)
def vncConnectionMade(self):
self.setImageMode()
encodings = [self.encoding]
if self.factory.pseudocursor or self.factory.nocursor:
encodings.append(rfb.PSEUDO_CURSOR_ENCODING)
if self.factory.pseudodesktop:
encodings.append(rfb.PSEUDO_DESKTOP_SIZE_ENCODING)
self.setEncodings(encodings)
self.factory.clientConnectionMade(self)
def bell(self):
print('ding')
def copy_text(self, text):
print('clipboard copy', repr(text))
def paste(self, message):
self.clientCutText(message)
return self
def updateRectangle(self, x, y, width, height, data):
# ignore empty updates
if not data:
return
size = (width, height)
update = Image.frombytes('RGB', size, data, 'raw', self.image_mode)
if not self.screen:
self.screen = update
# track upward screen resizes, often occurs during os boot of VMs
# When the screen is sent in chunks (as observed on VMWare ESXi), the canvas
# needs to be resized to fit all existing contents and the update.
elif self.screen.size[0] < (x+width) or self.screen.size[1] < (y+height):
new_size = (max(x+width, self.screen.size[0]), max(y+height, self.screen.size[1]))
new_screen = Image.new("RGB", new_size, "black")
new_screen.paste(self.screen, (0, 0))
new_screen.paste(update, (x, y))
self.screen = new_screen
else:
self.screen.paste(update, (x, y))
self.drawCursor()
def commitUpdate(self, rectangles):
if self.deferred:
d = self.deferred
self.deferred = None
d.callback(self)
def updateCursor(self, x, y, width, height, image, mask):
if self.factory.nocursor:
return
if not width or not height:
self.cursor = None
self.cursor = Image.frombytes('RGBX', (width, height), image)
self.cmask = Image.frombytes('1', (width, height), mask)
self.cfocus = x, y
self.drawCursor()
def drawCursor(self):
if not self.cursor:
return
if not self.screen:
return
x = self.x - self.cfocus[0]
y = self.y - self.cfocus[1]
self.screen.paste(self.cursor, (x, y), self.cmask)
def updateDesktopSize(self, width, height):
new_screen = Image.new("RGB", (width, height), "black")
if self.screen:
new_screen.paste(self.screen, (0, 0))
self.screen = new_screen
|
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.mouseDown | python | def mouseDown(self, button):
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self | Send a mouse button down at the last set position
button: int: [1-n] | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L205-L215 | null | class VNCDoToolClient(rfb.RFBClient):
encoding = rfb.RAW_ENCODING
x = 0
y = 0
buttons = 0
screen = None
image_mode = "RGBX"
deferred = None
cursor = None
cmask = None
SPECIAL_KEYS_US = "~!@#$%^&*()_+{}|:\"<>?"
def connectionMade(self):
rfb.RFBClient.connectionMade(self)
if self.transport.addressFamily == socket.AF_INET:
self.transport.setTcpNoDelay(True)
def _decodeKey(self, key):
if self.factory.force_caps:
if key.isupper() or key in self.SPECIAL_KEYS_US:
key = 'shift-%c' % key
if len(key) == 1:
keys = [key]
else:
keys = key.split('-')
keys = [KEYMAP.get(k) or ord(k) for k in keys]
return keys
def pause(self, duration):
d = Deferred()
reactor.callLater(duration, d.callback, self)
return d
def keyPress(self, key):
""" Send a key press to the server
key: string: either [a-z] or a from KEYMAP
"""
log.debug('keyPress %s', key)
self.keyDown(key)
self.keyUp(key)
return self
def keyDown(self, key):
log.debug('keyDown %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=1)
return self
def keyUp(self, key):
log.debug('keyUp %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=0)
return self
def mousePress(self, button):
""" Send a mouse click at the last set position
button: int: [1-n]
"""
log.debug('mousePress %s', button)
buttons = self.buttons | (1 << (button - 1))
self.mouseDown(button)
self.mouseUp(button)
return self
def mouseUp(self, button):
""" Send mouse button released at the last set position
button: int: [1-n]
"""
log.debug('mouseUp %s', button)
self.buttons &= ~(1 << (button - 1))
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def captureScreen(self, filename):
""" Save the current display to filename
"""
log.debug('captureScreen %s', filename)
return self._capture(filename)
def captureRegion(self, filename, x, y, w, h):
""" Save a region of the current display to filename
"""
log.debug('captureRegion %s', filename)
return self._capture(filename, x, y, x+w, y+h)
def refreshScreen(self, incremental=0):
d = self.deferred = Deferred()
self.framebufferUpdateRequest(incremental=incremental)
return d
def _capture(self, filename, *args):
d = self.refreshScreen()
d.addCallback(self._captureSave, filename, *args)
return d
def _captureSave(self, data, filename, *args):
log.debug('captureSave %s', filename)
if args:
capture = self.screen.crop(args)
else:
capture = self.screen
capture.save(filename)
return self
def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image
"""
log.debug('expectScreen %s', filename)
return self._expectFramebuffer(filename, 0, 0, maxrms)
def expectRegion(self, filename, x, y, maxrms=0):
""" Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height)
"""
log.debug('expectRegion %s (%s, %s)', filename, x, y)
return self._expectFramebuffer(filename, x, y, maxrms)
def _expectFramebuffer(self, filename, x, y, maxrms):
self.framebufferUpdateRequest(incremental=1)
image = Image.open(filename)
w, h = image.size
self.expected = image.histogram()
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, (x, y, x + w, y + h), maxrms)
return self.deferred
def _expectCompare(self, data, box, maxrms):
image = self.screen.crop(box)
hist = image.histogram()
if len(hist) == len(self.expected):
sum_ = 0
for h, e in zip(hist, self.expected):
sum_ += (h - e) ** 2
rms = math.sqrt(sum_ / len(hist))
log.debug('rms:%s maxrms: %s', int(rms), int(maxrms))
if rms <= maxrms:
return self
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, box, maxrms)
self.framebufferUpdateRequest(incremental=1) # use box ~(x, y, w - x, h - y)?
return self.deferred
def mouseMove(self, x, y):
""" Move the mouse pointer to position (x, y)
"""
log.debug('mouseMove %d,%d', x, y)
self.x, self.y = x, y
self.pointerEvent(x, y, self.buttons)
return self
def mouseDrag(self, x, y, step=1):
""" Move the mouse point to position (x, y) in increments of step
"""
log.debug('mouseDrag %d,%d', x, y)
if x < self.x:
xsteps = [self.x - i for i in range(step, self.x - x + 1, step)]
else:
xsteps = range(self.x, x, step)
if y < self.y:
ysteps = [self.y - i for i in range(step, self.y - y + 1, step)]
else:
ysteps = range(self.y, y, step)
for ypos in ysteps:
time.sleep(.2)
self.mouseMove(self.x, ypos)
for xpos in xsteps:
time.sleep(.2)
self.mouseMove(xpos, self.y)
self.mouseMove(x, y)
return self
def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax = 63, bluemax = 31,
redshift = 11, greenshift = 5, blueshift = 0
)
self.image_mode = "BGR;16"
elif (self.truecolor and (not self.bigendian) and self.depth == 24
and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):
pixel = ["X"] * self.bypp
offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
for offset, color in zip(offsets, "RGB"):
pixel[offset] = color
self.image_mode = "".join(pixel)
else:
self.setPixelFormat()
#
# base customizations
#
def vncRequestPassword(self):
if self.factory.password is None:
self.transport.loseConnection()
self.factory.clientConnectionFailed(self, AuthenticationError('password required, but none provided'))
return
self.sendPassword(self.factory.password)
def vncConnectionMade(self):
self.setImageMode()
encodings = [self.encoding]
if self.factory.pseudocursor or self.factory.nocursor:
encodings.append(rfb.PSEUDO_CURSOR_ENCODING)
if self.factory.pseudodesktop:
encodings.append(rfb.PSEUDO_DESKTOP_SIZE_ENCODING)
self.setEncodings(encodings)
self.factory.clientConnectionMade(self)
def bell(self):
print('ding')
def copy_text(self, text):
print('clipboard copy', repr(text))
def paste(self, message):
self.clientCutText(message)
return self
def updateRectangle(self, x, y, width, height, data):
# ignore empty updates
if not data:
return
size = (width, height)
update = Image.frombytes('RGB', size, data, 'raw', self.image_mode)
if not self.screen:
self.screen = update
# track upward screen resizes, often occurs during os boot of VMs
# When the screen is sent in chunks (as observed on VMWare ESXi), the canvas
# needs to be resized to fit all existing contents and the update.
elif self.screen.size[0] < (x+width) or self.screen.size[1] < (y+height):
new_size = (max(x+width, self.screen.size[0]), max(y+height, self.screen.size[1]))
new_screen = Image.new("RGB", new_size, "black")
new_screen.paste(self.screen, (0, 0))
new_screen.paste(update, (x, y))
self.screen = new_screen
else:
self.screen.paste(update, (x, y))
self.drawCursor()
def commitUpdate(self, rectangles):
if self.deferred:
d = self.deferred
self.deferred = None
d.callback(self)
def updateCursor(self, x, y, width, height, image, mask):
if self.factory.nocursor:
return
if not width or not height:
self.cursor = None
self.cursor = Image.frombytes('RGBX', (width, height), image)
self.cmask = Image.frombytes('1', (width, height), mask)
self.cfocus = x, y
self.drawCursor()
def drawCursor(self):
if not self.cursor:
return
if not self.screen:
return
x = self.x - self.cfocus[0]
y = self.y - self.cfocus[1]
self.screen.paste(self.cursor, (x, y), self.cmask)
def updateDesktopSize(self, width, height):
new_screen = Image.new("RGB", (width, height), "black")
if self.screen:
new_screen.paste(self.screen, (0, 0))
self.screen = new_screen
|
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.captureRegion | python | def captureRegion(self, filename, x, y, w, h):
log.debug('captureRegion %s', filename)
return self._capture(filename, x, y, x+w, y+h) | Save a region of the current display to filename | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L235-L239 | null | class VNCDoToolClient(rfb.RFBClient):
encoding = rfb.RAW_ENCODING
x = 0
y = 0
buttons = 0
screen = None
image_mode = "RGBX"
deferred = None
cursor = None
cmask = None
SPECIAL_KEYS_US = "~!@#$%^&*()_+{}|:\"<>?"
def connectionMade(self):
rfb.RFBClient.connectionMade(self)
if self.transport.addressFamily == socket.AF_INET:
self.transport.setTcpNoDelay(True)
def _decodeKey(self, key):
if self.factory.force_caps:
if key.isupper() or key in self.SPECIAL_KEYS_US:
key = 'shift-%c' % key
if len(key) == 1:
keys = [key]
else:
keys = key.split('-')
keys = [KEYMAP.get(k) or ord(k) for k in keys]
return keys
def pause(self, duration):
d = Deferred()
reactor.callLater(duration, d.callback, self)
return d
def keyPress(self, key):
""" Send a key press to the server
key: string: either [a-z] or a from KEYMAP
"""
log.debug('keyPress %s', key)
self.keyDown(key)
self.keyUp(key)
return self
def keyDown(self, key):
log.debug('keyDown %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=1)
return self
def keyUp(self, key):
log.debug('keyUp %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=0)
return self
def mousePress(self, button):
""" Send a mouse click at the last set position
button: int: [1-n]
"""
log.debug('mousePress %s', button)
buttons = self.buttons | (1 << (button - 1))
self.mouseDown(button)
self.mouseUp(button)
return self
def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
"""
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def mouseUp(self, button):
""" Send mouse button released at the last set position
button: int: [1-n]
"""
log.debug('mouseUp %s', button)
self.buttons &= ~(1 << (button - 1))
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def captureScreen(self, filename):
""" Save the current display to filename
"""
log.debug('captureScreen %s', filename)
return self._capture(filename)
def refreshScreen(self, incremental=0):
d = self.deferred = Deferred()
self.framebufferUpdateRequest(incremental=incremental)
return d
def _capture(self, filename, *args):
d = self.refreshScreen()
d.addCallback(self._captureSave, filename, *args)
return d
def _captureSave(self, data, filename, *args):
log.debug('captureSave %s', filename)
if args:
capture = self.screen.crop(args)
else:
capture = self.screen
capture.save(filename)
return self
def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image
"""
log.debug('expectScreen %s', filename)
return self._expectFramebuffer(filename, 0, 0, maxrms)
def expectRegion(self, filename, x, y, maxrms=0):
""" Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height)
"""
log.debug('expectRegion %s (%s, %s)', filename, x, y)
return self._expectFramebuffer(filename, x, y, maxrms)
def _expectFramebuffer(self, filename, x, y, maxrms):
self.framebufferUpdateRequest(incremental=1)
image = Image.open(filename)
w, h = image.size
self.expected = image.histogram()
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, (x, y, x + w, y + h), maxrms)
return self.deferred
def _expectCompare(self, data, box, maxrms):
image = self.screen.crop(box)
hist = image.histogram()
if len(hist) == len(self.expected):
sum_ = 0
for h, e in zip(hist, self.expected):
sum_ += (h - e) ** 2
rms = math.sqrt(sum_ / len(hist))
log.debug('rms:%s maxrms: %s', int(rms), int(maxrms))
if rms <= maxrms:
return self
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, box, maxrms)
self.framebufferUpdateRequest(incremental=1) # use box ~(x, y, w - x, h - y)?
return self.deferred
def mouseMove(self, x, y):
""" Move the mouse pointer to position (x, y)
"""
log.debug('mouseMove %d,%d', x, y)
self.x, self.y = x, y
self.pointerEvent(x, y, self.buttons)
return self
def mouseDrag(self, x, y, step=1):
""" Move the mouse point to position (x, y) in increments of step
"""
log.debug('mouseDrag %d,%d', x, y)
if x < self.x:
xsteps = [self.x - i for i in range(step, self.x - x + 1, step)]
else:
xsteps = range(self.x, x, step)
if y < self.y:
ysteps = [self.y - i for i in range(step, self.y - y + 1, step)]
else:
ysteps = range(self.y, y, step)
for ypos in ysteps:
time.sleep(.2)
self.mouseMove(self.x, ypos)
for xpos in xsteps:
time.sleep(.2)
self.mouseMove(xpos, self.y)
self.mouseMove(x, y)
return self
def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax = 63, bluemax = 31,
redshift = 11, greenshift = 5, blueshift = 0
)
self.image_mode = "BGR;16"
elif (self.truecolor and (not self.bigendian) and self.depth == 24
and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):
pixel = ["X"] * self.bypp
offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
for offset, color in zip(offsets, "RGB"):
pixel[offset] = color
self.image_mode = "".join(pixel)
else:
self.setPixelFormat()
#
# base customizations
#
def vncRequestPassword(self):
if self.factory.password is None:
self.transport.loseConnection()
self.factory.clientConnectionFailed(self, AuthenticationError('password required, but none provided'))
return
self.sendPassword(self.factory.password)
def vncConnectionMade(self):
self.setImageMode()
encodings = [self.encoding]
if self.factory.pseudocursor or self.factory.nocursor:
encodings.append(rfb.PSEUDO_CURSOR_ENCODING)
if self.factory.pseudodesktop:
encodings.append(rfb.PSEUDO_DESKTOP_SIZE_ENCODING)
self.setEncodings(encodings)
self.factory.clientConnectionMade(self)
def bell(self):
print('ding')
def copy_text(self, text):
print('clipboard copy', repr(text))
def paste(self, message):
self.clientCutText(message)
return self
def updateRectangle(self, x, y, width, height, data):
# ignore empty updates
if not data:
return
size = (width, height)
update = Image.frombytes('RGB', size, data, 'raw', self.image_mode)
if not self.screen:
self.screen = update
# track upward screen resizes, often occurs during os boot of VMs
# When the screen is sent in chunks (as observed on VMWare ESXi), the canvas
# needs to be resized to fit all existing contents and the update.
elif self.screen.size[0] < (x+width) or self.screen.size[1] < (y+height):
new_size = (max(x+width, self.screen.size[0]), max(y+height, self.screen.size[1]))
new_screen = Image.new("RGB", new_size, "black")
new_screen.paste(self.screen, (0, 0))
new_screen.paste(update, (x, y))
self.screen = new_screen
else:
self.screen.paste(update, (x, y))
self.drawCursor()
def commitUpdate(self, rectangles):
if self.deferred:
d = self.deferred
self.deferred = None
d.callback(self)
def updateCursor(self, x, y, width, height, image, mask):
if self.factory.nocursor:
return
if not width or not height:
self.cursor = None
self.cursor = Image.frombytes('RGBX', (width, height), image)
self.cmask = Image.frombytes('1', (width, height), mask)
self.cfocus = x, y
self.drawCursor()
def drawCursor(self):
if not self.cursor:
return
if not self.screen:
return
x = self.x - self.cfocus[0]
y = self.y - self.cfocus[1]
self.screen.paste(self.cursor, (x, y), self.cmask)
def updateDesktopSize(self, width, height):
new_screen = Image.new("RGB", (width, height), "black")
if self.screen:
new_screen.paste(self.screen, (0, 0))
self.screen = new_screen
|
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.expectScreen | python | def expectScreen(self, filename, maxrms=0):
log.debug('expectScreen %s', filename)
return self._expectFramebuffer(filename, 0, 0, maxrms) | Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L261-L269 | null | class VNCDoToolClient(rfb.RFBClient):
encoding = rfb.RAW_ENCODING
x = 0
y = 0
buttons = 0
screen = None
image_mode = "RGBX"
deferred = None
cursor = None
cmask = None
SPECIAL_KEYS_US = "~!@#$%^&*()_+{}|:\"<>?"
def connectionMade(self):
rfb.RFBClient.connectionMade(self)
if self.transport.addressFamily == socket.AF_INET:
self.transport.setTcpNoDelay(True)
def _decodeKey(self, key):
if self.factory.force_caps:
if key.isupper() or key in self.SPECIAL_KEYS_US:
key = 'shift-%c' % key
if len(key) == 1:
keys = [key]
else:
keys = key.split('-')
keys = [KEYMAP.get(k) or ord(k) for k in keys]
return keys
def pause(self, duration):
d = Deferred()
reactor.callLater(duration, d.callback, self)
return d
def keyPress(self, key):
""" Send a key press to the server
key: string: either [a-z] or a from KEYMAP
"""
log.debug('keyPress %s', key)
self.keyDown(key)
self.keyUp(key)
return self
def keyDown(self, key):
log.debug('keyDown %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=1)
return self
def keyUp(self, key):
log.debug('keyUp %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=0)
return self
def mousePress(self, button):
""" Send a mouse click at the last set position
button: int: [1-n]
"""
log.debug('mousePress %s', button)
buttons = self.buttons | (1 << (button - 1))
self.mouseDown(button)
self.mouseUp(button)
return self
def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
"""
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def mouseUp(self, button):
""" Send mouse button released at the last set position
button: int: [1-n]
"""
log.debug('mouseUp %s', button)
self.buttons &= ~(1 << (button - 1))
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def captureScreen(self, filename):
""" Save the current display to filename
"""
log.debug('captureScreen %s', filename)
return self._capture(filename)
def captureRegion(self, filename, x, y, w, h):
""" Save a region of the current display to filename
"""
log.debug('captureRegion %s', filename)
return self._capture(filename, x, y, x+w, y+h)
def refreshScreen(self, incremental=0):
d = self.deferred = Deferred()
self.framebufferUpdateRequest(incremental=incremental)
return d
def _capture(self, filename, *args):
d = self.refreshScreen()
d.addCallback(self._captureSave, filename, *args)
return d
def _captureSave(self, data, filename, *args):
log.debug('captureSave %s', filename)
if args:
capture = self.screen.crop(args)
else:
capture = self.screen
capture.save(filename)
return self
def expectRegion(self, filename, x, y, maxrms=0):
""" Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height)
"""
log.debug('expectRegion %s (%s, %s)', filename, x, y)
return self._expectFramebuffer(filename, x, y, maxrms)
def _expectFramebuffer(self, filename, x, y, maxrms):
self.framebufferUpdateRequest(incremental=1)
image = Image.open(filename)
w, h = image.size
self.expected = image.histogram()
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, (x, y, x + w, y + h), maxrms)
return self.deferred
def _expectCompare(self, data, box, maxrms):
image = self.screen.crop(box)
hist = image.histogram()
if len(hist) == len(self.expected):
sum_ = 0
for h, e in zip(hist, self.expected):
sum_ += (h - e) ** 2
rms = math.sqrt(sum_ / len(hist))
log.debug('rms:%s maxrms: %s', int(rms), int(maxrms))
if rms <= maxrms:
return self
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, box, maxrms)
self.framebufferUpdateRequest(incremental=1) # use box ~(x, y, w - x, h - y)?
return self.deferred
def mouseMove(self, x, y):
""" Move the mouse pointer to position (x, y)
"""
log.debug('mouseMove %d,%d', x, y)
self.x, self.y = x, y
self.pointerEvent(x, y, self.buttons)
return self
def mouseDrag(self, x, y, step=1):
""" Move the mouse point to position (x, y) in increments of step
"""
log.debug('mouseDrag %d,%d', x, y)
if x < self.x:
xsteps = [self.x - i for i in range(step, self.x - x + 1, step)]
else:
xsteps = range(self.x, x, step)
if y < self.y:
ysteps = [self.y - i for i in range(step, self.y - y + 1, step)]
else:
ysteps = range(self.y, y, step)
for ypos in ysteps:
time.sleep(.2)
self.mouseMove(self.x, ypos)
for xpos in xsteps:
time.sleep(.2)
self.mouseMove(xpos, self.y)
self.mouseMove(x, y)
return self
def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax = 63, bluemax = 31,
redshift = 11, greenshift = 5, blueshift = 0
)
self.image_mode = "BGR;16"
elif (self.truecolor and (not self.bigendian) and self.depth == 24
and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):
pixel = ["X"] * self.bypp
offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
for offset, color in zip(offsets, "RGB"):
pixel[offset] = color
self.image_mode = "".join(pixel)
else:
self.setPixelFormat()
#
# base customizations
#
def vncRequestPassword(self):
if self.factory.password is None:
self.transport.loseConnection()
self.factory.clientConnectionFailed(self, AuthenticationError('password required, but none provided'))
return
self.sendPassword(self.factory.password)
def vncConnectionMade(self):
self.setImageMode()
encodings = [self.encoding]
if self.factory.pseudocursor or self.factory.nocursor:
encodings.append(rfb.PSEUDO_CURSOR_ENCODING)
if self.factory.pseudodesktop:
encodings.append(rfb.PSEUDO_DESKTOP_SIZE_ENCODING)
self.setEncodings(encodings)
self.factory.clientConnectionMade(self)
def bell(self):
print('ding')
def copy_text(self, text):
print('clipboard copy', repr(text))
def paste(self, message):
self.clientCutText(message)
return self
def updateRectangle(self, x, y, width, height, data):
# ignore empty updates
if not data:
return
size = (width, height)
update = Image.frombytes('RGB', size, data, 'raw', self.image_mode)
if not self.screen:
self.screen = update
# track upward screen resizes, often occurs during os boot of VMs
# When the screen is sent in chunks (as observed on VMWare ESXi), the canvas
# needs to be resized to fit all existing contents and the update.
elif self.screen.size[0] < (x+width) or self.screen.size[1] < (y+height):
new_size = (max(x+width, self.screen.size[0]), max(y+height, self.screen.size[1]))
new_screen = Image.new("RGB", new_size, "black")
new_screen.paste(self.screen, (0, 0))
new_screen.paste(update, (x, y))
self.screen = new_screen
else:
self.screen.paste(update, (x, y))
self.drawCursor()
def commitUpdate(self, rectangles):
if self.deferred:
d = self.deferred
self.deferred = None
d.callback(self)
def updateCursor(self, x, y, width, height, image, mask):
if self.factory.nocursor:
return
if not width or not height:
self.cursor = None
self.cursor = Image.frombytes('RGBX', (width, height), image)
self.cmask = Image.frombytes('1', (width, height), mask)
self.cfocus = x, y
self.drawCursor()
def drawCursor(self):
if not self.cursor:
return
if not self.screen:
return
x = self.x - self.cfocus[0]
y = self.y - self.cfocus[1]
self.screen.paste(self.cursor, (x, y), self.cmask)
def updateDesktopSize(self, width, height):
new_screen = Image.new("RGB", (width, height), "black")
if self.screen:
new_screen.paste(self.screen, (0, 0))
self.screen = new_screen
|
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.expectRegion | python | def expectRegion(self, filename, x, y, maxrms=0):
log.debug('expectRegion %s (%s, %s)', filename, x, y)
return self._expectFramebuffer(filename, x, y, maxrms) | Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height) | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L271-L278 | null | class VNCDoToolClient(rfb.RFBClient):
encoding = rfb.RAW_ENCODING
x = 0
y = 0
buttons = 0
screen = None
image_mode = "RGBX"
deferred = None
cursor = None
cmask = None
SPECIAL_KEYS_US = "~!@#$%^&*()_+{}|:\"<>?"
def connectionMade(self):
rfb.RFBClient.connectionMade(self)
if self.transport.addressFamily == socket.AF_INET:
self.transport.setTcpNoDelay(True)
def _decodeKey(self, key):
if self.factory.force_caps:
if key.isupper() or key in self.SPECIAL_KEYS_US:
key = 'shift-%c' % key
if len(key) == 1:
keys = [key]
else:
keys = key.split('-')
keys = [KEYMAP.get(k) or ord(k) for k in keys]
return keys
def pause(self, duration):
d = Deferred()
reactor.callLater(duration, d.callback, self)
return d
def keyPress(self, key):
""" Send a key press to the server
key: string: either [a-z] or a from KEYMAP
"""
log.debug('keyPress %s', key)
self.keyDown(key)
self.keyUp(key)
return self
def keyDown(self, key):
log.debug('keyDown %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=1)
return self
def keyUp(self, key):
log.debug('keyUp %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=0)
return self
def mousePress(self, button):
""" Send a mouse click at the last set position
button: int: [1-n]
"""
log.debug('mousePress %s', button)
buttons = self.buttons | (1 << (button - 1))
self.mouseDown(button)
self.mouseUp(button)
return self
def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
"""
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def mouseUp(self, button):
""" Send mouse button released at the last set position
button: int: [1-n]
"""
log.debug('mouseUp %s', button)
self.buttons &= ~(1 << (button - 1))
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def captureScreen(self, filename):
""" Save the current display to filename
"""
log.debug('captureScreen %s', filename)
return self._capture(filename)
def captureRegion(self, filename, x, y, w, h):
""" Save a region of the current display to filename
"""
log.debug('captureRegion %s', filename)
return self._capture(filename, x, y, x+w, y+h)
def refreshScreen(self, incremental=0):
d = self.deferred = Deferred()
self.framebufferUpdateRequest(incremental=incremental)
return d
def _capture(self, filename, *args):
d = self.refreshScreen()
d.addCallback(self._captureSave, filename, *args)
return d
def _captureSave(self, data, filename, *args):
log.debug('captureSave %s', filename)
if args:
capture = self.screen.crop(args)
else:
capture = self.screen
capture.save(filename)
return self
def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image
"""
log.debug('expectScreen %s', filename)
return self._expectFramebuffer(filename, 0, 0, maxrms)
def _expectFramebuffer(self, filename, x, y, maxrms):
self.framebufferUpdateRequest(incremental=1)
image = Image.open(filename)
w, h = image.size
self.expected = image.histogram()
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, (x, y, x + w, y + h), maxrms)
return self.deferred
def _expectCompare(self, data, box, maxrms):
image = self.screen.crop(box)
hist = image.histogram()
if len(hist) == len(self.expected):
sum_ = 0
for h, e in zip(hist, self.expected):
sum_ += (h - e) ** 2
rms = math.sqrt(sum_ / len(hist))
log.debug('rms:%s maxrms: %s', int(rms), int(maxrms))
if rms <= maxrms:
return self
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, box, maxrms)
self.framebufferUpdateRequest(incremental=1) # use box ~(x, y, w - x, h - y)?
return self.deferred
def mouseMove(self, x, y):
""" Move the mouse pointer to position (x, y)
"""
log.debug('mouseMove %d,%d', x, y)
self.x, self.y = x, y
self.pointerEvent(x, y, self.buttons)
return self
def mouseDrag(self, x, y, step=1):
""" Move the mouse point to position (x, y) in increments of step
"""
log.debug('mouseDrag %d,%d', x, y)
if x < self.x:
xsteps = [self.x - i for i in range(step, self.x - x + 1, step)]
else:
xsteps = range(self.x, x, step)
if y < self.y:
ysteps = [self.y - i for i in range(step, self.y - y + 1, step)]
else:
ysteps = range(self.y, y, step)
for ypos in ysteps:
time.sleep(.2)
self.mouseMove(self.x, ypos)
for xpos in xsteps:
time.sleep(.2)
self.mouseMove(xpos, self.y)
self.mouseMove(x, y)
return self
def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax = 63, bluemax = 31,
redshift = 11, greenshift = 5, blueshift = 0
)
self.image_mode = "BGR;16"
elif (self.truecolor and (not self.bigendian) and self.depth == 24
and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):
pixel = ["X"] * self.bypp
offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
for offset, color in zip(offsets, "RGB"):
pixel[offset] = color
self.image_mode = "".join(pixel)
else:
self.setPixelFormat()
#
# base customizations
#
def vncRequestPassword(self):
if self.factory.password is None:
self.transport.loseConnection()
self.factory.clientConnectionFailed(self, AuthenticationError('password required, but none provided'))
return
self.sendPassword(self.factory.password)
def vncConnectionMade(self):
self.setImageMode()
encodings = [self.encoding]
if self.factory.pseudocursor or self.factory.nocursor:
encodings.append(rfb.PSEUDO_CURSOR_ENCODING)
if self.factory.pseudodesktop:
encodings.append(rfb.PSEUDO_DESKTOP_SIZE_ENCODING)
self.setEncodings(encodings)
self.factory.clientConnectionMade(self)
def bell(self):
print('ding')
def copy_text(self, text):
print('clipboard copy', repr(text))
def paste(self, message):
self.clientCutText(message)
return self
def updateRectangle(self, x, y, width, height, data):
# ignore empty updates
if not data:
return
size = (width, height)
update = Image.frombytes('RGB', size, data, 'raw', self.image_mode)
if not self.screen:
self.screen = update
# track upward screen resizes, often occurs during os boot of VMs
# When the screen is sent in chunks (as observed on VMWare ESXi), the canvas
# needs to be resized to fit all existing contents and the update.
elif self.screen.size[0] < (x+width) or self.screen.size[1] < (y+height):
new_size = (max(x+width, self.screen.size[0]), max(y+height, self.screen.size[1]))
new_screen = Image.new("RGB", new_size, "black")
new_screen.paste(self.screen, (0, 0))
new_screen.paste(update, (x, y))
self.screen = new_screen
else:
self.screen.paste(update, (x, y))
self.drawCursor()
def commitUpdate(self, rectangles):
if self.deferred:
d = self.deferred
self.deferred = None
d.callback(self)
def updateCursor(self, x, y, width, height, image, mask):
if self.factory.nocursor:
return
if not width or not height:
self.cursor = None
self.cursor = Image.frombytes('RGBX', (width, height), image)
self.cmask = Image.frombytes('1', (width, height), mask)
self.cfocus = x, y
self.drawCursor()
def drawCursor(self):
if not self.cursor:
return
if not self.screen:
return
x = self.x - self.cfocus[0]
y = self.y - self.cfocus[1]
self.screen.paste(self.cursor, (x, y), self.cmask)
def updateDesktopSize(self, width, height):
new_screen = Image.new("RGB", (width, height), "black")
if self.screen:
new_screen.paste(self.screen, (0, 0))
self.screen = new_screen
|
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.mouseMove | python | def mouseMove(self, x, y):
log.debug('mouseMove %d,%d', x, y)
self.x, self.y = x, y
self.pointerEvent(x, y, self.buttons)
return self | Move the mouse pointer to position (x, y) | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L310-L316 | null | class VNCDoToolClient(rfb.RFBClient):
encoding = rfb.RAW_ENCODING
x = 0
y = 0
buttons = 0
screen = None
image_mode = "RGBX"
deferred = None
cursor = None
cmask = None
SPECIAL_KEYS_US = "~!@#$%^&*()_+{}|:\"<>?"
def connectionMade(self):
rfb.RFBClient.connectionMade(self)
if self.transport.addressFamily == socket.AF_INET:
self.transport.setTcpNoDelay(True)
def _decodeKey(self, key):
if self.factory.force_caps:
if key.isupper() or key in self.SPECIAL_KEYS_US:
key = 'shift-%c' % key
if len(key) == 1:
keys = [key]
else:
keys = key.split('-')
keys = [KEYMAP.get(k) or ord(k) for k in keys]
return keys
def pause(self, duration):
d = Deferred()
reactor.callLater(duration, d.callback, self)
return d
def keyPress(self, key):
""" Send a key press to the server
key: string: either [a-z] or a from KEYMAP
"""
log.debug('keyPress %s', key)
self.keyDown(key)
self.keyUp(key)
return self
def keyDown(self, key):
log.debug('keyDown %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=1)
return self
def keyUp(self, key):
log.debug('keyUp %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=0)
return self
def mousePress(self, button):
""" Send a mouse click at the last set position
button: int: [1-n]
"""
log.debug('mousePress %s', button)
buttons = self.buttons | (1 << (button - 1))
self.mouseDown(button)
self.mouseUp(button)
return self
def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
"""
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def mouseUp(self, button):
""" Send mouse button released at the last set position
button: int: [1-n]
"""
log.debug('mouseUp %s', button)
self.buttons &= ~(1 << (button - 1))
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def captureScreen(self, filename):
""" Save the current display to filename
"""
log.debug('captureScreen %s', filename)
return self._capture(filename)
def captureRegion(self, filename, x, y, w, h):
""" Save a region of the current display to filename
"""
log.debug('captureRegion %s', filename)
return self._capture(filename, x, y, x+w, y+h)
def refreshScreen(self, incremental=0):
d = self.deferred = Deferred()
self.framebufferUpdateRequest(incremental=incremental)
return d
def _capture(self, filename, *args):
d = self.refreshScreen()
d.addCallback(self._captureSave, filename, *args)
return d
def _captureSave(self, data, filename, *args):
log.debug('captureSave %s', filename)
if args:
capture = self.screen.crop(args)
else:
capture = self.screen
capture.save(filename)
return self
def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image
"""
log.debug('expectScreen %s', filename)
return self._expectFramebuffer(filename, 0, 0, maxrms)
def expectRegion(self, filename, x, y, maxrms=0):
""" Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height)
"""
log.debug('expectRegion %s (%s, %s)', filename, x, y)
return self._expectFramebuffer(filename, x, y, maxrms)
def _expectFramebuffer(self, filename, x, y, maxrms):
self.framebufferUpdateRequest(incremental=1)
image = Image.open(filename)
w, h = image.size
self.expected = image.histogram()
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, (x, y, x + w, y + h), maxrms)
return self.deferred
def _expectCompare(self, data, box, maxrms):
image = self.screen.crop(box)
hist = image.histogram()
if len(hist) == len(self.expected):
sum_ = 0
for h, e in zip(hist, self.expected):
sum_ += (h - e) ** 2
rms = math.sqrt(sum_ / len(hist))
log.debug('rms:%s maxrms: %s', int(rms), int(maxrms))
if rms <= maxrms:
return self
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, box, maxrms)
self.framebufferUpdateRequest(incremental=1) # use box ~(x, y, w - x, h - y)?
return self.deferred
def mouseDrag(self, x, y, step=1):
""" Move the mouse point to position (x, y) in increments of step
"""
log.debug('mouseDrag %d,%d', x, y)
if x < self.x:
xsteps = [self.x - i for i in range(step, self.x - x + 1, step)]
else:
xsteps = range(self.x, x, step)
if y < self.y:
ysteps = [self.y - i for i in range(step, self.y - y + 1, step)]
else:
ysteps = range(self.y, y, step)
for ypos in ysteps:
time.sleep(.2)
self.mouseMove(self.x, ypos)
for xpos in xsteps:
time.sleep(.2)
self.mouseMove(xpos, self.y)
self.mouseMove(x, y)
return self
def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax = 63, bluemax = 31,
redshift = 11, greenshift = 5, blueshift = 0
)
self.image_mode = "BGR;16"
elif (self.truecolor and (not self.bigendian) and self.depth == 24
and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):
pixel = ["X"] * self.bypp
offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
for offset, color in zip(offsets, "RGB"):
pixel[offset] = color
self.image_mode = "".join(pixel)
else:
self.setPixelFormat()
#
# base customizations
#
def vncRequestPassword(self):
if self.factory.password is None:
self.transport.loseConnection()
self.factory.clientConnectionFailed(self, AuthenticationError('password required, but none provided'))
return
self.sendPassword(self.factory.password)
def vncConnectionMade(self):
self.setImageMode()
encodings = [self.encoding]
if self.factory.pseudocursor or self.factory.nocursor:
encodings.append(rfb.PSEUDO_CURSOR_ENCODING)
if self.factory.pseudodesktop:
encodings.append(rfb.PSEUDO_DESKTOP_SIZE_ENCODING)
self.setEncodings(encodings)
self.factory.clientConnectionMade(self)
def bell(self):
print('ding')
def copy_text(self, text):
print('clipboard copy', repr(text))
def paste(self, message):
self.clientCutText(message)
return self
def updateRectangle(self, x, y, width, height, data):
# ignore empty updates
if not data:
return
size = (width, height)
update = Image.frombytes('RGB', size, data, 'raw', self.image_mode)
if not self.screen:
self.screen = update
# track upward screen resizes, often occurs during os boot of VMs
# When the screen is sent in chunks (as observed on VMWare ESXi), the canvas
# needs to be resized to fit all existing contents and the update.
elif self.screen.size[0] < (x+width) or self.screen.size[1] < (y+height):
new_size = (max(x+width, self.screen.size[0]), max(y+height, self.screen.size[1]))
new_screen = Image.new("RGB", new_size, "black")
new_screen.paste(self.screen, (0, 0))
new_screen.paste(update, (x, y))
self.screen = new_screen
else:
self.screen.paste(update, (x, y))
self.drawCursor()
def commitUpdate(self, rectangles):
if self.deferred:
d = self.deferred
self.deferred = None
d.callback(self)
def updateCursor(self, x, y, width, height, image, mask):
if self.factory.nocursor:
return
if not width or not height:
self.cursor = None
self.cursor = Image.frombytes('RGBX', (width, height), image)
self.cmask = Image.frombytes('1', (width, height), mask)
self.cfocus = x, y
self.drawCursor()
def drawCursor(self):
if not self.cursor:
return
if not self.screen:
return
x = self.x - self.cfocus[0]
y = self.y - self.cfocus[1]
self.screen.paste(self.cursor, (x, y), self.cmask)
def updateDesktopSize(self, width, height):
new_screen = Image.new("RGB", (width, height), "black")
if self.screen:
new_screen.paste(self.screen, (0, 0))
self.screen = new_screen
|
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.mouseDrag | python | def mouseDrag(self, x, y, step=1):
log.debug('mouseDrag %d,%d', x, y)
if x < self.x:
xsteps = [self.x - i for i in range(step, self.x - x + 1, step)]
else:
xsteps = range(self.x, x, step)
if y < self.y:
ysteps = [self.y - i for i in range(step, self.y - y + 1, step)]
else:
ysteps = range(self.y, y, step)
for ypos in ysteps:
time.sleep(.2)
self.mouseMove(self.x, ypos)
for xpos in xsteps:
time.sleep(.2)
self.mouseMove(xpos, self.y)
self.mouseMove(x, y)
return self | Move the mouse point to position (x, y) in increments of step | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L318-L342 | null | class VNCDoToolClient(rfb.RFBClient):
encoding = rfb.RAW_ENCODING
x = 0
y = 0
buttons = 0
screen = None
image_mode = "RGBX"
deferred = None
cursor = None
cmask = None
SPECIAL_KEYS_US = "~!@#$%^&*()_+{}|:\"<>?"
def connectionMade(self):
rfb.RFBClient.connectionMade(self)
if self.transport.addressFamily == socket.AF_INET:
self.transport.setTcpNoDelay(True)
def _decodeKey(self, key):
if self.factory.force_caps:
if key.isupper() or key in self.SPECIAL_KEYS_US:
key = 'shift-%c' % key
if len(key) == 1:
keys = [key]
else:
keys = key.split('-')
keys = [KEYMAP.get(k) or ord(k) for k in keys]
return keys
def pause(self, duration):
d = Deferred()
reactor.callLater(duration, d.callback, self)
return d
def keyPress(self, key):
""" Send a key press to the server
key: string: either [a-z] or a from KEYMAP
"""
log.debug('keyPress %s', key)
self.keyDown(key)
self.keyUp(key)
return self
def keyDown(self, key):
log.debug('keyDown %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=1)
return self
def keyUp(self, key):
log.debug('keyUp %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=0)
return self
def mousePress(self, button):
""" Send a mouse click at the last set position
button: int: [1-n]
"""
log.debug('mousePress %s', button)
buttons = self.buttons | (1 << (button - 1))
self.mouseDown(button)
self.mouseUp(button)
return self
def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
"""
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def mouseUp(self, button):
""" Send mouse button released at the last set position
button: int: [1-n]
"""
log.debug('mouseUp %s', button)
self.buttons &= ~(1 << (button - 1))
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def captureScreen(self, filename):
""" Save the current display to filename
"""
log.debug('captureScreen %s', filename)
return self._capture(filename)
def captureRegion(self, filename, x, y, w, h):
""" Save a region of the current display to filename
"""
log.debug('captureRegion %s', filename)
return self._capture(filename, x, y, x+w, y+h)
def refreshScreen(self, incremental=0):
d = self.deferred = Deferred()
self.framebufferUpdateRequest(incremental=incremental)
return d
def _capture(self, filename, *args):
d = self.refreshScreen()
d.addCallback(self._captureSave, filename, *args)
return d
def _captureSave(self, data, filename, *args):
log.debug('captureSave %s', filename)
if args:
capture = self.screen.crop(args)
else:
capture = self.screen
capture.save(filename)
return self
def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image
"""
log.debug('expectScreen %s', filename)
return self._expectFramebuffer(filename, 0, 0, maxrms)
def expectRegion(self, filename, x, y, maxrms=0):
""" Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height)
"""
log.debug('expectRegion %s (%s, %s)', filename, x, y)
return self._expectFramebuffer(filename, x, y, maxrms)
def _expectFramebuffer(self, filename, x, y, maxrms):
self.framebufferUpdateRequest(incremental=1)
image = Image.open(filename)
w, h = image.size
self.expected = image.histogram()
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, (x, y, x + w, y + h), maxrms)
return self.deferred
def _expectCompare(self, data, box, maxrms):
image = self.screen.crop(box)
hist = image.histogram()
if len(hist) == len(self.expected):
sum_ = 0
for h, e in zip(hist, self.expected):
sum_ += (h - e) ** 2
rms = math.sqrt(sum_ / len(hist))
log.debug('rms:%s maxrms: %s', int(rms), int(maxrms))
if rms <= maxrms:
return self
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, box, maxrms)
self.framebufferUpdateRequest(incremental=1) # use box ~(x, y, w - x, h - y)?
return self.deferred
def mouseMove(self, x, y):
""" Move the mouse pointer to position (x, y)
"""
log.debug('mouseMove %d,%d', x, y)
self.x, self.y = x, y
self.pointerEvent(x, y, self.buttons)
return self
def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax = 63, bluemax = 31,
redshift = 11, greenshift = 5, blueshift = 0
)
self.image_mode = "BGR;16"
elif (self.truecolor and (not self.bigendian) and self.depth == 24
and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):
pixel = ["X"] * self.bypp
offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
for offset, color in zip(offsets, "RGB"):
pixel[offset] = color
self.image_mode = "".join(pixel)
else:
self.setPixelFormat()
#
# base customizations
#
def vncRequestPassword(self):
if self.factory.password is None:
self.transport.loseConnection()
self.factory.clientConnectionFailed(self, AuthenticationError('password required, but none provided'))
return
self.sendPassword(self.factory.password)
def vncConnectionMade(self):
self.setImageMode()
encodings = [self.encoding]
if self.factory.pseudocursor or self.factory.nocursor:
encodings.append(rfb.PSEUDO_CURSOR_ENCODING)
if self.factory.pseudodesktop:
encodings.append(rfb.PSEUDO_DESKTOP_SIZE_ENCODING)
self.setEncodings(encodings)
self.factory.clientConnectionMade(self)
def bell(self):
print('ding')
def copy_text(self, text):
print('clipboard copy', repr(text))
def paste(self, message):
self.clientCutText(message)
return self
def updateRectangle(self, x, y, width, height, data):
# ignore empty updates
if not data:
return
size = (width, height)
update = Image.frombytes('RGB', size, data, 'raw', self.image_mode)
if not self.screen:
self.screen = update
# track upward screen resizes, often occurs during os boot of VMs
# When the screen is sent in chunks (as observed on VMWare ESXi), the canvas
# needs to be resized to fit all existing contents and the update.
elif self.screen.size[0] < (x+width) or self.screen.size[1] < (y+height):
new_size = (max(x+width, self.screen.size[0]), max(y+height, self.screen.size[1]))
new_screen = Image.new("RGB", new_size, "black")
new_screen.paste(self.screen, (0, 0))
new_screen.paste(update, (x, y))
self.screen = new_screen
else:
self.screen.paste(update, (x, y))
self.drawCursor()
def commitUpdate(self, rectangles):
if self.deferred:
d = self.deferred
self.deferred = None
d.callback(self)
def updateCursor(self, x, y, width, height, image, mask):
if self.factory.nocursor:
return
if not width or not height:
self.cursor = None
self.cursor = Image.frombytes('RGBX', (width, height), image)
self.cmask = Image.frombytes('1', (width, height), mask)
self.cfocus = x, y
self.drawCursor()
def drawCursor(self):
if not self.cursor:
return
if not self.screen:
return
x = self.x - self.cfocus[0]
y = self.y - self.cfocus[1]
self.screen.paste(self.cursor, (x, y), self.cmask)
def updateDesktopSize(self, width, height):
new_screen = Image.new("RGB", (width, height), "black")
if self.screen:
new_screen.paste(self.screen, (0, 0))
self.screen = new_screen
|
sibson/vncdotool | vncdotool/client.py | VNCDoToolClient.setImageMode | python | def setImageMode(self):
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax = 63, bluemax = 31,
redshift = 11, greenshift = 5, blueshift = 0
)
self.image_mode = "BGR;16"
elif (self.truecolor and (not self.bigendian) and self.depth == 24
and self.redmax == 255 and self.greenmax == 255 and self.bluemax == 255):
pixel = ["X"] * self.bypp
offsets = [offset // 8 for offset in (self.redshift, self.greenshift, self.blueshift)]
for offset, color in zip(offsets, "RGB"):
pixel[offset] = color
self.image_mode = "".join(pixel)
else:
self.setPixelFormat() | Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/client.py#L344-L363 | null | class VNCDoToolClient(rfb.RFBClient):
encoding = rfb.RAW_ENCODING
x = 0
y = 0
buttons = 0
screen = None
image_mode = "RGBX"
deferred = None
cursor = None
cmask = None
SPECIAL_KEYS_US = "~!@#$%^&*()_+{}|:\"<>?"
def connectionMade(self):
rfb.RFBClient.connectionMade(self)
if self.transport.addressFamily == socket.AF_INET:
self.transport.setTcpNoDelay(True)
def _decodeKey(self, key):
if self.factory.force_caps:
if key.isupper() or key in self.SPECIAL_KEYS_US:
key = 'shift-%c' % key
if len(key) == 1:
keys = [key]
else:
keys = key.split('-')
keys = [KEYMAP.get(k) or ord(k) for k in keys]
return keys
def pause(self, duration):
d = Deferred()
reactor.callLater(duration, d.callback, self)
return d
def keyPress(self, key):
""" Send a key press to the server
key: string: either [a-z] or a from KEYMAP
"""
log.debug('keyPress %s', key)
self.keyDown(key)
self.keyUp(key)
return self
def keyDown(self, key):
log.debug('keyDown %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=1)
return self
def keyUp(self, key):
log.debug('keyUp %s', key)
keys = self._decodeKey(key)
for k in keys:
self.keyEvent(k, down=0)
return self
def mousePress(self, button):
""" Send a mouse click at the last set position
button: int: [1-n]
"""
log.debug('mousePress %s', button)
buttons = self.buttons | (1 << (button - 1))
self.mouseDown(button)
self.mouseUp(button)
return self
def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
"""
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def mouseUp(self, button):
""" Send mouse button released at the last set position
button: int: [1-n]
"""
log.debug('mouseUp %s', button)
self.buttons &= ~(1 << (button - 1))
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self
def captureScreen(self, filename):
""" Save the current display to filename
"""
log.debug('captureScreen %s', filename)
return self._capture(filename)
def captureRegion(self, filename, x, y, w, h):
""" Save a region of the current display to filename
"""
log.debug('captureRegion %s', filename)
return self._capture(filename, x, y, x+w, y+h)
def refreshScreen(self, incremental=0):
d = self.deferred = Deferred()
self.framebufferUpdateRequest(incremental=incremental)
return d
def _capture(self, filename, *args):
d = self.refreshScreen()
d.addCallback(self._captureSave, filename, *args)
return d
def _captureSave(self, data, filename, *args):
log.debug('captureSave %s', filename)
if args:
capture = self.screen.crop(args)
else:
capture = self.screen
capture.save(filename)
return self
def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image
"""
log.debug('expectScreen %s', filename)
return self._expectFramebuffer(filename, 0, 0, maxrms)
def expectRegion(self, filename, x, y, maxrms=0):
""" Wait until a portion of the screen matches the target image
The region compared is defined by the box
(x, y), (x + image.width, y + image.height)
"""
log.debug('expectRegion %s (%s, %s)', filename, x, y)
return self._expectFramebuffer(filename, x, y, maxrms)
def _expectFramebuffer(self, filename, x, y, maxrms):
self.framebufferUpdateRequest(incremental=1)
image = Image.open(filename)
w, h = image.size
self.expected = image.histogram()
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, (x, y, x + w, y + h), maxrms)
return self.deferred
def _expectCompare(self, data, box, maxrms):
image = self.screen.crop(box)
hist = image.histogram()
if len(hist) == len(self.expected):
sum_ = 0
for h, e in zip(hist, self.expected):
sum_ += (h - e) ** 2
rms = math.sqrt(sum_ / len(hist))
log.debug('rms:%s maxrms: %s', int(rms), int(maxrms))
if rms <= maxrms:
return self
self.deferred = Deferred()
self.deferred.addCallback(self._expectCompare, box, maxrms)
self.framebufferUpdateRequest(incremental=1) # use box ~(x, y, w - x, h - y)?
return self.deferred
def mouseMove(self, x, y):
""" Move the mouse pointer to position (x, y)
"""
log.debug('mouseMove %d,%d', x, y)
self.x, self.y = x, y
self.pointerEvent(x, y, self.buttons)
return self
def mouseDrag(self, x, y, step=1):
""" Move the mouse point to position (x, y) in increments of step
"""
log.debug('mouseDrag %d,%d', x, y)
if x < self.x:
xsteps = [self.x - i for i in range(step, self.x - x + 1, step)]
else:
xsteps = range(self.x, x, step)
if y < self.y:
ysteps = [self.y - i for i in range(step, self.y - y + 1, step)]
else:
ysteps = range(self.y, y, step)
for ypos in ysteps:
time.sleep(.2)
self.mouseMove(self.x, ypos)
for xpos in xsteps:
time.sleep(.2)
self.mouseMove(xpos, self.y)
self.mouseMove(x, y)
return self
#
# base customizations
#
def vncRequestPassword(self):
if self.factory.password is None:
self.transport.loseConnection()
self.factory.clientConnectionFailed(self, AuthenticationError('password required, but none provided'))
return
self.sendPassword(self.factory.password)
def vncConnectionMade(self):
self.setImageMode()
encodings = [self.encoding]
if self.factory.pseudocursor or self.factory.nocursor:
encodings.append(rfb.PSEUDO_CURSOR_ENCODING)
if self.factory.pseudodesktop:
encodings.append(rfb.PSEUDO_DESKTOP_SIZE_ENCODING)
self.setEncodings(encodings)
self.factory.clientConnectionMade(self)
def bell(self):
print('ding')
def copy_text(self, text):
print('clipboard copy', repr(text))
def paste(self, message):
self.clientCutText(message)
return self
def updateRectangle(self, x, y, width, height, data):
# ignore empty updates
if not data:
return
size = (width, height)
update = Image.frombytes('RGB', size, data, 'raw', self.image_mode)
if not self.screen:
self.screen = update
# track upward screen resizes, often occurs during os boot of VMs
# When the screen is sent in chunks (as observed on VMWare ESXi), the canvas
# needs to be resized to fit all existing contents and the update.
elif self.screen.size[0] < (x+width) or self.screen.size[1] < (y+height):
new_size = (max(x+width, self.screen.size[0]), max(y+height, self.screen.size[1]))
new_screen = Image.new("RGB", new_size, "black")
new_screen.paste(self.screen, (0, 0))
new_screen.paste(update, (x, y))
self.screen = new_screen
else:
self.screen.paste(update, (x, y))
self.drawCursor()
def commitUpdate(self, rectangles):
if self.deferred:
d = self.deferred
self.deferred = None
d.callback(self)
def updateCursor(self, x, y, width, height, image, mask):
if self.factory.nocursor:
return
if not width or not height:
self.cursor = None
self.cursor = Image.frombytes('RGBX', (width, height), image)
self.cmask = Image.frombytes('1', (width, height), mask)
self.cfocus = x, y
self.drawCursor()
def drawCursor(self):
if not self.cursor:
return
if not self.screen:
return
x = self.x - self.cfocus[0]
y = self.y - self.cfocus[1]
self.screen.paste(self.cursor, (x, y), self.cmask)
def updateDesktopSize(self, width, height):
new_screen = Image.new("RGB", (width, height), "black")
if self.screen:
new_screen.paste(self.screen, (0, 0))
self.screen = new_screen
|
sibson/vncdotool | vncdotool/rfb.py | RFBClient.sendPassword | python | def sendPassword(self, password):
pw = (password + '\0' * 8)[:8] #make sure its 8 chars long, zero padded
des = RFBDes(pw)
response = des.encrypt(self._challenge)
self.transport.write(response) | send password | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L209-L214 | [
"def encrypt(self, data, pad=None, padmode=None):\n\t\"\"\"encrypt(data, [pad], [padmode]) -> bytes\n\n\tdata : Bytes to be encrypted\n\tpad : Optional argument for encryption padding. Must only be one byte\n\tpadmode : Optional argument for overriding the padding mode.\n\n\tThe data must be a multiple of 8 bytes and will be encrypted\n\twith the already specified key. Data does not have to be a\n\tmultiple of 8 bytes if the padding character is supplied, or\n\tthe padmode is set to PAD_PKCS5, as bytes will then added to\n\tensure the be padded data is a multiple of 8 bytes.\n\t\"\"\"\n\tdata = self._guardAgainstUnicode(data)\n\tif pad is not None:\n\t\tpad = self._guardAgainstUnicode(pad)\n\tdata = self._padData(data, pad, padmode)\n\treturn self.crypt(data, des.ENCRYPT)\n"
] | class RFBClient(Protocol):
def __init__(self):
self._packet = []
self._packet_len = 0
self._handler = self._handleInitial
self._already_expecting = 0
self._version = None
self._version_server = None
#------------------------------------------------------
# states used on connection startup
#------------------------------------------------------
def _handleInitial(self):
buffer = b''.join(self._packet)
if b'\n' in buffer:
version = 3.3
if buffer[:3] == b'RFB':
version_server = float(buffer[3:-1].replace(b'0', b''))
SUPPORTED_VERSIONS = (3.3, 3.7, 3.8)
if version_server in SUPPORTED_VERSIONS:
version = version_server
else:
log.msg("Protocol version %.3f not supported"
% version_server)
version = max(filter(
lambda x: x <= version_server, SUPPORTED_VERSIONS))
buffer = buffer[12:]
log.msg("Using protocol version %.3f" % version)
parts = str(version).split('.')
self.transport.write(
bytes(b"RFB %03d.%03d\n" % (int(parts[0]), int(parts[1]))))
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._handler = self._handleExpected
self._version = version
self._version_server = version_server
if version < 3.7:
self.expect(self._handleAuth, 4)
else:
self.expect(self._handleNumberSecurityTypes, 1)
else:
self._packet[:] = [buffer]
self._packet_len = len(buffer)
def _handleNumberSecurityTypes(self, block):
(num_types,) = unpack("!B", block)
if num_types:
self.expect(self._handleSecurityTypes, num_types)
else:
self.expect(self._handleConnFailed, 4)
def _handleSecurityTypes(self, block):
types = unpack("!%dB" % len(block), block)
SUPPORTED_TYPES = (1, 2)
valid_types = [sec_type for sec_type in types if sec_type in SUPPORTED_TYPES]
if valid_types:
sec_type = max(valid_types)
self.transport.write(pack("!B", sec_type))
if sec_type == 1:
if self._version < 3.8:
self._doClientInitialization()
else:
self.expect(self._handleVNCAuthResult, 4)
else:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown security types: %s" % repr(types))
def _handleAuth(self, block):
(auth,) = unpack("!I", block)
#~ print "auth:", auth
if auth == 0:
self.expect(self._handleConnFailed, 4)
elif auth == 1:
self._doClientInitialization()
return
elif auth == 2:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown auth response (%d)" % auth)
def _handleConnFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleConnMessage, waitfor)
def _handleConnMessage(self, block):
log.msg("Connection refused: %r" % block)
def _handleVNCAuth(self, block):
self._challenge = block
self.vncRequestPassword()
self.expect(self._handleVNCAuthResult, 4)
def _handleVNCAuthResult(self, block):
(result,) = unpack("!I", block)
#~ print "auth:", auth
if result == 0: #OK
self._doClientInitialization()
return
elif result == 1: #failed
if self._version < 3.8:
self.vncAuthFailed("authentication failed")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
elif result == 2: #too many
if self._version < 3.8:
self.vncAuthFailed("too many tries to log in")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
else:
log.msg("unknown auth response (%d)" % result)
def _handleAuthFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleAuthFailedMessage, waitfor)
def _handleAuthFailedMessage(self, block):
self.vncAuthFailed(block)
self.transport.loseConnection()
def _doClientInitialization(self):
self.transport.write(pack("!B", self.factory.shared))
self.expect(self._handleServerInit, 24)
def _handleServerInit(self, block):
(self.width, self.height, pixformat, namelen) = unpack("!HH16sI", block)
(self.bpp, self.depth, self.bigendian, self.truecolor,
self.redmax, self.greenmax, self.bluemax,
self.redshift, self.greenshift, self.blueshift) = \
unpack("!BBBBHHHBBBxxx", pixformat)
self.bypp = self.bpp // 8 #calc bytes per pixel
self.expect(self._handleServerName, namelen)
def _handleServerName(self, block):
self.name = block
#callback:
self.vncConnectionMade()
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# Server to client messages
#------------------------------------------------------
def _handleConnection(self, block):
(msgid,) = unpack("!B", block)
if msgid == 0:
self.expect(self._handleFramebufferUpdate, 3)
elif msgid == 2:
self.bell()
self.expect(self._handleConnection, 1)
elif msgid == 3:
self.expect(self._handleServerCutText, 7)
else:
log.msg("unknown message received (id %d)" % msgid)
self.expect(self._handleConnection, 1)
def _handleFramebufferUpdate(self, block):
(self.rectangles,) = unpack("!xH", block)
self.rectanglePos = []
self.beginUpdate()
self._doConnection()
def _doConnection(self):
if self.rectangles:
self.expect(self._handleRectangle, 12)
else:
self.commitUpdate(self.rectanglePos)
self.expect(self._handleConnection, 1)
def _handleRectangle(self, block):
(x, y, width, height, encoding) = unpack("!HHHHi", block)
if self.rectangles:
self.rectangles -= 1
self.rectanglePos.append( (x, y, width, height) )
if encoding == COPY_RECTANGLE_ENCODING:
self.expect(self._handleDecodeCopyrect, 4, x, y, width, height)
elif encoding == RAW_ENCODING:
self.expect(self._handleDecodeRAW, width*height*self.bypp, x, y, width, height)
elif encoding == HEXTILE_ENCODING:
self._doNextHextileSubrect(None, None, x, y, width, height, None, None)
elif encoding == CORRE_ENCODING:
self.expect(self._handleDecodeCORRE, 4 + self.bypp, x, y, width, height)
elif encoding == RRE_ENCODING:
self.expect(self._handleDecodeRRE, 4 + self.bypp, x, y, width, height)
#~ elif encoding == ZRLE_ENCODING:
#~ self.expect(self._handleDecodeZRLE, )
elif encoding == PSEUDO_CURSOR_ENCODING:
length = width * height * self.bypp
length += int(math.floor((width + 7.0) / 8)) * height
self.expect(self._handleDecodePsuedoCursor, length, x, y, width, height)
elif encoding == PSEUDO_DESKTOP_SIZE_ENCODING:
self._handleDecodeDesktopSize(width, height)
else:
log.msg("unknown encoding received (encoding %d)" % encoding)
self._doConnection()
else:
self._doConnection()
# --- RAW Encoding
def _handleDecodeRAW(self, block, x, y, width, height):
#TODO convert pixel format?
self.updateRectangle(x, y, width, height, block)
self._doConnection()
# --- CopyRect Encoding
def _handleDecodeCopyrect(self, block, x, y, width, height):
(srcx, srcy) = unpack("!HH", block)
self.copyRectangle(srcx, srcy, x, y, width, height)
self._doConnection()
# --- RRE Encoding
def _handleDecodeRRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleRRESubRectangles, (8 + self.bypp) * subrects, x, y)
else:
self._doConnection()
def _handleRRESubRectangles(self, block, topx, topy):
#~ print "_handleRRESubRectangle"
pos = 0
end = len(block)
sz = self.bypp + 8
format = "!%dsHHHH" % self.bypp
while pos < end:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- CoRRE Encoding
def _handleDecodeCORRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleDecodeCORRERectangles, (4 + self.bypp)*subrects, x, y)
else:
self._doConnection()
def _handleDecodeCORRERectangles(self, block, topx, topy):
#~ print "_handleDecodeCORRERectangle"
pos = 0
end = len(block)
sz = self.bypp + 4
format = "!%dsBBBB" % self.bypp
while pos < sz:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- Hexile Encoding
def _doNextHextileSubrect(self, bg, color, x, y, width, height, tx, ty):
#~ print "_doNextHextileSubrect %r" % ((color, x, y, width, height, tx, ty), )
#coords of next tile
#its line after line of tiles
#finished when the last line is completly received
#dont inc the first time
if tx is not None:
#calc next subrect pos
tx += 16
if tx >= x + width:
tx = x
ty += 16
else:
tx = x
ty = y
#more tiles?
if ty >= y + height:
self._doConnection()
else:
self.expect(self._handleDecodeHextile, 1, bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextile(self, block, bg, color, x, y, width, height, tx, ty):
(subencoding,) = unpack("!B", block)
#calc tile size
tw = th = 16
if x + width - tx < 16: tw = x + width - tx
if y + height - ty < 16: th = y + height- ty
#decode tile
if subencoding & 1: #RAW
self.expect(self._handleDecodeHextileRAW, tw*th*self.bypp, bg, color, x, y, width, height, tx, ty, tw, th)
else:
numbytes = 0
if subencoding & 2: #BackgroundSpecified
numbytes += self.bypp
if subencoding & 4: #ForegroundSpecified
numbytes += self.bypp
if subencoding & 8: #AnySubrects
numbytes += 1
if numbytes:
self.expect(self._handleDecodeHextileSubrect, numbytes, subencoding, bg, color, x, y, width, height, tx, ty, tw, th)
else:
self.fillRectangle(tx, ty, tw, th, bg)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrect(self, block, subencoding, bg, color, x, y, width, height, tx, ty, tw, th):
subrects = 0
pos = 0
if subencoding & 2: #BackgroundSpecified
bg = block[:self.bypp]
pos += self.bypp
self.fillRectangle(tx, ty, tw, th, bg)
if subencoding & 4: #ForegroundSpecified
color = block[pos:pos+self.bypp]
pos += self.bypp
if subencoding & 8: #AnySubrects
#~ (subrects, ) = unpack("!B", block)
subrects = ord(block[pos])
#~ print subrects
if subrects:
if subencoding & 16: #SubrectsColoured
self.expect(self._handleDecodeHextileSubrectsColoured, (self.bypp + 2)*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self.expect(self._handleDecodeHextileSubrectsFG, 2*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):
"""the tile is in raw encoding"""
self.updateRectangle(tx, ty, tw, th, block)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""subrects with their own color"""
sz = self.bypp + 2
pos = 0
end = len(block)
while pos < end:
pos2 = pos + self.bypp
color = block[pos:pos2]
xy = ord(block[pos2])
wh = ord(block[pos2+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += sz
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsFG(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""all subrect with same color"""
pos = 0
end = len(block)
while pos < end:
xy = ord(block[pos])
wh = ord(block[pos+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += 2
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
# --- ZRLE Encoding
def _handleDecodeZRLE(self, block):
raise NotImplementedError
# --- Pseudo Cursor Encoding
def _handleDecodePsuedoCursor(self, block, x, y, width, height):
split = width * height * self.bypp
image = block[:split]
mask = block[split:]
self.updateCursor(x, y, width, height, image, mask)
self._doConnection()
# --- Pseudo Desktop Size Encoding
def _handleDecodeDesktopSize(self, width, height):
self.updateDesktopSize(width, height)
self._doConnection()
# --- other server messages
def _handleServerCutText(self, block):
(length, ) = unpack("!xxxI", block)
self.expect(self._handleServerCutTextValue, length)
def _handleServerCutTextValue(self, block):
self.copy_text(block)
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# incomming data redirector
#------------------------------------------------------
def dataReceived(self, data):
#~ sys.stdout.write(repr(data) + '\n')
#~ print len(data), ", ", len(self._packet)
self._packet.append(data)
self._packet_len += len(data)
self._handler()
def _handleExpected(self):
if self._packet_len >= self._expected_len:
buffer = b''.join(self._packet)
while len(buffer) >= self._expected_len:
self._already_expecting = 1
block, buffer = buffer[:self._expected_len], buffer[self._expected_len:]
#~ log.msg("handle %r with %r\n" % (block, self._expected_handler.__name__))
self._expected_handler(block, *self._expected_args, **self._expected_kwargs)
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._already_expecting = 0
def expect(self, handler, size, *args, **kwargs):
#~ log.msg("expect(%r, %r, %r, %r)\n" % (handler.__name__, size, args, kwargs))
self._expected_handler = handler
self._expected_len = size
self._expected_args = args
self._expected_kwargs = kwargs
if not self._already_expecting:
self._handleExpected() #just in case that there is already enough data
#------------------------------------------------------
# client -> server messages
#------------------------------------------------------
def setPixelFormat(self, bpp=32, depth=24, bigendian=0, truecolor=1, redmax=255, greenmax=255, bluemax=255, redshift=0, greenshift=8, blueshift=16):
pixformat = pack("!BBBBHHHBBBxxx", bpp, depth, bigendian, truecolor, redmax, greenmax, bluemax, redshift, greenshift, blueshift)
self.transport.write(pack("!Bxxx16s", 0, pixformat))
#rember these settings
self.bpp, self.depth, self.bigendian, self.truecolor = bpp, depth, bigendian, truecolor
self.redmax, self.greenmax, self.bluemax = redmax, greenmax, bluemax
self.redshift, self.greenshift, self.blueshift = redshift, greenshift, blueshift
self.bypp = self.bpp // 8 #calc bytes per pixel
#~ print self.bypp
def setEncodings(self, list_of_encodings):
self.transport.write(pack("!BxH", 2, len(list_of_encodings)))
for encoding in list_of_encodings:
self.transport.write(pack("!i", encoding))
def framebufferUpdateRequest(self, x=0, y=0, width=None, height=None, incremental=0):
if width is None: width = self.width - x
if height is None: height = self.height - y
self.transport.write(pack("!BBHHHH", 3, incremental, x, y, width, height))
def keyEvent(self, key, down=1):
"""For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants."""
self.transport.write(pack("!BBxxI", 4, down, key))
def pointerEvent(self, x, y, buttonmask=0):
"""Indicates either pointer movement or a pointer button press or release. The pointer is
now at (x-position, y-position), and the current state of buttons 1 to 8 are represented
by bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning down (pressed).
"""
self.transport.write(pack("!BBHH", 5, buttonmask, x, y))
def clientCutText(self, message):
"""The client has new ASCII text in its cut buffer.
(aka clipboard)
"""
self.transport.write(pack("!BxxxI", 6, len(message)) + message)
#------------------------------------------------------
# callbacks
# override these in your application
#------------------------------------------------------
def vncConnectionMade(self):
"""connection is initialized and ready.
typicaly, the pixel format is set here."""
def vncRequestPassword(self):
"""a password is needed to log on, use sendPassword() to
send one."""
if self.factory.password is None:
log.msg("need a password")
self.transport.loseConnection()
return
self.sendPassword(self.factory.password)
def vncAuthFailed(self, reason):
"""called when the authentication failed.
the connection is closed."""
log.msg("Cannot connect %s" % reason)
def beginUpdate(self):
"""called before a series of updateRectangle(),
copyRectangle() or fillRectangle()."""
def commitUpdate(self, rectangles=None):
"""called after a series of updateRectangle(), copyRectangle()
or fillRectangle() are finished.
typicaly, here is the place to request the next screen
update with FramebufferUpdateRequest(incremental=1).
argument is a list of tuples (x,y,w,h) with the updated
rectangles."""
def updateRectangle(self, x, y, width, height, data):
"""new bitmap data. data is a string in the pixel format set
up earlier."""
def copyRectangle(self, srcx, srcy, x, y, width, height):
"""used for copyrect encoding. copy the given rectangle
(src, srxy, width, height) to the target coords (x,y)"""
def fillRectangle(self, x, y, width, height, color):
"""fill the area with the color. the color is a string in
the pixel format set up earlier"""
#fallback variant, use update recatngle
#override with specialized function for better performance
self.updateRectangle(x, y, width, height, color*width*height)
def updateCursor(self, x, y, width, height, image, mask):
""" New cursor, focuses at (x, y)
"""
def updateDesktopSize(width, height):
""" New desktop size of width*height. """
def bell(self):
"""bell"""
def copy_text(self, text):
"""The server has new ASCII text in its cut buffer.
(aka clipboard)"""
|
sibson/vncdotool | vncdotool/rfb.py | RFBClient._handleDecodeHextileRAW | python | def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):
self.updateRectangle(tx, ty, tw, th, block)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty) | the tile is in raw encoding | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L452-L455 | null | class RFBClient(Protocol):
def __init__(self):
self._packet = []
self._packet_len = 0
self._handler = self._handleInitial
self._already_expecting = 0
self._version = None
self._version_server = None
#------------------------------------------------------
# states used on connection startup
#------------------------------------------------------
def _handleInitial(self):
buffer = b''.join(self._packet)
if b'\n' in buffer:
version = 3.3
if buffer[:3] == b'RFB':
version_server = float(buffer[3:-1].replace(b'0', b''))
SUPPORTED_VERSIONS = (3.3, 3.7, 3.8)
if version_server in SUPPORTED_VERSIONS:
version = version_server
else:
log.msg("Protocol version %.3f not supported"
% version_server)
version = max(filter(
lambda x: x <= version_server, SUPPORTED_VERSIONS))
buffer = buffer[12:]
log.msg("Using protocol version %.3f" % version)
parts = str(version).split('.')
self.transport.write(
bytes(b"RFB %03d.%03d\n" % (int(parts[0]), int(parts[1]))))
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._handler = self._handleExpected
self._version = version
self._version_server = version_server
if version < 3.7:
self.expect(self._handleAuth, 4)
else:
self.expect(self._handleNumberSecurityTypes, 1)
else:
self._packet[:] = [buffer]
self._packet_len = len(buffer)
def _handleNumberSecurityTypes(self, block):
(num_types,) = unpack("!B", block)
if num_types:
self.expect(self._handleSecurityTypes, num_types)
else:
self.expect(self._handleConnFailed, 4)
def _handleSecurityTypes(self, block):
types = unpack("!%dB" % len(block), block)
SUPPORTED_TYPES = (1, 2)
valid_types = [sec_type for sec_type in types if sec_type in SUPPORTED_TYPES]
if valid_types:
sec_type = max(valid_types)
self.transport.write(pack("!B", sec_type))
if sec_type == 1:
if self._version < 3.8:
self._doClientInitialization()
else:
self.expect(self._handleVNCAuthResult, 4)
else:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown security types: %s" % repr(types))
def _handleAuth(self, block):
(auth,) = unpack("!I", block)
#~ print "auth:", auth
if auth == 0:
self.expect(self._handleConnFailed, 4)
elif auth == 1:
self._doClientInitialization()
return
elif auth == 2:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown auth response (%d)" % auth)
def _handleConnFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleConnMessage, waitfor)
def _handleConnMessage(self, block):
log.msg("Connection refused: %r" % block)
def _handleVNCAuth(self, block):
self._challenge = block
self.vncRequestPassword()
self.expect(self._handleVNCAuthResult, 4)
def sendPassword(self, password):
"""send password"""
pw = (password + '\0' * 8)[:8] #make sure its 8 chars long, zero padded
des = RFBDes(pw)
response = des.encrypt(self._challenge)
self.transport.write(response)
def _handleVNCAuthResult(self, block):
(result,) = unpack("!I", block)
#~ print "auth:", auth
if result == 0: #OK
self._doClientInitialization()
return
elif result == 1: #failed
if self._version < 3.8:
self.vncAuthFailed("authentication failed")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
elif result == 2: #too many
if self._version < 3.8:
self.vncAuthFailed("too many tries to log in")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
else:
log.msg("unknown auth response (%d)" % result)
def _handleAuthFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleAuthFailedMessage, waitfor)
def _handleAuthFailedMessage(self, block):
self.vncAuthFailed(block)
self.transport.loseConnection()
def _doClientInitialization(self):
self.transport.write(pack("!B", self.factory.shared))
self.expect(self._handleServerInit, 24)
def _handleServerInit(self, block):
(self.width, self.height, pixformat, namelen) = unpack("!HH16sI", block)
(self.bpp, self.depth, self.bigendian, self.truecolor,
self.redmax, self.greenmax, self.bluemax,
self.redshift, self.greenshift, self.blueshift) = \
unpack("!BBBBHHHBBBxxx", pixformat)
self.bypp = self.bpp // 8 #calc bytes per pixel
self.expect(self._handleServerName, namelen)
def _handleServerName(self, block):
self.name = block
#callback:
self.vncConnectionMade()
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# Server to client messages
#------------------------------------------------------
def _handleConnection(self, block):
(msgid,) = unpack("!B", block)
if msgid == 0:
self.expect(self._handleFramebufferUpdate, 3)
elif msgid == 2:
self.bell()
self.expect(self._handleConnection, 1)
elif msgid == 3:
self.expect(self._handleServerCutText, 7)
else:
log.msg("unknown message received (id %d)" % msgid)
self.expect(self._handleConnection, 1)
def _handleFramebufferUpdate(self, block):
(self.rectangles,) = unpack("!xH", block)
self.rectanglePos = []
self.beginUpdate()
self._doConnection()
def _doConnection(self):
if self.rectangles:
self.expect(self._handleRectangle, 12)
else:
self.commitUpdate(self.rectanglePos)
self.expect(self._handleConnection, 1)
def _handleRectangle(self, block):
(x, y, width, height, encoding) = unpack("!HHHHi", block)
if self.rectangles:
self.rectangles -= 1
self.rectanglePos.append( (x, y, width, height) )
if encoding == COPY_RECTANGLE_ENCODING:
self.expect(self._handleDecodeCopyrect, 4, x, y, width, height)
elif encoding == RAW_ENCODING:
self.expect(self._handleDecodeRAW, width*height*self.bypp, x, y, width, height)
elif encoding == HEXTILE_ENCODING:
self._doNextHextileSubrect(None, None, x, y, width, height, None, None)
elif encoding == CORRE_ENCODING:
self.expect(self._handleDecodeCORRE, 4 + self.bypp, x, y, width, height)
elif encoding == RRE_ENCODING:
self.expect(self._handleDecodeRRE, 4 + self.bypp, x, y, width, height)
#~ elif encoding == ZRLE_ENCODING:
#~ self.expect(self._handleDecodeZRLE, )
elif encoding == PSEUDO_CURSOR_ENCODING:
length = width * height * self.bypp
length += int(math.floor((width + 7.0) / 8)) * height
self.expect(self._handleDecodePsuedoCursor, length, x, y, width, height)
elif encoding == PSEUDO_DESKTOP_SIZE_ENCODING:
self._handleDecodeDesktopSize(width, height)
else:
log.msg("unknown encoding received (encoding %d)" % encoding)
self._doConnection()
else:
self._doConnection()
# --- RAW Encoding
def _handleDecodeRAW(self, block, x, y, width, height):
#TODO convert pixel format?
self.updateRectangle(x, y, width, height, block)
self._doConnection()
# --- CopyRect Encoding
def _handleDecodeCopyrect(self, block, x, y, width, height):
(srcx, srcy) = unpack("!HH", block)
self.copyRectangle(srcx, srcy, x, y, width, height)
self._doConnection()
# --- RRE Encoding
def _handleDecodeRRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleRRESubRectangles, (8 + self.bypp) * subrects, x, y)
else:
self._doConnection()
def _handleRRESubRectangles(self, block, topx, topy):
#~ print "_handleRRESubRectangle"
pos = 0
end = len(block)
sz = self.bypp + 8
format = "!%dsHHHH" % self.bypp
while pos < end:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- CoRRE Encoding
def _handleDecodeCORRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleDecodeCORRERectangles, (4 + self.bypp)*subrects, x, y)
else:
self._doConnection()
def _handleDecodeCORRERectangles(self, block, topx, topy):
#~ print "_handleDecodeCORRERectangle"
pos = 0
end = len(block)
sz = self.bypp + 4
format = "!%dsBBBB" % self.bypp
while pos < sz:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- Hexile Encoding
def _doNextHextileSubrect(self, bg, color, x, y, width, height, tx, ty):
#~ print "_doNextHextileSubrect %r" % ((color, x, y, width, height, tx, ty), )
#coords of next tile
#its line after line of tiles
#finished when the last line is completly received
#dont inc the first time
if tx is not None:
#calc next subrect pos
tx += 16
if tx >= x + width:
tx = x
ty += 16
else:
tx = x
ty = y
#more tiles?
if ty >= y + height:
self._doConnection()
else:
self.expect(self._handleDecodeHextile, 1, bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextile(self, block, bg, color, x, y, width, height, tx, ty):
(subencoding,) = unpack("!B", block)
#calc tile size
tw = th = 16
if x + width - tx < 16: tw = x + width - tx
if y + height - ty < 16: th = y + height- ty
#decode tile
if subencoding & 1: #RAW
self.expect(self._handleDecodeHextileRAW, tw*th*self.bypp, bg, color, x, y, width, height, tx, ty, tw, th)
else:
numbytes = 0
if subencoding & 2: #BackgroundSpecified
numbytes += self.bypp
if subencoding & 4: #ForegroundSpecified
numbytes += self.bypp
if subencoding & 8: #AnySubrects
numbytes += 1
if numbytes:
self.expect(self._handleDecodeHextileSubrect, numbytes, subencoding, bg, color, x, y, width, height, tx, ty, tw, th)
else:
self.fillRectangle(tx, ty, tw, th, bg)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrect(self, block, subencoding, bg, color, x, y, width, height, tx, ty, tw, th):
subrects = 0
pos = 0
if subencoding & 2: #BackgroundSpecified
bg = block[:self.bypp]
pos += self.bypp
self.fillRectangle(tx, ty, tw, th, bg)
if subencoding & 4: #ForegroundSpecified
color = block[pos:pos+self.bypp]
pos += self.bypp
if subencoding & 8: #AnySubrects
#~ (subrects, ) = unpack("!B", block)
subrects = ord(block[pos])
#~ print subrects
if subrects:
if subencoding & 16: #SubrectsColoured
self.expect(self._handleDecodeHextileSubrectsColoured, (self.bypp + 2)*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self.expect(self._handleDecodeHextileSubrectsFG, 2*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""subrects with their own color"""
sz = self.bypp + 2
pos = 0
end = len(block)
while pos < end:
pos2 = pos + self.bypp
color = block[pos:pos2]
xy = ord(block[pos2])
wh = ord(block[pos2+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += sz
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsFG(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""all subrect with same color"""
pos = 0
end = len(block)
while pos < end:
xy = ord(block[pos])
wh = ord(block[pos+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += 2
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
# --- ZRLE Encoding
def _handleDecodeZRLE(self, block):
raise NotImplementedError
# --- Pseudo Cursor Encoding
def _handleDecodePsuedoCursor(self, block, x, y, width, height):
split = width * height * self.bypp
image = block[:split]
mask = block[split:]
self.updateCursor(x, y, width, height, image, mask)
self._doConnection()
# --- Pseudo Desktop Size Encoding
def _handleDecodeDesktopSize(self, width, height):
self.updateDesktopSize(width, height)
self._doConnection()
# --- other server messages
def _handleServerCutText(self, block):
(length, ) = unpack("!xxxI", block)
self.expect(self._handleServerCutTextValue, length)
def _handleServerCutTextValue(self, block):
self.copy_text(block)
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# incomming data redirector
#------------------------------------------------------
def dataReceived(self, data):
#~ sys.stdout.write(repr(data) + '\n')
#~ print len(data), ", ", len(self._packet)
self._packet.append(data)
self._packet_len += len(data)
self._handler()
def _handleExpected(self):
if self._packet_len >= self._expected_len:
buffer = b''.join(self._packet)
while len(buffer) >= self._expected_len:
self._already_expecting = 1
block, buffer = buffer[:self._expected_len], buffer[self._expected_len:]
#~ log.msg("handle %r with %r\n" % (block, self._expected_handler.__name__))
self._expected_handler(block, *self._expected_args, **self._expected_kwargs)
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._already_expecting = 0
def expect(self, handler, size, *args, **kwargs):
#~ log.msg("expect(%r, %r, %r, %r)\n" % (handler.__name__, size, args, kwargs))
self._expected_handler = handler
self._expected_len = size
self._expected_args = args
self._expected_kwargs = kwargs
if not self._already_expecting:
self._handleExpected() #just in case that there is already enough data
#------------------------------------------------------
# client -> server messages
#------------------------------------------------------
def setPixelFormat(self, bpp=32, depth=24, bigendian=0, truecolor=1, redmax=255, greenmax=255, bluemax=255, redshift=0, greenshift=8, blueshift=16):
pixformat = pack("!BBBBHHHBBBxxx", bpp, depth, bigendian, truecolor, redmax, greenmax, bluemax, redshift, greenshift, blueshift)
self.transport.write(pack("!Bxxx16s", 0, pixformat))
#rember these settings
self.bpp, self.depth, self.bigendian, self.truecolor = bpp, depth, bigendian, truecolor
self.redmax, self.greenmax, self.bluemax = redmax, greenmax, bluemax
self.redshift, self.greenshift, self.blueshift = redshift, greenshift, blueshift
self.bypp = self.bpp // 8 #calc bytes per pixel
#~ print self.bypp
def setEncodings(self, list_of_encodings):
self.transport.write(pack("!BxH", 2, len(list_of_encodings)))
for encoding in list_of_encodings:
self.transport.write(pack("!i", encoding))
def framebufferUpdateRequest(self, x=0, y=0, width=None, height=None, incremental=0):
if width is None: width = self.width - x
if height is None: height = self.height - y
self.transport.write(pack("!BBHHHH", 3, incremental, x, y, width, height))
def keyEvent(self, key, down=1):
"""For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants."""
self.transport.write(pack("!BBxxI", 4, down, key))
def pointerEvent(self, x, y, buttonmask=0):
"""Indicates either pointer movement or a pointer button press or release. The pointer is
now at (x-position, y-position), and the current state of buttons 1 to 8 are represented
by bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning down (pressed).
"""
self.transport.write(pack("!BBHH", 5, buttonmask, x, y))
def clientCutText(self, message):
"""The client has new ASCII text in its cut buffer.
(aka clipboard)
"""
self.transport.write(pack("!BxxxI", 6, len(message)) + message)
#------------------------------------------------------
# callbacks
# override these in your application
#------------------------------------------------------
def vncConnectionMade(self):
"""connection is initialized and ready.
typicaly, the pixel format is set here."""
def vncRequestPassword(self):
"""a password is needed to log on, use sendPassword() to
send one."""
if self.factory.password is None:
log.msg("need a password")
self.transport.loseConnection()
return
self.sendPassword(self.factory.password)
def vncAuthFailed(self, reason):
"""called when the authentication failed.
the connection is closed."""
log.msg("Cannot connect %s" % reason)
def beginUpdate(self):
"""called before a series of updateRectangle(),
copyRectangle() or fillRectangle()."""
def commitUpdate(self, rectangles=None):
"""called after a series of updateRectangle(), copyRectangle()
or fillRectangle() are finished.
typicaly, here is the place to request the next screen
update with FramebufferUpdateRequest(incremental=1).
argument is a list of tuples (x,y,w,h) with the updated
rectangles."""
def updateRectangle(self, x, y, width, height, data):
"""new bitmap data. data is a string in the pixel format set
up earlier."""
def copyRectangle(self, srcx, srcy, x, y, width, height):
"""used for copyrect encoding. copy the given rectangle
(src, srxy, width, height) to the target coords (x,y)"""
def fillRectangle(self, x, y, width, height, color):
"""fill the area with the color. the color is a string in
the pixel format set up earlier"""
#fallback variant, use update recatngle
#override with specialized function for better performance
self.updateRectangle(x, y, width, height, color*width*height)
def updateCursor(self, x, y, width, height, image, mask):
""" New cursor, focuses at (x, y)
"""
def updateDesktopSize(width, height):
""" New desktop size of width*height. """
def bell(self):
"""bell"""
def copy_text(self, text):
"""The server has new ASCII text in its cut buffer.
(aka clipboard)"""
|
sibson/vncdotool | vncdotool/rfb.py | RFBClient._handleDecodeHextileSubrectsColoured | python | def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
sz = self.bypp + 2
pos = 0
end = len(block)
while pos < end:
pos2 = pos + self.bypp
color = block[pos:pos2]
xy = ord(block[pos2])
wh = ord(block[pos2+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += sz
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty) | subrects with their own color | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L457-L473 | null | class RFBClient(Protocol):
def __init__(self):
self._packet = []
self._packet_len = 0
self._handler = self._handleInitial
self._already_expecting = 0
self._version = None
self._version_server = None
#------------------------------------------------------
# states used on connection startup
#------------------------------------------------------
def _handleInitial(self):
buffer = b''.join(self._packet)
if b'\n' in buffer:
version = 3.3
if buffer[:3] == b'RFB':
version_server = float(buffer[3:-1].replace(b'0', b''))
SUPPORTED_VERSIONS = (3.3, 3.7, 3.8)
if version_server in SUPPORTED_VERSIONS:
version = version_server
else:
log.msg("Protocol version %.3f not supported"
% version_server)
version = max(filter(
lambda x: x <= version_server, SUPPORTED_VERSIONS))
buffer = buffer[12:]
log.msg("Using protocol version %.3f" % version)
parts = str(version).split('.')
self.transport.write(
bytes(b"RFB %03d.%03d\n" % (int(parts[0]), int(parts[1]))))
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._handler = self._handleExpected
self._version = version
self._version_server = version_server
if version < 3.7:
self.expect(self._handleAuth, 4)
else:
self.expect(self._handleNumberSecurityTypes, 1)
else:
self._packet[:] = [buffer]
self._packet_len = len(buffer)
def _handleNumberSecurityTypes(self, block):
(num_types,) = unpack("!B", block)
if num_types:
self.expect(self._handleSecurityTypes, num_types)
else:
self.expect(self._handleConnFailed, 4)
def _handleSecurityTypes(self, block):
types = unpack("!%dB" % len(block), block)
SUPPORTED_TYPES = (1, 2)
valid_types = [sec_type for sec_type in types if sec_type in SUPPORTED_TYPES]
if valid_types:
sec_type = max(valid_types)
self.transport.write(pack("!B", sec_type))
if sec_type == 1:
if self._version < 3.8:
self._doClientInitialization()
else:
self.expect(self._handleVNCAuthResult, 4)
else:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown security types: %s" % repr(types))
def _handleAuth(self, block):
(auth,) = unpack("!I", block)
#~ print "auth:", auth
if auth == 0:
self.expect(self._handleConnFailed, 4)
elif auth == 1:
self._doClientInitialization()
return
elif auth == 2:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown auth response (%d)" % auth)
def _handleConnFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleConnMessage, waitfor)
def _handleConnMessage(self, block):
log.msg("Connection refused: %r" % block)
def _handleVNCAuth(self, block):
self._challenge = block
self.vncRequestPassword()
self.expect(self._handleVNCAuthResult, 4)
def sendPassword(self, password):
"""send password"""
pw = (password + '\0' * 8)[:8] #make sure its 8 chars long, zero padded
des = RFBDes(pw)
response = des.encrypt(self._challenge)
self.transport.write(response)
def _handleVNCAuthResult(self, block):
(result,) = unpack("!I", block)
#~ print "auth:", auth
if result == 0: #OK
self._doClientInitialization()
return
elif result == 1: #failed
if self._version < 3.8:
self.vncAuthFailed("authentication failed")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
elif result == 2: #too many
if self._version < 3.8:
self.vncAuthFailed("too many tries to log in")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
else:
log.msg("unknown auth response (%d)" % result)
def _handleAuthFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleAuthFailedMessage, waitfor)
def _handleAuthFailedMessage(self, block):
self.vncAuthFailed(block)
self.transport.loseConnection()
def _doClientInitialization(self):
self.transport.write(pack("!B", self.factory.shared))
self.expect(self._handleServerInit, 24)
def _handleServerInit(self, block):
(self.width, self.height, pixformat, namelen) = unpack("!HH16sI", block)
(self.bpp, self.depth, self.bigendian, self.truecolor,
self.redmax, self.greenmax, self.bluemax,
self.redshift, self.greenshift, self.blueshift) = \
unpack("!BBBBHHHBBBxxx", pixformat)
self.bypp = self.bpp // 8 #calc bytes per pixel
self.expect(self._handleServerName, namelen)
def _handleServerName(self, block):
self.name = block
#callback:
self.vncConnectionMade()
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# Server to client messages
#------------------------------------------------------
def _handleConnection(self, block):
(msgid,) = unpack("!B", block)
if msgid == 0:
self.expect(self._handleFramebufferUpdate, 3)
elif msgid == 2:
self.bell()
self.expect(self._handleConnection, 1)
elif msgid == 3:
self.expect(self._handleServerCutText, 7)
else:
log.msg("unknown message received (id %d)" % msgid)
self.expect(self._handleConnection, 1)
def _handleFramebufferUpdate(self, block):
(self.rectangles,) = unpack("!xH", block)
self.rectanglePos = []
self.beginUpdate()
self._doConnection()
def _doConnection(self):
if self.rectangles:
self.expect(self._handleRectangle, 12)
else:
self.commitUpdate(self.rectanglePos)
self.expect(self._handleConnection, 1)
def _handleRectangle(self, block):
(x, y, width, height, encoding) = unpack("!HHHHi", block)
if self.rectangles:
self.rectangles -= 1
self.rectanglePos.append( (x, y, width, height) )
if encoding == COPY_RECTANGLE_ENCODING:
self.expect(self._handleDecodeCopyrect, 4, x, y, width, height)
elif encoding == RAW_ENCODING:
self.expect(self._handleDecodeRAW, width*height*self.bypp, x, y, width, height)
elif encoding == HEXTILE_ENCODING:
self._doNextHextileSubrect(None, None, x, y, width, height, None, None)
elif encoding == CORRE_ENCODING:
self.expect(self._handleDecodeCORRE, 4 + self.bypp, x, y, width, height)
elif encoding == RRE_ENCODING:
self.expect(self._handleDecodeRRE, 4 + self.bypp, x, y, width, height)
#~ elif encoding == ZRLE_ENCODING:
#~ self.expect(self._handleDecodeZRLE, )
elif encoding == PSEUDO_CURSOR_ENCODING:
length = width * height * self.bypp
length += int(math.floor((width + 7.0) / 8)) * height
self.expect(self._handleDecodePsuedoCursor, length, x, y, width, height)
elif encoding == PSEUDO_DESKTOP_SIZE_ENCODING:
self._handleDecodeDesktopSize(width, height)
else:
log.msg("unknown encoding received (encoding %d)" % encoding)
self._doConnection()
else:
self._doConnection()
# --- RAW Encoding
def _handleDecodeRAW(self, block, x, y, width, height):
#TODO convert pixel format?
self.updateRectangle(x, y, width, height, block)
self._doConnection()
# --- CopyRect Encoding
def _handleDecodeCopyrect(self, block, x, y, width, height):
(srcx, srcy) = unpack("!HH", block)
self.copyRectangle(srcx, srcy, x, y, width, height)
self._doConnection()
# --- RRE Encoding
def _handleDecodeRRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleRRESubRectangles, (8 + self.bypp) * subrects, x, y)
else:
self._doConnection()
def _handleRRESubRectangles(self, block, topx, topy):
#~ print "_handleRRESubRectangle"
pos = 0
end = len(block)
sz = self.bypp + 8
format = "!%dsHHHH" % self.bypp
while pos < end:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- CoRRE Encoding
def _handleDecodeCORRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleDecodeCORRERectangles, (4 + self.bypp)*subrects, x, y)
else:
self._doConnection()
def _handleDecodeCORRERectangles(self, block, topx, topy):
#~ print "_handleDecodeCORRERectangle"
pos = 0
end = len(block)
sz = self.bypp + 4
format = "!%dsBBBB" % self.bypp
while pos < sz:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- Hexile Encoding
def _doNextHextileSubrect(self, bg, color, x, y, width, height, tx, ty):
#~ print "_doNextHextileSubrect %r" % ((color, x, y, width, height, tx, ty), )
#coords of next tile
#its line after line of tiles
#finished when the last line is completly received
#dont inc the first time
if tx is not None:
#calc next subrect pos
tx += 16
if tx >= x + width:
tx = x
ty += 16
else:
tx = x
ty = y
#more tiles?
if ty >= y + height:
self._doConnection()
else:
self.expect(self._handleDecodeHextile, 1, bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextile(self, block, bg, color, x, y, width, height, tx, ty):
(subencoding,) = unpack("!B", block)
#calc tile size
tw = th = 16
if x + width - tx < 16: tw = x + width - tx
if y + height - ty < 16: th = y + height- ty
#decode tile
if subencoding & 1: #RAW
self.expect(self._handleDecodeHextileRAW, tw*th*self.bypp, bg, color, x, y, width, height, tx, ty, tw, th)
else:
numbytes = 0
if subencoding & 2: #BackgroundSpecified
numbytes += self.bypp
if subencoding & 4: #ForegroundSpecified
numbytes += self.bypp
if subencoding & 8: #AnySubrects
numbytes += 1
if numbytes:
self.expect(self._handleDecodeHextileSubrect, numbytes, subencoding, bg, color, x, y, width, height, tx, ty, tw, th)
else:
self.fillRectangle(tx, ty, tw, th, bg)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrect(self, block, subencoding, bg, color, x, y, width, height, tx, ty, tw, th):
subrects = 0
pos = 0
if subencoding & 2: #BackgroundSpecified
bg = block[:self.bypp]
pos += self.bypp
self.fillRectangle(tx, ty, tw, th, bg)
if subencoding & 4: #ForegroundSpecified
color = block[pos:pos+self.bypp]
pos += self.bypp
if subencoding & 8: #AnySubrects
#~ (subrects, ) = unpack("!B", block)
subrects = ord(block[pos])
#~ print subrects
if subrects:
if subencoding & 16: #SubrectsColoured
self.expect(self._handleDecodeHextileSubrectsColoured, (self.bypp + 2)*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self.expect(self._handleDecodeHextileSubrectsFG, 2*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):
"""the tile is in raw encoding"""
self.updateRectangle(tx, ty, tw, th, block)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsFG(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""all subrect with same color"""
pos = 0
end = len(block)
while pos < end:
xy = ord(block[pos])
wh = ord(block[pos+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += 2
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
# --- ZRLE Encoding
def _handleDecodeZRLE(self, block):
raise NotImplementedError
# --- Pseudo Cursor Encoding
def _handleDecodePsuedoCursor(self, block, x, y, width, height):
split = width * height * self.bypp
image = block[:split]
mask = block[split:]
self.updateCursor(x, y, width, height, image, mask)
self._doConnection()
# --- Pseudo Desktop Size Encoding
def _handleDecodeDesktopSize(self, width, height):
self.updateDesktopSize(width, height)
self._doConnection()
# --- other server messages
def _handleServerCutText(self, block):
(length, ) = unpack("!xxxI", block)
self.expect(self._handleServerCutTextValue, length)
def _handleServerCutTextValue(self, block):
self.copy_text(block)
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# incomming data redirector
#------------------------------------------------------
def dataReceived(self, data):
#~ sys.stdout.write(repr(data) + '\n')
#~ print len(data), ", ", len(self._packet)
self._packet.append(data)
self._packet_len += len(data)
self._handler()
def _handleExpected(self):
if self._packet_len >= self._expected_len:
buffer = b''.join(self._packet)
while len(buffer) >= self._expected_len:
self._already_expecting = 1
block, buffer = buffer[:self._expected_len], buffer[self._expected_len:]
#~ log.msg("handle %r with %r\n" % (block, self._expected_handler.__name__))
self._expected_handler(block, *self._expected_args, **self._expected_kwargs)
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._already_expecting = 0
def expect(self, handler, size, *args, **kwargs):
#~ log.msg("expect(%r, %r, %r, %r)\n" % (handler.__name__, size, args, kwargs))
self._expected_handler = handler
self._expected_len = size
self._expected_args = args
self._expected_kwargs = kwargs
if not self._already_expecting:
self._handleExpected() #just in case that there is already enough data
#------------------------------------------------------
# client -> server messages
#------------------------------------------------------
def setPixelFormat(self, bpp=32, depth=24, bigendian=0, truecolor=1, redmax=255, greenmax=255, bluemax=255, redshift=0, greenshift=8, blueshift=16):
pixformat = pack("!BBBBHHHBBBxxx", bpp, depth, bigendian, truecolor, redmax, greenmax, bluemax, redshift, greenshift, blueshift)
self.transport.write(pack("!Bxxx16s", 0, pixformat))
#rember these settings
self.bpp, self.depth, self.bigendian, self.truecolor = bpp, depth, bigendian, truecolor
self.redmax, self.greenmax, self.bluemax = redmax, greenmax, bluemax
self.redshift, self.greenshift, self.blueshift = redshift, greenshift, blueshift
self.bypp = self.bpp // 8 #calc bytes per pixel
#~ print self.bypp
def setEncodings(self, list_of_encodings):
self.transport.write(pack("!BxH", 2, len(list_of_encodings)))
for encoding in list_of_encodings:
self.transport.write(pack("!i", encoding))
def framebufferUpdateRequest(self, x=0, y=0, width=None, height=None, incremental=0):
if width is None: width = self.width - x
if height is None: height = self.height - y
self.transport.write(pack("!BBHHHH", 3, incremental, x, y, width, height))
def keyEvent(self, key, down=1):
"""For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants."""
self.transport.write(pack("!BBxxI", 4, down, key))
def pointerEvent(self, x, y, buttonmask=0):
"""Indicates either pointer movement or a pointer button press or release. The pointer is
now at (x-position, y-position), and the current state of buttons 1 to 8 are represented
by bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning down (pressed).
"""
self.transport.write(pack("!BBHH", 5, buttonmask, x, y))
def clientCutText(self, message):
"""The client has new ASCII text in its cut buffer.
(aka clipboard)
"""
self.transport.write(pack("!BxxxI", 6, len(message)) + message)
#------------------------------------------------------
# callbacks
# override these in your application
#------------------------------------------------------
def vncConnectionMade(self):
"""connection is initialized and ready.
typicaly, the pixel format is set here."""
def vncRequestPassword(self):
"""a password is needed to log on, use sendPassword() to
send one."""
if self.factory.password is None:
log.msg("need a password")
self.transport.loseConnection()
return
self.sendPassword(self.factory.password)
def vncAuthFailed(self, reason):
"""called when the authentication failed.
the connection is closed."""
log.msg("Cannot connect %s" % reason)
def beginUpdate(self):
"""called before a series of updateRectangle(),
copyRectangle() or fillRectangle()."""
def commitUpdate(self, rectangles=None):
"""called after a series of updateRectangle(), copyRectangle()
or fillRectangle() are finished.
typicaly, here is the place to request the next screen
update with FramebufferUpdateRequest(incremental=1).
argument is a list of tuples (x,y,w,h) with the updated
rectangles."""
def updateRectangle(self, x, y, width, height, data):
"""new bitmap data. data is a string in the pixel format set
up earlier."""
def copyRectangle(self, srcx, srcy, x, y, width, height):
"""used for copyrect encoding. copy the given rectangle
(src, srxy, width, height) to the target coords (x,y)"""
def fillRectangle(self, x, y, width, height, color):
"""fill the area with the color. the color is a string in
the pixel format set up earlier"""
#fallback variant, use update recatngle
#override with specialized function for better performance
self.updateRectangle(x, y, width, height, color*width*height)
def updateCursor(self, x, y, width, height, image, mask):
""" New cursor, focuses at (x, y)
"""
def updateDesktopSize(width, height):
""" New desktop size of width*height. """
def bell(self):
"""bell"""
def copy_text(self, text):
"""The server has new ASCII text in its cut buffer.
(aka clipboard)"""
|
sibson/vncdotool | vncdotool/rfb.py | RFBClient.keyEvent | python | def keyEvent(self, key, down=1):
self.transport.write(pack("!BBxxI", 4, down, key)) | For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants. | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L574-L577 | null | class RFBClient(Protocol):
def __init__(self):
self._packet = []
self._packet_len = 0
self._handler = self._handleInitial
self._already_expecting = 0
self._version = None
self._version_server = None
#------------------------------------------------------
# states used on connection startup
#------------------------------------------------------
def _handleInitial(self):
buffer = b''.join(self._packet)
if b'\n' in buffer:
version = 3.3
if buffer[:3] == b'RFB':
version_server = float(buffer[3:-1].replace(b'0', b''))
SUPPORTED_VERSIONS = (3.3, 3.7, 3.8)
if version_server in SUPPORTED_VERSIONS:
version = version_server
else:
log.msg("Protocol version %.3f not supported"
% version_server)
version = max(filter(
lambda x: x <= version_server, SUPPORTED_VERSIONS))
buffer = buffer[12:]
log.msg("Using protocol version %.3f" % version)
parts = str(version).split('.')
self.transport.write(
bytes(b"RFB %03d.%03d\n" % (int(parts[0]), int(parts[1]))))
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._handler = self._handleExpected
self._version = version
self._version_server = version_server
if version < 3.7:
self.expect(self._handleAuth, 4)
else:
self.expect(self._handleNumberSecurityTypes, 1)
else:
self._packet[:] = [buffer]
self._packet_len = len(buffer)
def _handleNumberSecurityTypes(self, block):
(num_types,) = unpack("!B", block)
if num_types:
self.expect(self._handleSecurityTypes, num_types)
else:
self.expect(self._handleConnFailed, 4)
def _handleSecurityTypes(self, block):
types = unpack("!%dB" % len(block), block)
SUPPORTED_TYPES = (1, 2)
valid_types = [sec_type for sec_type in types if sec_type in SUPPORTED_TYPES]
if valid_types:
sec_type = max(valid_types)
self.transport.write(pack("!B", sec_type))
if sec_type == 1:
if self._version < 3.8:
self._doClientInitialization()
else:
self.expect(self._handleVNCAuthResult, 4)
else:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown security types: %s" % repr(types))
def _handleAuth(self, block):
(auth,) = unpack("!I", block)
#~ print "auth:", auth
if auth == 0:
self.expect(self._handleConnFailed, 4)
elif auth == 1:
self._doClientInitialization()
return
elif auth == 2:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown auth response (%d)" % auth)
def _handleConnFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleConnMessage, waitfor)
def _handleConnMessage(self, block):
log.msg("Connection refused: %r" % block)
def _handleVNCAuth(self, block):
self._challenge = block
self.vncRequestPassword()
self.expect(self._handleVNCAuthResult, 4)
def sendPassword(self, password):
"""send password"""
pw = (password + '\0' * 8)[:8] #make sure its 8 chars long, zero padded
des = RFBDes(pw)
response = des.encrypt(self._challenge)
self.transport.write(response)
def _handleVNCAuthResult(self, block):
(result,) = unpack("!I", block)
#~ print "auth:", auth
if result == 0: #OK
self._doClientInitialization()
return
elif result == 1: #failed
if self._version < 3.8:
self.vncAuthFailed("authentication failed")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
elif result == 2: #too many
if self._version < 3.8:
self.vncAuthFailed("too many tries to log in")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
else:
log.msg("unknown auth response (%d)" % result)
def _handleAuthFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleAuthFailedMessage, waitfor)
def _handleAuthFailedMessage(self, block):
self.vncAuthFailed(block)
self.transport.loseConnection()
def _doClientInitialization(self):
self.transport.write(pack("!B", self.factory.shared))
self.expect(self._handleServerInit, 24)
def _handleServerInit(self, block):
(self.width, self.height, pixformat, namelen) = unpack("!HH16sI", block)
(self.bpp, self.depth, self.bigendian, self.truecolor,
self.redmax, self.greenmax, self.bluemax,
self.redshift, self.greenshift, self.blueshift) = \
unpack("!BBBBHHHBBBxxx", pixformat)
self.bypp = self.bpp // 8 #calc bytes per pixel
self.expect(self._handleServerName, namelen)
def _handleServerName(self, block):
self.name = block
#callback:
self.vncConnectionMade()
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# Server to client messages
#------------------------------------------------------
def _handleConnection(self, block):
(msgid,) = unpack("!B", block)
if msgid == 0:
self.expect(self._handleFramebufferUpdate, 3)
elif msgid == 2:
self.bell()
self.expect(self._handleConnection, 1)
elif msgid == 3:
self.expect(self._handleServerCutText, 7)
else:
log.msg("unknown message received (id %d)" % msgid)
self.expect(self._handleConnection, 1)
def _handleFramebufferUpdate(self, block):
(self.rectangles,) = unpack("!xH", block)
self.rectanglePos = []
self.beginUpdate()
self._doConnection()
def _doConnection(self):
if self.rectangles:
self.expect(self._handleRectangle, 12)
else:
self.commitUpdate(self.rectanglePos)
self.expect(self._handleConnection, 1)
def _handleRectangle(self, block):
(x, y, width, height, encoding) = unpack("!HHHHi", block)
if self.rectangles:
self.rectangles -= 1
self.rectanglePos.append( (x, y, width, height) )
if encoding == COPY_RECTANGLE_ENCODING:
self.expect(self._handleDecodeCopyrect, 4, x, y, width, height)
elif encoding == RAW_ENCODING:
self.expect(self._handleDecodeRAW, width*height*self.bypp, x, y, width, height)
elif encoding == HEXTILE_ENCODING:
self._doNextHextileSubrect(None, None, x, y, width, height, None, None)
elif encoding == CORRE_ENCODING:
self.expect(self._handleDecodeCORRE, 4 + self.bypp, x, y, width, height)
elif encoding == RRE_ENCODING:
self.expect(self._handleDecodeRRE, 4 + self.bypp, x, y, width, height)
#~ elif encoding == ZRLE_ENCODING:
#~ self.expect(self._handleDecodeZRLE, )
elif encoding == PSEUDO_CURSOR_ENCODING:
length = width * height * self.bypp
length += int(math.floor((width + 7.0) / 8)) * height
self.expect(self._handleDecodePsuedoCursor, length, x, y, width, height)
elif encoding == PSEUDO_DESKTOP_SIZE_ENCODING:
self._handleDecodeDesktopSize(width, height)
else:
log.msg("unknown encoding received (encoding %d)" % encoding)
self._doConnection()
else:
self._doConnection()
# --- RAW Encoding
def _handleDecodeRAW(self, block, x, y, width, height):
#TODO convert pixel format?
self.updateRectangle(x, y, width, height, block)
self._doConnection()
# --- CopyRect Encoding
def _handleDecodeCopyrect(self, block, x, y, width, height):
(srcx, srcy) = unpack("!HH", block)
self.copyRectangle(srcx, srcy, x, y, width, height)
self._doConnection()
# --- RRE Encoding
def _handleDecodeRRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleRRESubRectangles, (8 + self.bypp) * subrects, x, y)
else:
self._doConnection()
def _handleRRESubRectangles(self, block, topx, topy):
#~ print "_handleRRESubRectangle"
pos = 0
end = len(block)
sz = self.bypp + 8
format = "!%dsHHHH" % self.bypp
while pos < end:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- CoRRE Encoding
def _handleDecodeCORRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleDecodeCORRERectangles, (4 + self.bypp)*subrects, x, y)
else:
self._doConnection()
def _handleDecodeCORRERectangles(self, block, topx, topy):
#~ print "_handleDecodeCORRERectangle"
pos = 0
end = len(block)
sz = self.bypp + 4
format = "!%dsBBBB" % self.bypp
while pos < sz:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- Hexile Encoding
def _doNextHextileSubrect(self, bg, color, x, y, width, height, tx, ty):
#~ print "_doNextHextileSubrect %r" % ((color, x, y, width, height, tx, ty), )
#coords of next tile
#its line after line of tiles
#finished when the last line is completly received
#dont inc the first time
if tx is not None:
#calc next subrect pos
tx += 16
if tx >= x + width:
tx = x
ty += 16
else:
tx = x
ty = y
#more tiles?
if ty >= y + height:
self._doConnection()
else:
self.expect(self._handleDecodeHextile, 1, bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextile(self, block, bg, color, x, y, width, height, tx, ty):
(subencoding,) = unpack("!B", block)
#calc tile size
tw = th = 16
if x + width - tx < 16: tw = x + width - tx
if y + height - ty < 16: th = y + height- ty
#decode tile
if subencoding & 1: #RAW
self.expect(self._handleDecodeHextileRAW, tw*th*self.bypp, bg, color, x, y, width, height, tx, ty, tw, th)
else:
numbytes = 0
if subencoding & 2: #BackgroundSpecified
numbytes += self.bypp
if subencoding & 4: #ForegroundSpecified
numbytes += self.bypp
if subencoding & 8: #AnySubrects
numbytes += 1
if numbytes:
self.expect(self._handleDecodeHextileSubrect, numbytes, subencoding, bg, color, x, y, width, height, tx, ty, tw, th)
else:
self.fillRectangle(tx, ty, tw, th, bg)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrect(self, block, subencoding, bg, color, x, y, width, height, tx, ty, tw, th):
subrects = 0
pos = 0
if subencoding & 2: #BackgroundSpecified
bg = block[:self.bypp]
pos += self.bypp
self.fillRectangle(tx, ty, tw, th, bg)
if subencoding & 4: #ForegroundSpecified
color = block[pos:pos+self.bypp]
pos += self.bypp
if subencoding & 8: #AnySubrects
#~ (subrects, ) = unpack("!B", block)
subrects = ord(block[pos])
#~ print subrects
if subrects:
if subencoding & 16: #SubrectsColoured
self.expect(self._handleDecodeHextileSubrectsColoured, (self.bypp + 2)*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self.expect(self._handleDecodeHextileSubrectsFG, 2*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):
"""the tile is in raw encoding"""
self.updateRectangle(tx, ty, tw, th, block)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""subrects with their own color"""
sz = self.bypp + 2
pos = 0
end = len(block)
while pos < end:
pos2 = pos + self.bypp
color = block[pos:pos2]
xy = ord(block[pos2])
wh = ord(block[pos2+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += sz
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsFG(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""all subrect with same color"""
pos = 0
end = len(block)
while pos < end:
xy = ord(block[pos])
wh = ord(block[pos+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += 2
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
# --- ZRLE Encoding
def _handleDecodeZRLE(self, block):
raise NotImplementedError
# --- Pseudo Cursor Encoding
def _handleDecodePsuedoCursor(self, block, x, y, width, height):
split = width * height * self.bypp
image = block[:split]
mask = block[split:]
self.updateCursor(x, y, width, height, image, mask)
self._doConnection()
# --- Pseudo Desktop Size Encoding
def _handleDecodeDesktopSize(self, width, height):
self.updateDesktopSize(width, height)
self._doConnection()
# --- other server messages
def _handleServerCutText(self, block):
(length, ) = unpack("!xxxI", block)
self.expect(self._handleServerCutTextValue, length)
def _handleServerCutTextValue(self, block):
self.copy_text(block)
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# incomming data redirector
#------------------------------------------------------
def dataReceived(self, data):
#~ sys.stdout.write(repr(data) + '\n')
#~ print len(data), ", ", len(self._packet)
self._packet.append(data)
self._packet_len += len(data)
self._handler()
def _handleExpected(self):
if self._packet_len >= self._expected_len:
buffer = b''.join(self._packet)
while len(buffer) >= self._expected_len:
self._already_expecting = 1
block, buffer = buffer[:self._expected_len], buffer[self._expected_len:]
#~ log.msg("handle %r with %r\n" % (block, self._expected_handler.__name__))
self._expected_handler(block, *self._expected_args, **self._expected_kwargs)
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._already_expecting = 0
def expect(self, handler, size, *args, **kwargs):
#~ log.msg("expect(%r, %r, %r, %r)\n" % (handler.__name__, size, args, kwargs))
self._expected_handler = handler
self._expected_len = size
self._expected_args = args
self._expected_kwargs = kwargs
if not self._already_expecting:
self._handleExpected() #just in case that there is already enough data
#------------------------------------------------------
# client -> server messages
#------------------------------------------------------
def setPixelFormat(self, bpp=32, depth=24, bigendian=0, truecolor=1, redmax=255, greenmax=255, bluemax=255, redshift=0, greenshift=8, blueshift=16):
pixformat = pack("!BBBBHHHBBBxxx", bpp, depth, bigendian, truecolor, redmax, greenmax, bluemax, redshift, greenshift, blueshift)
self.transport.write(pack("!Bxxx16s", 0, pixformat))
#rember these settings
self.bpp, self.depth, self.bigendian, self.truecolor = bpp, depth, bigendian, truecolor
self.redmax, self.greenmax, self.bluemax = redmax, greenmax, bluemax
self.redshift, self.greenshift, self.blueshift = redshift, greenshift, blueshift
self.bypp = self.bpp // 8 #calc bytes per pixel
#~ print self.bypp
def setEncodings(self, list_of_encodings):
self.transport.write(pack("!BxH", 2, len(list_of_encodings)))
for encoding in list_of_encodings:
self.transport.write(pack("!i", encoding))
def framebufferUpdateRequest(self, x=0, y=0, width=None, height=None, incremental=0):
if width is None: width = self.width - x
if height is None: height = self.height - y
self.transport.write(pack("!BBHHHH", 3, incremental, x, y, width, height))
def pointerEvent(self, x, y, buttonmask=0):
"""Indicates either pointer movement or a pointer button press or release. The pointer is
now at (x-position, y-position), and the current state of buttons 1 to 8 are represented
by bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning down (pressed).
"""
self.transport.write(pack("!BBHH", 5, buttonmask, x, y))
def clientCutText(self, message):
"""The client has new ASCII text in its cut buffer.
(aka clipboard)
"""
self.transport.write(pack("!BxxxI", 6, len(message)) + message)
#------------------------------------------------------
# callbacks
# override these in your application
#------------------------------------------------------
def vncConnectionMade(self):
"""connection is initialized and ready.
typicaly, the pixel format is set here."""
def vncRequestPassword(self):
"""a password is needed to log on, use sendPassword() to
send one."""
if self.factory.password is None:
log.msg("need a password")
self.transport.loseConnection()
return
self.sendPassword(self.factory.password)
def vncAuthFailed(self, reason):
"""called when the authentication failed.
the connection is closed."""
log.msg("Cannot connect %s" % reason)
def beginUpdate(self):
"""called before a series of updateRectangle(),
copyRectangle() or fillRectangle()."""
def commitUpdate(self, rectangles=None):
"""called after a series of updateRectangle(), copyRectangle()
or fillRectangle() are finished.
typicaly, here is the place to request the next screen
update with FramebufferUpdateRequest(incremental=1).
argument is a list of tuples (x,y,w,h) with the updated
rectangles."""
def updateRectangle(self, x, y, width, height, data):
"""new bitmap data. data is a string in the pixel format set
up earlier."""
def copyRectangle(self, srcx, srcy, x, y, width, height):
"""used for copyrect encoding. copy the given rectangle
(src, srxy, width, height) to the target coords (x,y)"""
def fillRectangle(self, x, y, width, height, color):
"""fill the area with the color. the color is a string in
the pixel format set up earlier"""
#fallback variant, use update recatngle
#override with specialized function for better performance
self.updateRectangle(x, y, width, height, color*width*height)
def updateCursor(self, x, y, width, height, image, mask):
""" New cursor, focuses at (x, y)
"""
def updateDesktopSize(width, height):
""" New desktop size of width*height. """
def bell(self):
"""bell"""
def copy_text(self, text):
"""The server has new ASCII text in its cut buffer.
(aka clipboard)"""
|
sibson/vncdotool | vncdotool/rfb.py | RFBClient.pointerEvent | python | def pointerEvent(self, x, y, buttonmask=0):
self.transport.write(pack("!BBHH", 5, buttonmask, x, y)) | Indicates either pointer movement or a pointer button press or release. The pointer is
now at (x-position, y-position), and the current state of buttons 1 to 8 are represented
by bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning down (pressed). | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L579-L584 | null | class RFBClient(Protocol):
def __init__(self):
self._packet = []
self._packet_len = 0
self._handler = self._handleInitial
self._already_expecting = 0
self._version = None
self._version_server = None
#------------------------------------------------------
# states used on connection startup
#------------------------------------------------------
def _handleInitial(self):
buffer = b''.join(self._packet)
if b'\n' in buffer:
version = 3.3
if buffer[:3] == b'RFB':
version_server = float(buffer[3:-1].replace(b'0', b''))
SUPPORTED_VERSIONS = (3.3, 3.7, 3.8)
if version_server in SUPPORTED_VERSIONS:
version = version_server
else:
log.msg("Protocol version %.3f not supported"
% version_server)
version = max(filter(
lambda x: x <= version_server, SUPPORTED_VERSIONS))
buffer = buffer[12:]
log.msg("Using protocol version %.3f" % version)
parts = str(version).split('.')
self.transport.write(
bytes(b"RFB %03d.%03d\n" % (int(parts[0]), int(parts[1]))))
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._handler = self._handleExpected
self._version = version
self._version_server = version_server
if version < 3.7:
self.expect(self._handleAuth, 4)
else:
self.expect(self._handleNumberSecurityTypes, 1)
else:
self._packet[:] = [buffer]
self._packet_len = len(buffer)
def _handleNumberSecurityTypes(self, block):
(num_types,) = unpack("!B", block)
if num_types:
self.expect(self._handleSecurityTypes, num_types)
else:
self.expect(self._handleConnFailed, 4)
def _handleSecurityTypes(self, block):
types = unpack("!%dB" % len(block), block)
SUPPORTED_TYPES = (1, 2)
valid_types = [sec_type for sec_type in types if sec_type in SUPPORTED_TYPES]
if valid_types:
sec_type = max(valid_types)
self.transport.write(pack("!B", sec_type))
if sec_type == 1:
if self._version < 3.8:
self._doClientInitialization()
else:
self.expect(self._handleVNCAuthResult, 4)
else:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown security types: %s" % repr(types))
def _handleAuth(self, block):
(auth,) = unpack("!I", block)
#~ print "auth:", auth
if auth == 0:
self.expect(self._handleConnFailed, 4)
elif auth == 1:
self._doClientInitialization()
return
elif auth == 2:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown auth response (%d)" % auth)
def _handleConnFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleConnMessage, waitfor)
def _handleConnMessage(self, block):
log.msg("Connection refused: %r" % block)
def _handleVNCAuth(self, block):
self._challenge = block
self.vncRequestPassword()
self.expect(self._handleVNCAuthResult, 4)
def sendPassword(self, password):
"""send password"""
pw = (password + '\0' * 8)[:8] #make sure its 8 chars long, zero padded
des = RFBDes(pw)
response = des.encrypt(self._challenge)
self.transport.write(response)
def _handleVNCAuthResult(self, block):
(result,) = unpack("!I", block)
#~ print "auth:", auth
if result == 0: #OK
self._doClientInitialization()
return
elif result == 1: #failed
if self._version < 3.8:
self.vncAuthFailed("authentication failed")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
elif result == 2: #too many
if self._version < 3.8:
self.vncAuthFailed("too many tries to log in")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
else:
log.msg("unknown auth response (%d)" % result)
def _handleAuthFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleAuthFailedMessage, waitfor)
def _handleAuthFailedMessage(self, block):
self.vncAuthFailed(block)
self.transport.loseConnection()
def _doClientInitialization(self):
self.transport.write(pack("!B", self.factory.shared))
self.expect(self._handleServerInit, 24)
def _handleServerInit(self, block):
(self.width, self.height, pixformat, namelen) = unpack("!HH16sI", block)
(self.bpp, self.depth, self.bigendian, self.truecolor,
self.redmax, self.greenmax, self.bluemax,
self.redshift, self.greenshift, self.blueshift) = \
unpack("!BBBBHHHBBBxxx", pixformat)
self.bypp = self.bpp // 8 #calc bytes per pixel
self.expect(self._handleServerName, namelen)
def _handleServerName(self, block):
self.name = block
#callback:
self.vncConnectionMade()
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# Server to client messages
#------------------------------------------------------
def _handleConnection(self, block):
(msgid,) = unpack("!B", block)
if msgid == 0:
self.expect(self._handleFramebufferUpdate, 3)
elif msgid == 2:
self.bell()
self.expect(self._handleConnection, 1)
elif msgid == 3:
self.expect(self._handleServerCutText, 7)
else:
log.msg("unknown message received (id %d)" % msgid)
self.expect(self._handleConnection, 1)
def _handleFramebufferUpdate(self, block):
(self.rectangles,) = unpack("!xH", block)
self.rectanglePos = []
self.beginUpdate()
self._doConnection()
def _doConnection(self):
if self.rectangles:
self.expect(self._handleRectangle, 12)
else:
self.commitUpdate(self.rectanglePos)
self.expect(self._handleConnection, 1)
def _handleRectangle(self, block):
(x, y, width, height, encoding) = unpack("!HHHHi", block)
if self.rectangles:
self.rectangles -= 1
self.rectanglePos.append( (x, y, width, height) )
if encoding == COPY_RECTANGLE_ENCODING:
self.expect(self._handleDecodeCopyrect, 4, x, y, width, height)
elif encoding == RAW_ENCODING:
self.expect(self._handleDecodeRAW, width*height*self.bypp, x, y, width, height)
elif encoding == HEXTILE_ENCODING:
self._doNextHextileSubrect(None, None, x, y, width, height, None, None)
elif encoding == CORRE_ENCODING:
self.expect(self._handleDecodeCORRE, 4 + self.bypp, x, y, width, height)
elif encoding == RRE_ENCODING:
self.expect(self._handleDecodeRRE, 4 + self.bypp, x, y, width, height)
#~ elif encoding == ZRLE_ENCODING:
#~ self.expect(self._handleDecodeZRLE, )
elif encoding == PSEUDO_CURSOR_ENCODING:
length = width * height * self.bypp
length += int(math.floor((width + 7.0) / 8)) * height
self.expect(self._handleDecodePsuedoCursor, length, x, y, width, height)
elif encoding == PSEUDO_DESKTOP_SIZE_ENCODING:
self._handleDecodeDesktopSize(width, height)
else:
log.msg("unknown encoding received (encoding %d)" % encoding)
self._doConnection()
else:
self._doConnection()
# --- RAW Encoding
def _handleDecodeRAW(self, block, x, y, width, height):
#TODO convert pixel format?
self.updateRectangle(x, y, width, height, block)
self._doConnection()
# --- CopyRect Encoding
def _handleDecodeCopyrect(self, block, x, y, width, height):
(srcx, srcy) = unpack("!HH", block)
self.copyRectangle(srcx, srcy, x, y, width, height)
self._doConnection()
# --- RRE Encoding
def _handleDecodeRRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleRRESubRectangles, (8 + self.bypp) * subrects, x, y)
else:
self._doConnection()
def _handleRRESubRectangles(self, block, topx, topy):
#~ print "_handleRRESubRectangle"
pos = 0
end = len(block)
sz = self.bypp + 8
format = "!%dsHHHH" % self.bypp
while pos < end:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- CoRRE Encoding
def _handleDecodeCORRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleDecodeCORRERectangles, (4 + self.bypp)*subrects, x, y)
else:
self._doConnection()
def _handleDecodeCORRERectangles(self, block, topx, topy):
#~ print "_handleDecodeCORRERectangle"
pos = 0
end = len(block)
sz = self.bypp + 4
format = "!%dsBBBB" % self.bypp
while pos < sz:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- Hexile Encoding
def _doNextHextileSubrect(self, bg, color, x, y, width, height, tx, ty):
#~ print "_doNextHextileSubrect %r" % ((color, x, y, width, height, tx, ty), )
#coords of next tile
#its line after line of tiles
#finished when the last line is completly received
#dont inc the first time
if tx is not None:
#calc next subrect pos
tx += 16
if tx >= x + width:
tx = x
ty += 16
else:
tx = x
ty = y
#more tiles?
if ty >= y + height:
self._doConnection()
else:
self.expect(self._handleDecodeHextile, 1, bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextile(self, block, bg, color, x, y, width, height, tx, ty):
(subencoding,) = unpack("!B", block)
#calc tile size
tw = th = 16
if x + width - tx < 16: tw = x + width - tx
if y + height - ty < 16: th = y + height- ty
#decode tile
if subencoding & 1: #RAW
self.expect(self._handleDecodeHextileRAW, tw*th*self.bypp, bg, color, x, y, width, height, tx, ty, tw, th)
else:
numbytes = 0
if subencoding & 2: #BackgroundSpecified
numbytes += self.bypp
if subencoding & 4: #ForegroundSpecified
numbytes += self.bypp
if subencoding & 8: #AnySubrects
numbytes += 1
if numbytes:
self.expect(self._handleDecodeHextileSubrect, numbytes, subencoding, bg, color, x, y, width, height, tx, ty, tw, th)
else:
self.fillRectangle(tx, ty, tw, th, bg)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrect(self, block, subencoding, bg, color, x, y, width, height, tx, ty, tw, th):
subrects = 0
pos = 0
if subencoding & 2: #BackgroundSpecified
bg = block[:self.bypp]
pos += self.bypp
self.fillRectangle(tx, ty, tw, th, bg)
if subencoding & 4: #ForegroundSpecified
color = block[pos:pos+self.bypp]
pos += self.bypp
if subencoding & 8: #AnySubrects
#~ (subrects, ) = unpack("!B", block)
subrects = ord(block[pos])
#~ print subrects
if subrects:
if subencoding & 16: #SubrectsColoured
self.expect(self._handleDecodeHextileSubrectsColoured, (self.bypp + 2)*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self.expect(self._handleDecodeHextileSubrectsFG, 2*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):
"""the tile is in raw encoding"""
self.updateRectangle(tx, ty, tw, th, block)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""subrects with their own color"""
sz = self.bypp + 2
pos = 0
end = len(block)
while pos < end:
pos2 = pos + self.bypp
color = block[pos:pos2]
xy = ord(block[pos2])
wh = ord(block[pos2+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += sz
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsFG(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""all subrect with same color"""
pos = 0
end = len(block)
while pos < end:
xy = ord(block[pos])
wh = ord(block[pos+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += 2
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
# --- ZRLE Encoding
def _handleDecodeZRLE(self, block):
raise NotImplementedError
# --- Pseudo Cursor Encoding
def _handleDecodePsuedoCursor(self, block, x, y, width, height):
split = width * height * self.bypp
image = block[:split]
mask = block[split:]
self.updateCursor(x, y, width, height, image, mask)
self._doConnection()
# --- Pseudo Desktop Size Encoding
def _handleDecodeDesktopSize(self, width, height):
self.updateDesktopSize(width, height)
self._doConnection()
# --- other server messages
def _handleServerCutText(self, block):
(length, ) = unpack("!xxxI", block)
self.expect(self._handleServerCutTextValue, length)
def _handleServerCutTextValue(self, block):
self.copy_text(block)
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# incomming data redirector
#------------------------------------------------------
def dataReceived(self, data):
#~ sys.stdout.write(repr(data) + '\n')
#~ print len(data), ", ", len(self._packet)
self._packet.append(data)
self._packet_len += len(data)
self._handler()
def _handleExpected(self):
if self._packet_len >= self._expected_len:
buffer = b''.join(self._packet)
while len(buffer) >= self._expected_len:
self._already_expecting = 1
block, buffer = buffer[:self._expected_len], buffer[self._expected_len:]
#~ log.msg("handle %r with %r\n" % (block, self._expected_handler.__name__))
self._expected_handler(block, *self._expected_args, **self._expected_kwargs)
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._already_expecting = 0
def expect(self, handler, size, *args, **kwargs):
#~ log.msg("expect(%r, %r, %r, %r)\n" % (handler.__name__, size, args, kwargs))
self._expected_handler = handler
self._expected_len = size
self._expected_args = args
self._expected_kwargs = kwargs
if not self._already_expecting:
self._handleExpected() #just in case that there is already enough data
#------------------------------------------------------
# client -> server messages
#------------------------------------------------------
def setPixelFormat(self, bpp=32, depth=24, bigendian=0, truecolor=1, redmax=255, greenmax=255, bluemax=255, redshift=0, greenshift=8, blueshift=16):
pixformat = pack("!BBBBHHHBBBxxx", bpp, depth, bigendian, truecolor, redmax, greenmax, bluemax, redshift, greenshift, blueshift)
self.transport.write(pack("!Bxxx16s", 0, pixformat))
#rember these settings
self.bpp, self.depth, self.bigendian, self.truecolor = bpp, depth, bigendian, truecolor
self.redmax, self.greenmax, self.bluemax = redmax, greenmax, bluemax
self.redshift, self.greenshift, self.blueshift = redshift, greenshift, blueshift
self.bypp = self.bpp // 8 #calc bytes per pixel
#~ print self.bypp
def setEncodings(self, list_of_encodings):
self.transport.write(pack("!BxH", 2, len(list_of_encodings)))
for encoding in list_of_encodings:
self.transport.write(pack("!i", encoding))
def framebufferUpdateRequest(self, x=0, y=0, width=None, height=None, incremental=0):
if width is None: width = self.width - x
if height is None: height = self.height - y
self.transport.write(pack("!BBHHHH", 3, incremental, x, y, width, height))
def keyEvent(self, key, down=1):
"""For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants."""
self.transport.write(pack("!BBxxI", 4, down, key))
def clientCutText(self, message):
"""The client has new ASCII text in its cut buffer.
(aka clipboard)
"""
self.transport.write(pack("!BxxxI", 6, len(message)) + message)
#------------------------------------------------------
# callbacks
# override these in your application
#------------------------------------------------------
def vncConnectionMade(self):
"""connection is initialized and ready.
typicaly, the pixel format is set here."""
def vncRequestPassword(self):
"""a password is needed to log on, use sendPassword() to
send one."""
if self.factory.password is None:
log.msg("need a password")
self.transport.loseConnection()
return
self.sendPassword(self.factory.password)
def vncAuthFailed(self, reason):
"""called when the authentication failed.
the connection is closed."""
log.msg("Cannot connect %s" % reason)
def beginUpdate(self):
"""called before a series of updateRectangle(),
copyRectangle() or fillRectangle()."""
def commitUpdate(self, rectangles=None):
"""called after a series of updateRectangle(), copyRectangle()
or fillRectangle() are finished.
typicaly, here is the place to request the next screen
update with FramebufferUpdateRequest(incremental=1).
argument is a list of tuples (x,y,w,h) with the updated
rectangles."""
def updateRectangle(self, x, y, width, height, data):
"""new bitmap data. data is a string in the pixel format set
up earlier."""
def copyRectangle(self, srcx, srcy, x, y, width, height):
"""used for copyrect encoding. copy the given rectangle
(src, srxy, width, height) to the target coords (x,y)"""
def fillRectangle(self, x, y, width, height, color):
"""fill the area with the color. the color is a string in
the pixel format set up earlier"""
#fallback variant, use update recatngle
#override with specialized function for better performance
self.updateRectangle(x, y, width, height, color*width*height)
def updateCursor(self, x, y, width, height, image, mask):
""" New cursor, focuses at (x, y)
"""
def updateDesktopSize(width, height):
""" New desktop size of width*height. """
def bell(self):
"""bell"""
def copy_text(self, text):
"""The server has new ASCII text in its cut buffer.
(aka clipboard)"""
|
sibson/vncdotool | vncdotool/rfb.py | RFBClient.clientCutText | python | def clientCutText(self, message):
self.transport.write(pack("!BxxxI", 6, len(message)) + message) | The client has new ASCII text in its cut buffer.
(aka clipboard) | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L586-L590 | null | class RFBClient(Protocol):
def __init__(self):
self._packet = []
self._packet_len = 0
self._handler = self._handleInitial
self._already_expecting = 0
self._version = None
self._version_server = None
#------------------------------------------------------
# states used on connection startup
#------------------------------------------------------
def _handleInitial(self):
buffer = b''.join(self._packet)
if b'\n' in buffer:
version = 3.3
if buffer[:3] == b'RFB':
version_server = float(buffer[3:-1].replace(b'0', b''))
SUPPORTED_VERSIONS = (3.3, 3.7, 3.8)
if version_server in SUPPORTED_VERSIONS:
version = version_server
else:
log.msg("Protocol version %.3f not supported"
% version_server)
version = max(filter(
lambda x: x <= version_server, SUPPORTED_VERSIONS))
buffer = buffer[12:]
log.msg("Using protocol version %.3f" % version)
parts = str(version).split('.')
self.transport.write(
bytes(b"RFB %03d.%03d\n" % (int(parts[0]), int(parts[1]))))
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._handler = self._handleExpected
self._version = version
self._version_server = version_server
if version < 3.7:
self.expect(self._handleAuth, 4)
else:
self.expect(self._handleNumberSecurityTypes, 1)
else:
self._packet[:] = [buffer]
self._packet_len = len(buffer)
def _handleNumberSecurityTypes(self, block):
(num_types,) = unpack("!B", block)
if num_types:
self.expect(self._handleSecurityTypes, num_types)
else:
self.expect(self._handleConnFailed, 4)
def _handleSecurityTypes(self, block):
types = unpack("!%dB" % len(block), block)
SUPPORTED_TYPES = (1, 2)
valid_types = [sec_type for sec_type in types if sec_type in SUPPORTED_TYPES]
if valid_types:
sec_type = max(valid_types)
self.transport.write(pack("!B", sec_type))
if sec_type == 1:
if self._version < 3.8:
self._doClientInitialization()
else:
self.expect(self._handleVNCAuthResult, 4)
else:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown security types: %s" % repr(types))
def _handleAuth(self, block):
(auth,) = unpack("!I", block)
#~ print "auth:", auth
if auth == 0:
self.expect(self._handleConnFailed, 4)
elif auth == 1:
self._doClientInitialization()
return
elif auth == 2:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown auth response (%d)" % auth)
def _handleConnFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleConnMessage, waitfor)
def _handleConnMessage(self, block):
log.msg("Connection refused: %r" % block)
def _handleVNCAuth(self, block):
self._challenge = block
self.vncRequestPassword()
self.expect(self._handleVNCAuthResult, 4)
def sendPassword(self, password):
"""send password"""
pw = (password + '\0' * 8)[:8] #make sure its 8 chars long, zero padded
des = RFBDes(pw)
response = des.encrypt(self._challenge)
self.transport.write(response)
def _handleVNCAuthResult(self, block):
(result,) = unpack("!I", block)
#~ print "auth:", auth
if result == 0: #OK
self._doClientInitialization()
return
elif result == 1: #failed
if self._version < 3.8:
self.vncAuthFailed("authentication failed")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
elif result == 2: #too many
if self._version < 3.8:
self.vncAuthFailed("too many tries to log in")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
else:
log.msg("unknown auth response (%d)" % result)
def _handleAuthFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleAuthFailedMessage, waitfor)
def _handleAuthFailedMessage(self, block):
self.vncAuthFailed(block)
self.transport.loseConnection()
def _doClientInitialization(self):
self.transport.write(pack("!B", self.factory.shared))
self.expect(self._handleServerInit, 24)
def _handleServerInit(self, block):
(self.width, self.height, pixformat, namelen) = unpack("!HH16sI", block)
(self.bpp, self.depth, self.bigendian, self.truecolor,
self.redmax, self.greenmax, self.bluemax,
self.redshift, self.greenshift, self.blueshift) = \
unpack("!BBBBHHHBBBxxx", pixformat)
self.bypp = self.bpp // 8 #calc bytes per pixel
self.expect(self._handleServerName, namelen)
def _handleServerName(self, block):
self.name = block
#callback:
self.vncConnectionMade()
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# Server to client messages
#------------------------------------------------------
def _handleConnection(self, block):
(msgid,) = unpack("!B", block)
if msgid == 0:
self.expect(self._handleFramebufferUpdate, 3)
elif msgid == 2:
self.bell()
self.expect(self._handleConnection, 1)
elif msgid == 3:
self.expect(self._handleServerCutText, 7)
else:
log.msg("unknown message received (id %d)" % msgid)
self.expect(self._handleConnection, 1)
def _handleFramebufferUpdate(self, block):
(self.rectangles,) = unpack("!xH", block)
self.rectanglePos = []
self.beginUpdate()
self._doConnection()
def _doConnection(self):
if self.rectangles:
self.expect(self._handleRectangle, 12)
else:
self.commitUpdate(self.rectanglePos)
self.expect(self._handleConnection, 1)
def _handleRectangle(self, block):
(x, y, width, height, encoding) = unpack("!HHHHi", block)
if self.rectangles:
self.rectangles -= 1
self.rectanglePos.append( (x, y, width, height) )
if encoding == COPY_RECTANGLE_ENCODING:
self.expect(self._handleDecodeCopyrect, 4, x, y, width, height)
elif encoding == RAW_ENCODING:
self.expect(self._handleDecodeRAW, width*height*self.bypp, x, y, width, height)
elif encoding == HEXTILE_ENCODING:
self._doNextHextileSubrect(None, None, x, y, width, height, None, None)
elif encoding == CORRE_ENCODING:
self.expect(self._handleDecodeCORRE, 4 + self.bypp, x, y, width, height)
elif encoding == RRE_ENCODING:
self.expect(self._handleDecodeRRE, 4 + self.bypp, x, y, width, height)
#~ elif encoding == ZRLE_ENCODING:
#~ self.expect(self._handleDecodeZRLE, )
elif encoding == PSEUDO_CURSOR_ENCODING:
length = width * height * self.bypp
length += int(math.floor((width + 7.0) / 8)) * height
self.expect(self._handleDecodePsuedoCursor, length, x, y, width, height)
elif encoding == PSEUDO_DESKTOP_SIZE_ENCODING:
self._handleDecodeDesktopSize(width, height)
else:
log.msg("unknown encoding received (encoding %d)" % encoding)
self._doConnection()
else:
self._doConnection()
# --- RAW Encoding
def _handleDecodeRAW(self, block, x, y, width, height):
#TODO convert pixel format?
self.updateRectangle(x, y, width, height, block)
self._doConnection()
# --- CopyRect Encoding
def _handleDecodeCopyrect(self, block, x, y, width, height):
(srcx, srcy) = unpack("!HH", block)
self.copyRectangle(srcx, srcy, x, y, width, height)
self._doConnection()
# --- RRE Encoding
def _handleDecodeRRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleRRESubRectangles, (8 + self.bypp) * subrects, x, y)
else:
self._doConnection()
def _handleRRESubRectangles(self, block, topx, topy):
#~ print "_handleRRESubRectangle"
pos = 0
end = len(block)
sz = self.bypp + 8
format = "!%dsHHHH" % self.bypp
while pos < end:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- CoRRE Encoding
def _handleDecodeCORRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleDecodeCORRERectangles, (4 + self.bypp)*subrects, x, y)
else:
self._doConnection()
def _handleDecodeCORRERectangles(self, block, topx, topy):
#~ print "_handleDecodeCORRERectangle"
pos = 0
end = len(block)
sz = self.bypp + 4
format = "!%dsBBBB" % self.bypp
while pos < sz:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- Hexile Encoding
def _doNextHextileSubrect(self, bg, color, x, y, width, height, tx, ty):
#~ print "_doNextHextileSubrect %r" % ((color, x, y, width, height, tx, ty), )
#coords of next tile
#its line after line of tiles
#finished when the last line is completly received
#dont inc the first time
if tx is not None:
#calc next subrect pos
tx += 16
if tx >= x + width:
tx = x
ty += 16
else:
tx = x
ty = y
#more tiles?
if ty >= y + height:
self._doConnection()
else:
self.expect(self._handleDecodeHextile, 1, bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextile(self, block, bg, color, x, y, width, height, tx, ty):
(subencoding,) = unpack("!B", block)
#calc tile size
tw = th = 16
if x + width - tx < 16: tw = x + width - tx
if y + height - ty < 16: th = y + height- ty
#decode tile
if subencoding & 1: #RAW
self.expect(self._handleDecodeHextileRAW, tw*th*self.bypp, bg, color, x, y, width, height, tx, ty, tw, th)
else:
numbytes = 0
if subencoding & 2: #BackgroundSpecified
numbytes += self.bypp
if subencoding & 4: #ForegroundSpecified
numbytes += self.bypp
if subencoding & 8: #AnySubrects
numbytes += 1
if numbytes:
self.expect(self._handleDecodeHextileSubrect, numbytes, subencoding, bg, color, x, y, width, height, tx, ty, tw, th)
else:
self.fillRectangle(tx, ty, tw, th, bg)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrect(self, block, subencoding, bg, color, x, y, width, height, tx, ty, tw, th):
subrects = 0
pos = 0
if subencoding & 2: #BackgroundSpecified
bg = block[:self.bypp]
pos += self.bypp
self.fillRectangle(tx, ty, tw, th, bg)
if subencoding & 4: #ForegroundSpecified
color = block[pos:pos+self.bypp]
pos += self.bypp
if subencoding & 8: #AnySubrects
#~ (subrects, ) = unpack("!B", block)
subrects = ord(block[pos])
#~ print subrects
if subrects:
if subencoding & 16: #SubrectsColoured
self.expect(self._handleDecodeHextileSubrectsColoured, (self.bypp + 2)*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self.expect(self._handleDecodeHextileSubrectsFG, 2*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):
"""the tile is in raw encoding"""
self.updateRectangle(tx, ty, tw, th, block)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""subrects with their own color"""
sz = self.bypp + 2
pos = 0
end = len(block)
while pos < end:
pos2 = pos + self.bypp
color = block[pos:pos2]
xy = ord(block[pos2])
wh = ord(block[pos2+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += sz
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsFG(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""all subrect with same color"""
pos = 0
end = len(block)
while pos < end:
xy = ord(block[pos])
wh = ord(block[pos+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += 2
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
# --- ZRLE Encoding
def _handleDecodeZRLE(self, block):
raise NotImplementedError
# --- Pseudo Cursor Encoding
def _handleDecodePsuedoCursor(self, block, x, y, width, height):
split = width * height * self.bypp
image = block[:split]
mask = block[split:]
self.updateCursor(x, y, width, height, image, mask)
self._doConnection()
# --- Pseudo Desktop Size Encoding
def _handleDecodeDesktopSize(self, width, height):
self.updateDesktopSize(width, height)
self._doConnection()
# --- other server messages
def _handleServerCutText(self, block):
(length, ) = unpack("!xxxI", block)
self.expect(self._handleServerCutTextValue, length)
def _handleServerCutTextValue(self, block):
self.copy_text(block)
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# incomming data redirector
#------------------------------------------------------
def dataReceived(self, data):
#~ sys.stdout.write(repr(data) + '\n')
#~ print len(data), ", ", len(self._packet)
self._packet.append(data)
self._packet_len += len(data)
self._handler()
def _handleExpected(self):
if self._packet_len >= self._expected_len:
buffer = b''.join(self._packet)
while len(buffer) >= self._expected_len:
self._already_expecting = 1
block, buffer = buffer[:self._expected_len], buffer[self._expected_len:]
#~ log.msg("handle %r with %r\n" % (block, self._expected_handler.__name__))
self._expected_handler(block, *self._expected_args, **self._expected_kwargs)
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._already_expecting = 0
def expect(self, handler, size, *args, **kwargs):
#~ log.msg("expect(%r, %r, %r, %r)\n" % (handler.__name__, size, args, kwargs))
self._expected_handler = handler
self._expected_len = size
self._expected_args = args
self._expected_kwargs = kwargs
if not self._already_expecting:
self._handleExpected() #just in case that there is already enough data
#------------------------------------------------------
# client -> server messages
#------------------------------------------------------
def setPixelFormat(self, bpp=32, depth=24, bigendian=0, truecolor=1, redmax=255, greenmax=255, bluemax=255, redshift=0, greenshift=8, blueshift=16):
pixformat = pack("!BBBBHHHBBBxxx", bpp, depth, bigendian, truecolor, redmax, greenmax, bluemax, redshift, greenshift, blueshift)
self.transport.write(pack("!Bxxx16s", 0, pixformat))
#rember these settings
self.bpp, self.depth, self.bigendian, self.truecolor = bpp, depth, bigendian, truecolor
self.redmax, self.greenmax, self.bluemax = redmax, greenmax, bluemax
self.redshift, self.greenshift, self.blueshift = redshift, greenshift, blueshift
self.bypp = self.bpp // 8 #calc bytes per pixel
#~ print self.bypp
def setEncodings(self, list_of_encodings):
self.transport.write(pack("!BxH", 2, len(list_of_encodings)))
for encoding in list_of_encodings:
self.transport.write(pack("!i", encoding))
def framebufferUpdateRequest(self, x=0, y=0, width=None, height=None, incremental=0):
if width is None: width = self.width - x
if height is None: height = self.height - y
self.transport.write(pack("!BBHHHH", 3, incremental, x, y, width, height))
def keyEvent(self, key, down=1):
"""For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants."""
self.transport.write(pack("!BBxxI", 4, down, key))
def pointerEvent(self, x, y, buttonmask=0):
"""Indicates either pointer movement or a pointer button press or release. The pointer is
now at (x-position, y-position), and the current state of buttons 1 to 8 are represented
by bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning down (pressed).
"""
self.transport.write(pack("!BBHH", 5, buttonmask, x, y))
#------------------------------------------------------
# callbacks
# override these in your application
#------------------------------------------------------
def vncConnectionMade(self):
"""connection is initialized and ready.
typicaly, the pixel format is set here."""
def vncRequestPassword(self):
"""a password is needed to log on, use sendPassword() to
send one."""
if self.factory.password is None:
log.msg("need a password")
self.transport.loseConnection()
return
self.sendPassword(self.factory.password)
def vncAuthFailed(self, reason):
"""called when the authentication failed.
the connection is closed."""
log.msg("Cannot connect %s" % reason)
def beginUpdate(self):
"""called before a series of updateRectangle(),
copyRectangle() or fillRectangle()."""
def commitUpdate(self, rectangles=None):
"""called after a series of updateRectangle(), copyRectangle()
or fillRectangle() are finished.
typicaly, here is the place to request the next screen
update with FramebufferUpdateRequest(incremental=1).
argument is a list of tuples (x,y,w,h) with the updated
rectangles."""
def updateRectangle(self, x, y, width, height, data):
"""new bitmap data. data is a string in the pixel format set
up earlier."""
def copyRectangle(self, srcx, srcy, x, y, width, height):
"""used for copyrect encoding. copy the given rectangle
(src, srxy, width, height) to the target coords (x,y)"""
def fillRectangle(self, x, y, width, height, color):
"""fill the area with the color. the color is a string in
the pixel format set up earlier"""
#fallback variant, use update recatngle
#override with specialized function for better performance
self.updateRectangle(x, y, width, height, color*width*height)
def updateCursor(self, x, y, width, height, image, mask):
""" New cursor, focuses at (x, y)
"""
def updateDesktopSize(width, height):
""" New desktop size of width*height. """
def bell(self):
"""bell"""
def copy_text(self, text):
"""The server has new ASCII text in its cut buffer.
(aka clipboard)"""
|
sibson/vncdotool | vncdotool/rfb.py | RFBClient.vncRequestPassword | python | def vncRequestPassword(self):
if self.factory.password is None:
log.msg("need a password")
self.transport.loseConnection()
return
self.sendPassword(self.factory.password) | a password is needed to log on, use sendPassword() to
send one. | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L600-L607 | null | class RFBClient(Protocol):
def __init__(self):
self._packet = []
self._packet_len = 0
self._handler = self._handleInitial
self._already_expecting = 0
self._version = None
self._version_server = None
#------------------------------------------------------
# states used on connection startup
#------------------------------------------------------
def _handleInitial(self):
buffer = b''.join(self._packet)
if b'\n' in buffer:
version = 3.3
if buffer[:3] == b'RFB':
version_server = float(buffer[3:-1].replace(b'0', b''))
SUPPORTED_VERSIONS = (3.3, 3.7, 3.8)
if version_server in SUPPORTED_VERSIONS:
version = version_server
else:
log.msg("Protocol version %.3f not supported"
% version_server)
version = max(filter(
lambda x: x <= version_server, SUPPORTED_VERSIONS))
buffer = buffer[12:]
log.msg("Using protocol version %.3f" % version)
parts = str(version).split('.')
self.transport.write(
bytes(b"RFB %03d.%03d\n" % (int(parts[0]), int(parts[1]))))
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._handler = self._handleExpected
self._version = version
self._version_server = version_server
if version < 3.7:
self.expect(self._handleAuth, 4)
else:
self.expect(self._handleNumberSecurityTypes, 1)
else:
self._packet[:] = [buffer]
self._packet_len = len(buffer)
def _handleNumberSecurityTypes(self, block):
(num_types,) = unpack("!B", block)
if num_types:
self.expect(self._handleSecurityTypes, num_types)
else:
self.expect(self._handleConnFailed, 4)
def _handleSecurityTypes(self, block):
types = unpack("!%dB" % len(block), block)
SUPPORTED_TYPES = (1, 2)
valid_types = [sec_type for sec_type in types if sec_type in SUPPORTED_TYPES]
if valid_types:
sec_type = max(valid_types)
self.transport.write(pack("!B", sec_type))
if sec_type == 1:
if self._version < 3.8:
self._doClientInitialization()
else:
self.expect(self._handleVNCAuthResult, 4)
else:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown security types: %s" % repr(types))
def _handleAuth(self, block):
(auth,) = unpack("!I", block)
#~ print "auth:", auth
if auth == 0:
self.expect(self._handleConnFailed, 4)
elif auth == 1:
self._doClientInitialization()
return
elif auth == 2:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown auth response (%d)" % auth)
def _handleConnFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleConnMessage, waitfor)
def _handleConnMessage(self, block):
log.msg("Connection refused: %r" % block)
def _handleVNCAuth(self, block):
self._challenge = block
self.vncRequestPassword()
self.expect(self._handleVNCAuthResult, 4)
def sendPassword(self, password):
"""send password"""
pw = (password + '\0' * 8)[:8] #make sure its 8 chars long, zero padded
des = RFBDes(pw)
response = des.encrypt(self._challenge)
self.transport.write(response)
def _handleVNCAuthResult(self, block):
(result,) = unpack("!I", block)
#~ print "auth:", auth
if result == 0: #OK
self._doClientInitialization()
return
elif result == 1: #failed
if self._version < 3.8:
self.vncAuthFailed("authentication failed")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
elif result == 2: #too many
if self._version < 3.8:
self.vncAuthFailed("too many tries to log in")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
else:
log.msg("unknown auth response (%d)" % result)
def _handleAuthFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleAuthFailedMessage, waitfor)
def _handleAuthFailedMessage(self, block):
self.vncAuthFailed(block)
self.transport.loseConnection()
def _doClientInitialization(self):
self.transport.write(pack("!B", self.factory.shared))
self.expect(self._handleServerInit, 24)
def _handleServerInit(self, block):
(self.width, self.height, pixformat, namelen) = unpack("!HH16sI", block)
(self.bpp, self.depth, self.bigendian, self.truecolor,
self.redmax, self.greenmax, self.bluemax,
self.redshift, self.greenshift, self.blueshift) = \
unpack("!BBBBHHHBBBxxx", pixformat)
self.bypp = self.bpp // 8 #calc bytes per pixel
self.expect(self._handleServerName, namelen)
def _handleServerName(self, block):
self.name = block
#callback:
self.vncConnectionMade()
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# Server to client messages
#------------------------------------------------------
def _handleConnection(self, block):
(msgid,) = unpack("!B", block)
if msgid == 0:
self.expect(self._handleFramebufferUpdate, 3)
elif msgid == 2:
self.bell()
self.expect(self._handleConnection, 1)
elif msgid == 3:
self.expect(self._handleServerCutText, 7)
else:
log.msg("unknown message received (id %d)" % msgid)
self.expect(self._handleConnection, 1)
def _handleFramebufferUpdate(self, block):
(self.rectangles,) = unpack("!xH", block)
self.rectanglePos = []
self.beginUpdate()
self._doConnection()
def _doConnection(self):
if self.rectangles:
self.expect(self._handleRectangle, 12)
else:
self.commitUpdate(self.rectanglePos)
self.expect(self._handleConnection, 1)
def _handleRectangle(self, block):
(x, y, width, height, encoding) = unpack("!HHHHi", block)
if self.rectangles:
self.rectangles -= 1
self.rectanglePos.append( (x, y, width, height) )
if encoding == COPY_RECTANGLE_ENCODING:
self.expect(self._handleDecodeCopyrect, 4, x, y, width, height)
elif encoding == RAW_ENCODING:
self.expect(self._handleDecodeRAW, width*height*self.bypp, x, y, width, height)
elif encoding == HEXTILE_ENCODING:
self._doNextHextileSubrect(None, None, x, y, width, height, None, None)
elif encoding == CORRE_ENCODING:
self.expect(self._handleDecodeCORRE, 4 + self.bypp, x, y, width, height)
elif encoding == RRE_ENCODING:
self.expect(self._handleDecodeRRE, 4 + self.bypp, x, y, width, height)
#~ elif encoding == ZRLE_ENCODING:
#~ self.expect(self._handleDecodeZRLE, )
elif encoding == PSEUDO_CURSOR_ENCODING:
length = width * height * self.bypp
length += int(math.floor((width + 7.0) / 8)) * height
self.expect(self._handleDecodePsuedoCursor, length, x, y, width, height)
elif encoding == PSEUDO_DESKTOP_SIZE_ENCODING:
self._handleDecodeDesktopSize(width, height)
else:
log.msg("unknown encoding received (encoding %d)" % encoding)
self._doConnection()
else:
self._doConnection()
# --- RAW Encoding
def _handleDecodeRAW(self, block, x, y, width, height):
#TODO convert pixel format?
self.updateRectangle(x, y, width, height, block)
self._doConnection()
# --- CopyRect Encoding
def _handleDecodeCopyrect(self, block, x, y, width, height):
(srcx, srcy) = unpack("!HH", block)
self.copyRectangle(srcx, srcy, x, y, width, height)
self._doConnection()
# --- RRE Encoding
def _handleDecodeRRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleRRESubRectangles, (8 + self.bypp) * subrects, x, y)
else:
self._doConnection()
def _handleRRESubRectangles(self, block, topx, topy):
#~ print "_handleRRESubRectangle"
pos = 0
end = len(block)
sz = self.bypp + 8
format = "!%dsHHHH" % self.bypp
while pos < end:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- CoRRE Encoding
def _handleDecodeCORRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleDecodeCORRERectangles, (4 + self.bypp)*subrects, x, y)
else:
self._doConnection()
def _handleDecodeCORRERectangles(self, block, topx, topy):
#~ print "_handleDecodeCORRERectangle"
pos = 0
end = len(block)
sz = self.bypp + 4
format = "!%dsBBBB" % self.bypp
while pos < sz:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- Hexile Encoding
def _doNextHextileSubrect(self, bg, color, x, y, width, height, tx, ty):
#~ print "_doNextHextileSubrect %r" % ((color, x, y, width, height, tx, ty), )
#coords of next tile
#its line after line of tiles
#finished when the last line is completly received
#dont inc the first time
if tx is not None:
#calc next subrect pos
tx += 16
if tx >= x + width:
tx = x
ty += 16
else:
tx = x
ty = y
#more tiles?
if ty >= y + height:
self._doConnection()
else:
self.expect(self._handleDecodeHextile, 1, bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextile(self, block, bg, color, x, y, width, height, tx, ty):
(subencoding,) = unpack("!B", block)
#calc tile size
tw = th = 16
if x + width - tx < 16: tw = x + width - tx
if y + height - ty < 16: th = y + height- ty
#decode tile
if subencoding & 1: #RAW
self.expect(self._handleDecodeHextileRAW, tw*th*self.bypp, bg, color, x, y, width, height, tx, ty, tw, th)
else:
numbytes = 0
if subencoding & 2: #BackgroundSpecified
numbytes += self.bypp
if subencoding & 4: #ForegroundSpecified
numbytes += self.bypp
if subencoding & 8: #AnySubrects
numbytes += 1
if numbytes:
self.expect(self._handleDecodeHextileSubrect, numbytes, subencoding, bg, color, x, y, width, height, tx, ty, tw, th)
else:
self.fillRectangle(tx, ty, tw, th, bg)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrect(self, block, subencoding, bg, color, x, y, width, height, tx, ty, tw, th):
subrects = 0
pos = 0
if subencoding & 2: #BackgroundSpecified
bg = block[:self.bypp]
pos += self.bypp
self.fillRectangle(tx, ty, tw, th, bg)
if subencoding & 4: #ForegroundSpecified
color = block[pos:pos+self.bypp]
pos += self.bypp
if subencoding & 8: #AnySubrects
#~ (subrects, ) = unpack("!B", block)
subrects = ord(block[pos])
#~ print subrects
if subrects:
if subencoding & 16: #SubrectsColoured
self.expect(self._handleDecodeHextileSubrectsColoured, (self.bypp + 2)*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self.expect(self._handleDecodeHextileSubrectsFG, 2*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):
"""the tile is in raw encoding"""
self.updateRectangle(tx, ty, tw, th, block)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""subrects with their own color"""
sz = self.bypp + 2
pos = 0
end = len(block)
while pos < end:
pos2 = pos + self.bypp
color = block[pos:pos2]
xy = ord(block[pos2])
wh = ord(block[pos2+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += sz
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsFG(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""all subrect with same color"""
pos = 0
end = len(block)
while pos < end:
xy = ord(block[pos])
wh = ord(block[pos+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += 2
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
# --- ZRLE Encoding
def _handleDecodeZRLE(self, block):
raise NotImplementedError
# --- Pseudo Cursor Encoding
def _handleDecodePsuedoCursor(self, block, x, y, width, height):
split = width * height * self.bypp
image = block[:split]
mask = block[split:]
self.updateCursor(x, y, width, height, image, mask)
self._doConnection()
# --- Pseudo Desktop Size Encoding
def _handleDecodeDesktopSize(self, width, height):
self.updateDesktopSize(width, height)
self._doConnection()
# --- other server messages
def _handleServerCutText(self, block):
(length, ) = unpack("!xxxI", block)
self.expect(self._handleServerCutTextValue, length)
def _handleServerCutTextValue(self, block):
self.copy_text(block)
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# incomming data redirector
#------------------------------------------------------
def dataReceived(self, data):
#~ sys.stdout.write(repr(data) + '\n')
#~ print len(data), ", ", len(self._packet)
self._packet.append(data)
self._packet_len += len(data)
self._handler()
def _handleExpected(self):
if self._packet_len >= self._expected_len:
buffer = b''.join(self._packet)
while len(buffer) >= self._expected_len:
self._already_expecting = 1
block, buffer = buffer[:self._expected_len], buffer[self._expected_len:]
#~ log.msg("handle %r with %r\n" % (block, self._expected_handler.__name__))
self._expected_handler(block, *self._expected_args, **self._expected_kwargs)
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._already_expecting = 0
def expect(self, handler, size, *args, **kwargs):
#~ log.msg("expect(%r, %r, %r, %r)\n" % (handler.__name__, size, args, kwargs))
self._expected_handler = handler
self._expected_len = size
self._expected_args = args
self._expected_kwargs = kwargs
if not self._already_expecting:
self._handleExpected() #just in case that there is already enough data
#------------------------------------------------------
# client -> server messages
#------------------------------------------------------
def setPixelFormat(self, bpp=32, depth=24, bigendian=0, truecolor=1, redmax=255, greenmax=255, bluemax=255, redshift=0, greenshift=8, blueshift=16):
pixformat = pack("!BBBBHHHBBBxxx", bpp, depth, bigendian, truecolor, redmax, greenmax, bluemax, redshift, greenshift, blueshift)
self.transport.write(pack("!Bxxx16s", 0, pixformat))
#rember these settings
self.bpp, self.depth, self.bigendian, self.truecolor = bpp, depth, bigendian, truecolor
self.redmax, self.greenmax, self.bluemax = redmax, greenmax, bluemax
self.redshift, self.greenshift, self.blueshift = redshift, greenshift, blueshift
self.bypp = self.bpp // 8 #calc bytes per pixel
#~ print self.bypp
def setEncodings(self, list_of_encodings):
self.transport.write(pack("!BxH", 2, len(list_of_encodings)))
for encoding in list_of_encodings:
self.transport.write(pack("!i", encoding))
def framebufferUpdateRequest(self, x=0, y=0, width=None, height=None, incremental=0):
if width is None: width = self.width - x
if height is None: height = self.height - y
self.transport.write(pack("!BBHHHH", 3, incremental, x, y, width, height))
def keyEvent(self, key, down=1):
"""For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants."""
self.transport.write(pack("!BBxxI", 4, down, key))
def pointerEvent(self, x, y, buttonmask=0):
"""Indicates either pointer movement or a pointer button press or release. The pointer is
now at (x-position, y-position), and the current state of buttons 1 to 8 are represented
by bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning down (pressed).
"""
self.transport.write(pack("!BBHH", 5, buttonmask, x, y))
def clientCutText(self, message):
"""The client has new ASCII text in its cut buffer.
(aka clipboard)
"""
self.transport.write(pack("!BxxxI", 6, len(message)) + message)
#------------------------------------------------------
# callbacks
# override these in your application
#------------------------------------------------------
def vncConnectionMade(self):
"""connection is initialized and ready.
typicaly, the pixel format is set here."""
def vncAuthFailed(self, reason):
"""called when the authentication failed.
the connection is closed."""
log.msg("Cannot connect %s" % reason)
def beginUpdate(self):
"""called before a series of updateRectangle(),
copyRectangle() or fillRectangle()."""
def commitUpdate(self, rectangles=None):
"""called after a series of updateRectangle(), copyRectangle()
or fillRectangle() are finished.
typicaly, here is the place to request the next screen
update with FramebufferUpdateRequest(incremental=1).
argument is a list of tuples (x,y,w,h) with the updated
rectangles."""
def updateRectangle(self, x, y, width, height, data):
"""new bitmap data. data is a string in the pixel format set
up earlier."""
def copyRectangle(self, srcx, srcy, x, y, width, height):
"""used for copyrect encoding. copy the given rectangle
(src, srxy, width, height) to the target coords (x,y)"""
def fillRectangle(self, x, y, width, height, color):
"""fill the area with the color. the color is a string in
the pixel format set up earlier"""
#fallback variant, use update recatngle
#override with specialized function for better performance
self.updateRectangle(x, y, width, height, color*width*height)
def updateCursor(self, x, y, width, height, image, mask):
""" New cursor, focuses at (x, y)
"""
def updateDesktopSize(width, height):
""" New desktop size of width*height. """
def bell(self):
"""bell"""
def copy_text(self, text):
"""The server has new ASCII text in its cut buffer.
(aka clipboard)"""
|
sibson/vncdotool | vncdotool/rfb.py | RFBClient.fillRectangle | python | def fillRectangle(self, x, y, width, height, color):
#fallback variant, use update recatngle
#override with specialized function for better performance
self.updateRectangle(x, y, width, height, color*width*height) | fill the area with the color. the color is a string in
the pixel format set up earlier | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L634-L639 | null | class RFBClient(Protocol):
def __init__(self):
self._packet = []
self._packet_len = 0
self._handler = self._handleInitial
self._already_expecting = 0
self._version = None
self._version_server = None
#------------------------------------------------------
# states used on connection startup
#------------------------------------------------------
def _handleInitial(self):
buffer = b''.join(self._packet)
if b'\n' in buffer:
version = 3.3
if buffer[:3] == b'RFB':
version_server = float(buffer[3:-1].replace(b'0', b''))
SUPPORTED_VERSIONS = (3.3, 3.7, 3.8)
if version_server in SUPPORTED_VERSIONS:
version = version_server
else:
log.msg("Protocol version %.3f not supported"
% version_server)
version = max(filter(
lambda x: x <= version_server, SUPPORTED_VERSIONS))
buffer = buffer[12:]
log.msg("Using protocol version %.3f" % version)
parts = str(version).split('.')
self.transport.write(
bytes(b"RFB %03d.%03d\n" % (int(parts[0]), int(parts[1]))))
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._handler = self._handleExpected
self._version = version
self._version_server = version_server
if version < 3.7:
self.expect(self._handleAuth, 4)
else:
self.expect(self._handleNumberSecurityTypes, 1)
else:
self._packet[:] = [buffer]
self._packet_len = len(buffer)
def _handleNumberSecurityTypes(self, block):
(num_types,) = unpack("!B", block)
if num_types:
self.expect(self._handleSecurityTypes, num_types)
else:
self.expect(self._handleConnFailed, 4)
def _handleSecurityTypes(self, block):
types = unpack("!%dB" % len(block), block)
SUPPORTED_TYPES = (1, 2)
valid_types = [sec_type for sec_type in types if sec_type in SUPPORTED_TYPES]
if valid_types:
sec_type = max(valid_types)
self.transport.write(pack("!B", sec_type))
if sec_type == 1:
if self._version < 3.8:
self._doClientInitialization()
else:
self.expect(self._handleVNCAuthResult, 4)
else:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown security types: %s" % repr(types))
def _handleAuth(self, block):
(auth,) = unpack("!I", block)
#~ print "auth:", auth
if auth == 0:
self.expect(self._handleConnFailed, 4)
elif auth == 1:
self._doClientInitialization()
return
elif auth == 2:
self.expect(self._handleVNCAuth, 16)
else:
log.msg("unknown auth response (%d)" % auth)
def _handleConnFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleConnMessage, waitfor)
def _handleConnMessage(self, block):
log.msg("Connection refused: %r" % block)
def _handleVNCAuth(self, block):
self._challenge = block
self.vncRequestPassword()
self.expect(self._handleVNCAuthResult, 4)
def sendPassword(self, password):
"""send password"""
pw = (password + '\0' * 8)[:8] #make sure its 8 chars long, zero padded
des = RFBDes(pw)
response = des.encrypt(self._challenge)
self.transport.write(response)
def _handleVNCAuthResult(self, block):
(result,) = unpack("!I", block)
#~ print "auth:", auth
if result == 0: #OK
self._doClientInitialization()
return
elif result == 1: #failed
if self._version < 3.8:
self.vncAuthFailed("authentication failed")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
elif result == 2: #too many
if self._version < 3.8:
self.vncAuthFailed("too many tries to log in")
self.transport.loseConnection()
else:
self.expect(self._handleAuthFailed, 4)
else:
log.msg("unknown auth response (%d)" % result)
def _handleAuthFailed(self, block):
(waitfor,) = unpack("!I", block)
self.expect(self._handleAuthFailedMessage, waitfor)
def _handleAuthFailedMessage(self, block):
self.vncAuthFailed(block)
self.transport.loseConnection()
def _doClientInitialization(self):
self.transport.write(pack("!B", self.factory.shared))
self.expect(self._handleServerInit, 24)
def _handleServerInit(self, block):
(self.width, self.height, pixformat, namelen) = unpack("!HH16sI", block)
(self.bpp, self.depth, self.bigendian, self.truecolor,
self.redmax, self.greenmax, self.bluemax,
self.redshift, self.greenshift, self.blueshift) = \
unpack("!BBBBHHHBBBxxx", pixformat)
self.bypp = self.bpp // 8 #calc bytes per pixel
self.expect(self._handleServerName, namelen)
def _handleServerName(self, block):
self.name = block
#callback:
self.vncConnectionMade()
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# Server to client messages
#------------------------------------------------------
def _handleConnection(self, block):
(msgid,) = unpack("!B", block)
if msgid == 0:
self.expect(self._handleFramebufferUpdate, 3)
elif msgid == 2:
self.bell()
self.expect(self._handleConnection, 1)
elif msgid == 3:
self.expect(self._handleServerCutText, 7)
else:
log.msg("unknown message received (id %d)" % msgid)
self.expect(self._handleConnection, 1)
def _handleFramebufferUpdate(self, block):
(self.rectangles,) = unpack("!xH", block)
self.rectanglePos = []
self.beginUpdate()
self._doConnection()
def _doConnection(self):
if self.rectangles:
self.expect(self._handleRectangle, 12)
else:
self.commitUpdate(self.rectanglePos)
self.expect(self._handleConnection, 1)
def _handleRectangle(self, block):
(x, y, width, height, encoding) = unpack("!HHHHi", block)
if self.rectangles:
self.rectangles -= 1
self.rectanglePos.append( (x, y, width, height) )
if encoding == COPY_RECTANGLE_ENCODING:
self.expect(self._handleDecodeCopyrect, 4, x, y, width, height)
elif encoding == RAW_ENCODING:
self.expect(self._handleDecodeRAW, width*height*self.bypp, x, y, width, height)
elif encoding == HEXTILE_ENCODING:
self._doNextHextileSubrect(None, None, x, y, width, height, None, None)
elif encoding == CORRE_ENCODING:
self.expect(self._handleDecodeCORRE, 4 + self.bypp, x, y, width, height)
elif encoding == RRE_ENCODING:
self.expect(self._handleDecodeRRE, 4 + self.bypp, x, y, width, height)
#~ elif encoding == ZRLE_ENCODING:
#~ self.expect(self._handleDecodeZRLE, )
elif encoding == PSEUDO_CURSOR_ENCODING:
length = width * height * self.bypp
length += int(math.floor((width + 7.0) / 8)) * height
self.expect(self._handleDecodePsuedoCursor, length, x, y, width, height)
elif encoding == PSEUDO_DESKTOP_SIZE_ENCODING:
self._handleDecodeDesktopSize(width, height)
else:
log.msg("unknown encoding received (encoding %d)" % encoding)
self._doConnection()
else:
self._doConnection()
# --- RAW Encoding
def _handleDecodeRAW(self, block, x, y, width, height):
#TODO convert pixel format?
self.updateRectangle(x, y, width, height, block)
self._doConnection()
# --- CopyRect Encoding
def _handleDecodeCopyrect(self, block, x, y, width, height):
(srcx, srcy) = unpack("!HH", block)
self.copyRectangle(srcx, srcy, x, y, width, height)
self._doConnection()
# --- RRE Encoding
def _handleDecodeRRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleRRESubRectangles, (8 + self.bypp) * subrects, x, y)
else:
self._doConnection()
def _handleRRESubRectangles(self, block, topx, topy):
#~ print "_handleRRESubRectangle"
pos = 0
end = len(block)
sz = self.bypp + 8
format = "!%dsHHHH" % self.bypp
while pos < end:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- CoRRE Encoding
def _handleDecodeCORRE(self, block, x, y, width, height):
(subrects,) = unpack("!I", block[:4])
color = block[4:]
self.fillRectangle(x, y, width, height, color)
if subrects:
self.expect(self._handleDecodeCORRERectangles, (4 + self.bypp)*subrects, x, y)
else:
self._doConnection()
def _handleDecodeCORRERectangles(self, block, topx, topy):
#~ print "_handleDecodeCORRERectangle"
pos = 0
end = len(block)
sz = self.bypp + 4
format = "!%dsBBBB" % self.bypp
while pos < sz:
(color, x, y, width, height) = unpack(format, block[pos:pos+sz])
self.fillRectangle(topx + x, topy + y, width, height, color)
pos += sz
self._doConnection()
# --- Hexile Encoding
def _doNextHextileSubrect(self, bg, color, x, y, width, height, tx, ty):
#~ print "_doNextHextileSubrect %r" % ((color, x, y, width, height, tx, ty), )
#coords of next tile
#its line after line of tiles
#finished when the last line is completly received
#dont inc the first time
if tx is not None:
#calc next subrect pos
tx += 16
if tx >= x + width:
tx = x
ty += 16
else:
tx = x
ty = y
#more tiles?
if ty >= y + height:
self._doConnection()
else:
self.expect(self._handleDecodeHextile, 1, bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextile(self, block, bg, color, x, y, width, height, tx, ty):
(subencoding,) = unpack("!B", block)
#calc tile size
tw = th = 16
if x + width - tx < 16: tw = x + width - tx
if y + height - ty < 16: th = y + height- ty
#decode tile
if subencoding & 1: #RAW
self.expect(self._handleDecodeHextileRAW, tw*th*self.bypp, bg, color, x, y, width, height, tx, ty, tw, th)
else:
numbytes = 0
if subencoding & 2: #BackgroundSpecified
numbytes += self.bypp
if subencoding & 4: #ForegroundSpecified
numbytes += self.bypp
if subencoding & 8: #AnySubrects
numbytes += 1
if numbytes:
self.expect(self._handleDecodeHextileSubrect, numbytes, subencoding, bg, color, x, y, width, height, tx, ty, tw, th)
else:
self.fillRectangle(tx, ty, tw, th, bg)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrect(self, block, subencoding, bg, color, x, y, width, height, tx, ty, tw, th):
subrects = 0
pos = 0
if subencoding & 2: #BackgroundSpecified
bg = block[:self.bypp]
pos += self.bypp
self.fillRectangle(tx, ty, tw, th, bg)
if subencoding & 4: #ForegroundSpecified
color = block[pos:pos+self.bypp]
pos += self.bypp
if subencoding & 8: #AnySubrects
#~ (subrects, ) = unpack("!B", block)
subrects = ord(block[pos])
#~ print subrects
if subrects:
if subencoding & 16: #SubrectsColoured
self.expect(self._handleDecodeHextileSubrectsColoured, (self.bypp + 2)*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self.expect(self._handleDecodeHextileSubrectsFG, 2*subrects, bg, color, subrects, x, y, width, height, tx, ty, tw, th)
else:
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileRAW(self, block, bg, color, x, y, width, height, tx, ty, tw, th):
"""the tile is in raw encoding"""
self.updateRectangle(tx, ty, tw, th, block)
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""subrects with their own color"""
sz = self.bypp + 2
pos = 0
end = len(block)
while pos < end:
pos2 = pos + self.bypp
color = block[pos:pos2]
xy = ord(block[pos2])
wh = ord(block[pos2+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += sz
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
def _handleDecodeHextileSubrectsFG(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th):
"""all subrect with same color"""
pos = 0
end = len(block)
while pos < end:
xy = ord(block[pos])
wh = ord(block[pos+1])
sx = xy >> 4
sy = xy & 0xf
sw = (wh >> 4) + 1
sh = (wh & 0xf) + 1
self.fillRectangle(tx + sx, ty + sy, sw, sh, color)
pos += 2
self._doNextHextileSubrect(bg, color, x, y, width, height, tx, ty)
# --- ZRLE Encoding
def _handleDecodeZRLE(self, block):
raise NotImplementedError
# --- Pseudo Cursor Encoding
def _handleDecodePsuedoCursor(self, block, x, y, width, height):
split = width * height * self.bypp
image = block[:split]
mask = block[split:]
self.updateCursor(x, y, width, height, image, mask)
self._doConnection()
# --- Pseudo Desktop Size Encoding
def _handleDecodeDesktopSize(self, width, height):
self.updateDesktopSize(width, height)
self._doConnection()
# --- other server messages
def _handleServerCutText(self, block):
(length, ) = unpack("!xxxI", block)
self.expect(self._handleServerCutTextValue, length)
def _handleServerCutTextValue(self, block):
self.copy_text(block)
self.expect(self._handleConnection, 1)
#------------------------------------------------------
# incomming data redirector
#------------------------------------------------------
def dataReceived(self, data):
#~ sys.stdout.write(repr(data) + '\n')
#~ print len(data), ", ", len(self._packet)
self._packet.append(data)
self._packet_len += len(data)
self._handler()
def _handleExpected(self):
if self._packet_len >= self._expected_len:
buffer = b''.join(self._packet)
while len(buffer) >= self._expected_len:
self._already_expecting = 1
block, buffer = buffer[:self._expected_len], buffer[self._expected_len:]
#~ log.msg("handle %r with %r\n" % (block, self._expected_handler.__name__))
self._expected_handler(block, *self._expected_args, **self._expected_kwargs)
self._packet[:] = [buffer]
self._packet_len = len(buffer)
self._already_expecting = 0
def expect(self, handler, size, *args, **kwargs):
#~ log.msg("expect(%r, %r, %r, %r)\n" % (handler.__name__, size, args, kwargs))
self._expected_handler = handler
self._expected_len = size
self._expected_args = args
self._expected_kwargs = kwargs
if not self._already_expecting:
self._handleExpected() #just in case that there is already enough data
#------------------------------------------------------
# client -> server messages
#------------------------------------------------------
def setPixelFormat(self, bpp=32, depth=24, bigendian=0, truecolor=1, redmax=255, greenmax=255, bluemax=255, redshift=0, greenshift=8, blueshift=16):
pixformat = pack("!BBBBHHHBBBxxx", bpp, depth, bigendian, truecolor, redmax, greenmax, bluemax, redshift, greenshift, blueshift)
self.transport.write(pack("!Bxxx16s", 0, pixformat))
#rember these settings
self.bpp, self.depth, self.bigendian, self.truecolor = bpp, depth, bigendian, truecolor
self.redmax, self.greenmax, self.bluemax = redmax, greenmax, bluemax
self.redshift, self.greenshift, self.blueshift = redshift, greenshift, blueshift
self.bypp = self.bpp // 8 #calc bytes per pixel
#~ print self.bypp
def setEncodings(self, list_of_encodings):
self.transport.write(pack("!BxH", 2, len(list_of_encodings)))
for encoding in list_of_encodings:
self.transport.write(pack("!i", encoding))
def framebufferUpdateRequest(self, x=0, y=0, width=None, height=None, incremental=0):
if width is None: width = self.width - x
if height is None: height = self.height - y
self.transport.write(pack("!BBHHHH", 3, incremental, x, y, width, height))
def keyEvent(self, key, down=1):
"""For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants."""
self.transport.write(pack("!BBxxI", 4, down, key))
def pointerEvent(self, x, y, buttonmask=0):
"""Indicates either pointer movement or a pointer button press or release. The pointer is
now at (x-position, y-position), and the current state of buttons 1 to 8 are represented
by bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning down (pressed).
"""
self.transport.write(pack("!BBHH", 5, buttonmask, x, y))
def clientCutText(self, message):
"""The client has new ASCII text in its cut buffer.
(aka clipboard)
"""
self.transport.write(pack("!BxxxI", 6, len(message)) + message)
#------------------------------------------------------
# callbacks
# override these in your application
#------------------------------------------------------
def vncConnectionMade(self):
"""connection is initialized and ready.
typicaly, the pixel format is set here."""
def vncRequestPassword(self):
"""a password is needed to log on, use sendPassword() to
send one."""
if self.factory.password is None:
log.msg("need a password")
self.transport.loseConnection()
return
self.sendPassword(self.factory.password)
def vncAuthFailed(self, reason):
"""called when the authentication failed.
the connection is closed."""
log.msg("Cannot connect %s" % reason)
def beginUpdate(self):
"""called before a series of updateRectangle(),
copyRectangle() or fillRectangle()."""
def commitUpdate(self, rectangles=None):
"""called after a series of updateRectangle(), copyRectangle()
or fillRectangle() are finished.
typicaly, here is the place to request the next screen
update with FramebufferUpdateRequest(incremental=1).
argument is a list of tuples (x,y,w,h) with the updated
rectangles."""
def updateRectangle(self, x, y, width, height, data):
"""new bitmap data. data is a string in the pixel format set
up earlier."""
def copyRectangle(self, srcx, srcy, x, y, width, height):
"""used for copyrect encoding. copy the given rectangle
(src, srxy, width, height) to the target coords (x,y)"""
def updateCursor(self, x, y, width, height, image, mask):
""" New cursor, focuses at (x, y)
"""
def updateDesktopSize(width, height):
""" New desktop size of width*height. """
def bell(self):
"""bell"""
def copy_text(self, text):
"""The server has new ASCII text in its cut buffer.
(aka clipboard)"""
|
sibson/vncdotool | vncdotool/rfb.py | RFBDes.setKey | python | def setKey(self, key):
newkey = []
for ki in range(len(key)):
bsrc = ord(key[ki])
btgt = 0
for i in range(8):
if bsrc & (1 << i):
btgt = btgt | (1 << 7-i)
newkey.append(chr(btgt))
super(RFBDes, self).setKey(newkey) | RFB protocol for authentication requires client to encrypt
challenge sent by server with password using DES method. However,
bits in each byte of the password are put in reverse order before
using it as encryption key. | train | https://github.com/sibson/vncdotool/blob/e133a8916efaa0f5ed421e0aa737196624635b0c/vncdotool/rfb.py#L667-L680 | [
"def setKey(self, key):\n\t\"\"\"Will set the crypting key for this object. Must be 8 bytes.\"\"\"\n\t_baseDes.setKey(self, key)\n\tself.__create_sub_keys()\n"
] | class RFBDes(pyDes.des):
|
ladybug-tools/uwg | uwg/solarcalcs.py | SolarCalcs.solarcalcs | python | def solarcalcs(self):
self.dir = self.forc.dir # Direct sunlight (perpendicular to the sun's ray)
self.dif = self.forc.dif # Diffuse sunlight
if self.dir + self.dif > 0.:
self.logger.debug("{} Solar radiation > 0".format(__name__))
# calculate zenith tangent, and critOrient solar angles
self.solarangles()
self.horSol = max(math.cos(self.zenith)*self.dir, 0.0) # Direct horizontal radiation
# Fractional terms for wall & road
self.Kw_term = min(abs(1./self.UCM.canAspect*(0.5-self.critOrient/math.pi) \
+ 1/math.pi*self.tanzen*(1-math.cos(self.critOrient))),1.)
self.Kr_term = min(abs(2.*self.critOrient/math.pi \
- (2/math.pi*self.UCM.canAspect*self.tanzen)*(1-math.cos(self.critOrient))), 1-2*self.UCM.canAspect*self.Kw_term)
# Direct and diffuse solar radiation
self.bldSol = self.horSol*self.Kw_term + self.UCM.wallConf*self.dif # Assume trees are shorter than buildings
self.roadSol = self.horSol*self.Kr_term + self.UCM.roadConf*self.dif
# Solar reflections. Add diffuse radiation from vegetation to alb_road if in season
if self.simTime.month < self.parameter.vegStart or self.simTime.month > self.parameter.vegEnd:
alb_road = self.UCM.road.albedo
else:
alb_road = self.UCM.road.albedo*(1.-self.UCM.road.vegCoverage) + self.parameter.vegAlbedo*self.UCM.road.vegCoverage
# First set of reflections
rr = alb_road * self.roadSol
rw = self.UCM.alb_wall * self.bldSol
# bounces
fr = (1. - (1. - 2.*self.UCM.wallConf) * self.UCM.alb_wall + (1. - self.UCM.roadConf) \
* self.UCM.wallConf * alb_road * self.UCM.alb_wall)
# (1.0-self.UCM.roadConf) road to wall view
self.mr = (rr + (1.0-self.UCM.roadConf) * alb_road * (rw + self.UCM.wallConf * self.UCM.alb_wall * rr)) / fr
self.mw = (rw + self.UCM.wallConf * self.UCM.alb_wall * rr) / fr
# Receiving solar, including bounces (W m-2)
self.UCM.road.solRec = self.roadSol + (1 - self.UCM.roadConf)*self.mw
for j in range(len(self.BEM)):
self.BEM[j].roof.solRec = self.horSol + self.dif
self.BEM[j].wall.solRec = self.bldSol + (1 - 2*self.UCM.wallConf) * self.mw + self.UCM.wallConf * self.mr
self.rural.solRec = self.horSol + self.dif # Solar received by rural
self.UCM.SolRecRoof = self.horSol + self.dif # Solar received by roof
self.UCM.SolRecRoad = self.UCM.road.solRec # Solar received by road
self.UCM.SolRecWall = self.bldSol+(1-2*self.UCM.wallConf)*self.UCM.road.albedo*self.roadSol # Solar received by wall
# Vegetation heat (per m^2 of veg)
self.UCM.treeSensHeat = (1-self.parameter.vegAlbedo)*(1-self.parameter.treeFLat)*self.UCM.SolRecRoad
self.UCM.treeLatHeat = (1-self.parameter.vegAlbedo)*self.parameter.treeFLat*self.UCM.SolRecRoad
else: # No Sun
self.logger.debug("{} Solar radiation = 0".format(__name__))
self.UCM.road.solRec = 0.
self.rural.solRec = 0.
for j in range(len(self.BEM)):
self.BEM[j].roof.solRec = 0.
self.BEM[j].wall.solRec = 0.
self.UCM.SolRecRoad = 0. # Solar received by road
self.UCM.SolRecRoof = 0. # Solar received by roof
self.UCM.SolRecWall = 0. # Solar received by wall
self.UCM.treeSensHeat = 0.
self.UCM.treeLatHeat = 0.
return self.rural, self.UCM, self.BEM | Solar Calculation
Mutates RSM, BEM, and UCM objects based on following parameters:
UCM # Urban Canopy - Building Energy Model object
BEM # Building Energy Model object
simTime # Simulation time bbject
RSM # Rural Site & Vertical Diffusion Model Object
forc # Forcing object
parameter # Geo Param Object
rural # Rural road Element object
Properties
self.dir # Direct sunlight
self.dif # Diffuse sunlight
self.tanzen
self.critOrient
self.horSol
self.Kw_term
self.Kr_term
self.mr
self.mw | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/solarcalcs.py#L43-L140 | null | class SolarCalcs(object):
"""
SolarCalcs
args:
UCM # Urban Canopy - Building Energy Model object
BEM # Building Energy Model object
simTime # Simulation time bbject
RSM # Rural Site & Vertical Diffusion Model Object
forc # Forcing object
parameter # Geo Param Object
rural # Rural road Element object
returns:
rural
UCM
BEM
"""
def __init__(self,UCM,BEM,simTime,RSM,forc,parameter,rural):
""" init solar calc inputs """
self.UCM = UCM
self.BEM = BEM
self.simTime = simTime
self.RSM = RSM
self.forc = forc
self.parameter = parameter
self.rural = rural
# Logger will be disabled by default unless explicitly called in tests
self.logger = logging.getLogger(__name__)
def solarangles (self):
"""
Calculation based on NOAA. Solves for zenith angle, tangent of zenithal angle,
and critical canyon angle based on following parameters:
canAspect # aspect Ratio of canyon
simTime # simulation parameters
RSM.lon # longitude (deg)
RSM.lat # latitude (deg)
RSM.GMT # GMT hour correction
Properties
self.ut # elapsed hours on current day
self.ad # fractional year in radians
self.eqtime
self.decsol # solar declination angle
self.zenith # Angle between normal to earth's surface and sun position
self.tanzen # tangente of solar zenithal angle
self.critOrient # critical canyon angle for which solar radiation reaches the road
"""
ln = self.RSM.lon
month = self.simTime.month
day = self.simTime.day
secDay = self.simTime.secDay # Total elapsed seconds in simulation
inobis = self.simTime.inobis # total days for first of month
# i.e [0,31,59,90,120,151,181,212,243,273,304,334]
canAspect = self.UCM.canAspect
lon = self.RSM.lon
lat = self.RSM.lat
GMT = self.RSM.GMT
self.ut = (24. + (int(secDay)/3600.%24.)) % 24. # Get elapsed hours on current day
ibis = list(range(len(inobis)))
for JI in range(1, 12):
ibis[JI] = inobis[JI]+1
date = day + inobis[month-1]-1 # Julian day of the year
# divide circle by 365 days, multiply by elapsed days + hours
self.ad = 2.0 * math.pi/365. * (date-1 + (self.ut-(12/24.))) # Fractional year (radians)
self.eqtime = 229.18 * (0.000075+0.001868*math.cos(self.ad)-0.032077*math.sin(self.ad) - \
0.01461*math.cos(2*self.ad)-0.040849*math.sin(2*self.ad))
# Declination angle (angle of sun with equatorial plane)
self.decsol = 0.006918-0.399912*math.cos(self.ad)+0.070257*math.sin(self.ad) \
-0.006758*math.cos(2.*self.ad)+0.000907*math.sin(2.*self.ad) \
-0.002697*math.cos(3.*self.ad)+0.00148 *math.sin(3.*self.ad)
time_offset = self.eqtime - 4. * lon + 60 * GMT
tst = secDay + time_offset * 60
ha = (tst/4./60.-180.) * math.pi/180.
zlat = lat * (math.pi/180.) # change angle units to radians
# Calculate zenith solar angle
self.zenith = math.acos(math.sin(zlat)*math.sin(self.decsol) + math.cos(zlat)*math.cos(self.decsol)*math.cos(ha))
# tangente of solar zenithal angle
if abs(0.5*math.pi - self.zenith) < 1e-6:
if 0.5*math.pi - self.zenith > 0.:
self.tanzen = math.tan(0.5*math.pi-1e-6)
elif 0.5*math.pi - self.zenith <= 0.:
self.tanzen = math.tan(0.5*math.pi+1e-6)
elif abs(self.zenith) < 1e-6:
# lim x->0 tan(x) -> 0 which results in division by zero error
# when calculating the critical canyon angle
# so set tanzen to 1e-6 which will result in critical canyon angle = 90
self.tanzen = 1e-6
else:
self.tanzen = math.tan(self.zenith)
# critical canyon angle for which solar radiation reaches the road
# has to do with street canyon orientation for given solar angle
self.critOrient = math.asin(min(abs( 1./self.tanzen)/canAspect, 1. ))
|
ladybug-tools/uwg | uwg/solarcalcs.py | SolarCalcs.solarangles | python | def solarangles (self):
ln = self.RSM.lon
month = self.simTime.month
day = self.simTime.day
secDay = self.simTime.secDay # Total elapsed seconds in simulation
inobis = self.simTime.inobis # total days for first of month
# i.e [0,31,59,90,120,151,181,212,243,273,304,334]
canAspect = self.UCM.canAspect
lon = self.RSM.lon
lat = self.RSM.lat
GMT = self.RSM.GMT
self.ut = (24. + (int(secDay)/3600.%24.)) % 24. # Get elapsed hours on current day
ibis = list(range(len(inobis)))
for JI in range(1, 12):
ibis[JI] = inobis[JI]+1
date = day + inobis[month-1]-1 # Julian day of the year
# divide circle by 365 days, multiply by elapsed days + hours
self.ad = 2.0 * math.pi/365. * (date-1 + (self.ut-(12/24.))) # Fractional year (radians)
self.eqtime = 229.18 * (0.000075+0.001868*math.cos(self.ad)-0.032077*math.sin(self.ad) - \
0.01461*math.cos(2*self.ad)-0.040849*math.sin(2*self.ad))
# Declination angle (angle of sun with equatorial plane)
self.decsol = 0.006918-0.399912*math.cos(self.ad)+0.070257*math.sin(self.ad) \
-0.006758*math.cos(2.*self.ad)+0.000907*math.sin(2.*self.ad) \
-0.002697*math.cos(3.*self.ad)+0.00148 *math.sin(3.*self.ad)
time_offset = self.eqtime - 4. * lon + 60 * GMT
tst = secDay + time_offset * 60
ha = (tst/4./60.-180.) * math.pi/180.
zlat = lat * (math.pi/180.) # change angle units to radians
# Calculate zenith solar angle
self.zenith = math.acos(math.sin(zlat)*math.sin(self.decsol) + math.cos(zlat)*math.cos(self.decsol)*math.cos(ha))
# tangente of solar zenithal angle
if abs(0.5*math.pi - self.zenith) < 1e-6:
if 0.5*math.pi - self.zenith > 0.:
self.tanzen = math.tan(0.5*math.pi-1e-6)
elif 0.5*math.pi - self.zenith <= 0.:
self.tanzen = math.tan(0.5*math.pi+1e-6)
elif abs(self.zenith) < 1e-6:
# lim x->0 tan(x) -> 0 which results in division by zero error
# when calculating the critical canyon angle
# so set tanzen to 1e-6 which will result in critical canyon angle = 90
self.tanzen = 1e-6
else:
self.tanzen = math.tan(self.zenith)
# critical canyon angle for which solar radiation reaches the road
# has to do with street canyon orientation for given solar angle
self.critOrient = math.asin(min(abs( 1./self.tanzen)/canAspect, 1. )) | Calculation based on NOAA. Solves for zenith angle, tangent of zenithal angle,
and critical canyon angle based on following parameters:
canAspect # aspect Ratio of canyon
simTime # simulation parameters
RSM.lon # longitude (deg)
RSM.lat # latitude (deg)
RSM.GMT # GMT hour correction
Properties
self.ut # elapsed hours on current day
self.ad # fractional year in radians
self.eqtime
self.decsol # solar declination angle
self.zenith # Angle between normal to earth's surface and sun position
self.tanzen # tangente of solar zenithal angle
self.critOrient # critical canyon angle for which solar radiation reaches the road | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/solarcalcs.py#L142-L220 | null | class SolarCalcs(object):
"""
SolarCalcs
args:
UCM # Urban Canopy - Building Energy Model object
BEM # Building Energy Model object
simTime # Simulation time bbject
RSM # Rural Site & Vertical Diffusion Model Object
forc # Forcing object
parameter # Geo Param Object
rural # Rural road Element object
returns:
rural
UCM
BEM
"""
def __init__(self,UCM,BEM,simTime,RSM,forc,parameter,rural):
""" init solar calc inputs """
self.UCM = UCM
self.BEM = BEM
self.simTime = simTime
self.RSM = RSM
self.forc = forc
self.parameter = parameter
self.rural = rural
# Logger will be disabled by default unless explicitly called in tests
self.logger = logging.getLogger(__name__)
def solarcalcs(self):
""" Solar Calculation
Mutates RSM, BEM, and UCM objects based on following parameters:
UCM # Urban Canopy - Building Energy Model object
BEM # Building Energy Model object
simTime # Simulation time bbject
RSM # Rural Site & Vertical Diffusion Model Object
forc # Forcing object
parameter # Geo Param Object
rural # Rural road Element object
Properties
self.dir # Direct sunlight
self.dif # Diffuse sunlight
self.tanzen
self.critOrient
self.horSol
self.Kw_term
self.Kr_term
self.mr
self.mw
"""
self.dir = self.forc.dir # Direct sunlight (perpendicular to the sun's ray)
self.dif = self.forc.dif # Diffuse sunlight
if self.dir + self.dif > 0.:
self.logger.debug("{} Solar radiation > 0".format(__name__))
# calculate zenith tangent, and critOrient solar angles
self.solarangles()
self.horSol = max(math.cos(self.zenith)*self.dir, 0.0) # Direct horizontal radiation
# Fractional terms for wall & road
self.Kw_term = min(abs(1./self.UCM.canAspect*(0.5-self.critOrient/math.pi) \
+ 1/math.pi*self.tanzen*(1-math.cos(self.critOrient))),1.)
self.Kr_term = min(abs(2.*self.critOrient/math.pi \
- (2/math.pi*self.UCM.canAspect*self.tanzen)*(1-math.cos(self.critOrient))), 1-2*self.UCM.canAspect*self.Kw_term)
# Direct and diffuse solar radiation
self.bldSol = self.horSol*self.Kw_term + self.UCM.wallConf*self.dif # Assume trees are shorter than buildings
self.roadSol = self.horSol*self.Kr_term + self.UCM.roadConf*self.dif
# Solar reflections. Add diffuse radiation from vegetation to alb_road if in season
if self.simTime.month < self.parameter.vegStart or self.simTime.month > self.parameter.vegEnd:
alb_road = self.UCM.road.albedo
else:
alb_road = self.UCM.road.albedo*(1.-self.UCM.road.vegCoverage) + self.parameter.vegAlbedo*self.UCM.road.vegCoverage
# First set of reflections
rr = alb_road * self.roadSol
rw = self.UCM.alb_wall * self.bldSol
# bounces
fr = (1. - (1. - 2.*self.UCM.wallConf) * self.UCM.alb_wall + (1. - self.UCM.roadConf) \
* self.UCM.wallConf * alb_road * self.UCM.alb_wall)
# (1.0-self.UCM.roadConf) road to wall view
self.mr = (rr + (1.0-self.UCM.roadConf) * alb_road * (rw + self.UCM.wallConf * self.UCM.alb_wall * rr)) / fr
self.mw = (rw + self.UCM.wallConf * self.UCM.alb_wall * rr) / fr
# Receiving solar, including bounces (W m-2)
self.UCM.road.solRec = self.roadSol + (1 - self.UCM.roadConf)*self.mw
for j in range(len(self.BEM)):
self.BEM[j].roof.solRec = self.horSol + self.dif
self.BEM[j].wall.solRec = self.bldSol + (1 - 2*self.UCM.wallConf) * self.mw + self.UCM.wallConf * self.mr
self.rural.solRec = self.horSol + self.dif # Solar received by rural
self.UCM.SolRecRoof = self.horSol + self.dif # Solar received by roof
self.UCM.SolRecRoad = self.UCM.road.solRec # Solar received by road
self.UCM.SolRecWall = self.bldSol+(1-2*self.UCM.wallConf)*self.UCM.road.albedo*self.roadSol # Solar received by wall
# Vegetation heat (per m^2 of veg)
self.UCM.treeSensHeat = (1-self.parameter.vegAlbedo)*(1-self.parameter.treeFLat)*self.UCM.SolRecRoad
self.UCM.treeLatHeat = (1-self.parameter.vegAlbedo)*self.parameter.treeFLat*self.UCM.SolRecRoad
else: # No Sun
self.logger.debug("{} Solar radiation = 0".format(__name__))
self.UCM.road.solRec = 0.
self.rural.solRec = 0.
for j in range(len(self.BEM)):
self.BEM[j].roof.solRec = 0.
self.BEM[j].wall.solRec = 0.
self.UCM.SolRecRoad = 0. # Solar received by road
self.UCM.SolRecRoof = 0. # Solar received by roof
self.UCM.SolRecWall = 0. # Solar received by wall
self.UCM.treeSensHeat = 0.
self.UCM.treeLatHeat = 0.
return self.rural, self.UCM, self.BEM
|
ladybug-tools/uwg | uwg/psychrometrics.py | psychrometrics | python | def psychrometrics (Tdb_in, w_in, P):
# Change units
c_air = 1006. # [J/kg] air heat capacity, value from ASHRAE Fundamentals
hlg = 2501000. # [J/kg] latent heat, value from ASHRAE Fundamentals
cw = 1860. # [J/kg] value from ASHRAE Fundamentals
P = P/1000. # convert from Pa to kPa
Tdb = Tdb_in - 273.15
w = w_in
# phi (RH) calculation from Tdb and w
Pw = (w*P)/(0.621945 + w) # partial pressure of water vapor
Pws = saturation_pressure(Tdb) # Get saturation pressure for given Tdb
phi = Pw/Pws*100.0
# enthalpy calculation from Tdb and w
h = c_air*Tdb + w*(hlg+cw*Tdb) # [J kga-1]
# specific volume calculation from Tdb and w
v = 0.287042 * (Tdb+273.15)*(1+1.607858*w)/P # ?
# dew point calculation from w
_pw = (w*P)/(0.621945 + w) # water vapor partial pressure in kPa
alpha = log(_pw)
Tdp = 6.54 + 14.526*alpha + pow(alpha,2)*0.7389 + pow(alpha,3)*0.09486 + pow(_pw,0.1984)*0.4569 # valid for Tdp between 0 C and 93 C
return Tdb, w, phi, h, Tdp, v | Modified version of Psychometrics by Tea Zakula
MIT Building Technology Lab
Input: Tdb_in, w_in, P
Output: Tdb, w, phi, h, Tdp, v
where:
Tdb_in = [K] dry bulb temperature
w_in = [kgv/kgda] Humidity Ratio
P = [P] Atmospheric Station Pressure
Tdb: [C] dry bulb temperature
w: [kgv/kgda] Humidity Ratio
phi: [Pw/Pws*100] relative humidity
Tdp: [C] dew point temperature
h: [J/kga] enthalpy
v: [m3/kga] specific volume | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/psychrometrics.py#L6-L51 | [
"def saturation_pressure(Tdb_):\n T = Tdb_ + 273.15\n\n # N.B In Matlab, negative values are converted to complex values.\n # log(-x) = log(x) + log(-1) = log(x) + i*pi\n # Python will throw an exception. Negative value occurs here if\n # simulation timestep (dtSim) is large, i.e 3600s.\n _Pws = exp(-1*(5.8002206e3) / T+1.3914993 + (4.8640239e-2)*T*(-1.) + (4.1764768e-5)*pow(T,2) - (1.4452093e-8)*pow(T,3) + 6.5459673*log(T)) #in Pa\n _Pws = _Pws/1000. # in kPa\n return _Pws\n"
] | from __future__ import division
from math import log, pow, exp
def saturation_pressure(Tdb_):
T = Tdb_ + 273.15
# N.B In Matlab, negative values are converted to complex values.
# log(-x) = log(x) + log(-1) = log(x) + i*pi
# Python will throw an exception. Negative value occurs here if
# simulation timestep (dtSim) is large, i.e 3600s.
_Pws = exp(-1*(5.8002206e3) / T+1.3914993 + (4.8640239e-2)*T*(-1.) + (4.1764768e-5)*pow(T,2) - (1.4452093e-8)*pow(T,3) + 6.5459673*log(T)) #in Pa
_Pws = _Pws/1000. # in kPa
return _Pws
def moist_air_density(P,Tdb,H):
# Moist air density [kgv/ m-3] given dry bulb temperature, humidity ratio, and pressure.
# ASHRAE Fundamentals (2005) ch. 6 eqn. 28
# ASHRAE Fundamentals (2009) ch. 1 eqn. 28
# from: https://github.com/psychrometrics/Libraries/blob/master/Psychrometrics_SI.cpp
moist_air_density = P/(1000*0.287042*Tdb*(1.+1.607858*H))
return moist_air_density
def HumFromRHumTemp(RH,T,P):
# Derive Specific HUmidity [kgh20/kgn202] from RH, T and Pa
# Saturation vapour pressure from ASHRAE
C8 = -5.8002206e3
C9 = 1.3914993
C10 = -4.8640239e-2
C11 = 4.1764768e-5
C12 = -1.4452093e-8
C13 = 6.5459673
T += 273.15
PWS = exp(C8/T + C9 + C10*T + C11 * pow(T,2) + C12 * pow(T,3) + C13 * log(T))
PW = RH*PWS/100.0 # Vapour pressure
W = 0.62198*PW/(P-PW) # 4. Specific humidity
return W
"""
function psat = psat(temp,parameter)
gamw = (parameter.cl - parameter.cpv) / parameter.rv;
betaw = (parameter.lvtt/parameter.rv) + (gamw * parameter.tt);
alpw = log(parameter.estt) + (betaw /parameter.tt) + (gamw *log(parameter.tt));
psat = zeros(size(temp));
for jj=1:size(temp)
psat = exp(alpw - betaw/temp - gamw*log(temp));
end
end
% Not used for this release but saved for possible future use
function Twb = wet_bulb(Tdb,Tdp,pres)
% Copyright (c) 2015, Rolf Henry Goodwin
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
% Code modified to merge into a single file - Joseph Yang, 2016
% Tdb, Tdp, Twb in K
% p in Pa (obtained function uses hPa, so /100 needed)
global T;
global T_d;
global p;
T = Tdb;
T_d = Tdp;
p = pres/100;
Twb = root_finder(@Delta_q,T_d,T);
end
function dQTw = Delta_q(T_w)
%Delta_q finds the value of function dq(Tw)
%INPUT wet bulb temperature T_w
%OUTPUT dq(Tw)
global T;
global T_d;
global p;
Cp = 1005; % Heat capacity of water vapor in J/(kg*K)
L = 2.501e6; % Latent heat of water vapor at 0 degC in J/kg
w1 = mixing_ratio(T_d,p); % Mixing ratio corresponding to T_d and p
w2 = mixing_ratio(T_w,p); % Mixing ratio corresponding to T_w and p
dQTw = (L*(w2-w1))/(1+w2)-Cp*(T-T_w)*(1+0.8*w2); % Finds deltaq(Tw)
end
"""
|
ladybug-tools/uwg | uwg/utilities.py | str2fl | python | def str2fl(x):
def helper_to_fl(s_):
""" deals with odd string imports converts to float"""
if s_ == "":
return "null"
elif "," in s_:
s_ = s_.replace(",", "")
try:
return float(s_)
except:
return (s_)
fl_lst = []
if isinstance(x[0], str): # Check if list of strings, then sent to conversion
for xi in range(len(x)):
fl_lst.append(helper_to_fl(x[xi]))
elif isinstance(x[0], list): # Check if list of lists, then recurse
for xi in range(len(x)):
fl_lst.append(str2fl(x[xi]))
else:
return False
return fl_lst | Recurses through lists and converts lists of string to float
Args:
x: string or list of strings | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/utilities.py#L42-L70 | [
"def str2fl(x):\n \"\"\"Recurses through lists and converts lists of string to float\n\n Args:\n x: string or list of strings\n \"\"\"\n def helper_to_fl(s_):\n \"\"\" deals with odd string imports converts to float\"\"\"\n if s_ == \"\":\n return \"null\"\n elif \",\" in s_:\n s_ = s_.replace(\",\", \"\")\n\n try:\n return float(s_)\n except:\n return (s_)\n\n fl_lst = []\n if isinstance(x[0], str): # Check if list of strings, then sent to conversion\n for xi in range(len(x)):\n fl_lst.append(helper_to_fl(x[xi]))\n elif isinstance(x[0], list): # Check if list of lists, then recurse\n for xi in range(len(x)):\n fl_lst.append(str2fl(x[xi]))\n else:\n return False\n\n return fl_lst\n",
"def helper_to_fl(s_):\n \"\"\" deals with odd string imports converts to float\"\"\"\n if s_ == \"\":\n return \"null\"\n elif \",\" in s_:\n s_ = s_.replace(\",\", \"\")\n\n try:\n return float(s_)\n except:\n return (s_)\n"
] | """Collection of useful methods."""
import os
from csv import reader as csv_reader
import sys
try:
range = xrange
except NameError:
pass
def zeros(h, w):
"""create a (h x w) matrix of zeros.
Args:
h: Height of the matrix.
w: Width of the matrix.
"""
return [[0 for x in range(w)] for y in range(h)]
def read_csv(file_name_):
# open csv file and read
if os.path.exists(file_name_):
if sys.version_info[0] >= 3:
file_ = open(file_name_, "r", errors='ignore')
else:
file_ = open(file_name_, "r")
gen_ = csv_reader(file_, delimiter=",")
L = [r for r in gen_]
file_.close()
return L
else:
raise Exception("File name: '{}' does not exist.".format(file_name_))
def is_near_zero(num, eps=1e-10):
return abs(num) < eps
|
ladybug-tools/uwg | uwg/uwg.py | procMat | python | def procMat(materials, max_thickness, min_thickness):
""" Processes material layer so that a material with single
layer thickness is divided into two and material layer that is too
thick is subdivided
"""
newmat = []
newthickness = []
k = materials.layerThermalCond
Vhc = materials.layerVolHeat
if len(materials.layerThickness) > 1:
for j in range(len(materials.layerThickness)):
# Break up each layer that's more than max thickness (0.05m)
if materials.layerThickness[j] > max_thickness:
nlayers = math.ceil(materials.layerThickness[j]/float(max_thickness))
for i in range(int(nlayers)):
newmat.append(Material(k[j], Vhc[j], name=materials._name))
newthickness.append(materials.layerThickness[j]/float(nlayers))
# Material that's less then min_thickness is not added.
elif materials.layerThickness[j] < min_thickness:
print("WARNING: Material '{}' layer found too thin (<{:.2f}cm), ignored.").format(
materials._name, min_thickness*100)
else:
newmat.append(Material(k[j], Vhc[j], name=materials._name))
newthickness.append(materials.layerThickness[j])
else:
# Divide single layer into two (uwg assumes at least 2 layers)
if materials.layerThickness[0] > max_thickness:
nlayers = math.ceil(materials.layerThickness[0]/float(max_thickness))
for i in range(int(nlayers)):
newmat.append(Material(k[0], Vhc[0], name=materials._name))
newthickness.append(materials.layerThickness[0]/float(nlayers))
# Material should be at least 1cm thick, so if we're here,
# should give warning and stop. Only warning given for now.
elif materials.layerThickness[0] < min_thickness*2:
newthickness = [min_thickness/2., min_thickness/2.]
newmat = [Material(k[0], Vhc[0], name=materials._name),
Material(k[0], Vhc[0], name=materials._name)]
print("WARNING: a thin (<2cm) single material '{}' layer found. May cause error.".format(
materials._name))
else:
newthickness = [materials.layerThickness[0]/2., materials.layerThickness[0]/2.]
newmat = [Material(k[0], Vhc[0], name=materials._name),
Material(k[0], Vhc[0], name=materials._name)]
return newmat, newthickness | Processes material layer so that a material with single
layer thickness is divided into two and material layer that is too
thick is subdivided | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/uwg.py#L977-L1024 | null | """
=========================================================================
THE URBAN WEATHER GENERATOR (uwg)
=========================================================================
Version 4.2
Original Author: B. Bueno
Edited by A. Nakano & Lingfu Zhang
Modified by Joseph Yang (joeyang@mit.edu) - May, 2016
Translated to Python by Saeran Vasanthakumar - February, 2018
Original Pulbication on the uwg's Methods:
Bueno, Bruno; Norford, Leslie; Hidalgo, Julia; Pigeon, Gregoire (2013).
The urban weather generator, Journal of Building Performance Simulation. 6:4,269-281.
doi: 10.1080/19401493.2012.718797
=========================================================================
"""
from __future__ import division, print_function
from functools import reduce
try:
range = xrange
except NameError:
pass
import os
import math
import copy
import logging
try:
import cPickle as pickle
except ImportError:
import pickle
from .simparam import SimParam
from .weather import Weather
from .building import Building
from .material import Material
from .element import Element
from .BEMDef import BEMDef
from .schdef import SchDef
from .param import Param
from .UCMDef import UCMDef
from .forcing import Forcing
from .UBLDef import UBLDef
from .RSMDef import RSMDef
from .solarcalcs import SolarCalcs
from .psychrometrics import psychrometrics
from .readDOE import readDOE
from .urbflux import urbflux
from . import utilities
# For debugging only
#from pprint import pprint
#from decimal import Decimal
#pp = pprint
#dd = Decimal.from_float
class uwg(object):
"""Morph a rural EPW file to urban conditions using a file with a list of urban parameters.
args:
epwDir: The directory in which the rural EPW file sits.
epwFileName: The name of the rural epw file that will be morphed.
uwgParamDir: The directory in which the uwg Parameter File (.uwg) sits.
uwgParamFileName: The name of the uwg Parameter File (.uwg).
destinationDir: Optional destination directory for the morphed EPW file.
If left blank, the morphed file will be written into the same directory
as the rural EPW file (the epwDir).
destinationFileName: Optional destination file name for the morphed EPW file.
If left blank, the morphed file will append "_UWG" to the original file name.
returns:
newClimateFile: the path to a new EPW file that has been morphed to account
for uban conditions.
"""
""" Section 1 - Definitions for constants / other parameters """
MINTHICKNESS = 0.01 # Minimum layer thickness (to prevent crashing) (m)
MAXTHICKNESS = 0.05 # Maximum layer thickness (m)
# http://web.mit.edu/parmstr/Public/NRCan/nrcc29118.pdf (Figly & Snodgrass)
SOILTCOND = 1
# http://www.europment.org/library/2013/venice/bypaper/MFHEEF/MFHEEF-21.pdf (average taken from Table 1)
SOILVOLHEAT = 2e6
# Soil material used for soil-depth padding
SOIL = Material(SOILTCOND, SOILVOLHEAT, name="soil")
# Physical constants
G = 9.81 # gravity (m s-2)
CP = 1004. # heat capacity for air (J/kg K)
VK = 0.40 # von karman constant (dimensionless)
R = 287. # gas constant dry air (J/kg K)
RV = 461.5 # gas constant water vapor (J/kg K)
LV = 2.26e6 # latent heat of evaporation (J/kg)
SIGMA = 5.67e-08 # Stefan Boltzmann constant (W m-2 K-4)
WATERDENS = 1000. # water density (kg m-3)
LVTT = 2.5008e6 #
TT = 273.16 #
ESTT = 611.14 #
CL = 4.218e3 #
CPV = 1846.1 #
B = 9.4 # Coefficients derived by Louis (1979)
CM = 7.4 #
# (Pr/Sc)^(2/3) for Colburn analogy in water evaporation
COLBURN = math.pow((0.713/0.621), (2/3.))
# Site-specific parameters
WGMAX = 0.005 # maximum film water depth on horizontal surfaces (m)
# File path parameter
RESOURCE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "resources"))
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
def __init__(self, epwFileName, uwgParamFileName=None, epwDir=None, uwgParamDir=None, destinationDir=None, destinationFileName=None):
# Logger will be disabled by default unless explicitly called in tests
self.logger = logging.getLogger(__name__)
# User defined
self.epwFileName = epwFileName if epwFileName.lower().endswith('.epw') else epwFileName + \
'.epw' # Revise epw file name if not end with epw
# If file name is entered then will uwg will set input from .uwg file
self.uwgParamFileName = uwgParamFileName
# If user does not overload
self.destinationFileName = destinationFileName if destinationFileName else self.epwFileName.strip(
'.epw') + '_UWG.epw'
self.epwDir = epwDir if epwDir else os.path.join(self.RESOURCE_PATH, "epw")
self.uwgParamDir = uwgParamDir if uwgParamDir else os.path.join(
self.RESOURCE_PATH, "parameters")
self.destinationDir = destinationDir if destinationDir else os.path.join(
self.RESOURCE_PATH, "epw_uwg")
# refdata: Serialized DOE reference data, z_meso height data
self.readDOE_file_path = os.path.join(self.CURRENT_PATH, "refdata", "readDOE.pkl")
self.z_meso_dir_path = os.path.join(self.CURRENT_PATH, "refdata")
# EPW precision
self.epw_precision = 1
# init uwg variables
self._init_param_dict = None
# Define Simulation and Weather parameters
self.Month = None # starting month (1-12)
self.Day = None # starting day (1-31)
self.nDay = None # number of days
self.dtSim = None # simulation time step (s)
self.dtWeather = None # seconds (s)
# HVAC system and internal laod
self.autosize = None # autosize HVAC (1 or 0)
self.sensOcc = None # Sensible heat from occupant
self.LatFOcc = None # Latent heat fraction from occupant (normally 0.3)
self.RadFOcc = None # Radiant heat fraction from occupant (normally 0.2)
self.RadFEquip = None # Radiant heat fraction from equipment (normally 0.5)
self.RadFLight = None # Radiant heat fraction from light (normally 0.7)
# Define Urban microclimate parameters
self.h_ubl1 = None # ubl height - day (m)
self.h_ubl2 = None # ubl height - night (m)
self.h_ref = None # inversion height
self.h_temp = None # temperature height
self.h_wind = None # wind height
self.c_circ = None # circulation coefficient
self.c_exch = None # exchange coefficient
self.maxDay = None # max day threshhold
self.maxNight = None # max night threshhold
self.windMin = None # min wind speed (m/s)
self.h_obs = None # rural average obstacle height
# Urban characteristics
self.bldHeight = None # average building height (m)
self.h_mix = None # mixing height (m)
self.bldDensity = None # building density (0-1)
self.verToHor = None # building aspect ratio
# radius defining the urban area of study [aka. characteristic length] (m)
self.charLength = None
self.alb_road = None # road albedo
self.d_road = None # road pavement thickness
self.sensAnth = None # non-building sensible heat (W/m^2)
self.latAnth = None # non-building latent heat heat (W/m^2). Not used, taken out by JH.
# Fraction of building typology stock
self.bld = None # 16x3 matrix of fraction of building type by era
# climate Zone
self.zone = None
# Vegetation parameters
self.vegCover = None # urban area veg coverage ratio
self.treeCoverage = None # urban area tree coverage ratio
self.vegStart = None # vegetation start month
self.vegEnd = None # vegetation end month
self.albVeg = None # Vegetation albedo
self.rurVegCover = None # rural vegetation cover
self.latGrss = None # latent fraction of grass
self.latTree = None # latent fraction of tree
# Define Traffic schedule
self.SchTraffic = None
# Define Road (Assume 0.5m of asphalt)
self.kRoad = None # road pavement conductivity (W/m K)
self.cRoad = None # road volumetric heat capacity (J/m^3 K)
# Define optional Building characteristics
self.flr_h = None # floor-to-floor height
self.albRoof = None # roof albedo (0 - 1)
self.vegRoof = None # Fraction of the roofs covered in grass/shrubs (0-1)
self.glzR = None # Glazing Ratio
self.SHGC = None # Solar Heat Gain Coefficient
self.albWall = None # Wall albedo
def ToString(self):
"""Overwrite .NET ToString method."""
return self.__repr__()
def __repr__(self):
def _split_string(s):
return s[0] + ":\n " + s[1].replace(",", "\n ")
def _tabbed(s):
return _split_string(s.__repr__().split(":"))
def _list_2_tabbed(b):
return reduce(lambda a, b: a+"\n"+b, [_tabbed(_b) for _b in b])
return "uwg for {}:\n\n{}{}{}{}{}{}{}{}".format(
self.epwFileName,
_tabbed(self.simTime)+"\n" if hasattr(self, "simTime") else "No simTime attr.\n",
_tabbed(self.weather)+"\n" if hasattr(self, "weather") else "No weather attr.\n",
_tabbed(self.geoParam)+"\n" if hasattr(self, "geoParam") else "No geoParam attr.\n",
_tabbed(self.UBL)+"\n" if hasattr(self, "UBL") else "No UBL attr.\n",
"Rural "+_tabbed(self.RSM)+"\n" if hasattr(self, "RSM") else "No Rural RSM attr.\n",
"Urban "+_tabbed(self.USM)+"\n" if hasattr(self, "USM") else "No Urban RSM attr.\n",
_tabbed(self.UCM)+"\n" if hasattr(self, "UCM") else "No UCM attr.\n",
_list_2_tabbed(self.BEM) if hasattr(self, "BEM") else "No BEM attr."
)
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def read_epw(self):
"""Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT # GMT
self.nSoil # Number of soil depths
self.Tsoil # nSoil x 12 matrix for soil temperture (K)
self.depth_soil # nSoil x 1 matrix for soil depth (m)
"""
# Make dir path to epw file
self.climateDataPath = os.path.join(self.epwDir, self.epwFileName)
# Open epw file and feed csv data to climate_data
try:
climate_data = utilities.read_csv(self.climateDataPath)
except Exception as e:
raise Exception("Failed to read epw file! {}".format(e.message))
# Read header lines (1 to 8) from EPW and ensure TMY2 format.
self._header = climate_data[0:8]
# Read weather data from EPW for each time step in weather file. (lines 8 - end)
self.epwinput = climate_data[8:]
# Read Lat, Long (line 1 of EPW)
self.lat = float(self._header[0][6])
self.lon = float(self._header[0][7])
self.GMT = float(self._header[0][8])
# Read in soil temperature data (assumes this is always there)
# ref: http://bigladdersoftware.com/epx/docs/8-2/auxiliary-programs/epw-csv-format-inout.html
soilData = self._header[3]
self.nSoil = int(soilData[1]) # Number of ground temperature depths
self.Tsoil = utilities.zeros(self.nSoil, 12) # nSoil x 12 matrix for soil temperture (K)
self.depth_soil = utilities.zeros(self.nSoil, 1) # nSoil x 1 matrix for soil depth (m)
# Read monthly data for each layer of soil from EPW file
for i in range(self.nSoil):
self.depth_soil[i][0] = float(soilData[2 + (i*16)]) # get soil depth for each nSoil
# Monthly data
for j in range(12):
# 12 months of soil T for specific depth
self.Tsoil[i][j] = float(soilData[6 + (i*16) + j]) + 273.15
# Set new directory path for the moprhed EPW file
self.newPathName = os.path.join(self.destinationDir, self.destinationFileName)
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic # Traffice schedule
self.BEM # list of BEMDef objects extracted from readDOE
self.Sch # list of Schedule objects extracted from readDOE
"""
uwg_param_file_path = os.path.join(self.uwgParamDir, self.uwgParamFileName)
if not os.path.exists(uwg_param_file_path):
raise Exception("Param file: '{}' does not exist.".format(uwg_param_file_path))
# Open .uwg file and feed csv data to initializeDataFile
try:
uwg_param_data = utilities.read_csv(uwg_param_file_path)
except Exception as e:
raise Exception("Failed to read .uwg file! {}".format(e.message))
# The initialize.uwg is read with a dictionary so that users changing
# line endings or line numbers doesn't make reading input incorrect
self._init_param_dict = {}
count = 0
while count < len(uwg_param_data):
row = uwg_param_data[count]
row = [row[i].replace(" ", "") for i in range(len(row))] # strip white spaces
# Optional parameters might be empty so handle separately
is_optional_parameter = (
row != [] and
(
row[0] == "albRoof" or
row[0] == "vegRoof" or
row[0] == "glzR" or
row[0] == "hvac" or
row[0] == "albWall" or
row[0] == "SHGC"
)
)
try:
if row == [] or "#" in row[0]:
count += 1
continue
elif row[0] == "SchTraffic":
# SchTraffic: 3 x 24 matrix
trafficrows = uwg_param_data[count+1:count+4]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:24]) for r in trafficrows]
count += 4
elif row[0] == "bld":
# bld: 17 x 3 matrix
bldrows = uwg_param_data[count+1:count+17]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:3]) for r in bldrows]
count += 17
elif is_optional_parameter:
self._init_param_dict[row[0]] = float(row[1]) if row[1] != "" else None
count += 1
else:
self._init_param_dict[row[0]] = float(row[1])
count += 1
except ValueError:
print("Error while reading parameter at {} {}".format(count, row))
ipd = self._init_param_dict
# Define Simulation and Weather parameters
if self.Month is None: self.Month = ipd['Month']
if self.Day is None: self.Day = ipd['Day']
if self.nDay is None: self.nDay = ipd['nDay']
if self.dtSim is None: self.dtSim = ipd['dtSim']
if self.dtWeather is None: self.dtWeather = ipd['dtWeather']
# HVAC system and internal laod
if self.autosize is None: self.autosize = ipd['autosize']
if self.sensOcc is None: self.sensOcc = ipd['sensOcc']
if self.LatFOcc is None: self.LatFOcc = ipd['LatFOcc']
if self.RadFOcc is None: self.RadFOcc = ipd['RadFOcc']
if self.RadFEquip is None: self.RadFEquip = ipd['RadFEquip']
if self.RadFLight is None: self.RadFLight = ipd['RadFLight']
# Define Urban microclimate parameters
if self.h_ubl1 is None: self.h_ubl1 = ipd['h_ubl1']
if self.h_ubl2 is None: self.h_ubl2 = ipd['h_ubl2']
if self.h_ref is None: self.h_ref = ipd['h_ref']
if self.h_temp is None: self.h_temp = ipd['h_temp']
if self.h_wind is None: self.h_wind = ipd['h_wind']
if self.c_circ is None: self.c_circ = ipd['c_circ']
if self.c_exch is None: self.c_exch = ipd['c_exch']
if self.maxDay is None: self.maxDay = ipd['maxDay']
if self.maxNight is None: self.maxNight = ipd['maxNight']
if self.windMin is None: self.windMin = ipd['windMin']
if self.h_obs is None: self.h_obs = ipd['h_obs']
# Urban characteristics
if self.bldHeight is None: self.bldHeight = ipd['bldHeight']
if self.h_mix is None: self.h_mix = ipd['h_mix']
if self.bldDensity is None: self.bldDensity = ipd['bldDensity']
if self.verToHor is None: self.verToHor = ipd['verToHor']
if self.charLength is None: self.charLength = ipd['charLength']
if self.alb_road is None: self.alb_road = ipd['albRoad']
if self.d_road is None: self.d_road = ipd['dRoad']
if self.sensAnth is None: self.sensAnth = ipd['sensAnth']
# if self.latAnth is None: self.latAnth = ipd['latAnth'] # Not used, taken out by JH.
# climate Zone
if self.zone is None: self.zone = ipd['zone']
# Vegetation parameters
if self.vegCover is None: self.vegCover = ipd['vegCover']
if self.treeCoverage is None: self.treeCoverage = ipd['treeCoverage']
if self.vegStart is None: self.vegStart = ipd['vegStart']
if self.vegEnd is None: self.vegEnd = ipd['vegEnd']
if self.albVeg is None: self.albVeg = ipd['albVeg']
if self.rurVegCover is None: self.rurVegCover = ipd['rurVegCover']
if self.latGrss is None: self.latGrss = ipd['latGrss']
if self.latTree is None: self.latTree = ipd['latTree']
# Define Traffic schedule
if self.SchTraffic is None: self.SchTraffic = ipd['SchTraffic']
# Define Road (Assume 0.5m of asphalt)
if self.kRoad is None: self.kRoad = ipd['kRoad']
if self.cRoad is None: self.cRoad = ipd['cRoad']
# Building stock fraction
if self.bld is None: self.bld = ipd['bld']
# Optional parameters
if self.albRoof is None: self.albRoof = ipd['albRoof']
if self.vegRoof is None: self.vegRoof = ipd['vegRoof']
if self.glzR is None: self.glzR = ipd['glzR']
if self.albWall is None: self.albWall = ipd['albWall']
if self.SHGC is None: self.SHGC = ipd['SHGC']
def check_required_inputs(self):
# Fail if required parameters aren't correct
assert isinstance(self.Month, (float, int)), \
'Month must be a number. Got {}'.format(type(self.Month))
assert isinstance(self.Day, (float, int)), \
'Day must be a number. Got {}'.format(type(self.Day))
assert isinstance(self.nDay, (float, int)), \
'nDay must be a number. Got {}'.format(type(self.nDay))
assert isinstance(self.dtSim, float), \
'dtSim must be a float. Got {}'.format(type(self.dtSim))
assert isinstance(self.dtWeather, float), \
'dtWeather must be a float. Got {}'.format(type(self.dtWeather))
assert isinstance(self.autosize, (float, int)), \
'autosize must be a number. Got {}'.format(type(self.autosize))
assert isinstance(self.sensOcc, float), \
'sensOcc must be a float. Got {}'.format(type(self.sensOcc))
assert isinstance(self.LatFOcc, float), \
'LatFOcc must be a float. Got {}'.format(type(self.LatFOcc))
assert isinstance(self.RadFOcc, float), \
'RadFOcc must be a float. Got {}'.format(type(self.RadFOcc))
assert isinstance(self.RadFEquip, float), \
'RadFEquip must be a float. Got {}'.format(type(self.RadFEquip))
assert isinstance(self.RadFLight, float), \
'RadFLight must be a float. Got {}'.format(type(self.RadFLight))
assert isinstance(self.h_ubl1, float), \
'h_ubl1 must be a float. Got {}'.format(type(self.h_ubl1))
assert isinstance(self.h_ubl2, float), \
'h_ubl2 must be a float. Got {}'.format(type(self.h_ubl2))
assert isinstance(self.h_ref, float), \
'h_ref must be a float. Got {}'.format(type(self.h_ref))
assert isinstance(self.h_temp, float), \
'h_temp must be a float. Got {}'.format(type(self.h_temp))
assert isinstance(self.h_wind, float), \
'h_wind must be a float. Got {}'.format(type(self.h_wind))
assert isinstance(self.c_circ, float), \
'c_circ must be a float. Got {}'.format(type(self.c_circ))
assert isinstance(self.c_exch, float), \
'c_exch must be a float. Got {}'.format(type(self.c_exch))
assert isinstance(self.maxDay, float), \
'maxDay must be a float. Got {}'.format(type(self.maxDay))
assert isinstance(self.maxNight, float), \
'maxNight must be a float. Got {}'.format(type(self.maxNight))
assert isinstance(self.windMin, float), \
'windMin must be a float. Got {}'.format(type(self.windMin))
assert isinstance(self.h_obs, float), \
'h_obs must be a float. Got {}'.format(type(self.h_obs))
assert isinstance(self.bldHeight, float), \
'bldHeight must be a float. Got {}'.format(type(self.bldHeight))
assert isinstance(self.h_mix, float), \
'h_mix must be a float. Got {}'.format(type(self.h_mix))
assert isinstance(self.bldDensity, float), \
'bldDensity must be a float. Got {}'.format(type(self.bldDensity))
assert isinstance(self.verToHor, float), \
'verToHor must be a float. Got {}'.format(type(self.verToHor))
assert isinstance(self.charLength, float), \
'charLength must be a float. Got {}'.format(type(self.charLength))
assert isinstance(self.alb_road, float), \
'alb_road must be a float. Got {}'.format(type(self.alb_road))
assert isinstance(self.d_road, float), \
'd_road must be a float. Got {}'.format(type(self.d_road))
assert isinstance(self.sensAnth, float), \
'sensAnth must be a float. Got {}'.format(type(self.sensAnth))
# assert isinstance(self.latAnth, float) # Take this out as isn't being used
assert isinstance(self.bld, list), \
'bld must be a list. Got {}'.format(type(self.bld))
assert len(self.bld) == 16, \
'length of bld must be 16. Got {}'.format(len(self.bld))
assert isinstance(self.latTree, float), \
'latTree must be a float. Got {}'.format(type(self.latTree))
assert isinstance(self.latGrss, float), \
'latGrss must be a float. Got {}'.format(type(self.latGrss))
assert isinstance(self.zone, (float, int)), \
'zone must be a number. Got {}'.format(type(self.zone))
assert isinstance(self.vegStart, (float, int)), \
'vegStart must be a number. Got {}'.format(type(self.vegStart))
assert isinstance(self.vegEnd, (float, int)), \
'vegEnd must be a number. Got {}'.format(type(self.vegEnd))
assert isinstance(self.vegCover, float), \
'vegCover must be a float. Got {}'.format(type(self.vegCover))
assert isinstance(self.treeCoverage, float), \
'treeCoverage must be a float. Got {}'.format(type(self.treeCoverage))
assert isinstance(self.albVeg, float), \
'albVeg must be a float. Got {}'.format(type(self.albVeg))
assert isinstance(self.rurVegCover, float), \
'rurVegCover must be a float. Got {}'.format(type(self.rurVegCover))
assert isinstance(self.kRoad, float), \
'kRoad must be a float. Got {}'.format(type(self.kRoad))
assert isinstance(self.cRoad, float), \
'cRoad must be a float. Got {}'.format(type(self.cRoad))
assert isinstance(self.SchTraffic, list), \
'SchTraffic must be a list. Got {}'.format(type(self.SchTraffic))
assert len(self.SchTraffic) == 3, \
'length of SchTraffic must be 3. Got {}'.format(len(self.SchTraffic))
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the .uwg file.
if self.uwgParamFileName is not None:
print("\nReading uwg file input.")
self.read_input()
else:
print("\nNo .uwg file input.")
self.check_required_inputs()
# Modify zone to be used as python index
self.zone = int(self.zone)-1
def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total building stock
"""
if not os.path.exists(self.readDOE_file_path):
raise Exception("readDOE.pkl file: '{}' does not exist.".format(readDOE_file_path))
readDOE_file = open(self.readDOE_file_path, 'rb') # open pickle file in binary form
refDOE = pickle.load(readDOE_file)
refBEM = pickle.load(readDOE_file)
refSchedule = pickle.load(readDOE_file)
readDOE_file.close()
# Define building energy models
k = 0
self.r_glaze_total = 0. # Glazing ratio for total building stock
self.SHGC_total = 0. # SHGC addition for total building stock
self.alb_wall_total = 0. # albedo wall addition for total building stock
h_floor = self.flr_h or 3.05 # average floor height
total_urban_bld_area = math.pow(self.charLength, 2)*self.bldDensity * \
self.bldHeight/h_floor # total building floor area
area_matrix = utilities.zeros(16, 3)
self.BEM = [] # list of BEMDef objects
self.Sch = [] # list of Schedule objects
for i in range(16): # 16 building types
for j in range(3): # 3 built eras
if self.bld[i][j] > 0.:
# Add to BEM list
self.BEM.append(refBEM[i][j][self.zone])
self.BEM[k].frac = self.bld[i][j]
self.BEM[k].fl_area = self.bld[i][j] * total_urban_bld_area
# Overwrite with optional parameters if provided
if self.glzR:
self.BEM[k].building.glazingRatio = self.glzR
if self.albRoof:
self.BEM[k].roof.albedo = self.albRoof
if self.vegRoof:
self.BEM[k].roof.vegCoverage = self.vegRoof
if self.SHGC:
self.BEM[k].building.shgc = self.SHGC
if self.albWall:
self.BEM[k].wall.albedo = self.albWall
if self.flr_h:
self.BEM[k].building.floorHeight = self.flr_h
# Keep track of total urban r_glaze, SHGC, and alb_wall for UCM model
self.r_glaze_total += self.BEM[k].frac * self.BEM[k].building.glazingRatio
self.SHGC_total += self.BEM[k].frac * self.BEM[k].building.shgc
self.alb_wall_total += self.BEM[k].frac * self.BEM[k].wall.albedo
# Add to schedule list
self.Sch.append(refSchedule[i][j][self.zone])
k += 1
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
self.geoParam # geographic parameters obj
self.RSM # Rural site & vertical diffusion model obj
self.USM # Urban site & vertical diffusion model obj
self.UCM # Urban canopy model obj
self.UBL # Urban boundary layer model
self.road # urban road element
self.rural # rural road element
self.soilindex1 # soil index for urban rsoad depth
self.soilindex2 # soil index for rural road depth
self.Sch # list of Schedule objects
"""
climate_file_path = os.path.join(self.epwDir, self.epwFileName)
self.simTime = SimParam(self.dtSim, self.dtWeather, self.Month,
self.Day, self.nDay) # simulation time parametrs
# weather file data for simulation time period
self.weather = Weather(climate_file_path, self.simTime.timeInitial, self.simTime.timeFinal)
self.forcIP = Forcing(self.weather.staTemp, self.weather) # initialized Forcing class
self.forc = Forcing() # empty forcing class
# Initialize geographic Param and Urban Boundary Layer Objects
nightStart = 18. # arbitrary values for begin/end hour for night setpoint
nightEnd = 8.
maxdx = 250. # max dx (m)
self.geoParam = Param(self.h_ubl1, self.h_ubl2, self.h_ref, self.h_temp, self.h_wind, self.c_circ,
self.maxDay, self.maxNight, self.latTree, self.latGrss, self.albVeg, self.vegStart, self.vegEnd,
nightStart, nightEnd, self.windMin, self.WGMAX, self.c_exch, maxdx, self.G, self.CP, self.VK, self.R,
self.RV, self.LV, math.pi, self.SIGMA, self.WATERDENS, self.LVTT, self.TT, self.ESTT, self.CL,
self.CPV, self.B, self.CM, self.COLBURN)
self.UBL = UBLDef(
'C', self.charLength, self.weather.staTemp[0], maxdx, self.geoParam.dayBLHeight, self.geoParam.nightBLHeight)
# Defining road
emis = 0.93
asphalt = Material(self.kRoad, self.cRoad, 'asphalt')
road_T_init = 293.
road_horizontal = 1
# fraction of surface vegetation coverage
road_veg_coverage = min(self.vegCover/(1-self.bldDensity), 1.)
# define road layers
road_layer_num = int(math.ceil(self.d_road/0.05))
# 0.5/0.05 ~ 10 x 1 matrix of 0.05 thickness
thickness_vector = [0.05 for r in range(road_layer_num)]
material_vector = [asphalt for r in range(road_layer_num)]
self.road = Element(self.alb_road, emis, thickness_vector, material_vector, road_veg_coverage,
road_T_init, road_horizontal, name="urban_road")
self.rural = copy.deepcopy(self.road)
self.rural.vegCoverage = self.rurVegCover
self.rural._name = "rural_road"
# Reference site class (also include VDM)
self.RSM = RSMDef(self.lat, self.lon, self.GMT, self.h_obs,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
self.USM = RSMDef(self.lat, self.lon, self.GMT, self.bldHeight/10.,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
T_init = self.weather.staTemp[0]
H_init = self.weather.staHum[0]
self.UCM = UCMDef(self.bldHeight, self.bldDensity, self.verToHor, self.treeCoverage, self.sensAnth, self.latAnth, T_init, H_init,
self.weather.staUmod[0], self.geoParam, self.r_glaze_total, self.SHGC_total, self.alb_wall_total, self.road)
self.UCM.h_mix = self.h_mix
# Define Road Element & buffer to match ground temperature depth
roadMat, newthickness = procMat(self.road, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
roadMat.append(self.SOIL)
self.soilindex1 = i
break
self.road = Element(self.road.albedo, self.road.emissivity, newthickness, roadMat,
self.road.vegCoverage, self.road.layerTemp[0], self.road.horizontal, self.road._name)
# Define Rural Element
ruralMat, newthickness = procMat(self.rural, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
ruralMat.append(self.SOIL)
self.soilindex2 = i
break
self.rural = Element(self.rural.albedo, self.rural.emissivity, newthickness,
ruralMat, self.rural.vegCoverage, self.rural.layerTemp[0], self.rural.horizontal, self.rural._name)
def hvac_autosize(self):
""" Section 6 - HVAC Autosizing (unlimited cooling & heating) """
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999.
def simulate(self):
""" Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# Output of object instance vector
self.WeatherData # Nx1 vector of forc instance
self.UCMData # Nx1 vector of UCM instance
self.UBLData # Nx1 vector of UBL instance
self.RSMData # Nx1 vector of RSM instance
self.USMData # Nx1 vector of USM instance
"""
self.N = int(self.simTime.days * 24) # total number of hours in simulation
n = 0 # weather time step counter
self.ph = self.simTime.dt/3600. # dt (simulation time step) in hours
# Data dump variables
time = range(self.N)
self.WeatherData = [None for x in range(self.N)]
self.UCMData = [None for x in range(self.N)]
self.UBLData = [None for x in range(self.N)]
self.RSMData = [None for x in range(self.N)]
self.USMData = [None for x in range(self.N)]
print('\nSimulating new temperature and humidity values for {} days from {}/{}.\n'.format(
int(self.nDay), int(self.Month), int(self.Day)))
self.logger.info("Start simulation")
for it in range(1, self.simTime.nt, 1): # for every simulation time-step (i.e 5 min) defined by uwg
# Update water temperature (estimated)
if self.nSoil < 3: # correction to original matlab code
# for BUBBLE/CAPITOUL/Singapore only
self.forc.deepTemp = sum(self.forcIP.temp)/float(len(self.forcIP.temp))
self.forc.waterTemp = sum(
self.forcIP.temp)/float(len(self.forcIP.temp)) - 10. # for BUBBLE/CAPITOUL/Singapore only
else:
# soil temperature by depth, by month
self.forc.deepTemp = self.Tsoil[self.soilindex1][self.simTime.month-1]
self.forc.waterTemp = self.Tsoil[2][self.simTime.month-1]
# There's probably a better way to update the weather...
self.simTime.UpdateDate()
self.logger.info("\n{0} m={1}, d={2}, h={3}, s={4}".format(
__name__, self.simTime.month, self.simTime.day, self.simTime.secDay/3600., self.simTime.secDay))
# simulation time increment raised to weather time step
self.ceil_time_step = int(math.ceil(it * self.ph))-1
# minus one to be consistent with forcIP list index
# Updating forcing instance
# horizontal Infrared Radiation Intensity (W m-2)
self.forc.infra = self.forcIP.infra[self.ceil_time_step]
# wind speed (m s-1)
self.forc.wind = max(self.forcIP.wind[self.ceil_time_step], self.geoParam.windMin)
self.forc.uDir = self.forcIP.uDir[self.ceil_time_step] # wind direction
# specific humidty (kg kg-1)
self.forc.hum = self.forcIP.hum[self.ceil_time_step]
self.forc.pres = self.forcIP.pres[self.ceil_time_step] # Pressure (Pa)
self.forc.temp = self.forcIP.temp[self.ceil_time_step] # air temperature (C)
self.forc.rHum = self.forcIP.rHum[self.ceil_time_step] # Relative humidity (%)
self.forc.prec = self.forcIP.prec[self.ceil_time_step] # Precipitation (mm h-1)
# horizontal solar diffuse radiation (W m-2)
self.forc.dif = self.forcIP.dif[self.ceil_time_step]
# normal solar direct radiation (W m-2)
self.forc.dir = self.forcIP.dir[self.ceil_time_step]
# Canyon humidity (absolute) same as rural
self.UCM.canHum = copy.copy(self.forc.hum)
# Update solar flux
self.solar = SolarCalcs(self.UCM, self.BEM, self.simTime,
self.RSM, self.forc, self.geoParam, self.rural)
self.rural, self.UCM, self.BEM = self.solar.solarcalcs()
# Update building & traffic schedule
# Assign day type (1 = weekday, 2 = sat, 3 = sun/other)
if self.is_near_zero(self.simTime.julian % 7):
self.dayType = 3 # Sunday
elif self.is_near_zero(self.simTime.julian % 7 - 6.):
self.dayType = 2 # Saturday
else:
self.dayType = 1 # Weekday
# Update anthropogenic heat load for each hour (building & UCM)
self.UCM.sensAnthrop = self.sensAnth * (self.SchTraffic[self.dayType-1][self.simTime.hourDay])
# Update the energy components for building types defined in initialize.uwg
for i in range(len(self.BEM)):
# Set temperature
self.BEM[i].building.coolSetpointDay = self.Sch[i].Cool[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for cooling
self.BEM[i].building.coolSetpointNight = self.BEM[i].building.coolSetpointDay
self.BEM[i].building.heatSetpointDay = self.Sch[i].Heat[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for heating
self.BEM[i].building.heatSetpointNight = self.BEM[i].building.heatSetpointDay
# Internal Heat Load Schedule (W/m^2 of floor area for Q)
self.BEM[i].Elec = self.Sch[i].Qelec * self.Sch[i].Elec[self.dayType -
1][self.simTime.hourDay] # Qelec x elec fraction for day
self.BEM[i].Light = self.Sch[i].Qlight * self.Sch[i].Light[self.dayType -
1][self.simTime.hourDay] # Qlight x light fraction for day
self.BEM[i].Nocc = self.Sch[i].Nocc * self.Sch[i].Occ[self.dayType -
1][self.simTime.hourDay] # Number of occupants x occ fraction for day
# Sensible Q occupant * fraction occupant sensible Q * number of occupants
self.BEM[i].Qocc = self.sensOcc * (1 - self.LatFOcc) * self.BEM[i].Nocc
# SWH and ventilation schedule
self.BEM[i].SWH = self.Sch[i].Vswh * self.Sch[i].SWH[self.dayType -
1][self.simTime.hourDay] # litres per hour x SWH fraction for day
# m^3/s/m^2 of floor
self.BEM[i].building.vent = self.Sch[i].Vent
self.BEM[i].Gas = self.Sch[i].Qgas * self.Sch[i].Gas[self.dayType -
1][self.simTime.hourDay] # Gas Equip Schedule, per m^2 of floor
# This is quite messy, should update
# Update internal heat and corresponding fractional loads
intHeat = self.BEM[i].Light + self.BEM[i].Elec + self.BEM[i].Qocc
# W/m2 from light, electricity, occupants
self.BEM[i].building.intHeatDay = intHeat
self.BEM[i].building.intHeatNight = intHeat
# fraction of radiant heat from light and equipment of whole internal heat
self.BEM[i].building.intHeatFRad = (
self.RadFLight * self.BEM[i].Light + self.RadFEquip * self.BEM[i].Elec) / intHeat
# fraction of latent heat (from occupants) of whole internal heat
self.BEM[i].building.intHeatFLat = self.LatFOcc * \
self.sensOcc * self.BEM[i].Nocc/intHeat
# Update envelope temperature layers
self.BEM[i].T_wallex = self.BEM[i].wall.layerTemp[0]
self.BEM[i].T_wallin = self.BEM[i].wall.layerTemp[-1]
self.BEM[i].T_roofex = self.BEM[i].roof.layerTemp[0]
self.BEM[i].T_roofin = self.BEM[i].roof.layerTemp[-1]
# Update rural heat fluxes & update vertical diffusion model (VDM)
self.rural.infra = self.forc.infra - self.rural.emissivity * self.SIGMA * \
self.rural.layerTemp[0]**4. # Infrared radiation from rural road
self.rural.SurfFlux(self.forc, self.geoParam, self.simTime,
self.forc.hum, self.forc.temp, self.forc.wind, 2., 0.)
self.RSM.VDM(self.forc, self.rural, self.geoParam, self.simTime)
# Calculate urban heat fluxes, update UCM & UBL
self.UCM, self.UBL, self.BEM = urbflux(
self.UCM, self.UBL, self.BEM, self.forc, self.geoParam, self.simTime, self.RSM)
self.UCM.UCModel(self.BEM, self.UBL.ublTemp, self.forc, self.geoParam)
self.UBL.UBLModel(self.UCM, self.RSM, self.rural,
self.forc, self.geoParam, self.simTime)
"""
# Experimental code to run diffusion model in the urban area
# N.B Commented out in python uwg because computed wind speed in
# urban VDM: y = =0.84*ln((2-x/20)/0.51) results in negative log
# for building heights >= 40m.
Uroad = copy.copy(self.UCM.road)
Uroad.sens = copy.copy(self.UCM.sensHeat)
Uforc = copy.copy(self.forc)
Uforc.wind = copy.copy(self.UCM.canWind)
Uforc.temp = copy.copy(self.UCM.canTemp)
self.USM.VDM(Uforc,Uroad,self.geoParam,self.simTime)
"""
self.logger.info("dbT = {}".format(self.UCM.canTemp-273.15))
if n > 0:
logging.info("dpT = {}".format(self.UCM.Tdp))
logging.info("RH = {}".format(self.UCM.canRHum))
if self.is_near_zero(self.simTime.secDay % self.simTime.timePrint) and n < self.N:
self.logger.info("{0} ----sim time step = {1}----\n\n".format(__name__, n))
self.WeatherData[n] = copy.copy(self.forc)
_Tdb, _w, self.UCM.canRHum, _h, self.UCM.Tdp, _v = psychrometrics(
self.UCM.canTemp, self.UCM.canHum, self.forc.pres)
self.UBLData[n] = copy.copy(self.UBL)
self.UCMData[n] = copy.copy(self.UCM)
self.RSMData[n] = copy.copy(self.RSM)
self.logger.info("dbT = {}".format(self.UCMData[n].canTemp-273.15))
self.logger.info("dpT = {}".format(self.UCMData[n].Tdp))
self.logger.info("RH = {}".format(self.UCMData[n].canRHum))
n += 1
def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] = column data of epw
self.epwinput[iJ+self.simTime.timeInitial-8][6] = "{0:.{1}f}".format(
self.UCMData[iJ].canTemp - 273.15, epw_prec) # dry bulb temperature [?C]
# dew point temperature [?C]
self.epwinput[iJ+self.simTime.timeInitial -
8][7] = "{0:.{1}f}".format(self.UCMData[iJ].Tdp, epw_prec)
# relative humidity [%]
self.epwinput[iJ+self.simTime.timeInitial -
8][8] = "{0:.{1}f}".format(self.UCMData[iJ].canRHum, epw_prec)
self.epwinput[iJ+self.simTime.timeInitial-8][21] = "{0:.{1}f}".format(
self.WeatherData[iJ].wind, epw_prec) # wind speed [m/s]
# Writing new EPW file
epw_new_id = open(self.newPathName, "w")
for i in range(8):
new_epw_line = '{}\n'.format(reduce(lambda x, y: x+","+y, self._header[i]))
epw_new_id.write(new_epw_line)
for i in range(len(self.epwinput)):
printme = ""
for ei in range(34):
printme += "{}".format(self.epwinput[i][ei]) + ','
printme = printme + "{}".format(self.epwinput[i][ei])
new_epw_line = "{0}\n".format(printme)
epw_new_id.write(new_epw_line)
epw_new_id.close()
print("New climate file '{}' is generated at {}.".format(
self.destinationFileName, self.destinationDir))
def run(self):
# run main class methods
self.read_epw()
self.set_input()
self.init_BEM_obj()
self.init_input_obj()
self.hvac_autosize()
self.simulate()
self.write_epw()
def procMat(materials, max_thickness, min_thickness):
""" Processes material layer so that a material with single
layer thickness is divided into two and material layer that is too
thick is subdivided
"""
newmat = []
newthickness = []
k = materials.layerThermalCond
Vhc = materials.layerVolHeat
if len(materials.layerThickness) > 1:
for j in range(len(materials.layerThickness)):
# Break up each layer that's more than max thickness (0.05m)
if materials.layerThickness[j] > max_thickness:
nlayers = math.ceil(materials.layerThickness[j]/float(max_thickness))
for i in range(int(nlayers)):
newmat.append(Material(k[j], Vhc[j], name=materials._name))
newthickness.append(materials.layerThickness[j]/float(nlayers))
# Material that's less then min_thickness is not added.
elif materials.layerThickness[j] < min_thickness:
print("WARNING: Material '{}' layer found too thin (<{:.2f}cm), ignored.").format(
materials._name, min_thickness*100)
else:
newmat.append(Material(k[j], Vhc[j], name=materials._name))
newthickness.append(materials.layerThickness[j])
else:
# Divide single layer into two (uwg assumes at least 2 layers)
if materials.layerThickness[0] > max_thickness:
nlayers = math.ceil(materials.layerThickness[0]/float(max_thickness))
for i in range(int(nlayers)):
newmat.append(Material(k[0], Vhc[0], name=materials._name))
newthickness.append(materials.layerThickness[0]/float(nlayers))
# Material should be at least 1cm thick, so if we're here,
# should give warning and stop. Only warning given for now.
elif materials.layerThickness[0] < min_thickness*2:
newthickness = [min_thickness/2., min_thickness/2.]
newmat = [Material(k[0], Vhc[0], name=materials._name),
Material(k[0], Vhc[0], name=materials._name)]
print("WARNING: a thin (<2cm) single material '{}' layer found. May cause error.".format(
materials._name))
else:
newthickness = [materials.layerThickness[0]/2., materials.layerThickness[0]/2.]
newmat = [Material(k[0], Vhc[0], name=materials._name),
Material(k[0], Vhc[0], name=materials._name)]
return newmat, newthickness
|
ladybug-tools/uwg | uwg/uwg.py | uwg.read_epw | python | def read_epw(self):
"""Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT # GMT
self.nSoil # Number of soil depths
self.Tsoil # nSoil x 12 matrix for soil temperture (K)
self.depth_soil # nSoil x 1 matrix for soil depth (m)
"""
# Make dir path to epw file
self.climateDataPath = os.path.join(self.epwDir, self.epwFileName)
# Open epw file and feed csv data to climate_data
try:
climate_data = utilities.read_csv(self.climateDataPath)
except Exception as e:
raise Exception("Failed to read epw file! {}".format(e.message))
# Read header lines (1 to 8) from EPW and ensure TMY2 format.
self._header = climate_data[0:8]
# Read weather data from EPW for each time step in weather file. (lines 8 - end)
self.epwinput = climate_data[8:]
# Read Lat, Long (line 1 of EPW)
self.lat = float(self._header[0][6])
self.lon = float(self._header[0][7])
self.GMT = float(self._header[0][8])
# Read in soil temperature data (assumes this is always there)
# ref: http://bigladdersoftware.com/epx/docs/8-2/auxiliary-programs/epw-csv-format-inout.html
soilData = self._header[3]
self.nSoil = int(soilData[1]) # Number of ground temperature depths
self.Tsoil = utilities.zeros(self.nSoil, 12) # nSoil x 12 matrix for soil temperture (K)
self.depth_soil = utilities.zeros(self.nSoil, 1) # nSoil x 1 matrix for soil depth (m)
# Read monthly data for each layer of soil from EPW file
for i in range(self.nSoil):
self.depth_soil[i][0] = float(soilData[2 + (i*16)]) # get soil depth for each nSoil
# Monthly data
for j in range(12):
# 12 months of soil T for specific depth
self.Tsoil[i][j] = float(soilData[6 + (i*16) + j]) + 273.15
# Set new directory path for the moprhed EPW file
self.newPathName = os.path.join(self.destinationDir, self.destinationFileName) | Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT # GMT
self.nSoil # Number of soil depths
self.Tsoil # nSoil x 12 matrix for soil temperture (K)
self.depth_soil # nSoil x 1 matrix for soil depth (m) | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/uwg.py#L246-L297 | [
"def zeros(h, w):\n \"\"\"create a (h x w) matrix of zeros.\n\n Args:\n h: Height of the matrix.\n w: Width of the matrix.\n \"\"\"\n return [[0 for x in range(w)] for y in range(h)]\n",
"def read_csv(file_name_):\n # open csv file and read\n if os.path.exists(file_name_):\n if sys.version_info[0] >= 3:\n file_ = open(file_name_, \"r\", errors='ignore')\n else:\n file_ = open(file_name_, \"r\")\n\n gen_ = csv_reader(file_, delimiter=\",\")\n L = [r for r in gen_]\n file_.close()\n return L\n else:\n raise Exception(\"File name: '{}' does not exist.\".format(file_name_))\n"
] | class uwg(object):
"""Morph a rural EPW file to urban conditions using a file with a list of urban parameters.
args:
epwDir: The directory in which the rural EPW file sits.
epwFileName: The name of the rural epw file that will be morphed.
uwgParamDir: The directory in which the uwg Parameter File (.uwg) sits.
uwgParamFileName: The name of the uwg Parameter File (.uwg).
destinationDir: Optional destination directory for the morphed EPW file.
If left blank, the morphed file will be written into the same directory
as the rural EPW file (the epwDir).
destinationFileName: Optional destination file name for the morphed EPW file.
If left blank, the morphed file will append "_UWG" to the original file name.
returns:
newClimateFile: the path to a new EPW file that has been morphed to account
for uban conditions.
"""
""" Section 1 - Definitions for constants / other parameters """
MINTHICKNESS = 0.01 # Minimum layer thickness (to prevent crashing) (m)
MAXTHICKNESS = 0.05 # Maximum layer thickness (m)
# http://web.mit.edu/parmstr/Public/NRCan/nrcc29118.pdf (Figly & Snodgrass)
SOILTCOND = 1
# http://www.europment.org/library/2013/venice/bypaper/MFHEEF/MFHEEF-21.pdf (average taken from Table 1)
SOILVOLHEAT = 2e6
# Soil material used for soil-depth padding
SOIL = Material(SOILTCOND, SOILVOLHEAT, name="soil")
# Physical constants
G = 9.81 # gravity (m s-2)
CP = 1004. # heat capacity for air (J/kg K)
VK = 0.40 # von karman constant (dimensionless)
R = 287. # gas constant dry air (J/kg K)
RV = 461.5 # gas constant water vapor (J/kg K)
LV = 2.26e6 # latent heat of evaporation (J/kg)
SIGMA = 5.67e-08 # Stefan Boltzmann constant (W m-2 K-4)
WATERDENS = 1000. # water density (kg m-3)
LVTT = 2.5008e6 #
TT = 273.16 #
ESTT = 611.14 #
CL = 4.218e3 #
CPV = 1846.1 #
B = 9.4 # Coefficients derived by Louis (1979)
CM = 7.4 #
# (Pr/Sc)^(2/3) for Colburn analogy in water evaporation
COLBURN = math.pow((0.713/0.621), (2/3.))
# Site-specific parameters
WGMAX = 0.005 # maximum film water depth on horizontal surfaces (m)
# File path parameter
RESOURCE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "resources"))
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
def __init__(self, epwFileName, uwgParamFileName=None, epwDir=None, uwgParamDir=None, destinationDir=None, destinationFileName=None):
# Logger will be disabled by default unless explicitly called in tests
self.logger = logging.getLogger(__name__)
# User defined
self.epwFileName = epwFileName if epwFileName.lower().endswith('.epw') else epwFileName + \
'.epw' # Revise epw file name if not end with epw
# If file name is entered then will uwg will set input from .uwg file
self.uwgParamFileName = uwgParamFileName
# If user does not overload
self.destinationFileName = destinationFileName if destinationFileName else self.epwFileName.strip(
'.epw') + '_UWG.epw'
self.epwDir = epwDir if epwDir else os.path.join(self.RESOURCE_PATH, "epw")
self.uwgParamDir = uwgParamDir if uwgParamDir else os.path.join(
self.RESOURCE_PATH, "parameters")
self.destinationDir = destinationDir if destinationDir else os.path.join(
self.RESOURCE_PATH, "epw_uwg")
# refdata: Serialized DOE reference data, z_meso height data
self.readDOE_file_path = os.path.join(self.CURRENT_PATH, "refdata", "readDOE.pkl")
self.z_meso_dir_path = os.path.join(self.CURRENT_PATH, "refdata")
# EPW precision
self.epw_precision = 1
# init uwg variables
self._init_param_dict = None
# Define Simulation and Weather parameters
self.Month = None # starting month (1-12)
self.Day = None # starting day (1-31)
self.nDay = None # number of days
self.dtSim = None # simulation time step (s)
self.dtWeather = None # seconds (s)
# HVAC system and internal laod
self.autosize = None # autosize HVAC (1 or 0)
self.sensOcc = None # Sensible heat from occupant
self.LatFOcc = None # Latent heat fraction from occupant (normally 0.3)
self.RadFOcc = None # Radiant heat fraction from occupant (normally 0.2)
self.RadFEquip = None # Radiant heat fraction from equipment (normally 0.5)
self.RadFLight = None # Radiant heat fraction from light (normally 0.7)
# Define Urban microclimate parameters
self.h_ubl1 = None # ubl height - day (m)
self.h_ubl2 = None # ubl height - night (m)
self.h_ref = None # inversion height
self.h_temp = None # temperature height
self.h_wind = None # wind height
self.c_circ = None # circulation coefficient
self.c_exch = None # exchange coefficient
self.maxDay = None # max day threshhold
self.maxNight = None # max night threshhold
self.windMin = None # min wind speed (m/s)
self.h_obs = None # rural average obstacle height
# Urban characteristics
self.bldHeight = None # average building height (m)
self.h_mix = None # mixing height (m)
self.bldDensity = None # building density (0-1)
self.verToHor = None # building aspect ratio
# radius defining the urban area of study [aka. characteristic length] (m)
self.charLength = None
self.alb_road = None # road albedo
self.d_road = None # road pavement thickness
self.sensAnth = None # non-building sensible heat (W/m^2)
self.latAnth = None # non-building latent heat heat (W/m^2). Not used, taken out by JH.
# Fraction of building typology stock
self.bld = None # 16x3 matrix of fraction of building type by era
# climate Zone
self.zone = None
# Vegetation parameters
self.vegCover = None # urban area veg coverage ratio
self.treeCoverage = None # urban area tree coverage ratio
self.vegStart = None # vegetation start month
self.vegEnd = None # vegetation end month
self.albVeg = None # Vegetation albedo
self.rurVegCover = None # rural vegetation cover
self.latGrss = None # latent fraction of grass
self.latTree = None # latent fraction of tree
# Define Traffic schedule
self.SchTraffic = None
# Define Road (Assume 0.5m of asphalt)
self.kRoad = None # road pavement conductivity (W/m K)
self.cRoad = None # road volumetric heat capacity (J/m^3 K)
# Define optional Building characteristics
self.flr_h = None # floor-to-floor height
self.albRoof = None # roof albedo (0 - 1)
self.vegRoof = None # Fraction of the roofs covered in grass/shrubs (0-1)
self.glzR = None # Glazing Ratio
self.SHGC = None # Solar Heat Gain Coefficient
self.albWall = None # Wall albedo
def ToString(self):
"""Overwrite .NET ToString method."""
return self.__repr__()
def __repr__(self):
def _split_string(s):
return s[0] + ":\n " + s[1].replace(",", "\n ")
def _tabbed(s):
return _split_string(s.__repr__().split(":"))
def _list_2_tabbed(b):
return reduce(lambda a, b: a+"\n"+b, [_tabbed(_b) for _b in b])
return "uwg for {}:\n\n{}{}{}{}{}{}{}{}".format(
self.epwFileName,
_tabbed(self.simTime)+"\n" if hasattr(self, "simTime") else "No simTime attr.\n",
_tabbed(self.weather)+"\n" if hasattr(self, "weather") else "No weather attr.\n",
_tabbed(self.geoParam)+"\n" if hasattr(self, "geoParam") else "No geoParam attr.\n",
_tabbed(self.UBL)+"\n" if hasattr(self, "UBL") else "No UBL attr.\n",
"Rural "+_tabbed(self.RSM)+"\n" if hasattr(self, "RSM") else "No Rural RSM attr.\n",
"Urban "+_tabbed(self.USM)+"\n" if hasattr(self, "USM") else "No Urban RSM attr.\n",
_tabbed(self.UCM)+"\n" if hasattr(self, "UCM") else "No UCM attr.\n",
_list_2_tabbed(self.BEM) if hasattr(self, "BEM") else "No BEM attr."
)
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def read_epw(self):
"""Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT # GMT
self.nSoil # Number of soil depths
self.Tsoil # nSoil x 12 matrix for soil temperture (K)
self.depth_soil # nSoil x 1 matrix for soil depth (m)
"""
# Make dir path to epw file
self.climateDataPath = os.path.join(self.epwDir, self.epwFileName)
# Open epw file and feed csv data to climate_data
try:
climate_data = utilities.read_csv(self.climateDataPath)
except Exception as e:
raise Exception("Failed to read epw file! {}".format(e.message))
# Read header lines (1 to 8) from EPW and ensure TMY2 format.
self._header = climate_data[0:8]
# Read weather data from EPW for each time step in weather file. (lines 8 - end)
self.epwinput = climate_data[8:]
# Read Lat, Long (line 1 of EPW)
self.lat = float(self._header[0][6])
self.lon = float(self._header[0][7])
self.GMT = float(self._header[0][8])
# Read in soil temperature data (assumes this is always there)
# ref: http://bigladdersoftware.com/epx/docs/8-2/auxiliary-programs/epw-csv-format-inout.html
soilData = self._header[3]
self.nSoil = int(soilData[1]) # Number of ground temperature depths
self.Tsoil = utilities.zeros(self.nSoil, 12) # nSoil x 12 matrix for soil temperture (K)
self.depth_soil = utilities.zeros(self.nSoil, 1) # nSoil x 1 matrix for soil depth (m)
# Read monthly data for each layer of soil from EPW file
for i in range(self.nSoil):
self.depth_soil[i][0] = float(soilData[2 + (i*16)]) # get soil depth for each nSoil
# Monthly data
for j in range(12):
# 12 months of soil T for specific depth
self.Tsoil[i][j] = float(soilData[6 + (i*16) + j]) + 273.15
# Set new directory path for the moprhed EPW file
self.newPathName = os.path.join(self.destinationDir, self.destinationFileName)
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic # Traffice schedule
self.BEM # list of BEMDef objects extracted from readDOE
self.Sch # list of Schedule objects extracted from readDOE
"""
uwg_param_file_path = os.path.join(self.uwgParamDir, self.uwgParamFileName)
if not os.path.exists(uwg_param_file_path):
raise Exception("Param file: '{}' does not exist.".format(uwg_param_file_path))
# Open .uwg file and feed csv data to initializeDataFile
try:
uwg_param_data = utilities.read_csv(uwg_param_file_path)
except Exception as e:
raise Exception("Failed to read .uwg file! {}".format(e.message))
# The initialize.uwg is read with a dictionary so that users changing
# line endings or line numbers doesn't make reading input incorrect
self._init_param_dict = {}
count = 0
while count < len(uwg_param_data):
row = uwg_param_data[count]
row = [row[i].replace(" ", "") for i in range(len(row))] # strip white spaces
# Optional parameters might be empty so handle separately
is_optional_parameter = (
row != [] and
(
row[0] == "albRoof" or
row[0] == "vegRoof" or
row[0] == "glzR" or
row[0] == "hvac" or
row[0] == "albWall" or
row[0] == "SHGC"
)
)
try:
if row == [] or "#" in row[0]:
count += 1
continue
elif row[0] == "SchTraffic":
# SchTraffic: 3 x 24 matrix
trafficrows = uwg_param_data[count+1:count+4]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:24]) for r in trafficrows]
count += 4
elif row[0] == "bld":
# bld: 17 x 3 matrix
bldrows = uwg_param_data[count+1:count+17]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:3]) for r in bldrows]
count += 17
elif is_optional_parameter:
self._init_param_dict[row[0]] = float(row[1]) if row[1] != "" else None
count += 1
else:
self._init_param_dict[row[0]] = float(row[1])
count += 1
except ValueError:
print("Error while reading parameter at {} {}".format(count, row))
ipd = self._init_param_dict
# Define Simulation and Weather parameters
if self.Month is None: self.Month = ipd['Month']
if self.Day is None: self.Day = ipd['Day']
if self.nDay is None: self.nDay = ipd['nDay']
if self.dtSim is None: self.dtSim = ipd['dtSim']
if self.dtWeather is None: self.dtWeather = ipd['dtWeather']
# HVAC system and internal laod
if self.autosize is None: self.autosize = ipd['autosize']
if self.sensOcc is None: self.sensOcc = ipd['sensOcc']
if self.LatFOcc is None: self.LatFOcc = ipd['LatFOcc']
if self.RadFOcc is None: self.RadFOcc = ipd['RadFOcc']
if self.RadFEquip is None: self.RadFEquip = ipd['RadFEquip']
if self.RadFLight is None: self.RadFLight = ipd['RadFLight']
# Define Urban microclimate parameters
if self.h_ubl1 is None: self.h_ubl1 = ipd['h_ubl1']
if self.h_ubl2 is None: self.h_ubl2 = ipd['h_ubl2']
if self.h_ref is None: self.h_ref = ipd['h_ref']
if self.h_temp is None: self.h_temp = ipd['h_temp']
if self.h_wind is None: self.h_wind = ipd['h_wind']
if self.c_circ is None: self.c_circ = ipd['c_circ']
if self.c_exch is None: self.c_exch = ipd['c_exch']
if self.maxDay is None: self.maxDay = ipd['maxDay']
if self.maxNight is None: self.maxNight = ipd['maxNight']
if self.windMin is None: self.windMin = ipd['windMin']
if self.h_obs is None: self.h_obs = ipd['h_obs']
# Urban characteristics
if self.bldHeight is None: self.bldHeight = ipd['bldHeight']
if self.h_mix is None: self.h_mix = ipd['h_mix']
if self.bldDensity is None: self.bldDensity = ipd['bldDensity']
if self.verToHor is None: self.verToHor = ipd['verToHor']
if self.charLength is None: self.charLength = ipd['charLength']
if self.alb_road is None: self.alb_road = ipd['albRoad']
if self.d_road is None: self.d_road = ipd['dRoad']
if self.sensAnth is None: self.sensAnth = ipd['sensAnth']
# if self.latAnth is None: self.latAnth = ipd['latAnth'] # Not used, taken out by JH.
# climate Zone
if self.zone is None: self.zone = ipd['zone']
# Vegetation parameters
if self.vegCover is None: self.vegCover = ipd['vegCover']
if self.treeCoverage is None: self.treeCoverage = ipd['treeCoverage']
if self.vegStart is None: self.vegStart = ipd['vegStart']
if self.vegEnd is None: self.vegEnd = ipd['vegEnd']
if self.albVeg is None: self.albVeg = ipd['albVeg']
if self.rurVegCover is None: self.rurVegCover = ipd['rurVegCover']
if self.latGrss is None: self.latGrss = ipd['latGrss']
if self.latTree is None: self.latTree = ipd['latTree']
# Define Traffic schedule
if self.SchTraffic is None: self.SchTraffic = ipd['SchTraffic']
# Define Road (Assume 0.5m of asphalt)
if self.kRoad is None: self.kRoad = ipd['kRoad']
if self.cRoad is None: self.cRoad = ipd['cRoad']
# Building stock fraction
if self.bld is None: self.bld = ipd['bld']
# Optional parameters
if self.albRoof is None: self.albRoof = ipd['albRoof']
if self.vegRoof is None: self.vegRoof = ipd['vegRoof']
if self.glzR is None: self.glzR = ipd['glzR']
if self.albWall is None: self.albWall = ipd['albWall']
if self.SHGC is None: self.SHGC = ipd['SHGC']
def check_required_inputs(self):
# Fail if required parameters aren't correct
assert isinstance(self.Month, (float, int)), \
'Month must be a number. Got {}'.format(type(self.Month))
assert isinstance(self.Day, (float, int)), \
'Day must be a number. Got {}'.format(type(self.Day))
assert isinstance(self.nDay, (float, int)), \
'nDay must be a number. Got {}'.format(type(self.nDay))
assert isinstance(self.dtSim, float), \
'dtSim must be a float. Got {}'.format(type(self.dtSim))
assert isinstance(self.dtWeather, float), \
'dtWeather must be a float. Got {}'.format(type(self.dtWeather))
assert isinstance(self.autosize, (float, int)), \
'autosize must be a number. Got {}'.format(type(self.autosize))
assert isinstance(self.sensOcc, float), \
'sensOcc must be a float. Got {}'.format(type(self.sensOcc))
assert isinstance(self.LatFOcc, float), \
'LatFOcc must be a float. Got {}'.format(type(self.LatFOcc))
assert isinstance(self.RadFOcc, float), \
'RadFOcc must be a float. Got {}'.format(type(self.RadFOcc))
assert isinstance(self.RadFEquip, float), \
'RadFEquip must be a float. Got {}'.format(type(self.RadFEquip))
assert isinstance(self.RadFLight, float), \
'RadFLight must be a float. Got {}'.format(type(self.RadFLight))
assert isinstance(self.h_ubl1, float), \
'h_ubl1 must be a float. Got {}'.format(type(self.h_ubl1))
assert isinstance(self.h_ubl2, float), \
'h_ubl2 must be a float. Got {}'.format(type(self.h_ubl2))
assert isinstance(self.h_ref, float), \
'h_ref must be a float. Got {}'.format(type(self.h_ref))
assert isinstance(self.h_temp, float), \
'h_temp must be a float. Got {}'.format(type(self.h_temp))
assert isinstance(self.h_wind, float), \
'h_wind must be a float. Got {}'.format(type(self.h_wind))
assert isinstance(self.c_circ, float), \
'c_circ must be a float. Got {}'.format(type(self.c_circ))
assert isinstance(self.c_exch, float), \
'c_exch must be a float. Got {}'.format(type(self.c_exch))
assert isinstance(self.maxDay, float), \
'maxDay must be a float. Got {}'.format(type(self.maxDay))
assert isinstance(self.maxNight, float), \
'maxNight must be a float. Got {}'.format(type(self.maxNight))
assert isinstance(self.windMin, float), \
'windMin must be a float. Got {}'.format(type(self.windMin))
assert isinstance(self.h_obs, float), \
'h_obs must be a float. Got {}'.format(type(self.h_obs))
assert isinstance(self.bldHeight, float), \
'bldHeight must be a float. Got {}'.format(type(self.bldHeight))
assert isinstance(self.h_mix, float), \
'h_mix must be a float. Got {}'.format(type(self.h_mix))
assert isinstance(self.bldDensity, float), \
'bldDensity must be a float. Got {}'.format(type(self.bldDensity))
assert isinstance(self.verToHor, float), \
'verToHor must be a float. Got {}'.format(type(self.verToHor))
assert isinstance(self.charLength, float), \
'charLength must be a float. Got {}'.format(type(self.charLength))
assert isinstance(self.alb_road, float), \
'alb_road must be a float. Got {}'.format(type(self.alb_road))
assert isinstance(self.d_road, float), \
'd_road must be a float. Got {}'.format(type(self.d_road))
assert isinstance(self.sensAnth, float), \
'sensAnth must be a float. Got {}'.format(type(self.sensAnth))
# assert isinstance(self.latAnth, float) # Take this out as isn't being used
assert isinstance(self.bld, list), \
'bld must be a list. Got {}'.format(type(self.bld))
assert len(self.bld) == 16, \
'length of bld must be 16. Got {}'.format(len(self.bld))
assert isinstance(self.latTree, float), \
'latTree must be a float. Got {}'.format(type(self.latTree))
assert isinstance(self.latGrss, float), \
'latGrss must be a float. Got {}'.format(type(self.latGrss))
assert isinstance(self.zone, (float, int)), \
'zone must be a number. Got {}'.format(type(self.zone))
assert isinstance(self.vegStart, (float, int)), \
'vegStart must be a number. Got {}'.format(type(self.vegStart))
assert isinstance(self.vegEnd, (float, int)), \
'vegEnd must be a number. Got {}'.format(type(self.vegEnd))
assert isinstance(self.vegCover, float), \
'vegCover must be a float. Got {}'.format(type(self.vegCover))
assert isinstance(self.treeCoverage, float), \
'treeCoverage must be a float. Got {}'.format(type(self.treeCoverage))
assert isinstance(self.albVeg, float), \
'albVeg must be a float. Got {}'.format(type(self.albVeg))
assert isinstance(self.rurVegCover, float), \
'rurVegCover must be a float. Got {}'.format(type(self.rurVegCover))
assert isinstance(self.kRoad, float), \
'kRoad must be a float. Got {}'.format(type(self.kRoad))
assert isinstance(self.cRoad, float), \
'cRoad must be a float. Got {}'.format(type(self.cRoad))
assert isinstance(self.SchTraffic, list), \
'SchTraffic must be a list. Got {}'.format(type(self.SchTraffic))
assert len(self.SchTraffic) == 3, \
'length of SchTraffic must be 3. Got {}'.format(len(self.SchTraffic))
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the .uwg file.
if self.uwgParamFileName is not None:
print("\nReading uwg file input.")
self.read_input()
else:
print("\nNo .uwg file input.")
self.check_required_inputs()
# Modify zone to be used as python index
self.zone = int(self.zone)-1
def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total building stock
"""
if not os.path.exists(self.readDOE_file_path):
raise Exception("readDOE.pkl file: '{}' does not exist.".format(readDOE_file_path))
readDOE_file = open(self.readDOE_file_path, 'rb') # open pickle file in binary form
refDOE = pickle.load(readDOE_file)
refBEM = pickle.load(readDOE_file)
refSchedule = pickle.load(readDOE_file)
readDOE_file.close()
# Define building energy models
k = 0
self.r_glaze_total = 0. # Glazing ratio for total building stock
self.SHGC_total = 0. # SHGC addition for total building stock
self.alb_wall_total = 0. # albedo wall addition for total building stock
h_floor = self.flr_h or 3.05 # average floor height
total_urban_bld_area = math.pow(self.charLength, 2)*self.bldDensity * \
self.bldHeight/h_floor # total building floor area
area_matrix = utilities.zeros(16, 3)
self.BEM = [] # list of BEMDef objects
self.Sch = [] # list of Schedule objects
for i in range(16): # 16 building types
for j in range(3): # 3 built eras
if self.bld[i][j] > 0.:
# Add to BEM list
self.BEM.append(refBEM[i][j][self.zone])
self.BEM[k].frac = self.bld[i][j]
self.BEM[k].fl_area = self.bld[i][j] * total_urban_bld_area
# Overwrite with optional parameters if provided
if self.glzR:
self.BEM[k].building.glazingRatio = self.glzR
if self.albRoof:
self.BEM[k].roof.albedo = self.albRoof
if self.vegRoof:
self.BEM[k].roof.vegCoverage = self.vegRoof
if self.SHGC:
self.BEM[k].building.shgc = self.SHGC
if self.albWall:
self.BEM[k].wall.albedo = self.albWall
if self.flr_h:
self.BEM[k].building.floorHeight = self.flr_h
# Keep track of total urban r_glaze, SHGC, and alb_wall for UCM model
self.r_glaze_total += self.BEM[k].frac * self.BEM[k].building.glazingRatio
self.SHGC_total += self.BEM[k].frac * self.BEM[k].building.shgc
self.alb_wall_total += self.BEM[k].frac * self.BEM[k].wall.albedo
# Add to schedule list
self.Sch.append(refSchedule[i][j][self.zone])
k += 1
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
self.geoParam # geographic parameters obj
self.RSM # Rural site & vertical diffusion model obj
self.USM # Urban site & vertical diffusion model obj
self.UCM # Urban canopy model obj
self.UBL # Urban boundary layer model
self.road # urban road element
self.rural # rural road element
self.soilindex1 # soil index for urban rsoad depth
self.soilindex2 # soil index for rural road depth
self.Sch # list of Schedule objects
"""
climate_file_path = os.path.join(self.epwDir, self.epwFileName)
self.simTime = SimParam(self.dtSim, self.dtWeather, self.Month,
self.Day, self.nDay) # simulation time parametrs
# weather file data for simulation time period
self.weather = Weather(climate_file_path, self.simTime.timeInitial, self.simTime.timeFinal)
self.forcIP = Forcing(self.weather.staTemp, self.weather) # initialized Forcing class
self.forc = Forcing() # empty forcing class
# Initialize geographic Param and Urban Boundary Layer Objects
nightStart = 18. # arbitrary values for begin/end hour for night setpoint
nightEnd = 8.
maxdx = 250. # max dx (m)
self.geoParam = Param(self.h_ubl1, self.h_ubl2, self.h_ref, self.h_temp, self.h_wind, self.c_circ,
self.maxDay, self.maxNight, self.latTree, self.latGrss, self.albVeg, self.vegStart, self.vegEnd,
nightStart, nightEnd, self.windMin, self.WGMAX, self.c_exch, maxdx, self.G, self.CP, self.VK, self.R,
self.RV, self.LV, math.pi, self.SIGMA, self.WATERDENS, self.LVTT, self.TT, self.ESTT, self.CL,
self.CPV, self.B, self.CM, self.COLBURN)
self.UBL = UBLDef(
'C', self.charLength, self.weather.staTemp[0], maxdx, self.geoParam.dayBLHeight, self.geoParam.nightBLHeight)
# Defining road
emis = 0.93
asphalt = Material(self.kRoad, self.cRoad, 'asphalt')
road_T_init = 293.
road_horizontal = 1
# fraction of surface vegetation coverage
road_veg_coverage = min(self.vegCover/(1-self.bldDensity), 1.)
# define road layers
road_layer_num = int(math.ceil(self.d_road/0.05))
# 0.5/0.05 ~ 10 x 1 matrix of 0.05 thickness
thickness_vector = [0.05 for r in range(road_layer_num)]
material_vector = [asphalt for r in range(road_layer_num)]
self.road = Element(self.alb_road, emis, thickness_vector, material_vector, road_veg_coverage,
road_T_init, road_horizontal, name="urban_road")
self.rural = copy.deepcopy(self.road)
self.rural.vegCoverage = self.rurVegCover
self.rural._name = "rural_road"
# Reference site class (also include VDM)
self.RSM = RSMDef(self.lat, self.lon, self.GMT, self.h_obs,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
self.USM = RSMDef(self.lat, self.lon, self.GMT, self.bldHeight/10.,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
T_init = self.weather.staTemp[0]
H_init = self.weather.staHum[0]
self.UCM = UCMDef(self.bldHeight, self.bldDensity, self.verToHor, self.treeCoverage, self.sensAnth, self.latAnth, T_init, H_init,
self.weather.staUmod[0], self.geoParam, self.r_glaze_total, self.SHGC_total, self.alb_wall_total, self.road)
self.UCM.h_mix = self.h_mix
# Define Road Element & buffer to match ground temperature depth
roadMat, newthickness = procMat(self.road, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
roadMat.append(self.SOIL)
self.soilindex1 = i
break
self.road = Element(self.road.albedo, self.road.emissivity, newthickness, roadMat,
self.road.vegCoverage, self.road.layerTemp[0], self.road.horizontal, self.road._name)
# Define Rural Element
ruralMat, newthickness = procMat(self.rural, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
ruralMat.append(self.SOIL)
self.soilindex2 = i
break
self.rural = Element(self.rural.albedo, self.rural.emissivity, newthickness,
ruralMat, self.rural.vegCoverage, self.rural.layerTemp[0], self.rural.horizontal, self.rural._name)
def hvac_autosize(self):
""" Section 6 - HVAC Autosizing (unlimited cooling & heating) """
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999.
def simulate(self):
""" Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# Output of object instance vector
self.WeatherData # Nx1 vector of forc instance
self.UCMData # Nx1 vector of UCM instance
self.UBLData # Nx1 vector of UBL instance
self.RSMData # Nx1 vector of RSM instance
self.USMData # Nx1 vector of USM instance
"""
self.N = int(self.simTime.days * 24) # total number of hours in simulation
n = 0 # weather time step counter
self.ph = self.simTime.dt/3600. # dt (simulation time step) in hours
# Data dump variables
time = range(self.N)
self.WeatherData = [None for x in range(self.N)]
self.UCMData = [None for x in range(self.N)]
self.UBLData = [None for x in range(self.N)]
self.RSMData = [None for x in range(self.N)]
self.USMData = [None for x in range(self.N)]
print('\nSimulating new temperature and humidity values for {} days from {}/{}.\n'.format(
int(self.nDay), int(self.Month), int(self.Day)))
self.logger.info("Start simulation")
for it in range(1, self.simTime.nt, 1): # for every simulation time-step (i.e 5 min) defined by uwg
# Update water temperature (estimated)
if self.nSoil < 3: # correction to original matlab code
# for BUBBLE/CAPITOUL/Singapore only
self.forc.deepTemp = sum(self.forcIP.temp)/float(len(self.forcIP.temp))
self.forc.waterTemp = sum(
self.forcIP.temp)/float(len(self.forcIP.temp)) - 10. # for BUBBLE/CAPITOUL/Singapore only
else:
# soil temperature by depth, by month
self.forc.deepTemp = self.Tsoil[self.soilindex1][self.simTime.month-1]
self.forc.waterTemp = self.Tsoil[2][self.simTime.month-1]
# There's probably a better way to update the weather...
self.simTime.UpdateDate()
self.logger.info("\n{0} m={1}, d={2}, h={3}, s={4}".format(
__name__, self.simTime.month, self.simTime.day, self.simTime.secDay/3600., self.simTime.secDay))
# simulation time increment raised to weather time step
self.ceil_time_step = int(math.ceil(it * self.ph))-1
# minus one to be consistent with forcIP list index
# Updating forcing instance
# horizontal Infrared Radiation Intensity (W m-2)
self.forc.infra = self.forcIP.infra[self.ceil_time_step]
# wind speed (m s-1)
self.forc.wind = max(self.forcIP.wind[self.ceil_time_step], self.geoParam.windMin)
self.forc.uDir = self.forcIP.uDir[self.ceil_time_step] # wind direction
# specific humidty (kg kg-1)
self.forc.hum = self.forcIP.hum[self.ceil_time_step]
self.forc.pres = self.forcIP.pres[self.ceil_time_step] # Pressure (Pa)
self.forc.temp = self.forcIP.temp[self.ceil_time_step] # air temperature (C)
self.forc.rHum = self.forcIP.rHum[self.ceil_time_step] # Relative humidity (%)
self.forc.prec = self.forcIP.prec[self.ceil_time_step] # Precipitation (mm h-1)
# horizontal solar diffuse radiation (W m-2)
self.forc.dif = self.forcIP.dif[self.ceil_time_step]
# normal solar direct radiation (W m-2)
self.forc.dir = self.forcIP.dir[self.ceil_time_step]
# Canyon humidity (absolute) same as rural
self.UCM.canHum = copy.copy(self.forc.hum)
# Update solar flux
self.solar = SolarCalcs(self.UCM, self.BEM, self.simTime,
self.RSM, self.forc, self.geoParam, self.rural)
self.rural, self.UCM, self.BEM = self.solar.solarcalcs()
# Update building & traffic schedule
# Assign day type (1 = weekday, 2 = sat, 3 = sun/other)
if self.is_near_zero(self.simTime.julian % 7):
self.dayType = 3 # Sunday
elif self.is_near_zero(self.simTime.julian % 7 - 6.):
self.dayType = 2 # Saturday
else:
self.dayType = 1 # Weekday
# Update anthropogenic heat load for each hour (building & UCM)
self.UCM.sensAnthrop = self.sensAnth * (self.SchTraffic[self.dayType-1][self.simTime.hourDay])
# Update the energy components for building types defined in initialize.uwg
for i in range(len(self.BEM)):
# Set temperature
self.BEM[i].building.coolSetpointDay = self.Sch[i].Cool[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for cooling
self.BEM[i].building.coolSetpointNight = self.BEM[i].building.coolSetpointDay
self.BEM[i].building.heatSetpointDay = self.Sch[i].Heat[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for heating
self.BEM[i].building.heatSetpointNight = self.BEM[i].building.heatSetpointDay
# Internal Heat Load Schedule (W/m^2 of floor area for Q)
self.BEM[i].Elec = self.Sch[i].Qelec * self.Sch[i].Elec[self.dayType -
1][self.simTime.hourDay] # Qelec x elec fraction for day
self.BEM[i].Light = self.Sch[i].Qlight * self.Sch[i].Light[self.dayType -
1][self.simTime.hourDay] # Qlight x light fraction for day
self.BEM[i].Nocc = self.Sch[i].Nocc * self.Sch[i].Occ[self.dayType -
1][self.simTime.hourDay] # Number of occupants x occ fraction for day
# Sensible Q occupant * fraction occupant sensible Q * number of occupants
self.BEM[i].Qocc = self.sensOcc * (1 - self.LatFOcc) * self.BEM[i].Nocc
# SWH and ventilation schedule
self.BEM[i].SWH = self.Sch[i].Vswh * self.Sch[i].SWH[self.dayType -
1][self.simTime.hourDay] # litres per hour x SWH fraction for day
# m^3/s/m^2 of floor
self.BEM[i].building.vent = self.Sch[i].Vent
self.BEM[i].Gas = self.Sch[i].Qgas * self.Sch[i].Gas[self.dayType -
1][self.simTime.hourDay] # Gas Equip Schedule, per m^2 of floor
# This is quite messy, should update
# Update internal heat and corresponding fractional loads
intHeat = self.BEM[i].Light + self.BEM[i].Elec + self.BEM[i].Qocc
# W/m2 from light, electricity, occupants
self.BEM[i].building.intHeatDay = intHeat
self.BEM[i].building.intHeatNight = intHeat
# fraction of radiant heat from light and equipment of whole internal heat
self.BEM[i].building.intHeatFRad = (
self.RadFLight * self.BEM[i].Light + self.RadFEquip * self.BEM[i].Elec) / intHeat
# fraction of latent heat (from occupants) of whole internal heat
self.BEM[i].building.intHeatFLat = self.LatFOcc * \
self.sensOcc * self.BEM[i].Nocc/intHeat
# Update envelope temperature layers
self.BEM[i].T_wallex = self.BEM[i].wall.layerTemp[0]
self.BEM[i].T_wallin = self.BEM[i].wall.layerTemp[-1]
self.BEM[i].T_roofex = self.BEM[i].roof.layerTemp[0]
self.BEM[i].T_roofin = self.BEM[i].roof.layerTemp[-1]
# Update rural heat fluxes & update vertical diffusion model (VDM)
self.rural.infra = self.forc.infra - self.rural.emissivity * self.SIGMA * \
self.rural.layerTemp[0]**4. # Infrared radiation from rural road
self.rural.SurfFlux(self.forc, self.geoParam, self.simTime,
self.forc.hum, self.forc.temp, self.forc.wind, 2., 0.)
self.RSM.VDM(self.forc, self.rural, self.geoParam, self.simTime)
# Calculate urban heat fluxes, update UCM & UBL
self.UCM, self.UBL, self.BEM = urbflux(
self.UCM, self.UBL, self.BEM, self.forc, self.geoParam, self.simTime, self.RSM)
self.UCM.UCModel(self.BEM, self.UBL.ublTemp, self.forc, self.geoParam)
self.UBL.UBLModel(self.UCM, self.RSM, self.rural,
self.forc, self.geoParam, self.simTime)
"""
# Experimental code to run diffusion model in the urban area
# N.B Commented out in python uwg because computed wind speed in
# urban VDM: y = =0.84*ln((2-x/20)/0.51) results in negative log
# for building heights >= 40m.
Uroad = copy.copy(self.UCM.road)
Uroad.sens = copy.copy(self.UCM.sensHeat)
Uforc = copy.copy(self.forc)
Uforc.wind = copy.copy(self.UCM.canWind)
Uforc.temp = copy.copy(self.UCM.canTemp)
self.USM.VDM(Uforc,Uroad,self.geoParam,self.simTime)
"""
self.logger.info("dbT = {}".format(self.UCM.canTemp-273.15))
if n > 0:
logging.info("dpT = {}".format(self.UCM.Tdp))
logging.info("RH = {}".format(self.UCM.canRHum))
if self.is_near_zero(self.simTime.secDay % self.simTime.timePrint) and n < self.N:
self.logger.info("{0} ----sim time step = {1}----\n\n".format(__name__, n))
self.WeatherData[n] = copy.copy(self.forc)
_Tdb, _w, self.UCM.canRHum, _h, self.UCM.Tdp, _v = psychrometrics(
self.UCM.canTemp, self.UCM.canHum, self.forc.pres)
self.UBLData[n] = copy.copy(self.UBL)
self.UCMData[n] = copy.copy(self.UCM)
self.RSMData[n] = copy.copy(self.RSM)
self.logger.info("dbT = {}".format(self.UCMData[n].canTemp-273.15))
self.logger.info("dpT = {}".format(self.UCMData[n].Tdp))
self.logger.info("RH = {}".format(self.UCMData[n].canRHum))
n += 1
def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] = column data of epw
self.epwinput[iJ+self.simTime.timeInitial-8][6] = "{0:.{1}f}".format(
self.UCMData[iJ].canTemp - 273.15, epw_prec) # dry bulb temperature [?C]
# dew point temperature [?C]
self.epwinput[iJ+self.simTime.timeInitial -
8][7] = "{0:.{1}f}".format(self.UCMData[iJ].Tdp, epw_prec)
# relative humidity [%]
self.epwinput[iJ+self.simTime.timeInitial -
8][8] = "{0:.{1}f}".format(self.UCMData[iJ].canRHum, epw_prec)
self.epwinput[iJ+self.simTime.timeInitial-8][21] = "{0:.{1}f}".format(
self.WeatherData[iJ].wind, epw_prec) # wind speed [m/s]
# Writing new EPW file
epw_new_id = open(self.newPathName, "w")
for i in range(8):
new_epw_line = '{}\n'.format(reduce(lambda x, y: x+","+y, self._header[i]))
epw_new_id.write(new_epw_line)
for i in range(len(self.epwinput)):
printme = ""
for ei in range(34):
printme += "{}".format(self.epwinput[i][ei]) + ','
printme = printme + "{}".format(self.epwinput[i][ei])
new_epw_line = "{0}\n".format(printme)
epw_new_id.write(new_epw_line)
epw_new_id.close()
print("New climate file '{}' is generated at {}.".format(
self.destinationFileName, self.destinationDir))
def run(self):
# run main class methods
self.read_epw()
self.set_input()
self.init_BEM_obj()
self.init_input_obj()
self.hvac_autosize()
self.simulate()
self.write_epw()
|
ladybug-tools/uwg | uwg/uwg.py | uwg.read_input | python | def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic # Traffice schedule
self.BEM # list of BEMDef objects extracted from readDOE
self.Sch # list of Schedule objects extracted from readDOE
"""
uwg_param_file_path = os.path.join(self.uwgParamDir, self.uwgParamFileName)
if not os.path.exists(uwg_param_file_path):
raise Exception("Param file: '{}' does not exist.".format(uwg_param_file_path))
# Open .uwg file and feed csv data to initializeDataFile
try:
uwg_param_data = utilities.read_csv(uwg_param_file_path)
except Exception as e:
raise Exception("Failed to read .uwg file! {}".format(e.message))
# The initialize.uwg is read with a dictionary so that users changing
# line endings or line numbers doesn't make reading input incorrect
self._init_param_dict = {}
count = 0
while count < len(uwg_param_data):
row = uwg_param_data[count]
row = [row[i].replace(" ", "") for i in range(len(row))] # strip white spaces
# Optional parameters might be empty so handle separately
is_optional_parameter = (
row != [] and
(
row[0] == "albRoof" or
row[0] == "vegRoof" or
row[0] == "glzR" or
row[0] == "hvac" or
row[0] == "albWall" or
row[0] == "SHGC"
)
)
try:
if row == [] or "#" in row[0]:
count += 1
continue
elif row[0] == "SchTraffic":
# SchTraffic: 3 x 24 matrix
trafficrows = uwg_param_data[count+1:count+4]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:24]) for r in trafficrows]
count += 4
elif row[0] == "bld":
# bld: 17 x 3 matrix
bldrows = uwg_param_data[count+1:count+17]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:3]) for r in bldrows]
count += 17
elif is_optional_parameter:
self._init_param_dict[row[0]] = float(row[1]) if row[1] != "" else None
count += 1
else:
self._init_param_dict[row[0]] = float(row[1])
count += 1
except ValueError:
print("Error while reading parameter at {} {}".format(count, row))
ipd = self._init_param_dict
# Define Simulation and Weather parameters
if self.Month is None: self.Month = ipd['Month']
if self.Day is None: self.Day = ipd['Day']
if self.nDay is None: self.nDay = ipd['nDay']
if self.dtSim is None: self.dtSim = ipd['dtSim']
if self.dtWeather is None: self.dtWeather = ipd['dtWeather']
# HVAC system and internal laod
if self.autosize is None: self.autosize = ipd['autosize']
if self.sensOcc is None: self.sensOcc = ipd['sensOcc']
if self.LatFOcc is None: self.LatFOcc = ipd['LatFOcc']
if self.RadFOcc is None: self.RadFOcc = ipd['RadFOcc']
if self.RadFEquip is None: self.RadFEquip = ipd['RadFEquip']
if self.RadFLight is None: self.RadFLight = ipd['RadFLight']
# Define Urban microclimate parameters
if self.h_ubl1 is None: self.h_ubl1 = ipd['h_ubl1']
if self.h_ubl2 is None: self.h_ubl2 = ipd['h_ubl2']
if self.h_ref is None: self.h_ref = ipd['h_ref']
if self.h_temp is None: self.h_temp = ipd['h_temp']
if self.h_wind is None: self.h_wind = ipd['h_wind']
if self.c_circ is None: self.c_circ = ipd['c_circ']
if self.c_exch is None: self.c_exch = ipd['c_exch']
if self.maxDay is None: self.maxDay = ipd['maxDay']
if self.maxNight is None: self.maxNight = ipd['maxNight']
if self.windMin is None: self.windMin = ipd['windMin']
if self.h_obs is None: self.h_obs = ipd['h_obs']
# Urban characteristics
if self.bldHeight is None: self.bldHeight = ipd['bldHeight']
if self.h_mix is None: self.h_mix = ipd['h_mix']
if self.bldDensity is None: self.bldDensity = ipd['bldDensity']
if self.verToHor is None: self.verToHor = ipd['verToHor']
if self.charLength is None: self.charLength = ipd['charLength']
if self.alb_road is None: self.alb_road = ipd['albRoad']
if self.d_road is None: self.d_road = ipd['dRoad']
if self.sensAnth is None: self.sensAnth = ipd['sensAnth']
# if self.latAnth is None: self.latAnth = ipd['latAnth'] # Not used, taken out by JH.
# climate Zone
if self.zone is None: self.zone = ipd['zone']
# Vegetation parameters
if self.vegCover is None: self.vegCover = ipd['vegCover']
if self.treeCoverage is None: self.treeCoverage = ipd['treeCoverage']
if self.vegStart is None: self.vegStart = ipd['vegStart']
if self.vegEnd is None: self.vegEnd = ipd['vegEnd']
if self.albVeg is None: self.albVeg = ipd['albVeg']
if self.rurVegCover is None: self.rurVegCover = ipd['rurVegCover']
if self.latGrss is None: self.latGrss = ipd['latGrss']
if self.latTree is None: self.latTree = ipd['latTree']
# Define Traffic schedule
if self.SchTraffic is None: self.SchTraffic = ipd['SchTraffic']
# Define Road (Assume 0.5m of asphalt)
if self.kRoad is None: self.kRoad = ipd['kRoad']
if self.cRoad is None: self.cRoad = ipd['cRoad']
# Building stock fraction
if self.bld is None: self.bld = ipd['bld']
# Optional parameters
if self.albRoof is None: self.albRoof = ipd['albRoof']
if self.vegRoof is None: self.vegRoof = ipd['vegRoof']
if self.glzR is None: self.glzR = ipd['glzR']
if self.albWall is None: self.albWall = ipd['albWall']
if self.SHGC is None: self.SHGC = ipd['SHGC'] | Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic # Traffice schedule
self.BEM # list of BEMDef objects extracted from readDOE
self.Sch # list of Schedule objects extracted from readDOE | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/uwg.py#L299-L436 | [
"def read_csv(file_name_):\n # open csv file and read\n if os.path.exists(file_name_):\n if sys.version_info[0] >= 3:\n file_ = open(file_name_, \"r\", errors='ignore')\n else:\n file_ = open(file_name_, \"r\")\n\n gen_ = csv_reader(file_, delimiter=\",\")\n L = [r for r in gen_]\n file_.close()\n return L\n else:\n raise Exception(\"File name: '{}' does not exist.\".format(file_name_))\n"
] | class uwg(object):
"""Morph a rural EPW file to urban conditions using a file with a list of urban parameters.
args:
epwDir: The directory in which the rural EPW file sits.
epwFileName: The name of the rural epw file that will be morphed.
uwgParamDir: The directory in which the uwg Parameter File (.uwg) sits.
uwgParamFileName: The name of the uwg Parameter File (.uwg).
destinationDir: Optional destination directory for the morphed EPW file.
If left blank, the morphed file will be written into the same directory
as the rural EPW file (the epwDir).
destinationFileName: Optional destination file name for the morphed EPW file.
If left blank, the morphed file will append "_UWG" to the original file name.
returns:
newClimateFile: the path to a new EPW file that has been morphed to account
for uban conditions.
"""
""" Section 1 - Definitions for constants / other parameters """
MINTHICKNESS = 0.01 # Minimum layer thickness (to prevent crashing) (m)
MAXTHICKNESS = 0.05 # Maximum layer thickness (m)
# http://web.mit.edu/parmstr/Public/NRCan/nrcc29118.pdf (Figly & Snodgrass)
SOILTCOND = 1
# http://www.europment.org/library/2013/venice/bypaper/MFHEEF/MFHEEF-21.pdf (average taken from Table 1)
SOILVOLHEAT = 2e6
# Soil material used for soil-depth padding
SOIL = Material(SOILTCOND, SOILVOLHEAT, name="soil")
# Physical constants
G = 9.81 # gravity (m s-2)
CP = 1004. # heat capacity for air (J/kg K)
VK = 0.40 # von karman constant (dimensionless)
R = 287. # gas constant dry air (J/kg K)
RV = 461.5 # gas constant water vapor (J/kg K)
LV = 2.26e6 # latent heat of evaporation (J/kg)
SIGMA = 5.67e-08 # Stefan Boltzmann constant (W m-2 K-4)
WATERDENS = 1000. # water density (kg m-3)
LVTT = 2.5008e6 #
TT = 273.16 #
ESTT = 611.14 #
CL = 4.218e3 #
CPV = 1846.1 #
B = 9.4 # Coefficients derived by Louis (1979)
CM = 7.4 #
# (Pr/Sc)^(2/3) for Colburn analogy in water evaporation
COLBURN = math.pow((0.713/0.621), (2/3.))
# Site-specific parameters
WGMAX = 0.005 # maximum film water depth on horizontal surfaces (m)
# File path parameter
RESOURCE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "resources"))
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
def __init__(self, epwFileName, uwgParamFileName=None, epwDir=None, uwgParamDir=None, destinationDir=None, destinationFileName=None):
# Logger will be disabled by default unless explicitly called in tests
self.logger = logging.getLogger(__name__)
# User defined
self.epwFileName = epwFileName if epwFileName.lower().endswith('.epw') else epwFileName + \
'.epw' # Revise epw file name if not end with epw
# If file name is entered then will uwg will set input from .uwg file
self.uwgParamFileName = uwgParamFileName
# If user does not overload
self.destinationFileName = destinationFileName if destinationFileName else self.epwFileName.strip(
'.epw') + '_UWG.epw'
self.epwDir = epwDir if epwDir else os.path.join(self.RESOURCE_PATH, "epw")
self.uwgParamDir = uwgParamDir if uwgParamDir else os.path.join(
self.RESOURCE_PATH, "parameters")
self.destinationDir = destinationDir if destinationDir else os.path.join(
self.RESOURCE_PATH, "epw_uwg")
# refdata: Serialized DOE reference data, z_meso height data
self.readDOE_file_path = os.path.join(self.CURRENT_PATH, "refdata", "readDOE.pkl")
self.z_meso_dir_path = os.path.join(self.CURRENT_PATH, "refdata")
# EPW precision
self.epw_precision = 1
# init uwg variables
self._init_param_dict = None
# Define Simulation and Weather parameters
self.Month = None # starting month (1-12)
self.Day = None # starting day (1-31)
self.nDay = None # number of days
self.dtSim = None # simulation time step (s)
self.dtWeather = None # seconds (s)
# HVAC system and internal laod
self.autosize = None # autosize HVAC (1 or 0)
self.sensOcc = None # Sensible heat from occupant
self.LatFOcc = None # Latent heat fraction from occupant (normally 0.3)
self.RadFOcc = None # Radiant heat fraction from occupant (normally 0.2)
self.RadFEquip = None # Radiant heat fraction from equipment (normally 0.5)
self.RadFLight = None # Radiant heat fraction from light (normally 0.7)
# Define Urban microclimate parameters
self.h_ubl1 = None # ubl height - day (m)
self.h_ubl2 = None # ubl height - night (m)
self.h_ref = None # inversion height
self.h_temp = None # temperature height
self.h_wind = None # wind height
self.c_circ = None # circulation coefficient
self.c_exch = None # exchange coefficient
self.maxDay = None # max day threshhold
self.maxNight = None # max night threshhold
self.windMin = None # min wind speed (m/s)
self.h_obs = None # rural average obstacle height
# Urban characteristics
self.bldHeight = None # average building height (m)
self.h_mix = None # mixing height (m)
self.bldDensity = None # building density (0-1)
self.verToHor = None # building aspect ratio
# radius defining the urban area of study [aka. characteristic length] (m)
self.charLength = None
self.alb_road = None # road albedo
self.d_road = None # road pavement thickness
self.sensAnth = None # non-building sensible heat (W/m^2)
self.latAnth = None # non-building latent heat heat (W/m^2). Not used, taken out by JH.
# Fraction of building typology stock
self.bld = None # 16x3 matrix of fraction of building type by era
# climate Zone
self.zone = None
# Vegetation parameters
self.vegCover = None # urban area veg coverage ratio
self.treeCoverage = None # urban area tree coverage ratio
self.vegStart = None # vegetation start month
self.vegEnd = None # vegetation end month
self.albVeg = None # Vegetation albedo
self.rurVegCover = None # rural vegetation cover
self.latGrss = None # latent fraction of grass
self.latTree = None # latent fraction of tree
# Define Traffic schedule
self.SchTraffic = None
# Define Road (Assume 0.5m of asphalt)
self.kRoad = None # road pavement conductivity (W/m K)
self.cRoad = None # road volumetric heat capacity (J/m^3 K)
# Define optional Building characteristics
self.flr_h = None # floor-to-floor height
self.albRoof = None # roof albedo (0 - 1)
self.vegRoof = None # Fraction of the roofs covered in grass/shrubs (0-1)
self.glzR = None # Glazing Ratio
self.SHGC = None # Solar Heat Gain Coefficient
self.albWall = None # Wall albedo
def ToString(self):
"""Overwrite .NET ToString method."""
return self.__repr__()
def __repr__(self):
def _split_string(s):
return s[0] + ":\n " + s[1].replace(",", "\n ")
def _tabbed(s):
return _split_string(s.__repr__().split(":"))
def _list_2_tabbed(b):
return reduce(lambda a, b: a+"\n"+b, [_tabbed(_b) for _b in b])
return "uwg for {}:\n\n{}{}{}{}{}{}{}{}".format(
self.epwFileName,
_tabbed(self.simTime)+"\n" if hasattr(self, "simTime") else "No simTime attr.\n",
_tabbed(self.weather)+"\n" if hasattr(self, "weather") else "No weather attr.\n",
_tabbed(self.geoParam)+"\n" if hasattr(self, "geoParam") else "No geoParam attr.\n",
_tabbed(self.UBL)+"\n" if hasattr(self, "UBL") else "No UBL attr.\n",
"Rural "+_tabbed(self.RSM)+"\n" if hasattr(self, "RSM") else "No Rural RSM attr.\n",
"Urban "+_tabbed(self.USM)+"\n" if hasattr(self, "USM") else "No Urban RSM attr.\n",
_tabbed(self.UCM)+"\n" if hasattr(self, "UCM") else "No UCM attr.\n",
_list_2_tabbed(self.BEM) if hasattr(self, "BEM") else "No BEM attr."
)
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def read_epw(self):
"""Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT # GMT
self.nSoil # Number of soil depths
self.Tsoil # nSoil x 12 matrix for soil temperture (K)
self.depth_soil # nSoil x 1 matrix for soil depth (m)
"""
# Make dir path to epw file
self.climateDataPath = os.path.join(self.epwDir, self.epwFileName)
# Open epw file and feed csv data to climate_data
try:
climate_data = utilities.read_csv(self.climateDataPath)
except Exception as e:
raise Exception("Failed to read epw file! {}".format(e.message))
# Read header lines (1 to 8) from EPW and ensure TMY2 format.
self._header = climate_data[0:8]
# Read weather data from EPW for each time step in weather file. (lines 8 - end)
self.epwinput = climate_data[8:]
# Read Lat, Long (line 1 of EPW)
self.lat = float(self._header[0][6])
self.lon = float(self._header[0][7])
self.GMT = float(self._header[0][8])
# Read in soil temperature data (assumes this is always there)
# ref: http://bigladdersoftware.com/epx/docs/8-2/auxiliary-programs/epw-csv-format-inout.html
soilData = self._header[3]
self.nSoil = int(soilData[1]) # Number of ground temperature depths
self.Tsoil = utilities.zeros(self.nSoil, 12) # nSoil x 12 matrix for soil temperture (K)
self.depth_soil = utilities.zeros(self.nSoil, 1) # nSoil x 1 matrix for soil depth (m)
# Read monthly data for each layer of soil from EPW file
for i in range(self.nSoil):
self.depth_soil[i][0] = float(soilData[2 + (i*16)]) # get soil depth for each nSoil
# Monthly data
for j in range(12):
# 12 months of soil T for specific depth
self.Tsoil[i][j] = float(soilData[6 + (i*16) + j]) + 273.15
# Set new directory path for the moprhed EPW file
self.newPathName = os.path.join(self.destinationDir, self.destinationFileName)
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic # Traffice schedule
self.BEM # list of BEMDef objects extracted from readDOE
self.Sch # list of Schedule objects extracted from readDOE
"""
uwg_param_file_path = os.path.join(self.uwgParamDir, self.uwgParamFileName)
if not os.path.exists(uwg_param_file_path):
raise Exception("Param file: '{}' does not exist.".format(uwg_param_file_path))
# Open .uwg file and feed csv data to initializeDataFile
try:
uwg_param_data = utilities.read_csv(uwg_param_file_path)
except Exception as e:
raise Exception("Failed to read .uwg file! {}".format(e.message))
# The initialize.uwg is read with a dictionary so that users changing
# line endings or line numbers doesn't make reading input incorrect
self._init_param_dict = {}
count = 0
while count < len(uwg_param_data):
row = uwg_param_data[count]
row = [row[i].replace(" ", "") for i in range(len(row))] # strip white spaces
# Optional parameters might be empty so handle separately
is_optional_parameter = (
row != [] and
(
row[0] == "albRoof" or
row[0] == "vegRoof" or
row[0] == "glzR" or
row[0] == "hvac" or
row[0] == "albWall" or
row[0] == "SHGC"
)
)
try:
if row == [] or "#" in row[0]:
count += 1
continue
elif row[0] == "SchTraffic":
# SchTraffic: 3 x 24 matrix
trafficrows = uwg_param_data[count+1:count+4]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:24]) for r in trafficrows]
count += 4
elif row[0] == "bld":
# bld: 17 x 3 matrix
bldrows = uwg_param_data[count+1:count+17]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:3]) for r in bldrows]
count += 17
elif is_optional_parameter:
self._init_param_dict[row[0]] = float(row[1]) if row[1] != "" else None
count += 1
else:
self._init_param_dict[row[0]] = float(row[1])
count += 1
except ValueError:
print("Error while reading parameter at {} {}".format(count, row))
ipd = self._init_param_dict
# Define Simulation and Weather parameters
if self.Month is None: self.Month = ipd['Month']
if self.Day is None: self.Day = ipd['Day']
if self.nDay is None: self.nDay = ipd['nDay']
if self.dtSim is None: self.dtSim = ipd['dtSim']
if self.dtWeather is None: self.dtWeather = ipd['dtWeather']
# HVAC system and internal laod
if self.autosize is None: self.autosize = ipd['autosize']
if self.sensOcc is None: self.sensOcc = ipd['sensOcc']
if self.LatFOcc is None: self.LatFOcc = ipd['LatFOcc']
if self.RadFOcc is None: self.RadFOcc = ipd['RadFOcc']
if self.RadFEquip is None: self.RadFEquip = ipd['RadFEquip']
if self.RadFLight is None: self.RadFLight = ipd['RadFLight']
# Define Urban microclimate parameters
if self.h_ubl1 is None: self.h_ubl1 = ipd['h_ubl1']
if self.h_ubl2 is None: self.h_ubl2 = ipd['h_ubl2']
if self.h_ref is None: self.h_ref = ipd['h_ref']
if self.h_temp is None: self.h_temp = ipd['h_temp']
if self.h_wind is None: self.h_wind = ipd['h_wind']
if self.c_circ is None: self.c_circ = ipd['c_circ']
if self.c_exch is None: self.c_exch = ipd['c_exch']
if self.maxDay is None: self.maxDay = ipd['maxDay']
if self.maxNight is None: self.maxNight = ipd['maxNight']
if self.windMin is None: self.windMin = ipd['windMin']
if self.h_obs is None: self.h_obs = ipd['h_obs']
# Urban characteristics
if self.bldHeight is None: self.bldHeight = ipd['bldHeight']
if self.h_mix is None: self.h_mix = ipd['h_mix']
if self.bldDensity is None: self.bldDensity = ipd['bldDensity']
if self.verToHor is None: self.verToHor = ipd['verToHor']
if self.charLength is None: self.charLength = ipd['charLength']
if self.alb_road is None: self.alb_road = ipd['albRoad']
if self.d_road is None: self.d_road = ipd['dRoad']
if self.sensAnth is None: self.sensAnth = ipd['sensAnth']
# if self.latAnth is None: self.latAnth = ipd['latAnth'] # Not used, taken out by JH.
# climate Zone
if self.zone is None: self.zone = ipd['zone']
# Vegetation parameters
if self.vegCover is None: self.vegCover = ipd['vegCover']
if self.treeCoverage is None: self.treeCoverage = ipd['treeCoverage']
if self.vegStart is None: self.vegStart = ipd['vegStart']
if self.vegEnd is None: self.vegEnd = ipd['vegEnd']
if self.albVeg is None: self.albVeg = ipd['albVeg']
if self.rurVegCover is None: self.rurVegCover = ipd['rurVegCover']
if self.latGrss is None: self.latGrss = ipd['latGrss']
if self.latTree is None: self.latTree = ipd['latTree']
# Define Traffic schedule
if self.SchTraffic is None: self.SchTraffic = ipd['SchTraffic']
# Define Road (Assume 0.5m of asphalt)
if self.kRoad is None: self.kRoad = ipd['kRoad']
if self.cRoad is None: self.cRoad = ipd['cRoad']
# Building stock fraction
if self.bld is None: self.bld = ipd['bld']
# Optional parameters
if self.albRoof is None: self.albRoof = ipd['albRoof']
if self.vegRoof is None: self.vegRoof = ipd['vegRoof']
if self.glzR is None: self.glzR = ipd['glzR']
if self.albWall is None: self.albWall = ipd['albWall']
if self.SHGC is None: self.SHGC = ipd['SHGC']
def check_required_inputs(self):
# Fail if required parameters aren't correct
assert isinstance(self.Month, (float, int)), \
'Month must be a number. Got {}'.format(type(self.Month))
assert isinstance(self.Day, (float, int)), \
'Day must be a number. Got {}'.format(type(self.Day))
assert isinstance(self.nDay, (float, int)), \
'nDay must be a number. Got {}'.format(type(self.nDay))
assert isinstance(self.dtSim, float), \
'dtSim must be a float. Got {}'.format(type(self.dtSim))
assert isinstance(self.dtWeather, float), \
'dtWeather must be a float. Got {}'.format(type(self.dtWeather))
assert isinstance(self.autosize, (float, int)), \
'autosize must be a number. Got {}'.format(type(self.autosize))
assert isinstance(self.sensOcc, float), \
'sensOcc must be a float. Got {}'.format(type(self.sensOcc))
assert isinstance(self.LatFOcc, float), \
'LatFOcc must be a float. Got {}'.format(type(self.LatFOcc))
assert isinstance(self.RadFOcc, float), \
'RadFOcc must be a float. Got {}'.format(type(self.RadFOcc))
assert isinstance(self.RadFEquip, float), \
'RadFEquip must be a float. Got {}'.format(type(self.RadFEquip))
assert isinstance(self.RadFLight, float), \
'RadFLight must be a float. Got {}'.format(type(self.RadFLight))
assert isinstance(self.h_ubl1, float), \
'h_ubl1 must be a float. Got {}'.format(type(self.h_ubl1))
assert isinstance(self.h_ubl2, float), \
'h_ubl2 must be a float. Got {}'.format(type(self.h_ubl2))
assert isinstance(self.h_ref, float), \
'h_ref must be a float. Got {}'.format(type(self.h_ref))
assert isinstance(self.h_temp, float), \
'h_temp must be a float. Got {}'.format(type(self.h_temp))
assert isinstance(self.h_wind, float), \
'h_wind must be a float. Got {}'.format(type(self.h_wind))
assert isinstance(self.c_circ, float), \
'c_circ must be a float. Got {}'.format(type(self.c_circ))
assert isinstance(self.c_exch, float), \
'c_exch must be a float. Got {}'.format(type(self.c_exch))
assert isinstance(self.maxDay, float), \
'maxDay must be a float. Got {}'.format(type(self.maxDay))
assert isinstance(self.maxNight, float), \
'maxNight must be a float. Got {}'.format(type(self.maxNight))
assert isinstance(self.windMin, float), \
'windMin must be a float. Got {}'.format(type(self.windMin))
assert isinstance(self.h_obs, float), \
'h_obs must be a float. Got {}'.format(type(self.h_obs))
assert isinstance(self.bldHeight, float), \
'bldHeight must be a float. Got {}'.format(type(self.bldHeight))
assert isinstance(self.h_mix, float), \
'h_mix must be a float. Got {}'.format(type(self.h_mix))
assert isinstance(self.bldDensity, float), \
'bldDensity must be a float. Got {}'.format(type(self.bldDensity))
assert isinstance(self.verToHor, float), \
'verToHor must be a float. Got {}'.format(type(self.verToHor))
assert isinstance(self.charLength, float), \
'charLength must be a float. Got {}'.format(type(self.charLength))
assert isinstance(self.alb_road, float), \
'alb_road must be a float. Got {}'.format(type(self.alb_road))
assert isinstance(self.d_road, float), \
'd_road must be a float. Got {}'.format(type(self.d_road))
assert isinstance(self.sensAnth, float), \
'sensAnth must be a float. Got {}'.format(type(self.sensAnth))
# assert isinstance(self.latAnth, float) # Take this out as isn't being used
assert isinstance(self.bld, list), \
'bld must be a list. Got {}'.format(type(self.bld))
assert len(self.bld) == 16, \
'length of bld must be 16. Got {}'.format(len(self.bld))
assert isinstance(self.latTree, float), \
'latTree must be a float. Got {}'.format(type(self.latTree))
assert isinstance(self.latGrss, float), \
'latGrss must be a float. Got {}'.format(type(self.latGrss))
assert isinstance(self.zone, (float, int)), \
'zone must be a number. Got {}'.format(type(self.zone))
assert isinstance(self.vegStart, (float, int)), \
'vegStart must be a number. Got {}'.format(type(self.vegStart))
assert isinstance(self.vegEnd, (float, int)), \
'vegEnd must be a number. Got {}'.format(type(self.vegEnd))
assert isinstance(self.vegCover, float), \
'vegCover must be a float. Got {}'.format(type(self.vegCover))
assert isinstance(self.treeCoverage, float), \
'treeCoverage must be a float. Got {}'.format(type(self.treeCoverage))
assert isinstance(self.albVeg, float), \
'albVeg must be a float. Got {}'.format(type(self.albVeg))
assert isinstance(self.rurVegCover, float), \
'rurVegCover must be a float. Got {}'.format(type(self.rurVegCover))
assert isinstance(self.kRoad, float), \
'kRoad must be a float. Got {}'.format(type(self.kRoad))
assert isinstance(self.cRoad, float), \
'cRoad must be a float. Got {}'.format(type(self.cRoad))
assert isinstance(self.SchTraffic, list), \
'SchTraffic must be a list. Got {}'.format(type(self.SchTraffic))
assert len(self.SchTraffic) == 3, \
'length of SchTraffic must be 3. Got {}'.format(len(self.SchTraffic))
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the .uwg file.
if self.uwgParamFileName is not None:
print("\nReading uwg file input.")
self.read_input()
else:
print("\nNo .uwg file input.")
self.check_required_inputs()
# Modify zone to be used as python index
self.zone = int(self.zone)-1
def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total building stock
"""
if not os.path.exists(self.readDOE_file_path):
raise Exception("readDOE.pkl file: '{}' does not exist.".format(readDOE_file_path))
readDOE_file = open(self.readDOE_file_path, 'rb') # open pickle file in binary form
refDOE = pickle.load(readDOE_file)
refBEM = pickle.load(readDOE_file)
refSchedule = pickle.load(readDOE_file)
readDOE_file.close()
# Define building energy models
k = 0
self.r_glaze_total = 0. # Glazing ratio for total building stock
self.SHGC_total = 0. # SHGC addition for total building stock
self.alb_wall_total = 0. # albedo wall addition for total building stock
h_floor = self.flr_h or 3.05 # average floor height
total_urban_bld_area = math.pow(self.charLength, 2)*self.bldDensity * \
self.bldHeight/h_floor # total building floor area
area_matrix = utilities.zeros(16, 3)
self.BEM = [] # list of BEMDef objects
self.Sch = [] # list of Schedule objects
for i in range(16): # 16 building types
for j in range(3): # 3 built eras
if self.bld[i][j] > 0.:
# Add to BEM list
self.BEM.append(refBEM[i][j][self.zone])
self.BEM[k].frac = self.bld[i][j]
self.BEM[k].fl_area = self.bld[i][j] * total_urban_bld_area
# Overwrite with optional parameters if provided
if self.glzR:
self.BEM[k].building.glazingRatio = self.glzR
if self.albRoof:
self.BEM[k].roof.albedo = self.albRoof
if self.vegRoof:
self.BEM[k].roof.vegCoverage = self.vegRoof
if self.SHGC:
self.BEM[k].building.shgc = self.SHGC
if self.albWall:
self.BEM[k].wall.albedo = self.albWall
if self.flr_h:
self.BEM[k].building.floorHeight = self.flr_h
# Keep track of total urban r_glaze, SHGC, and alb_wall for UCM model
self.r_glaze_total += self.BEM[k].frac * self.BEM[k].building.glazingRatio
self.SHGC_total += self.BEM[k].frac * self.BEM[k].building.shgc
self.alb_wall_total += self.BEM[k].frac * self.BEM[k].wall.albedo
# Add to schedule list
self.Sch.append(refSchedule[i][j][self.zone])
k += 1
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
self.geoParam # geographic parameters obj
self.RSM # Rural site & vertical diffusion model obj
self.USM # Urban site & vertical diffusion model obj
self.UCM # Urban canopy model obj
self.UBL # Urban boundary layer model
self.road # urban road element
self.rural # rural road element
self.soilindex1 # soil index for urban rsoad depth
self.soilindex2 # soil index for rural road depth
self.Sch # list of Schedule objects
"""
climate_file_path = os.path.join(self.epwDir, self.epwFileName)
self.simTime = SimParam(self.dtSim, self.dtWeather, self.Month,
self.Day, self.nDay) # simulation time parametrs
# weather file data for simulation time period
self.weather = Weather(climate_file_path, self.simTime.timeInitial, self.simTime.timeFinal)
self.forcIP = Forcing(self.weather.staTemp, self.weather) # initialized Forcing class
self.forc = Forcing() # empty forcing class
# Initialize geographic Param and Urban Boundary Layer Objects
nightStart = 18. # arbitrary values for begin/end hour for night setpoint
nightEnd = 8.
maxdx = 250. # max dx (m)
self.geoParam = Param(self.h_ubl1, self.h_ubl2, self.h_ref, self.h_temp, self.h_wind, self.c_circ,
self.maxDay, self.maxNight, self.latTree, self.latGrss, self.albVeg, self.vegStart, self.vegEnd,
nightStart, nightEnd, self.windMin, self.WGMAX, self.c_exch, maxdx, self.G, self.CP, self.VK, self.R,
self.RV, self.LV, math.pi, self.SIGMA, self.WATERDENS, self.LVTT, self.TT, self.ESTT, self.CL,
self.CPV, self.B, self.CM, self.COLBURN)
self.UBL = UBLDef(
'C', self.charLength, self.weather.staTemp[0], maxdx, self.geoParam.dayBLHeight, self.geoParam.nightBLHeight)
# Defining road
emis = 0.93
asphalt = Material(self.kRoad, self.cRoad, 'asphalt')
road_T_init = 293.
road_horizontal = 1
# fraction of surface vegetation coverage
road_veg_coverage = min(self.vegCover/(1-self.bldDensity), 1.)
# define road layers
road_layer_num = int(math.ceil(self.d_road/0.05))
# 0.5/0.05 ~ 10 x 1 matrix of 0.05 thickness
thickness_vector = [0.05 for r in range(road_layer_num)]
material_vector = [asphalt for r in range(road_layer_num)]
self.road = Element(self.alb_road, emis, thickness_vector, material_vector, road_veg_coverage,
road_T_init, road_horizontal, name="urban_road")
self.rural = copy.deepcopy(self.road)
self.rural.vegCoverage = self.rurVegCover
self.rural._name = "rural_road"
# Reference site class (also include VDM)
self.RSM = RSMDef(self.lat, self.lon, self.GMT, self.h_obs,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
self.USM = RSMDef(self.lat, self.lon, self.GMT, self.bldHeight/10.,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
T_init = self.weather.staTemp[0]
H_init = self.weather.staHum[0]
self.UCM = UCMDef(self.bldHeight, self.bldDensity, self.verToHor, self.treeCoverage, self.sensAnth, self.latAnth, T_init, H_init,
self.weather.staUmod[0], self.geoParam, self.r_glaze_total, self.SHGC_total, self.alb_wall_total, self.road)
self.UCM.h_mix = self.h_mix
# Define Road Element & buffer to match ground temperature depth
roadMat, newthickness = procMat(self.road, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
roadMat.append(self.SOIL)
self.soilindex1 = i
break
self.road = Element(self.road.albedo, self.road.emissivity, newthickness, roadMat,
self.road.vegCoverage, self.road.layerTemp[0], self.road.horizontal, self.road._name)
# Define Rural Element
ruralMat, newthickness = procMat(self.rural, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
ruralMat.append(self.SOIL)
self.soilindex2 = i
break
self.rural = Element(self.rural.albedo, self.rural.emissivity, newthickness,
ruralMat, self.rural.vegCoverage, self.rural.layerTemp[0], self.rural.horizontal, self.rural._name)
def hvac_autosize(self):
""" Section 6 - HVAC Autosizing (unlimited cooling & heating) """
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999.
def simulate(self):
""" Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# Output of object instance vector
self.WeatherData # Nx1 vector of forc instance
self.UCMData # Nx1 vector of UCM instance
self.UBLData # Nx1 vector of UBL instance
self.RSMData # Nx1 vector of RSM instance
self.USMData # Nx1 vector of USM instance
"""
self.N = int(self.simTime.days * 24) # total number of hours in simulation
n = 0 # weather time step counter
self.ph = self.simTime.dt/3600. # dt (simulation time step) in hours
# Data dump variables
time = range(self.N)
self.WeatherData = [None for x in range(self.N)]
self.UCMData = [None for x in range(self.N)]
self.UBLData = [None for x in range(self.N)]
self.RSMData = [None for x in range(self.N)]
self.USMData = [None for x in range(self.N)]
print('\nSimulating new temperature and humidity values for {} days from {}/{}.\n'.format(
int(self.nDay), int(self.Month), int(self.Day)))
self.logger.info("Start simulation")
for it in range(1, self.simTime.nt, 1): # for every simulation time-step (i.e 5 min) defined by uwg
# Update water temperature (estimated)
if self.nSoil < 3: # correction to original matlab code
# for BUBBLE/CAPITOUL/Singapore only
self.forc.deepTemp = sum(self.forcIP.temp)/float(len(self.forcIP.temp))
self.forc.waterTemp = sum(
self.forcIP.temp)/float(len(self.forcIP.temp)) - 10. # for BUBBLE/CAPITOUL/Singapore only
else:
# soil temperature by depth, by month
self.forc.deepTemp = self.Tsoil[self.soilindex1][self.simTime.month-1]
self.forc.waterTemp = self.Tsoil[2][self.simTime.month-1]
# There's probably a better way to update the weather...
self.simTime.UpdateDate()
self.logger.info("\n{0} m={1}, d={2}, h={3}, s={4}".format(
__name__, self.simTime.month, self.simTime.day, self.simTime.secDay/3600., self.simTime.secDay))
# simulation time increment raised to weather time step
self.ceil_time_step = int(math.ceil(it * self.ph))-1
# minus one to be consistent with forcIP list index
# Updating forcing instance
# horizontal Infrared Radiation Intensity (W m-2)
self.forc.infra = self.forcIP.infra[self.ceil_time_step]
# wind speed (m s-1)
self.forc.wind = max(self.forcIP.wind[self.ceil_time_step], self.geoParam.windMin)
self.forc.uDir = self.forcIP.uDir[self.ceil_time_step] # wind direction
# specific humidty (kg kg-1)
self.forc.hum = self.forcIP.hum[self.ceil_time_step]
self.forc.pres = self.forcIP.pres[self.ceil_time_step] # Pressure (Pa)
self.forc.temp = self.forcIP.temp[self.ceil_time_step] # air temperature (C)
self.forc.rHum = self.forcIP.rHum[self.ceil_time_step] # Relative humidity (%)
self.forc.prec = self.forcIP.prec[self.ceil_time_step] # Precipitation (mm h-1)
# horizontal solar diffuse radiation (W m-2)
self.forc.dif = self.forcIP.dif[self.ceil_time_step]
# normal solar direct radiation (W m-2)
self.forc.dir = self.forcIP.dir[self.ceil_time_step]
# Canyon humidity (absolute) same as rural
self.UCM.canHum = copy.copy(self.forc.hum)
# Update solar flux
self.solar = SolarCalcs(self.UCM, self.BEM, self.simTime,
self.RSM, self.forc, self.geoParam, self.rural)
self.rural, self.UCM, self.BEM = self.solar.solarcalcs()
# Update building & traffic schedule
# Assign day type (1 = weekday, 2 = sat, 3 = sun/other)
if self.is_near_zero(self.simTime.julian % 7):
self.dayType = 3 # Sunday
elif self.is_near_zero(self.simTime.julian % 7 - 6.):
self.dayType = 2 # Saturday
else:
self.dayType = 1 # Weekday
# Update anthropogenic heat load for each hour (building & UCM)
self.UCM.sensAnthrop = self.sensAnth * (self.SchTraffic[self.dayType-1][self.simTime.hourDay])
# Update the energy components for building types defined in initialize.uwg
for i in range(len(self.BEM)):
# Set temperature
self.BEM[i].building.coolSetpointDay = self.Sch[i].Cool[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for cooling
self.BEM[i].building.coolSetpointNight = self.BEM[i].building.coolSetpointDay
self.BEM[i].building.heatSetpointDay = self.Sch[i].Heat[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for heating
self.BEM[i].building.heatSetpointNight = self.BEM[i].building.heatSetpointDay
# Internal Heat Load Schedule (W/m^2 of floor area for Q)
self.BEM[i].Elec = self.Sch[i].Qelec * self.Sch[i].Elec[self.dayType -
1][self.simTime.hourDay] # Qelec x elec fraction for day
self.BEM[i].Light = self.Sch[i].Qlight * self.Sch[i].Light[self.dayType -
1][self.simTime.hourDay] # Qlight x light fraction for day
self.BEM[i].Nocc = self.Sch[i].Nocc * self.Sch[i].Occ[self.dayType -
1][self.simTime.hourDay] # Number of occupants x occ fraction for day
# Sensible Q occupant * fraction occupant sensible Q * number of occupants
self.BEM[i].Qocc = self.sensOcc * (1 - self.LatFOcc) * self.BEM[i].Nocc
# SWH and ventilation schedule
self.BEM[i].SWH = self.Sch[i].Vswh * self.Sch[i].SWH[self.dayType -
1][self.simTime.hourDay] # litres per hour x SWH fraction for day
# m^3/s/m^2 of floor
self.BEM[i].building.vent = self.Sch[i].Vent
self.BEM[i].Gas = self.Sch[i].Qgas * self.Sch[i].Gas[self.dayType -
1][self.simTime.hourDay] # Gas Equip Schedule, per m^2 of floor
# This is quite messy, should update
# Update internal heat and corresponding fractional loads
intHeat = self.BEM[i].Light + self.BEM[i].Elec + self.BEM[i].Qocc
# W/m2 from light, electricity, occupants
self.BEM[i].building.intHeatDay = intHeat
self.BEM[i].building.intHeatNight = intHeat
# fraction of radiant heat from light and equipment of whole internal heat
self.BEM[i].building.intHeatFRad = (
self.RadFLight * self.BEM[i].Light + self.RadFEquip * self.BEM[i].Elec) / intHeat
# fraction of latent heat (from occupants) of whole internal heat
self.BEM[i].building.intHeatFLat = self.LatFOcc * \
self.sensOcc * self.BEM[i].Nocc/intHeat
# Update envelope temperature layers
self.BEM[i].T_wallex = self.BEM[i].wall.layerTemp[0]
self.BEM[i].T_wallin = self.BEM[i].wall.layerTemp[-1]
self.BEM[i].T_roofex = self.BEM[i].roof.layerTemp[0]
self.BEM[i].T_roofin = self.BEM[i].roof.layerTemp[-1]
# Update rural heat fluxes & update vertical diffusion model (VDM)
self.rural.infra = self.forc.infra - self.rural.emissivity * self.SIGMA * \
self.rural.layerTemp[0]**4. # Infrared radiation from rural road
self.rural.SurfFlux(self.forc, self.geoParam, self.simTime,
self.forc.hum, self.forc.temp, self.forc.wind, 2., 0.)
self.RSM.VDM(self.forc, self.rural, self.geoParam, self.simTime)
# Calculate urban heat fluxes, update UCM & UBL
self.UCM, self.UBL, self.BEM = urbflux(
self.UCM, self.UBL, self.BEM, self.forc, self.geoParam, self.simTime, self.RSM)
self.UCM.UCModel(self.BEM, self.UBL.ublTemp, self.forc, self.geoParam)
self.UBL.UBLModel(self.UCM, self.RSM, self.rural,
self.forc, self.geoParam, self.simTime)
"""
# Experimental code to run diffusion model in the urban area
# N.B Commented out in python uwg because computed wind speed in
# urban VDM: y = =0.84*ln((2-x/20)/0.51) results in negative log
# for building heights >= 40m.
Uroad = copy.copy(self.UCM.road)
Uroad.sens = copy.copy(self.UCM.sensHeat)
Uforc = copy.copy(self.forc)
Uforc.wind = copy.copy(self.UCM.canWind)
Uforc.temp = copy.copy(self.UCM.canTemp)
self.USM.VDM(Uforc,Uroad,self.geoParam,self.simTime)
"""
self.logger.info("dbT = {}".format(self.UCM.canTemp-273.15))
if n > 0:
logging.info("dpT = {}".format(self.UCM.Tdp))
logging.info("RH = {}".format(self.UCM.canRHum))
if self.is_near_zero(self.simTime.secDay % self.simTime.timePrint) and n < self.N:
self.logger.info("{0} ----sim time step = {1}----\n\n".format(__name__, n))
self.WeatherData[n] = copy.copy(self.forc)
_Tdb, _w, self.UCM.canRHum, _h, self.UCM.Tdp, _v = psychrometrics(
self.UCM.canTemp, self.UCM.canHum, self.forc.pres)
self.UBLData[n] = copy.copy(self.UBL)
self.UCMData[n] = copy.copy(self.UCM)
self.RSMData[n] = copy.copy(self.RSM)
self.logger.info("dbT = {}".format(self.UCMData[n].canTemp-273.15))
self.logger.info("dpT = {}".format(self.UCMData[n].Tdp))
self.logger.info("RH = {}".format(self.UCMData[n].canRHum))
n += 1
def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] = column data of epw
self.epwinput[iJ+self.simTime.timeInitial-8][6] = "{0:.{1}f}".format(
self.UCMData[iJ].canTemp - 273.15, epw_prec) # dry bulb temperature [?C]
# dew point temperature [?C]
self.epwinput[iJ+self.simTime.timeInitial -
8][7] = "{0:.{1}f}".format(self.UCMData[iJ].Tdp, epw_prec)
# relative humidity [%]
self.epwinput[iJ+self.simTime.timeInitial -
8][8] = "{0:.{1}f}".format(self.UCMData[iJ].canRHum, epw_prec)
self.epwinput[iJ+self.simTime.timeInitial-8][21] = "{0:.{1}f}".format(
self.WeatherData[iJ].wind, epw_prec) # wind speed [m/s]
# Writing new EPW file
epw_new_id = open(self.newPathName, "w")
for i in range(8):
new_epw_line = '{}\n'.format(reduce(lambda x, y: x+","+y, self._header[i]))
epw_new_id.write(new_epw_line)
for i in range(len(self.epwinput)):
printme = ""
for ei in range(34):
printme += "{}".format(self.epwinput[i][ei]) + ','
printme = printme + "{}".format(self.epwinput[i][ei])
new_epw_line = "{0}\n".format(printme)
epw_new_id.write(new_epw_line)
epw_new_id.close()
print("New climate file '{}' is generated at {}.".format(
self.destinationFileName, self.destinationDir))
def run(self):
# run main class methods
self.read_epw()
self.set_input()
self.init_BEM_obj()
self.init_input_obj()
self.hvac_autosize()
self.simulate()
self.write_epw()
|
ladybug-tools/uwg | uwg/uwg.py | uwg.set_input | python | def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the .uwg file.
if self.uwgParamFileName is not None:
print("\nReading uwg file input.")
self.read_input()
else:
print("\nNo .uwg file input.")
self.check_required_inputs()
# Modify zone to be used as python index
self.zone = int(self.zone)-1 | Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there. | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/uwg.py#L532-L548 | [
"def read_input(self):\n \"\"\"Section 3 - Read Input File (.m, file)\n Note: UWG_Matlab input files are xlsm, XML, .m, file.\n properties:\n self._init_param_dict # dictionary of simulation initialization parameters\n\n self.sensAnth # non-building sensible heat (W/m^2)\n self.SchTraffic # Traffice schedule\n\n self.BEM # list of BEMDef objects extracted from readDOE\n self.Sch # list of Schedule objects extracted from readDOE\n\n \"\"\"\n\n uwg_param_file_path = os.path.join(self.uwgParamDir, self.uwgParamFileName)\n\n if not os.path.exists(uwg_param_file_path):\n raise Exception(\"Param file: '{}' does not exist.\".format(uwg_param_file_path))\n\n # Open .uwg file and feed csv data to initializeDataFile\n try:\n uwg_param_data = utilities.read_csv(uwg_param_file_path)\n except Exception as e:\n raise Exception(\"Failed to read .uwg file! {}\".format(e.message))\n\n # The initialize.uwg is read with a dictionary so that users changing\n # line endings or line numbers doesn't make reading input incorrect\n self._init_param_dict = {}\n count = 0\n while count < len(uwg_param_data):\n row = uwg_param_data[count]\n row = [row[i].replace(\" \", \"\") for i in range(len(row))] # strip white spaces\n\n # Optional parameters might be empty so handle separately\n is_optional_parameter = (\n row != [] and\n (\n row[0] == \"albRoof\" or\n row[0] == \"vegRoof\" or\n row[0] == \"glzR\" or\n row[0] == \"hvac\" or\n row[0] == \"albWall\" or\n row[0] == \"SHGC\"\n )\n )\n try:\n if row == [] or \"#\" in row[0]:\n count += 1\n continue\n elif row[0] == \"SchTraffic\":\n # SchTraffic: 3 x 24 matrix\n trafficrows = uwg_param_data[count+1:count+4]\n self._init_param_dict[row[0]] = [utilities.str2fl(r[:24]) for r in trafficrows]\n count += 4\n elif row[0] == \"bld\":\n # bld: 17 x 3 matrix\n bldrows = uwg_param_data[count+1:count+17]\n self._init_param_dict[row[0]] = [utilities.str2fl(r[:3]) for r in bldrows]\n count += 17\n elif is_optional_parameter:\n self._init_param_dict[row[0]] = float(row[1]) if row[1] != \"\" else None\n count += 1\n else:\n self._init_param_dict[row[0]] = float(row[1])\n count += 1\n except ValueError:\n print(\"Error while reading parameter at {} {}\".format(count, row))\n\n ipd = self._init_param_dict\n\n # Define Simulation and Weather parameters\n if self.Month is None: self.Month = ipd['Month']\n if self.Day is None: self.Day = ipd['Day']\n if self.nDay is None: self.nDay = ipd['nDay']\n if self.dtSim is None: self.dtSim = ipd['dtSim']\n if self.dtWeather is None: self.dtWeather = ipd['dtWeather']\n\n # HVAC system and internal laod\n if self.autosize is None: self.autosize = ipd['autosize']\n if self.sensOcc is None: self.sensOcc = ipd['sensOcc']\n if self.LatFOcc is None: self.LatFOcc = ipd['LatFOcc']\n if self.RadFOcc is None: self.RadFOcc = ipd['RadFOcc']\n if self.RadFEquip is None: self.RadFEquip = ipd['RadFEquip']\n if self.RadFLight is None: self.RadFLight = ipd['RadFLight']\n\n # Define Urban microclimate parameters\n if self.h_ubl1 is None: self.h_ubl1 = ipd['h_ubl1']\n if self.h_ubl2 is None: self.h_ubl2 = ipd['h_ubl2']\n if self.h_ref is None: self.h_ref = ipd['h_ref']\n if self.h_temp is None: self.h_temp = ipd['h_temp']\n if self.h_wind is None: self.h_wind = ipd['h_wind']\n if self.c_circ is None: self.c_circ = ipd['c_circ']\n if self.c_exch is None: self.c_exch = ipd['c_exch']\n if self.maxDay is None: self.maxDay = ipd['maxDay']\n if self.maxNight is None: self.maxNight = ipd['maxNight']\n if self.windMin is None: self.windMin = ipd['windMin']\n if self.h_obs is None: self.h_obs = ipd['h_obs']\n\n # Urban characteristics\n if self.bldHeight is None: self.bldHeight = ipd['bldHeight']\n if self.h_mix is None: self.h_mix = ipd['h_mix']\n if self.bldDensity is None: self.bldDensity = ipd['bldDensity']\n if self.verToHor is None: self.verToHor = ipd['verToHor']\n if self.charLength is None: self.charLength = ipd['charLength']\n if self.alb_road is None: self.alb_road = ipd['albRoad']\n if self.d_road is None: self.d_road = ipd['dRoad']\n if self.sensAnth is None: self.sensAnth = ipd['sensAnth']\n # if self.latAnth is None: self.latAnth = ipd['latAnth'] # Not used, taken out by JH.\n\n # climate Zone\n if self.zone is None: self.zone = ipd['zone']\n\n # Vegetation parameters\n if self.vegCover is None: self.vegCover = ipd['vegCover']\n if self.treeCoverage is None: self.treeCoverage = ipd['treeCoverage']\n if self.vegStart is None: self.vegStart = ipd['vegStart']\n if self.vegEnd is None: self.vegEnd = ipd['vegEnd']\n if self.albVeg is None: self.albVeg = ipd['albVeg']\n if self.rurVegCover is None: self.rurVegCover = ipd['rurVegCover']\n if self.latGrss is None: self.latGrss = ipd['latGrss']\n if self.latTree is None: self.latTree = ipd['latTree']\n\n # Define Traffic schedule\n if self.SchTraffic is None: self.SchTraffic = ipd['SchTraffic']\n\n # Define Road (Assume 0.5m of asphalt)\n if self.kRoad is None: self.kRoad = ipd['kRoad']\n if self.cRoad is None: self.cRoad = ipd['cRoad']\n\n # Building stock fraction\n if self.bld is None: self.bld = ipd['bld']\n\n # Optional parameters\n if self.albRoof is None: self.albRoof = ipd['albRoof']\n if self.vegRoof is None: self.vegRoof = ipd['vegRoof']\n if self.glzR is None: self.glzR = ipd['glzR']\n if self.albWall is None: self.albWall = ipd['albWall']\n if self.SHGC is None: self.SHGC = ipd['SHGC']\n",
"def check_required_inputs(self):\n # Fail if required parameters aren't correct\n assert isinstance(self.Month, (float, int)), \\\n 'Month must be a number. Got {}'.format(type(self.Month))\n assert isinstance(self.Day, (float, int)), \\\n 'Day must be a number. Got {}'.format(type(self.Day))\n assert isinstance(self.nDay, (float, int)), \\\n 'nDay must be a number. Got {}'.format(type(self.nDay))\n assert isinstance(self.dtSim, float), \\\n 'dtSim must be a float. Got {}'.format(type(self.dtSim))\n assert isinstance(self.dtWeather, float), \\\n 'dtWeather must be a float. Got {}'.format(type(self.dtWeather))\n assert isinstance(self.autosize, (float, int)), \\\n 'autosize must be a number. Got {}'.format(type(self.autosize))\n assert isinstance(self.sensOcc, float), \\\n 'sensOcc must be a float. Got {}'.format(type(self.sensOcc))\n assert isinstance(self.LatFOcc, float), \\\n 'LatFOcc must be a float. Got {}'.format(type(self.LatFOcc))\n assert isinstance(self.RadFOcc, float), \\\n 'RadFOcc must be a float. Got {}'.format(type(self.RadFOcc))\n assert isinstance(self.RadFEquip, float), \\\n 'RadFEquip must be a float. Got {}'.format(type(self.RadFEquip))\n assert isinstance(self.RadFLight, float), \\\n 'RadFLight must be a float. Got {}'.format(type(self.RadFLight))\n assert isinstance(self.h_ubl1, float), \\\n 'h_ubl1 must be a float. Got {}'.format(type(self.h_ubl1))\n assert isinstance(self.h_ubl2, float), \\\n 'h_ubl2 must be a float. Got {}'.format(type(self.h_ubl2))\n assert isinstance(self.h_ref, float), \\\n 'h_ref must be a float. Got {}'.format(type(self.h_ref))\n assert isinstance(self.h_temp, float), \\\n 'h_temp must be a float. Got {}'.format(type(self.h_temp))\n assert isinstance(self.h_wind, float), \\\n 'h_wind must be a float. Got {}'.format(type(self.h_wind))\n assert isinstance(self.c_circ, float), \\\n 'c_circ must be a float. Got {}'.format(type(self.c_circ))\n assert isinstance(self.c_exch, float), \\\n 'c_exch must be a float. Got {}'.format(type(self.c_exch))\n assert isinstance(self.maxDay, float), \\\n 'maxDay must be a float. Got {}'.format(type(self.maxDay))\n assert isinstance(self.maxNight, float), \\\n 'maxNight must be a float. Got {}'.format(type(self.maxNight))\n assert isinstance(self.windMin, float), \\\n 'windMin must be a float. Got {}'.format(type(self.windMin))\n assert isinstance(self.h_obs, float), \\\n 'h_obs must be a float. Got {}'.format(type(self.h_obs))\n assert isinstance(self.bldHeight, float), \\\n 'bldHeight must be a float. Got {}'.format(type(self.bldHeight))\n assert isinstance(self.h_mix, float), \\\n 'h_mix must be a float. Got {}'.format(type(self.h_mix))\n assert isinstance(self.bldDensity, float), \\\n 'bldDensity must be a float. Got {}'.format(type(self.bldDensity))\n assert isinstance(self.verToHor, float), \\\n 'verToHor must be a float. Got {}'.format(type(self.verToHor))\n assert isinstance(self.charLength, float), \\\n 'charLength must be a float. Got {}'.format(type(self.charLength))\n assert isinstance(self.alb_road, float), \\\n 'alb_road must be a float. Got {}'.format(type(self.alb_road))\n assert isinstance(self.d_road, float), \\\n 'd_road must be a float. Got {}'.format(type(self.d_road))\n assert isinstance(self.sensAnth, float), \\\n 'sensAnth must be a float. Got {}'.format(type(self.sensAnth))\n # assert isinstance(self.latAnth, float) # Take this out as isn't being used\n assert isinstance(self.bld, list), \\\n 'bld must be a list. Got {}'.format(type(self.bld))\n assert len(self.bld) == 16, \\\n 'length of bld must be 16. Got {}'.format(len(self.bld))\n assert isinstance(self.latTree, float), \\\n 'latTree must be a float. Got {}'.format(type(self.latTree))\n assert isinstance(self.latGrss, float), \\\n 'latGrss must be a float. Got {}'.format(type(self.latGrss))\n assert isinstance(self.zone, (float, int)), \\\n 'zone must be a number. Got {}'.format(type(self.zone))\n assert isinstance(self.vegStart, (float, int)), \\\n 'vegStart must be a number. Got {}'.format(type(self.vegStart))\n assert isinstance(self.vegEnd, (float, int)), \\\n 'vegEnd must be a number. Got {}'.format(type(self.vegEnd))\n assert isinstance(self.vegCover, float), \\\n 'vegCover must be a float. Got {}'.format(type(self.vegCover))\n assert isinstance(self.treeCoverage, float), \\\n 'treeCoverage must be a float. Got {}'.format(type(self.treeCoverage))\n assert isinstance(self.albVeg, float), \\\n 'albVeg must be a float. Got {}'.format(type(self.albVeg))\n assert isinstance(self.rurVegCover, float), \\\n 'rurVegCover must be a float. Got {}'.format(type(self.rurVegCover))\n assert isinstance(self.kRoad, float), \\\n 'kRoad must be a float. Got {}'.format(type(self.kRoad))\n assert isinstance(self.cRoad, float), \\\n 'cRoad must be a float. Got {}'.format(type(self.cRoad))\n assert isinstance(self.SchTraffic, list), \\\n 'SchTraffic must be a list. Got {}'.format(type(self.SchTraffic))\n assert len(self.SchTraffic) == 3, \\\n 'length of SchTraffic must be 3. Got {}'.format(len(self.SchTraffic))\n"
] | class uwg(object):
"""Morph a rural EPW file to urban conditions using a file with a list of urban parameters.
args:
epwDir: The directory in which the rural EPW file sits.
epwFileName: The name of the rural epw file that will be morphed.
uwgParamDir: The directory in which the uwg Parameter File (.uwg) sits.
uwgParamFileName: The name of the uwg Parameter File (.uwg).
destinationDir: Optional destination directory for the morphed EPW file.
If left blank, the morphed file will be written into the same directory
as the rural EPW file (the epwDir).
destinationFileName: Optional destination file name for the morphed EPW file.
If left blank, the morphed file will append "_UWG" to the original file name.
returns:
newClimateFile: the path to a new EPW file that has been morphed to account
for uban conditions.
"""
""" Section 1 - Definitions for constants / other parameters """
MINTHICKNESS = 0.01 # Minimum layer thickness (to prevent crashing) (m)
MAXTHICKNESS = 0.05 # Maximum layer thickness (m)
# http://web.mit.edu/parmstr/Public/NRCan/nrcc29118.pdf (Figly & Snodgrass)
SOILTCOND = 1
# http://www.europment.org/library/2013/venice/bypaper/MFHEEF/MFHEEF-21.pdf (average taken from Table 1)
SOILVOLHEAT = 2e6
# Soil material used for soil-depth padding
SOIL = Material(SOILTCOND, SOILVOLHEAT, name="soil")
# Physical constants
G = 9.81 # gravity (m s-2)
CP = 1004. # heat capacity for air (J/kg K)
VK = 0.40 # von karman constant (dimensionless)
R = 287. # gas constant dry air (J/kg K)
RV = 461.5 # gas constant water vapor (J/kg K)
LV = 2.26e6 # latent heat of evaporation (J/kg)
SIGMA = 5.67e-08 # Stefan Boltzmann constant (W m-2 K-4)
WATERDENS = 1000. # water density (kg m-3)
LVTT = 2.5008e6 #
TT = 273.16 #
ESTT = 611.14 #
CL = 4.218e3 #
CPV = 1846.1 #
B = 9.4 # Coefficients derived by Louis (1979)
CM = 7.4 #
# (Pr/Sc)^(2/3) for Colburn analogy in water evaporation
COLBURN = math.pow((0.713/0.621), (2/3.))
# Site-specific parameters
WGMAX = 0.005 # maximum film water depth on horizontal surfaces (m)
# File path parameter
RESOURCE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "resources"))
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
def __init__(self, epwFileName, uwgParamFileName=None, epwDir=None, uwgParamDir=None, destinationDir=None, destinationFileName=None):
# Logger will be disabled by default unless explicitly called in tests
self.logger = logging.getLogger(__name__)
# User defined
self.epwFileName = epwFileName if epwFileName.lower().endswith('.epw') else epwFileName + \
'.epw' # Revise epw file name if not end with epw
# If file name is entered then will uwg will set input from .uwg file
self.uwgParamFileName = uwgParamFileName
# If user does not overload
self.destinationFileName = destinationFileName if destinationFileName else self.epwFileName.strip(
'.epw') + '_UWG.epw'
self.epwDir = epwDir if epwDir else os.path.join(self.RESOURCE_PATH, "epw")
self.uwgParamDir = uwgParamDir if uwgParamDir else os.path.join(
self.RESOURCE_PATH, "parameters")
self.destinationDir = destinationDir if destinationDir else os.path.join(
self.RESOURCE_PATH, "epw_uwg")
# refdata: Serialized DOE reference data, z_meso height data
self.readDOE_file_path = os.path.join(self.CURRENT_PATH, "refdata", "readDOE.pkl")
self.z_meso_dir_path = os.path.join(self.CURRENT_PATH, "refdata")
# EPW precision
self.epw_precision = 1
# init uwg variables
self._init_param_dict = None
# Define Simulation and Weather parameters
self.Month = None # starting month (1-12)
self.Day = None # starting day (1-31)
self.nDay = None # number of days
self.dtSim = None # simulation time step (s)
self.dtWeather = None # seconds (s)
# HVAC system and internal laod
self.autosize = None # autosize HVAC (1 or 0)
self.sensOcc = None # Sensible heat from occupant
self.LatFOcc = None # Latent heat fraction from occupant (normally 0.3)
self.RadFOcc = None # Radiant heat fraction from occupant (normally 0.2)
self.RadFEquip = None # Radiant heat fraction from equipment (normally 0.5)
self.RadFLight = None # Radiant heat fraction from light (normally 0.7)
# Define Urban microclimate parameters
self.h_ubl1 = None # ubl height - day (m)
self.h_ubl2 = None # ubl height - night (m)
self.h_ref = None # inversion height
self.h_temp = None # temperature height
self.h_wind = None # wind height
self.c_circ = None # circulation coefficient
self.c_exch = None # exchange coefficient
self.maxDay = None # max day threshhold
self.maxNight = None # max night threshhold
self.windMin = None # min wind speed (m/s)
self.h_obs = None # rural average obstacle height
# Urban characteristics
self.bldHeight = None # average building height (m)
self.h_mix = None # mixing height (m)
self.bldDensity = None # building density (0-1)
self.verToHor = None # building aspect ratio
# radius defining the urban area of study [aka. characteristic length] (m)
self.charLength = None
self.alb_road = None # road albedo
self.d_road = None # road pavement thickness
self.sensAnth = None # non-building sensible heat (W/m^2)
self.latAnth = None # non-building latent heat heat (W/m^2). Not used, taken out by JH.
# Fraction of building typology stock
self.bld = None # 16x3 matrix of fraction of building type by era
# climate Zone
self.zone = None
# Vegetation parameters
self.vegCover = None # urban area veg coverage ratio
self.treeCoverage = None # urban area tree coverage ratio
self.vegStart = None # vegetation start month
self.vegEnd = None # vegetation end month
self.albVeg = None # Vegetation albedo
self.rurVegCover = None # rural vegetation cover
self.latGrss = None # latent fraction of grass
self.latTree = None # latent fraction of tree
# Define Traffic schedule
self.SchTraffic = None
# Define Road (Assume 0.5m of asphalt)
self.kRoad = None # road pavement conductivity (W/m K)
self.cRoad = None # road volumetric heat capacity (J/m^3 K)
# Define optional Building characteristics
self.flr_h = None # floor-to-floor height
self.albRoof = None # roof albedo (0 - 1)
self.vegRoof = None # Fraction of the roofs covered in grass/shrubs (0-1)
self.glzR = None # Glazing Ratio
self.SHGC = None # Solar Heat Gain Coefficient
self.albWall = None # Wall albedo
def ToString(self):
"""Overwrite .NET ToString method."""
return self.__repr__()
def __repr__(self):
def _split_string(s):
return s[0] + ":\n " + s[1].replace(",", "\n ")
def _tabbed(s):
return _split_string(s.__repr__().split(":"))
def _list_2_tabbed(b):
return reduce(lambda a, b: a+"\n"+b, [_tabbed(_b) for _b in b])
return "uwg for {}:\n\n{}{}{}{}{}{}{}{}".format(
self.epwFileName,
_tabbed(self.simTime)+"\n" if hasattr(self, "simTime") else "No simTime attr.\n",
_tabbed(self.weather)+"\n" if hasattr(self, "weather") else "No weather attr.\n",
_tabbed(self.geoParam)+"\n" if hasattr(self, "geoParam") else "No geoParam attr.\n",
_tabbed(self.UBL)+"\n" if hasattr(self, "UBL") else "No UBL attr.\n",
"Rural "+_tabbed(self.RSM)+"\n" if hasattr(self, "RSM") else "No Rural RSM attr.\n",
"Urban "+_tabbed(self.USM)+"\n" if hasattr(self, "USM") else "No Urban RSM attr.\n",
_tabbed(self.UCM)+"\n" if hasattr(self, "UCM") else "No UCM attr.\n",
_list_2_tabbed(self.BEM) if hasattr(self, "BEM") else "No BEM attr."
)
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def read_epw(self):
"""Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT # GMT
self.nSoil # Number of soil depths
self.Tsoil # nSoil x 12 matrix for soil temperture (K)
self.depth_soil # nSoil x 1 matrix for soil depth (m)
"""
# Make dir path to epw file
self.climateDataPath = os.path.join(self.epwDir, self.epwFileName)
# Open epw file and feed csv data to climate_data
try:
climate_data = utilities.read_csv(self.climateDataPath)
except Exception as e:
raise Exception("Failed to read epw file! {}".format(e.message))
# Read header lines (1 to 8) from EPW and ensure TMY2 format.
self._header = climate_data[0:8]
# Read weather data from EPW for each time step in weather file. (lines 8 - end)
self.epwinput = climate_data[8:]
# Read Lat, Long (line 1 of EPW)
self.lat = float(self._header[0][6])
self.lon = float(self._header[0][7])
self.GMT = float(self._header[0][8])
# Read in soil temperature data (assumes this is always there)
# ref: http://bigladdersoftware.com/epx/docs/8-2/auxiliary-programs/epw-csv-format-inout.html
soilData = self._header[3]
self.nSoil = int(soilData[1]) # Number of ground temperature depths
self.Tsoil = utilities.zeros(self.nSoil, 12) # nSoil x 12 matrix for soil temperture (K)
self.depth_soil = utilities.zeros(self.nSoil, 1) # nSoil x 1 matrix for soil depth (m)
# Read monthly data for each layer of soil from EPW file
for i in range(self.nSoil):
self.depth_soil[i][0] = float(soilData[2 + (i*16)]) # get soil depth for each nSoil
# Monthly data
for j in range(12):
# 12 months of soil T for specific depth
self.Tsoil[i][j] = float(soilData[6 + (i*16) + j]) + 273.15
# Set new directory path for the moprhed EPW file
self.newPathName = os.path.join(self.destinationDir, self.destinationFileName)
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic # Traffice schedule
self.BEM # list of BEMDef objects extracted from readDOE
self.Sch # list of Schedule objects extracted from readDOE
"""
uwg_param_file_path = os.path.join(self.uwgParamDir, self.uwgParamFileName)
if not os.path.exists(uwg_param_file_path):
raise Exception("Param file: '{}' does not exist.".format(uwg_param_file_path))
# Open .uwg file and feed csv data to initializeDataFile
try:
uwg_param_data = utilities.read_csv(uwg_param_file_path)
except Exception as e:
raise Exception("Failed to read .uwg file! {}".format(e.message))
# The initialize.uwg is read with a dictionary so that users changing
# line endings or line numbers doesn't make reading input incorrect
self._init_param_dict = {}
count = 0
while count < len(uwg_param_data):
row = uwg_param_data[count]
row = [row[i].replace(" ", "") for i in range(len(row))] # strip white spaces
# Optional parameters might be empty so handle separately
is_optional_parameter = (
row != [] and
(
row[0] == "albRoof" or
row[0] == "vegRoof" or
row[0] == "glzR" or
row[0] == "hvac" or
row[0] == "albWall" or
row[0] == "SHGC"
)
)
try:
if row == [] or "#" in row[0]:
count += 1
continue
elif row[0] == "SchTraffic":
# SchTraffic: 3 x 24 matrix
trafficrows = uwg_param_data[count+1:count+4]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:24]) for r in trafficrows]
count += 4
elif row[0] == "bld":
# bld: 17 x 3 matrix
bldrows = uwg_param_data[count+1:count+17]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:3]) for r in bldrows]
count += 17
elif is_optional_parameter:
self._init_param_dict[row[0]] = float(row[1]) if row[1] != "" else None
count += 1
else:
self._init_param_dict[row[0]] = float(row[1])
count += 1
except ValueError:
print("Error while reading parameter at {} {}".format(count, row))
ipd = self._init_param_dict
# Define Simulation and Weather parameters
if self.Month is None: self.Month = ipd['Month']
if self.Day is None: self.Day = ipd['Day']
if self.nDay is None: self.nDay = ipd['nDay']
if self.dtSim is None: self.dtSim = ipd['dtSim']
if self.dtWeather is None: self.dtWeather = ipd['dtWeather']
# HVAC system and internal laod
if self.autosize is None: self.autosize = ipd['autosize']
if self.sensOcc is None: self.sensOcc = ipd['sensOcc']
if self.LatFOcc is None: self.LatFOcc = ipd['LatFOcc']
if self.RadFOcc is None: self.RadFOcc = ipd['RadFOcc']
if self.RadFEquip is None: self.RadFEquip = ipd['RadFEquip']
if self.RadFLight is None: self.RadFLight = ipd['RadFLight']
# Define Urban microclimate parameters
if self.h_ubl1 is None: self.h_ubl1 = ipd['h_ubl1']
if self.h_ubl2 is None: self.h_ubl2 = ipd['h_ubl2']
if self.h_ref is None: self.h_ref = ipd['h_ref']
if self.h_temp is None: self.h_temp = ipd['h_temp']
if self.h_wind is None: self.h_wind = ipd['h_wind']
if self.c_circ is None: self.c_circ = ipd['c_circ']
if self.c_exch is None: self.c_exch = ipd['c_exch']
if self.maxDay is None: self.maxDay = ipd['maxDay']
if self.maxNight is None: self.maxNight = ipd['maxNight']
if self.windMin is None: self.windMin = ipd['windMin']
if self.h_obs is None: self.h_obs = ipd['h_obs']
# Urban characteristics
if self.bldHeight is None: self.bldHeight = ipd['bldHeight']
if self.h_mix is None: self.h_mix = ipd['h_mix']
if self.bldDensity is None: self.bldDensity = ipd['bldDensity']
if self.verToHor is None: self.verToHor = ipd['verToHor']
if self.charLength is None: self.charLength = ipd['charLength']
if self.alb_road is None: self.alb_road = ipd['albRoad']
if self.d_road is None: self.d_road = ipd['dRoad']
if self.sensAnth is None: self.sensAnth = ipd['sensAnth']
# if self.latAnth is None: self.latAnth = ipd['latAnth'] # Not used, taken out by JH.
# climate Zone
if self.zone is None: self.zone = ipd['zone']
# Vegetation parameters
if self.vegCover is None: self.vegCover = ipd['vegCover']
if self.treeCoverage is None: self.treeCoverage = ipd['treeCoverage']
if self.vegStart is None: self.vegStart = ipd['vegStart']
if self.vegEnd is None: self.vegEnd = ipd['vegEnd']
if self.albVeg is None: self.albVeg = ipd['albVeg']
if self.rurVegCover is None: self.rurVegCover = ipd['rurVegCover']
if self.latGrss is None: self.latGrss = ipd['latGrss']
if self.latTree is None: self.latTree = ipd['latTree']
# Define Traffic schedule
if self.SchTraffic is None: self.SchTraffic = ipd['SchTraffic']
# Define Road (Assume 0.5m of asphalt)
if self.kRoad is None: self.kRoad = ipd['kRoad']
if self.cRoad is None: self.cRoad = ipd['cRoad']
# Building stock fraction
if self.bld is None: self.bld = ipd['bld']
# Optional parameters
if self.albRoof is None: self.albRoof = ipd['albRoof']
if self.vegRoof is None: self.vegRoof = ipd['vegRoof']
if self.glzR is None: self.glzR = ipd['glzR']
if self.albWall is None: self.albWall = ipd['albWall']
if self.SHGC is None: self.SHGC = ipd['SHGC']
def check_required_inputs(self):
# Fail if required parameters aren't correct
assert isinstance(self.Month, (float, int)), \
'Month must be a number. Got {}'.format(type(self.Month))
assert isinstance(self.Day, (float, int)), \
'Day must be a number. Got {}'.format(type(self.Day))
assert isinstance(self.nDay, (float, int)), \
'nDay must be a number. Got {}'.format(type(self.nDay))
assert isinstance(self.dtSim, float), \
'dtSim must be a float. Got {}'.format(type(self.dtSim))
assert isinstance(self.dtWeather, float), \
'dtWeather must be a float. Got {}'.format(type(self.dtWeather))
assert isinstance(self.autosize, (float, int)), \
'autosize must be a number. Got {}'.format(type(self.autosize))
assert isinstance(self.sensOcc, float), \
'sensOcc must be a float. Got {}'.format(type(self.sensOcc))
assert isinstance(self.LatFOcc, float), \
'LatFOcc must be a float. Got {}'.format(type(self.LatFOcc))
assert isinstance(self.RadFOcc, float), \
'RadFOcc must be a float. Got {}'.format(type(self.RadFOcc))
assert isinstance(self.RadFEquip, float), \
'RadFEquip must be a float. Got {}'.format(type(self.RadFEquip))
assert isinstance(self.RadFLight, float), \
'RadFLight must be a float. Got {}'.format(type(self.RadFLight))
assert isinstance(self.h_ubl1, float), \
'h_ubl1 must be a float. Got {}'.format(type(self.h_ubl1))
assert isinstance(self.h_ubl2, float), \
'h_ubl2 must be a float. Got {}'.format(type(self.h_ubl2))
assert isinstance(self.h_ref, float), \
'h_ref must be a float. Got {}'.format(type(self.h_ref))
assert isinstance(self.h_temp, float), \
'h_temp must be a float. Got {}'.format(type(self.h_temp))
assert isinstance(self.h_wind, float), \
'h_wind must be a float. Got {}'.format(type(self.h_wind))
assert isinstance(self.c_circ, float), \
'c_circ must be a float. Got {}'.format(type(self.c_circ))
assert isinstance(self.c_exch, float), \
'c_exch must be a float. Got {}'.format(type(self.c_exch))
assert isinstance(self.maxDay, float), \
'maxDay must be a float. Got {}'.format(type(self.maxDay))
assert isinstance(self.maxNight, float), \
'maxNight must be a float. Got {}'.format(type(self.maxNight))
assert isinstance(self.windMin, float), \
'windMin must be a float. Got {}'.format(type(self.windMin))
assert isinstance(self.h_obs, float), \
'h_obs must be a float. Got {}'.format(type(self.h_obs))
assert isinstance(self.bldHeight, float), \
'bldHeight must be a float. Got {}'.format(type(self.bldHeight))
assert isinstance(self.h_mix, float), \
'h_mix must be a float. Got {}'.format(type(self.h_mix))
assert isinstance(self.bldDensity, float), \
'bldDensity must be a float. Got {}'.format(type(self.bldDensity))
assert isinstance(self.verToHor, float), \
'verToHor must be a float. Got {}'.format(type(self.verToHor))
assert isinstance(self.charLength, float), \
'charLength must be a float. Got {}'.format(type(self.charLength))
assert isinstance(self.alb_road, float), \
'alb_road must be a float. Got {}'.format(type(self.alb_road))
assert isinstance(self.d_road, float), \
'd_road must be a float. Got {}'.format(type(self.d_road))
assert isinstance(self.sensAnth, float), \
'sensAnth must be a float. Got {}'.format(type(self.sensAnth))
# assert isinstance(self.latAnth, float) # Take this out as isn't being used
assert isinstance(self.bld, list), \
'bld must be a list. Got {}'.format(type(self.bld))
assert len(self.bld) == 16, \
'length of bld must be 16. Got {}'.format(len(self.bld))
assert isinstance(self.latTree, float), \
'latTree must be a float. Got {}'.format(type(self.latTree))
assert isinstance(self.latGrss, float), \
'latGrss must be a float. Got {}'.format(type(self.latGrss))
assert isinstance(self.zone, (float, int)), \
'zone must be a number. Got {}'.format(type(self.zone))
assert isinstance(self.vegStart, (float, int)), \
'vegStart must be a number. Got {}'.format(type(self.vegStart))
assert isinstance(self.vegEnd, (float, int)), \
'vegEnd must be a number. Got {}'.format(type(self.vegEnd))
assert isinstance(self.vegCover, float), \
'vegCover must be a float. Got {}'.format(type(self.vegCover))
assert isinstance(self.treeCoverage, float), \
'treeCoverage must be a float. Got {}'.format(type(self.treeCoverage))
assert isinstance(self.albVeg, float), \
'albVeg must be a float. Got {}'.format(type(self.albVeg))
assert isinstance(self.rurVegCover, float), \
'rurVegCover must be a float. Got {}'.format(type(self.rurVegCover))
assert isinstance(self.kRoad, float), \
'kRoad must be a float. Got {}'.format(type(self.kRoad))
assert isinstance(self.cRoad, float), \
'cRoad must be a float. Got {}'.format(type(self.cRoad))
assert isinstance(self.SchTraffic, list), \
'SchTraffic must be a list. Got {}'.format(type(self.SchTraffic))
assert len(self.SchTraffic) == 3, \
'length of SchTraffic must be 3. Got {}'.format(len(self.SchTraffic))
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the .uwg file.
if self.uwgParamFileName is not None:
print("\nReading uwg file input.")
self.read_input()
else:
print("\nNo .uwg file input.")
self.check_required_inputs()
# Modify zone to be used as python index
self.zone = int(self.zone)-1
def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total building stock
"""
if not os.path.exists(self.readDOE_file_path):
raise Exception("readDOE.pkl file: '{}' does not exist.".format(readDOE_file_path))
readDOE_file = open(self.readDOE_file_path, 'rb') # open pickle file in binary form
refDOE = pickle.load(readDOE_file)
refBEM = pickle.load(readDOE_file)
refSchedule = pickle.load(readDOE_file)
readDOE_file.close()
# Define building energy models
k = 0
self.r_glaze_total = 0. # Glazing ratio for total building stock
self.SHGC_total = 0. # SHGC addition for total building stock
self.alb_wall_total = 0. # albedo wall addition for total building stock
h_floor = self.flr_h or 3.05 # average floor height
total_urban_bld_area = math.pow(self.charLength, 2)*self.bldDensity * \
self.bldHeight/h_floor # total building floor area
area_matrix = utilities.zeros(16, 3)
self.BEM = [] # list of BEMDef objects
self.Sch = [] # list of Schedule objects
for i in range(16): # 16 building types
for j in range(3): # 3 built eras
if self.bld[i][j] > 0.:
# Add to BEM list
self.BEM.append(refBEM[i][j][self.zone])
self.BEM[k].frac = self.bld[i][j]
self.BEM[k].fl_area = self.bld[i][j] * total_urban_bld_area
# Overwrite with optional parameters if provided
if self.glzR:
self.BEM[k].building.glazingRatio = self.glzR
if self.albRoof:
self.BEM[k].roof.albedo = self.albRoof
if self.vegRoof:
self.BEM[k].roof.vegCoverage = self.vegRoof
if self.SHGC:
self.BEM[k].building.shgc = self.SHGC
if self.albWall:
self.BEM[k].wall.albedo = self.albWall
if self.flr_h:
self.BEM[k].building.floorHeight = self.flr_h
# Keep track of total urban r_glaze, SHGC, and alb_wall for UCM model
self.r_glaze_total += self.BEM[k].frac * self.BEM[k].building.glazingRatio
self.SHGC_total += self.BEM[k].frac * self.BEM[k].building.shgc
self.alb_wall_total += self.BEM[k].frac * self.BEM[k].wall.albedo
# Add to schedule list
self.Sch.append(refSchedule[i][j][self.zone])
k += 1
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
self.geoParam # geographic parameters obj
self.RSM # Rural site & vertical diffusion model obj
self.USM # Urban site & vertical diffusion model obj
self.UCM # Urban canopy model obj
self.UBL # Urban boundary layer model
self.road # urban road element
self.rural # rural road element
self.soilindex1 # soil index for urban rsoad depth
self.soilindex2 # soil index for rural road depth
self.Sch # list of Schedule objects
"""
climate_file_path = os.path.join(self.epwDir, self.epwFileName)
self.simTime = SimParam(self.dtSim, self.dtWeather, self.Month,
self.Day, self.nDay) # simulation time parametrs
# weather file data for simulation time period
self.weather = Weather(climate_file_path, self.simTime.timeInitial, self.simTime.timeFinal)
self.forcIP = Forcing(self.weather.staTemp, self.weather) # initialized Forcing class
self.forc = Forcing() # empty forcing class
# Initialize geographic Param and Urban Boundary Layer Objects
nightStart = 18. # arbitrary values for begin/end hour for night setpoint
nightEnd = 8.
maxdx = 250. # max dx (m)
self.geoParam = Param(self.h_ubl1, self.h_ubl2, self.h_ref, self.h_temp, self.h_wind, self.c_circ,
self.maxDay, self.maxNight, self.latTree, self.latGrss, self.albVeg, self.vegStart, self.vegEnd,
nightStart, nightEnd, self.windMin, self.WGMAX, self.c_exch, maxdx, self.G, self.CP, self.VK, self.R,
self.RV, self.LV, math.pi, self.SIGMA, self.WATERDENS, self.LVTT, self.TT, self.ESTT, self.CL,
self.CPV, self.B, self.CM, self.COLBURN)
self.UBL = UBLDef(
'C', self.charLength, self.weather.staTemp[0], maxdx, self.geoParam.dayBLHeight, self.geoParam.nightBLHeight)
# Defining road
emis = 0.93
asphalt = Material(self.kRoad, self.cRoad, 'asphalt')
road_T_init = 293.
road_horizontal = 1
# fraction of surface vegetation coverage
road_veg_coverage = min(self.vegCover/(1-self.bldDensity), 1.)
# define road layers
road_layer_num = int(math.ceil(self.d_road/0.05))
# 0.5/0.05 ~ 10 x 1 matrix of 0.05 thickness
thickness_vector = [0.05 for r in range(road_layer_num)]
material_vector = [asphalt for r in range(road_layer_num)]
self.road = Element(self.alb_road, emis, thickness_vector, material_vector, road_veg_coverage,
road_T_init, road_horizontal, name="urban_road")
self.rural = copy.deepcopy(self.road)
self.rural.vegCoverage = self.rurVegCover
self.rural._name = "rural_road"
# Reference site class (also include VDM)
self.RSM = RSMDef(self.lat, self.lon, self.GMT, self.h_obs,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
self.USM = RSMDef(self.lat, self.lon, self.GMT, self.bldHeight/10.,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
T_init = self.weather.staTemp[0]
H_init = self.weather.staHum[0]
self.UCM = UCMDef(self.bldHeight, self.bldDensity, self.verToHor, self.treeCoverage, self.sensAnth, self.latAnth, T_init, H_init,
self.weather.staUmod[0], self.geoParam, self.r_glaze_total, self.SHGC_total, self.alb_wall_total, self.road)
self.UCM.h_mix = self.h_mix
# Define Road Element & buffer to match ground temperature depth
roadMat, newthickness = procMat(self.road, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
roadMat.append(self.SOIL)
self.soilindex1 = i
break
self.road = Element(self.road.albedo, self.road.emissivity, newthickness, roadMat,
self.road.vegCoverage, self.road.layerTemp[0], self.road.horizontal, self.road._name)
# Define Rural Element
ruralMat, newthickness = procMat(self.rural, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
ruralMat.append(self.SOIL)
self.soilindex2 = i
break
self.rural = Element(self.rural.albedo, self.rural.emissivity, newthickness,
ruralMat, self.rural.vegCoverage, self.rural.layerTemp[0], self.rural.horizontal, self.rural._name)
def hvac_autosize(self):
""" Section 6 - HVAC Autosizing (unlimited cooling & heating) """
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999.
def simulate(self):
""" Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# Output of object instance vector
self.WeatherData # Nx1 vector of forc instance
self.UCMData # Nx1 vector of UCM instance
self.UBLData # Nx1 vector of UBL instance
self.RSMData # Nx1 vector of RSM instance
self.USMData # Nx1 vector of USM instance
"""
self.N = int(self.simTime.days * 24) # total number of hours in simulation
n = 0 # weather time step counter
self.ph = self.simTime.dt/3600. # dt (simulation time step) in hours
# Data dump variables
time = range(self.N)
self.WeatherData = [None for x in range(self.N)]
self.UCMData = [None for x in range(self.N)]
self.UBLData = [None for x in range(self.N)]
self.RSMData = [None for x in range(self.N)]
self.USMData = [None for x in range(self.N)]
print('\nSimulating new temperature and humidity values for {} days from {}/{}.\n'.format(
int(self.nDay), int(self.Month), int(self.Day)))
self.logger.info("Start simulation")
for it in range(1, self.simTime.nt, 1): # for every simulation time-step (i.e 5 min) defined by uwg
# Update water temperature (estimated)
if self.nSoil < 3: # correction to original matlab code
# for BUBBLE/CAPITOUL/Singapore only
self.forc.deepTemp = sum(self.forcIP.temp)/float(len(self.forcIP.temp))
self.forc.waterTemp = sum(
self.forcIP.temp)/float(len(self.forcIP.temp)) - 10. # for BUBBLE/CAPITOUL/Singapore only
else:
# soil temperature by depth, by month
self.forc.deepTemp = self.Tsoil[self.soilindex1][self.simTime.month-1]
self.forc.waterTemp = self.Tsoil[2][self.simTime.month-1]
# There's probably a better way to update the weather...
self.simTime.UpdateDate()
self.logger.info("\n{0} m={1}, d={2}, h={3}, s={4}".format(
__name__, self.simTime.month, self.simTime.day, self.simTime.secDay/3600., self.simTime.secDay))
# simulation time increment raised to weather time step
self.ceil_time_step = int(math.ceil(it * self.ph))-1
# minus one to be consistent with forcIP list index
# Updating forcing instance
# horizontal Infrared Radiation Intensity (W m-2)
self.forc.infra = self.forcIP.infra[self.ceil_time_step]
# wind speed (m s-1)
self.forc.wind = max(self.forcIP.wind[self.ceil_time_step], self.geoParam.windMin)
self.forc.uDir = self.forcIP.uDir[self.ceil_time_step] # wind direction
# specific humidty (kg kg-1)
self.forc.hum = self.forcIP.hum[self.ceil_time_step]
self.forc.pres = self.forcIP.pres[self.ceil_time_step] # Pressure (Pa)
self.forc.temp = self.forcIP.temp[self.ceil_time_step] # air temperature (C)
self.forc.rHum = self.forcIP.rHum[self.ceil_time_step] # Relative humidity (%)
self.forc.prec = self.forcIP.prec[self.ceil_time_step] # Precipitation (mm h-1)
# horizontal solar diffuse radiation (W m-2)
self.forc.dif = self.forcIP.dif[self.ceil_time_step]
# normal solar direct radiation (W m-2)
self.forc.dir = self.forcIP.dir[self.ceil_time_step]
# Canyon humidity (absolute) same as rural
self.UCM.canHum = copy.copy(self.forc.hum)
# Update solar flux
self.solar = SolarCalcs(self.UCM, self.BEM, self.simTime,
self.RSM, self.forc, self.geoParam, self.rural)
self.rural, self.UCM, self.BEM = self.solar.solarcalcs()
# Update building & traffic schedule
# Assign day type (1 = weekday, 2 = sat, 3 = sun/other)
if self.is_near_zero(self.simTime.julian % 7):
self.dayType = 3 # Sunday
elif self.is_near_zero(self.simTime.julian % 7 - 6.):
self.dayType = 2 # Saturday
else:
self.dayType = 1 # Weekday
# Update anthropogenic heat load for each hour (building & UCM)
self.UCM.sensAnthrop = self.sensAnth * (self.SchTraffic[self.dayType-1][self.simTime.hourDay])
# Update the energy components for building types defined in initialize.uwg
for i in range(len(self.BEM)):
# Set temperature
self.BEM[i].building.coolSetpointDay = self.Sch[i].Cool[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for cooling
self.BEM[i].building.coolSetpointNight = self.BEM[i].building.coolSetpointDay
self.BEM[i].building.heatSetpointDay = self.Sch[i].Heat[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for heating
self.BEM[i].building.heatSetpointNight = self.BEM[i].building.heatSetpointDay
# Internal Heat Load Schedule (W/m^2 of floor area for Q)
self.BEM[i].Elec = self.Sch[i].Qelec * self.Sch[i].Elec[self.dayType -
1][self.simTime.hourDay] # Qelec x elec fraction for day
self.BEM[i].Light = self.Sch[i].Qlight * self.Sch[i].Light[self.dayType -
1][self.simTime.hourDay] # Qlight x light fraction for day
self.BEM[i].Nocc = self.Sch[i].Nocc * self.Sch[i].Occ[self.dayType -
1][self.simTime.hourDay] # Number of occupants x occ fraction for day
# Sensible Q occupant * fraction occupant sensible Q * number of occupants
self.BEM[i].Qocc = self.sensOcc * (1 - self.LatFOcc) * self.BEM[i].Nocc
# SWH and ventilation schedule
self.BEM[i].SWH = self.Sch[i].Vswh * self.Sch[i].SWH[self.dayType -
1][self.simTime.hourDay] # litres per hour x SWH fraction for day
# m^3/s/m^2 of floor
self.BEM[i].building.vent = self.Sch[i].Vent
self.BEM[i].Gas = self.Sch[i].Qgas * self.Sch[i].Gas[self.dayType -
1][self.simTime.hourDay] # Gas Equip Schedule, per m^2 of floor
# This is quite messy, should update
# Update internal heat and corresponding fractional loads
intHeat = self.BEM[i].Light + self.BEM[i].Elec + self.BEM[i].Qocc
# W/m2 from light, electricity, occupants
self.BEM[i].building.intHeatDay = intHeat
self.BEM[i].building.intHeatNight = intHeat
# fraction of radiant heat from light and equipment of whole internal heat
self.BEM[i].building.intHeatFRad = (
self.RadFLight * self.BEM[i].Light + self.RadFEquip * self.BEM[i].Elec) / intHeat
# fraction of latent heat (from occupants) of whole internal heat
self.BEM[i].building.intHeatFLat = self.LatFOcc * \
self.sensOcc * self.BEM[i].Nocc/intHeat
# Update envelope temperature layers
self.BEM[i].T_wallex = self.BEM[i].wall.layerTemp[0]
self.BEM[i].T_wallin = self.BEM[i].wall.layerTemp[-1]
self.BEM[i].T_roofex = self.BEM[i].roof.layerTemp[0]
self.BEM[i].T_roofin = self.BEM[i].roof.layerTemp[-1]
# Update rural heat fluxes & update vertical diffusion model (VDM)
self.rural.infra = self.forc.infra - self.rural.emissivity * self.SIGMA * \
self.rural.layerTemp[0]**4. # Infrared radiation from rural road
self.rural.SurfFlux(self.forc, self.geoParam, self.simTime,
self.forc.hum, self.forc.temp, self.forc.wind, 2., 0.)
self.RSM.VDM(self.forc, self.rural, self.geoParam, self.simTime)
# Calculate urban heat fluxes, update UCM & UBL
self.UCM, self.UBL, self.BEM = urbflux(
self.UCM, self.UBL, self.BEM, self.forc, self.geoParam, self.simTime, self.RSM)
self.UCM.UCModel(self.BEM, self.UBL.ublTemp, self.forc, self.geoParam)
self.UBL.UBLModel(self.UCM, self.RSM, self.rural,
self.forc, self.geoParam, self.simTime)
"""
# Experimental code to run diffusion model in the urban area
# N.B Commented out in python uwg because computed wind speed in
# urban VDM: y = =0.84*ln((2-x/20)/0.51) results in negative log
# for building heights >= 40m.
Uroad = copy.copy(self.UCM.road)
Uroad.sens = copy.copy(self.UCM.sensHeat)
Uforc = copy.copy(self.forc)
Uforc.wind = copy.copy(self.UCM.canWind)
Uforc.temp = copy.copy(self.UCM.canTemp)
self.USM.VDM(Uforc,Uroad,self.geoParam,self.simTime)
"""
self.logger.info("dbT = {}".format(self.UCM.canTemp-273.15))
if n > 0:
logging.info("dpT = {}".format(self.UCM.Tdp))
logging.info("RH = {}".format(self.UCM.canRHum))
if self.is_near_zero(self.simTime.secDay % self.simTime.timePrint) and n < self.N:
self.logger.info("{0} ----sim time step = {1}----\n\n".format(__name__, n))
self.WeatherData[n] = copy.copy(self.forc)
_Tdb, _w, self.UCM.canRHum, _h, self.UCM.Tdp, _v = psychrometrics(
self.UCM.canTemp, self.UCM.canHum, self.forc.pres)
self.UBLData[n] = copy.copy(self.UBL)
self.UCMData[n] = copy.copy(self.UCM)
self.RSMData[n] = copy.copy(self.RSM)
self.logger.info("dbT = {}".format(self.UCMData[n].canTemp-273.15))
self.logger.info("dpT = {}".format(self.UCMData[n].Tdp))
self.logger.info("RH = {}".format(self.UCMData[n].canRHum))
n += 1
def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] = column data of epw
self.epwinput[iJ+self.simTime.timeInitial-8][6] = "{0:.{1}f}".format(
self.UCMData[iJ].canTemp - 273.15, epw_prec) # dry bulb temperature [?C]
# dew point temperature [?C]
self.epwinput[iJ+self.simTime.timeInitial -
8][7] = "{0:.{1}f}".format(self.UCMData[iJ].Tdp, epw_prec)
# relative humidity [%]
self.epwinput[iJ+self.simTime.timeInitial -
8][8] = "{0:.{1}f}".format(self.UCMData[iJ].canRHum, epw_prec)
self.epwinput[iJ+self.simTime.timeInitial-8][21] = "{0:.{1}f}".format(
self.WeatherData[iJ].wind, epw_prec) # wind speed [m/s]
# Writing new EPW file
epw_new_id = open(self.newPathName, "w")
for i in range(8):
new_epw_line = '{}\n'.format(reduce(lambda x, y: x+","+y, self._header[i]))
epw_new_id.write(new_epw_line)
for i in range(len(self.epwinput)):
printme = ""
for ei in range(34):
printme += "{}".format(self.epwinput[i][ei]) + ','
printme = printme + "{}".format(self.epwinput[i][ei])
new_epw_line = "{0}\n".format(printme)
epw_new_id.write(new_epw_line)
epw_new_id.close()
print("New climate file '{}' is generated at {}.".format(
self.destinationFileName, self.destinationDir))
def run(self):
# run main class methods
self.read_epw()
self.set_input()
self.init_BEM_obj()
self.init_input_obj()
self.hvac_autosize()
self.simulate()
self.write_epw()
|
ladybug-tools/uwg | uwg/uwg.py | uwg.init_BEM_obj | python | def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total building stock
"""
if not os.path.exists(self.readDOE_file_path):
raise Exception("readDOE.pkl file: '{}' does not exist.".format(readDOE_file_path))
readDOE_file = open(self.readDOE_file_path, 'rb') # open pickle file in binary form
refDOE = pickle.load(readDOE_file)
refBEM = pickle.load(readDOE_file)
refSchedule = pickle.load(readDOE_file)
readDOE_file.close()
# Define building energy models
k = 0
self.r_glaze_total = 0. # Glazing ratio for total building stock
self.SHGC_total = 0. # SHGC addition for total building stock
self.alb_wall_total = 0. # albedo wall addition for total building stock
h_floor = self.flr_h or 3.05 # average floor height
total_urban_bld_area = math.pow(self.charLength, 2)*self.bldDensity * \
self.bldHeight/h_floor # total building floor area
area_matrix = utilities.zeros(16, 3)
self.BEM = [] # list of BEMDef objects
self.Sch = [] # list of Schedule objects
for i in range(16): # 16 building types
for j in range(3): # 3 built eras
if self.bld[i][j] > 0.:
# Add to BEM list
self.BEM.append(refBEM[i][j][self.zone])
self.BEM[k].frac = self.bld[i][j]
self.BEM[k].fl_area = self.bld[i][j] * total_urban_bld_area
# Overwrite with optional parameters if provided
if self.glzR:
self.BEM[k].building.glazingRatio = self.glzR
if self.albRoof:
self.BEM[k].roof.albedo = self.albRoof
if self.vegRoof:
self.BEM[k].roof.vegCoverage = self.vegRoof
if self.SHGC:
self.BEM[k].building.shgc = self.SHGC
if self.albWall:
self.BEM[k].wall.albedo = self.albWall
if self.flr_h:
self.BEM[k].building.floorHeight = self.flr_h
# Keep track of total urban r_glaze, SHGC, and alb_wall for UCM model
self.r_glaze_total += self.BEM[k].frac * self.BEM[k].building.glazingRatio
self.SHGC_total += self.BEM[k].frac * self.BEM[k].building.shgc
self.alb_wall_total += self.BEM[k].frac * self.BEM[k].wall.albedo
# Add to schedule list
self.Sch.append(refSchedule[i][j][self.zone])
k += 1 | Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total building stock | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/uwg.py#L550-L610 | [
"def zeros(h, w):\n \"\"\"create a (h x w) matrix of zeros.\n\n Args:\n h: Height of the matrix.\n w: Width of the matrix.\n \"\"\"\n return [[0 for x in range(w)] for y in range(h)]\n"
] | class uwg(object):
"""Morph a rural EPW file to urban conditions using a file with a list of urban parameters.
args:
epwDir: The directory in which the rural EPW file sits.
epwFileName: The name of the rural epw file that will be morphed.
uwgParamDir: The directory in which the uwg Parameter File (.uwg) sits.
uwgParamFileName: The name of the uwg Parameter File (.uwg).
destinationDir: Optional destination directory for the morphed EPW file.
If left blank, the morphed file will be written into the same directory
as the rural EPW file (the epwDir).
destinationFileName: Optional destination file name for the morphed EPW file.
If left blank, the morphed file will append "_UWG" to the original file name.
returns:
newClimateFile: the path to a new EPW file that has been morphed to account
for uban conditions.
"""
""" Section 1 - Definitions for constants / other parameters """
MINTHICKNESS = 0.01 # Minimum layer thickness (to prevent crashing) (m)
MAXTHICKNESS = 0.05 # Maximum layer thickness (m)
# http://web.mit.edu/parmstr/Public/NRCan/nrcc29118.pdf (Figly & Snodgrass)
SOILTCOND = 1
# http://www.europment.org/library/2013/venice/bypaper/MFHEEF/MFHEEF-21.pdf (average taken from Table 1)
SOILVOLHEAT = 2e6
# Soil material used for soil-depth padding
SOIL = Material(SOILTCOND, SOILVOLHEAT, name="soil")
# Physical constants
G = 9.81 # gravity (m s-2)
CP = 1004. # heat capacity for air (J/kg K)
VK = 0.40 # von karman constant (dimensionless)
R = 287. # gas constant dry air (J/kg K)
RV = 461.5 # gas constant water vapor (J/kg K)
LV = 2.26e6 # latent heat of evaporation (J/kg)
SIGMA = 5.67e-08 # Stefan Boltzmann constant (W m-2 K-4)
WATERDENS = 1000. # water density (kg m-3)
LVTT = 2.5008e6 #
TT = 273.16 #
ESTT = 611.14 #
CL = 4.218e3 #
CPV = 1846.1 #
B = 9.4 # Coefficients derived by Louis (1979)
CM = 7.4 #
# (Pr/Sc)^(2/3) for Colburn analogy in water evaporation
COLBURN = math.pow((0.713/0.621), (2/3.))
# Site-specific parameters
WGMAX = 0.005 # maximum film water depth on horizontal surfaces (m)
# File path parameter
RESOURCE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "resources"))
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
def __init__(self, epwFileName, uwgParamFileName=None, epwDir=None, uwgParamDir=None, destinationDir=None, destinationFileName=None):
# Logger will be disabled by default unless explicitly called in tests
self.logger = logging.getLogger(__name__)
# User defined
self.epwFileName = epwFileName if epwFileName.lower().endswith('.epw') else epwFileName + \
'.epw' # Revise epw file name if not end with epw
# If file name is entered then will uwg will set input from .uwg file
self.uwgParamFileName = uwgParamFileName
# If user does not overload
self.destinationFileName = destinationFileName if destinationFileName else self.epwFileName.strip(
'.epw') + '_UWG.epw'
self.epwDir = epwDir if epwDir else os.path.join(self.RESOURCE_PATH, "epw")
self.uwgParamDir = uwgParamDir if uwgParamDir else os.path.join(
self.RESOURCE_PATH, "parameters")
self.destinationDir = destinationDir if destinationDir else os.path.join(
self.RESOURCE_PATH, "epw_uwg")
# refdata: Serialized DOE reference data, z_meso height data
self.readDOE_file_path = os.path.join(self.CURRENT_PATH, "refdata", "readDOE.pkl")
self.z_meso_dir_path = os.path.join(self.CURRENT_PATH, "refdata")
# EPW precision
self.epw_precision = 1
# init uwg variables
self._init_param_dict = None
# Define Simulation and Weather parameters
self.Month = None # starting month (1-12)
self.Day = None # starting day (1-31)
self.nDay = None # number of days
self.dtSim = None # simulation time step (s)
self.dtWeather = None # seconds (s)
# HVAC system and internal laod
self.autosize = None # autosize HVAC (1 or 0)
self.sensOcc = None # Sensible heat from occupant
self.LatFOcc = None # Latent heat fraction from occupant (normally 0.3)
self.RadFOcc = None # Radiant heat fraction from occupant (normally 0.2)
self.RadFEquip = None # Radiant heat fraction from equipment (normally 0.5)
self.RadFLight = None # Radiant heat fraction from light (normally 0.7)
# Define Urban microclimate parameters
self.h_ubl1 = None # ubl height - day (m)
self.h_ubl2 = None # ubl height - night (m)
self.h_ref = None # inversion height
self.h_temp = None # temperature height
self.h_wind = None # wind height
self.c_circ = None # circulation coefficient
self.c_exch = None # exchange coefficient
self.maxDay = None # max day threshhold
self.maxNight = None # max night threshhold
self.windMin = None # min wind speed (m/s)
self.h_obs = None # rural average obstacle height
# Urban characteristics
self.bldHeight = None # average building height (m)
self.h_mix = None # mixing height (m)
self.bldDensity = None # building density (0-1)
self.verToHor = None # building aspect ratio
# radius defining the urban area of study [aka. characteristic length] (m)
self.charLength = None
self.alb_road = None # road albedo
self.d_road = None # road pavement thickness
self.sensAnth = None # non-building sensible heat (W/m^2)
self.latAnth = None # non-building latent heat heat (W/m^2). Not used, taken out by JH.
# Fraction of building typology stock
self.bld = None # 16x3 matrix of fraction of building type by era
# climate Zone
self.zone = None
# Vegetation parameters
self.vegCover = None # urban area veg coverage ratio
self.treeCoverage = None # urban area tree coverage ratio
self.vegStart = None # vegetation start month
self.vegEnd = None # vegetation end month
self.albVeg = None # Vegetation albedo
self.rurVegCover = None # rural vegetation cover
self.latGrss = None # latent fraction of grass
self.latTree = None # latent fraction of tree
# Define Traffic schedule
self.SchTraffic = None
# Define Road (Assume 0.5m of asphalt)
self.kRoad = None # road pavement conductivity (W/m K)
self.cRoad = None # road volumetric heat capacity (J/m^3 K)
# Define optional Building characteristics
self.flr_h = None # floor-to-floor height
self.albRoof = None # roof albedo (0 - 1)
self.vegRoof = None # Fraction of the roofs covered in grass/shrubs (0-1)
self.glzR = None # Glazing Ratio
self.SHGC = None # Solar Heat Gain Coefficient
self.albWall = None # Wall albedo
def ToString(self):
"""Overwrite .NET ToString method."""
return self.__repr__()
def __repr__(self):
def _split_string(s):
return s[0] + ":\n " + s[1].replace(",", "\n ")
def _tabbed(s):
return _split_string(s.__repr__().split(":"))
def _list_2_tabbed(b):
return reduce(lambda a, b: a+"\n"+b, [_tabbed(_b) for _b in b])
return "uwg for {}:\n\n{}{}{}{}{}{}{}{}".format(
self.epwFileName,
_tabbed(self.simTime)+"\n" if hasattr(self, "simTime") else "No simTime attr.\n",
_tabbed(self.weather)+"\n" if hasattr(self, "weather") else "No weather attr.\n",
_tabbed(self.geoParam)+"\n" if hasattr(self, "geoParam") else "No geoParam attr.\n",
_tabbed(self.UBL)+"\n" if hasattr(self, "UBL") else "No UBL attr.\n",
"Rural "+_tabbed(self.RSM)+"\n" if hasattr(self, "RSM") else "No Rural RSM attr.\n",
"Urban "+_tabbed(self.USM)+"\n" if hasattr(self, "USM") else "No Urban RSM attr.\n",
_tabbed(self.UCM)+"\n" if hasattr(self, "UCM") else "No UCM attr.\n",
_list_2_tabbed(self.BEM) if hasattr(self, "BEM") else "No BEM attr."
)
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def read_epw(self):
"""Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT # GMT
self.nSoil # Number of soil depths
self.Tsoil # nSoil x 12 matrix for soil temperture (K)
self.depth_soil # nSoil x 1 matrix for soil depth (m)
"""
# Make dir path to epw file
self.climateDataPath = os.path.join(self.epwDir, self.epwFileName)
# Open epw file and feed csv data to climate_data
try:
climate_data = utilities.read_csv(self.climateDataPath)
except Exception as e:
raise Exception("Failed to read epw file! {}".format(e.message))
# Read header lines (1 to 8) from EPW and ensure TMY2 format.
self._header = climate_data[0:8]
# Read weather data from EPW for each time step in weather file. (lines 8 - end)
self.epwinput = climate_data[8:]
# Read Lat, Long (line 1 of EPW)
self.lat = float(self._header[0][6])
self.lon = float(self._header[0][7])
self.GMT = float(self._header[0][8])
# Read in soil temperature data (assumes this is always there)
# ref: http://bigladdersoftware.com/epx/docs/8-2/auxiliary-programs/epw-csv-format-inout.html
soilData = self._header[3]
self.nSoil = int(soilData[1]) # Number of ground temperature depths
self.Tsoil = utilities.zeros(self.nSoil, 12) # nSoil x 12 matrix for soil temperture (K)
self.depth_soil = utilities.zeros(self.nSoil, 1) # nSoil x 1 matrix for soil depth (m)
# Read monthly data for each layer of soil from EPW file
for i in range(self.nSoil):
self.depth_soil[i][0] = float(soilData[2 + (i*16)]) # get soil depth for each nSoil
# Monthly data
for j in range(12):
# 12 months of soil T for specific depth
self.Tsoil[i][j] = float(soilData[6 + (i*16) + j]) + 273.15
# Set new directory path for the moprhed EPW file
self.newPathName = os.path.join(self.destinationDir, self.destinationFileName)
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic # Traffice schedule
self.BEM # list of BEMDef objects extracted from readDOE
self.Sch # list of Schedule objects extracted from readDOE
"""
uwg_param_file_path = os.path.join(self.uwgParamDir, self.uwgParamFileName)
if not os.path.exists(uwg_param_file_path):
raise Exception("Param file: '{}' does not exist.".format(uwg_param_file_path))
# Open .uwg file and feed csv data to initializeDataFile
try:
uwg_param_data = utilities.read_csv(uwg_param_file_path)
except Exception as e:
raise Exception("Failed to read .uwg file! {}".format(e.message))
# The initialize.uwg is read with a dictionary so that users changing
# line endings or line numbers doesn't make reading input incorrect
self._init_param_dict = {}
count = 0
while count < len(uwg_param_data):
row = uwg_param_data[count]
row = [row[i].replace(" ", "") for i in range(len(row))] # strip white spaces
# Optional parameters might be empty so handle separately
is_optional_parameter = (
row != [] and
(
row[0] == "albRoof" or
row[0] == "vegRoof" or
row[0] == "glzR" or
row[0] == "hvac" or
row[0] == "albWall" or
row[0] == "SHGC"
)
)
try:
if row == [] or "#" in row[0]:
count += 1
continue
elif row[0] == "SchTraffic":
# SchTraffic: 3 x 24 matrix
trafficrows = uwg_param_data[count+1:count+4]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:24]) for r in trafficrows]
count += 4
elif row[0] == "bld":
# bld: 17 x 3 matrix
bldrows = uwg_param_data[count+1:count+17]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:3]) for r in bldrows]
count += 17
elif is_optional_parameter:
self._init_param_dict[row[0]] = float(row[1]) if row[1] != "" else None
count += 1
else:
self._init_param_dict[row[0]] = float(row[1])
count += 1
except ValueError:
print("Error while reading parameter at {} {}".format(count, row))
ipd = self._init_param_dict
# Define Simulation and Weather parameters
if self.Month is None: self.Month = ipd['Month']
if self.Day is None: self.Day = ipd['Day']
if self.nDay is None: self.nDay = ipd['nDay']
if self.dtSim is None: self.dtSim = ipd['dtSim']
if self.dtWeather is None: self.dtWeather = ipd['dtWeather']
# HVAC system and internal laod
if self.autosize is None: self.autosize = ipd['autosize']
if self.sensOcc is None: self.sensOcc = ipd['sensOcc']
if self.LatFOcc is None: self.LatFOcc = ipd['LatFOcc']
if self.RadFOcc is None: self.RadFOcc = ipd['RadFOcc']
if self.RadFEquip is None: self.RadFEquip = ipd['RadFEquip']
if self.RadFLight is None: self.RadFLight = ipd['RadFLight']
# Define Urban microclimate parameters
if self.h_ubl1 is None: self.h_ubl1 = ipd['h_ubl1']
if self.h_ubl2 is None: self.h_ubl2 = ipd['h_ubl2']
if self.h_ref is None: self.h_ref = ipd['h_ref']
if self.h_temp is None: self.h_temp = ipd['h_temp']
if self.h_wind is None: self.h_wind = ipd['h_wind']
if self.c_circ is None: self.c_circ = ipd['c_circ']
if self.c_exch is None: self.c_exch = ipd['c_exch']
if self.maxDay is None: self.maxDay = ipd['maxDay']
if self.maxNight is None: self.maxNight = ipd['maxNight']
if self.windMin is None: self.windMin = ipd['windMin']
if self.h_obs is None: self.h_obs = ipd['h_obs']
# Urban characteristics
if self.bldHeight is None: self.bldHeight = ipd['bldHeight']
if self.h_mix is None: self.h_mix = ipd['h_mix']
if self.bldDensity is None: self.bldDensity = ipd['bldDensity']
if self.verToHor is None: self.verToHor = ipd['verToHor']
if self.charLength is None: self.charLength = ipd['charLength']
if self.alb_road is None: self.alb_road = ipd['albRoad']
if self.d_road is None: self.d_road = ipd['dRoad']
if self.sensAnth is None: self.sensAnth = ipd['sensAnth']
# if self.latAnth is None: self.latAnth = ipd['latAnth'] # Not used, taken out by JH.
# climate Zone
if self.zone is None: self.zone = ipd['zone']
# Vegetation parameters
if self.vegCover is None: self.vegCover = ipd['vegCover']
if self.treeCoverage is None: self.treeCoverage = ipd['treeCoverage']
if self.vegStart is None: self.vegStart = ipd['vegStart']
if self.vegEnd is None: self.vegEnd = ipd['vegEnd']
if self.albVeg is None: self.albVeg = ipd['albVeg']
if self.rurVegCover is None: self.rurVegCover = ipd['rurVegCover']
if self.latGrss is None: self.latGrss = ipd['latGrss']
if self.latTree is None: self.latTree = ipd['latTree']
# Define Traffic schedule
if self.SchTraffic is None: self.SchTraffic = ipd['SchTraffic']
# Define Road (Assume 0.5m of asphalt)
if self.kRoad is None: self.kRoad = ipd['kRoad']
if self.cRoad is None: self.cRoad = ipd['cRoad']
# Building stock fraction
if self.bld is None: self.bld = ipd['bld']
# Optional parameters
if self.albRoof is None: self.albRoof = ipd['albRoof']
if self.vegRoof is None: self.vegRoof = ipd['vegRoof']
if self.glzR is None: self.glzR = ipd['glzR']
if self.albWall is None: self.albWall = ipd['albWall']
if self.SHGC is None: self.SHGC = ipd['SHGC']
def check_required_inputs(self):
# Fail if required parameters aren't correct
assert isinstance(self.Month, (float, int)), \
'Month must be a number. Got {}'.format(type(self.Month))
assert isinstance(self.Day, (float, int)), \
'Day must be a number. Got {}'.format(type(self.Day))
assert isinstance(self.nDay, (float, int)), \
'nDay must be a number. Got {}'.format(type(self.nDay))
assert isinstance(self.dtSim, float), \
'dtSim must be a float. Got {}'.format(type(self.dtSim))
assert isinstance(self.dtWeather, float), \
'dtWeather must be a float. Got {}'.format(type(self.dtWeather))
assert isinstance(self.autosize, (float, int)), \
'autosize must be a number. Got {}'.format(type(self.autosize))
assert isinstance(self.sensOcc, float), \
'sensOcc must be a float. Got {}'.format(type(self.sensOcc))
assert isinstance(self.LatFOcc, float), \
'LatFOcc must be a float. Got {}'.format(type(self.LatFOcc))
assert isinstance(self.RadFOcc, float), \
'RadFOcc must be a float. Got {}'.format(type(self.RadFOcc))
assert isinstance(self.RadFEquip, float), \
'RadFEquip must be a float. Got {}'.format(type(self.RadFEquip))
assert isinstance(self.RadFLight, float), \
'RadFLight must be a float. Got {}'.format(type(self.RadFLight))
assert isinstance(self.h_ubl1, float), \
'h_ubl1 must be a float. Got {}'.format(type(self.h_ubl1))
assert isinstance(self.h_ubl2, float), \
'h_ubl2 must be a float. Got {}'.format(type(self.h_ubl2))
assert isinstance(self.h_ref, float), \
'h_ref must be a float. Got {}'.format(type(self.h_ref))
assert isinstance(self.h_temp, float), \
'h_temp must be a float. Got {}'.format(type(self.h_temp))
assert isinstance(self.h_wind, float), \
'h_wind must be a float. Got {}'.format(type(self.h_wind))
assert isinstance(self.c_circ, float), \
'c_circ must be a float. Got {}'.format(type(self.c_circ))
assert isinstance(self.c_exch, float), \
'c_exch must be a float. Got {}'.format(type(self.c_exch))
assert isinstance(self.maxDay, float), \
'maxDay must be a float. Got {}'.format(type(self.maxDay))
assert isinstance(self.maxNight, float), \
'maxNight must be a float. Got {}'.format(type(self.maxNight))
assert isinstance(self.windMin, float), \
'windMin must be a float. Got {}'.format(type(self.windMin))
assert isinstance(self.h_obs, float), \
'h_obs must be a float. Got {}'.format(type(self.h_obs))
assert isinstance(self.bldHeight, float), \
'bldHeight must be a float. Got {}'.format(type(self.bldHeight))
assert isinstance(self.h_mix, float), \
'h_mix must be a float. Got {}'.format(type(self.h_mix))
assert isinstance(self.bldDensity, float), \
'bldDensity must be a float. Got {}'.format(type(self.bldDensity))
assert isinstance(self.verToHor, float), \
'verToHor must be a float. Got {}'.format(type(self.verToHor))
assert isinstance(self.charLength, float), \
'charLength must be a float. Got {}'.format(type(self.charLength))
assert isinstance(self.alb_road, float), \
'alb_road must be a float. Got {}'.format(type(self.alb_road))
assert isinstance(self.d_road, float), \
'd_road must be a float. Got {}'.format(type(self.d_road))
assert isinstance(self.sensAnth, float), \
'sensAnth must be a float. Got {}'.format(type(self.sensAnth))
# assert isinstance(self.latAnth, float) # Take this out as isn't being used
assert isinstance(self.bld, list), \
'bld must be a list. Got {}'.format(type(self.bld))
assert len(self.bld) == 16, \
'length of bld must be 16. Got {}'.format(len(self.bld))
assert isinstance(self.latTree, float), \
'latTree must be a float. Got {}'.format(type(self.latTree))
assert isinstance(self.latGrss, float), \
'latGrss must be a float. Got {}'.format(type(self.latGrss))
assert isinstance(self.zone, (float, int)), \
'zone must be a number. Got {}'.format(type(self.zone))
assert isinstance(self.vegStart, (float, int)), \
'vegStart must be a number. Got {}'.format(type(self.vegStart))
assert isinstance(self.vegEnd, (float, int)), \
'vegEnd must be a number. Got {}'.format(type(self.vegEnd))
assert isinstance(self.vegCover, float), \
'vegCover must be a float. Got {}'.format(type(self.vegCover))
assert isinstance(self.treeCoverage, float), \
'treeCoverage must be a float. Got {}'.format(type(self.treeCoverage))
assert isinstance(self.albVeg, float), \
'albVeg must be a float. Got {}'.format(type(self.albVeg))
assert isinstance(self.rurVegCover, float), \
'rurVegCover must be a float. Got {}'.format(type(self.rurVegCover))
assert isinstance(self.kRoad, float), \
'kRoad must be a float. Got {}'.format(type(self.kRoad))
assert isinstance(self.cRoad, float), \
'cRoad must be a float. Got {}'.format(type(self.cRoad))
assert isinstance(self.SchTraffic, list), \
'SchTraffic must be a list. Got {}'.format(type(self.SchTraffic))
assert len(self.SchTraffic) == 3, \
'length of SchTraffic must be 3. Got {}'.format(len(self.SchTraffic))
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the .uwg file.
if self.uwgParamFileName is not None:
print("\nReading uwg file input.")
self.read_input()
else:
print("\nNo .uwg file input.")
self.check_required_inputs()
# Modify zone to be used as python index
self.zone = int(self.zone)-1
def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total building stock
"""
if not os.path.exists(self.readDOE_file_path):
raise Exception("readDOE.pkl file: '{}' does not exist.".format(readDOE_file_path))
readDOE_file = open(self.readDOE_file_path, 'rb') # open pickle file in binary form
refDOE = pickle.load(readDOE_file)
refBEM = pickle.load(readDOE_file)
refSchedule = pickle.load(readDOE_file)
readDOE_file.close()
# Define building energy models
k = 0
self.r_glaze_total = 0. # Glazing ratio for total building stock
self.SHGC_total = 0. # SHGC addition for total building stock
self.alb_wall_total = 0. # albedo wall addition for total building stock
h_floor = self.flr_h or 3.05 # average floor height
total_urban_bld_area = math.pow(self.charLength, 2)*self.bldDensity * \
self.bldHeight/h_floor # total building floor area
area_matrix = utilities.zeros(16, 3)
self.BEM = [] # list of BEMDef objects
self.Sch = [] # list of Schedule objects
for i in range(16): # 16 building types
for j in range(3): # 3 built eras
if self.bld[i][j] > 0.:
# Add to BEM list
self.BEM.append(refBEM[i][j][self.zone])
self.BEM[k].frac = self.bld[i][j]
self.BEM[k].fl_area = self.bld[i][j] * total_urban_bld_area
# Overwrite with optional parameters if provided
if self.glzR:
self.BEM[k].building.glazingRatio = self.glzR
if self.albRoof:
self.BEM[k].roof.albedo = self.albRoof
if self.vegRoof:
self.BEM[k].roof.vegCoverage = self.vegRoof
if self.SHGC:
self.BEM[k].building.shgc = self.SHGC
if self.albWall:
self.BEM[k].wall.albedo = self.albWall
if self.flr_h:
self.BEM[k].building.floorHeight = self.flr_h
# Keep track of total urban r_glaze, SHGC, and alb_wall for UCM model
self.r_glaze_total += self.BEM[k].frac * self.BEM[k].building.glazingRatio
self.SHGC_total += self.BEM[k].frac * self.BEM[k].building.shgc
self.alb_wall_total += self.BEM[k].frac * self.BEM[k].wall.albedo
# Add to schedule list
self.Sch.append(refSchedule[i][j][self.zone])
k += 1
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
self.geoParam # geographic parameters obj
self.RSM # Rural site & vertical diffusion model obj
self.USM # Urban site & vertical diffusion model obj
self.UCM # Urban canopy model obj
self.UBL # Urban boundary layer model
self.road # urban road element
self.rural # rural road element
self.soilindex1 # soil index for urban rsoad depth
self.soilindex2 # soil index for rural road depth
self.Sch # list of Schedule objects
"""
climate_file_path = os.path.join(self.epwDir, self.epwFileName)
self.simTime = SimParam(self.dtSim, self.dtWeather, self.Month,
self.Day, self.nDay) # simulation time parametrs
# weather file data for simulation time period
self.weather = Weather(climate_file_path, self.simTime.timeInitial, self.simTime.timeFinal)
self.forcIP = Forcing(self.weather.staTemp, self.weather) # initialized Forcing class
self.forc = Forcing() # empty forcing class
# Initialize geographic Param and Urban Boundary Layer Objects
nightStart = 18. # arbitrary values for begin/end hour for night setpoint
nightEnd = 8.
maxdx = 250. # max dx (m)
self.geoParam = Param(self.h_ubl1, self.h_ubl2, self.h_ref, self.h_temp, self.h_wind, self.c_circ,
self.maxDay, self.maxNight, self.latTree, self.latGrss, self.albVeg, self.vegStart, self.vegEnd,
nightStart, nightEnd, self.windMin, self.WGMAX, self.c_exch, maxdx, self.G, self.CP, self.VK, self.R,
self.RV, self.LV, math.pi, self.SIGMA, self.WATERDENS, self.LVTT, self.TT, self.ESTT, self.CL,
self.CPV, self.B, self.CM, self.COLBURN)
self.UBL = UBLDef(
'C', self.charLength, self.weather.staTemp[0], maxdx, self.geoParam.dayBLHeight, self.geoParam.nightBLHeight)
# Defining road
emis = 0.93
asphalt = Material(self.kRoad, self.cRoad, 'asphalt')
road_T_init = 293.
road_horizontal = 1
# fraction of surface vegetation coverage
road_veg_coverage = min(self.vegCover/(1-self.bldDensity), 1.)
# define road layers
road_layer_num = int(math.ceil(self.d_road/0.05))
# 0.5/0.05 ~ 10 x 1 matrix of 0.05 thickness
thickness_vector = [0.05 for r in range(road_layer_num)]
material_vector = [asphalt for r in range(road_layer_num)]
self.road = Element(self.alb_road, emis, thickness_vector, material_vector, road_veg_coverage,
road_T_init, road_horizontal, name="urban_road")
self.rural = copy.deepcopy(self.road)
self.rural.vegCoverage = self.rurVegCover
self.rural._name = "rural_road"
# Reference site class (also include VDM)
self.RSM = RSMDef(self.lat, self.lon, self.GMT, self.h_obs,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
self.USM = RSMDef(self.lat, self.lon, self.GMT, self.bldHeight/10.,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
T_init = self.weather.staTemp[0]
H_init = self.weather.staHum[0]
self.UCM = UCMDef(self.bldHeight, self.bldDensity, self.verToHor, self.treeCoverage, self.sensAnth, self.latAnth, T_init, H_init,
self.weather.staUmod[0], self.geoParam, self.r_glaze_total, self.SHGC_total, self.alb_wall_total, self.road)
self.UCM.h_mix = self.h_mix
# Define Road Element & buffer to match ground temperature depth
roadMat, newthickness = procMat(self.road, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
roadMat.append(self.SOIL)
self.soilindex1 = i
break
self.road = Element(self.road.albedo, self.road.emissivity, newthickness, roadMat,
self.road.vegCoverage, self.road.layerTemp[0], self.road.horizontal, self.road._name)
# Define Rural Element
ruralMat, newthickness = procMat(self.rural, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
ruralMat.append(self.SOIL)
self.soilindex2 = i
break
self.rural = Element(self.rural.albedo, self.rural.emissivity, newthickness,
ruralMat, self.rural.vegCoverage, self.rural.layerTemp[0], self.rural.horizontal, self.rural._name)
def hvac_autosize(self):
""" Section 6 - HVAC Autosizing (unlimited cooling & heating) """
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999.
def simulate(self):
""" Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# Output of object instance vector
self.WeatherData # Nx1 vector of forc instance
self.UCMData # Nx1 vector of UCM instance
self.UBLData # Nx1 vector of UBL instance
self.RSMData # Nx1 vector of RSM instance
self.USMData # Nx1 vector of USM instance
"""
self.N = int(self.simTime.days * 24) # total number of hours in simulation
n = 0 # weather time step counter
self.ph = self.simTime.dt/3600. # dt (simulation time step) in hours
# Data dump variables
time = range(self.N)
self.WeatherData = [None for x in range(self.N)]
self.UCMData = [None for x in range(self.N)]
self.UBLData = [None for x in range(self.N)]
self.RSMData = [None for x in range(self.N)]
self.USMData = [None for x in range(self.N)]
print('\nSimulating new temperature and humidity values for {} days from {}/{}.\n'.format(
int(self.nDay), int(self.Month), int(self.Day)))
self.logger.info("Start simulation")
for it in range(1, self.simTime.nt, 1): # for every simulation time-step (i.e 5 min) defined by uwg
# Update water temperature (estimated)
if self.nSoil < 3: # correction to original matlab code
# for BUBBLE/CAPITOUL/Singapore only
self.forc.deepTemp = sum(self.forcIP.temp)/float(len(self.forcIP.temp))
self.forc.waterTemp = sum(
self.forcIP.temp)/float(len(self.forcIP.temp)) - 10. # for BUBBLE/CAPITOUL/Singapore only
else:
# soil temperature by depth, by month
self.forc.deepTemp = self.Tsoil[self.soilindex1][self.simTime.month-1]
self.forc.waterTemp = self.Tsoil[2][self.simTime.month-1]
# There's probably a better way to update the weather...
self.simTime.UpdateDate()
self.logger.info("\n{0} m={1}, d={2}, h={3}, s={4}".format(
__name__, self.simTime.month, self.simTime.day, self.simTime.secDay/3600., self.simTime.secDay))
# simulation time increment raised to weather time step
self.ceil_time_step = int(math.ceil(it * self.ph))-1
# minus one to be consistent with forcIP list index
# Updating forcing instance
# horizontal Infrared Radiation Intensity (W m-2)
self.forc.infra = self.forcIP.infra[self.ceil_time_step]
# wind speed (m s-1)
self.forc.wind = max(self.forcIP.wind[self.ceil_time_step], self.geoParam.windMin)
self.forc.uDir = self.forcIP.uDir[self.ceil_time_step] # wind direction
# specific humidty (kg kg-1)
self.forc.hum = self.forcIP.hum[self.ceil_time_step]
self.forc.pres = self.forcIP.pres[self.ceil_time_step] # Pressure (Pa)
self.forc.temp = self.forcIP.temp[self.ceil_time_step] # air temperature (C)
self.forc.rHum = self.forcIP.rHum[self.ceil_time_step] # Relative humidity (%)
self.forc.prec = self.forcIP.prec[self.ceil_time_step] # Precipitation (mm h-1)
# horizontal solar diffuse radiation (W m-2)
self.forc.dif = self.forcIP.dif[self.ceil_time_step]
# normal solar direct radiation (W m-2)
self.forc.dir = self.forcIP.dir[self.ceil_time_step]
# Canyon humidity (absolute) same as rural
self.UCM.canHum = copy.copy(self.forc.hum)
# Update solar flux
self.solar = SolarCalcs(self.UCM, self.BEM, self.simTime,
self.RSM, self.forc, self.geoParam, self.rural)
self.rural, self.UCM, self.BEM = self.solar.solarcalcs()
# Update building & traffic schedule
# Assign day type (1 = weekday, 2 = sat, 3 = sun/other)
if self.is_near_zero(self.simTime.julian % 7):
self.dayType = 3 # Sunday
elif self.is_near_zero(self.simTime.julian % 7 - 6.):
self.dayType = 2 # Saturday
else:
self.dayType = 1 # Weekday
# Update anthropogenic heat load for each hour (building & UCM)
self.UCM.sensAnthrop = self.sensAnth * (self.SchTraffic[self.dayType-1][self.simTime.hourDay])
# Update the energy components for building types defined in initialize.uwg
for i in range(len(self.BEM)):
# Set temperature
self.BEM[i].building.coolSetpointDay = self.Sch[i].Cool[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for cooling
self.BEM[i].building.coolSetpointNight = self.BEM[i].building.coolSetpointDay
self.BEM[i].building.heatSetpointDay = self.Sch[i].Heat[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for heating
self.BEM[i].building.heatSetpointNight = self.BEM[i].building.heatSetpointDay
# Internal Heat Load Schedule (W/m^2 of floor area for Q)
self.BEM[i].Elec = self.Sch[i].Qelec * self.Sch[i].Elec[self.dayType -
1][self.simTime.hourDay] # Qelec x elec fraction for day
self.BEM[i].Light = self.Sch[i].Qlight * self.Sch[i].Light[self.dayType -
1][self.simTime.hourDay] # Qlight x light fraction for day
self.BEM[i].Nocc = self.Sch[i].Nocc * self.Sch[i].Occ[self.dayType -
1][self.simTime.hourDay] # Number of occupants x occ fraction for day
# Sensible Q occupant * fraction occupant sensible Q * number of occupants
self.BEM[i].Qocc = self.sensOcc * (1 - self.LatFOcc) * self.BEM[i].Nocc
# SWH and ventilation schedule
self.BEM[i].SWH = self.Sch[i].Vswh * self.Sch[i].SWH[self.dayType -
1][self.simTime.hourDay] # litres per hour x SWH fraction for day
# m^3/s/m^2 of floor
self.BEM[i].building.vent = self.Sch[i].Vent
self.BEM[i].Gas = self.Sch[i].Qgas * self.Sch[i].Gas[self.dayType -
1][self.simTime.hourDay] # Gas Equip Schedule, per m^2 of floor
# This is quite messy, should update
# Update internal heat and corresponding fractional loads
intHeat = self.BEM[i].Light + self.BEM[i].Elec + self.BEM[i].Qocc
# W/m2 from light, electricity, occupants
self.BEM[i].building.intHeatDay = intHeat
self.BEM[i].building.intHeatNight = intHeat
# fraction of radiant heat from light and equipment of whole internal heat
self.BEM[i].building.intHeatFRad = (
self.RadFLight * self.BEM[i].Light + self.RadFEquip * self.BEM[i].Elec) / intHeat
# fraction of latent heat (from occupants) of whole internal heat
self.BEM[i].building.intHeatFLat = self.LatFOcc * \
self.sensOcc * self.BEM[i].Nocc/intHeat
# Update envelope temperature layers
self.BEM[i].T_wallex = self.BEM[i].wall.layerTemp[0]
self.BEM[i].T_wallin = self.BEM[i].wall.layerTemp[-1]
self.BEM[i].T_roofex = self.BEM[i].roof.layerTemp[0]
self.BEM[i].T_roofin = self.BEM[i].roof.layerTemp[-1]
# Update rural heat fluxes & update vertical diffusion model (VDM)
self.rural.infra = self.forc.infra - self.rural.emissivity * self.SIGMA * \
self.rural.layerTemp[0]**4. # Infrared radiation from rural road
self.rural.SurfFlux(self.forc, self.geoParam, self.simTime,
self.forc.hum, self.forc.temp, self.forc.wind, 2., 0.)
self.RSM.VDM(self.forc, self.rural, self.geoParam, self.simTime)
# Calculate urban heat fluxes, update UCM & UBL
self.UCM, self.UBL, self.BEM = urbflux(
self.UCM, self.UBL, self.BEM, self.forc, self.geoParam, self.simTime, self.RSM)
self.UCM.UCModel(self.BEM, self.UBL.ublTemp, self.forc, self.geoParam)
self.UBL.UBLModel(self.UCM, self.RSM, self.rural,
self.forc, self.geoParam, self.simTime)
"""
# Experimental code to run diffusion model in the urban area
# N.B Commented out in python uwg because computed wind speed in
# urban VDM: y = =0.84*ln((2-x/20)/0.51) results in negative log
# for building heights >= 40m.
Uroad = copy.copy(self.UCM.road)
Uroad.sens = copy.copy(self.UCM.sensHeat)
Uforc = copy.copy(self.forc)
Uforc.wind = copy.copy(self.UCM.canWind)
Uforc.temp = copy.copy(self.UCM.canTemp)
self.USM.VDM(Uforc,Uroad,self.geoParam,self.simTime)
"""
self.logger.info("dbT = {}".format(self.UCM.canTemp-273.15))
if n > 0:
logging.info("dpT = {}".format(self.UCM.Tdp))
logging.info("RH = {}".format(self.UCM.canRHum))
if self.is_near_zero(self.simTime.secDay % self.simTime.timePrint) and n < self.N:
self.logger.info("{0} ----sim time step = {1}----\n\n".format(__name__, n))
self.WeatherData[n] = copy.copy(self.forc)
_Tdb, _w, self.UCM.canRHum, _h, self.UCM.Tdp, _v = psychrometrics(
self.UCM.canTemp, self.UCM.canHum, self.forc.pres)
self.UBLData[n] = copy.copy(self.UBL)
self.UCMData[n] = copy.copy(self.UCM)
self.RSMData[n] = copy.copy(self.RSM)
self.logger.info("dbT = {}".format(self.UCMData[n].canTemp-273.15))
self.logger.info("dpT = {}".format(self.UCMData[n].Tdp))
self.logger.info("RH = {}".format(self.UCMData[n].canRHum))
n += 1
def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] = column data of epw
self.epwinput[iJ+self.simTime.timeInitial-8][6] = "{0:.{1}f}".format(
self.UCMData[iJ].canTemp - 273.15, epw_prec) # dry bulb temperature [?C]
# dew point temperature [?C]
self.epwinput[iJ+self.simTime.timeInitial -
8][7] = "{0:.{1}f}".format(self.UCMData[iJ].Tdp, epw_prec)
# relative humidity [%]
self.epwinput[iJ+self.simTime.timeInitial -
8][8] = "{0:.{1}f}".format(self.UCMData[iJ].canRHum, epw_prec)
self.epwinput[iJ+self.simTime.timeInitial-8][21] = "{0:.{1}f}".format(
self.WeatherData[iJ].wind, epw_prec) # wind speed [m/s]
# Writing new EPW file
epw_new_id = open(self.newPathName, "w")
for i in range(8):
new_epw_line = '{}\n'.format(reduce(lambda x, y: x+","+y, self._header[i]))
epw_new_id.write(new_epw_line)
for i in range(len(self.epwinput)):
printme = ""
for ei in range(34):
printme += "{}".format(self.epwinput[i][ei]) + ','
printme = printme + "{}".format(self.epwinput[i][ei])
new_epw_line = "{0}\n".format(printme)
epw_new_id.write(new_epw_line)
epw_new_id.close()
print("New climate file '{}' is generated at {}.".format(
self.destinationFileName, self.destinationDir))
def run(self):
# run main class methods
self.read_epw()
self.set_input()
self.init_BEM_obj()
self.init_input_obj()
self.hvac_autosize()
self.simulate()
self.write_epw()
|
ladybug-tools/uwg | uwg/uwg.py | uwg.init_input_obj | python | def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
self.geoParam # geographic parameters obj
self.RSM # Rural site & vertical diffusion model obj
self.USM # Urban site & vertical diffusion model obj
self.UCM # Urban canopy model obj
self.UBL # Urban boundary layer model
self.road # urban road element
self.rural # rural road element
self.soilindex1 # soil index for urban rsoad depth
self.soilindex2 # soil index for rural road depth
self.Sch # list of Schedule objects
"""
climate_file_path = os.path.join(self.epwDir, self.epwFileName)
self.simTime = SimParam(self.dtSim, self.dtWeather, self.Month,
self.Day, self.nDay) # simulation time parametrs
# weather file data for simulation time period
self.weather = Weather(climate_file_path, self.simTime.timeInitial, self.simTime.timeFinal)
self.forcIP = Forcing(self.weather.staTemp, self.weather) # initialized Forcing class
self.forc = Forcing() # empty forcing class
# Initialize geographic Param and Urban Boundary Layer Objects
nightStart = 18. # arbitrary values for begin/end hour for night setpoint
nightEnd = 8.
maxdx = 250. # max dx (m)
self.geoParam = Param(self.h_ubl1, self.h_ubl2, self.h_ref, self.h_temp, self.h_wind, self.c_circ,
self.maxDay, self.maxNight, self.latTree, self.latGrss, self.albVeg, self.vegStart, self.vegEnd,
nightStart, nightEnd, self.windMin, self.WGMAX, self.c_exch, maxdx, self.G, self.CP, self.VK, self.R,
self.RV, self.LV, math.pi, self.SIGMA, self.WATERDENS, self.LVTT, self.TT, self.ESTT, self.CL,
self.CPV, self.B, self.CM, self.COLBURN)
self.UBL = UBLDef(
'C', self.charLength, self.weather.staTemp[0], maxdx, self.geoParam.dayBLHeight, self.geoParam.nightBLHeight)
# Defining road
emis = 0.93
asphalt = Material(self.kRoad, self.cRoad, 'asphalt')
road_T_init = 293.
road_horizontal = 1
# fraction of surface vegetation coverage
road_veg_coverage = min(self.vegCover/(1-self.bldDensity), 1.)
# define road layers
road_layer_num = int(math.ceil(self.d_road/0.05))
# 0.5/0.05 ~ 10 x 1 matrix of 0.05 thickness
thickness_vector = [0.05 for r in range(road_layer_num)]
material_vector = [asphalt for r in range(road_layer_num)]
self.road = Element(self.alb_road, emis, thickness_vector, material_vector, road_veg_coverage,
road_T_init, road_horizontal, name="urban_road")
self.rural = copy.deepcopy(self.road)
self.rural.vegCoverage = self.rurVegCover
self.rural._name = "rural_road"
# Reference site class (also include VDM)
self.RSM = RSMDef(self.lat, self.lon, self.GMT, self.h_obs,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
self.USM = RSMDef(self.lat, self.lon, self.GMT, self.bldHeight/10.,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
T_init = self.weather.staTemp[0]
H_init = self.weather.staHum[0]
self.UCM = UCMDef(self.bldHeight, self.bldDensity, self.verToHor, self.treeCoverage, self.sensAnth, self.latAnth, T_init, H_init,
self.weather.staUmod[0], self.geoParam, self.r_glaze_total, self.SHGC_total, self.alb_wall_total, self.road)
self.UCM.h_mix = self.h_mix
# Define Road Element & buffer to match ground temperature depth
roadMat, newthickness = procMat(self.road, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
roadMat.append(self.SOIL)
self.soilindex1 = i
break
self.road = Element(self.road.albedo, self.road.emissivity, newthickness, roadMat,
self.road.vegCoverage, self.road.layerTemp[0], self.road.horizontal, self.road._name)
# Define Rural Element
ruralMat, newthickness = procMat(self.rural, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
ruralMat.append(self.SOIL)
self.soilindex2 = i
break
self.rural = Element(self.rural.albedo, self.rural.emissivity, newthickness,
ruralMat, self.rural.vegCoverage, self.rural.layerTemp[0], self.rural.horizontal, self.rural._name) | Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
self.geoParam # geographic parameters obj
self.RSM # Rural site & vertical diffusion model obj
self.USM # Urban site & vertical diffusion model obj
self.UCM # Urban canopy model obj
self.UBL # Urban boundary layer model
self.road # urban road element
self.rural # rural road element
self.soilindex1 # soil index for urban rsoad depth
self.soilindex2 # soil index for rural road depth
self.Sch # list of Schedule objects | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/uwg.py#L612-L727 | [
"def procMat(materials, max_thickness, min_thickness):\n \"\"\" Processes material layer so that a material with single\n layer thickness is divided into two and material layer that is too\n thick is subdivided\n \"\"\"\n newmat = []\n newthickness = []\n k = materials.layerThermalCond\n Vhc = materials.layerVolHeat\n\n if len(materials.layerThickness) > 1:\n\n for j in range(len(materials.layerThickness)):\n # Break up each layer that's more than max thickness (0.05m)\n if materials.layerThickness[j] > max_thickness:\n nlayers = math.ceil(materials.layerThickness[j]/float(max_thickness))\n for i in range(int(nlayers)):\n newmat.append(Material(k[j], Vhc[j], name=materials._name))\n newthickness.append(materials.layerThickness[j]/float(nlayers))\n # Material that's less then min_thickness is not added.\n elif materials.layerThickness[j] < min_thickness:\n print(\"WARNING: Material '{}' layer found too thin (<{:.2f}cm), ignored.\").format(\n materials._name, min_thickness*100)\n else:\n newmat.append(Material(k[j], Vhc[j], name=materials._name))\n newthickness.append(materials.layerThickness[j])\n\n else:\n\n # Divide single layer into two (uwg assumes at least 2 layers)\n if materials.layerThickness[0] > max_thickness:\n nlayers = math.ceil(materials.layerThickness[0]/float(max_thickness))\n for i in range(int(nlayers)):\n newmat.append(Material(k[0], Vhc[0], name=materials._name))\n newthickness.append(materials.layerThickness[0]/float(nlayers))\n # Material should be at least 1cm thick, so if we're here,\n # should give warning and stop. Only warning given for now.\n elif materials.layerThickness[0] < min_thickness*2:\n newthickness = [min_thickness/2., min_thickness/2.]\n newmat = [Material(k[0], Vhc[0], name=materials._name),\n Material(k[0], Vhc[0], name=materials._name)]\n print(\"WARNING: a thin (<2cm) single material '{}' layer found. May cause error.\".format(\n materials._name))\n else:\n newthickness = [materials.layerThickness[0]/2., materials.layerThickness[0]/2.]\n newmat = [Material(k[0], Vhc[0], name=materials._name),\n Material(k[0], Vhc[0], name=materials._name)]\n return newmat, newthickness\n",
"def is_near_zero(self,num,eps=1e-10):\n return abs(float(num)) < eps\n"
] | class uwg(object):
"""Morph a rural EPW file to urban conditions using a file with a list of urban parameters.
args:
epwDir: The directory in which the rural EPW file sits.
epwFileName: The name of the rural epw file that will be morphed.
uwgParamDir: The directory in which the uwg Parameter File (.uwg) sits.
uwgParamFileName: The name of the uwg Parameter File (.uwg).
destinationDir: Optional destination directory for the morphed EPW file.
If left blank, the morphed file will be written into the same directory
as the rural EPW file (the epwDir).
destinationFileName: Optional destination file name for the morphed EPW file.
If left blank, the morphed file will append "_UWG" to the original file name.
returns:
newClimateFile: the path to a new EPW file that has been morphed to account
for uban conditions.
"""
""" Section 1 - Definitions for constants / other parameters """
MINTHICKNESS = 0.01 # Minimum layer thickness (to prevent crashing) (m)
MAXTHICKNESS = 0.05 # Maximum layer thickness (m)
# http://web.mit.edu/parmstr/Public/NRCan/nrcc29118.pdf (Figly & Snodgrass)
SOILTCOND = 1
# http://www.europment.org/library/2013/venice/bypaper/MFHEEF/MFHEEF-21.pdf (average taken from Table 1)
SOILVOLHEAT = 2e6
# Soil material used for soil-depth padding
SOIL = Material(SOILTCOND, SOILVOLHEAT, name="soil")
# Physical constants
G = 9.81 # gravity (m s-2)
CP = 1004. # heat capacity for air (J/kg K)
VK = 0.40 # von karman constant (dimensionless)
R = 287. # gas constant dry air (J/kg K)
RV = 461.5 # gas constant water vapor (J/kg K)
LV = 2.26e6 # latent heat of evaporation (J/kg)
SIGMA = 5.67e-08 # Stefan Boltzmann constant (W m-2 K-4)
WATERDENS = 1000. # water density (kg m-3)
LVTT = 2.5008e6 #
TT = 273.16 #
ESTT = 611.14 #
CL = 4.218e3 #
CPV = 1846.1 #
B = 9.4 # Coefficients derived by Louis (1979)
CM = 7.4 #
# (Pr/Sc)^(2/3) for Colburn analogy in water evaporation
COLBURN = math.pow((0.713/0.621), (2/3.))
# Site-specific parameters
WGMAX = 0.005 # maximum film water depth on horizontal surfaces (m)
# File path parameter
RESOURCE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "resources"))
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
def __init__(self, epwFileName, uwgParamFileName=None, epwDir=None, uwgParamDir=None, destinationDir=None, destinationFileName=None):
# Logger will be disabled by default unless explicitly called in tests
self.logger = logging.getLogger(__name__)
# User defined
self.epwFileName = epwFileName if epwFileName.lower().endswith('.epw') else epwFileName + \
'.epw' # Revise epw file name if not end with epw
# If file name is entered then will uwg will set input from .uwg file
self.uwgParamFileName = uwgParamFileName
# If user does not overload
self.destinationFileName = destinationFileName if destinationFileName else self.epwFileName.strip(
'.epw') + '_UWG.epw'
self.epwDir = epwDir if epwDir else os.path.join(self.RESOURCE_PATH, "epw")
self.uwgParamDir = uwgParamDir if uwgParamDir else os.path.join(
self.RESOURCE_PATH, "parameters")
self.destinationDir = destinationDir if destinationDir else os.path.join(
self.RESOURCE_PATH, "epw_uwg")
# refdata: Serialized DOE reference data, z_meso height data
self.readDOE_file_path = os.path.join(self.CURRENT_PATH, "refdata", "readDOE.pkl")
self.z_meso_dir_path = os.path.join(self.CURRENT_PATH, "refdata")
# EPW precision
self.epw_precision = 1
# init uwg variables
self._init_param_dict = None
# Define Simulation and Weather parameters
self.Month = None # starting month (1-12)
self.Day = None # starting day (1-31)
self.nDay = None # number of days
self.dtSim = None # simulation time step (s)
self.dtWeather = None # seconds (s)
# HVAC system and internal laod
self.autosize = None # autosize HVAC (1 or 0)
self.sensOcc = None # Sensible heat from occupant
self.LatFOcc = None # Latent heat fraction from occupant (normally 0.3)
self.RadFOcc = None # Radiant heat fraction from occupant (normally 0.2)
self.RadFEquip = None # Radiant heat fraction from equipment (normally 0.5)
self.RadFLight = None # Radiant heat fraction from light (normally 0.7)
# Define Urban microclimate parameters
self.h_ubl1 = None # ubl height - day (m)
self.h_ubl2 = None # ubl height - night (m)
self.h_ref = None # inversion height
self.h_temp = None # temperature height
self.h_wind = None # wind height
self.c_circ = None # circulation coefficient
self.c_exch = None # exchange coefficient
self.maxDay = None # max day threshhold
self.maxNight = None # max night threshhold
self.windMin = None # min wind speed (m/s)
self.h_obs = None # rural average obstacle height
# Urban characteristics
self.bldHeight = None # average building height (m)
self.h_mix = None # mixing height (m)
self.bldDensity = None # building density (0-1)
self.verToHor = None # building aspect ratio
# radius defining the urban area of study [aka. characteristic length] (m)
self.charLength = None
self.alb_road = None # road albedo
self.d_road = None # road pavement thickness
self.sensAnth = None # non-building sensible heat (W/m^2)
self.latAnth = None # non-building latent heat heat (W/m^2). Not used, taken out by JH.
# Fraction of building typology stock
self.bld = None # 16x3 matrix of fraction of building type by era
# climate Zone
self.zone = None
# Vegetation parameters
self.vegCover = None # urban area veg coverage ratio
self.treeCoverage = None # urban area tree coverage ratio
self.vegStart = None # vegetation start month
self.vegEnd = None # vegetation end month
self.albVeg = None # Vegetation albedo
self.rurVegCover = None # rural vegetation cover
self.latGrss = None # latent fraction of grass
self.latTree = None # latent fraction of tree
# Define Traffic schedule
self.SchTraffic = None
# Define Road (Assume 0.5m of asphalt)
self.kRoad = None # road pavement conductivity (W/m K)
self.cRoad = None # road volumetric heat capacity (J/m^3 K)
# Define optional Building characteristics
self.flr_h = None # floor-to-floor height
self.albRoof = None # roof albedo (0 - 1)
self.vegRoof = None # Fraction of the roofs covered in grass/shrubs (0-1)
self.glzR = None # Glazing Ratio
self.SHGC = None # Solar Heat Gain Coefficient
self.albWall = None # Wall albedo
def ToString(self):
"""Overwrite .NET ToString method."""
return self.__repr__()
def __repr__(self):
def _split_string(s):
return s[0] + ":\n " + s[1].replace(",", "\n ")
def _tabbed(s):
return _split_string(s.__repr__().split(":"))
def _list_2_tabbed(b):
return reduce(lambda a, b: a+"\n"+b, [_tabbed(_b) for _b in b])
return "uwg for {}:\n\n{}{}{}{}{}{}{}{}".format(
self.epwFileName,
_tabbed(self.simTime)+"\n" if hasattr(self, "simTime") else "No simTime attr.\n",
_tabbed(self.weather)+"\n" if hasattr(self, "weather") else "No weather attr.\n",
_tabbed(self.geoParam)+"\n" if hasattr(self, "geoParam") else "No geoParam attr.\n",
_tabbed(self.UBL)+"\n" if hasattr(self, "UBL") else "No UBL attr.\n",
"Rural "+_tabbed(self.RSM)+"\n" if hasattr(self, "RSM") else "No Rural RSM attr.\n",
"Urban "+_tabbed(self.USM)+"\n" if hasattr(self, "USM") else "No Urban RSM attr.\n",
_tabbed(self.UCM)+"\n" if hasattr(self, "UCM") else "No UCM attr.\n",
_list_2_tabbed(self.BEM) if hasattr(self, "BEM") else "No BEM attr."
)
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def read_epw(self):
"""Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT # GMT
self.nSoil # Number of soil depths
self.Tsoil # nSoil x 12 matrix for soil temperture (K)
self.depth_soil # nSoil x 1 matrix for soil depth (m)
"""
# Make dir path to epw file
self.climateDataPath = os.path.join(self.epwDir, self.epwFileName)
# Open epw file and feed csv data to climate_data
try:
climate_data = utilities.read_csv(self.climateDataPath)
except Exception as e:
raise Exception("Failed to read epw file! {}".format(e.message))
# Read header lines (1 to 8) from EPW and ensure TMY2 format.
self._header = climate_data[0:8]
# Read weather data from EPW for each time step in weather file. (lines 8 - end)
self.epwinput = climate_data[8:]
# Read Lat, Long (line 1 of EPW)
self.lat = float(self._header[0][6])
self.lon = float(self._header[0][7])
self.GMT = float(self._header[0][8])
# Read in soil temperature data (assumes this is always there)
# ref: http://bigladdersoftware.com/epx/docs/8-2/auxiliary-programs/epw-csv-format-inout.html
soilData = self._header[3]
self.nSoil = int(soilData[1]) # Number of ground temperature depths
self.Tsoil = utilities.zeros(self.nSoil, 12) # nSoil x 12 matrix for soil temperture (K)
self.depth_soil = utilities.zeros(self.nSoil, 1) # nSoil x 1 matrix for soil depth (m)
# Read monthly data for each layer of soil from EPW file
for i in range(self.nSoil):
self.depth_soil[i][0] = float(soilData[2 + (i*16)]) # get soil depth for each nSoil
# Monthly data
for j in range(12):
# 12 months of soil T for specific depth
self.Tsoil[i][j] = float(soilData[6 + (i*16) + j]) + 273.15
# Set new directory path for the moprhed EPW file
self.newPathName = os.path.join(self.destinationDir, self.destinationFileName)
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic # Traffice schedule
self.BEM # list of BEMDef objects extracted from readDOE
self.Sch # list of Schedule objects extracted from readDOE
"""
uwg_param_file_path = os.path.join(self.uwgParamDir, self.uwgParamFileName)
if not os.path.exists(uwg_param_file_path):
raise Exception("Param file: '{}' does not exist.".format(uwg_param_file_path))
# Open .uwg file and feed csv data to initializeDataFile
try:
uwg_param_data = utilities.read_csv(uwg_param_file_path)
except Exception as e:
raise Exception("Failed to read .uwg file! {}".format(e.message))
# The initialize.uwg is read with a dictionary so that users changing
# line endings or line numbers doesn't make reading input incorrect
self._init_param_dict = {}
count = 0
while count < len(uwg_param_data):
row = uwg_param_data[count]
row = [row[i].replace(" ", "") for i in range(len(row))] # strip white spaces
# Optional parameters might be empty so handle separately
is_optional_parameter = (
row != [] and
(
row[0] == "albRoof" or
row[0] == "vegRoof" or
row[0] == "glzR" or
row[0] == "hvac" or
row[0] == "albWall" or
row[0] == "SHGC"
)
)
try:
if row == [] or "#" in row[0]:
count += 1
continue
elif row[0] == "SchTraffic":
# SchTraffic: 3 x 24 matrix
trafficrows = uwg_param_data[count+1:count+4]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:24]) for r in trafficrows]
count += 4
elif row[0] == "bld":
# bld: 17 x 3 matrix
bldrows = uwg_param_data[count+1:count+17]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:3]) for r in bldrows]
count += 17
elif is_optional_parameter:
self._init_param_dict[row[0]] = float(row[1]) if row[1] != "" else None
count += 1
else:
self._init_param_dict[row[0]] = float(row[1])
count += 1
except ValueError:
print("Error while reading parameter at {} {}".format(count, row))
ipd = self._init_param_dict
# Define Simulation and Weather parameters
if self.Month is None: self.Month = ipd['Month']
if self.Day is None: self.Day = ipd['Day']
if self.nDay is None: self.nDay = ipd['nDay']
if self.dtSim is None: self.dtSim = ipd['dtSim']
if self.dtWeather is None: self.dtWeather = ipd['dtWeather']
# HVAC system and internal laod
if self.autosize is None: self.autosize = ipd['autosize']
if self.sensOcc is None: self.sensOcc = ipd['sensOcc']
if self.LatFOcc is None: self.LatFOcc = ipd['LatFOcc']
if self.RadFOcc is None: self.RadFOcc = ipd['RadFOcc']
if self.RadFEquip is None: self.RadFEquip = ipd['RadFEquip']
if self.RadFLight is None: self.RadFLight = ipd['RadFLight']
# Define Urban microclimate parameters
if self.h_ubl1 is None: self.h_ubl1 = ipd['h_ubl1']
if self.h_ubl2 is None: self.h_ubl2 = ipd['h_ubl2']
if self.h_ref is None: self.h_ref = ipd['h_ref']
if self.h_temp is None: self.h_temp = ipd['h_temp']
if self.h_wind is None: self.h_wind = ipd['h_wind']
if self.c_circ is None: self.c_circ = ipd['c_circ']
if self.c_exch is None: self.c_exch = ipd['c_exch']
if self.maxDay is None: self.maxDay = ipd['maxDay']
if self.maxNight is None: self.maxNight = ipd['maxNight']
if self.windMin is None: self.windMin = ipd['windMin']
if self.h_obs is None: self.h_obs = ipd['h_obs']
# Urban characteristics
if self.bldHeight is None: self.bldHeight = ipd['bldHeight']
if self.h_mix is None: self.h_mix = ipd['h_mix']
if self.bldDensity is None: self.bldDensity = ipd['bldDensity']
if self.verToHor is None: self.verToHor = ipd['verToHor']
if self.charLength is None: self.charLength = ipd['charLength']
if self.alb_road is None: self.alb_road = ipd['albRoad']
if self.d_road is None: self.d_road = ipd['dRoad']
if self.sensAnth is None: self.sensAnth = ipd['sensAnth']
# if self.latAnth is None: self.latAnth = ipd['latAnth'] # Not used, taken out by JH.
# climate Zone
if self.zone is None: self.zone = ipd['zone']
# Vegetation parameters
if self.vegCover is None: self.vegCover = ipd['vegCover']
if self.treeCoverage is None: self.treeCoverage = ipd['treeCoverage']
if self.vegStart is None: self.vegStart = ipd['vegStart']
if self.vegEnd is None: self.vegEnd = ipd['vegEnd']
if self.albVeg is None: self.albVeg = ipd['albVeg']
if self.rurVegCover is None: self.rurVegCover = ipd['rurVegCover']
if self.latGrss is None: self.latGrss = ipd['latGrss']
if self.latTree is None: self.latTree = ipd['latTree']
# Define Traffic schedule
if self.SchTraffic is None: self.SchTraffic = ipd['SchTraffic']
# Define Road (Assume 0.5m of asphalt)
if self.kRoad is None: self.kRoad = ipd['kRoad']
if self.cRoad is None: self.cRoad = ipd['cRoad']
# Building stock fraction
if self.bld is None: self.bld = ipd['bld']
# Optional parameters
if self.albRoof is None: self.albRoof = ipd['albRoof']
if self.vegRoof is None: self.vegRoof = ipd['vegRoof']
if self.glzR is None: self.glzR = ipd['glzR']
if self.albWall is None: self.albWall = ipd['albWall']
if self.SHGC is None: self.SHGC = ipd['SHGC']
def check_required_inputs(self):
# Fail if required parameters aren't correct
assert isinstance(self.Month, (float, int)), \
'Month must be a number. Got {}'.format(type(self.Month))
assert isinstance(self.Day, (float, int)), \
'Day must be a number. Got {}'.format(type(self.Day))
assert isinstance(self.nDay, (float, int)), \
'nDay must be a number. Got {}'.format(type(self.nDay))
assert isinstance(self.dtSim, float), \
'dtSim must be a float. Got {}'.format(type(self.dtSim))
assert isinstance(self.dtWeather, float), \
'dtWeather must be a float. Got {}'.format(type(self.dtWeather))
assert isinstance(self.autosize, (float, int)), \
'autosize must be a number. Got {}'.format(type(self.autosize))
assert isinstance(self.sensOcc, float), \
'sensOcc must be a float. Got {}'.format(type(self.sensOcc))
assert isinstance(self.LatFOcc, float), \
'LatFOcc must be a float. Got {}'.format(type(self.LatFOcc))
assert isinstance(self.RadFOcc, float), \
'RadFOcc must be a float. Got {}'.format(type(self.RadFOcc))
assert isinstance(self.RadFEquip, float), \
'RadFEquip must be a float. Got {}'.format(type(self.RadFEquip))
assert isinstance(self.RadFLight, float), \
'RadFLight must be a float. Got {}'.format(type(self.RadFLight))
assert isinstance(self.h_ubl1, float), \
'h_ubl1 must be a float. Got {}'.format(type(self.h_ubl1))
assert isinstance(self.h_ubl2, float), \
'h_ubl2 must be a float. Got {}'.format(type(self.h_ubl2))
assert isinstance(self.h_ref, float), \
'h_ref must be a float. Got {}'.format(type(self.h_ref))
assert isinstance(self.h_temp, float), \
'h_temp must be a float. Got {}'.format(type(self.h_temp))
assert isinstance(self.h_wind, float), \
'h_wind must be a float. Got {}'.format(type(self.h_wind))
assert isinstance(self.c_circ, float), \
'c_circ must be a float. Got {}'.format(type(self.c_circ))
assert isinstance(self.c_exch, float), \
'c_exch must be a float. Got {}'.format(type(self.c_exch))
assert isinstance(self.maxDay, float), \
'maxDay must be a float. Got {}'.format(type(self.maxDay))
assert isinstance(self.maxNight, float), \
'maxNight must be a float. Got {}'.format(type(self.maxNight))
assert isinstance(self.windMin, float), \
'windMin must be a float. Got {}'.format(type(self.windMin))
assert isinstance(self.h_obs, float), \
'h_obs must be a float. Got {}'.format(type(self.h_obs))
assert isinstance(self.bldHeight, float), \
'bldHeight must be a float. Got {}'.format(type(self.bldHeight))
assert isinstance(self.h_mix, float), \
'h_mix must be a float. Got {}'.format(type(self.h_mix))
assert isinstance(self.bldDensity, float), \
'bldDensity must be a float. Got {}'.format(type(self.bldDensity))
assert isinstance(self.verToHor, float), \
'verToHor must be a float. Got {}'.format(type(self.verToHor))
assert isinstance(self.charLength, float), \
'charLength must be a float. Got {}'.format(type(self.charLength))
assert isinstance(self.alb_road, float), \
'alb_road must be a float. Got {}'.format(type(self.alb_road))
assert isinstance(self.d_road, float), \
'd_road must be a float. Got {}'.format(type(self.d_road))
assert isinstance(self.sensAnth, float), \
'sensAnth must be a float. Got {}'.format(type(self.sensAnth))
# assert isinstance(self.latAnth, float) # Take this out as isn't being used
assert isinstance(self.bld, list), \
'bld must be a list. Got {}'.format(type(self.bld))
assert len(self.bld) == 16, \
'length of bld must be 16. Got {}'.format(len(self.bld))
assert isinstance(self.latTree, float), \
'latTree must be a float. Got {}'.format(type(self.latTree))
assert isinstance(self.latGrss, float), \
'latGrss must be a float. Got {}'.format(type(self.latGrss))
assert isinstance(self.zone, (float, int)), \
'zone must be a number. Got {}'.format(type(self.zone))
assert isinstance(self.vegStart, (float, int)), \
'vegStart must be a number. Got {}'.format(type(self.vegStart))
assert isinstance(self.vegEnd, (float, int)), \
'vegEnd must be a number. Got {}'.format(type(self.vegEnd))
assert isinstance(self.vegCover, float), \
'vegCover must be a float. Got {}'.format(type(self.vegCover))
assert isinstance(self.treeCoverage, float), \
'treeCoverage must be a float. Got {}'.format(type(self.treeCoverage))
assert isinstance(self.albVeg, float), \
'albVeg must be a float. Got {}'.format(type(self.albVeg))
assert isinstance(self.rurVegCover, float), \
'rurVegCover must be a float. Got {}'.format(type(self.rurVegCover))
assert isinstance(self.kRoad, float), \
'kRoad must be a float. Got {}'.format(type(self.kRoad))
assert isinstance(self.cRoad, float), \
'cRoad must be a float. Got {}'.format(type(self.cRoad))
assert isinstance(self.SchTraffic, list), \
'SchTraffic must be a list. Got {}'.format(type(self.SchTraffic))
assert len(self.SchTraffic) == 3, \
'length of SchTraffic must be 3. Got {}'.format(len(self.SchTraffic))
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the .uwg file.
if self.uwgParamFileName is not None:
print("\nReading uwg file input.")
self.read_input()
else:
print("\nNo .uwg file input.")
self.check_required_inputs()
# Modify zone to be used as python index
self.zone = int(self.zone)-1
def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total building stock
"""
if not os.path.exists(self.readDOE_file_path):
raise Exception("readDOE.pkl file: '{}' does not exist.".format(readDOE_file_path))
readDOE_file = open(self.readDOE_file_path, 'rb') # open pickle file in binary form
refDOE = pickle.load(readDOE_file)
refBEM = pickle.load(readDOE_file)
refSchedule = pickle.load(readDOE_file)
readDOE_file.close()
# Define building energy models
k = 0
self.r_glaze_total = 0. # Glazing ratio for total building stock
self.SHGC_total = 0. # SHGC addition for total building stock
self.alb_wall_total = 0. # albedo wall addition for total building stock
h_floor = self.flr_h or 3.05 # average floor height
total_urban_bld_area = math.pow(self.charLength, 2)*self.bldDensity * \
self.bldHeight/h_floor # total building floor area
area_matrix = utilities.zeros(16, 3)
self.BEM = [] # list of BEMDef objects
self.Sch = [] # list of Schedule objects
for i in range(16): # 16 building types
for j in range(3): # 3 built eras
if self.bld[i][j] > 0.:
# Add to BEM list
self.BEM.append(refBEM[i][j][self.zone])
self.BEM[k].frac = self.bld[i][j]
self.BEM[k].fl_area = self.bld[i][j] * total_urban_bld_area
# Overwrite with optional parameters if provided
if self.glzR:
self.BEM[k].building.glazingRatio = self.glzR
if self.albRoof:
self.BEM[k].roof.albedo = self.albRoof
if self.vegRoof:
self.BEM[k].roof.vegCoverage = self.vegRoof
if self.SHGC:
self.BEM[k].building.shgc = self.SHGC
if self.albWall:
self.BEM[k].wall.albedo = self.albWall
if self.flr_h:
self.BEM[k].building.floorHeight = self.flr_h
# Keep track of total urban r_glaze, SHGC, and alb_wall for UCM model
self.r_glaze_total += self.BEM[k].frac * self.BEM[k].building.glazingRatio
self.SHGC_total += self.BEM[k].frac * self.BEM[k].building.shgc
self.alb_wall_total += self.BEM[k].frac * self.BEM[k].wall.albedo
# Add to schedule list
self.Sch.append(refSchedule[i][j][self.zone])
k += 1
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
self.geoParam # geographic parameters obj
self.RSM # Rural site & vertical diffusion model obj
self.USM # Urban site & vertical diffusion model obj
self.UCM # Urban canopy model obj
self.UBL # Urban boundary layer model
self.road # urban road element
self.rural # rural road element
self.soilindex1 # soil index for urban rsoad depth
self.soilindex2 # soil index for rural road depth
self.Sch # list of Schedule objects
"""
climate_file_path = os.path.join(self.epwDir, self.epwFileName)
self.simTime = SimParam(self.dtSim, self.dtWeather, self.Month,
self.Day, self.nDay) # simulation time parametrs
# weather file data for simulation time period
self.weather = Weather(climate_file_path, self.simTime.timeInitial, self.simTime.timeFinal)
self.forcIP = Forcing(self.weather.staTemp, self.weather) # initialized Forcing class
self.forc = Forcing() # empty forcing class
# Initialize geographic Param and Urban Boundary Layer Objects
nightStart = 18. # arbitrary values for begin/end hour for night setpoint
nightEnd = 8.
maxdx = 250. # max dx (m)
self.geoParam = Param(self.h_ubl1, self.h_ubl2, self.h_ref, self.h_temp, self.h_wind, self.c_circ,
self.maxDay, self.maxNight, self.latTree, self.latGrss, self.albVeg, self.vegStart, self.vegEnd,
nightStart, nightEnd, self.windMin, self.WGMAX, self.c_exch, maxdx, self.G, self.CP, self.VK, self.R,
self.RV, self.LV, math.pi, self.SIGMA, self.WATERDENS, self.LVTT, self.TT, self.ESTT, self.CL,
self.CPV, self.B, self.CM, self.COLBURN)
self.UBL = UBLDef(
'C', self.charLength, self.weather.staTemp[0], maxdx, self.geoParam.dayBLHeight, self.geoParam.nightBLHeight)
# Defining road
emis = 0.93
asphalt = Material(self.kRoad, self.cRoad, 'asphalt')
road_T_init = 293.
road_horizontal = 1
# fraction of surface vegetation coverage
road_veg_coverage = min(self.vegCover/(1-self.bldDensity), 1.)
# define road layers
road_layer_num = int(math.ceil(self.d_road/0.05))
# 0.5/0.05 ~ 10 x 1 matrix of 0.05 thickness
thickness_vector = [0.05 for r in range(road_layer_num)]
material_vector = [asphalt for r in range(road_layer_num)]
self.road = Element(self.alb_road, emis, thickness_vector, material_vector, road_veg_coverage,
road_T_init, road_horizontal, name="urban_road")
self.rural = copy.deepcopy(self.road)
self.rural.vegCoverage = self.rurVegCover
self.rural._name = "rural_road"
# Reference site class (also include VDM)
self.RSM = RSMDef(self.lat, self.lon, self.GMT, self.h_obs,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
self.USM = RSMDef(self.lat, self.lon, self.GMT, self.bldHeight/10.,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
T_init = self.weather.staTemp[0]
H_init = self.weather.staHum[0]
self.UCM = UCMDef(self.bldHeight, self.bldDensity, self.verToHor, self.treeCoverage, self.sensAnth, self.latAnth, T_init, H_init,
self.weather.staUmod[0], self.geoParam, self.r_glaze_total, self.SHGC_total, self.alb_wall_total, self.road)
self.UCM.h_mix = self.h_mix
# Define Road Element & buffer to match ground temperature depth
roadMat, newthickness = procMat(self.road, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
roadMat.append(self.SOIL)
self.soilindex1 = i
break
self.road = Element(self.road.albedo, self.road.emissivity, newthickness, roadMat,
self.road.vegCoverage, self.road.layerTemp[0], self.road.horizontal, self.road._name)
# Define Rural Element
ruralMat, newthickness = procMat(self.rural, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
ruralMat.append(self.SOIL)
self.soilindex2 = i
break
self.rural = Element(self.rural.albedo, self.rural.emissivity, newthickness,
ruralMat, self.rural.vegCoverage, self.rural.layerTemp[0], self.rural.horizontal, self.rural._name)
def hvac_autosize(self):
""" Section 6 - HVAC Autosizing (unlimited cooling & heating) """
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999.
def simulate(self):
""" Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# Output of object instance vector
self.WeatherData # Nx1 vector of forc instance
self.UCMData # Nx1 vector of UCM instance
self.UBLData # Nx1 vector of UBL instance
self.RSMData # Nx1 vector of RSM instance
self.USMData # Nx1 vector of USM instance
"""
self.N = int(self.simTime.days * 24) # total number of hours in simulation
n = 0 # weather time step counter
self.ph = self.simTime.dt/3600. # dt (simulation time step) in hours
# Data dump variables
time = range(self.N)
self.WeatherData = [None for x in range(self.N)]
self.UCMData = [None for x in range(self.N)]
self.UBLData = [None for x in range(self.N)]
self.RSMData = [None for x in range(self.N)]
self.USMData = [None for x in range(self.N)]
print('\nSimulating new temperature and humidity values for {} days from {}/{}.\n'.format(
int(self.nDay), int(self.Month), int(self.Day)))
self.logger.info("Start simulation")
for it in range(1, self.simTime.nt, 1): # for every simulation time-step (i.e 5 min) defined by uwg
# Update water temperature (estimated)
if self.nSoil < 3: # correction to original matlab code
# for BUBBLE/CAPITOUL/Singapore only
self.forc.deepTemp = sum(self.forcIP.temp)/float(len(self.forcIP.temp))
self.forc.waterTemp = sum(
self.forcIP.temp)/float(len(self.forcIP.temp)) - 10. # for BUBBLE/CAPITOUL/Singapore only
else:
# soil temperature by depth, by month
self.forc.deepTemp = self.Tsoil[self.soilindex1][self.simTime.month-1]
self.forc.waterTemp = self.Tsoil[2][self.simTime.month-1]
# There's probably a better way to update the weather...
self.simTime.UpdateDate()
self.logger.info("\n{0} m={1}, d={2}, h={3}, s={4}".format(
__name__, self.simTime.month, self.simTime.day, self.simTime.secDay/3600., self.simTime.secDay))
# simulation time increment raised to weather time step
self.ceil_time_step = int(math.ceil(it * self.ph))-1
# minus one to be consistent with forcIP list index
# Updating forcing instance
# horizontal Infrared Radiation Intensity (W m-2)
self.forc.infra = self.forcIP.infra[self.ceil_time_step]
# wind speed (m s-1)
self.forc.wind = max(self.forcIP.wind[self.ceil_time_step], self.geoParam.windMin)
self.forc.uDir = self.forcIP.uDir[self.ceil_time_step] # wind direction
# specific humidty (kg kg-1)
self.forc.hum = self.forcIP.hum[self.ceil_time_step]
self.forc.pres = self.forcIP.pres[self.ceil_time_step] # Pressure (Pa)
self.forc.temp = self.forcIP.temp[self.ceil_time_step] # air temperature (C)
self.forc.rHum = self.forcIP.rHum[self.ceil_time_step] # Relative humidity (%)
self.forc.prec = self.forcIP.prec[self.ceil_time_step] # Precipitation (mm h-1)
# horizontal solar diffuse radiation (W m-2)
self.forc.dif = self.forcIP.dif[self.ceil_time_step]
# normal solar direct radiation (W m-2)
self.forc.dir = self.forcIP.dir[self.ceil_time_step]
# Canyon humidity (absolute) same as rural
self.UCM.canHum = copy.copy(self.forc.hum)
# Update solar flux
self.solar = SolarCalcs(self.UCM, self.BEM, self.simTime,
self.RSM, self.forc, self.geoParam, self.rural)
self.rural, self.UCM, self.BEM = self.solar.solarcalcs()
# Update building & traffic schedule
# Assign day type (1 = weekday, 2 = sat, 3 = sun/other)
if self.is_near_zero(self.simTime.julian % 7):
self.dayType = 3 # Sunday
elif self.is_near_zero(self.simTime.julian % 7 - 6.):
self.dayType = 2 # Saturday
else:
self.dayType = 1 # Weekday
# Update anthropogenic heat load for each hour (building & UCM)
self.UCM.sensAnthrop = self.sensAnth * (self.SchTraffic[self.dayType-1][self.simTime.hourDay])
# Update the energy components for building types defined in initialize.uwg
for i in range(len(self.BEM)):
# Set temperature
self.BEM[i].building.coolSetpointDay = self.Sch[i].Cool[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for cooling
self.BEM[i].building.coolSetpointNight = self.BEM[i].building.coolSetpointDay
self.BEM[i].building.heatSetpointDay = self.Sch[i].Heat[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for heating
self.BEM[i].building.heatSetpointNight = self.BEM[i].building.heatSetpointDay
# Internal Heat Load Schedule (W/m^2 of floor area for Q)
self.BEM[i].Elec = self.Sch[i].Qelec * self.Sch[i].Elec[self.dayType -
1][self.simTime.hourDay] # Qelec x elec fraction for day
self.BEM[i].Light = self.Sch[i].Qlight * self.Sch[i].Light[self.dayType -
1][self.simTime.hourDay] # Qlight x light fraction for day
self.BEM[i].Nocc = self.Sch[i].Nocc * self.Sch[i].Occ[self.dayType -
1][self.simTime.hourDay] # Number of occupants x occ fraction for day
# Sensible Q occupant * fraction occupant sensible Q * number of occupants
self.BEM[i].Qocc = self.sensOcc * (1 - self.LatFOcc) * self.BEM[i].Nocc
# SWH and ventilation schedule
self.BEM[i].SWH = self.Sch[i].Vswh * self.Sch[i].SWH[self.dayType -
1][self.simTime.hourDay] # litres per hour x SWH fraction for day
# m^3/s/m^2 of floor
self.BEM[i].building.vent = self.Sch[i].Vent
self.BEM[i].Gas = self.Sch[i].Qgas * self.Sch[i].Gas[self.dayType -
1][self.simTime.hourDay] # Gas Equip Schedule, per m^2 of floor
# This is quite messy, should update
# Update internal heat and corresponding fractional loads
intHeat = self.BEM[i].Light + self.BEM[i].Elec + self.BEM[i].Qocc
# W/m2 from light, electricity, occupants
self.BEM[i].building.intHeatDay = intHeat
self.BEM[i].building.intHeatNight = intHeat
# fraction of radiant heat from light and equipment of whole internal heat
self.BEM[i].building.intHeatFRad = (
self.RadFLight * self.BEM[i].Light + self.RadFEquip * self.BEM[i].Elec) / intHeat
# fraction of latent heat (from occupants) of whole internal heat
self.BEM[i].building.intHeatFLat = self.LatFOcc * \
self.sensOcc * self.BEM[i].Nocc/intHeat
# Update envelope temperature layers
self.BEM[i].T_wallex = self.BEM[i].wall.layerTemp[0]
self.BEM[i].T_wallin = self.BEM[i].wall.layerTemp[-1]
self.BEM[i].T_roofex = self.BEM[i].roof.layerTemp[0]
self.BEM[i].T_roofin = self.BEM[i].roof.layerTemp[-1]
# Update rural heat fluxes & update vertical diffusion model (VDM)
self.rural.infra = self.forc.infra - self.rural.emissivity * self.SIGMA * \
self.rural.layerTemp[0]**4. # Infrared radiation from rural road
self.rural.SurfFlux(self.forc, self.geoParam, self.simTime,
self.forc.hum, self.forc.temp, self.forc.wind, 2., 0.)
self.RSM.VDM(self.forc, self.rural, self.geoParam, self.simTime)
# Calculate urban heat fluxes, update UCM & UBL
self.UCM, self.UBL, self.BEM = urbflux(
self.UCM, self.UBL, self.BEM, self.forc, self.geoParam, self.simTime, self.RSM)
self.UCM.UCModel(self.BEM, self.UBL.ublTemp, self.forc, self.geoParam)
self.UBL.UBLModel(self.UCM, self.RSM, self.rural,
self.forc, self.geoParam, self.simTime)
"""
# Experimental code to run diffusion model in the urban area
# N.B Commented out in python uwg because computed wind speed in
# urban VDM: y = =0.84*ln((2-x/20)/0.51) results in negative log
# for building heights >= 40m.
Uroad = copy.copy(self.UCM.road)
Uroad.sens = copy.copy(self.UCM.sensHeat)
Uforc = copy.copy(self.forc)
Uforc.wind = copy.copy(self.UCM.canWind)
Uforc.temp = copy.copy(self.UCM.canTemp)
self.USM.VDM(Uforc,Uroad,self.geoParam,self.simTime)
"""
self.logger.info("dbT = {}".format(self.UCM.canTemp-273.15))
if n > 0:
logging.info("dpT = {}".format(self.UCM.Tdp))
logging.info("RH = {}".format(self.UCM.canRHum))
if self.is_near_zero(self.simTime.secDay % self.simTime.timePrint) and n < self.N:
self.logger.info("{0} ----sim time step = {1}----\n\n".format(__name__, n))
self.WeatherData[n] = copy.copy(self.forc)
_Tdb, _w, self.UCM.canRHum, _h, self.UCM.Tdp, _v = psychrometrics(
self.UCM.canTemp, self.UCM.canHum, self.forc.pres)
self.UBLData[n] = copy.copy(self.UBL)
self.UCMData[n] = copy.copy(self.UCM)
self.RSMData[n] = copy.copy(self.RSM)
self.logger.info("dbT = {}".format(self.UCMData[n].canTemp-273.15))
self.logger.info("dpT = {}".format(self.UCMData[n].Tdp))
self.logger.info("RH = {}".format(self.UCMData[n].canRHum))
n += 1
def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] = column data of epw
self.epwinput[iJ+self.simTime.timeInitial-8][6] = "{0:.{1}f}".format(
self.UCMData[iJ].canTemp - 273.15, epw_prec) # dry bulb temperature [?C]
# dew point temperature [?C]
self.epwinput[iJ+self.simTime.timeInitial -
8][7] = "{0:.{1}f}".format(self.UCMData[iJ].Tdp, epw_prec)
# relative humidity [%]
self.epwinput[iJ+self.simTime.timeInitial -
8][8] = "{0:.{1}f}".format(self.UCMData[iJ].canRHum, epw_prec)
self.epwinput[iJ+self.simTime.timeInitial-8][21] = "{0:.{1}f}".format(
self.WeatherData[iJ].wind, epw_prec) # wind speed [m/s]
# Writing new EPW file
epw_new_id = open(self.newPathName, "w")
for i in range(8):
new_epw_line = '{}\n'.format(reduce(lambda x, y: x+","+y, self._header[i]))
epw_new_id.write(new_epw_line)
for i in range(len(self.epwinput)):
printme = ""
for ei in range(34):
printme += "{}".format(self.epwinput[i][ei]) + ','
printme = printme + "{}".format(self.epwinput[i][ei])
new_epw_line = "{0}\n".format(printme)
epw_new_id.write(new_epw_line)
epw_new_id.close()
print("New climate file '{}' is generated at {}.".format(
self.destinationFileName, self.destinationDir))
def run(self):
# run main class methods
self.read_epw()
self.set_input()
self.init_BEM_obj()
self.init_input_obj()
self.hvac_autosize()
self.simulate()
self.write_epw()
|
ladybug-tools/uwg | uwg/uwg.py | uwg.hvac_autosize | python | def hvac_autosize(self):
""" Section 6 - HVAC Autosizing (unlimited cooling & heating) """
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999. | Section 6 - HVAC Autosizing (unlimited cooling & heating) | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/uwg.py#L729-L735 | [
"def is_near_zero(self,num,eps=1e-10):\n return abs(float(num)) < eps\n"
] | class uwg(object):
"""Morph a rural EPW file to urban conditions using a file with a list of urban parameters.
args:
epwDir: The directory in which the rural EPW file sits.
epwFileName: The name of the rural epw file that will be morphed.
uwgParamDir: The directory in which the uwg Parameter File (.uwg) sits.
uwgParamFileName: The name of the uwg Parameter File (.uwg).
destinationDir: Optional destination directory for the morphed EPW file.
If left blank, the morphed file will be written into the same directory
as the rural EPW file (the epwDir).
destinationFileName: Optional destination file name for the morphed EPW file.
If left blank, the morphed file will append "_UWG" to the original file name.
returns:
newClimateFile: the path to a new EPW file that has been morphed to account
for uban conditions.
"""
""" Section 1 - Definitions for constants / other parameters """
MINTHICKNESS = 0.01 # Minimum layer thickness (to prevent crashing) (m)
MAXTHICKNESS = 0.05 # Maximum layer thickness (m)
# http://web.mit.edu/parmstr/Public/NRCan/nrcc29118.pdf (Figly & Snodgrass)
SOILTCOND = 1
# http://www.europment.org/library/2013/venice/bypaper/MFHEEF/MFHEEF-21.pdf (average taken from Table 1)
SOILVOLHEAT = 2e6
# Soil material used for soil-depth padding
SOIL = Material(SOILTCOND, SOILVOLHEAT, name="soil")
# Physical constants
G = 9.81 # gravity (m s-2)
CP = 1004. # heat capacity for air (J/kg K)
VK = 0.40 # von karman constant (dimensionless)
R = 287. # gas constant dry air (J/kg K)
RV = 461.5 # gas constant water vapor (J/kg K)
LV = 2.26e6 # latent heat of evaporation (J/kg)
SIGMA = 5.67e-08 # Stefan Boltzmann constant (W m-2 K-4)
WATERDENS = 1000. # water density (kg m-3)
LVTT = 2.5008e6 #
TT = 273.16 #
ESTT = 611.14 #
CL = 4.218e3 #
CPV = 1846.1 #
B = 9.4 # Coefficients derived by Louis (1979)
CM = 7.4 #
# (Pr/Sc)^(2/3) for Colburn analogy in water evaporation
COLBURN = math.pow((0.713/0.621), (2/3.))
# Site-specific parameters
WGMAX = 0.005 # maximum film water depth on horizontal surfaces (m)
# File path parameter
RESOURCE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "resources"))
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
def __init__(self, epwFileName, uwgParamFileName=None, epwDir=None, uwgParamDir=None, destinationDir=None, destinationFileName=None):
# Logger will be disabled by default unless explicitly called in tests
self.logger = logging.getLogger(__name__)
# User defined
self.epwFileName = epwFileName if epwFileName.lower().endswith('.epw') else epwFileName + \
'.epw' # Revise epw file name if not end with epw
# If file name is entered then will uwg will set input from .uwg file
self.uwgParamFileName = uwgParamFileName
# If user does not overload
self.destinationFileName = destinationFileName if destinationFileName else self.epwFileName.strip(
'.epw') + '_UWG.epw'
self.epwDir = epwDir if epwDir else os.path.join(self.RESOURCE_PATH, "epw")
self.uwgParamDir = uwgParamDir if uwgParamDir else os.path.join(
self.RESOURCE_PATH, "parameters")
self.destinationDir = destinationDir if destinationDir else os.path.join(
self.RESOURCE_PATH, "epw_uwg")
# refdata: Serialized DOE reference data, z_meso height data
self.readDOE_file_path = os.path.join(self.CURRENT_PATH, "refdata", "readDOE.pkl")
self.z_meso_dir_path = os.path.join(self.CURRENT_PATH, "refdata")
# EPW precision
self.epw_precision = 1
# init uwg variables
self._init_param_dict = None
# Define Simulation and Weather parameters
self.Month = None # starting month (1-12)
self.Day = None # starting day (1-31)
self.nDay = None # number of days
self.dtSim = None # simulation time step (s)
self.dtWeather = None # seconds (s)
# HVAC system and internal laod
self.autosize = None # autosize HVAC (1 or 0)
self.sensOcc = None # Sensible heat from occupant
self.LatFOcc = None # Latent heat fraction from occupant (normally 0.3)
self.RadFOcc = None # Radiant heat fraction from occupant (normally 0.2)
self.RadFEquip = None # Radiant heat fraction from equipment (normally 0.5)
self.RadFLight = None # Radiant heat fraction from light (normally 0.7)
# Define Urban microclimate parameters
self.h_ubl1 = None # ubl height - day (m)
self.h_ubl2 = None # ubl height - night (m)
self.h_ref = None # inversion height
self.h_temp = None # temperature height
self.h_wind = None # wind height
self.c_circ = None # circulation coefficient
self.c_exch = None # exchange coefficient
self.maxDay = None # max day threshhold
self.maxNight = None # max night threshhold
self.windMin = None # min wind speed (m/s)
self.h_obs = None # rural average obstacle height
# Urban characteristics
self.bldHeight = None # average building height (m)
self.h_mix = None # mixing height (m)
self.bldDensity = None # building density (0-1)
self.verToHor = None # building aspect ratio
# radius defining the urban area of study [aka. characteristic length] (m)
self.charLength = None
self.alb_road = None # road albedo
self.d_road = None # road pavement thickness
self.sensAnth = None # non-building sensible heat (W/m^2)
self.latAnth = None # non-building latent heat heat (W/m^2). Not used, taken out by JH.
# Fraction of building typology stock
self.bld = None # 16x3 matrix of fraction of building type by era
# climate Zone
self.zone = None
# Vegetation parameters
self.vegCover = None # urban area veg coverage ratio
self.treeCoverage = None # urban area tree coverage ratio
self.vegStart = None # vegetation start month
self.vegEnd = None # vegetation end month
self.albVeg = None # Vegetation albedo
self.rurVegCover = None # rural vegetation cover
self.latGrss = None # latent fraction of grass
self.latTree = None # latent fraction of tree
# Define Traffic schedule
self.SchTraffic = None
# Define Road (Assume 0.5m of asphalt)
self.kRoad = None # road pavement conductivity (W/m K)
self.cRoad = None # road volumetric heat capacity (J/m^3 K)
# Define optional Building characteristics
self.flr_h = None # floor-to-floor height
self.albRoof = None # roof albedo (0 - 1)
self.vegRoof = None # Fraction of the roofs covered in grass/shrubs (0-1)
self.glzR = None # Glazing Ratio
self.SHGC = None # Solar Heat Gain Coefficient
self.albWall = None # Wall albedo
def ToString(self):
"""Overwrite .NET ToString method."""
return self.__repr__()
def __repr__(self):
def _split_string(s):
return s[0] + ":\n " + s[1].replace(",", "\n ")
def _tabbed(s):
return _split_string(s.__repr__().split(":"))
def _list_2_tabbed(b):
return reduce(lambda a, b: a+"\n"+b, [_tabbed(_b) for _b in b])
return "uwg for {}:\n\n{}{}{}{}{}{}{}{}".format(
self.epwFileName,
_tabbed(self.simTime)+"\n" if hasattr(self, "simTime") else "No simTime attr.\n",
_tabbed(self.weather)+"\n" if hasattr(self, "weather") else "No weather attr.\n",
_tabbed(self.geoParam)+"\n" if hasattr(self, "geoParam") else "No geoParam attr.\n",
_tabbed(self.UBL)+"\n" if hasattr(self, "UBL") else "No UBL attr.\n",
"Rural "+_tabbed(self.RSM)+"\n" if hasattr(self, "RSM") else "No Rural RSM attr.\n",
"Urban "+_tabbed(self.USM)+"\n" if hasattr(self, "USM") else "No Urban RSM attr.\n",
_tabbed(self.UCM)+"\n" if hasattr(self, "UCM") else "No UCM attr.\n",
_list_2_tabbed(self.BEM) if hasattr(self, "BEM") else "No BEM attr."
)
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def read_epw(self):
"""Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT # GMT
self.nSoil # Number of soil depths
self.Tsoil # nSoil x 12 matrix for soil temperture (K)
self.depth_soil # nSoil x 1 matrix for soil depth (m)
"""
# Make dir path to epw file
self.climateDataPath = os.path.join(self.epwDir, self.epwFileName)
# Open epw file and feed csv data to climate_data
try:
climate_data = utilities.read_csv(self.climateDataPath)
except Exception as e:
raise Exception("Failed to read epw file! {}".format(e.message))
# Read header lines (1 to 8) from EPW and ensure TMY2 format.
self._header = climate_data[0:8]
# Read weather data from EPW for each time step in weather file. (lines 8 - end)
self.epwinput = climate_data[8:]
# Read Lat, Long (line 1 of EPW)
self.lat = float(self._header[0][6])
self.lon = float(self._header[0][7])
self.GMT = float(self._header[0][8])
# Read in soil temperature data (assumes this is always there)
# ref: http://bigladdersoftware.com/epx/docs/8-2/auxiliary-programs/epw-csv-format-inout.html
soilData = self._header[3]
self.nSoil = int(soilData[1]) # Number of ground temperature depths
self.Tsoil = utilities.zeros(self.nSoil, 12) # nSoil x 12 matrix for soil temperture (K)
self.depth_soil = utilities.zeros(self.nSoil, 1) # nSoil x 1 matrix for soil depth (m)
# Read monthly data for each layer of soil from EPW file
for i in range(self.nSoil):
self.depth_soil[i][0] = float(soilData[2 + (i*16)]) # get soil depth for each nSoil
# Monthly data
for j in range(12):
# 12 months of soil T for specific depth
self.Tsoil[i][j] = float(soilData[6 + (i*16) + j]) + 273.15
# Set new directory path for the moprhed EPW file
self.newPathName = os.path.join(self.destinationDir, self.destinationFileName)
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic # Traffice schedule
self.BEM # list of BEMDef objects extracted from readDOE
self.Sch # list of Schedule objects extracted from readDOE
"""
uwg_param_file_path = os.path.join(self.uwgParamDir, self.uwgParamFileName)
if not os.path.exists(uwg_param_file_path):
raise Exception("Param file: '{}' does not exist.".format(uwg_param_file_path))
# Open .uwg file and feed csv data to initializeDataFile
try:
uwg_param_data = utilities.read_csv(uwg_param_file_path)
except Exception as e:
raise Exception("Failed to read .uwg file! {}".format(e.message))
# The initialize.uwg is read with a dictionary so that users changing
# line endings or line numbers doesn't make reading input incorrect
self._init_param_dict = {}
count = 0
while count < len(uwg_param_data):
row = uwg_param_data[count]
row = [row[i].replace(" ", "") for i in range(len(row))] # strip white spaces
# Optional parameters might be empty so handle separately
is_optional_parameter = (
row != [] and
(
row[0] == "albRoof" or
row[0] == "vegRoof" or
row[0] == "glzR" or
row[0] == "hvac" or
row[0] == "albWall" or
row[0] == "SHGC"
)
)
try:
if row == [] or "#" in row[0]:
count += 1
continue
elif row[0] == "SchTraffic":
# SchTraffic: 3 x 24 matrix
trafficrows = uwg_param_data[count+1:count+4]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:24]) for r in trafficrows]
count += 4
elif row[0] == "bld":
# bld: 17 x 3 matrix
bldrows = uwg_param_data[count+1:count+17]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:3]) for r in bldrows]
count += 17
elif is_optional_parameter:
self._init_param_dict[row[0]] = float(row[1]) if row[1] != "" else None
count += 1
else:
self._init_param_dict[row[0]] = float(row[1])
count += 1
except ValueError:
print("Error while reading parameter at {} {}".format(count, row))
ipd = self._init_param_dict
# Define Simulation and Weather parameters
if self.Month is None: self.Month = ipd['Month']
if self.Day is None: self.Day = ipd['Day']
if self.nDay is None: self.nDay = ipd['nDay']
if self.dtSim is None: self.dtSim = ipd['dtSim']
if self.dtWeather is None: self.dtWeather = ipd['dtWeather']
# HVAC system and internal laod
if self.autosize is None: self.autosize = ipd['autosize']
if self.sensOcc is None: self.sensOcc = ipd['sensOcc']
if self.LatFOcc is None: self.LatFOcc = ipd['LatFOcc']
if self.RadFOcc is None: self.RadFOcc = ipd['RadFOcc']
if self.RadFEquip is None: self.RadFEquip = ipd['RadFEquip']
if self.RadFLight is None: self.RadFLight = ipd['RadFLight']
# Define Urban microclimate parameters
if self.h_ubl1 is None: self.h_ubl1 = ipd['h_ubl1']
if self.h_ubl2 is None: self.h_ubl2 = ipd['h_ubl2']
if self.h_ref is None: self.h_ref = ipd['h_ref']
if self.h_temp is None: self.h_temp = ipd['h_temp']
if self.h_wind is None: self.h_wind = ipd['h_wind']
if self.c_circ is None: self.c_circ = ipd['c_circ']
if self.c_exch is None: self.c_exch = ipd['c_exch']
if self.maxDay is None: self.maxDay = ipd['maxDay']
if self.maxNight is None: self.maxNight = ipd['maxNight']
if self.windMin is None: self.windMin = ipd['windMin']
if self.h_obs is None: self.h_obs = ipd['h_obs']
# Urban characteristics
if self.bldHeight is None: self.bldHeight = ipd['bldHeight']
if self.h_mix is None: self.h_mix = ipd['h_mix']
if self.bldDensity is None: self.bldDensity = ipd['bldDensity']
if self.verToHor is None: self.verToHor = ipd['verToHor']
if self.charLength is None: self.charLength = ipd['charLength']
if self.alb_road is None: self.alb_road = ipd['albRoad']
if self.d_road is None: self.d_road = ipd['dRoad']
if self.sensAnth is None: self.sensAnth = ipd['sensAnth']
# if self.latAnth is None: self.latAnth = ipd['latAnth'] # Not used, taken out by JH.
# climate Zone
if self.zone is None: self.zone = ipd['zone']
# Vegetation parameters
if self.vegCover is None: self.vegCover = ipd['vegCover']
if self.treeCoverage is None: self.treeCoverage = ipd['treeCoverage']
if self.vegStart is None: self.vegStart = ipd['vegStart']
if self.vegEnd is None: self.vegEnd = ipd['vegEnd']
if self.albVeg is None: self.albVeg = ipd['albVeg']
if self.rurVegCover is None: self.rurVegCover = ipd['rurVegCover']
if self.latGrss is None: self.latGrss = ipd['latGrss']
if self.latTree is None: self.latTree = ipd['latTree']
# Define Traffic schedule
if self.SchTraffic is None: self.SchTraffic = ipd['SchTraffic']
# Define Road (Assume 0.5m of asphalt)
if self.kRoad is None: self.kRoad = ipd['kRoad']
if self.cRoad is None: self.cRoad = ipd['cRoad']
# Building stock fraction
if self.bld is None: self.bld = ipd['bld']
# Optional parameters
if self.albRoof is None: self.albRoof = ipd['albRoof']
if self.vegRoof is None: self.vegRoof = ipd['vegRoof']
if self.glzR is None: self.glzR = ipd['glzR']
if self.albWall is None: self.albWall = ipd['albWall']
if self.SHGC is None: self.SHGC = ipd['SHGC']
def check_required_inputs(self):
# Fail if required parameters aren't correct
assert isinstance(self.Month, (float, int)), \
'Month must be a number. Got {}'.format(type(self.Month))
assert isinstance(self.Day, (float, int)), \
'Day must be a number. Got {}'.format(type(self.Day))
assert isinstance(self.nDay, (float, int)), \
'nDay must be a number. Got {}'.format(type(self.nDay))
assert isinstance(self.dtSim, float), \
'dtSim must be a float. Got {}'.format(type(self.dtSim))
assert isinstance(self.dtWeather, float), \
'dtWeather must be a float. Got {}'.format(type(self.dtWeather))
assert isinstance(self.autosize, (float, int)), \
'autosize must be a number. Got {}'.format(type(self.autosize))
assert isinstance(self.sensOcc, float), \
'sensOcc must be a float. Got {}'.format(type(self.sensOcc))
assert isinstance(self.LatFOcc, float), \
'LatFOcc must be a float. Got {}'.format(type(self.LatFOcc))
assert isinstance(self.RadFOcc, float), \
'RadFOcc must be a float. Got {}'.format(type(self.RadFOcc))
assert isinstance(self.RadFEquip, float), \
'RadFEquip must be a float. Got {}'.format(type(self.RadFEquip))
assert isinstance(self.RadFLight, float), \
'RadFLight must be a float. Got {}'.format(type(self.RadFLight))
assert isinstance(self.h_ubl1, float), \
'h_ubl1 must be a float. Got {}'.format(type(self.h_ubl1))
assert isinstance(self.h_ubl2, float), \
'h_ubl2 must be a float. Got {}'.format(type(self.h_ubl2))
assert isinstance(self.h_ref, float), \
'h_ref must be a float. Got {}'.format(type(self.h_ref))
assert isinstance(self.h_temp, float), \
'h_temp must be a float. Got {}'.format(type(self.h_temp))
assert isinstance(self.h_wind, float), \
'h_wind must be a float. Got {}'.format(type(self.h_wind))
assert isinstance(self.c_circ, float), \
'c_circ must be a float. Got {}'.format(type(self.c_circ))
assert isinstance(self.c_exch, float), \
'c_exch must be a float. Got {}'.format(type(self.c_exch))
assert isinstance(self.maxDay, float), \
'maxDay must be a float. Got {}'.format(type(self.maxDay))
assert isinstance(self.maxNight, float), \
'maxNight must be a float. Got {}'.format(type(self.maxNight))
assert isinstance(self.windMin, float), \
'windMin must be a float. Got {}'.format(type(self.windMin))
assert isinstance(self.h_obs, float), \
'h_obs must be a float. Got {}'.format(type(self.h_obs))
assert isinstance(self.bldHeight, float), \
'bldHeight must be a float. Got {}'.format(type(self.bldHeight))
assert isinstance(self.h_mix, float), \
'h_mix must be a float. Got {}'.format(type(self.h_mix))
assert isinstance(self.bldDensity, float), \
'bldDensity must be a float. Got {}'.format(type(self.bldDensity))
assert isinstance(self.verToHor, float), \
'verToHor must be a float. Got {}'.format(type(self.verToHor))
assert isinstance(self.charLength, float), \
'charLength must be a float. Got {}'.format(type(self.charLength))
assert isinstance(self.alb_road, float), \
'alb_road must be a float. Got {}'.format(type(self.alb_road))
assert isinstance(self.d_road, float), \
'd_road must be a float. Got {}'.format(type(self.d_road))
assert isinstance(self.sensAnth, float), \
'sensAnth must be a float. Got {}'.format(type(self.sensAnth))
# assert isinstance(self.latAnth, float) # Take this out as isn't being used
assert isinstance(self.bld, list), \
'bld must be a list. Got {}'.format(type(self.bld))
assert len(self.bld) == 16, \
'length of bld must be 16. Got {}'.format(len(self.bld))
assert isinstance(self.latTree, float), \
'latTree must be a float. Got {}'.format(type(self.latTree))
assert isinstance(self.latGrss, float), \
'latGrss must be a float. Got {}'.format(type(self.latGrss))
assert isinstance(self.zone, (float, int)), \
'zone must be a number. Got {}'.format(type(self.zone))
assert isinstance(self.vegStart, (float, int)), \
'vegStart must be a number. Got {}'.format(type(self.vegStart))
assert isinstance(self.vegEnd, (float, int)), \
'vegEnd must be a number. Got {}'.format(type(self.vegEnd))
assert isinstance(self.vegCover, float), \
'vegCover must be a float. Got {}'.format(type(self.vegCover))
assert isinstance(self.treeCoverage, float), \
'treeCoverage must be a float. Got {}'.format(type(self.treeCoverage))
assert isinstance(self.albVeg, float), \
'albVeg must be a float. Got {}'.format(type(self.albVeg))
assert isinstance(self.rurVegCover, float), \
'rurVegCover must be a float. Got {}'.format(type(self.rurVegCover))
assert isinstance(self.kRoad, float), \
'kRoad must be a float. Got {}'.format(type(self.kRoad))
assert isinstance(self.cRoad, float), \
'cRoad must be a float. Got {}'.format(type(self.cRoad))
assert isinstance(self.SchTraffic, list), \
'SchTraffic must be a list. Got {}'.format(type(self.SchTraffic))
assert len(self.SchTraffic) == 3, \
'length of SchTraffic must be 3. Got {}'.format(len(self.SchTraffic))
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the .uwg file.
if self.uwgParamFileName is not None:
print("\nReading uwg file input.")
self.read_input()
else:
print("\nNo .uwg file input.")
self.check_required_inputs()
# Modify zone to be used as python index
self.zone = int(self.zone)-1
def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total building stock
"""
if not os.path.exists(self.readDOE_file_path):
raise Exception("readDOE.pkl file: '{}' does not exist.".format(readDOE_file_path))
readDOE_file = open(self.readDOE_file_path, 'rb') # open pickle file in binary form
refDOE = pickle.load(readDOE_file)
refBEM = pickle.load(readDOE_file)
refSchedule = pickle.load(readDOE_file)
readDOE_file.close()
# Define building energy models
k = 0
self.r_glaze_total = 0. # Glazing ratio for total building stock
self.SHGC_total = 0. # SHGC addition for total building stock
self.alb_wall_total = 0. # albedo wall addition for total building stock
h_floor = self.flr_h or 3.05 # average floor height
total_urban_bld_area = math.pow(self.charLength, 2)*self.bldDensity * \
self.bldHeight/h_floor # total building floor area
area_matrix = utilities.zeros(16, 3)
self.BEM = [] # list of BEMDef objects
self.Sch = [] # list of Schedule objects
for i in range(16): # 16 building types
for j in range(3): # 3 built eras
if self.bld[i][j] > 0.:
# Add to BEM list
self.BEM.append(refBEM[i][j][self.zone])
self.BEM[k].frac = self.bld[i][j]
self.BEM[k].fl_area = self.bld[i][j] * total_urban_bld_area
# Overwrite with optional parameters if provided
if self.glzR:
self.BEM[k].building.glazingRatio = self.glzR
if self.albRoof:
self.BEM[k].roof.albedo = self.albRoof
if self.vegRoof:
self.BEM[k].roof.vegCoverage = self.vegRoof
if self.SHGC:
self.BEM[k].building.shgc = self.SHGC
if self.albWall:
self.BEM[k].wall.albedo = self.albWall
if self.flr_h:
self.BEM[k].building.floorHeight = self.flr_h
# Keep track of total urban r_glaze, SHGC, and alb_wall for UCM model
self.r_glaze_total += self.BEM[k].frac * self.BEM[k].building.glazingRatio
self.SHGC_total += self.BEM[k].frac * self.BEM[k].building.shgc
self.alb_wall_total += self.BEM[k].frac * self.BEM[k].wall.albedo
# Add to schedule list
self.Sch.append(refSchedule[i][j][self.zone])
k += 1
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
self.geoParam # geographic parameters obj
self.RSM # Rural site & vertical diffusion model obj
self.USM # Urban site & vertical diffusion model obj
self.UCM # Urban canopy model obj
self.UBL # Urban boundary layer model
self.road # urban road element
self.rural # rural road element
self.soilindex1 # soil index for urban rsoad depth
self.soilindex2 # soil index for rural road depth
self.Sch # list of Schedule objects
"""
climate_file_path = os.path.join(self.epwDir, self.epwFileName)
self.simTime = SimParam(self.dtSim, self.dtWeather, self.Month,
self.Day, self.nDay) # simulation time parametrs
# weather file data for simulation time period
self.weather = Weather(climate_file_path, self.simTime.timeInitial, self.simTime.timeFinal)
self.forcIP = Forcing(self.weather.staTemp, self.weather) # initialized Forcing class
self.forc = Forcing() # empty forcing class
# Initialize geographic Param and Urban Boundary Layer Objects
nightStart = 18. # arbitrary values for begin/end hour for night setpoint
nightEnd = 8.
maxdx = 250. # max dx (m)
self.geoParam = Param(self.h_ubl1, self.h_ubl2, self.h_ref, self.h_temp, self.h_wind, self.c_circ,
self.maxDay, self.maxNight, self.latTree, self.latGrss, self.albVeg, self.vegStart, self.vegEnd,
nightStart, nightEnd, self.windMin, self.WGMAX, self.c_exch, maxdx, self.G, self.CP, self.VK, self.R,
self.RV, self.LV, math.pi, self.SIGMA, self.WATERDENS, self.LVTT, self.TT, self.ESTT, self.CL,
self.CPV, self.B, self.CM, self.COLBURN)
self.UBL = UBLDef(
'C', self.charLength, self.weather.staTemp[0], maxdx, self.geoParam.dayBLHeight, self.geoParam.nightBLHeight)
# Defining road
emis = 0.93
asphalt = Material(self.kRoad, self.cRoad, 'asphalt')
road_T_init = 293.
road_horizontal = 1
# fraction of surface vegetation coverage
road_veg_coverage = min(self.vegCover/(1-self.bldDensity), 1.)
# define road layers
road_layer_num = int(math.ceil(self.d_road/0.05))
# 0.5/0.05 ~ 10 x 1 matrix of 0.05 thickness
thickness_vector = [0.05 for r in range(road_layer_num)]
material_vector = [asphalt for r in range(road_layer_num)]
self.road = Element(self.alb_road, emis, thickness_vector, material_vector, road_veg_coverage,
road_T_init, road_horizontal, name="urban_road")
self.rural = copy.deepcopy(self.road)
self.rural.vegCoverage = self.rurVegCover
self.rural._name = "rural_road"
# Reference site class (also include VDM)
self.RSM = RSMDef(self.lat, self.lon, self.GMT, self.h_obs,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
self.USM = RSMDef(self.lat, self.lon, self.GMT, self.bldHeight/10.,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
T_init = self.weather.staTemp[0]
H_init = self.weather.staHum[0]
self.UCM = UCMDef(self.bldHeight, self.bldDensity, self.verToHor, self.treeCoverage, self.sensAnth, self.latAnth, T_init, H_init,
self.weather.staUmod[0], self.geoParam, self.r_glaze_total, self.SHGC_total, self.alb_wall_total, self.road)
self.UCM.h_mix = self.h_mix
# Define Road Element & buffer to match ground temperature depth
roadMat, newthickness = procMat(self.road, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
roadMat.append(self.SOIL)
self.soilindex1 = i
break
self.road = Element(self.road.albedo, self.road.emissivity, newthickness, roadMat,
self.road.vegCoverage, self.road.layerTemp[0], self.road.horizontal, self.road._name)
# Define Rural Element
ruralMat, newthickness = procMat(self.rural, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
ruralMat.append(self.SOIL)
self.soilindex2 = i
break
self.rural = Element(self.rural.albedo, self.rural.emissivity, newthickness,
ruralMat, self.rural.vegCoverage, self.rural.layerTemp[0], self.rural.horizontal, self.rural._name)
def hvac_autosize(self):
""" Section 6 - HVAC Autosizing (unlimited cooling & heating) """
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999.
def simulate(self):
""" Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# Output of object instance vector
self.WeatherData # Nx1 vector of forc instance
self.UCMData # Nx1 vector of UCM instance
self.UBLData # Nx1 vector of UBL instance
self.RSMData # Nx1 vector of RSM instance
self.USMData # Nx1 vector of USM instance
"""
self.N = int(self.simTime.days * 24) # total number of hours in simulation
n = 0 # weather time step counter
self.ph = self.simTime.dt/3600. # dt (simulation time step) in hours
# Data dump variables
time = range(self.N)
self.WeatherData = [None for x in range(self.N)]
self.UCMData = [None for x in range(self.N)]
self.UBLData = [None for x in range(self.N)]
self.RSMData = [None for x in range(self.N)]
self.USMData = [None for x in range(self.N)]
print('\nSimulating new temperature and humidity values for {} days from {}/{}.\n'.format(
int(self.nDay), int(self.Month), int(self.Day)))
self.logger.info("Start simulation")
for it in range(1, self.simTime.nt, 1): # for every simulation time-step (i.e 5 min) defined by uwg
# Update water temperature (estimated)
if self.nSoil < 3: # correction to original matlab code
# for BUBBLE/CAPITOUL/Singapore only
self.forc.deepTemp = sum(self.forcIP.temp)/float(len(self.forcIP.temp))
self.forc.waterTemp = sum(
self.forcIP.temp)/float(len(self.forcIP.temp)) - 10. # for BUBBLE/CAPITOUL/Singapore only
else:
# soil temperature by depth, by month
self.forc.deepTemp = self.Tsoil[self.soilindex1][self.simTime.month-1]
self.forc.waterTemp = self.Tsoil[2][self.simTime.month-1]
# There's probably a better way to update the weather...
self.simTime.UpdateDate()
self.logger.info("\n{0} m={1}, d={2}, h={3}, s={4}".format(
__name__, self.simTime.month, self.simTime.day, self.simTime.secDay/3600., self.simTime.secDay))
# simulation time increment raised to weather time step
self.ceil_time_step = int(math.ceil(it * self.ph))-1
# minus one to be consistent with forcIP list index
# Updating forcing instance
# horizontal Infrared Radiation Intensity (W m-2)
self.forc.infra = self.forcIP.infra[self.ceil_time_step]
# wind speed (m s-1)
self.forc.wind = max(self.forcIP.wind[self.ceil_time_step], self.geoParam.windMin)
self.forc.uDir = self.forcIP.uDir[self.ceil_time_step] # wind direction
# specific humidty (kg kg-1)
self.forc.hum = self.forcIP.hum[self.ceil_time_step]
self.forc.pres = self.forcIP.pres[self.ceil_time_step] # Pressure (Pa)
self.forc.temp = self.forcIP.temp[self.ceil_time_step] # air temperature (C)
self.forc.rHum = self.forcIP.rHum[self.ceil_time_step] # Relative humidity (%)
self.forc.prec = self.forcIP.prec[self.ceil_time_step] # Precipitation (mm h-1)
# horizontal solar diffuse radiation (W m-2)
self.forc.dif = self.forcIP.dif[self.ceil_time_step]
# normal solar direct radiation (W m-2)
self.forc.dir = self.forcIP.dir[self.ceil_time_step]
# Canyon humidity (absolute) same as rural
self.UCM.canHum = copy.copy(self.forc.hum)
# Update solar flux
self.solar = SolarCalcs(self.UCM, self.BEM, self.simTime,
self.RSM, self.forc, self.geoParam, self.rural)
self.rural, self.UCM, self.BEM = self.solar.solarcalcs()
# Update building & traffic schedule
# Assign day type (1 = weekday, 2 = sat, 3 = sun/other)
if self.is_near_zero(self.simTime.julian % 7):
self.dayType = 3 # Sunday
elif self.is_near_zero(self.simTime.julian % 7 - 6.):
self.dayType = 2 # Saturday
else:
self.dayType = 1 # Weekday
# Update anthropogenic heat load for each hour (building & UCM)
self.UCM.sensAnthrop = self.sensAnth * (self.SchTraffic[self.dayType-1][self.simTime.hourDay])
# Update the energy components for building types defined in initialize.uwg
for i in range(len(self.BEM)):
# Set temperature
self.BEM[i].building.coolSetpointDay = self.Sch[i].Cool[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for cooling
self.BEM[i].building.coolSetpointNight = self.BEM[i].building.coolSetpointDay
self.BEM[i].building.heatSetpointDay = self.Sch[i].Heat[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for heating
self.BEM[i].building.heatSetpointNight = self.BEM[i].building.heatSetpointDay
# Internal Heat Load Schedule (W/m^2 of floor area for Q)
self.BEM[i].Elec = self.Sch[i].Qelec * self.Sch[i].Elec[self.dayType -
1][self.simTime.hourDay] # Qelec x elec fraction for day
self.BEM[i].Light = self.Sch[i].Qlight * self.Sch[i].Light[self.dayType -
1][self.simTime.hourDay] # Qlight x light fraction for day
self.BEM[i].Nocc = self.Sch[i].Nocc * self.Sch[i].Occ[self.dayType -
1][self.simTime.hourDay] # Number of occupants x occ fraction for day
# Sensible Q occupant * fraction occupant sensible Q * number of occupants
self.BEM[i].Qocc = self.sensOcc * (1 - self.LatFOcc) * self.BEM[i].Nocc
# SWH and ventilation schedule
self.BEM[i].SWH = self.Sch[i].Vswh * self.Sch[i].SWH[self.dayType -
1][self.simTime.hourDay] # litres per hour x SWH fraction for day
# m^3/s/m^2 of floor
self.BEM[i].building.vent = self.Sch[i].Vent
self.BEM[i].Gas = self.Sch[i].Qgas * self.Sch[i].Gas[self.dayType -
1][self.simTime.hourDay] # Gas Equip Schedule, per m^2 of floor
# This is quite messy, should update
# Update internal heat and corresponding fractional loads
intHeat = self.BEM[i].Light + self.BEM[i].Elec + self.BEM[i].Qocc
# W/m2 from light, electricity, occupants
self.BEM[i].building.intHeatDay = intHeat
self.BEM[i].building.intHeatNight = intHeat
# fraction of radiant heat from light and equipment of whole internal heat
self.BEM[i].building.intHeatFRad = (
self.RadFLight * self.BEM[i].Light + self.RadFEquip * self.BEM[i].Elec) / intHeat
# fraction of latent heat (from occupants) of whole internal heat
self.BEM[i].building.intHeatFLat = self.LatFOcc * \
self.sensOcc * self.BEM[i].Nocc/intHeat
# Update envelope temperature layers
self.BEM[i].T_wallex = self.BEM[i].wall.layerTemp[0]
self.BEM[i].T_wallin = self.BEM[i].wall.layerTemp[-1]
self.BEM[i].T_roofex = self.BEM[i].roof.layerTemp[0]
self.BEM[i].T_roofin = self.BEM[i].roof.layerTemp[-1]
# Update rural heat fluxes & update vertical diffusion model (VDM)
self.rural.infra = self.forc.infra - self.rural.emissivity * self.SIGMA * \
self.rural.layerTemp[0]**4. # Infrared radiation from rural road
self.rural.SurfFlux(self.forc, self.geoParam, self.simTime,
self.forc.hum, self.forc.temp, self.forc.wind, 2., 0.)
self.RSM.VDM(self.forc, self.rural, self.geoParam, self.simTime)
# Calculate urban heat fluxes, update UCM & UBL
self.UCM, self.UBL, self.BEM = urbflux(
self.UCM, self.UBL, self.BEM, self.forc, self.geoParam, self.simTime, self.RSM)
self.UCM.UCModel(self.BEM, self.UBL.ublTemp, self.forc, self.geoParam)
self.UBL.UBLModel(self.UCM, self.RSM, self.rural,
self.forc, self.geoParam, self.simTime)
"""
# Experimental code to run diffusion model in the urban area
# N.B Commented out in python uwg because computed wind speed in
# urban VDM: y = =0.84*ln((2-x/20)/0.51) results in negative log
# for building heights >= 40m.
Uroad = copy.copy(self.UCM.road)
Uroad.sens = copy.copy(self.UCM.sensHeat)
Uforc = copy.copy(self.forc)
Uforc.wind = copy.copy(self.UCM.canWind)
Uforc.temp = copy.copy(self.UCM.canTemp)
self.USM.VDM(Uforc,Uroad,self.geoParam,self.simTime)
"""
self.logger.info("dbT = {}".format(self.UCM.canTemp-273.15))
if n > 0:
logging.info("dpT = {}".format(self.UCM.Tdp))
logging.info("RH = {}".format(self.UCM.canRHum))
if self.is_near_zero(self.simTime.secDay % self.simTime.timePrint) and n < self.N:
self.logger.info("{0} ----sim time step = {1}----\n\n".format(__name__, n))
self.WeatherData[n] = copy.copy(self.forc)
_Tdb, _w, self.UCM.canRHum, _h, self.UCM.Tdp, _v = psychrometrics(
self.UCM.canTemp, self.UCM.canHum, self.forc.pres)
self.UBLData[n] = copy.copy(self.UBL)
self.UCMData[n] = copy.copy(self.UCM)
self.RSMData[n] = copy.copy(self.RSM)
self.logger.info("dbT = {}".format(self.UCMData[n].canTemp-273.15))
self.logger.info("dpT = {}".format(self.UCMData[n].Tdp))
self.logger.info("RH = {}".format(self.UCMData[n].canRHum))
n += 1
def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] = column data of epw
self.epwinput[iJ+self.simTime.timeInitial-8][6] = "{0:.{1}f}".format(
self.UCMData[iJ].canTemp - 273.15, epw_prec) # dry bulb temperature [?C]
# dew point temperature [?C]
self.epwinput[iJ+self.simTime.timeInitial -
8][7] = "{0:.{1}f}".format(self.UCMData[iJ].Tdp, epw_prec)
# relative humidity [%]
self.epwinput[iJ+self.simTime.timeInitial -
8][8] = "{0:.{1}f}".format(self.UCMData[iJ].canRHum, epw_prec)
self.epwinput[iJ+self.simTime.timeInitial-8][21] = "{0:.{1}f}".format(
self.WeatherData[iJ].wind, epw_prec) # wind speed [m/s]
# Writing new EPW file
epw_new_id = open(self.newPathName, "w")
for i in range(8):
new_epw_line = '{}\n'.format(reduce(lambda x, y: x+","+y, self._header[i]))
epw_new_id.write(new_epw_line)
for i in range(len(self.epwinput)):
printme = ""
for ei in range(34):
printme += "{}".format(self.epwinput[i][ei]) + ','
printme = printme + "{}".format(self.epwinput[i][ei])
new_epw_line = "{0}\n".format(printme)
epw_new_id.write(new_epw_line)
epw_new_id.close()
print("New climate file '{}' is generated at {}.".format(
self.destinationFileName, self.destinationDir))
def run(self):
# run main class methods
self.read_epw()
self.set_input()
self.init_BEM_obj()
self.init_input_obj()
self.hvac_autosize()
self.simulate()
self.write_epw()
|
ladybug-tools/uwg | uwg/uwg.py | uwg.simulate | python | def simulate(self):
""" Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# Output of object instance vector
self.WeatherData # Nx1 vector of forc instance
self.UCMData # Nx1 vector of UCM instance
self.UBLData # Nx1 vector of UBL instance
self.RSMData # Nx1 vector of RSM instance
self.USMData # Nx1 vector of USM instance
"""
self.N = int(self.simTime.days * 24) # total number of hours in simulation
n = 0 # weather time step counter
self.ph = self.simTime.dt/3600. # dt (simulation time step) in hours
# Data dump variables
time = range(self.N)
self.WeatherData = [None for x in range(self.N)]
self.UCMData = [None for x in range(self.N)]
self.UBLData = [None for x in range(self.N)]
self.RSMData = [None for x in range(self.N)]
self.USMData = [None for x in range(self.N)]
print('\nSimulating new temperature and humidity values for {} days from {}/{}.\n'.format(
int(self.nDay), int(self.Month), int(self.Day)))
self.logger.info("Start simulation")
for it in range(1, self.simTime.nt, 1): # for every simulation time-step (i.e 5 min) defined by uwg
# Update water temperature (estimated)
if self.nSoil < 3: # correction to original matlab code
# for BUBBLE/CAPITOUL/Singapore only
self.forc.deepTemp = sum(self.forcIP.temp)/float(len(self.forcIP.temp))
self.forc.waterTemp = sum(
self.forcIP.temp)/float(len(self.forcIP.temp)) - 10. # for BUBBLE/CAPITOUL/Singapore only
else:
# soil temperature by depth, by month
self.forc.deepTemp = self.Tsoil[self.soilindex1][self.simTime.month-1]
self.forc.waterTemp = self.Tsoil[2][self.simTime.month-1]
# There's probably a better way to update the weather...
self.simTime.UpdateDate()
self.logger.info("\n{0} m={1}, d={2}, h={3}, s={4}".format(
__name__, self.simTime.month, self.simTime.day, self.simTime.secDay/3600., self.simTime.secDay))
# simulation time increment raised to weather time step
self.ceil_time_step = int(math.ceil(it * self.ph))-1
# minus one to be consistent with forcIP list index
# Updating forcing instance
# horizontal Infrared Radiation Intensity (W m-2)
self.forc.infra = self.forcIP.infra[self.ceil_time_step]
# wind speed (m s-1)
self.forc.wind = max(self.forcIP.wind[self.ceil_time_step], self.geoParam.windMin)
self.forc.uDir = self.forcIP.uDir[self.ceil_time_step] # wind direction
# specific humidty (kg kg-1)
self.forc.hum = self.forcIP.hum[self.ceil_time_step]
self.forc.pres = self.forcIP.pres[self.ceil_time_step] # Pressure (Pa)
self.forc.temp = self.forcIP.temp[self.ceil_time_step] # air temperature (C)
self.forc.rHum = self.forcIP.rHum[self.ceil_time_step] # Relative humidity (%)
self.forc.prec = self.forcIP.prec[self.ceil_time_step] # Precipitation (mm h-1)
# horizontal solar diffuse radiation (W m-2)
self.forc.dif = self.forcIP.dif[self.ceil_time_step]
# normal solar direct radiation (W m-2)
self.forc.dir = self.forcIP.dir[self.ceil_time_step]
# Canyon humidity (absolute) same as rural
self.UCM.canHum = copy.copy(self.forc.hum)
# Update solar flux
self.solar = SolarCalcs(self.UCM, self.BEM, self.simTime,
self.RSM, self.forc, self.geoParam, self.rural)
self.rural, self.UCM, self.BEM = self.solar.solarcalcs()
# Update building & traffic schedule
# Assign day type (1 = weekday, 2 = sat, 3 = sun/other)
if self.is_near_zero(self.simTime.julian % 7):
self.dayType = 3 # Sunday
elif self.is_near_zero(self.simTime.julian % 7 - 6.):
self.dayType = 2 # Saturday
else:
self.dayType = 1 # Weekday
# Update anthropogenic heat load for each hour (building & UCM)
self.UCM.sensAnthrop = self.sensAnth * (self.SchTraffic[self.dayType-1][self.simTime.hourDay])
# Update the energy components for building types defined in initialize.uwg
for i in range(len(self.BEM)):
# Set temperature
self.BEM[i].building.coolSetpointDay = self.Sch[i].Cool[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for cooling
self.BEM[i].building.coolSetpointNight = self.BEM[i].building.coolSetpointDay
self.BEM[i].building.heatSetpointDay = self.Sch[i].Heat[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for heating
self.BEM[i].building.heatSetpointNight = self.BEM[i].building.heatSetpointDay
# Internal Heat Load Schedule (W/m^2 of floor area for Q)
self.BEM[i].Elec = self.Sch[i].Qelec * self.Sch[i].Elec[self.dayType -
1][self.simTime.hourDay] # Qelec x elec fraction for day
self.BEM[i].Light = self.Sch[i].Qlight * self.Sch[i].Light[self.dayType -
1][self.simTime.hourDay] # Qlight x light fraction for day
self.BEM[i].Nocc = self.Sch[i].Nocc * self.Sch[i].Occ[self.dayType -
1][self.simTime.hourDay] # Number of occupants x occ fraction for day
# Sensible Q occupant * fraction occupant sensible Q * number of occupants
self.BEM[i].Qocc = self.sensOcc * (1 - self.LatFOcc) * self.BEM[i].Nocc
# SWH and ventilation schedule
self.BEM[i].SWH = self.Sch[i].Vswh * self.Sch[i].SWH[self.dayType -
1][self.simTime.hourDay] # litres per hour x SWH fraction for day
# m^3/s/m^2 of floor
self.BEM[i].building.vent = self.Sch[i].Vent
self.BEM[i].Gas = self.Sch[i].Qgas * self.Sch[i].Gas[self.dayType -
1][self.simTime.hourDay] # Gas Equip Schedule, per m^2 of floor
# This is quite messy, should update
# Update internal heat and corresponding fractional loads
intHeat = self.BEM[i].Light + self.BEM[i].Elec + self.BEM[i].Qocc
# W/m2 from light, electricity, occupants
self.BEM[i].building.intHeatDay = intHeat
self.BEM[i].building.intHeatNight = intHeat
# fraction of radiant heat from light and equipment of whole internal heat
self.BEM[i].building.intHeatFRad = (
self.RadFLight * self.BEM[i].Light + self.RadFEquip * self.BEM[i].Elec) / intHeat
# fraction of latent heat (from occupants) of whole internal heat
self.BEM[i].building.intHeatFLat = self.LatFOcc * \
self.sensOcc * self.BEM[i].Nocc/intHeat
# Update envelope temperature layers
self.BEM[i].T_wallex = self.BEM[i].wall.layerTemp[0]
self.BEM[i].T_wallin = self.BEM[i].wall.layerTemp[-1]
self.BEM[i].T_roofex = self.BEM[i].roof.layerTemp[0]
self.BEM[i].T_roofin = self.BEM[i].roof.layerTemp[-1]
# Update rural heat fluxes & update vertical diffusion model (VDM)
self.rural.infra = self.forc.infra - self.rural.emissivity * self.SIGMA * \
self.rural.layerTemp[0]**4. # Infrared radiation from rural road
self.rural.SurfFlux(self.forc, self.geoParam, self.simTime,
self.forc.hum, self.forc.temp, self.forc.wind, 2., 0.)
self.RSM.VDM(self.forc, self.rural, self.geoParam, self.simTime)
# Calculate urban heat fluxes, update UCM & UBL
self.UCM, self.UBL, self.BEM = urbflux(
self.UCM, self.UBL, self.BEM, self.forc, self.geoParam, self.simTime, self.RSM)
self.UCM.UCModel(self.BEM, self.UBL.ublTemp, self.forc, self.geoParam)
self.UBL.UBLModel(self.UCM, self.RSM, self.rural,
self.forc, self.geoParam, self.simTime)
"""
# Experimental code to run diffusion model in the urban area
# N.B Commented out in python uwg because computed wind speed in
# urban VDM: y = =0.84*ln((2-x/20)/0.51) results in negative log
# for building heights >= 40m.
Uroad = copy.copy(self.UCM.road)
Uroad.sens = copy.copy(self.UCM.sensHeat)
Uforc = copy.copy(self.forc)
Uforc.wind = copy.copy(self.UCM.canWind)
Uforc.temp = copy.copy(self.UCM.canTemp)
self.USM.VDM(Uforc,Uroad,self.geoParam,self.simTime)
"""
self.logger.info("dbT = {}".format(self.UCM.canTemp-273.15))
if n > 0:
logging.info("dpT = {}".format(self.UCM.Tdp))
logging.info("RH = {}".format(self.UCM.canRHum))
if self.is_near_zero(self.simTime.secDay % self.simTime.timePrint) and n < self.N:
self.logger.info("{0} ----sim time step = {1}----\n\n".format(__name__, n))
self.WeatherData[n] = copy.copy(self.forc)
_Tdb, _w, self.UCM.canRHum, _h, self.UCM.Tdp, _v = psychrometrics(
self.UCM.canTemp, self.UCM.canHum, self.forc.pres)
self.UBLData[n] = copy.copy(self.UBL)
self.UCMData[n] = copy.copy(self.UCM)
self.RSMData[n] = copy.copy(self.RSM)
self.logger.info("dbT = {}".format(self.UCMData[n].canTemp-273.15))
self.logger.info("dpT = {}".format(self.UCMData[n].Tdp))
self.logger.info("RH = {}".format(self.UCMData[n].canRHum))
n += 1 | Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# Output of object instance vector
self.WeatherData # Nx1 vector of forc instance
self.UCMData # Nx1 vector of UCM instance
self.UBLData # Nx1 vector of UBL instance
self.RSMData # Nx1 vector of RSM instance
self.USMData # Nx1 vector of USM instance | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/uwg.py#L737-L924 | [
"def urbflux(UCM, UBL, BEM, forc, parameter, simTime, RSM):\n \"\"\"\n Calculate the surface heat fluxes\n Output: [UCM,UBL,BEM]\n \"\"\"\n T_can = UCM.canTemp\n Cp = parameter.cp\n UCM.Q_roof = 0.\n sigma = 5.67e-8 # Stephan-Boltzman constant\n UCM.roofTemp = 0. # Average urban roof temperature\n UCM.wallTemp = 0. # Average urban wall temperature\n\n for j in range(len(BEM)):\n # Building energy model\n BEM[j].building.BEMCalc(UCM, BEM[j], forc, parameter, simTime)\n BEM[j].ElecTotal = BEM[j].building.ElecTotal * BEM[j].fl_area # W m-2\n\n # Update roof infra calc\n e_roof = BEM[j].roof.emissivity\n T_roof = BEM[j].roof.layerTemp[0]\n BEM[j].roof.infra = e_roof * (forc.infra - sigma * T_roof**4.)\n\n # update wall infra calc (road done later)\n e_wall = BEM[j].wall.emissivity\n T_wall = BEM[j].wall.layerTemp[0]\n # calculates the infrared radiation for wall, taking into account radiation exchange from road\n _infra_road_, BEM[j].wall.infra = infracalcs(UCM, forc, UCM.road.emissivity, e_wall, UCM.roadTemp, T_wall)\n\n # Update element temperatures\n BEM[j].mass.layerTemp = BEM[j].mass.Conduction(simTime.dt, BEM[j].building.fluxMass,1.,0.,BEM[j].building.fluxMass)\n BEM[j].roof.SurfFlux(forc,parameter,simTime,UCM.canHum,T_can,max(forc.wind,UCM.canWind),1.,BEM[j].building.fluxRoof)\n BEM[j].wall.SurfFlux(forc,parameter,simTime,UCM.canHum,T_can,UCM.canWind,1.,BEM[j].building.fluxWall)\n\n # Note the average wall & roof temperature\n UCM.wallTemp = UCM.wallTemp + BEM[j].frac*BEM[j].wall.layerTemp[0]\n UCM.roofTemp = UCM.roofTemp + BEM[j].frac*BEM[j].roof.layerTemp[0]\n\n # Update road infra calc (assume walls have similar emissivity, so use the last one)\n UCM.road.infra, _wall_infra = infracalcs(UCM,forc,UCM.road.emissivity,e_wall,UCM.roadTemp,UCM.wallTemp)\n UCM.road.SurfFlux(forc,parameter,simTime,UCM.canHum,T_can,UCM.canWind,2.,0.)\n UCM.roadTemp = UCM.road.layerTemp[0]\n\n # Sensible & latent heat flux (total)\n if UCM.latHeat != None:\n UCM.latHeat = UCM.latHeat + UCM.latAnthrop + UCM.treeLatHeat + UCM.road.lat*(1.-UCM.bldDensity)\n\n # ---------------------------------------------------------------------\n # Advective heat flux to UBL from VDM\n #\n # Note: UWG_Matlab code here is modified to compensate for rounding errors\n # that occur when recursively adding forDens, intAdv1, and intAdv2.\n # This causes issues in the UBL.advHeat calculatiuon when large (1e5)\n # numbers are subtracted to produce small numbers (1e-10) that can\n # differ from equivalent matlab calculations by a factor of 2.\n # Values this small are ~ 0, but for consistency's sake Kahan Summation\n # algorithm is applied to keep margin of difference from UWG_Matlab low.\n # ---------------------------------------------------------------------\n\n forDens = 0.0\n intAdv1 = 0.0\n intAdv2 = 0.0\n\n # c1 & c2 stores values truncated by floating point rounding for values < 10^-16\n c1 = 0.0\n c2 = 0.0\n c3 = 0.0\n\n for iz in range(RSM.nzfor):\n # At c loss of precision at at low order of magnitude, that we need in UBL.advHeat calc\n # Algebraically t is 0, but with floating pt numbers c will accumulate truncated values\n y = RSM.densityProfC[iz]*RSM.dz[iz]/(RSM.z[RSM.nzfor-1] + RSM.dz[RSM.nzfor-1]/2.)\n t = forDens + y\n c1 += (t - forDens) - y\n forDens = t\n\n y = RSM.windProf[iz]*RSM.tempProf[iz]*RSM.dz[iz]\n t = intAdv1 + y\n c2 += (t - intAdv1) - y\n intAdv1 = t\n\n y = RSM.windProf[iz]*RSM.dz[iz]\n t = intAdv2 + y\n c3 += (t - intAdv2) - y\n intAdv2 = t\n\n # Add the truncated values back\n forDens -= c1\n intAdv1 -= c2\n intAdv2 -= c3\n UBL.advHeat = UBL.paralLength*Cp*forDens*(intAdv1-(UBL.ublTemp*intAdv2))/UBL.urbArea\n\n # ---------------------------------------------------------------------\n # Convective heat flux to UBL from UCM (see Appendix - Bueno (2014))\n # ---------------------------------------------------------------------\n zrUrb = 2*UCM.bldHeight\n zref = RSM.z[RSM.nzref-1] # Reference height\n\n # Reference wind speed & canyon air density\n windUrb = forc.wind*log(zref/RSM.z0r)/log(parameter.windHeight/RSM.z0r)*\\\n log(zrUrb/UCM.z0u)/log(zref/UCM.z0u)\n dens = forc.pres/(1000*0.287042*T_can*(1.+1.607858*UCM.canHum))\n\n # Friction velocity\n UCM.ustar = parameter.vk*windUrb/log((zrUrb-UCM.l_disp)/UCM.z0u)\n\n # Convective scaling velocity\n wstar = (parameter.g*max(UCM.sensHeat,0.0)*zref/dens/Cp/T_can)**(1/3.)\n UCM.ustarMod = max(UCM.ustar,wstar) # Modified friction velocity\n UCM.uExch = parameter.exCoeff*UCM.ustarMod # Exchange velocity\n\n # Canyon wind speed, Eq. 27 Chp. 3 Hanna and Britter, 2002\n # assuming CD = 1 and lambda_f = verToHor/4\n UCM.canWind = UCM.ustarMod*(UCM.verToHor/8.)**(-1/2.)\n\n # Canyon turbulent velocities\n UCM.turbU = 2.4*UCM.ustarMod\n UCM.turbV = 1.9*UCM.ustarMod\n UCM.turbW = 1.3*UCM.ustarMod\n\n # Urban wind profile\n for iz in range(RSM.nzref):\n UCM.windProf.append(UCM.ustar/parameter.vk*\\\n log((RSM.z[iz]+UCM.bldHeight-UCM.l_disp)/UCM.z0u))\n\n return UCM,UBL,BEM\n",
"def VDM(self,forc,rural,parameter,simTime):\n\n self.tempProf[0] = forc.temp # Lower boundary condition\n\n # compute pressure profile\n for iz in reversed(list(range(self.nzref))[1:]):\n self.presProf[iz-1] = (math.pow(self.presProf[iz],parameter.r/parameter.cp) + \\\n parameter.g/parameter.cp*(math.pow(forc.pres,parameter.r/parameter.cp)) * \\\n (1./self.tempProf[iz] + 1./self.tempProf[iz-1]) * \\\n 0.5 * self.dz[iz])**(1./(parameter.r/parameter.cp))\n\n # compute the real temperature profile\n for iz in range(self.nzref):\n self.tempRealProf[iz]= self.tempProf[iz] * \\\n (self.presProf[iz]/forc.pres)**(parameter.r/parameter.cp)\n\n # compute the density profile\n for iz in range(self.nzref):\n self.densityProfC[iz] = self.presProf[iz]/parameter.r/self.tempRealProf[iz]\n self.densityProfS[0] = self.densityProfC[0]\n\n for iz in range(1,self.nzref):\n self.densityProfS[iz] = (self.densityProfC[iz] * self.dz[iz-1] + \\\n self.densityProfC[iz-1] * self.dz[iz])/(self.dz[iz-1] + self.dz[iz])\n\n self.densityProfS[self.nzref] = self.densityProfC[self.nzref-1]\n\n # Ref: The uwg (2012), Eq. (5)\n # compute diffusion coefficient\n cd,ustarRur = self.DiffusionCoefficient(self.densityProfC[0], \\\n self.z, self.dz, self.z0r, self.disp, \\\n self.tempProf[0], rural.sens, self.nzref, forc.wind, \\\n self.tempProf, parameter)\n\n\n # solve diffusion equation\n self.tempProf = self.DiffusionEquation(self.nzref,simTime.dt,\\\n self.tempProf,self.densityProfC,self.densityProfS,cd,self.dz)\n\n # compute wind profile\n # N.B In Matlab, negative values are converted to complex values.\n # log(-x) = log(x) + log(-1) = log(x) + i*pi\n # Python will throw an exception. Negative value occurs here if\n # VDM is run for average obstacle height ~ 4m.\n for iz in range(self.nzref):\n self.windProf[iz] = ustarRur/parameter.vk*\\\n math.log((self.z[iz]-self.disp)/self.z0r)\n\n # Average pressure\n self.ublPres = 0.\n for iz in range(self.nzfor):\n self.ublPres = self.ublPres + \\\n self.presProf[iz]*self.dz[iz]/(self.z[self.nzref-1]+self.dz[self.nzref-1]/2.)\n",
"def UpdateDate(self):\n self.secDay = self.secDay + self.dt\n\n if self.is_near_zero(self.secDay - 3600*24):\n self.day += 1\n self.julian = self.julian + 1\n self.secDay = 0.\n for j in range(12):\n if self.is_near_zero(self.julian - self.inobis[j]):\n self.month = self.month + 1\n self.day = 1\n\n if self.secDay > (3600*24):\n raise Exception(\"{}. CURRENTLY AT {}.\".format(self.TIMESTEP_CONFLICT_MSG, self.dt))\n\n self.hourDay = int(math.floor(self.secDay/3600.)) # 0 - 23hr\n",
"def solarcalcs(self):\n \"\"\" Solar Calculation\n Mutates RSM, BEM, and UCM objects based on following parameters:\n UCM # Urban Canopy - Building Energy Model object\n BEM # Building Energy Model object\n simTime # Simulation time bbject\n RSM # Rural Site & Vertical Diffusion Model Object\n forc # Forcing object\n parameter # Geo Param Object\n rural # Rural road Element object\n\n Properties\n self.dir # Direct sunlight\n self.dif # Diffuse sunlight\n self.tanzen\n self.critOrient\n self.horSol\n self.Kw_term\n self.Kr_term\n self.mr\n self.mw\n\n \"\"\"\n\n self.dir = self.forc.dir # Direct sunlight (perpendicular to the sun's ray)\n self.dif = self.forc.dif # Diffuse sunlight\n\n if self.dir + self.dif > 0.:\n\n self.logger.debug(\"{} Solar radiation > 0\".format(__name__))\n\n # calculate zenith tangent, and critOrient solar angles\n self.solarangles()\n\n self.horSol = max(math.cos(self.zenith)*self.dir, 0.0) # Direct horizontal radiation\n # Fractional terms for wall & road\n self.Kw_term = min(abs(1./self.UCM.canAspect*(0.5-self.critOrient/math.pi) \\\n + 1/math.pi*self.tanzen*(1-math.cos(self.critOrient))),1.)\n self.Kr_term = min(abs(2.*self.critOrient/math.pi \\\n - (2/math.pi*self.UCM.canAspect*self.tanzen)*(1-math.cos(self.critOrient))), 1-2*self.UCM.canAspect*self.Kw_term)\n\n\n # Direct and diffuse solar radiation\n self.bldSol = self.horSol*self.Kw_term + self.UCM.wallConf*self.dif # Assume trees are shorter than buildings\n self.roadSol = self.horSol*self.Kr_term + self.UCM.roadConf*self.dif\n\n # Solar reflections. Add diffuse radiation from vegetation to alb_road if in season\n if self.simTime.month < self.parameter.vegStart or self.simTime.month > self.parameter.vegEnd:\n alb_road = self.UCM.road.albedo\n else:\n alb_road = self.UCM.road.albedo*(1.-self.UCM.road.vegCoverage) + self.parameter.vegAlbedo*self.UCM.road.vegCoverage\n\n # First set of reflections\n rr = alb_road * self.roadSol\n rw = self.UCM.alb_wall * self.bldSol\n\n # bounces\n fr = (1. - (1. - 2.*self.UCM.wallConf) * self.UCM.alb_wall + (1. - self.UCM.roadConf) \\\n * self.UCM.wallConf * alb_road * self.UCM.alb_wall)\n\n # (1.0-self.UCM.roadConf) road to wall view\n self.mr = (rr + (1.0-self.UCM.roadConf) * alb_road * (rw + self.UCM.wallConf * self.UCM.alb_wall * rr)) / fr\n self.mw = (rw + self.UCM.wallConf * self.UCM.alb_wall * rr) / fr\n\n # Receiving solar, including bounces (W m-2)\n self.UCM.road.solRec = self.roadSol + (1 - self.UCM.roadConf)*self.mw\n\n for j in range(len(self.BEM)):\n self.BEM[j].roof.solRec = self.horSol + self.dif\n self.BEM[j].wall.solRec = self.bldSol + (1 - 2*self.UCM.wallConf) * self.mw + self.UCM.wallConf * self.mr\n\n self.rural.solRec = self.horSol + self.dif # Solar received by rural\n self.UCM.SolRecRoof = self.horSol + self.dif # Solar received by roof\n self.UCM.SolRecRoad = self.UCM.road.solRec # Solar received by road\n self.UCM.SolRecWall = self.bldSol+(1-2*self.UCM.wallConf)*self.UCM.road.albedo*self.roadSol # Solar received by wall\n\n # Vegetation heat (per m^2 of veg)\n self.UCM.treeSensHeat = (1-self.parameter.vegAlbedo)*(1-self.parameter.treeFLat)*self.UCM.SolRecRoad\n self.UCM.treeLatHeat = (1-self.parameter.vegAlbedo)*self.parameter.treeFLat*self.UCM.SolRecRoad\n\n else: # No Sun\n\n self.logger.debug(\"{} Solar radiation = 0\".format(__name__))\n\n self.UCM.road.solRec = 0.\n self.rural.solRec = 0.\n\n for j in range(len(self.BEM)):\n self.BEM[j].roof.solRec = 0.\n self.BEM[j].wall.solRec = 0.\n\n self.UCM.SolRecRoad = 0. # Solar received by road\n self.UCM.SolRecRoof = 0. # Solar received by roof\n self.UCM.SolRecWall = 0. # Solar received by wall\n self.UCM.treeSensHeat = 0.\n self.UCM.treeLatHeat = 0.\n\n return self.rural, self.UCM, self.BEM\n",
"def is_near_zero(self,num,eps=1e-10):\n return abs(float(num)) < eps\n"
] | class uwg(object):
"""Morph a rural EPW file to urban conditions using a file with a list of urban parameters.
args:
epwDir: The directory in which the rural EPW file sits.
epwFileName: The name of the rural epw file that will be morphed.
uwgParamDir: The directory in which the uwg Parameter File (.uwg) sits.
uwgParamFileName: The name of the uwg Parameter File (.uwg).
destinationDir: Optional destination directory for the morphed EPW file.
If left blank, the morphed file will be written into the same directory
as the rural EPW file (the epwDir).
destinationFileName: Optional destination file name for the morphed EPW file.
If left blank, the morphed file will append "_UWG" to the original file name.
returns:
newClimateFile: the path to a new EPW file that has been morphed to account
for uban conditions.
"""
""" Section 1 - Definitions for constants / other parameters """
MINTHICKNESS = 0.01 # Minimum layer thickness (to prevent crashing) (m)
MAXTHICKNESS = 0.05 # Maximum layer thickness (m)
# http://web.mit.edu/parmstr/Public/NRCan/nrcc29118.pdf (Figly & Snodgrass)
SOILTCOND = 1
# http://www.europment.org/library/2013/venice/bypaper/MFHEEF/MFHEEF-21.pdf (average taken from Table 1)
SOILVOLHEAT = 2e6
# Soil material used for soil-depth padding
SOIL = Material(SOILTCOND, SOILVOLHEAT, name="soil")
# Physical constants
G = 9.81 # gravity (m s-2)
CP = 1004. # heat capacity for air (J/kg K)
VK = 0.40 # von karman constant (dimensionless)
R = 287. # gas constant dry air (J/kg K)
RV = 461.5 # gas constant water vapor (J/kg K)
LV = 2.26e6 # latent heat of evaporation (J/kg)
SIGMA = 5.67e-08 # Stefan Boltzmann constant (W m-2 K-4)
WATERDENS = 1000. # water density (kg m-3)
LVTT = 2.5008e6 #
TT = 273.16 #
ESTT = 611.14 #
CL = 4.218e3 #
CPV = 1846.1 #
B = 9.4 # Coefficients derived by Louis (1979)
CM = 7.4 #
# (Pr/Sc)^(2/3) for Colburn analogy in water evaporation
COLBURN = math.pow((0.713/0.621), (2/3.))
# Site-specific parameters
WGMAX = 0.005 # maximum film water depth on horizontal surfaces (m)
# File path parameter
RESOURCE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "resources"))
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
def __init__(self, epwFileName, uwgParamFileName=None, epwDir=None, uwgParamDir=None, destinationDir=None, destinationFileName=None):
# Logger will be disabled by default unless explicitly called in tests
self.logger = logging.getLogger(__name__)
# User defined
self.epwFileName = epwFileName if epwFileName.lower().endswith('.epw') else epwFileName + \
'.epw' # Revise epw file name if not end with epw
# If file name is entered then will uwg will set input from .uwg file
self.uwgParamFileName = uwgParamFileName
# If user does not overload
self.destinationFileName = destinationFileName if destinationFileName else self.epwFileName.strip(
'.epw') + '_UWG.epw'
self.epwDir = epwDir if epwDir else os.path.join(self.RESOURCE_PATH, "epw")
self.uwgParamDir = uwgParamDir if uwgParamDir else os.path.join(
self.RESOURCE_PATH, "parameters")
self.destinationDir = destinationDir if destinationDir else os.path.join(
self.RESOURCE_PATH, "epw_uwg")
# refdata: Serialized DOE reference data, z_meso height data
self.readDOE_file_path = os.path.join(self.CURRENT_PATH, "refdata", "readDOE.pkl")
self.z_meso_dir_path = os.path.join(self.CURRENT_PATH, "refdata")
# EPW precision
self.epw_precision = 1
# init uwg variables
self._init_param_dict = None
# Define Simulation and Weather parameters
self.Month = None # starting month (1-12)
self.Day = None # starting day (1-31)
self.nDay = None # number of days
self.dtSim = None # simulation time step (s)
self.dtWeather = None # seconds (s)
# HVAC system and internal laod
self.autosize = None # autosize HVAC (1 or 0)
self.sensOcc = None # Sensible heat from occupant
self.LatFOcc = None # Latent heat fraction from occupant (normally 0.3)
self.RadFOcc = None # Radiant heat fraction from occupant (normally 0.2)
self.RadFEquip = None # Radiant heat fraction from equipment (normally 0.5)
self.RadFLight = None # Radiant heat fraction from light (normally 0.7)
# Define Urban microclimate parameters
self.h_ubl1 = None # ubl height - day (m)
self.h_ubl2 = None # ubl height - night (m)
self.h_ref = None # inversion height
self.h_temp = None # temperature height
self.h_wind = None # wind height
self.c_circ = None # circulation coefficient
self.c_exch = None # exchange coefficient
self.maxDay = None # max day threshhold
self.maxNight = None # max night threshhold
self.windMin = None # min wind speed (m/s)
self.h_obs = None # rural average obstacle height
# Urban characteristics
self.bldHeight = None # average building height (m)
self.h_mix = None # mixing height (m)
self.bldDensity = None # building density (0-1)
self.verToHor = None # building aspect ratio
# radius defining the urban area of study [aka. characteristic length] (m)
self.charLength = None
self.alb_road = None # road albedo
self.d_road = None # road pavement thickness
self.sensAnth = None # non-building sensible heat (W/m^2)
self.latAnth = None # non-building latent heat heat (W/m^2). Not used, taken out by JH.
# Fraction of building typology stock
self.bld = None # 16x3 matrix of fraction of building type by era
# climate Zone
self.zone = None
# Vegetation parameters
self.vegCover = None # urban area veg coverage ratio
self.treeCoverage = None # urban area tree coverage ratio
self.vegStart = None # vegetation start month
self.vegEnd = None # vegetation end month
self.albVeg = None # Vegetation albedo
self.rurVegCover = None # rural vegetation cover
self.latGrss = None # latent fraction of grass
self.latTree = None # latent fraction of tree
# Define Traffic schedule
self.SchTraffic = None
# Define Road (Assume 0.5m of asphalt)
self.kRoad = None # road pavement conductivity (W/m K)
self.cRoad = None # road volumetric heat capacity (J/m^3 K)
# Define optional Building characteristics
self.flr_h = None # floor-to-floor height
self.albRoof = None # roof albedo (0 - 1)
self.vegRoof = None # Fraction of the roofs covered in grass/shrubs (0-1)
self.glzR = None # Glazing Ratio
self.SHGC = None # Solar Heat Gain Coefficient
self.albWall = None # Wall albedo
def ToString(self):
"""Overwrite .NET ToString method."""
return self.__repr__()
def __repr__(self):
def _split_string(s):
return s[0] + ":\n " + s[1].replace(",", "\n ")
def _tabbed(s):
return _split_string(s.__repr__().split(":"))
def _list_2_tabbed(b):
return reduce(lambda a, b: a+"\n"+b, [_tabbed(_b) for _b in b])
return "uwg for {}:\n\n{}{}{}{}{}{}{}{}".format(
self.epwFileName,
_tabbed(self.simTime)+"\n" if hasattr(self, "simTime") else "No simTime attr.\n",
_tabbed(self.weather)+"\n" if hasattr(self, "weather") else "No weather attr.\n",
_tabbed(self.geoParam)+"\n" if hasattr(self, "geoParam") else "No geoParam attr.\n",
_tabbed(self.UBL)+"\n" if hasattr(self, "UBL") else "No UBL attr.\n",
"Rural "+_tabbed(self.RSM)+"\n" if hasattr(self, "RSM") else "No Rural RSM attr.\n",
"Urban "+_tabbed(self.USM)+"\n" if hasattr(self, "USM") else "No Urban RSM attr.\n",
_tabbed(self.UCM)+"\n" if hasattr(self, "UCM") else "No UCM attr.\n",
_list_2_tabbed(self.BEM) if hasattr(self, "BEM") else "No BEM attr."
)
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def read_epw(self):
"""Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT # GMT
self.nSoil # Number of soil depths
self.Tsoil # nSoil x 12 matrix for soil temperture (K)
self.depth_soil # nSoil x 1 matrix for soil depth (m)
"""
# Make dir path to epw file
self.climateDataPath = os.path.join(self.epwDir, self.epwFileName)
# Open epw file and feed csv data to climate_data
try:
climate_data = utilities.read_csv(self.climateDataPath)
except Exception as e:
raise Exception("Failed to read epw file! {}".format(e.message))
# Read header lines (1 to 8) from EPW and ensure TMY2 format.
self._header = climate_data[0:8]
# Read weather data from EPW for each time step in weather file. (lines 8 - end)
self.epwinput = climate_data[8:]
# Read Lat, Long (line 1 of EPW)
self.lat = float(self._header[0][6])
self.lon = float(self._header[0][7])
self.GMT = float(self._header[0][8])
# Read in soil temperature data (assumes this is always there)
# ref: http://bigladdersoftware.com/epx/docs/8-2/auxiliary-programs/epw-csv-format-inout.html
soilData = self._header[3]
self.nSoil = int(soilData[1]) # Number of ground temperature depths
self.Tsoil = utilities.zeros(self.nSoil, 12) # nSoil x 12 matrix for soil temperture (K)
self.depth_soil = utilities.zeros(self.nSoil, 1) # nSoil x 1 matrix for soil depth (m)
# Read monthly data for each layer of soil from EPW file
for i in range(self.nSoil):
self.depth_soil[i][0] = float(soilData[2 + (i*16)]) # get soil depth for each nSoil
# Monthly data
for j in range(12):
# 12 months of soil T for specific depth
self.Tsoil[i][j] = float(soilData[6 + (i*16) + j]) + 273.15
# Set new directory path for the moprhed EPW file
self.newPathName = os.path.join(self.destinationDir, self.destinationFileName)
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic # Traffice schedule
self.BEM # list of BEMDef objects extracted from readDOE
self.Sch # list of Schedule objects extracted from readDOE
"""
uwg_param_file_path = os.path.join(self.uwgParamDir, self.uwgParamFileName)
if not os.path.exists(uwg_param_file_path):
raise Exception("Param file: '{}' does not exist.".format(uwg_param_file_path))
# Open .uwg file and feed csv data to initializeDataFile
try:
uwg_param_data = utilities.read_csv(uwg_param_file_path)
except Exception as e:
raise Exception("Failed to read .uwg file! {}".format(e.message))
# The initialize.uwg is read with a dictionary so that users changing
# line endings or line numbers doesn't make reading input incorrect
self._init_param_dict = {}
count = 0
while count < len(uwg_param_data):
row = uwg_param_data[count]
row = [row[i].replace(" ", "") for i in range(len(row))] # strip white spaces
# Optional parameters might be empty so handle separately
is_optional_parameter = (
row != [] and
(
row[0] == "albRoof" or
row[0] == "vegRoof" or
row[0] == "glzR" or
row[0] == "hvac" or
row[0] == "albWall" or
row[0] == "SHGC"
)
)
try:
if row == [] or "#" in row[0]:
count += 1
continue
elif row[0] == "SchTraffic":
# SchTraffic: 3 x 24 matrix
trafficrows = uwg_param_data[count+1:count+4]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:24]) for r in trafficrows]
count += 4
elif row[0] == "bld":
# bld: 17 x 3 matrix
bldrows = uwg_param_data[count+1:count+17]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:3]) for r in bldrows]
count += 17
elif is_optional_parameter:
self._init_param_dict[row[0]] = float(row[1]) if row[1] != "" else None
count += 1
else:
self._init_param_dict[row[0]] = float(row[1])
count += 1
except ValueError:
print("Error while reading parameter at {} {}".format(count, row))
ipd = self._init_param_dict
# Define Simulation and Weather parameters
if self.Month is None: self.Month = ipd['Month']
if self.Day is None: self.Day = ipd['Day']
if self.nDay is None: self.nDay = ipd['nDay']
if self.dtSim is None: self.dtSim = ipd['dtSim']
if self.dtWeather is None: self.dtWeather = ipd['dtWeather']
# HVAC system and internal laod
if self.autosize is None: self.autosize = ipd['autosize']
if self.sensOcc is None: self.sensOcc = ipd['sensOcc']
if self.LatFOcc is None: self.LatFOcc = ipd['LatFOcc']
if self.RadFOcc is None: self.RadFOcc = ipd['RadFOcc']
if self.RadFEquip is None: self.RadFEquip = ipd['RadFEquip']
if self.RadFLight is None: self.RadFLight = ipd['RadFLight']
# Define Urban microclimate parameters
if self.h_ubl1 is None: self.h_ubl1 = ipd['h_ubl1']
if self.h_ubl2 is None: self.h_ubl2 = ipd['h_ubl2']
if self.h_ref is None: self.h_ref = ipd['h_ref']
if self.h_temp is None: self.h_temp = ipd['h_temp']
if self.h_wind is None: self.h_wind = ipd['h_wind']
if self.c_circ is None: self.c_circ = ipd['c_circ']
if self.c_exch is None: self.c_exch = ipd['c_exch']
if self.maxDay is None: self.maxDay = ipd['maxDay']
if self.maxNight is None: self.maxNight = ipd['maxNight']
if self.windMin is None: self.windMin = ipd['windMin']
if self.h_obs is None: self.h_obs = ipd['h_obs']
# Urban characteristics
if self.bldHeight is None: self.bldHeight = ipd['bldHeight']
if self.h_mix is None: self.h_mix = ipd['h_mix']
if self.bldDensity is None: self.bldDensity = ipd['bldDensity']
if self.verToHor is None: self.verToHor = ipd['verToHor']
if self.charLength is None: self.charLength = ipd['charLength']
if self.alb_road is None: self.alb_road = ipd['albRoad']
if self.d_road is None: self.d_road = ipd['dRoad']
if self.sensAnth is None: self.sensAnth = ipd['sensAnth']
# if self.latAnth is None: self.latAnth = ipd['latAnth'] # Not used, taken out by JH.
# climate Zone
if self.zone is None: self.zone = ipd['zone']
# Vegetation parameters
if self.vegCover is None: self.vegCover = ipd['vegCover']
if self.treeCoverage is None: self.treeCoverage = ipd['treeCoverage']
if self.vegStart is None: self.vegStart = ipd['vegStart']
if self.vegEnd is None: self.vegEnd = ipd['vegEnd']
if self.albVeg is None: self.albVeg = ipd['albVeg']
if self.rurVegCover is None: self.rurVegCover = ipd['rurVegCover']
if self.latGrss is None: self.latGrss = ipd['latGrss']
if self.latTree is None: self.latTree = ipd['latTree']
# Define Traffic schedule
if self.SchTraffic is None: self.SchTraffic = ipd['SchTraffic']
# Define Road (Assume 0.5m of asphalt)
if self.kRoad is None: self.kRoad = ipd['kRoad']
if self.cRoad is None: self.cRoad = ipd['cRoad']
# Building stock fraction
if self.bld is None: self.bld = ipd['bld']
# Optional parameters
if self.albRoof is None: self.albRoof = ipd['albRoof']
if self.vegRoof is None: self.vegRoof = ipd['vegRoof']
if self.glzR is None: self.glzR = ipd['glzR']
if self.albWall is None: self.albWall = ipd['albWall']
if self.SHGC is None: self.SHGC = ipd['SHGC']
def check_required_inputs(self):
# Fail if required parameters aren't correct
assert isinstance(self.Month, (float, int)), \
'Month must be a number. Got {}'.format(type(self.Month))
assert isinstance(self.Day, (float, int)), \
'Day must be a number. Got {}'.format(type(self.Day))
assert isinstance(self.nDay, (float, int)), \
'nDay must be a number. Got {}'.format(type(self.nDay))
assert isinstance(self.dtSim, float), \
'dtSim must be a float. Got {}'.format(type(self.dtSim))
assert isinstance(self.dtWeather, float), \
'dtWeather must be a float. Got {}'.format(type(self.dtWeather))
assert isinstance(self.autosize, (float, int)), \
'autosize must be a number. Got {}'.format(type(self.autosize))
assert isinstance(self.sensOcc, float), \
'sensOcc must be a float. Got {}'.format(type(self.sensOcc))
assert isinstance(self.LatFOcc, float), \
'LatFOcc must be a float. Got {}'.format(type(self.LatFOcc))
assert isinstance(self.RadFOcc, float), \
'RadFOcc must be a float. Got {}'.format(type(self.RadFOcc))
assert isinstance(self.RadFEquip, float), \
'RadFEquip must be a float. Got {}'.format(type(self.RadFEquip))
assert isinstance(self.RadFLight, float), \
'RadFLight must be a float. Got {}'.format(type(self.RadFLight))
assert isinstance(self.h_ubl1, float), \
'h_ubl1 must be a float. Got {}'.format(type(self.h_ubl1))
assert isinstance(self.h_ubl2, float), \
'h_ubl2 must be a float. Got {}'.format(type(self.h_ubl2))
assert isinstance(self.h_ref, float), \
'h_ref must be a float. Got {}'.format(type(self.h_ref))
assert isinstance(self.h_temp, float), \
'h_temp must be a float. Got {}'.format(type(self.h_temp))
assert isinstance(self.h_wind, float), \
'h_wind must be a float. Got {}'.format(type(self.h_wind))
assert isinstance(self.c_circ, float), \
'c_circ must be a float. Got {}'.format(type(self.c_circ))
assert isinstance(self.c_exch, float), \
'c_exch must be a float. Got {}'.format(type(self.c_exch))
assert isinstance(self.maxDay, float), \
'maxDay must be a float. Got {}'.format(type(self.maxDay))
assert isinstance(self.maxNight, float), \
'maxNight must be a float. Got {}'.format(type(self.maxNight))
assert isinstance(self.windMin, float), \
'windMin must be a float. Got {}'.format(type(self.windMin))
assert isinstance(self.h_obs, float), \
'h_obs must be a float. Got {}'.format(type(self.h_obs))
assert isinstance(self.bldHeight, float), \
'bldHeight must be a float. Got {}'.format(type(self.bldHeight))
assert isinstance(self.h_mix, float), \
'h_mix must be a float. Got {}'.format(type(self.h_mix))
assert isinstance(self.bldDensity, float), \
'bldDensity must be a float. Got {}'.format(type(self.bldDensity))
assert isinstance(self.verToHor, float), \
'verToHor must be a float. Got {}'.format(type(self.verToHor))
assert isinstance(self.charLength, float), \
'charLength must be a float. Got {}'.format(type(self.charLength))
assert isinstance(self.alb_road, float), \
'alb_road must be a float. Got {}'.format(type(self.alb_road))
assert isinstance(self.d_road, float), \
'd_road must be a float. Got {}'.format(type(self.d_road))
assert isinstance(self.sensAnth, float), \
'sensAnth must be a float. Got {}'.format(type(self.sensAnth))
# assert isinstance(self.latAnth, float) # Take this out as isn't being used
assert isinstance(self.bld, list), \
'bld must be a list. Got {}'.format(type(self.bld))
assert len(self.bld) == 16, \
'length of bld must be 16. Got {}'.format(len(self.bld))
assert isinstance(self.latTree, float), \
'latTree must be a float. Got {}'.format(type(self.latTree))
assert isinstance(self.latGrss, float), \
'latGrss must be a float. Got {}'.format(type(self.latGrss))
assert isinstance(self.zone, (float, int)), \
'zone must be a number. Got {}'.format(type(self.zone))
assert isinstance(self.vegStart, (float, int)), \
'vegStart must be a number. Got {}'.format(type(self.vegStart))
assert isinstance(self.vegEnd, (float, int)), \
'vegEnd must be a number. Got {}'.format(type(self.vegEnd))
assert isinstance(self.vegCover, float), \
'vegCover must be a float. Got {}'.format(type(self.vegCover))
assert isinstance(self.treeCoverage, float), \
'treeCoverage must be a float. Got {}'.format(type(self.treeCoverage))
assert isinstance(self.albVeg, float), \
'albVeg must be a float. Got {}'.format(type(self.albVeg))
assert isinstance(self.rurVegCover, float), \
'rurVegCover must be a float. Got {}'.format(type(self.rurVegCover))
assert isinstance(self.kRoad, float), \
'kRoad must be a float. Got {}'.format(type(self.kRoad))
assert isinstance(self.cRoad, float), \
'cRoad must be a float. Got {}'.format(type(self.cRoad))
assert isinstance(self.SchTraffic, list), \
'SchTraffic must be a list. Got {}'.format(type(self.SchTraffic))
assert len(self.SchTraffic) == 3, \
'length of SchTraffic must be 3. Got {}'.format(len(self.SchTraffic))
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the .uwg file.
if self.uwgParamFileName is not None:
print("\nReading uwg file input.")
self.read_input()
else:
print("\nNo .uwg file input.")
self.check_required_inputs()
# Modify zone to be used as python index
self.zone = int(self.zone)-1
def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total building stock
"""
if not os.path.exists(self.readDOE_file_path):
raise Exception("readDOE.pkl file: '{}' does not exist.".format(readDOE_file_path))
readDOE_file = open(self.readDOE_file_path, 'rb') # open pickle file in binary form
refDOE = pickle.load(readDOE_file)
refBEM = pickle.load(readDOE_file)
refSchedule = pickle.load(readDOE_file)
readDOE_file.close()
# Define building energy models
k = 0
self.r_glaze_total = 0. # Glazing ratio for total building stock
self.SHGC_total = 0. # SHGC addition for total building stock
self.alb_wall_total = 0. # albedo wall addition for total building stock
h_floor = self.flr_h or 3.05 # average floor height
total_urban_bld_area = math.pow(self.charLength, 2)*self.bldDensity * \
self.bldHeight/h_floor # total building floor area
area_matrix = utilities.zeros(16, 3)
self.BEM = [] # list of BEMDef objects
self.Sch = [] # list of Schedule objects
for i in range(16): # 16 building types
for j in range(3): # 3 built eras
if self.bld[i][j] > 0.:
# Add to BEM list
self.BEM.append(refBEM[i][j][self.zone])
self.BEM[k].frac = self.bld[i][j]
self.BEM[k].fl_area = self.bld[i][j] * total_urban_bld_area
# Overwrite with optional parameters if provided
if self.glzR:
self.BEM[k].building.glazingRatio = self.glzR
if self.albRoof:
self.BEM[k].roof.albedo = self.albRoof
if self.vegRoof:
self.BEM[k].roof.vegCoverage = self.vegRoof
if self.SHGC:
self.BEM[k].building.shgc = self.SHGC
if self.albWall:
self.BEM[k].wall.albedo = self.albWall
if self.flr_h:
self.BEM[k].building.floorHeight = self.flr_h
# Keep track of total urban r_glaze, SHGC, and alb_wall for UCM model
self.r_glaze_total += self.BEM[k].frac * self.BEM[k].building.glazingRatio
self.SHGC_total += self.BEM[k].frac * self.BEM[k].building.shgc
self.alb_wall_total += self.BEM[k].frac * self.BEM[k].wall.albedo
# Add to schedule list
self.Sch.append(refSchedule[i][j][self.zone])
k += 1
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
self.geoParam # geographic parameters obj
self.RSM # Rural site & vertical diffusion model obj
self.USM # Urban site & vertical diffusion model obj
self.UCM # Urban canopy model obj
self.UBL # Urban boundary layer model
self.road # urban road element
self.rural # rural road element
self.soilindex1 # soil index for urban rsoad depth
self.soilindex2 # soil index for rural road depth
self.Sch # list of Schedule objects
"""
climate_file_path = os.path.join(self.epwDir, self.epwFileName)
self.simTime = SimParam(self.dtSim, self.dtWeather, self.Month,
self.Day, self.nDay) # simulation time parametrs
# weather file data for simulation time period
self.weather = Weather(climate_file_path, self.simTime.timeInitial, self.simTime.timeFinal)
self.forcIP = Forcing(self.weather.staTemp, self.weather) # initialized Forcing class
self.forc = Forcing() # empty forcing class
# Initialize geographic Param and Urban Boundary Layer Objects
nightStart = 18. # arbitrary values for begin/end hour for night setpoint
nightEnd = 8.
maxdx = 250. # max dx (m)
self.geoParam = Param(self.h_ubl1, self.h_ubl2, self.h_ref, self.h_temp, self.h_wind, self.c_circ,
self.maxDay, self.maxNight, self.latTree, self.latGrss, self.albVeg, self.vegStart, self.vegEnd,
nightStart, nightEnd, self.windMin, self.WGMAX, self.c_exch, maxdx, self.G, self.CP, self.VK, self.R,
self.RV, self.LV, math.pi, self.SIGMA, self.WATERDENS, self.LVTT, self.TT, self.ESTT, self.CL,
self.CPV, self.B, self.CM, self.COLBURN)
self.UBL = UBLDef(
'C', self.charLength, self.weather.staTemp[0], maxdx, self.geoParam.dayBLHeight, self.geoParam.nightBLHeight)
# Defining road
emis = 0.93
asphalt = Material(self.kRoad, self.cRoad, 'asphalt')
road_T_init = 293.
road_horizontal = 1
# fraction of surface vegetation coverage
road_veg_coverage = min(self.vegCover/(1-self.bldDensity), 1.)
# define road layers
road_layer_num = int(math.ceil(self.d_road/0.05))
# 0.5/0.05 ~ 10 x 1 matrix of 0.05 thickness
thickness_vector = [0.05 for r in range(road_layer_num)]
material_vector = [asphalt for r in range(road_layer_num)]
self.road = Element(self.alb_road, emis, thickness_vector, material_vector, road_veg_coverage,
road_T_init, road_horizontal, name="urban_road")
self.rural = copy.deepcopy(self.road)
self.rural.vegCoverage = self.rurVegCover
self.rural._name = "rural_road"
# Reference site class (also include VDM)
self.RSM = RSMDef(self.lat, self.lon, self.GMT, self.h_obs,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
self.USM = RSMDef(self.lat, self.lon, self.GMT, self.bldHeight/10.,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
T_init = self.weather.staTemp[0]
H_init = self.weather.staHum[0]
self.UCM = UCMDef(self.bldHeight, self.bldDensity, self.verToHor, self.treeCoverage, self.sensAnth, self.latAnth, T_init, H_init,
self.weather.staUmod[0], self.geoParam, self.r_glaze_total, self.SHGC_total, self.alb_wall_total, self.road)
self.UCM.h_mix = self.h_mix
# Define Road Element & buffer to match ground temperature depth
roadMat, newthickness = procMat(self.road, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
roadMat.append(self.SOIL)
self.soilindex1 = i
break
self.road = Element(self.road.albedo, self.road.emissivity, newthickness, roadMat,
self.road.vegCoverage, self.road.layerTemp[0], self.road.horizontal, self.road._name)
# Define Rural Element
ruralMat, newthickness = procMat(self.rural, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
ruralMat.append(self.SOIL)
self.soilindex2 = i
break
self.rural = Element(self.rural.albedo, self.rural.emissivity, newthickness,
ruralMat, self.rural.vegCoverage, self.rural.layerTemp[0], self.rural.horizontal, self.rural._name)
def hvac_autosize(self):
""" Section 6 - HVAC Autosizing (unlimited cooling & heating) """
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999.
def simulate(self):
""" Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# Output of object instance vector
self.WeatherData # Nx1 vector of forc instance
self.UCMData # Nx1 vector of UCM instance
self.UBLData # Nx1 vector of UBL instance
self.RSMData # Nx1 vector of RSM instance
self.USMData # Nx1 vector of USM instance
"""
self.N = int(self.simTime.days * 24) # total number of hours in simulation
n = 0 # weather time step counter
self.ph = self.simTime.dt/3600. # dt (simulation time step) in hours
# Data dump variables
time = range(self.N)
self.WeatherData = [None for x in range(self.N)]
self.UCMData = [None for x in range(self.N)]
self.UBLData = [None for x in range(self.N)]
self.RSMData = [None for x in range(self.N)]
self.USMData = [None for x in range(self.N)]
print('\nSimulating new temperature and humidity values for {} days from {}/{}.\n'.format(
int(self.nDay), int(self.Month), int(self.Day)))
self.logger.info("Start simulation")
for it in range(1, self.simTime.nt, 1): # for every simulation time-step (i.e 5 min) defined by uwg
# Update water temperature (estimated)
if self.nSoil < 3: # correction to original matlab code
# for BUBBLE/CAPITOUL/Singapore only
self.forc.deepTemp = sum(self.forcIP.temp)/float(len(self.forcIP.temp))
self.forc.waterTemp = sum(
self.forcIP.temp)/float(len(self.forcIP.temp)) - 10. # for BUBBLE/CAPITOUL/Singapore only
else:
# soil temperature by depth, by month
self.forc.deepTemp = self.Tsoil[self.soilindex1][self.simTime.month-1]
self.forc.waterTemp = self.Tsoil[2][self.simTime.month-1]
# There's probably a better way to update the weather...
self.simTime.UpdateDate()
self.logger.info("\n{0} m={1}, d={2}, h={3}, s={4}".format(
__name__, self.simTime.month, self.simTime.day, self.simTime.secDay/3600., self.simTime.secDay))
# simulation time increment raised to weather time step
self.ceil_time_step = int(math.ceil(it * self.ph))-1
# minus one to be consistent with forcIP list index
# Updating forcing instance
# horizontal Infrared Radiation Intensity (W m-2)
self.forc.infra = self.forcIP.infra[self.ceil_time_step]
# wind speed (m s-1)
self.forc.wind = max(self.forcIP.wind[self.ceil_time_step], self.geoParam.windMin)
self.forc.uDir = self.forcIP.uDir[self.ceil_time_step] # wind direction
# specific humidty (kg kg-1)
self.forc.hum = self.forcIP.hum[self.ceil_time_step]
self.forc.pres = self.forcIP.pres[self.ceil_time_step] # Pressure (Pa)
self.forc.temp = self.forcIP.temp[self.ceil_time_step] # air temperature (C)
self.forc.rHum = self.forcIP.rHum[self.ceil_time_step] # Relative humidity (%)
self.forc.prec = self.forcIP.prec[self.ceil_time_step] # Precipitation (mm h-1)
# horizontal solar diffuse radiation (W m-2)
self.forc.dif = self.forcIP.dif[self.ceil_time_step]
# normal solar direct radiation (W m-2)
self.forc.dir = self.forcIP.dir[self.ceil_time_step]
# Canyon humidity (absolute) same as rural
self.UCM.canHum = copy.copy(self.forc.hum)
# Update solar flux
self.solar = SolarCalcs(self.UCM, self.BEM, self.simTime,
self.RSM, self.forc, self.geoParam, self.rural)
self.rural, self.UCM, self.BEM = self.solar.solarcalcs()
# Update building & traffic schedule
# Assign day type (1 = weekday, 2 = sat, 3 = sun/other)
if self.is_near_zero(self.simTime.julian % 7):
self.dayType = 3 # Sunday
elif self.is_near_zero(self.simTime.julian % 7 - 6.):
self.dayType = 2 # Saturday
else:
self.dayType = 1 # Weekday
# Update anthropogenic heat load for each hour (building & UCM)
self.UCM.sensAnthrop = self.sensAnth * (self.SchTraffic[self.dayType-1][self.simTime.hourDay])
# Update the energy components for building types defined in initialize.uwg
for i in range(len(self.BEM)):
# Set temperature
self.BEM[i].building.coolSetpointDay = self.Sch[i].Cool[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for cooling
self.BEM[i].building.coolSetpointNight = self.BEM[i].building.coolSetpointDay
self.BEM[i].building.heatSetpointDay = self.Sch[i].Heat[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for heating
self.BEM[i].building.heatSetpointNight = self.BEM[i].building.heatSetpointDay
# Internal Heat Load Schedule (W/m^2 of floor area for Q)
self.BEM[i].Elec = self.Sch[i].Qelec * self.Sch[i].Elec[self.dayType -
1][self.simTime.hourDay] # Qelec x elec fraction for day
self.BEM[i].Light = self.Sch[i].Qlight * self.Sch[i].Light[self.dayType -
1][self.simTime.hourDay] # Qlight x light fraction for day
self.BEM[i].Nocc = self.Sch[i].Nocc * self.Sch[i].Occ[self.dayType -
1][self.simTime.hourDay] # Number of occupants x occ fraction for day
# Sensible Q occupant * fraction occupant sensible Q * number of occupants
self.BEM[i].Qocc = self.sensOcc * (1 - self.LatFOcc) * self.BEM[i].Nocc
# SWH and ventilation schedule
self.BEM[i].SWH = self.Sch[i].Vswh * self.Sch[i].SWH[self.dayType -
1][self.simTime.hourDay] # litres per hour x SWH fraction for day
# m^3/s/m^2 of floor
self.BEM[i].building.vent = self.Sch[i].Vent
self.BEM[i].Gas = self.Sch[i].Qgas * self.Sch[i].Gas[self.dayType -
1][self.simTime.hourDay] # Gas Equip Schedule, per m^2 of floor
# This is quite messy, should update
# Update internal heat and corresponding fractional loads
intHeat = self.BEM[i].Light + self.BEM[i].Elec + self.BEM[i].Qocc
# W/m2 from light, electricity, occupants
self.BEM[i].building.intHeatDay = intHeat
self.BEM[i].building.intHeatNight = intHeat
# fraction of radiant heat from light and equipment of whole internal heat
self.BEM[i].building.intHeatFRad = (
self.RadFLight * self.BEM[i].Light + self.RadFEquip * self.BEM[i].Elec) / intHeat
# fraction of latent heat (from occupants) of whole internal heat
self.BEM[i].building.intHeatFLat = self.LatFOcc * \
self.sensOcc * self.BEM[i].Nocc/intHeat
# Update envelope temperature layers
self.BEM[i].T_wallex = self.BEM[i].wall.layerTemp[0]
self.BEM[i].T_wallin = self.BEM[i].wall.layerTemp[-1]
self.BEM[i].T_roofex = self.BEM[i].roof.layerTemp[0]
self.BEM[i].T_roofin = self.BEM[i].roof.layerTemp[-1]
# Update rural heat fluxes & update vertical diffusion model (VDM)
self.rural.infra = self.forc.infra - self.rural.emissivity * self.SIGMA * \
self.rural.layerTemp[0]**4. # Infrared radiation from rural road
self.rural.SurfFlux(self.forc, self.geoParam, self.simTime,
self.forc.hum, self.forc.temp, self.forc.wind, 2., 0.)
self.RSM.VDM(self.forc, self.rural, self.geoParam, self.simTime)
# Calculate urban heat fluxes, update UCM & UBL
self.UCM, self.UBL, self.BEM = urbflux(
self.UCM, self.UBL, self.BEM, self.forc, self.geoParam, self.simTime, self.RSM)
self.UCM.UCModel(self.BEM, self.UBL.ublTemp, self.forc, self.geoParam)
self.UBL.UBLModel(self.UCM, self.RSM, self.rural,
self.forc, self.geoParam, self.simTime)
"""
# Experimental code to run diffusion model in the urban area
# N.B Commented out in python uwg because computed wind speed in
# urban VDM: y = =0.84*ln((2-x/20)/0.51) results in negative log
# for building heights >= 40m.
Uroad = copy.copy(self.UCM.road)
Uroad.sens = copy.copy(self.UCM.sensHeat)
Uforc = copy.copy(self.forc)
Uforc.wind = copy.copy(self.UCM.canWind)
Uforc.temp = copy.copy(self.UCM.canTemp)
self.USM.VDM(Uforc,Uroad,self.geoParam,self.simTime)
"""
self.logger.info("dbT = {}".format(self.UCM.canTemp-273.15))
if n > 0:
logging.info("dpT = {}".format(self.UCM.Tdp))
logging.info("RH = {}".format(self.UCM.canRHum))
if self.is_near_zero(self.simTime.secDay % self.simTime.timePrint) and n < self.N:
self.logger.info("{0} ----sim time step = {1}----\n\n".format(__name__, n))
self.WeatherData[n] = copy.copy(self.forc)
_Tdb, _w, self.UCM.canRHum, _h, self.UCM.Tdp, _v = psychrometrics(
self.UCM.canTemp, self.UCM.canHum, self.forc.pres)
self.UBLData[n] = copy.copy(self.UBL)
self.UCMData[n] = copy.copy(self.UCM)
self.RSMData[n] = copy.copy(self.RSM)
self.logger.info("dbT = {}".format(self.UCMData[n].canTemp-273.15))
self.logger.info("dpT = {}".format(self.UCMData[n].Tdp))
self.logger.info("RH = {}".format(self.UCMData[n].canRHum))
n += 1
def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] = column data of epw
self.epwinput[iJ+self.simTime.timeInitial-8][6] = "{0:.{1}f}".format(
self.UCMData[iJ].canTemp - 273.15, epw_prec) # dry bulb temperature [?C]
# dew point temperature [?C]
self.epwinput[iJ+self.simTime.timeInitial -
8][7] = "{0:.{1}f}".format(self.UCMData[iJ].Tdp, epw_prec)
# relative humidity [%]
self.epwinput[iJ+self.simTime.timeInitial -
8][8] = "{0:.{1}f}".format(self.UCMData[iJ].canRHum, epw_prec)
self.epwinput[iJ+self.simTime.timeInitial-8][21] = "{0:.{1}f}".format(
self.WeatherData[iJ].wind, epw_prec) # wind speed [m/s]
# Writing new EPW file
epw_new_id = open(self.newPathName, "w")
for i in range(8):
new_epw_line = '{}\n'.format(reduce(lambda x, y: x+","+y, self._header[i]))
epw_new_id.write(new_epw_line)
for i in range(len(self.epwinput)):
printme = ""
for ei in range(34):
printme += "{}".format(self.epwinput[i][ei]) + ','
printme = printme + "{}".format(self.epwinput[i][ei])
new_epw_line = "{0}\n".format(printme)
epw_new_id.write(new_epw_line)
epw_new_id.close()
print("New climate file '{}' is generated at {}.".format(
self.destinationFileName, self.destinationDir))
def run(self):
# run main class methods
self.read_epw()
self.set_input()
self.init_BEM_obj()
self.init_input_obj()
self.hvac_autosize()
self.simulate()
self.write_epw()
|
ladybug-tools/uwg | uwg/uwg.py | uwg.write_epw | python | def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] = column data of epw
self.epwinput[iJ+self.simTime.timeInitial-8][6] = "{0:.{1}f}".format(
self.UCMData[iJ].canTemp - 273.15, epw_prec) # dry bulb temperature [?C]
# dew point temperature [?C]
self.epwinput[iJ+self.simTime.timeInitial -
8][7] = "{0:.{1}f}".format(self.UCMData[iJ].Tdp, epw_prec)
# relative humidity [%]
self.epwinput[iJ+self.simTime.timeInitial -
8][8] = "{0:.{1}f}".format(self.UCMData[iJ].canRHum, epw_prec)
self.epwinput[iJ+self.simTime.timeInitial-8][21] = "{0:.{1}f}".format(
self.WeatherData[iJ].wind, epw_prec) # wind speed [m/s]
# Writing new EPW file
epw_new_id = open(self.newPathName, "w")
for i in range(8):
new_epw_line = '{}\n'.format(reduce(lambda x, y: x+","+y, self._header[i]))
epw_new_id.write(new_epw_line)
for i in range(len(self.epwinput)):
printme = ""
for ei in range(34):
printme += "{}".format(self.epwinput[i][ei]) + ','
printme = printme + "{}".format(self.epwinput[i][ei])
new_epw_line = "{0}\n".format(printme)
epw_new_id.write(new_epw_line)
epw_new_id.close()
print("New climate file '{}' is generated at {}.".format(
self.destinationFileName, self.destinationDir)) | Section 8 - Writing new EPW file | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/uwg.py#L926-L963 | null | class uwg(object):
"""Morph a rural EPW file to urban conditions using a file with a list of urban parameters.
args:
epwDir: The directory in which the rural EPW file sits.
epwFileName: The name of the rural epw file that will be morphed.
uwgParamDir: The directory in which the uwg Parameter File (.uwg) sits.
uwgParamFileName: The name of the uwg Parameter File (.uwg).
destinationDir: Optional destination directory for the morphed EPW file.
If left blank, the morphed file will be written into the same directory
as the rural EPW file (the epwDir).
destinationFileName: Optional destination file name for the morphed EPW file.
If left blank, the morphed file will append "_UWG" to the original file name.
returns:
newClimateFile: the path to a new EPW file that has been morphed to account
for uban conditions.
"""
""" Section 1 - Definitions for constants / other parameters """
MINTHICKNESS = 0.01 # Minimum layer thickness (to prevent crashing) (m)
MAXTHICKNESS = 0.05 # Maximum layer thickness (m)
# http://web.mit.edu/parmstr/Public/NRCan/nrcc29118.pdf (Figly & Snodgrass)
SOILTCOND = 1
# http://www.europment.org/library/2013/venice/bypaper/MFHEEF/MFHEEF-21.pdf (average taken from Table 1)
SOILVOLHEAT = 2e6
# Soil material used for soil-depth padding
SOIL = Material(SOILTCOND, SOILVOLHEAT, name="soil")
# Physical constants
G = 9.81 # gravity (m s-2)
CP = 1004. # heat capacity for air (J/kg K)
VK = 0.40 # von karman constant (dimensionless)
R = 287. # gas constant dry air (J/kg K)
RV = 461.5 # gas constant water vapor (J/kg K)
LV = 2.26e6 # latent heat of evaporation (J/kg)
SIGMA = 5.67e-08 # Stefan Boltzmann constant (W m-2 K-4)
WATERDENS = 1000. # water density (kg m-3)
LVTT = 2.5008e6 #
TT = 273.16 #
ESTT = 611.14 #
CL = 4.218e3 #
CPV = 1846.1 #
B = 9.4 # Coefficients derived by Louis (1979)
CM = 7.4 #
# (Pr/Sc)^(2/3) for Colburn analogy in water evaporation
COLBURN = math.pow((0.713/0.621), (2/3.))
# Site-specific parameters
WGMAX = 0.005 # maximum film water depth on horizontal surfaces (m)
# File path parameter
RESOURCE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "resources"))
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
def __init__(self, epwFileName, uwgParamFileName=None, epwDir=None, uwgParamDir=None, destinationDir=None, destinationFileName=None):
# Logger will be disabled by default unless explicitly called in tests
self.logger = logging.getLogger(__name__)
# User defined
self.epwFileName = epwFileName if epwFileName.lower().endswith('.epw') else epwFileName + \
'.epw' # Revise epw file name if not end with epw
# If file name is entered then will uwg will set input from .uwg file
self.uwgParamFileName = uwgParamFileName
# If user does not overload
self.destinationFileName = destinationFileName if destinationFileName else self.epwFileName.strip(
'.epw') + '_UWG.epw'
self.epwDir = epwDir if epwDir else os.path.join(self.RESOURCE_PATH, "epw")
self.uwgParamDir = uwgParamDir if uwgParamDir else os.path.join(
self.RESOURCE_PATH, "parameters")
self.destinationDir = destinationDir if destinationDir else os.path.join(
self.RESOURCE_PATH, "epw_uwg")
# refdata: Serialized DOE reference data, z_meso height data
self.readDOE_file_path = os.path.join(self.CURRENT_PATH, "refdata", "readDOE.pkl")
self.z_meso_dir_path = os.path.join(self.CURRENT_PATH, "refdata")
# EPW precision
self.epw_precision = 1
# init uwg variables
self._init_param_dict = None
# Define Simulation and Weather parameters
self.Month = None # starting month (1-12)
self.Day = None # starting day (1-31)
self.nDay = None # number of days
self.dtSim = None # simulation time step (s)
self.dtWeather = None # seconds (s)
# HVAC system and internal laod
self.autosize = None # autosize HVAC (1 or 0)
self.sensOcc = None # Sensible heat from occupant
self.LatFOcc = None # Latent heat fraction from occupant (normally 0.3)
self.RadFOcc = None # Radiant heat fraction from occupant (normally 0.2)
self.RadFEquip = None # Radiant heat fraction from equipment (normally 0.5)
self.RadFLight = None # Radiant heat fraction from light (normally 0.7)
# Define Urban microclimate parameters
self.h_ubl1 = None # ubl height - day (m)
self.h_ubl2 = None # ubl height - night (m)
self.h_ref = None # inversion height
self.h_temp = None # temperature height
self.h_wind = None # wind height
self.c_circ = None # circulation coefficient
self.c_exch = None # exchange coefficient
self.maxDay = None # max day threshhold
self.maxNight = None # max night threshhold
self.windMin = None # min wind speed (m/s)
self.h_obs = None # rural average obstacle height
# Urban characteristics
self.bldHeight = None # average building height (m)
self.h_mix = None # mixing height (m)
self.bldDensity = None # building density (0-1)
self.verToHor = None # building aspect ratio
# radius defining the urban area of study [aka. characteristic length] (m)
self.charLength = None
self.alb_road = None # road albedo
self.d_road = None # road pavement thickness
self.sensAnth = None # non-building sensible heat (W/m^2)
self.latAnth = None # non-building latent heat heat (W/m^2). Not used, taken out by JH.
# Fraction of building typology stock
self.bld = None # 16x3 matrix of fraction of building type by era
# climate Zone
self.zone = None
# Vegetation parameters
self.vegCover = None # urban area veg coverage ratio
self.treeCoverage = None # urban area tree coverage ratio
self.vegStart = None # vegetation start month
self.vegEnd = None # vegetation end month
self.albVeg = None # Vegetation albedo
self.rurVegCover = None # rural vegetation cover
self.latGrss = None # latent fraction of grass
self.latTree = None # latent fraction of tree
# Define Traffic schedule
self.SchTraffic = None
# Define Road (Assume 0.5m of asphalt)
self.kRoad = None # road pavement conductivity (W/m K)
self.cRoad = None # road volumetric heat capacity (J/m^3 K)
# Define optional Building characteristics
self.flr_h = None # floor-to-floor height
self.albRoof = None # roof albedo (0 - 1)
self.vegRoof = None # Fraction of the roofs covered in grass/shrubs (0-1)
self.glzR = None # Glazing Ratio
self.SHGC = None # Solar Heat Gain Coefficient
self.albWall = None # Wall albedo
def ToString(self):
"""Overwrite .NET ToString method."""
return self.__repr__()
def __repr__(self):
def _split_string(s):
return s[0] + ":\n " + s[1].replace(",", "\n ")
def _tabbed(s):
return _split_string(s.__repr__().split(":"))
def _list_2_tabbed(b):
return reduce(lambda a, b: a+"\n"+b, [_tabbed(_b) for _b in b])
return "uwg for {}:\n\n{}{}{}{}{}{}{}{}".format(
self.epwFileName,
_tabbed(self.simTime)+"\n" if hasattr(self, "simTime") else "No simTime attr.\n",
_tabbed(self.weather)+"\n" if hasattr(self, "weather") else "No weather attr.\n",
_tabbed(self.geoParam)+"\n" if hasattr(self, "geoParam") else "No geoParam attr.\n",
_tabbed(self.UBL)+"\n" if hasattr(self, "UBL") else "No UBL attr.\n",
"Rural "+_tabbed(self.RSM)+"\n" if hasattr(self, "RSM") else "No Rural RSM attr.\n",
"Urban "+_tabbed(self.USM)+"\n" if hasattr(self, "USM") else "No Urban RSM attr.\n",
_tabbed(self.UCM)+"\n" if hasattr(self, "UCM") else "No UCM attr.\n",
_list_2_tabbed(self.BEM) if hasattr(self, "BEM") else "No BEM attr."
)
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def read_epw(self):
"""Section 2 - Read EPW file
properties:
self.climateDataPath
self.newPathName
self._header # header data
self.epwinput # timestep data for weather
self.lat # latitude
self.lon # longitude
self.GMT # GMT
self.nSoil # Number of soil depths
self.Tsoil # nSoil x 12 matrix for soil temperture (K)
self.depth_soil # nSoil x 1 matrix for soil depth (m)
"""
# Make dir path to epw file
self.climateDataPath = os.path.join(self.epwDir, self.epwFileName)
# Open epw file and feed csv data to climate_data
try:
climate_data = utilities.read_csv(self.climateDataPath)
except Exception as e:
raise Exception("Failed to read epw file! {}".format(e.message))
# Read header lines (1 to 8) from EPW and ensure TMY2 format.
self._header = climate_data[0:8]
# Read weather data from EPW for each time step in weather file. (lines 8 - end)
self.epwinput = climate_data[8:]
# Read Lat, Long (line 1 of EPW)
self.lat = float(self._header[0][6])
self.lon = float(self._header[0][7])
self.GMT = float(self._header[0][8])
# Read in soil temperature data (assumes this is always there)
# ref: http://bigladdersoftware.com/epx/docs/8-2/auxiliary-programs/epw-csv-format-inout.html
soilData = self._header[3]
self.nSoil = int(soilData[1]) # Number of ground temperature depths
self.Tsoil = utilities.zeros(self.nSoil, 12) # nSoil x 12 matrix for soil temperture (K)
self.depth_soil = utilities.zeros(self.nSoil, 1) # nSoil x 1 matrix for soil depth (m)
# Read monthly data for each layer of soil from EPW file
for i in range(self.nSoil):
self.depth_soil[i][0] = float(soilData[2 + (i*16)]) # get soil depth for each nSoil
# Monthly data
for j in range(12):
# 12 months of soil T for specific depth
self.Tsoil[i][j] = float(soilData[6 + (i*16) + j]) + 273.15
# Set new directory path for the moprhed EPW file
self.newPathName = os.path.join(self.destinationDir, self.destinationFileName)
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^2)
self.SchTraffic # Traffice schedule
self.BEM # list of BEMDef objects extracted from readDOE
self.Sch # list of Schedule objects extracted from readDOE
"""
uwg_param_file_path = os.path.join(self.uwgParamDir, self.uwgParamFileName)
if not os.path.exists(uwg_param_file_path):
raise Exception("Param file: '{}' does not exist.".format(uwg_param_file_path))
# Open .uwg file and feed csv data to initializeDataFile
try:
uwg_param_data = utilities.read_csv(uwg_param_file_path)
except Exception as e:
raise Exception("Failed to read .uwg file! {}".format(e.message))
# The initialize.uwg is read with a dictionary so that users changing
# line endings or line numbers doesn't make reading input incorrect
self._init_param_dict = {}
count = 0
while count < len(uwg_param_data):
row = uwg_param_data[count]
row = [row[i].replace(" ", "") for i in range(len(row))] # strip white spaces
# Optional parameters might be empty so handle separately
is_optional_parameter = (
row != [] and
(
row[0] == "albRoof" or
row[0] == "vegRoof" or
row[0] == "glzR" or
row[0] == "hvac" or
row[0] == "albWall" or
row[0] == "SHGC"
)
)
try:
if row == [] or "#" in row[0]:
count += 1
continue
elif row[0] == "SchTraffic":
# SchTraffic: 3 x 24 matrix
trafficrows = uwg_param_data[count+1:count+4]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:24]) for r in trafficrows]
count += 4
elif row[0] == "bld":
# bld: 17 x 3 matrix
bldrows = uwg_param_data[count+1:count+17]
self._init_param_dict[row[0]] = [utilities.str2fl(r[:3]) for r in bldrows]
count += 17
elif is_optional_parameter:
self._init_param_dict[row[0]] = float(row[1]) if row[1] != "" else None
count += 1
else:
self._init_param_dict[row[0]] = float(row[1])
count += 1
except ValueError:
print("Error while reading parameter at {} {}".format(count, row))
ipd = self._init_param_dict
# Define Simulation and Weather parameters
if self.Month is None: self.Month = ipd['Month']
if self.Day is None: self.Day = ipd['Day']
if self.nDay is None: self.nDay = ipd['nDay']
if self.dtSim is None: self.dtSim = ipd['dtSim']
if self.dtWeather is None: self.dtWeather = ipd['dtWeather']
# HVAC system and internal laod
if self.autosize is None: self.autosize = ipd['autosize']
if self.sensOcc is None: self.sensOcc = ipd['sensOcc']
if self.LatFOcc is None: self.LatFOcc = ipd['LatFOcc']
if self.RadFOcc is None: self.RadFOcc = ipd['RadFOcc']
if self.RadFEquip is None: self.RadFEquip = ipd['RadFEquip']
if self.RadFLight is None: self.RadFLight = ipd['RadFLight']
# Define Urban microclimate parameters
if self.h_ubl1 is None: self.h_ubl1 = ipd['h_ubl1']
if self.h_ubl2 is None: self.h_ubl2 = ipd['h_ubl2']
if self.h_ref is None: self.h_ref = ipd['h_ref']
if self.h_temp is None: self.h_temp = ipd['h_temp']
if self.h_wind is None: self.h_wind = ipd['h_wind']
if self.c_circ is None: self.c_circ = ipd['c_circ']
if self.c_exch is None: self.c_exch = ipd['c_exch']
if self.maxDay is None: self.maxDay = ipd['maxDay']
if self.maxNight is None: self.maxNight = ipd['maxNight']
if self.windMin is None: self.windMin = ipd['windMin']
if self.h_obs is None: self.h_obs = ipd['h_obs']
# Urban characteristics
if self.bldHeight is None: self.bldHeight = ipd['bldHeight']
if self.h_mix is None: self.h_mix = ipd['h_mix']
if self.bldDensity is None: self.bldDensity = ipd['bldDensity']
if self.verToHor is None: self.verToHor = ipd['verToHor']
if self.charLength is None: self.charLength = ipd['charLength']
if self.alb_road is None: self.alb_road = ipd['albRoad']
if self.d_road is None: self.d_road = ipd['dRoad']
if self.sensAnth is None: self.sensAnth = ipd['sensAnth']
# if self.latAnth is None: self.latAnth = ipd['latAnth'] # Not used, taken out by JH.
# climate Zone
if self.zone is None: self.zone = ipd['zone']
# Vegetation parameters
if self.vegCover is None: self.vegCover = ipd['vegCover']
if self.treeCoverage is None: self.treeCoverage = ipd['treeCoverage']
if self.vegStart is None: self.vegStart = ipd['vegStart']
if self.vegEnd is None: self.vegEnd = ipd['vegEnd']
if self.albVeg is None: self.albVeg = ipd['albVeg']
if self.rurVegCover is None: self.rurVegCover = ipd['rurVegCover']
if self.latGrss is None: self.latGrss = ipd['latGrss']
if self.latTree is None: self.latTree = ipd['latTree']
# Define Traffic schedule
if self.SchTraffic is None: self.SchTraffic = ipd['SchTraffic']
# Define Road (Assume 0.5m of asphalt)
if self.kRoad is None: self.kRoad = ipd['kRoad']
if self.cRoad is None: self.cRoad = ipd['cRoad']
# Building stock fraction
if self.bld is None: self.bld = ipd['bld']
# Optional parameters
if self.albRoof is None: self.albRoof = ipd['albRoof']
if self.vegRoof is None: self.vegRoof = ipd['vegRoof']
if self.glzR is None: self.glzR = ipd['glzR']
if self.albWall is None: self.albWall = ipd['albWall']
if self.SHGC is None: self.SHGC = ipd['SHGC']
def check_required_inputs(self):
# Fail if required parameters aren't correct
assert isinstance(self.Month, (float, int)), \
'Month must be a number. Got {}'.format(type(self.Month))
assert isinstance(self.Day, (float, int)), \
'Day must be a number. Got {}'.format(type(self.Day))
assert isinstance(self.nDay, (float, int)), \
'nDay must be a number. Got {}'.format(type(self.nDay))
assert isinstance(self.dtSim, float), \
'dtSim must be a float. Got {}'.format(type(self.dtSim))
assert isinstance(self.dtWeather, float), \
'dtWeather must be a float. Got {}'.format(type(self.dtWeather))
assert isinstance(self.autosize, (float, int)), \
'autosize must be a number. Got {}'.format(type(self.autosize))
assert isinstance(self.sensOcc, float), \
'sensOcc must be a float. Got {}'.format(type(self.sensOcc))
assert isinstance(self.LatFOcc, float), \
'LatFOcc must be a float. Got {}'.format(type(self.LatFOcc))
assert isinstance(self.RadFOcc, float), \
'RadFOcc must be a float. Got {}'.format(type(self.RadFOcc))
assert isinstance(self.RadFEquip, float), \
'RadFEquip must be a float. Got {}'.format(type(self.RadFEquip))
assert isinstance(self.RadFLight, float), \
'RadFLight must be a float. Got {}'.format(type(self.RadFLight))
assert isinstance(self.h_ubl1, float), \
'h_ubl1 must be a float. Got {}'.format(type(self.h_ubl1))
assert isinstance(self.h_ubl2, float), \
'h_ubl2 must be a float. Got {}'.format(type(self.h_ubl2))
assert isinstance(self.h_ref, float), \
'h_ref must be a float. Got {}'.format(type(self.h_ref))
assert isinstance(self.h_temp, float), \
'h_temp must be a float. Got {}'.format(type(self.h_temp))
assert isinstance(self.h_wind, float), \
'h_wind must be a float. Got {}'.format(type(self.h_wind))
assert isinstance(self.c_circ, float), \
'c_circ must be a float. Got {}'.format(type(self.c_circ))
assert isinstance(self.c_exch, float), \
'c_exch must be a float. Got {}'.format(type(self.c_exch))
assert isinstance(self.maxDay, float), \
'maxDay must be a float. Got {}'.format(type(self.maxDay))
assert isinstance(self.maxNight, float), \
'maxNight must be a float. Got {}'.format(type(self.maxNight))
assert isinstance(self.windMin, float), \
'windMin must be a float. Got {}'.format(type(self.windMin))
assert isinstance(self.h_obs, float), \
'h_obs must be a float. Got {}'.format(type(self.h_obs))
assert isinstance(self.bldHeight, float), \
'bldHeight must be a float. Got {}'.format(type(self.bldHeight))
assert isinstance(self.h_mix, float), \
'h_mix must be a float. Got {}'.format(type(self.h_mix))
assert isinstance(self.bldDensity, float), \
'bldDensity must be a float. Got {}'.format(type(self.bldDensity))
assert isinstance(self.verToHor, float), \
'verToHor must be a float. Got {}'.format(type(self.verToHor))
assert isinstance(self.charLength, float), \
'charLength must be a float. Got {}'.format(type(self.charLength))
assert isinstance(self.alb_road, float), \
'alb_road must be a float. Got {}'.format(type(self.alb_road))
assert isinstance(self.d_road, float), \
'd_road must be a float. Got {}'.format(type(self.d_road))
assert isinstance(self.sensAnth, float), \
'sensAnth must be a float. Got {}'.format(type(self.sensAnth))
# assert isinstance(self.latAnth, float) # Take this out as isn't being used
assert isinstance(self.bld, list), \
'bld must be a list. Got {}'.format(type(self.bld))
assert len(self.bld) == 16, \
'length of bld must be 16. Got {}'.format(len(self.bld))
assert isinstance(self.latTree, float), \
'latTree must be a float. Got {}'.format(type(self.latTree))
assert isinstance(self.latGrss, float), \
'latGrss must be a float. Got {}'.format(type(self.latGrss))
assert isinstance(self.zone, (float, int)), \
'zone must be a number. Got {}'.format(type(self.zone))
assert isinstance(self.vegStart, (float, int)), \
'vegStart must be a number. Got {}'.format(type(self.vegStart))
assert isinstance(self.vegEnd, (float, int)), \
'vegEnd must be a number. Got {}'.format(type(self.vegEnd))
assert isinstance(self.vegCover, float), \
'vegCover must be a float. Got {}'.format(type(self.vegCover))
assert isinstance(self.treeCoverage, float), \
'treeCoverage must be a float. Got {}'.format(type(self.treeCoverage))
assert isinstance(self.albVeg, float), \
'albVeg must be a float. Got {}'.format(type(self.albVeg))
assert isinstance(self.rurVegCover, float), \
'rurVegCover must be a float. Got {}'.format(type(self.rurVegCover))
assert isinstance(self.kRoad, float), \
'kRoad must be a float. Got {}'.format(type(self.kRoad))
assert isinstance(self.cRoad, float), \
'cRoad must be a float. Got {}'.format(type(self.cRoad))
assert isinstance(self.SchTraffic, list), \
'SchTraffic must be a list. Got {}'.format(type(self.SchTraffic))
assert len(self.SchTraffic) == 3, \
'length of SchTraffic must be 3. Got {}'.format(len(self.SchTraffic))
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the .uwg file.
if self.uwgParamFileName is not None:
print("\nReading uwg file input.")
self.read_input()
else:
print("\nNo .uwg file input.")
self.check_required_inputs()
# Modify zone to be used as python index
self.zone = int(self.zone)-1
def init_BEM_obj(self):
"""
Define BEM for each DOE type (read the fraction)
self.BEM # list of BEMDef objects
self.r_glaze # Glazing ratio for total building stock
self.SHGC # SHGC addition for total building stock
self.alb_wall # albedo wall addition for total building stock
"""
if not os.path.exists(self.readDOE_file_path):
raise Exception("readDOE.pkl file: '{}' does not exist.".format(readDOE_file_path))
readDOE_file = open(self.readDOE_file_path, 'rb') # open pickle file in binary form
refDOE = pickle.load(readDOE_file)
refBEM = pickle.load(readDOE_file)
refSchedule = pickle.load(readDOE_file)
readDOE_file.close()
# Define building energy models
k = 0
self.r_glaze_total = 0. # Glazing ratio for total building stock
self.SHGC_total = 0. # SHGC addition for total building stock
self.alb_wall_total = 0. # albedo wall addition for total building stock
h_floor = self.flr_h or 3.05 # average floor height
total_urban_bld_area = math.pow(self.charLength, 2)*self.bldDensity * \
self.bldHeight/h_floor # total building floor area
area_matrix = utilities.zeros(16, 3)
self.BEM = [] # list of BEMDef objects
self.Sch = [] # list of Schedule objects
for i in range(16): # 16 building types
for j in range(3): # 3 built eras
if self.bld[i][j] > 0.:
# Add to BEM list
self.BEM.append(refBEM[i][j][self.zone])
self.BEM[k].frac = self.bld[i][j]
self.BEM[k].fl_area = self.bld[i][j] * total_urban_bld_area
# Overwrite with optional parameters if provided
if self.glzR:
self.BEM[k].building.glazingRatio = self.glzR
if self.albRoof:
self.BEM[k].roof.albedo = self.albRoof
if self.vegRoof:
self.BEM[k].roof.vegCoverage = self.vegRoof
if self.SHGC:
self.BEM[k].building.shgc = self.SHGC
if self.albWall:
self.BEM[k].wall.albedo = self.albWall
if self.flr_h:
self.BEM[k].building.floorHeight = self.flr_h
# Keep track of total urban r_glaze, SHGC, and alb_wall for UCM model
self.r_glaze_total += self.BEM[k].frac * self.BEM[k].building.glazingRatio
self.SHGC_total += self.BEM[k].frac * self.BEM[k].building.shgc
self.alb_wall_total += self.BEM[k].frac * self.BEM[k].wall.albedo
# Add to schedule list
self.Sch.append(refSchedule[i][j][self.zone])
k += 1
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
self.geoParam # geographic parameters obj
self.RSM # Rural site & vertical diffusion model obj
self.USM # Urban site & vertical diffusion model obj
self.UCM # Urban canopy model obj
self.UBL # Urban boundary layer model
self.road # urban road element
self.rural # rural road element
self.soilindex1 # soil index for urban rsoad depth
self.soilindex2 # soil index for rural road depth
self.Sch # list of Schedule objects
"""
climate_file_path = os.path.join(self.epwDir, self.epwFileName)
self.simTime = SimParam(self.dtSim, self.dtWeather, self.Month,
self.Day, self.nDay) # simulation time parametrs
# weather file data for simulation time period
self.weather = Weather(climate_file_path, self.simTime.timeInitial, self.simTime.timeFinal)
self.forcIP = Forcing(self.weather.staTemp, self.weather) # initialized Forcing class
self.forc = Forcing() # empty forcing class
# Initialize geographic Param and Urban Boundary Layer Objects
nightStart = 18. # arbitrary values for begin/end hour for night setpoint
nightEnd = 8.
maxdx = 250. # max dx (m)
self.geoParam = Param(self.h_ubl1, self.h_ubl2, self.h_ref, self.h_temp, self.h_wind, self.c_circ,
self.maxDay, self.maxNight, self.latTree, self.latGrss, self.albVeg, self.vegStart, self.vegEnd,
nightStart, nightEnd, self.windMin, self.WGMAX, self.c_exch, maxdx, self.G, self.CP, self.VK, self.R,
self.RV, self.LV, math.pi, self.SIGMA, self.WATERDENS, self.LVTT, self.TT, self.ESTT, self.CL,
self.CPV, self.B, self.CM, self.COLBURN)
self.UBL = UBLDef(
'C', self.charLength, self.weather.staTemp[0], maxdx, self.geoParam.dayBLHeight, self.geoParam.nightBLHeight)
# Defining road
emis = 0.93
asphalt = Material(self.kRoad, self.cRoad, 'asphalt')
road_T_init = 293.
road_horizontal = 1
# fraction of surface vegetation coverage
road_veg_coverage = min(self.vegCover/(1-self.bldDensity), 1.)
# define road layers
road_layer_num = int(math.ceil(self.d_road/0.05))
# 0.5/0.05 ~ 10 x 1 matrix of 0.05 thickness
thickness_vector = [0.05 for r in range(road_layer_num)]
material_vector = [asphalt for r in range(road_layer_num)]
self.road = Element(self.alb_road, emis, thickness_vector, material_vector, road_veg_coverage,
road_T_init, road_horizontal, name="urban_road")
self.rural = copy.deepcopy(self.road)
self.rural.vegCoverage = self.rurVegCover
self.rural._name = "rural_road"
# Reference site class (also include VDM)
self.RSM = RSMDef(self.lat, self.lon, self.GMT, self.h_obs,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
self.USM = RSMDef(self.lat, self.lon, self.GMT, self.bldHeight/10.,
self.weather.staTemp[0], self.weather.staPres[0], self.geoParam, self.z_meso_dir_path)
T_init = self.weather.staTemp[0]
H_init = self.weather.staHum[0]
self.UCM = UCMDef(self.bldHeight, self.bldDensity, self.verToHor, self.treeCoverage, self.sensAnth, self.latAnth, T_init, H_init,
self.weather.staUmod[0], self.geoParam, self.r_glaze_total, self.SHGC_total, self.alb_wall_total, self.road)
self.UCM.h_mix = self.h_mix
# Define Road Element & buffer to match ground temperature depth
roadMat, newthickness = procMat(self.road, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
roadMat.append(self.SOIL)
self.soilindex1 = i
break
self.road = Element(self.road.albedo, self.road.emissivity, newthickness, roadMat,
self.road.vegCoverage, self.road.layerTemp[0], self.road.horizontal, self.road._name)
# Define Rural Element
ruralMat, newthickness = procMat(self.rural, self.MAXTHICKNESS, self.MINTHICKNESS)
for i in range(self.nSoil):
# if soil depth is greater then the thickness of the road
# we add new slices of soil at max thickness until road is greater or equal
is_soildepth_equal = self.is_near_zero(self.depth_soil[i][0] - sum(newthickness), 1e-15)
if is_soildepth_equal or (self.depth_soil[i][0] > sum(newthickness)):
while self.depth_soil[i][0] > sum(newthickness):
newthickness.append(self.MAXTHICKNESS)
ruralMat.append(self.SOIL)
self.soilindex2 = i
break
self.rural = Element(self.rural.albedo, self.rural.emissivity, newthickness,
ruralMat, self.rural.vegCoverage, self.rural.layerTemp[0], self.rural.horizontal, self.rural._name)
def hvac_autosize(self):
""" Section 6 - HVAC Autosizing (unlimited cooling & heating) """
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999.
def simulate(self):
""" Section 7 - uwg main section
self.N # Total hours in simulation
self.ph # per hour
self.dayType # 3=Sun, 2=Sat, 1=Weekday
self.ceil_time_step # simulation timestep (dt) fitted to weather file timestep
# Output of object instance vector
self.WeatherData # Nx1 vector of forc instance
self.UCMData # Nx1 vector of UCM instance
self.UBLData # Nx1 vector of UBL instance
self.RSMData # Nx1 vector of RSM instance
self.USMData # Nx1 vector of USM instance
"""
self.N = int(self.simTime.days * 24) # total number of hours in simulation
n = 0 # weather time step counter
self.ph = self.simTime.dt/3600. # dt (simulation time step) in hours
# Data dump variables
time = range(self.N)
self.WeatherData = [None for x in range(self.N)]
self.UCMData = [None for x in range(self.N)]
self.UBLData = [None for x in range(self.N)]
self.RSMData = [None for x in range(self.N)]
self.USMData = [None for x in range(self.N)]
print('\nSimulating new temperature and humidity values for {} days from {}/{}.\n'.format(
int(self.nDay), int(self.Month), int(self.Day)))
self.logger.info("Start simulation")
for it in range(1, self.simTime.nt, 1): # for every simulation time-step (i.e 5 min) defined by uwg
# Update water temperature (estimated)
if self.nSoil < 3: # correction to original matlab code
# for BUBBLE/CAPITOUL/Singapore only
self.forc.deepTemp = sum(self.forcIP.temp)/float(len(self.forcIP.temp))
self.forc.waterTemp = sum(
self.forcIP.temp)/float(len(self.forcIP.temp)) - 10. # for BUBBLE/CAPITOUL/Singapore only
else:
# soil temperature by depth, by month
self.forc.deepTemp = self.Tsoil[self.soilindex1][self.simTime.month-1]
self.forc.waterTemp = self.Tsoil[2][self.simTime.month-1]
# There's probably a better way to update the weather...
self.simTime.UpdateDate()
self.logger.info("\n{0} m={1}, d={2}, h={3}, s={4}".format(
__name__, self.simTime.month, self.simTime.day, self.simTime.secDay/3600., self.simTime.secDay))
# simulation time increment raised to weather time step
self.ceil_time_step = int(math.ceil(it * self.ph))-1
# minus one to be consistent with forcIP list index
# Updating forcing instance
# horizontal Infrared Radiation Intensity (W m-2)
self.forc.infra = self.forcIP.infra[self.ceil_time_step]
# wind speed (m s-1)
self.forc.wind = max(self.forcIP.wind[self.ceil_time_step], self.geoParam.windMin)
self.forc.uDir = self.forcIP.uDir[self.ceil_time_step] # wind direction
# specific humidty (kg kg-1)
self.forc.hum = self.forcIP.hum[self.ceil_time_step]
self.forc.pres = self.forcIP.pres[self.ceil_time_step] # Pressure (Pa)
self.forc.temp = self.forcIP.temp[self.ceil_time_step] # air temperature (C)
self.forc.rHum = self.forcIP.rHum[self.ceil_time_step] # Relative humidity (%)
self.forc.prec = self.forcIP.prec[self.ceil_time_step] # Precipitation (mm h-1)
# horizontal solar diffuse radiation (W m-2)
self.forc.dif = self.forcIP.dif[self.ceil_time_step]
# normal solar direct radiation (W m-2)
self.forc.dir = self.forcIP.dir[self.ceil_time_step]
# Canyon humidity (absolute) same as rural
self.UCM.canHum = copy.copy(self.forc.hum)
# Update solar flux
self.solar = SolarCalcs(self.UCM, self.BEM, self.simTime,
self.RSM, self.forc, self.geoParam, self.rural)
self.rural, self.UCM, self.BEM = self.solar.solarcalcs()
# Update building & traffic schedule
# Assign day type (1 = weekday, 2 = sat, 3 = sun/other)
if self.is_near_zero(self.simTime.julian % 7):
self.dayType = 3 # Sunday
elif self.is_near_zero(self.simTime.julian % 7 - 6.):
self.dayType = 2 # Saturday
else:
self.dayType = 1 # Weekday
# Update anthropogenic heat load for each hour (building & UCM)
self.UCM.sensAnthrop = self.sensAnth * (self.SchTraffic[self.dayType-1][self.simTime.hourDay])
# Update the energy components for building types defined in initialize.uwg
for i in range(len(self.BEM)):
# Set temperature
self.BEM[i].building.coolSetpointDay = self.Sch[i].Cool[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for cooling
self.BEM[i].building.coolSetpointNight = self.BEM[i].building.coolSetpointDay
self.BEM[i].building.heatSetpointDay = self.Sch[i].Heat[self.dayType -
1][self.simTime.hourDay] + 273.15 # add from temperature schedule for heating
self.BEM[i].building.heatSetpointNight = self.BEM[i].building.heatSetpointDay
# Internal Heat Load Schedule (W/m^2 of floor area for Q)
self.BEM[i].Elec = self.Sch[i].Qelec * self.Sch[i].Elec[self.dayType -
1][self.simTime.hourDay] # Qelec x elec fraction for day
self.BEM[i].Light = self.Sch[i].Qlight * self.Sch[i].Light[self.dayType -
1][self.simTime.hourDay] # Qlight x light fraction for day
self.BEM[i].Nocc = self.Sch[i].Nocc * self.Sch[i].Occ[self.dayType -
1][self.simTime.hourDay] # Number of occupants x occ fraction for day
# Sensible Q occupant * fraction occupant sensible Q * number of occupants
self.BEM[i].Qocc = self.sensOcc * (1 - self.LatFOcc) * self.BEM[i].Nocc
# SWH and ventilation schedule
self.BEM[i].SWH = self.Sch[i].Vswh * self.Sch[i].SWH[self.dayType -
1][self.simTime.hourDay] # litres per hour x SWH fraction for day
# m^3/s/m^2 of floor
self.BEM[i].building.vent = self.Sch[i].Vent
self.BEM[i].Gas = self.Sch[i].Qgas * self.Sch[i].Gas[self.dayType -
1][self.simTime.hourDay] # Gas Equip Schedule, per m^2 of floor
# This is quite messy, should update
# Update internal heat and corresponding fractional loads
intHeat = self.BEM[i].Light + self.BEM[i].Elec + self.BEM[i].Qocc
# W/m2 from light, electricity, occupants
self.BEM[i].building.intHeatDay = intHeat
self.BEM[i].building.intHeatNight = intHeat
# fraction of radiant heat from light and equipment of whole internal heat
self.BEM[i].building.intHeatFRad = (
self.RadFLight * self.BEM[i].Light + self.RadFEquip * self.BEM[i].Elec) / intHeat
# fraction of latent heat (from occupants) of whole internal heat
self.BEM[i].building.intHeatFLat = self.LatFOcc * \
self.sensOcc * self.BEM[i].Nocc/intHeat
# Update envelope temperature layers
self.BEM[i].T_wallex = self.BEM[i].wall.layerTemp[0]
self.BEM[i].T_wallin = self.BEM[i].wall.layerTemp[-1]
self.BEM[i].T_roofex = self.BEM[i].roof.layerTemp[0]
self.BEM[i].T_roofin = self.BEM[i].roof.layerTemp[-1]
# Update rural heat fluxes & update vertical diffusion model (VDM)
self.rural.infra = self.forc.infra - self.rural.emissivity * self.SIGMA * \
self.rural.layerTemp[0]**4. # Infrared radiation from rural road
self.rural.SurfFlux(self.forc, self.geoParam, self.simTime,
self.forc.hum, self.forc.temp, self.forc.wind, 2., 0.)
self.RSM.VDM(self.forc, self.rural, self.geoParam, self.simTime)
# Calculate urban heat fluxes, update UCM & UBL
self.UCM, self.UBL, self.BEM = urbflux(
self.UCM, self.UBL, self.BEM, self.forc, self.geoParam, self.simTime, self.RSM)
self.UCM.UCModel(self.BEM, self.UBL.ublTemp, self.forc, self.geoParam)
self.UBL.UBLModel(self.UCM, self.RSM, self.rural,
self.forc, self.geoParam, self.simTime)
"""
# Experimental code to run diffusion model in the urban area
# N.B Commented out in python uwg because computed wind speed in
# urban VDM: y = =0.84*ln((2-x/20)/0.51) results in negative log
# for building heights >= 40m.
Uroad = copy.copy(self.UCM.road)
Uroad.sens = copy.copy(self.UCM.sensHeat)
Uforc = copy.copy(self.forc)
Uforc.wind = copy.copy(self.UCM.canWind)
Uforc.temp = copy.copy(self.UCM.canTemp)
self.USM.VDM(Uforc,Uroad,self.geoParam,self.simTime)
"""
self.logger.info("dbT = {}".format(self.UCM.canTemp-273.15))
if n > 0:
logging.info("dpT = {}".format(self.UCM.Tdp))
logging.info("RH = {}".format(self.UCM.canRHum))
if self.is_near_zero(self.simTime.secDay % self.simTime.timePrint) and n < self.N:
self.logger.info("{0} ----sim time step = {1}----\n\n".format(__name__, n))
self.WeatherData[n] = copy.copy(self.forc)
_Tdb, _w, self.UCM.canRHum, _h, self.UCM.Tdp, _v = psychrometrics(
self.UCM.canTemp, self.UCM.canHum, self.forc.pres)
self.UBLData[n] = copy.copy(self.UBL)
self.UCMData[n] = copy.copy(self.UCM)
self.RSMData[n] = copy.copy(self.RSM)
self.logger.info("dbT = {}".format(self.UCMData[n].canTemp-273.15))
self.logger.info("dpT = {}".format(self.UCMData[n].Tdp))
self.logger.info("RH = {}".format(self.UCMData[n].canRHum))
n += 1
def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] = column data of epw
self.epwinput[iJ+self.simTime.timeInitial-8][6] = "{0:.{1}f}".format(
self.UCMData[iJ].canTemp - 273.15, epw_prec) # dry bulb temperature [?C]
# dew point temperature [?C]
self.epwinput[iJ+self.simTime.timeInitial -
8][7] = "{0:.{1}f}".format(self.UCMData[iJ].Tdp, epw_prec)
# relative humidity [%]
self.epwinput[iJ+self.simTime.timeInitial -
8][8] = "{0:.{1}f}".format(self.UCMData[iJ].canRHum, epw_prec)
self.epwinput[iJ+self.simTime.timeInitial-8][21] = "{0:.{1}f}".format(
self.WeatherData[iJ].wind, epw_prec) # wind speed [m/s]
# Writing new EPW file
epw_new_id = open(self.newPathName, "w")
for i in range(8):
new_epw_line = '{}\n'.format(reduce(lambda x, y: x+","+y, self._header[i]))
epw_new_id.write(new_epw_line)
for i in range(len(self.epwinput)):
printme = ""
for ei in range(34):
printme += "{}".format(self.epwinput[i][ei]) + ','
printme = printme + "{}".format(self.epwinput[i][ei])
new_epw_line = "{0}\n".format(printme)
epw_new_id.write(new_epw_line)
epw_new_id.close()
print("New climate file '{}' is generated at {}.".format(
self.destinationFileName, self.destinationDir))
def run(self):
# run main class methods
self.read_epw()
self.set_input()
self.init_BEM_obj()
self.init_input_obj()
self.hvac_autosize()
self.simulate()
self.write_epw()
|
ladybug-tools/uwg | uwg/element.py | Element.SurfFlux | python | def SurfFlux(self,forc,parameter,simTime,humRef,tempRef,windRef,boundCond,intFlux):
# Calculated per unit area (m^2)
dens = forc.pres/(1000*0.287042*tempRef*(1.+1.607858*humRef)) # air density (kgd m-3)
self.aeroCond = 5.8 + 3.7 * windRef # Convection coef (ref: uwg, eq. 12))
if (self.horizontal): # For roof, mass, road
# Evaporation (m s-1), Film water & soil latent heat
if not self.is_near_zero(self.waterStorage) and self.waterStorage > 0.0:
# N.B In the current uwg code, latent heat from evapotranspiration, stagnant water,
# or anthropogenic sources is not modelled due to the difficulty of validation, and
# lack of reliability of precipitation data from EPW files.Therefore this condition
# is never run because all elements have had their waterStorage hardcoded to 0.
qtsat = self.qsat([self.layerTemp[0]],[forc.pres],parameter)[0]
eg = self.aeroCond*parameter.colburn*dens*(qtsat-humRef)/parameter.waterDens/parameter.cp
self.waterStorage = min(self.waterStorage + simTime.dt*(forc.prec-eg),parameter.wgmax)
self.waterStorage = max(self.waterStorage,0.) # (m)
else:
eg = 0.
soilLat = eg*parameter.waterDens*parameter.lv
# Winter, no veg
if simTime.month < parameter.vegStart and simTime.month > parameter.vegEnd:
self.solAbs = (1.-self.albedo)*self.solRec # (W m-2)
vegLat = 0.
vegSens = 0.
else: # Summer, veg
self.solAbs = ((1.-self.vegCoverage)*(1.-self.albedo)+self.vegCoverage*(1.-parameter.vegAlbedo))*self.solRec
vegLat = self.vegCoverage*parameter.grassFLat*(1.-parameter.vegAlbedo)*self.solRec
vegSens = self.vegCoverage*(1.-parameter.grassFLat)*(1.-parameter.vegAlbedo)*self.solRec
self.lat = soilLat + vegLat
# Sensible & net heat flux
self.sens = vegSens + self.aeroCond*(self.layerTemp[0]-tempRef)
self.flux = -self.sens + self.solAbs + self.infra - self.lat # (W m-2)
else: # For vertical surfaces (wall)
self.solAbs = (1.-self.albedo)*self.solRec
self.lat = 0.
# Sensible & net heat flux
self.sens = self.aeroCond*(self.layerTemp[0]-tempRef)
self.flux = -self.sens + self.solAbs + self.infra - self.lat # (W m-2)
self.layerTemp = self.Conduction(simTime.dt, self.flux, boundCond, forc.deepTemp, intFlux)
self.T_ext = self.layerTemp[0]
self.T_int = self.layerTemp[-1] | Calculate net heat flux, and update element layer temperatures | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/element.py#L97-L145 | [
"def is_near_zero(self,num,eps=1e-10):\n return abs(float(num)) < eps\n",
"def Conduction(self, dt, flx1, bc, temp2, flx2):\n \"\"\"\n Solve the conductance of heat based on of the element layers.\n arg:\n flx1 : net heat flux on surface\n bc : boundary condition parameter (1 or 2)\n temp2 : deep soil temperature (ave of air temperature)\n flx2 : surface flux (sum of absorbed, emitted, etc.)\n\n key prop:\n za = [[ x00, x01, x02 ... x0w ]\n [ x10, x11, x12 ... x1w ]\n ...\n [ xh0, xh1, xh2 ... xhw ]]\n\n where h = matrix row index = element layer number\n w = matrix column index = 3\n\n \"\"\"\n t = self.layerTemp # vector of layer temperatures (K)\n hc = self.layerVolHeat # vector of layer volumetric heat (J m-3 K-1)\n tc = self.layerThermalCond # vector of layer thermal conductivities (W m-1 K-1)\n d = self.layerThickness # vector of layer thicknesses (m)\n\n # flx1 : net heat flux on surface\n # bc : boundary condition parameter (1 or 2)\n # temp2 : deep soil temperature (avg of air temperature)\n # flx2 : surface flux (sum of absorbed, emitted, etc.)\n\n fimp = 0.5 # implicit coefficient\n fexp = 0.5 # explicit coefficient\n num = len(t) # number of layers\n\n # Mean thermal conductivity over distance between 2 layers (W/mK)\n tcp = [0 for x in range(num)]\n # Thermal capacity times layer depth (J/m2K)\n hcp = [0 for x in range(num)]\n # lower, main, and upper diagonals\n za = [[0 for y in range(3)] for x in range(num)]\n # RHS\n zy = [0 for x in range(num)]\n\n #--------------------------------------------------------------------------\n # Define the column vectors for heat capactiy and conductivity\n hcp[0] = hc[0] * d[0]\n for j in range(1,num):\n tcp[j] = 2. / (d[j-1] / tc[j-1] + d[j] / tc[j])\n hcp[j] = hc[j] * d[j]\n\n #--------------------------------------------------------------------------\n # Define the first row of za matrix, and RHS column vector\n za[0][0] = 0.\n za[0][1] = hcp[0]/dt + fimp*tcp[1]\n za[0][2] = -fimp*tcp[1]\n zy[0] = hcp[0]/dt*t[0] - fexp*tcp[1]*(t[0]-t[1]) + flx1\n\n #--------------------------------------------------------------------------\n # Define other rows\n for j in range(1,num-1):\n za[j][0] = fimp*(-tcp[j])\n za[j][1] = hcp[j]/dt + fimp*(tcp[j]+tcp[j+1])\n za[j][2] = fimp*(-tcp[j+1])\n zy[j] = hcp[j]/dt * t[j] + fexp * \\\n (tcp[j]*t[j-1] - tcp[j]*t[j] - tcp[j+1]*t[j] + tcp[j+1]*t[j+1])\n\n #--------------------------------------------------------------------------\n # Boundary conditions\n if self.is_near_zero(bc-1.): # heat flux\n za[num-1][0] = fimp * (-tcp[num-1])\n za[num-1][1] = hcp[num-1]/dt + fimp*tcp[num-1]\n za[num-1][2] = 0.\n zy[num-1] = hcp[num-1]/dt*t[num-1] + fexp*tcp[num-1]*(t[num-2]-t[num-1]) + flx2\n elif self.is_near_zero(bc-2.): # deep-temperature\n za[num-1][0] = 0.\n za[num-1][1] = 1.\n za[num-1][2] = 0.\n zy[num-1] = temp2\n else:\n raise Exception(self.CONDUCTION_INPUT_MSG)\n\n #--------------------------------------------------------------------------\n\n zx = self.invert(num,za,zy)\n #t(:) = zx(:);\n return zx # return zx as 1d vector of templayers\n"
] | class Element(object):
"""
uwg Element
# Note: In matlab not all instance variables are instantiated. They are assumed to be a 0-by-0 empty matrix
# https://www.mathworks.com/help/matlab/matlab_oop/specifying-properties.html
Attributes:
albedo; % outer surface albedo
emissivity; % outer surface emissivity
layerThickness; % vector of layer thicknesses (m)
layerThermalCond;% vector of layer thermal conductivities (W m-1 K-1)
layerVolHeat; % vector of layer volumetric heat (J m-3 K-1)
vegCoverage; % surface vegetation coverage
layerTemp; % vector of layer temperatures (K)
waterStorage; % thickness of water film (m) (only for horizontal surfaces)
horizontal; % 1-horizontal, 0-vertical
solRec; % solar radiation received (W m-2)
infra; % net longwave radiation (W m-2)
lat; % surface latent heat flux (W m-2)
sens; % surface sensible heat flux (W m-2)
solAbs; % solar radiation absorbed (W m-2)
aeroCond; % convective heat transfer
T_ext; % external surface temperature
T_int; % internal surface temperature
flux; % external surface heat flux
"""
THICKNESSLST_EQ_MATERIALLST_MSG = \
"-----------------------------------------\n" +\
"ERROR: the number of layer thickness must\n" +\
"match the number of layer materials\n"
"-----------------------------------------"
CONDUCTION_INPUT_MSG = 'ERROR: check input parameters in the Conduction routine'
def __init__(self, alb, emis, thicknessLst, materialLst, vegCoverage, T_init, horizontal,name=None):
if len(thicknessLst) != len(materialLst):
raise Exception(self.THICKNESSLST_EQ_MATERIALLST_MSG)
else:
self._name = name # purely for internal process
self.albedo = alb # outer surface albedo
self.emissivity = emis # outer surface emissivity
self.layerThickness = thicknessLst # vector of layer thicnesses (m)
self.layerThermalCond = [0. for i in materialLst] # vector of layer thermal conductivity (W m-1 K-1)
self.layerVolHeat = [0. for i in materialLst] # vector of layer volumetric heat (J m-3 K-1)
# Create list of layer k and (Cp*density) from materialLst properties
for i in range(len(materialLst)):
self.layerThermalCond[i] = materialLst[i].thermalCond
self.layerVolHeat[i] = materialLst[i].volHeat
self.vegCoverage = vegCoverage # surface vegetation coverage
self.layerTemp = [T_init] * len(thicknessLst) # vector of layer temperatures (K)
self.waterStorage = 0. # thickness of water film (m) for horizontal surfaces only
self.infra = 0. # net longwave radiation (W m-2)
self.horizontal = horizontal # 1-horizontal, 0-vertical
self.sens = 0. # surface sensible heat flux (W m-2)
# B/c we have to explicity define this in python. Set as None
self.solRec = None # solar radiation received (W m-2)
self.lat = None # surface latent heat flux (W m-2)
self.solAbs = None # solar radiation absorbed (W m-2)
self.aeroCond = None # convective heat transfer
self.T_ext = None # external surface temperature
self.T_int = None # internal surface temperature
self.flux = None # external surface heat flux
def __repr__(self):
# Returns some representative wall properties
s1 = "Element: {a}\n\tlayerNum={b}, totaldepth={c}\n\t".format(
a=self._name,
b=len(self.layerThickness),
c=sum(self.layerThickness)
)
s2 = "e={d}, a={e}\n\tr_val={f}, Cp*dens_avg={g}\n\tlayerTemp: {h}".format(
d=self.emissivity,
e=self.albedo,
f=round(sum(self.layerThermalCond)/2.,2),
g=round(sum(self.layerVolHeat)/2.,2),
h=self.layerTemp
)
return s1 + s2
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def Conduction(self, dt, flx1, bc, temp2, flx2):
"""
Solve the conductance of heat based on of the element layers.
arg:
flx1 : net heat flux on surface
bc : boundary condition parameter (1 or 2)
temp2 : deep soil temperature (ave of air temperature)
flx2 : surface flux (sum of absorbed, emitted, etc.)
key prop:
za = [[ x00, x01, x02 ... x0w ]
[ x10, x11, x12 ... x1w ]
...
[ xh0, xh1, xh2 ... xhw ]]
where h = matrix row index = element layer number
w = matrix column index = 3
"""
t = self.layerTemp # vector of layer temperatures (K)
hc = self.layerVolHeat # vector of layer volumetric heat (J m-3 K-1)
tc = self.layerThermalCond # vector of layer thermal conductivities (W m-1 K-1)
d = self.layerThickness # vector of layer thicknesses (m)
# flx1 : net heat flux on surface
# bc : boundary condition parameter (1 or 2)
# temp2 : deep soil temperature (avg of air temperature)
# flx2 : surface flux (sum of absorbed, emitted, etc.)
fimp = 0.5 # implicit coefficient
fexp = 0.5 # explicit coefficient
num = len(t) # number of layers
# Mean thermal conductivity over distance between 2 layers (W/mK)
tcp = [0 for x in range(num)]
# Thermal capacity times layer depth (J/m2K)
hcp = [0 for x in range(num)]
# lower, main, and upper diagonals
za = [[0 for y in range(3)] for x in range(num)]
# RHS
zy = [0 for x in range(num)]
#--------------------------------------------------------------------------
# Define the column vectors for heat capactiy and conductivity
hcp[0] = hc[0] * d[0]
for j in range(1,num):
tcp[j] = 2. / (d[j-1] / tc[j-1] + d[j] / tc[j])
hcp[j] = hc[j] * d[j]
#--------------------------------------------------------------------------
# Define the first row of za matrix, and RHS column vector
za[0][0] = 0.
za[0][1] = hcp[0]/dt + fimp*tcp[1]
za[0][2] = -fimp*tcp[1]
zy[0] = hcp[0]/dt*t[0] - fexp*tcp[1]*(t[0]-t[1]) + flx1
#--------------------------------------------------------------------------
# Define other rows
for j in range(1,num-1):
za[j][0] = fimp*(-tcp[j])
za[j][1] = hcp[j]/dt + fimp*(tcp[j]+tcp[j+1])
za[j][2] = fimp*(-tcp[j+1])
zy[j] = hcp[j]/dt * t[j] + fexp * \
(tcp[j]*t[j-1] - tcp[j]*t[j] - tcp[j+1]*t[j] + tcp[j+1]*t[j+1])
#--------------------------------------------------------------------------
# Boundary conditions
if self.is_near_zero(bc-1.): # heat flux
za[num-1][0] = fimp * (-tcp[num-1])
za[num-1][1] = hcp[num-1]/dt + fimp*tcp[num-1]
za[num-1][2] = 0.
zy[num-1] = hcp[num-1]/dt*t[num-1] + fexp*tcp[num-1]*(t[num-2]-t[num-1]) + flx2
elif self.is_near_zero(bc-2.): # deep-temperature
za[num-1][0] = 0.
za[num-1][1] = 1.
za[num-1][2] = 0.
zy[num-1] = temp2
else:
raise Exception(self.CONDUCTION_INPUT_MSG)
#--------------------------------------------------------------------------
zx = self.invert(num,za,zy)
#t(:) = zx(:);
return zx # return zx as 1d vector of templayers
def qsat(self,temp,pres,parameter):
"""
Calculate (qsat_lst) vector of saturation humidity from:
temp = vector of element layer temperatures
pres = pressure (at current timestep).
"""
gamw = (parameter.cl - parameter.cpv) / parameter.rv
betaw = (parameter.lvtt/parameter.rv) + (gamw * parameter.tt)
alpw = math.log(parameter.estt) + (betaw /parameter.tt) + (gamw * math.log(parameter.tt))
work2 = parameter.r/parameter.rv
foes_lst = [0 for i in range(len(temp))]
work1_lst = [0 for i in range(len(temp))]
qsat_lst = [0 for i in range(len(temp))]
for i in range(len(temp)):
# saturation vapor pressure
foes_lst[i] = math.exp( alpw - betaw/temp[i] - gamw*math.log(temp[i]) )
work1_lst[i] = foes_lst[i]/pres[i]
# saturation humidity
qsat_lst[i] = work2*work1_lst[i] / (1. + (work2-1.) * work1_lst[i])
return qsat_lst
def invert(self,nz,A,C):
"""
Inversion and resolution of a tridiagonal matrix
A X = C
Input:
nz number of layers
a(*,1) lower diagonal (Ai,i-1)
a(*,2) principal diagonal (Ai,i)
a(*,3) upper diagonal (Ai,i+1)
c
Output
x results
"""
X = [0 for i in range(nz)]
for i in reversed(range(nz-1)):
C[i] = C[i] - A[i][2] * C[i+1]/A[i+1][1]
A[i][1] = A[i][1] - A[i][2] * A[i+1][0]/A[i+1][1]
for i in range(1,nz,1):
C[i] = C[i] - A[i][0] * C[i-1]/A[i-1][1]
for i in range(nz):
X[i] = C[i]/A[i][1]
return X
|
ladybug-tools/uwg | uwg/element.py | Element.Conduction | python | def Conduction(self, dt, flx1, bc, temp2, flx2):
t = self.layerTemp # vector of layer temperatures (K)
hc = self.layerVolHeat # vector of layer volumetric heat (J m-3 K-1)
tc = self.layerThermalCond # vector of layer thermal conductivities (W m-1 K-1)
d = self.layerThickness # vector of layer thicknesses (m)
# flx1 : net heat flux on surface
# bc : boundary condition parameter (1 or 2)
# temp2 : deep soil temperature (avg of air temperature)
# flx2 : surface flux (sum of absorbed, emitted, etc.)
fimp = 0.5 # implicit coefficient
fexp = 0.5 # explicit coefficient
num = len(t) # number of layers
# Mean thermal conductivity over distance between 2 layers (W/mK)
tcp = [0 for x in range(num)]
# Thermal capacity times layer depth (J/m2K)
hcp = [0 for x in range(num)]
# lower, main, and upper diagonals
za = [[0 for y in range(3)] for x in range(num)]
# RHS
zy = [0 for x in range(num)]
#--------------------------------------------------------------------------
# Define the column vectors for heat capactiy and conductivity
hcp[0] = hc[0] * d[0]
for j in range(1,num):
tcp[j] = 2. / (d[j-1] / tc[j-1] + d[j] / tc[j])
hcp[j] = hc[j] * d[j]
#--------------------------------------------------------------------------
# Define the first row of za matrix, and RHS column vector
za[0][0] = 0.
za[0][1] = hcp[0]/dt + fimp*tcp[1]
za[0][2] = -fimp*tcp[1]
zy[0] = hcp[0]/dt*t[0] - fexp*tcp[1]*(t[0]-t[1]) + flx1
#--------------------------------------------------------------------------
# Define other rows
for j in range(1,num-1):
za[j][0] = fimp*(-tcp[j])
za[j][1] = hcp[j]/dt + fimp*(tcp[j]+tcp[j+1])
za[j][2] = fimp*(-tcp[j+1])
zy[j] = hcp[j]/dt * t[j] + fexp * \
(tcp[j]*t[j-1] - tcp[j]*t[j] - tcp[j+1]*t[j] + tcp[j+1]*t[j+1])
#--------------------------------------------------------------------------
# Boundary conditions
if self.is_near_zero(bc-1.): # heat flux
za[num-1][0] = fimp * (-tcp[num-1])
za[num-1][1] = hcp[num-1]/dt + fimp*tcp[num-1]
za[num-1][2] = 0.
zy[num-1] = hcp[num-1]/dt*t[num-1] + fexp*tcp[num-1]*(t[num-2]-t[num-1]) + flx2
elif self.is_near_zero(bc-2.): # deep-temperature
za[num-1][0] = 0.
za[num-1][1] = 1.
za[num-1][2] = 0.
zy[num-1] = temp2
else:
raise Exception(self.CONDUCTION_INPUT_MSG)
#--------------------------------------------------------------------------
zx = self.invert(num,za,zy)
#t(:) = zx(:);
return zx | Solve the conductance of heat based on of the element layers.
arg:
flx1 : net heat flux on surface
bc : boundary condition parameter (1 or 2)
temp2 : deep soil temperature (ave of air temperature)
flx2 : surface flux (sum of absorbed, emitted, etc.)
key prop:
za = [[ x00, x01, x02 ... x0w ]
[ x10, x11, x12 ... x1w ]
...
[ xh0, xh1, xh2 ... xhw ]]
where h = matrix row index = element layer number
w = matrix column index = 3 | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/element.py#L147-L231 | [
"def is_near_zero(self,num,eps=1e-10):\n return abs(float(num)) < eps\n"
] | class Element(object):
"""
uwg Element
# Note: In matlab not all instance variables are instantiated. They are assumed to be a 0-by-0 empty matrix
# https://www.mathworks.com/help/matlab/matlab_oop/specifying-properties.html
Attributes:
albedo; % outer surface albedo
emissivity; % outer surface emissivity
layerThickness; % vector of layer thicknesses (m)
layerThermalCond;% vector of layer thermal conductivities (W m-1 K-1)
layerVolHeat; % vector of layer volumetric heat (J m-3 K-1)
vegCoverage; % surface vegetation coverage
layerTemp; % vector of layer temperatures (K)
waterStorage; % thickness of water film (m) (only for horizontal surfaces)
horizontal; % 1-horizontal, 0-vertical
solRec; % solar radiation received (W m-2)
infra; % net longwave radiation (W m-2)
lat; % surface latent heat flux (W m-2)
sens; % surface sensible heat flux (W m-2)
solAbs; % solar radiation absorbed (W m-2)
aeroCond; % convective heat transfer
T_ext; % external surface temperature
T_int; % internal surface temperature
flux; % external surface heat flux
"""
THICKNESSLST_EQ_MATERIALLST_MSG = \
"-----------------------------------------\n" +\
"ERROR: the number of layer thickness must\n" +\
"match the number of layer materials\n"
"-----------------------------------------"
CONDUCTION_INPUT_MSG = 'ERROR: check input parameters in the Conduction routine'
def __init__(self, alb, emis, thicknessLst, materialLst, vegCoverage, T_init, horizontal,name=None):
if len(thicknessLst) != len(materialLst):
raise Exception(self.THICKNESSLST_EQ_MATERIALLST_MSG)
else:
self._name = name # purely for internal process
self.albedo = alb # outer surface albedo
self.emissivity = emis # outer surface emissivity
self.layerThickness = thicknessLst # vector of layer thicnesses (m)
self.layerThermalCond = [0. for i in materialLst] # vector of layer thermal conductivity (W m-1 K-1)
self.layerVolHeat = [0. for i in materialLst] # vector of layer volumetric heat (J m-3 K-1)
# Create list of layer k and (Cp*density) from materialLst properties
for i in range(len(materialLst)):
self.layerThermalCond[i] = materialLst[i].thermalCond
self.layerVolHeat[i] = materialLst[i].volHeat
self.vegCoverage = vegCoverage # surface vegetation coverage
self.layerTemp = [T_init] * len(thicknessLst) # vector of layer temperatures (K)
self.waterStorage = 0. # thickness of water film (m) for horizontal surfaces only
self.infra = 0. # net longwave radiation (W m-2)
self.horizontal = horizontal # 1-horizontal, 0-vertical
self.sens = 0. # surface sensible heat flux (W m-2)
# B/c we have to explicity define this in python. Set as None
self.solRec = None # solar radiation received (W m-2)
self.lat = None # surface latent heat flux (W m-2)
self.solAbs = None # solar radiation absorbed (W m-2)
self.aeroCond = None # convective heat transfer
self.T_ext = None # external surface temperature
self.T_int = None # internal surface temperature
self.flux = None # external surface heat flux
def __repr__(self):
# Returns some representative wall properties
s1 = "Element: {a}\n\tlayerNum={b}, totaldepth={c}\n\t".format(
a=self._name,
b=len(self.layerThickness),
c=sum(self.layerThickness)
)
s2 = "e={d}, a={e}\n\tr_val={f}, Cp*dens_avg={g}\n\tlayerTemp: {h}".format(
d=self.emissivity,
e=self.albedo,
f=round(sum(self.layerThermalCond)/2.,2),
g=round(sum(self.layerVolHeat)/2.,2),
h=self.layerTemp
)
return s1 + s2
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def SurfFlux(self,forc,parameter,simTime,humRef,tempRef,windRef,boundCond,intFlux):
""" Calculate net heat flux, and update element layer temperatures
"""
# Calculated per unit area (m^2)
dens = forc.pres/(1000*0.287042*tempRef*(1.+1.607858*humRef)) # air density (kgd m-3)
self.aeroCond = 5.8 + 3.7 * windRef # Convection coef (ref: uwg, eq. 12))
if (self.horizontal): # For roof, mass, road
# Evaporation (m s-1), Film water & soil latent heat
if not self.is_near_zero(self.waterStorage) and self.waterStorage > 0.0:
# N.B In the current uwg code, latent heat from evapotranspiration, stagnant water,
# or anthropogenic sources is not modelled due to the difficulty of validation, and
# lack of reliability of precipitation data from EPW files.Therefore this condition
# is never run because all elements have had their waterStorage hardcoded to 0.
qtsat = self.qsat([self.layerTemp[0]],[forc.pres],parameter)[0]
eg = self.aeroCond*parameter.colburn*dens*(qtsat-humRef)/parameter.waterDens/parameter.cp
self.waterStorage = min(self.waterStorage + simTime.dt*(forc.prec-eg),parameter.wgmax)
self.waterStorage = max(self.waterStorage,0.) # (m)
else:
eg = 0.
soilLat = eg*parameter.waterDens*parameter.lv
# Winter, no veg
if simTime.month < parameter.vegStart and simTime.month > parameter.vegEnd:
self.solAbs = (1.-self.albedo)*self.solRec # (W m-2)
vegLat = 0.
vegSens = 0.
else: # Summer, veg
self.solAbs = ((1.-self.vegCoverage)*(1.-self.albedo)+self.vegCoverage*(1.-parameter.vegAlbedo))*self.solRec
vegLat = self.vegCoverage*parameter.grassFLat*(1.-parameter.vegAlbedo)*self.solRec
vegSens = self.vegCoverage*(1.-parameter.grassFLat)*(1.-parameter.vegAlbedo)*self.solRec
self.lat = soilLat + vegLat
# Sensible & net heat flux
self.sens = vegSens + self.aeroCond*(self.layerTemp[0]-tempRef)
self.flux = -self.sens + self.solAbs + self.infra - self.lat # (W m-2)
else: # For vertical surfaces (wall)
self.solAbs = (1.-self.albedo)*self.solRec
self.lat = 0.
# Sensible & net heat flux
self.sens = self.aeroCond*(self.layerTemp[0]-tempRef)
self.flux = -self.sens + self.solAbs + self.infra - self.lat # (W m-2)
self.layerTemp = self.Conduction(simTime.dt, self.flux, boundCond, forc.deepTemp, intFlux)
self.T_ext = self.layerTemp[0]
self.T_int = self.layerTemp[-1]
# return zx as 1d vector of templayers
def qsat(self,temp,pres,parameter):
"""
Calculate (qsat_lst) vector of saturation humidity from:
temp = vector of element layer temperatures
pres = pressure (at current timestep).
"""
gamw = (parameter.cl - parameter.cpv) / parameter.rv
betaw = (parameter.lvtt/parameter.rv) + (gamw * parameter.tt)
alpw = math.log(parameter.estt) + (betaw /parameter.tt) + (gamw * math.log(parameter.tt))
work2 = parameter.r/parameter.rv
foes_lst = [0 for i in range(len(temp))]
work1_lst = [0 for i in range(len(temp))]
qsat_lst = [0 for i in range(len(temp))]
for i in range(len(temp)):
# saturation vapor pressure
foes_lst[i] = math.exp( alpw - betaw/temp[i] - gamw*math.log(temp[i]) )
work1_lst[i] = foes_lst[i]/pres[i]
# saturation humidity
qsat_lst[i] = work2*work1_lst[i] / (1. + (work2-1.) * work1_lst[i])
return qsat_lst
def invert(self,nz,A,C):
"""
Inversion and resolution of a tridiagonal matrix
A X = C
Input:
nz number of layers
a(*,1) lower diagonal (Ai,i-1)
a(*,2) principal diagonal (Ai,i)
a(*,3) upper diagonal (Ai,i+1)
c
Output
x results
"""
X = [0 for i in range(nz)]
for i in reversed(range(nz-1)):
C[i] = C[i] - A[i][2] * C[i+1]/A[i+1][1]
A[i][1] = A[i][1] - A[i][2] * A[i+1][0]/A[i+1][1]
for i in range(1,nz,1):
C[i] = C[i] - A[i][0] * C[i-1]/A[i-1][1]
for i in range(nz):
X[i] = C[i]/A[i][1]
return X
|
ladybug-tools/uwg | uwg/element.py | Element.qsat | python | def qsat(self,temp,pres,parameter):
gamw = (parameter.cl - parameter.cpv) / parameter.rv
betaw = (parameter.lvtt/parameter.rv) + (gamw * parameter.tt)
alpw = math.log(parameter.estt) + (betaw /parameter.tt) + (gamw * math.log(parameter.tt))
work2 = parameter.r/parameter.rv
foes_lst = [0 for i in range(len(temp))]
work1_lst = [0 for i in range(len(temp))]
qsat_lst = [0 for i in range(len(temp))]
for i in range(len(temp)):
# saturation vapor pressure
foes_lst[i] = math.exp( alpw - betaw/temp[i] - gamw*math.log(temp[i]) )
work1_lst[i] = foes_lst[i]/pres[i]
# saturation humidity
qsat_lst[i] = work2*work1_lst[i] / (1. + (work2-1.) * work1_lst[i])
return qsat_lst | Calculate (qsat_lst) vector of saturation humidity from:
temp = vector of element layer temperatures
pres = pressure (at current timestep). | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/element.py#L233-L254 | null | class Element(object):
"""
uwg Element
# Note: In matlab not all instance variables are instantiated. They are assumed to be a 0-by-0 empty matrix
# https://www.mathworks.com/help/matlab/matlab_oop/specifying-properties.html
Attributes:
albedo; % outer surface albedo
emissivity; % outer surface emissivity
layerThickness; % vector of layer thicknesses (m)
layerThermalCond;% vector of layer thermal conductivities (W m-1 K-1)
layerVolHeat; % vector of layer volumetric heat (J m-3 K-1)
vegCoverage; % surface vegetation coverage
layerTemp; % vector of layer temperatures (K)
waterStorage; % thickness of water film (m) (only for horizontal surfaces)
horizontal; % 1-horizontal, 0-vertical
solRec; % solar radiation received (W m-2)
infra; % net longwave radiation (W m-2)
lat; % surface latent heat flux (W m-2)
sens; % surface sensible heat flux (W m-2)
solAbs; % solar radiation absorbed (W m-2)
aeroCond; % convective heat transfer
T_ext; % external surface temperature
T_int; % internal surface temperature
flux; % external surface heat flux
"""
THICKNESSLST_EQ_MATERIALLST_MSG = \
"-----------------------------------------\n" +\
"ERROR: the number of layer thickness must\n" +\
"match the number of layer materials\n"
"-----------------------------------------"
CONDUCTION_INPUT_MSG = 'ERROR: check input parameters in the Conduction routine'
def __init__(self, alb, emis, thicknessLst, materialLst, vegCoverage, T_init, horizontal,name=None):
if len(thicknessLst) != len(materialLst):
raise Exception(self.THICKNESSLST_EQ_MATERIALLST_MSG)
else:
self._name = name # purely for internal process
self.albedo = alb # outer surface albedo
self.emissivity = emis # outer surface emissivity
self.layerThickness = thicknessLst # vector of layer thicnesses (m)
self.layerThermalCond = [0. for i in materialLst] # vector of layer thermal conductivity (W m-1 K-1)
self.layerVolHeat = [0. for i in materialLst] # vector of layer volumetric heat (J m-3 K-1)
# Create list of layer k and (Cp*density) from materialLst properties
for i in range(len(materialLst)):
self.layerThermalCond[i] = materialLst[i].thermalCond
self.layerVolHeat[i] = materialLst[i].volHeat
self.vegCoverage = vegCoverage # surface vegetation coverage
self.layerTemp = [T_init] * len(thicknessLst) # vector of layer temperatures (K)
self.waterStorage = 0. # thickness of water film (m) for horizontal surfaces only
self.infra = 0. # net longwave radiation (W m-2)
self.horizontal = horizontal # 1-horizontal, 0-vertical
self.sens = 0. # surface sensible heat flux (W m-2)
# B/c we have to explicity define this in python. Set as None
self.solRec = None # solar radiation received (W m-2)
self.lat = None # surface latent heat flux (W m-2)
self.solAbs = None # solar radiation absorbed (W m-2)
self.aeroCond = None # convective heat transfer
self.T_ext = None # external surface temperature
self.T_int = None # internal surface temperature
self.flux = None # external surface heat flux
def __repr__(self):
# Returns some representative wall properties
s1 = "Element: {a}\n\tlayerNum={b}, totaldepth={c}\n\t".format(
a=self._name,
b=len(self.layerThickness),
c=sum(self.layerThickness)
)
s2 = "e={d}, a={e}\n\tr_val={f}, Cp*dens_avg={g}\n\tlayerTemp: {h}".format(
d=self.emissivity,
e=self.albedo,
f=round(sum(self.layerThermalCond)/2.,2),
g=round(sum(self.layerVolHeat)/2.,2),
h=self.layerTemp
)
return s1 + s2
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def SurfFlux(self,forc,parameter,simTime,humRef,tempRef,windRef,boundCond,intFlux):
""" Calculate net heat flux, and update element layer temperatures
"""
# Calculated per unit area (m^2)
dens = forc.pres/(1000*0.287042*tempRef*(1.+1.607858*humRef)) # air density (kgd m-3)
self.aeroCond = 5.8 + 3.7 * windRef # Convection coef (ref: uwg, eq. 12))
if (self.horizontal): # For roof, mass, road
# Evaporation (m s-1), Film water & soil latent heat
if not self.is_near_zero(self.waterStorage) and self.waterStorage > 0.0:
# N.B In the current uwg code, latent heat from evapotranspiration, stagnant water,
# or anthropogenic sources is not modelled due to the difficulty of validation, and
# lack of reliability of precipitation data from EPW files.Therefore this condition
# is never run because all elements have had their waterStorage hardcoded to 0.
qtsat = self.qsat([self.layerTemp[0]],[forc.pres],parameter)[0]
eg = self.aeroCond*parameter.colburn*dens*(qtsat-humRef)/parameter.waterDens/parameter.cp
self.waterStorage = min(self.waterStorage + simTime.dt*(forc.prec-eg),parameter.wgmax)
self.waterStorage = max(self.waterStorage,0.) # (m)
else:
eg = 0.
soilLat = eg*parameter.waterDens*parameter.lv
# Winter, no veg
if simTime.month < parameter.vegStart and simTime.month > parameter.vegEnd:
self.solAbs = (1.-self.albedo)*self.solRec # (W m-2)
vegLat = 0.
vegSens = 0.
else: # Summer, veg
self.solAbs = ((1.-self.vegCoverage)*(1.-self.albedo)+self.vegCoverage*(1.-parameter.vegAlbedo))*self.solRec
vegLat = self.vegCoverage*parameter.grassFLat*(1.-parameter.vegAlbedo)*self.solRec
vegSens = self.vegCoverage*(1.-parameter.grassFLat)*(1.-parameter.vegAlbedo)*self.solRec
self.lat = soilLat + vegLat
# Sensible & net heat flux
self.sens = vegSens + self.aeroCond*(self.layerTemp[0]-tempRef)
self.flux = -self.sens + self.solAbs + self.infra - self.lat # (W m-2)
else: # For vertical surfaces (wall)
self.solAbs = (1.-self.albedo)*self.solRec
self.lat = 0.
# Sensible & net heat flux
self.sens = self.aeroCond*(self.layerTemp[0]-tempRef)
self.flux = -self.sens + self.solAbs + self.infra - self.lat # (W m-2)
self.layerTemp = self.Conduction(simTime.dt, self.flux, boundCond, forc.deepTemp, intFlux)
self.T_ext = self.layerTemp[0]
self.T_int = self.layerTemp[-1]
def Conduction(self, dt, flx1, bc, temp2, flx2):
"""
Solve the conductance of heat based on of the element layers.
arg:
flx1 : net heat flux on surface
bc : boundary condition parameter (1 or 2)
temp2 : deep soil temperature (ave of air temperature)
flx2 : surface flux (sum of absorbed, emitted, etc.)
key prop:
za = [[ x00, x01, x02 ... x0w ]
[ x10, x11, x12 ... x1w ]
...
[ xh0, xh1, xh2 ... xhw ]]
where h = matrix row index = element layer number
w = matrix column index = 3
"""
t = self.layerTemp # vector of layer temperatures (K)
hc = self.layerVolHeat # vector of layer volumetric heat (J m-3 K-1)
tc = self.layerThermalCond # vector of layer thermal conductivities (W m-1 K-1)
d = self.layerThickness # vector of layer thicknesses (m)
# flx1 : net heat flux on surface
# bc : boundary condition parameter (1 or 2)
# temp2 : deep soil temperature (avg of air temperature)
# flx2 : surface flux (sum of absorbed, emitted, etc.)
fimp = 0.5 # implicit coefficient
fexp = 0.5 # explicit coefficient
num = len(t) # number of layers
# Mean thermal conductivity over distance between 2 layers (W/mK)
tcp = [0 for x in range(num)]
# Thermal capacity times layer depth (J/m2K)
hcp = [0 for x in range(num)]
# lower, main, and upper diagonals
za = [[0 for y in range(3)] for x in range(num)]
# RHS
zy = [0 for x in range(num)]
#--------------------------------------------------------------------------
# Define the column vectors for heat capactiy and conductivity
hcp[0] = hc[0] * d[0]
for j in range(1,num):
tcp[j] = 2. / (d[j-1] / tc[j-1] + d[j] / tc[j])
hcp[j] = hc[j] * d[j]
#--------------------------------------------------------------------------
# Define the first row of za matrix, and RHS column vector
za[0][0] = 0.
za[0][1] = hcp[0]/dt + fimp*tcp[1]
za[0][2] = -fimp*tcp[1]
zy[0] = hcp[0]/dt*t[0] - fexp*tcp[1]*(t[0]-t[1]) + flx1
#--------------------------------------------------------------------------
# Define other rows
for j in range(1,num-1):
za[j][0] = fimp*(-tcp[j])
za[j][1] = hcp[j]/dt + fimp*(tcp[j]+tcp[j+1])
za[j][2] = fimp*(-tcp[j+1])
zy[j] = hcp[j]/dt * t[j] + fexp * \
(tcp[j]*t[j-1] - tcp[j]*t[j] - tcp[j+1]*t[j] + tcp[j+1]*t[j+1])
#--------------------------------------------------------------------------
# Boundary conditions
if self.is_near_zero(bc-1.): # heat flux
za[num-1][0] = fimp * (-tcp[num-1])
za[num-1][1] = hcp[num-1]/dt + fimp*tcp[num-1]
za[num-1][2] = 0.
zy[num-1] = hcp[num-1]/dt*t[num-1] + fexp*tcp[num-1]*(t[num-2]-t[num-1]) + flx2
elif self.is_near_zero(bc-2.): # deep-temperature
za[num-1][0] = 0.
za[num-1][1] = 1.
za[num-1][2] = 0.
zy[num-1] = temp2
else:
raise Exception(self.CONDUCTION_INPUT_MSG)
#--------------------------------------------------------------------------
zx = self.invert(num,za,zy)
#t(:) = zx(:);
return zx # return zx as 1d vector of templayers
def invert(self,nz,A,C):
"""
Inversion and resolution of a tridiagonal matrix
A X = C
Input:
nz number of layers
a(*,1) lower diagonal (Ai,i-1)
a(*,2) principal diagonal (Ai,i)
a(*,3) upper diagonal (Ai,i+1)
c
Output
x results
"""
X = [0 for i in range(nz)]
for i in reversed(range(nz-1)):
C[i] = C[i] - A[i][2] * C[i+1]/A[i+1][1]
A[i][1] = A[i][1] - A[i][2] * A[i+1][0]/A[i+1][1]
for i in range(1,nz,1):
C[i] = C[i] - A[i][0] * C[i-1]/A[i-1][1]
for i in range(nz):
X[i] = C[i]/A[i][1]
return X
|
ladybug-tools/uwg | uwg/element.py | Element.invert | python | def invert(self,nz,A,C):
X = [0 for i in range(nz)]
for i in reversed(range(nz-1)):
C[i] = C[i] - A[i][2] * C[i+1]/A[i+1][1]
A[i][1] = A[i][1] - A[i][2] * A[i+1][0]/A[i+1][1]
for i in range(1,nz,1):
C[i] = C[i] - A[i][0] * C[i-1]/A[i-1][1]
for i in range(nz):
X[i] = C[i]/A[i][1]
return X | Inversion and resolution of a tridiagonal matrix
A X = C
Input:
nz number of layers
a(*,1) lower diagonal (Ai,i-1)
a(*,2) principal diagonal (Ai,i)
a(*,3) upper diagonal (Ai,i+1)
c
Output
x results | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/element.py#L257-L283 | null | class Element(object):
"""
uwg Element
# Note: In matlab not all instance variables are instantiated. They are assumed to be a 0-by-0 empty matrix
# https://www.mathworks.com/help/matlab/matlab_oop/specifying-properties.html
Attributes:
albedo; % outer surface albedo
emissivity; % outer surface emissivity
layerThickness; % vector of layer thicknesses (m)
layerThermalCond;% vector of layer thermal conductivities (W m-1 K-1)
layerVolHeat; % vector of layer volumetric heat (J m-3 K-1)
vegCoverage; % surface vegetation coverage
layerTemp; % vector of layer temperatures (K)
waterStorage; % thickness of water film (m) (only for horizontal surfaces)
horizontal; % 1-horizontal, 0-vertical
solRec; % solar radiation received (W m-2)
infra; % net longwave radiation (W m-2)
lat; % surface latent heat flux (W m-2)
sens; % surface sensible heat flux (W m-2)
solAbs; % solar radiation absorbed (W m-2)
aeroCond; % convective heat transfer
T_ext; % external surface temperature
T_int; % internal surface temperature
flux; % external surface heat flux
"""
THICKNESSLST_EQ_MATERIALLST_MSG = \
"-----------------------------------------\n" +\
"ERROR: the number of layer thickness must\n" +\
"match the number of layer materials\n"
"-----------------------------------------"
CONDUCTION_INPUT_MSG = 'ERROR: check input parameters in the Conduction routine'
def __init__(self, alb, emis, thicknessLst, materialLst, vegCoverage, T_init, horizontal,name=None):
if len(thicknessLst) != len(materialLst):
raise Exception(self.THICKNESSLST_EQ_MATERIALLST_MSG)
else:
self._name = name # purely for internal process
self.albedo = alb # outer surface albedo
self.emissivity = emis # outer surface emissivity
self.layerThickness = thicknessLst # vector of layer thicnesses (m)
self.layerThermalCond = [0. for i in materialLst] # vector of layer thermal conductivity (W m-1 K-1)
self.layerVolHeat = [0. for i in materialLst] # vector of layer volumetric heat (J m-3 K-1)
# Create list of layer k and (Cp*density) from materialLst properties
for i in range(len(materialLst)):
self.layerThermalCond[i] = materialLst[i].thermalCond
self.layerVolHeat[i] = materialLst[i].volHeat
self.vegCoverage = vegCoverage # surface vegetation coverage
self.layerTemp = [T_init] * len(thicknessLst) # vector of layer temperatures (K)
self.waterStorage = 0. # thickness of water film (m) for horizontal surfaces only
self.infra = 0. # net longwave radiation (W m-2)
self.horizontal = horizontal # 1-horizontal, 0-vertical
self.sens = 0. # surface sensible heat flux (W m-2)
# B/c we have to explicity define this in python. Set as None
self.solRec = None # solar radiation received (W m-2)
self.lat = None # surface latent heat flux (W m-2)
self.solAbs = None # solar radiation absorbed (W m-2)
self.aeroCond = None # convective heat transfer
self.T_ext = None # external surface temperature
self.T_int = None # internal surface temperature
self.flux = None # external surface heat flux
def __repr__(self):
# Returns some representative wall properties
s1 = "Element: {a}\n\tlayerNum={b}, totaldepth={c}\n\t".format(
a=self._name,
b=len(self.layerThickness),
c=sum(self.layerThickness)
)
s2 = "e={d}, a={e}\n\tr_val={f}, Cp*dens_avg={g}\n\tlayerTemp: {h}".format(
d=self.emissivity,
e=self.albedo,
f=round(sum(self.layerThermalCond)/2.,2),
g=round(sum(self.layerVolHeat)/2.,2),
h=self.layerTemp
)
return s1 + s2
def is_near_zero(self,num,eps=1e-10):
return abs(float(num)) < eps
def SurfFlux(self,forc,parameter,simTime,humRef,tempRef,windRef,boundCond,intFlux):
""" Calculate net heat flux, and update element layer temperatures
"""
# Calculated per unit area (m^2)
dens = forc.pres/(1000*0.287042*tempRef*(1.+1.607858*humRef)) # air density (kgd m-3)
self.aeroCond = 5.8 + 3.7 * windRef # Convection coef (ref: uwg, eq. 12))
if (self.horizontal): # For roof, mass, road
# Evaporation (m s-1), Film water & soil latent heat
if not self.is_near_zero(self.waterStorage) and self.waterStorage > 0.0:
# N.B In the current uwg code, latent heat from evapotranspiration, stagnant water,
# or anthropogenic sources is not modelled due to the difficulty of validation, and
# lack of reliability of precipitation data from EPW files.Therefore this condition
# is never run because all elements have had their waterStorage hardcoded to 0.
qtsat = self.qsat([self.layerTemp[0]],[forc.pres],parameter)[0]
eg = self.aeroCond*parameter.colburn*dens*(qtsat-humRef)/parameter.waterDens/parameter.cp
self.waterStorage = min(self.waterStorage + simTime.dt*(forc.prec-eg),parameter.wgmax)
self.waterStorage = max(self.waterStorage,0.) # (m)
else:
eg = 0.
soilLat = eg*parameter.waterDens*parameter.lv
# Winter, no veg
if simTime.month < parameter.vegStart and simTime.month > parameter.vegEnd:
self.solAbs = (1.-self.albedo)*self.solRec # (W m-2)
vegLat = 0.
vegSens = 0.
else: # Summer, veg
self.solAbs = ((1.-self.vegCoverage)*(1.-self.albedo)+self.vegCoverage*(1.-parameter.vegAlbedo))*self.solRec
vegLat = self.vegCoverage*parameter.grassFLat*(1.-parameter.vegAlbedo)*self.solRec
vegSens = self.vegCoverage*(1.-parameter.grassFLat)*(1.-parameter.vegAlbedo)*self.solRec
self.lat = soilLat + vegLat
# Sensible & net heat flux
self.sens = vegSens + self.aeroCond*(self.layerTemp[0]-tempRef)
self.flux = -self.sens + self.solAbs + self.infra - self.lat # (W m-2)
else: # For vertical surfaces (wall)
self.solAbs = (1.-self.albedo)*self.solRec
self.lat = 0.
# Sensible & net heat flux
self.sens = self.aeroCond*(self.layerTemp[0]-tempRef)
self.flux = -self.sens + self.solAbs + self.infra - self.lat # (W m-2)
self.layerTemp = self.Conduction(simTime.dt, self.flux, boundCond, forc.deepTemp, intFlux)
self.T_ext = self.layerTemp[0]
self.T_int = self.layerTemp[-1]
def Conduction(self, dt, flx1, bc, temp2, flx2):
"""
Solve the conductance of heat based on of the element layers.
arg:
flx1 : net heat flux on surface
bc : boundary condition parameter (1 or 2)
temp2 : deep soil temperature (ave of air temperature)
flx2 : surface flux (sum of absorbed, emitted, etc.)
key prop:
za = [[ x00, x01, x02 ... x0w ]
[ x10, x11, x12 ... x1w ]
...
[ xh0, xh1, xh2 ... xhw ]]
where h = matrix row index = element layer number
w = matrix column index = 3
"""
t = self.layerTemp # vector of layer temperatures (K)
hc = self.layerVolHeat # vector of layer volumetric heat (J m-3 K-1)
tc = self.layerThermalCond # vector of layer thermal conductivities (W m-1 K-1)
d = self.layerThickness # vector of layer thicknesses (m)
# flx1 : net heat flux on surface
# bc : boundary condition parameter (1 or 2)
# temp2 : deep soil temperature (avg of air temperature)
# flx2 : surface flux (sum of absorbed, emitted, etc.)
fimp = 0.5 # implicit coefficient
fexp = 0.5 # explicit coefficient
num = len(t) # number of layers
# Mean thermal conductivity over distance between 2 layers (W/mK)
tcp = [0 for x in range(num)]
# Thermal capacity times layer depth (J/m2K)
hcp = [0 for x in range(num)]
# lower, main, and upper diagonals
za = [[0 for y in range(3)] for x in range(num)]
# RHS
zy = [0 for x in range(num)]
#--------------------------------------------------------------------------
# Define the column vectors for heat capactiy and conductivity
hcp[0] = hc[0] * d[0]
for j in range(1,num):
tcp[j] = 2. / (d[j-1] / tc[j-1] + d[j] / tc[j])
hcp[j] = hc[j] * d[j]
#--------------------------------------------------------------------------
# Define the first row of za matrix, and RHS column vector
za[0][0] = 0.
za[0][1] = hcp[0]/dt + fimp*tcp[1]
za[0][2] = -fimp*tcp[1]
zy[0] = hcp[0]/dt*t[0] - fexp*tcp[1]*(t[0]-t[1]) + flx1
#--------------------------------------------------------------------------
# Define other rows
for j in range(1,num-1):
za[j][0] = fimp*(-tcp[j])
za[j][1] = hcp[j]/dt + fimp*(tcp[j]+tcp[j+1])
za[j][2] = fimp*(-tcp[j+1])
zy[j] = hcp[j]/dt * t[j] + fexp * \
(tcp[j]*t[j-1] - tcp[j]*t[j] - tcp[j+1]*t[j] + tcp[j+1]*t[j+1])
#--------------------------------------------------------------------------
# Boundary conditions
if self.is_near_zero(bc-1.): # heat flux
za[num-1][0] = fimp * (-tcp[num-1])
za[num-1][1] = hcp[num-1]/dt + fimp*tcp[num-1]
za[num-1][2] = 0.
zy[num-1] = hcp[num-1]/dt*t[num-1] + fexp*tcp[num-1]*(t[num-2]-t[num-1]) + flx2
elif self.is_near_zero(bc-2.): # deep-temperature
za[num-1][0] = 0.
za[num-1][1] = 1.
za[num-1][2] = 0.
zy[num-1] = temp2
else:
raise Exception(self.CONDUCTION_INPUT_MSG)
#--------------------------------------------------------------------------
zx = self.invert(num,za,zy)
#t(:) = zx(:);
return zx # return zx as 1d vector of templayers
def qsat(self,temp,pres,parameter):
"""
Calculate (qsat_lst) vector of saturation humidity from:
temp = vector of element layer temperatures
pres = pressure (at current timestep).
"""
gamw = (parameter.cl - parameter.cpv) / parameter.rv
betaw = (parameter.lvtt/parameter.rv) + (gamw * parameter.tt)
alpw = math.log(parameter.estt) + (betaw /parameter.tt) + (gamw * math.log(parameter.tt))
work2 = parameter.r/parameter.rv
foes_lst = [0 for i in range(len(temp))]
work1_lst = [0 for i in range(len(temp))]
qsat_lst = [0 for i in range(len(temp))]
for i in range(len(temp)):
# saturation vapor pressure
foes_lst[i] = math.exp( alpw - betaw/temp[i] - gamw*math.log(temp[i]) )
work1_lst[i] = foes_lst[i]/pres[i]
# saturation humidity
qsat_lst[i] = work2*work1_lst[i] / (1. + (work2-1.) * work1_lst[i])
return qsat_lst
|
ladybug-tools/uwg | uwg/readDOE.py | readDOE | python | def readDOE(serialize_output=True):
#Nested, nested lists of Building, SchDef, BEMDef objects
refDOE = [[[None]*16 for k_ in range(3)] for j_ in range(16)] #refDOE(16,3,16) = Building
Schedule = [[[None]*16 for k_ in range(3)] for j_ in range(16)] #Schedule (16,3,16) = SchDef
refBEM = [[[None]*16 for k_ in range(3)] for j_ in range(16)] #refBEM (16,3,16) = BEMDef
#Purpose: Loop through every DOE reference csv and extract building data
#Nested loop = 16 types, 3 era, 16 zones = time complexity O(n*m*k) = 768
for i in range(16):
#i = 16 types of buildings
#print "\tType: {} @i={}".format(BLDTYPE[i], i)
# Read building summary (Sheet 1)
file_doe_name_bld = os.path.join("{}".format(DIR_DOE_PATH), "BLD{}".format(i+1),"BLD{}_BuildingSummary.csv".format(i+1))
list_doe1 = read_csv(file_doe_name_bld)
#listof(listof 3 era values)
nFloor = str2fl(list_doe1[3][3:6]) # Number of Floors, this will be list of floats and str if "basement"
glazing = str2fl(list_doe1[4][3:6]) # [?] Total
hCeiling = str2fl(list_doe1[5][3:6]) # [m] Ceiling height
ver2hor = str2fl(list_doe1[7][3:6]) # Wall to Skin Ratio
AreaRoof = str2fl(list_doe1[8][3:6]) # [m2] Gross Dimensions - Total area
# Read zone summary (Sheet 2)
file_doe_name_zone = os.path.join("{}".format(DIR_DOE_PATH), "BLD{}".format(i+1),"BLD{}_ZoneSummary.csv".format(i+1))
list_doe2 = read_csv(file_doe_name_zone)
#listof(listof 3 eras)
AreaFloor = str2fl([list_doe2[2][5],list_doe2[3][5],list_doe2[4][5]]) # [m2]
Volume = str2fl([list_doe2[2][6],list_doe2[3][6],list_doe2[4][6]]) # [m3]
AreaWall = str2fl([list_doe2[2][8],list_doe2[3][8],list_doe2[4][8]]) # [m2]
AreaWindow = str2fl([list_doe2[2][9],list_doe2[3][9],list_doe2[4][9]]) # [m2]
Occupant = str2fl([list_doe2[2][11],list_doe2[3][11],list_doe2[4][11]]) # Number of People
Light = str2fl([list_doe2[2][12],list_doe2[3][12],list_doe2[4][12]]) # [W/m2]
Elec = str2fl([list_doe2[2][13],list_doe2[3][13],list_doe2[4][13]]) # [W/m2] Electric Plug and Process
Gas = str2fl([list_doe2[2][14],list_doe2[3][14],list_doe2[4][14]]) # [W/m2] Gas Plug and Process
SHW = str2fl([list_doe2[2][15],list_doe2[3][15],list_doe2[4][15]]) # [Litres/hr] Peak Service Hot Water
Vent = str2fl([list_doe2[2][17],list_doe2[3][17],list_doe2[4][17]]) # [L/s/m2] Ventilation
Infil = str2fl([list_doe2[2][20],list_doe2[3][20],list_doe2[4][20]]) # Air Changes Per Hour (ACH) Infiltration
# Read location summary (Sheet 3)
file_doe_name_location = os.path.join("{}".format(DIR_DOE_PATH), "BLD{}".format(i+1),"BLD{}_LocationSummary.csv".format(i+1))
list_doe3 = read_csv(file_doe_name_location)
#(listof (listof 3 eras (listof 16 climate types)))
TypeWall = [list_doe3[3][4:20],list_doe3[14][4:20],list_doe3[25][4:20]] # Construction type
RvalWall = str2fl([list_doe3[4][4:20],list_doe3[15][4:20],list_doe3[26][4:20]]) # [m2*K/W] R-value
TypeRoof = [list_doe3[5][4:20],list_doe3[16][4:20],list_doe3[27][4:20]] # Construction type
RvalRoof = str2fl([list_doe3[6][4:20],list_doe3[17][4:20],list_doe3[28][4:20]]) # [m2*K/W] R-value
Uwindow = str2fl([list_doe3[7][4:20],list_doe3[18][4:20],list_doe3[29][4:20]]) # [W/m2*K] U-factor
SHGC = str2fl([list_doe3[8][4:20],list_doe3[19][4:20],list_doe3[30][4:20]]) # [-] coefficient
HVAC = str2fl([list_doe3[9][4:20],list_doe3[20][4:20],list_doe3[31][4:20]]) # [kW] Air Conditioning
HEAT = str2fl([list_doe3[10][4:20],list_doe3[21][4:20],list_doe3[32][4:20]]) # [kW] Heating
COP = str2fl([list_doe3[11][4:20],list_doe3[22][4:20],list_doe3[33][4:20]]) # [-] Air Conditioning COP
EffHeat = str2fl([list_doe3[12][4:20],list_doe3[23][4:20],list_doe3[34][4:20]]) # [%] Heating Efficiency
FanFlow = str2fl([list_doe3[13][4:20],list_doe3[24][4:20],list_doe3[35][4:20]]) # [m3/s] Fan Max Flow Rate
# Read Schedules (Sheet 4)
file_doe_name_schedules = os.path.join("{}".format(DIR_DOE_PATH), "BLD{}".format(i+1),"BLD{}_Schedules.csv".format(i+1))
list_doe4 = read_csv(file_doe_name_schedules)
#listof(listof weekday, sat, sun (list of 24 fractions)))
SchEquip = str2fl([list_doe4[1][6:30],list_doe4[2][6:30],list_doe4[3][6:30]]) # Equipment Schedule 24 hrs
SchLight = str2fl([list_doe4[4][6:30],list_doe4[5][6:30],list_doe4[6][6:30]]) # Light Schedule 24 hrs; Wkday=Sat=Sun=Hol
SchOcc = str2fl([list_doe4[7][6:30],list_doe4[8][6:30],list_doe4[9][6:30]]) # Occupancy Schedule 24 hrs
SetCool = str2fl([list_doe4[10][6:30],list_doe4[11][6:30],list_doe4[12][6:30]]) # Cooling Setpoint Schedule 24 hrs
SetHeat = str2fl([list_doe4[13][6:30],list_doe4[14][6:30],list_doe4[15][6:30]]) # Heating Setpoint Schedule 24 hrs; summer design
SchGas = str2fl([list_doe4[16][6:30],list_doe4[17][6:30],list_doe4[18][6:30]]) # Gas Equipment Schedule 24 hrs; wkday=sat
SchSWH = str2fl([list_doe4[19][6:30],list_doe4[20][6:30],list_doe4[21][6:30]]) # Solar Water Heating Schedule 24 hrs; wkday=summerdesign, sat=winterdesgin
for j in range(3):
# j = 3 built eras
#print"\tEra: {} @j={}".format(BUILTERA[j], j)
for k in range(16):
# k = 16 climate zones
#print "\tClimate zone: {} @k={}".format(ZONETYPE[k], k)
B = Building(
hCeiling[j], # floorHeight by era
1, # intHeatNight
1, # intHeatDay
0.1, # intHeatFRad
0.1, # intHeatFLat
Infil[j], # infil (ACH) by era
Vent[j]/1000., # vent (m^3/s/m^2) by era, converted from liters
glazing[j], # glazing ratio by era
Uwindow[j][k], # uValue by era, by climate type
SHGC[j][k], # SHGC, by era, by climate type
'AIR', # cooling condensation system type: AIR, WATER
COP[j][k], # cop by era, climate type
297, # coolSetpointDay = 24 C
297, # coolSetpointNight
293, # heatSetpointDay = 20 C
293, # heatSetpointNight
(HVAC[j][k]*1000.0)/AreaFloor[j], # coolCap converted to W/m2 by era, climate type
EffHeat[j][k], # heatEff by era, climate type
293) # initialTemp at 20 C
#Not defined in the constructor
B.heatCap = (HEAT[j][k]*1000.0)/AreaFloor[j] # heating Capacity converted to W/m2 by era, climate type
B.Type = BLDTYPE[i]
B.Era = BUILTERA[j]
B.Zone = ZONETYPE[k]
refDOE[i][j][k] = B
# Define wall, mass(floor), roof
# Reference from E+ for conductivity, thickness (reference below)
# Material: (thermalCond, volHeat = specific heat * density)
Concrete = Material (1.311, 836.8 * 2240,"Concrete")
Insulation = Material (0.049, 836.8 * 265.0, "Insulation")
Gypsum = Material (0.16, 830.0 * 784.9, "Gypsum")
Wood = Material (0.11, 1210.0 * 544.62, "Wood")
Stucco = Material(0.6918, 837.0 * 1858.0, "Stucco")
# Wall (1 in stucco, concrete, insulation, gypsum)
# Check TypWall by era, by climate
if TypeWall[j][k] == "MassWall":
#Construct wall based on R value of Wall from refDOE and properties defined above
# 1" stucco, 8" concrete, tbd insulation, 1/2" gypsum
Rbase = 0.271087 # R val based on stucco, concrete, gypsum
Rins = RvalWall[j][k] - Rbase #find insulation value
D_ins = Rins * Insulation.thermalCond # depth of ins from m2*K/W * W/m*K = m
if D_ins > 0.01:
thickness = [0.0254,0.0508,0.0508,0.0508,0.0508,D_ins,0.0127]
layers = [Stucco,Concrete,Concrete,Concrete,Concrete,Insulation,Gypsum]
else:
#if it's less then 1 cm don't include in layers
thickness = [0.0254,0.0508,0.0508,0.0508,0.0508,0.0127]
layers = [Stucco,Concrete,Concrete,Concrete,Concrete,Gypsum]
wall = Element(0.08,0.92,thickness,layers,0.,293.,0.,"MassWall")
# If mass wall, assume mass floor (4" concrete)
# Mass (assume 4" concrete);
alb = 0.2
emis = 0.9
thickness = [0.054,0.054]
concrete = Material (1.31, 2240.0*836.8)
mass = Element(alb,emis,thickness,[concrete,concrete],0,293,1,"MassFloor")
elif TypeWall[j][k] == "WoodFrame":
# 0.01m wood siding, tbd insulation, 1/2" gypsum
Rbase = 0.170284091 # based on wood siding, gypsum
Rins = RvalWall[j][k] - Rbase
D_ins = Rins * Insulation.thermalCond #depth of insulatino
if D_ins > 0.01:
thickness = [0.01,D_ins,0.0127]
layers = [Wood,Insulation,Gypsum]
else:
thickness = [0.01,0.0127]
layers = [Wood,Gypsum]
wall = Element(0.22,0.92,thickness,layers,0.,293.,0.,"WoodFrameWall")
# If wood frame wall, assume wooden floor
alb = 0.2
emis = 0.9
thickness = [0.05,0.05]
wood = Material(1.31, 2240.0*836.8)
mass = Element(alb,emis,thickness,[wood,wood],0.,293.,1.,"WoodFloor")
elif TypeWall[j][k] == "SteelFrame":
# 1" stucco, 8" concrete, tbd insulation, 1/2" gypsum
Rbase = 0.271087 # based on stucco, concrete, gypsum
Rins = RvalWall[j][k] - Rbase
D_ins = Rins * Insulation.thermalCond
if D_ins > 0.01:
thickness = [0.0254,0.0508,0.0508,0.0508,0.0508,D_ins,0.0127]
layers = [Stucco,Concrete,Concrete,Concrete,Concrete,Insulation,Gypsum]
else: # If insulation is too thin, assume no insulation
thickness = [0.0254,0.0508,0.0508,0.0508,0.0508,0.0127]
layers = [Stucco,Concrete,Concrete,Concrete,Concrete,Gypsum]
wall = Element(0.15,0.92,thickness,layers,0.,293.,0.,"SteelFrame")
# If mass wall, assume mass foor
# Mass (assume 4" concrete),
alb = 0.2
emis = 0.93
thickness = [0.05,0.05]
mass = Element(alb,emis,thickness,[Concrete,Concrete],0.,293.,1.,"MassFloor")
elif TypeWall[j][k] == "MetalWall":
# metal siding, insulation, 1/2" gypsum
alb = 0.2
emis = 0.9
D_ins = max((RvalWall[j][k] * Insulation.thermalCond)/2, 0.01) #use derived insul thickness or 0.01 based on max
thickness = [D_ins,D_ins,0.0127]
materials = [Insulation,Insulation,Gypsum]
wall = Element(alb,emis,thickness,materials,0,293,0,"MetalWall")
# Mass (assume 4" concrete);
alb = 0.2
emis = 0.9
thickness = [0.05, 0.05]
concrete = Material(1.31, 2240.0*836.8)
mass = Element(alb,emis,thickness,[concrete,concrete],0.,293.,1.,"MassFloor")
# Roof
if TypeRoof[j][k] == "IEAD": #Insulation Entirely Above Deck
# IEAD-> membrane, insulation, decking
alb = 0.2
emis = 0.93
D_ins = max(RvalRoof[j][k] * Insulation.thermalCond/2.,0.01);
roof = Element(alb,emis,[D_ins,D_ins],[Insulation,Insulation],0.,293.,0.,"IEAD")
elif TypeRoof[j][k] == "Attic":
# IEAD-> membrane, insulation, decking
alb = 0.2
emis = 0.9
D_ins = max(RvalRoof[j][k] * Insulation.thermalCond/2.,0.01)
roof = Element(alb,emis,[D_ins,D_ins],[Insulation,Insulation],0.,293.,0.,"Attic")
elif TypeRoof[j][k] == "MetalRoof":
# IEAD-> membrane, insulation, decking
alb = 0.2
emis = 0.9
D_ins = max(RvalRoof[j][k] * Insulation.thermalCond/2.,0.01)
roof = Element(alb,emis,[D_ins,D_ins],[Insulation,Insulation],0.,293.,0.,"MetalRoof")
# Define bulding energy model, set fraction of the urban floor space of this typology to zero
refBEM[i][j][k] = BEMDef(B, mass, wall, roof, 0.0)
refBEM[i][j][k].building.FanMax = FanFlow[j][k] # max fan flow rate (m^3/s) per DOE
Schedule[i][j][k] = SchDef()
Schedule[i][j][k].Elec = SchEquip # 3x24 matrix of schedule for fraction electricity (WD,Sat,Sun)
Schedule[i][j][k].Light = SchLight # 3x24 matrix of schedule for fraction light (WD,Sat,Sun)
Schedule[i][j][k].Gas = SchGas # 3x24 matrix of schedule for fraction gas (WD,Sat,Sun)
Schedule[i][j][k].Occ = SchOcc # 3x24 matrix of schedule for fraction occupancy (WD,Sat,Sun)
Schedule[i][j][k].Cool = SetCool # 3x24 matrix of schedule for fraction cooling temp (WD,Sat,Sun)
Schedule[i][j][k].Heat = SetHeat # 3x24 matrix of schedule for fraction heating temp (WD,Sat,Sun)
Schedule[i][j][k].SWH = SchSWH # 3x24 matrix of schedule for fraction SWH (WD,Sat,Sun
Schedule[i][j][k].Qelec = Elec[j] # W/m^2 (max) for electrical plug process
Schedule[i][j][k].Qlight = Light[j] # W/m^2 (max) for light
Schedule[i][j][k].Nocc = Occupant[j]/AreaFloor[j] # Person/m^2
Schedule[i][j][k].Qgas = Gas[j] # W/m^2 (max) for gas
Schedule[i][j][k].Vent = Vent[j]/1000.0 # m^3/m^2 per person
Schedule[i][j][k].Vswh = SHW[j]/AreaFloor[j] # litres per hour per m^2 of floor
# if not test serialize refDOE,refBEM,Schedule and store in resources
if serialize_output:
# create a binary file for serialized obj
pkl_file_path = os.path.join(DIR_CURR,'refdata','readDOE.pkl')
pickle_readDOE = open(pkl_file_path, 'wb')
# dump in ../resources
# Pickle objects, protocol 1 b/c binary file
pickle.dump(refDOE, pickle_readDOE,1)
pickle.dump(refBEM, pickle_readDOE,1)
pickle.dump(Schedule, pickle_readDOE,1)
pickle_readDOE.close()
return refDOE, refBEM, Schedule | Read csv files of DOE buildings
Sheet 1 = BuildingSummary
Sheet 2 = ZoneSummary
Sheet 3 = LocationSummary
Sheet 4 = Schedules
Note BLD8 & 10 = school
Then make matrix of ref data as nested nested lists [16, 3, 16]:
matrix refDOE = Building objs
matrix Schedule = SchDef objs
matrix refBEM (16,3,16) = BEMDef
where:
[16,3,16] is Type = 1-16, Era = 1-3, climate zone = 1-16
i.e.
Type: FullServiceRestaurant, Era: Pre80, Zone: 6A Minneapolis
Nested tree:
[TYPE_1:
ERA_1:
CLIMATE_ZONE_1
...
CLIMATE_ZONE_16
ERA_2:
CLIMATE_ZONE_1
...
CLIMATE_ZONE_16
...
ERA_3:
CLIMATE_ZONE_1
...
CLIMATE_ZONE_16] | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/readDOE.py#L79-L374 | [
"def read_csv(file_name_):\n # open csv file and read\n if os.path.exists(file_name_):\n if sys.version_info[0] >= 3:\n file_ = open(file_name_, \"r\", errors='ignore')\n else:\n file_ = open(file_name_, \"r\")\n\n gen_ = csv_reader(file_, delimiter=\",\")\n L = [r for r in gen_]\n file_.close()\n return L\n else:\n raise Exception(\"File name: '{}' does not exist.\".format(file_name_))\n",
"def str2fl(x):\n \"\"\"Recurses through lists and converts lists of string to float\n\n Args:\n x: string or list of strings\n \"\"\"\n def helper_to_fl(s_):\n \"\"\" deals with odd string imports converts to float\"\"\"\n if s_ == \"\":\n return \"null\"\n elif \",\" in s_:\n s_ = s_.replace(\",\", \"\")\n\n try:\n return float(s_)\n except:\n return (s_)\n\n fl_lst = []\n if isinstance(x[0], str): # Check if list of strings, then sent to conversion\n for xi in range(len(x)):\n fl_lst.append(helper_to_fl(x[xi]))\n elif isinstance(x[0], list): # Check if list of lists, then recurse\n for xi in range(len(x)):\n fl_lst.append(str2fl(x[xi]))\n else:\n return False\n\n return fl_lst\n"
] | from __future__ import division, print_function
try:
range = xrange
except NameError:
pass
import sys
import os
try:
import cPickle as pickle
except ImportError:
import pickle
from .building import Building
from .material import Material
from .element import Element
from .BEMDef import BEMDef
from .schdef import SchDef
from .utilities import read_csv, str2fl
# For debugging only
#import pprint
#import decimal
#pp = pprint.pprint
#dd = decimal.Decimal.from_float
DIR_CURR = os.path.abspath(os.path.dirname(__file__))
DIR_DOE_PATH = os.path.join(DIR_CURR,"..","resources","DOERefBuildings")
# Define standards: 16 buiding types, 3 built eras, 16 climate zones
# DOE Building Types
BLDTYPE = [
'FullServiceRestaurant', # 1
'Hospital', # 2
'LargeHotel', # 3
'LargeOffice', # 4
'MedOffice', # 5
'MidRiseApartment', # 6
'OutPatient', # 7
'PrimarySchool', # 8
'QuickServiceRestaurant', # 9
'SecondarySchool', # 10
'SmallHotel', # 11
'SmallOffice', # 12
'StandAloneRetail', # 13
'StripMall', # 14
'SuperMarket', # 15
'WareHouse'] # 16
BUILTERA = [
'Pre80', # 1
'Pst80', # 2
'New' # 3
]
ZONETYPE = [
'1A (Miami)', # 1
'2A (Houston)', # 2
'2B (Phoenix)', # 3
'3A (Atlanta)', # 4
'3B-CA (Los Angeles)', # 5
'3B (Las Vegas)', # 6
'3C (San Francisco)', # 7
'4A (Baltimore)', # 8
'4B (Albuquerque)', # 9
'4C (Seattle)', # 10
'5A (Chicago)', # 11
'5B (Boulder)', # 12
'6A (Minneapolis)', # 13
'6B (Helena)', # 14
'7 (Duluth)', # 15
'8 (Fairbanks)' # 16
]
if __name__ == "__main__":
# Set to True only if you want create new .pkls of DOE refs
# Use --serialize switch to serialize the readDOE data
if len(sys.argv)> 1 and sys.argv[1]=="--serialize":
refDOE, refBEM, Schedule = readDOE(True)
else:
refDOE, refBEM, Schedule = readDOE(False)
# Material ref from E+
# 1/2IN Gypsum, !- Name
# Smooth, !- Roughness
# 0.0127, !- Thickness {m}
# 0.1600, !- Conductivity {W/m-K}
# 784.9000, !- Density {kg/m3}
# 830.0000, !- Specific Heat {J/kg-K}
# 0.9000, !- Thermal Absorptance
# 0.9200, !- Solar Absorptance
# 0.9200; !- Visible Absorptance
#
# Material,
# 1IN Stucco, !- Name
# Smooth, !- Roughness
# 0.0253, !- Thickness
# 0.6918, !- Conductivity
# 1858.0000, !- Density
# 837.0000, !- Specific Heat
# 0.9000, !- Thermal Absorptance
# 0.9200, !- Solar Absorptance
# 0.9200; !- Visible Absorptance
#
# Material,
# 8IN CONCRETE HW, !- Name
# Rough, !- Roughness
# 0.2032, !- Thickness {m}
# 1.3110, !- Conductivity {W/m-K}
# 2240.0000, !- Density {kg/m3}
# 836.8000, !- Specific Heat {J/kg-K}
# 0.9000, !- Thermal Absorptance
# 0.7000, !- Solar Absorptance
# 0.7000; !- Visible Absorptance
#
# Material,
# Mass NonRes Wall Insulation, !- Name
# MediumRough, !- Roughness
# 0.0484268844343858, !- Thickness {m}
# 0.049, !- Conductivity {W/m-K}
# 265.0000, !- Density {kg/m3}
# 836.8000, !- Specific Heat {J/kg-K}
# 0.9000, !- Thermal Absorptance
# 0.7000, !- Solar Absorptance
# 0.7000; !- Visible Absorptance
#
# Material,
# Std Wood 6inch, !- Name
# MediumSmooth, !- Roughness
# 0.15, !- Thickness {m}
# 0.12, !- Conductivity {W/m-K}
# 540.0000, !- Density {kg/m3}
# 1210, !- Specific Heat {J/kg-K}
# 0.9000000, !- Thermal Absorptance
# 0.7000000, !- Solar Absorptance
# 0.7000000; !- Visible Absorptance! Common Materials
#
# Material,
# Wood Siding, !- Name
# MediumSmooth, !- Roughness
# 0.0100, !- Thickness {m}
# 0.1100, !- Conductivity {W/m-K}
# 544.6200, !- Density {kg/m3}
# 1210.0000, !- Specific Heat {J/kg-K}
# 0.9000, !- Thermal Absorptance
# 0.7800, !- Solar Absorptance
# 0.7800; !- Visible Absorptance
|
ladybug-tools/uwg | uwg/RSMDef.py | RSMDef.load_z_meso | python | def load_z_meso(self,z_meso_path):
self.z_meso = []
z_meso_file_path = os.path.join(z_meso_path, self.Z_MESO_FILE_NAME)
# Check if exists
if not os.path.exists(z_meso_file_path):
raise Exception("z_meso.txt file: '{}' does not exist.".format(uwg_param_file))
f = open(z_meso_file_path,'r')
for txtline in f:
z_ = float("".join(txtline.split())) # Strip all white spaces and change to float
self.z_meso.append(z_)
f.close() | Open the z_meso.txt file and return heights as list | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/RSMDef.py#L140-L154 | null | class RSMDef(object):
"""
% Rural Site & Vertical Diffusion Model (VDM)
% Calculates the vertical profiles of air temperature above the weather
% station per 'The uwg' (2012) Eq. 4, 5, 6.
properties
lat; % latitude (deg)
lon; % longitude (deg)
GMT; % GMT hour correction
height % average obstacle height (m)
z0r; % rural roughness length (m)
disp; % rural displacement length (m)
z; % vertical height (m)
dz; % vertical discretization (m)
nz0; % layer number at zmt (m)
nzref; % layer number at zref (m)
nzfor; % layer number at zfor (m)
nz10; % layer number at zmu (m)
nzi; % layer number at zi_d (m)
tempProf; % potential temperature profile at the rural site (K)
presProf; % pressure profile at the rural site (Pa)
tempRealProf; % real temperature profile at the rural site (K)
densityProfC; % density profile at the center of layers (kg m-3)
densityProfS; % density profile at the sides of layers (kg m-3)
windProf; % wind profile at the rural site (m s-1)
ublPres; % Average pressure at UBL (Pa)
end
"""
Z_MESO_FILE_NAME = "z_meso.txt"
def __init__(self,lat,lon,GMT,height,T_init,P_init,parameter,z_meso_path):
# defines self.z_meso property
self.load_z_meso(z_meso_path)
self.lat = lat # latitude (deg)
self.lon = lon # longitude (deg)
self.GMT = GMT # GMT hour correction
self.height = height # average obstacle height (m)
self.z0r = 0.1 * height # rural roughness length (m)
self.disp = 0.5 * height # rural displacement lenght (m)
# vertical grid at the rural site
self.z = [0 for x in range(len(self.z_meso)-1)] # Midht btwn each distance interval
self.dz = [0 for x in range(len(self.z_meso)-1)] # Distance betweeen each interval
for zi in range(len(self.z_meso)-1):
self.z[zi] = 0.5 * (self.z_meso[zi] + self.z_meso[zi+1])
self.dz[zi] = self.z_meso[zi+1] - self.z_meso[zi]
# Define initial booleans
ll = True
mm = True
nn = True
oo = True
pp = True
# Define self.nz0, self.nzref, self.nzfor, self.nz10, self.nzi
for iz in range(len(self.z_meso)-1):
# self.nz0: self.z index >= reference height for weather station
eq_th = self.is_near_zero(self.z[iz] - parameter.tempHeight)
if (eq_th == True or self.z[iz] > parameter.tempHeight) and ll==True:
self.nz0 = iz+1 # layer number at zmt (m)
ll = False
# self.nzref: self.z index >= reference inversion height
eq_rh = self.is_near_zero(self.z[iz] - parameter.refHeight)
if (eq_rh == True or self.z[iz] > parameter.refHeight) and mm==True:
self.nzref = iz+1 # layer number at zref (m)
mm = False
# self.nzfor: self.z index >= nighttime boundary layer height
eq_nh = self.is_near_zero(self.z[iz] - parameter.nightBLHeight)
if (eq_nh == True or self.z[iz] > parameter.nightBLHeight) and nn==True:
self.nzfor = iz+1 # layer number at zfor (m)
nn = False
# self.nz10: self.z index >= wind height
eq_wh = self.is_near_zero(self.z[iz] - parameter.windHeight)
if (eq_wh == True or self.z[iz] > parameter.windHeight) and oo==True:
self.nz10 = iz+1 # layer number at zmu (m)
oo = False
eq_dh = self.is_near_zero(self.z[iz] - parameter.dayBLHeight)
if (eq_dh == True or self.z[iz] > parameter.dayBLHeight) and pp==True:
self.nzi = iz+1 # layer number at zi_d (m)
pp = False
# Define temperature, pressure and density vertical profiles
self.tempProf = [T_init for x in range(self.nzref)]
self.presProf = [P_init for x in range(self.nzref)]
for iz in range(1,self.nzref):
self.presProf[iz] = (self.presProf[iz-1]**(parameter.r/parameter.cp) -\
parameter.g/parameter.cp * (P_init**(parameter.r/parameter.cp)) * (1./self.tempProf[iz] +\
1./self.tempProf[iz-1]) * 0.5 * self.dz[iz])**(1./(parameter.r/parameter.cp))
self.tempRealProf = [T_init for x in range(self.nzref)]
for iz in range(self.nzref):
self.tempRealProf[iz] = self.tempProf[iz] * (self.presProf[iz] / P_init)**(parameter.r/parameter.cp)
self.densityProfC = [None for x in range(self.nzref)]
for iz in range(self.nzref):
self.densityProfC[iz] = self.presProf[iz] / parameter.r / self.tempRealProf[iz]
self.densityProfS = [self.densityProfC[0] for x in range(self.nzref+1)]
for iz in range(1,self.nzref):
self.densityProfS[iz] = (self.densityProfC[iz] * self.dz[iz-1] +\
self.densityProfC[iz-1] * self.dz[iz]) / (self.dz[iz-1]+self.dz[iz])
self.densityProfS[self.nzref] = self.densityProfC[self.nzref-1]
self.windProf = [1 for x in range(self.nzref)]
def __repr__(self):
return "RSM: obstacle ht = {}m, surface roughness length = {}m, displacement length = {}m".format(
self.height,
self.z0r, # rural roughness length (m)
self.disp # rural displacement lenght (m)
)
def is_near_zero(self,num,eps=1e-16):
return abs(float(num)) < eps
# Ref: The uwg (2012), Eq. (4)
def VDM(self,forc,rural,parameter,simTime):
self.tempProf[0] = forc.temp # Lower boundary condition
# compute pressure profile
for iz in reversed(list(range(self.nzref))[1:]):
self.presProf[iz-1] = (math.pow(self.presProf[iz],parameter.r/parameter.cp) + \
parameter.g/parameter.cp*(math.pow(forc.pres,parameter.r/parameter.cp)) * \
(1./self.tempProf[iz] + 1./self.tempProf[iz-1]) * \
0.5 * self.dz[iz])**(1./(parameter.r/parameter.cp))
# compute the real temperature profile
for iz in range(self.nzref):
self.tempRealProf[iz]= self.tempProf[iz] * \
(self.presProf[iz]/forc.pres)**(parameter.r/parameter.cp)
# compute the density profile
for iz in range(self.nzref):
self.densityProfC[iz] = self.presProf[iz]/parameter.r/self.tempRealProf[iz]
self.densityProfS[0] = self.densityProfC[0]
for iz in range(1,self.nzref):
self.densityProfS[iz] = (self.densityProfC[iz] * self.dz[iz-1] + \
self.densityProfC[iz-1] * self.dz[iz])/(self.dz[iz-1] + self.dz[iz])
self.densityProfS[self.nzref] = self.densityProfC[self.nzref-1]
# Ref: The uwg (2012), Eq. (5)
# compute diffusion coefficient
cd,ustarRur = self.DiffusionCoefficient(self.densityProfC[0], \
self.z, self.dz, self.z0r, self.disp, \
self.tempProf[0], rural.sens, self.nzref, forc.wind, \
self.tempProf, parameter)
# solve diffusion equation
self.tempProf = self.DiffusionEquation(self.nzref,simTime.dt,\
self.tempProf,self.densityProfC,self.densityProfS,cd,self.dz)
# compute wind profile
# N.B In Matlab, negative values are converted to complex values.
# log(-x) = log(x) + log(-1) = log(x) + i*pi
# Python will throw an exception. Negative value occurs here if
# VDM is run for average obstacle height ~ 4m.
for iz in range(self.nzref):
self.windProf[iz] = ustarRur/parameter.vk*\
math.log((self.z[iz]-self.disp)/self.z0r)
# Average pressure
self.ublPres = 0.
for iz in range(self.nzfor):
self.ublPres = self.ublPres + \
self.presProf[iz]*self.dz[iz]/(self.z[self.nzref-1]+self.dz[self.nzref-1]/2.)
def DiffusionEquation(self,nz,dt,co,da,daz,cd,dz):
cddz = [0 for i in range(nz+2)]
a = [[0 for j in range(3)] for i in range(nz)]
c = [0 for i in range(nz)]
#--------------------------------------------------------------------------
cddz[0] = daz[0]*cd[0]/dz[0]
for iz in range(1,nz):
cddz[iz] = 2.*daz[iz]*cd[iz]/(dz[iz]+dz[iz-1])
cddz[nz] = daz[nz]*cd[nz]/dz[nz]
#--------------------------------------------------------------------------
a[0][0] = 0.
a[0][1] = 1.
a[0][2] = 0.
c[0] = co[0]
for iz in range(1,nz-1):
dzv = dz[iz]
a[iz][0]=-cddz[iz]*dt/dzv/da[iz]
a[iz][1]=1+dt*(cddz[iz]+cddz[iz+1])/dzv/da[iz]
a[iz][2]=-cddz[iz+1]*dt/dzv/da[iz]
c[iz]=co[iz]
a[nz-1][0]=-1.
a[nz-1][1]=1.
a[nz-1][2]=0.
c[nz-1]=0.
#--------------------------------------------------------------------------
co = self.invert(nz,a,c)
return co
def DiffusionCoefficient(self,rho,z,dz,z0,disp,tempRur,heatRur,nz,uref,th,parameter):
# Initialization
Kt = [0 for x in range(nz+1)]
ws = [0 for x in range(nz)]
te = [0 for x in range(nz)]
# Friction velocity (Louis 1979)
ustar = parameter.vk * uref/math.log((10.-disp)/z0)
# Monin-Obukhov length
lengthRur = max(-rho*parameter.cp*ustar**3*tempRur/parameter.vk/parameter.g/heatRur,-50.)
# Unstable conditions
if heatRur > 1e-2:
# Convective velocity scale
wstar = (parameter.g*heatRur*parameter.dayBLHeight/rho/parameter.cp/tempRur)**(1/3.)
# Wind profile function
phi_m = (1-8.*0.1*parameter.dayBLHeight/lengthRur)**(-1./3.)
for iz in range(nz):
# Mixed-layer velocity scale
ws[iz] = (ustar**3 + phi_m*parameter.vk*wstar**3*z[iz]/parameter.dayBLHeight)**(1/3.)
# TKE approximation
te[iz] = max(ws[iz]**2., 0.01)
else: # Stable and neutral conditions
for iz in range(nz):
# TKE approximation
te[iz] = max(ustar**2.,0.01)
# lenght scales (l_up, l_down, l_k, l_eps)
self.dlu, self.dld = self.DissipationBougeault(parameter.g,nz,z,dz,te,th)
self.dld,dls,dlk = self.LengthBougeault(nz,self.dld,self.dlu,z)
# Boundary-layer diffusion coefficient
for iz in range(nz):
Kt[iz] = 0.4*dlk[iz]*math.sqrt(te[iz])
Kt[nz] = Kt[nz-1]
return Kt, ustar
def DissipationBougeault(self,g,nz,z,dz,te,pt):
# Note on translation from UWG_Matlab
# list length (i.e nz) != list indexing (i.e dlu[0] in python
# wherease in matlab it is
dlu = [0 for x in range(nz)]
dld = [0 for x in range(nz)]
for iz in range(nz):
zup=0.
dlu[iz] = z[nz] - z[iz] - dz[iz]/2.
zzz=0.
zup_inf=0.
beta=g/pt[iz]
for izz in range(iz,nz-1):
dzt=(dz[izz+1]+dz[izz])/2.
zup=zup-beta*pt[iz]*dzt
zup=zup+beta*(pt[izz+1]+pt[izz])*dzt/2.
zzz=zzz+dzt
if (te[iz]<zup) and ((te[iz]>zup_inf) or self.is_near_zero(te[iz]-zup_inf)):
bbb=(pt[izz+1]-pt[izz])/dzt
if not self.is_near_zero(bbb-0.):
tl=(-beta*(pt[izz]-pt[iz])+ \
math.sqrt( max(0.,(beta*(pt[izz]-pt[iz]))**2.+ \
2.*bbb*beta*(te[iz]-zup_inf))))/bbb/beta
else:
tl=(te[iz]-zup_inf)/(beta*(pt[izz]-pt[iz]))
dlu[iz]=max(1.,zzz-dzt+tl)
zup_inf=zup
zdo=0.
zdo_sup=0.
dld[iz]=z[iz]+dz[iz]/2.
zzz=0.
for izz in range(iz,0,-1):
dzt=(dz[izz-1]+dz[izz])/2.
zdo=zdo+beta*pt[iz]*dzt
zdo=zdo-beta*(pt[izz-1]+pt[izz])*dzt/2.
zzz=zzz+dzt
if (te[iz]<zdo) and ((te[iz]>zdo_sup) or self.is_near_zero(te[iz]-zdo_sup)):
bbb=(pt[izz]-pt[izz-1])/dzt
if not self.is_near_zero(bbb-0.):
tl=(beta*(pt[izz]-pt[iz])+ \
math.sqrt( max(0.,(beta*(pt[izz]-pt[iz]))**2.+ \
2.*bbb*beta*(te[iz]-zdo_sup))))/bbb/beta
else:
tl=(te[iz]-zdo_sup)/(beta*(pt[izz]-pt[iz]))
dld[iz]=max(1.,zzz-dzt+tl)
zdo_sup=zdo
return dlu,dld
def LengthBougeault(self,nz,dld,dlu,z):
dlg = [0 for x in range(nz)]
dls = [0 for x in range(nz)]
dlk = [0 for x in range(nz)]
for iz in range(nz):
dlg[iz] = (z[iz]+z[iz+1])/2.
for iz in range(nz):
dld[iz] = min(dld[iz], dlg[iz])
dls[iz] = math.sqrt(dlu[iz]*dld[iz])
dlk[iz] = min(dlu[iz],dld[iz])
return dld,dls,dlk
def invert(self,nz,A,C):
"""
Inversion and resolution of a tridiagonal matrix
A X = C
Input:
nz number of layers
a(*,1) lower diagonal (Ai,i-1)
a(*,2) principal diagonal (Ai,i)
a(*,3) upper diagonal (Ai,i+1)
c
Output
x results
"""
X = [0 for i in range(nz)]
for i in reversed(range(nz-1)):
C[i] = C[i] - A[i][2] * C[i+1]/A[i+1][1]
A[i][1] = A[i][1] - A[i][2] * A[i+1][0]/A[i+1][1]
for i in range(1,nz,1):
C[i] = C[i] - A[i][0] * C[i-1]/A[i-1][1]
for i in range(nz):
X[i] = C[i]/A[i][1]
return X
|
ladybug-tools/uwg | uwg/urbflux.py | urbflux | python | def urbflux(UCM, UBL, BEM, forc, parameter, simTime, RSM):
T_can = UCM.canTemp
Cp = parameter.cp
UCM.Q_roof = 0.
sigma = 5.67e-8 # Stephan-Boltzman constant
UCM.roofTemp = 0. # Average urban roof temperature
UCM.wallTemp = 0. # Average urban wall temperature
for j in range(len(BEM)):
# Building energy model
BEM[j].building.BEMCalc(UCM, BEM[j], forc, parameter, simTime)
BEM[j].ElecTotal = BEM[j].building.ElecTotal * BEM[j].fl_area # W m-2
# Update roof infra calc
e_roof = BEM[j].roof.emissivity
T_roof = BEM[j].roof.layerTemp[0]
BEM[j].roof.infra = e_roof * (forc.infra - sigma * T_roof**4.)
# update wall infra calc (road done later)
e_wall = BEM[j].wall.emissivity
T_wall = BEM[j].wall.layerTemp[0]
# calculates the infrared radiation for wall, taking into account radiation exchange from road
_infra_road_, BEM[j].wall.infra = infracalcs(UCM, forc, UCM.road.emissivity, e_wall, UCM.roadTemp, T_wall)
# Update element temperatures
BEM[j].mass.layerTemp = BEM[j].mass.Conduction(simTime.dt, BEM[j].building.fluxMass,1.,0.,BEM[j].building.fluxMass)
BEM[j].roof.SurfFlux(forc,parameter,simTime,UCM.canHum,T_can,max(forc.wind,UCM.canWind),1.,BEM[j].building.fluxRoof)
BEM[j].wall.SurfFlux(forc,parameter,simTime,UCM.canHum,T_can,UCM.canWind,1.,BEM[j].building.fluxWall)
# Note the average wall & roof temperature
UCM.wallTemp = UCM.wallTemp + BEM[j].frac*BEM[j].wall.layerTemp[0]
UCM.roofTemp = UCM.roofTemp + BEM[j].frac*BEM[j].roof.layerTemp[0]
# Update road infra calc (assume walls have similar emissivity, so use the last one)
UCM.road.infra, _wall_infra = infracalcs(UCM,forc,UCM.road.emissivity,e_wall,UCM.roadTemp,UCM.wallTemp)
UCM.road.SurfFlux(forc,parameter,simTime,UCM.canHum,T_can,UCM.canWind,2.,0.)
UCM.roadTemp = UCM.road.layerTemp[0]
# Sensible & latent heat flux (total)
if UCM.latHeat != None:
UCM.latHeat = UCM.latHeat + UCM.latAnthrop + UCM.treeLatHeat + UCM.road.lat*(1.-UCM.bldDensity)
# ---------------------------------------------------------------------
# Advective heat flux to UBL from VDM
#
# Note: UWG_Matlab code here is modified to compensate for rounding errors
# that occur when recursively adding forDens, intAdv1, and intAdv2.
# This causes issues in the UBL.advHeat calculatiuon when large (1e5)
# numbers are subtracted to produce small numbers (1e-10) that can
# differ from equivalent matlab calculations by a factor of 2.
# Values this small are ~ 0, but for consistency's sake Kahan Summation
# algorithm is applied to keep margin of difference from UWG_Matlab low.
# ---------------------------------------------------------------------
forDens = 0.0
intAdv1 = 0.0
intAdv2 = 0.0
# c1 & c2 stores values truncated by floating point rounding for values < 10^-16
c1 = 0.0
c2 = 0.0
c3 = 0.0
for iz in range(RSM.nzfor):
# At c loss of precision at at low order of magnitude, that we need in UBL.advHeat calc
# Algebraically t is 0, but with floating pt numbers c will accumulate truncated values
y = RSM.densityProfC[iz]*RSM.dz[iz]/(RSM.z[RSM.nzfor-1] + RSM.dz[RSM.nzfor-1]/2.)
t = forDens + y
c1 += (t - forDens) - y
forDens = t
y = RSM.windProf[iz]*RSM.tempProf[iz]*RSM.dz[iz]
t = intAdv1 + y
c2 += (t - intAdv1) - y
intAdv1 = t
y = RSM.windProf[iz]*RSM.dz[iz]
t = intAdv2 + y
c3 += (t - intAdv2) - y
intAdv2 = t
# Add the truncated values back
forDens -= c1
intAdv1 -= c2
intAdv2 -= c3
UBL.advHeat = UBL.paralLength*Cp*forDens*(intAdv1-(UBL.ublTemp*intAdv2))/UBL.urbArea
# ---------------------------------------------------------------------
# Convective heat flux to UBL from UCM (see Appendix - Bueno (2014))
# ---------------------------------------------------------------------
zrUrb = 2*UCM.bldHeight
zref = RSM.z[RSM.nzref-1] # Reference height
# Reference wind speed & canyon air density
windUrb = forc.wind*log(zref/RSM.z0r)/log(parameter.windHeight/RSM.z0r)*\
log(zrUrb/UCM.z0u)/log(zref/UCM.z0u)
dens = forc.pres/(1000*0.287042*T_can*(1.+1.607858*UCM.canHum))
# Friction velocity
UCM.ustar = parameter.vk*windUrb/log((zrUrb-UCM.l_disp)/UCM.z0u)
# Convective scaling velocity
wstar = (parameter.g*max(UCM.sensHeat,0.0)*zref/dens/Cp/T_can)**(1/3.)
UCM.ustarMod = max(UCM.ustar,wstar) # Modified friction velocity
UCM.uExch = parameter.exCoeff*UCM.ustarMod # Exchange velocity
# Canyon wind speed, Eq. 27 Chp. 3 Hanna and Britter, 2002
# assuming CD = 1 and lambda_f = verToHor/4
UCM.canWind = UCM.ustarMod*(UCM.verToHor/8.)**(-1/2.)
# Canyon turbulent velocities
UCM.turbU = 2.4*UCM.ustarMod
UCM.turbV = 1.9*UCM.ustarMod
UCM.turbW = 1.3*UCM.ustarMod
# Urban wind profile
for iz in range(RSM.nzref):
UCM.windProf.append(UCM.ustar/parameter.vk*\
log((RSM.z[iz]+UCM.bldHeight-UCM.l_disp)/UCM.z0u))
return UCM,UBL,BEM | Calculate the surface heat fluxes
Output: [UCM,UBL,BEM] | train | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/urbflux.py#L12-L136 | [
"def infracalcs(UCM,forc,e_road,e_wall,T_road,T_wall):\n # Calculate IR surface flux\n sigma = 5.67e-8 # Stephen-Boltzman const\n road_wall_conf = (1. - UCM.roadConf) # configuration factor (view factor) for road to wall\n wall_road_conf = UCM.wallConf # wall to road VF same as wall-sky configuration factors (sky view factor)\n\n # Calculate radiation of unshaded road, accounting for radiation exchange from wall\n infra_road = e_road * UCM.roadConf * (1.-UCM.roadShad) * (forc.infra - sigma*T_road**4.) + (1.-UCM.roadShad) * e_wall * e_road * sigma * road_wall_conf * (T_wall**4.-T_road**4.)\n # Calculate radiation of wall, accounting for radiation exchange from unshaded road\n infra_wall = e_wall * UCM.wallConf * (forc.infra - sigma*T_wall**4.) + (1.-UCM.roadShad) * e_wall * e_road * sigma * wall_road_conf * (T_road**4.-T_wall**4.)\n\n return infra_road, infra_wall\n"
] | from __future__ import division
try:
range = xrange
except NameError:
pass
from .infracalcs import infracalcs
from math import log
|
makinacorpus/landez | landez/sources.py | MBTilesReader.find_coverage | python | def find_coverage(self, zoom):
# Find a group of adjacent available tiles at this zoom level
rows = self._query('''SELECT tile_column, tile_row FROM tiles
WHERE zoom_level=?
ORDER BY tile_column, tile_row;''', (zoom,))
t = rows.fetchone()
xmin, ymin = t
previous = t
while t and t[0] - previous[0] <= 1:
# adjacent, go on
previous = t
t = rows.fetchone()
xmax, ymax = previous
# Transform (xmin, ymin) (xmax, ymax) to pixels
S = self.tilesize
bottomleft = (xmin * S, (ymax + 1) * S)
topright = ((xmax + 1) * S, ymin * S)
# Convert center to (lon, lat)
proj = GoogleProjection(S, [zoom]) # WGS84
return proj.unproject_pixels(bottomleft, zoom) + proj.unproject_pixels(topright, zoom) | Returns the bounding box (minx, miny, maxx, maxy) of an adjacent
group of tiles at this zoom level. | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/sources.py#L128-L151 | [
"def unproject_pixels(self,px,zoom):\n e = self.zc[zoom]\n f = (px[0] - e[0])/self.Bc[zoom]\n g = (px[1] - e[1])/-self.Cc[zoom]\n h = RAD_TO_DEG * ( 2 * atan(exp(g)) - 0.5 * pi)\n if self.scheme == 'tms':\n h = - h\n return (f,h)\n",
"def _query(self, sql, *args):\n \"\"\" Executes the specified `sql` query and returns the cursor \"\"\"\n if not self._con:\n logger.debug(_(\"Open MBTiles file '%s'\") % self.filename)\n self._con = sqlite3.connect(self.filename)\n self._cur = self._con.cursor()\n sql = ' '.join(sql.split())\n logger.debug(_(\"Execute query '%s' %s\") % (sql, args))\n try:\n self._cur.execute(sql, *args)\n except (sqlite3.OperationalError, sqlite3.DatabaseError)as e:\n raise InvalidFormatError(_(\"%s while reading %s\") % (e, self.filename))\n return self._cur\n"
] | class MBTilesReader(TileSource):
def __init__(self, filename, tilesize=None):
super(MBTilesReader, self).__init__(tilesize)
self.filename = filename
self.basename = os.path.basename(self.filename)
self._con = None
self._cur = None
def _query(self, sql, *args):
""" Executes the specified `sql` query and returns the cursor """
if not self._con:
logger.debug(_("Open MBTiles file '%s'") % self.filename)
self._con = sqlite3.connect(self.filename)
self._cur = self._con.cursor()
sql = ' '.join(sql.split())
logger.debug(_("Execute query '%s' %s") % (sql, args))
try:
self._cur.execute(sql, *args)
except (sqlite3.OperationalError, sqlite3.DatabaseError)as e:
raise InvalidFormatError(_("%s while reading %s") % (e, self.filename))
return self._cur
def metadata(self):
rows = self._query('SELECT name, value FROM metadata')
rows = [(row[0], row[1]) for row in rows]
return dict(rows)
def zoomlevels(self):
rows = self._query('SELECT DISTINCT(zoom_level) FROM tiles ORDER BY zoom_level')
return [int(row[0]) for row in rows]
def tile(self, z, x, y):
logger.debug(_("Extract tile %s") % ((z, x, y),))
tms_y = flip_y(int(y), int(z))
rows = self._query('''SELECT tile_data FROM tiles
WHERE zoom_level=? AND tile_column=? AND tile_row=?;''', (z, x, tms_y))
t = rows.fetchone()
if not t:
raise ExtractionError(_("Could not extract tile %s from %s") % ((z, x, y), self.filename))
return t[0]
def grid(self, z, x, y, callback=None):
tms_y = flip_y(int(y), int(z))
rows = self._query('''SELECT grid FROM grids
WHERE zoom_level=? AND tile_column=? AND tile_row=?;''', (z, x, tms_y))
t = rows.fetchone()
if not t:
raise ExtractionError(_("Could not extract grid %s from %s") % ((z, x, y), self.filename))
grid_json = json.loads(zlib.decompress(t[0]))
rows = self._query('''SELECT key_name, key_json FROM grid_data
WHERE zoom_level=? AND tile_column=? AND tile_row=?;''', (z, x, tms_y))
# join up with the grid 'data' which is in pieces when stored in mbtiles file
grid_json['data'] = {}
grid_data = rows.fetchone()
while grid_data:
grid_json['data'][grid_data[0]] = json.loads(grid_data[1])
grid_data = rows.fetchone()
serialized = json.dumps(grid_json)
if callback is not None:
return '%s(%s);' % (callback, serialized)
return serialized
|
makinacorpus/landez | landez/sources.py | TileDownloader.tile | python | def tile(self, z, x, y):
logger.debug(_("Download tile %s") % ((z, x, y),))
# Render each keyword in URL ({s}, {x}, {y}, {z}, {size} ... )
size = self.tilesize
s = self.tiles_subdomains[(x + y) % len(self.tiles_subdomains)];
try:
url = self.tiles_url.format(**locals())
except KeyError as e:
raise DownloadError(_("Unknown keyword %s in URL") % e)
logger.debug(_("Retrieve tile at %s") % url)
r = DOWNLOAD_RETRIES
sleeptime = 1
while r > 0:
try:
request = requests.get(url, headers=self.headers)
if request.status_code == 200:
return request.content
raise DownloadError(_("Status code : %s, url : %s") % (request.status_code, url))
except requests.exceptions.ConnectionError as e:
logger.debug(_("Download error, retry (%s left). (%s)") % (r, e))
r -= 1
time.sleep(sleeptime)
# progressivly sleep longer to wait for this tile
if (sleeptime <= 10) and (r % 2 == 0):
sleeptime += 1 # increase wait
raise DownloadError(_("Cannot download URL %s") % url) | Download the specified tile from `tiles_url` | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/sources.py#L163-L192 | null | class TileDownloader(TileSource):
def __init__(self, url, headers=None, subdomains=None, tilesize=None):
super(TileDownloader, self).__init__(tilesize)
self.tiles_url = url
self.tiles_subdomains = subdomains or ['a', 'b', 'c']
parsed = urlparse(self.tiles_url)
self.basename = parsed.netloc+parsed.path
self.headers = headers or {}
|
makinacorpus/landez | landez/sources.py | MapnikRenderer.tile | python | def tile(self, z, x, y):
logger.debug(_("Render tile %s") % ((z, x, y),))
proj = GoogleProjection(self.tilesize, [z])
return self.render(proj.tile_bbox((z, x, y))) | Render the specified tile with Mapnik | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/sources.py#L247-L253 | [
"def tile_bbox(self, z_x_y):\n \"\"\"\n Returns the WGS84 bbox of the specified tile\n \"\"\"\n (z, x, y) = z_x_y\n topleft = (x * self.tilesize, (y + 1) * self.tilesize)\n bottomright = ((x + 1) * self.tilesize, y * self.tilesize)\n nw = self.unproject_pixels(topleft, z)\n se = self.unproject_pixels(bottomright, z)\n return nw + se\n",
"def render(self, bbox, width=None, height=None):\n \"\"\"\n Render the specified tile with Mapnik\n \"\"\"\n width = width or self.tilesize\n height = height or self.tilesize\n self._prepare_rendering(bbox, width=width, height=height)\n\n # Render image with default Agg renderer\n tmpfile = NamedTemporaryFile(delete=False)\n im = mapnik.Image(width, height)\n mapnik.render(self._mapnik, im)\n im.save(tmpfile.name, 'png256') # TODO: mapnik output only to file?\n tmpfile.close()\n content = open(tmpfile.name, 'rb').read()\n os.unlink(tmpfile.name)\n return content\n"
] | class MapnikRenderer(TileSource):
def __init__(self, stylefile, tilesize=None):
super(MapnikRenderer, self).__init__(tilesize)
assert has_mapnik, _("Cannot render tiles without mapnik !")
self.stylefile = stylefile
self.basename = os.path.basename(self.stylefile)
self._mapnik = None
self._prj = None
def _prepare_rendering(self, bbox, width=None, height=None):
if not self._mapnik:
self._mapnik = mapnik.Map(width, height)
# Load style XML
mapnik.load_map(self._mapnik, self.stylefile, True)
# Obtain <Map> projection
self._prj = mapnik.Projection(self._mapnik.srs)
# Convert to map projection
assert len(bbox) == 4, _("Provide a bounding box tuple (minx, miny, maxx, maxy)")
c0 = self._prj.forward(mapnik.Coord(bbox[0], bbox[1]))
c1 = self._prj.forward(mapnik.Coord(bbox[2], bbox[3]))
# Bounding box for the tile
bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y)
self._mapnik.resize(width, height)
self._mapnik.zoom_to_box(bbox)
self._mapnik.buffer_size = 128
def render(self, bbox, width=None, height=None):
"""
Render the specified tile with Mapnik
"""
width = width or self.tilesize
height = height or self.tilesize
self._prepare_rendering(bbox, width=width, height=height)
# Render image with default Agg renderer
tmpfile = NamedTemporaryFile(delete=False)
im = mapnik.Image(width, height)
mapnik.render(self._mapnik, im)
im.save(tmpfile.name, 'png256') # TODO: mapnik output only to file?
tmpfile.close()
content = open(tmpfile.name, 'rb').read()
os.unlink(tmpfile.name)
return content
def grid(self, z, x, y, fields, layer):
"""
Render the specified grid with Mapnik
"""
logger.debug(_("Render grid %s") % ((z, x, y),))
proj = GoogleProjection(self.tilesize, [z])
return self.render_grid(proj.tile_bbox((z, x, y)), fields, layer)
def render_grid(self, bbox, grid_fields, layer, width=None, height=None):
"""
Render the specified grid with Mapnik
"""
width = width or self.tilesize
height = height or self.tilesize
self._prepare_rendering(bbox, width=width, height=height)
grid = mapnik.Grid(width, height)
mapnik.render_layer(self._mapnik, grid, layer=layer, fields=grid_fields)
grid = grid.encode()
return json.dumps(grid)
|
makinacorpus/landez | landez/sources.py | MapnikRenderer.render | python | def render(self, bbox, width=None, height=None):
width = width or self.tilesize
height = height or self.tilesize
self._prepare_rendering(bbox, width=width, height=height)
# Render image with default Agg renderer
tmpfile = NamedTemporaryFile(delete=False)
im = mapnik.Image(width, height)
mapnik.render(self._mapnik, im)
im.save(tmpfile.name, 'png256') # TODO: mapnik output only to file?
tmpfile.close()
content = open(tmpfile.name, 'rb').read()
os.unlink(tmpfile.name)
return content | Render the specified tile with Mapnik | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/sources.py#L274-L290 | [
"def _prepare_rendering(self, bbox, width=None, height=None):\n if not self._mapnik:\n self._mapnik = mapnik.Map(width, height)\n # Load style XML\n mapnik.load_map(self._mapnik, self.stylefile, True)\n # Obtain <Map> projection\n self._prj = mapnik.Projection(self._mapnik.srs)\n\n # Convert to map projection\n assert len(bbox) == 4, _(\"Provide a bounding box tuple (minx, miny, maxx, maxy)\")\n c0 = self._prj.forward(mapnik.Coord(bbox[0], bbox[1]))\n c1 = self._prj.forward(mapnik.Coord(bbox[2], bbox[3]))\n\n # Bounding box for the tile\n bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y)\n self._mapnik.resize(width, height)\n self._mapnik.zoom_to_box(bbox)\n self._mapnik.buffer_size = 128\n"
] | class MapnikRenderer(TileSource):
def __init__(self, stylefile, tilesize=None):
super(MapnikRenderer, self).__init__(tilesize)
assert has_mapnik, _("Cannot render tiles without mapnik !")
self.stylefile = stylefile
self.basename = os.path.basename(self.stylefile)
self._mapnik = None
self._prj = None
def tile(self, z, x, y):
"""
Render the specified tile with Mapnik
"""
logger.debug(_("Render tile %s") % ((z, x, y),))
proj = GoogleProjection(self.tilesize, [z])
return self.render(proj.tile_bbox((z, x, y)))
def _prepare_rendering(self, bbox, width=None, height=None):
if not self._mapnik:
self._mapnik = mapnik.Map(width, height)
# Load style XML
mapnik.load_map(self._mapnik, self.stylefile, True)
# Obtain <Map> projection
self._prj = mapnik.Projection(self._mapnik.srs)
# Convert to map projection
assert len(bbox) == 4, _("Provide a bounding box tuple (minx, miny, maxx, maxy)")
c0 = self._prj.forward(mapnik.Coord(bbox[0], bbox[1]))
c1 = self._prj.forward(mapnik.Coord(bbox[2], bbox[3]))
# Bounding box for the tile
bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y)
self._mapnik.resize(width, height)
self._mapnik.zoom_to_box(bbox)
self._mapnik.buffer_size = 128
def grid(self, z, x, y, fields, layer):
"""
Render the specified grid with Mapnik
"""
logger.debug(_("Render grid %s") % ((z, x, y),))
proj = GoogleProjection(self.tilesize, [z])
return self.render_grid(proj.tile_bbox((z, x, y)), fields, layer)
def render_grid(self, bbox, grid_fields, layer, width=None, height=None):
"""
Render the specified grid with Mapnik
"""
width = width or self.tilesize
height = height or self.tilesize
self._prepare_rendering(bbox, width=width, height=height)
grid = mapnik.Grid(width, height)
mapnik.render_layer(self._mapnik, grid, layer=layer, fields=grid_fields)
grid = grid.encode()
return json.dumps(grid)
|
makinacorpus/landez | landez/sources.py | MapnikRenderer.grid | python | def grid(self, z, x, y, fields, layer):
logger.debug(_("Render grid %s") % ((z, x, y),))
proj = GoogleProjection(self.tilesize, [z])
return self.render_grid(proj.tile_bbox((z, x, y)), fields, layer) | Render the specified grid with Mapnik | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/sources.py#L292-L298 | [
"def tile_bbox(self, z_x_y):\n \"\"\"\n Returns the WGS84 bbox of the specified tile\n \"\"\"\n (z, x, y) = z_x_y\n topleft = (x * self.tilesize, (y + 1) * self.tilesize)\n bottomright = ((x + 1) * self.tilesize, y * self.tilesize)\n nw = self.unproject_pixels(topleft, z)\n se = self.unproject_pixels(bottomright, z)\n return nw + se\n",
"def render_grid(self, bbox, grid_fields, layer, width=None, height=None):\n \"\"\"\n Render the specified grid with Mapnik\n \"\"\"\n width = width or self.tilesize\n height = height or self.tilesize\n self._prepare_rendering(bbox, width=width, height=height)\n\n grid = mapnik.Grid(width, height)\n mapnik.render_layer(self._mapnik, grid, layer=layer, fields=grid_fields)\n grid = grid.encode()\n return json.dumps(grid)\n"
] | class MapnikRenderer(TileSource):
def __init__(self, stylefile, tilesize=None):
super(MapnikRenderer, self).__init__(tilesize)
assert has_mapnik, _("Cannot render tiles without mapnik !")
self.stylefile = stylefile
self.basename = os.path.basename(self.stylefile)
self._mapnik = None
self._prj = None
def tile(self, z, x, y):
"""
Render the specified tile with Mapnik
"""
logger.debug(_("Render tile %s") % ((z, x, y),))
proj = GoogleProjection(self.tilesize, [z])
return self.render(proj.tile_bbox((z, x, y)))
def _prepare_rendering(self, bbox, width=None, height=None):
if not self._mapnik:
self._mapnik = mapnik.Map(width, height)
# Load style XML
mapnik.load_map(self._mapnik, self.stylefile, True)
# Obtain <Map> projection
self._prj = mapnik.Projection(self._mapnik.srs)
# Convert to map projection
assert len(bbox) == 4, _("Provide a bounding box tuple (minx, miny, maxx, maxy)")
c0 = self._prj.forward(mapnik.Coord(bbox[0], bbox[1]))
c1 = self._prj.forward(mapnik.Coord(bbox[2], bbox[3]))
# Bounding box for the tile
bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y)
self._mapnik.resize(width, height)
self._mapnik.zoom_to_box(bbox)
self._mapnik.buffer_size = 128
def render(self, bbox, width=None, height=None):
"""
Render the specified tile with Mapnik
"""
width = width or self.tilesize
height = height or self.tilesize
self._prepare_rendering(bbox, width=width, height=height)
# Render image with default Agg renderer
tmpfile = NamedTemporaryFile(delete=False)
im = mapnik.Image(width, height)
mapnik.render(self._mapnik, im)
im.save(tmpfile.name, 'png256') # TODO: mapnik output only to file?
tmpfile.close()
content = open(tmpfile.name, 'rb').read()
os.unlink(tmpfile.name)
return content
def render_grid(self, bbox, grid_fields, layer, width=None, height=None):
"""
Render the specified grid with Mapnik
"""
width = width or self.tilesize
height = height or self.tilesize
self._prepare_rendering(bbox, width=width, height=height)
grid = mapnik.Grid(width, height)
mapnik.render_layer(self._mapnik, grid, layer=layer, fields=grid_fields)
grid = grid.encode()
return json.dumps(grid)
|
makinacorpus/landez | landez/sources.py | MapnikRenderer.render_grid | python | def render_grid(self, bbox, grid_fields, layer, width=None, height=None):
width = width or self.tilesize
height = height or self.tilesize
self._prepare_rendering(bbox, width=width, height=height)
grid = mapnik.Grid(width, height)
mapnik.render_layer(self._mapnik, grid, layer=layer, fields=grid_fields)
grid = grid.encode()
return json.dumps(grid) | Render the specified grid with Mapnik | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/sources.py#L300-L311 | [
"def _prepare_rendering(self, bbox, width=None, height=None):\n if not self._mapnik:\n self._mapnik = mapnik.Map(width, height)\n # Load style XML\n mapnik.load_map(self._mapnik, self.stylefile, True)\n # Obtain <Map> projection\n self._prj = mapnik.Projection(self._mapnik.srs)\n\n # Convert to map projection\n assert len(bbox) == 4, _(\"Provide a bounding box tuple (minx, miny, maxx, maxy)\")\n c0 = self._prj.forward(mapnik.Coord(bbox[0], bbox[1]))\n c1 = self._prj.forward(mapnik.Coord(bbox[2], bbox[3]))\n\n # Bounding box for the tile\n bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y)\n self._mapnik.resize(width, height)\n self._mapnik.zoom_to_box(bbox)\n self._mapnik.buffer_size = 128\n"
] | class MapnikRenderer(TileSource):
def __init__(self, stylefile, tilesize=None):
super(MapnikRenderer, self).__init__(tilesize)
assert has_mapnik, _("Cannot render tiles without mapnik !")
self.stylefile = stylefile
self.basename = os.path.basename(self.stylefile)
self._mapnik = None
self._prj = None
def tile(self, z, x, y):
"""
Render the specified tile with Mapnik
"""
logger.debug(_("Render tile %s") % ((z, x, y),))
proj = GoogleProjection(self.tilesize, [z])
return self.render(proj.tile_bbox((z, x, y)))
def _prepare_rendering(self, bbox, width=None, height=None):
if not self._mapnik:
self._mapnik = mapnik.Map(width, height)
# Load style XML
mapnik.load_map(self._mapnik, self.stylefile, True)
# Obtain <Map> projection
self._prj = mapnik.Projection(self._mapnik.srs)
# Convert to map projection
assert len(bbox) == 4, _("Provide a bounding box tuple (minx, miny, maxx, maxy)")
c0 = self._prj.forward(mapnik.Coord(bbox[0], bbox[1]))
c1 = self._prj.forward(mapnik.Coord(bbox[2], bbox[3]))
# Bounding box for the tile
bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y)
self._mapnik.resize(width, height)
self._mapnik.zoom_to_box(bbox)
self._mapnik.buffer_size = 128
def render(self, bbox, width=None, height=None):
"""
Render the specified tile with Mapnik
"""
width = width or self.tilesize
height = height or self.tilesize
self._prepare_rendering(bbox, width=width, height=height)
# Render image with default Agg renderer
tmpfile = NamedTemporaryFile(delete=False)
im = mapnik.Image(width, height)
mapnik.render(self._mapnik, im)
im.save(tmpfile.name, 'png256') # TODO: mapnik output only to file?
tmpfile.close()
content = open(tmpfile.name, 'rb').read()
os.unlink(tmpfile.name)
return content
def grid(self, z, x, y, fields, layer):
"""
Render the specified grid with Mapnik
"""
logger.debug(_("Render grid %s") % ((z, x, y),))
proj = GoogleProjection(self.tilesize, [z])
return self.render_grid(proj.tile_bbox((z, x, y)), fields, layer)
|
makinacorpus/landez | landez/proj.py | GoogleProjection.tile_at | python | def tile_at(self, zoom, position):
x, y = self.project_pixels(position, zoom)
return (zoom, int(x/self.tilesize), int(y/self.tilesize)) | Returns a tuple of (z, x, y) | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/proj.py#L66-L71 | [
"def project_pixels(self,ll,zoom):\n d = self.zc[zoom]\n e = round(d[0] + ll[0] * self.Bc[zoom])\n f = minmax(sin(DEG_TO_RAD * ll[1]),-0.9999,0.9999)\n g = round(d[1] + 0.5*log((1+f)/(1-f))*-self.Cc[zoom])\n return (e,g)\n"
] | class GoogleProjection(object):
NAME = 'EPSG:3857'
"""
Transform Lon/Lat to Pixel within tiles
Originally written by OSM team : http://svn.openstreetmap.org/applications/rendering/mapnik/generate_tiles.py
"""
def __init__(self, tilesize=DEFAULT_TILE_SIZE, levels = [0], scheme='wmts'):
if not levels:
raise InvalidCoverageError(_("Wrong zoom levels."))
self.Bc = []
self.Cc = []
self.zc = []
self.Ac = []
self.levels = levels
self.maxlevel = max(levels) + 1
self.tilesize = tilesize
self.scheme = scheme
c = tilesize
for d in range(self.maxlevel):
e = c/2;
self.Bc.append(c/360.0)
self.Cc.append(c/(2 * pi))
self.zc.append((e,e))
self.Ac.append(c)
c *= 2
def project_pixels(self,ll,zoom):
d = self.zc[zoom]
e = round(d[0] + ll[0] * self.Bc[zoom])
f = minmax(sin(DEG_TO_RAD * ll[1]),-0.9999,0.9999)
g = round(d[1] + 0.5*log((1+f)/(1-f))*-self.Cc[zoom])
return (e,g)
def unproject_pixels(self,px,zoom):
e = self.zc[zoom]
f = (px[0] - e[0])/self.Bc[zoom]
g = (px[1] - e[1])/-self.Cc[zoom]
h = RAD_TO_DEG * ( 2 * atan(exp(g)) - 0.5 * pi)
if self.scheme == 'tms':
h = - h
return (f,h)
def tile_bbox(self, z_x_y):
"""
Returns the WGS84 bbox of the specified tile
"""
(z, x, y) = z_x_y
topleft = (x * self.tilesize, (y + 1) * self.tilesize)
bottomright = ((x + 1) * self.tilesize, y * self.tilesize)
nw = self.unproject_pixels(topleft, z)
se = self.unproject_pixels(bottomright, z)
return nw + se
def project(self, lng_lat):
"""
Returns the coordinates in meters from WGS84
"""
(lng, lat) = lng_lat
x = lng * DEG_TO_RAD
lat = max(min(MAX_LATITUDE, lat), -MAX_LATITUDE)
y = lat * DEG_TO_RAD
y = log(tan((pi / 4) + (y / 2)))
return (x*EARTH_RADIUS, y*EARTH_RADIUS)
def unproject(self, x_y):
"""
Returns the coordinates from position in meters
"""
(x, y) = x_y
lng = x/EARTH_RADIUS * RAD_TO_DEG
lat = 2 * atan(exp(y/EARTH_RADIUS)) - pi/2 * RAD_TO_DEG
return (lng, lat)
def tileslist(self, bbox):
if len(bbox) != 4:
raise InvalidCoverageError(_("Wrong format of bounding box."))
xmin, ymin, xmax, ymax = bbox
if abs(xmin) > 180 or abs(xmax) > 180 or \
abs(ymin) > 90 or abs(ymax) > 90:
raise InvalidCoverageError(_("Some coordinates exceed [-180,+180], [-90, 90]."))
if xmin >= xmax or ymin >= ymax:
raise InvalidCoverageError(_("Bounding box format is (xmin, ymin, xmax, ymax)"))
ll0 = (xmin, ymax) # left top
ll1 = (xmax, ymin) # right bottom
l = []
for z in self.levels:
px0 = self.project_pixels(ll0,z)
px1 = self.project_pixels(ll1,z)
for x in range(int(px0[0]/self.tilesize),
int(ceil(px1[0]/self.tilesize))):
if (x < 0) or (x >= 2**z):
continue
for y in range(int(px0[1]/self.tilesize),
int(ceil(px1[1]/self.tilesize))):
if (y < 0) or (y >= 2**z):
continue
if self.scheme == 'tms':
y = ((2**z-1) - y)
l.append((z, x, y))
return l
|
makinacorpus/landez | landez/proj.py | GoogleProjection.project | python | def project(self, lng_lat):
(lng, lat) = lng_lat
x = lng * DEG_TO_RAD
lat = max(min(MAX_LATITUDE, lat), -MAX_LATITUDE)
y = lat * DEG_TO_RAD
y = log(tan((pi / 4) + (y / 2)))
return (x*EARTH_RADIUS, y*EARTH_RADIUS) | Returns the coordinates in meters from WGS84 | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/proj.py#L84-L93 | null | class GoogleProjection(object):
NAME = 'EPSG:3857'
"""
Transform Lon/Lat to Pixel within tiles
Originally written by OSM team : http://svn.openstreetmap.org/applications/rendering/mapnik/generate_tiles.py
"""
def __init__(self, tilesize=DEFAULT_TILE_SIZE, levels = [0], scheme='wmts'):
if not levels:
raise InvalidCoverageError(_("Wrong zoom levels."))
self.Bc = []
self.Cc = []
self.zc = []
self.Ac = []
self.levels = levels
self.maxlevel = max(levels) + 1
self.tilesize = tilesize
self.scheme = scheme
c = tilesize
for d in range(self.maxlevel):
e = c/2;
self.Bc.append(c/360.0)
self.Cc.append(c/(2 * pi))
self.zc.append((e,e))
self.Ac.append(c)
c *= 2
def project_pixels(self,ll,zoom):
d = self.zc[zoom]
e = round(d[0] + ll[0] * self.Bc[zoom])
f = minmax(sin(DEG_TO_RAD * ll[1]),-0.9999,0.9999)
g = round(d[1] + 0.5*log((1+f)/(1-f))*-self.Cc[zoom])
return (e,g)
def unproject_pixels(self,px,zoom):
e = self.zc[zoom]
f = (px[0] - e[0])/self.Bc[zoom]
g = (px[1] - e[1])/-self.Cc[zoom]
h = RAD_TO_DEG * ( 2 * atan(exp(g)) - 0.5 * pi)
if self.scheme == 'tms':
h = - h
return (f,h)
def tile_at(self, zoom, position):
"""
Returns a tuple of (z, x, y)
"""
x, y = self.project_pixels(position, zoom)
return (zoom, int(x/self.tilesize), int(y/self.tilesize))
def tile_bbox(self, z_x_y):
"""
Returns the WGS84 bbox of the specified tile
"""
(z, x, y) = z_x_y
topleft = (x * self.tilesize, (y + 1) * self.tilesize)
bottomright = ((x + 1) * self.tilesize, y * self.tilesize)
nw = self.unproject_pixels(topleft, z)
se = self.unproject_pixels(bottomright, z)
return nw + se
def unproject(self, x_y):
"""
Returns the coordinates from position in meters
"""
(x, y) = x_y
lng = x/EARTH_RADIUS * RAD_TO_DEG
lat = 2 * atan(exp(y/EARTH_RADIUS)) - pi/2 * RAD_TO_DEG
return (lng, lat)
def tileslist(self, bbox):
if len(bbox) != 4:
raise InvalidCoverageError(_("Wrong format of bounding box."))
xmin, ymin, xmax, ymax = bbox
if abs(xmin) > 180 or abs(xmax) > 180 or \
abs(ymin) > 90 or abs(ymax) > 90:
raise InvalidCoverageError(_("Some coordinates exceed [-180,+180], [-90, 90]."))
if xmin >= xmax or ymin >= ymax:
raise InvalidCoverageError(_("Bounding box format is (xmin, ymin, xmax, ymax)"))
ll0 = (xmin, ymax) # left top
ll1 = (xmax, ymin) # right bottom
l = []
for z in self.levels:
px0 = self.project_pixels(ll0,z)
px1 = self.project_pixels(ll1,z)
for x in range(int(px0[0]/self.tilesize),
int(ceil(px1[0]/self.tilesize))):
if (x < 0) or (x >= 2**z):
continue
for y in range(int(px0[1]/self.tilesize),
int(ceil(px1[1]/self.tilesize))):
if (y < 0) or (y >= 2**z):
continue
if self.scheme == 'tms':
y = ((2**z-1) - y)
l.append((z, x, y))
return l
|
makinacorpus/landez | landez/filters.py | Filter.string2rgba | python | def string2rgba(cls, colorstring):
colorstring = colorstring.strip()
if colorstring[0] == '#':
colorstring = colorstring[1:]
if len(colorstring) < 6:
raise ValueError("input #%s is not in #RRGGBB format" % colorstring)
r, g, b = colorstring[:2], colorstring[2:4], colorstring[4:6]
a = 'ff'
if len(colorstring) > 6:
a = colorstring[6:8]
r, g, b, a = [int(n, 16) for n in (r, g, b, a)]
return (r, g, b, a) | Convert #RRGGBBAA to an (R, G, B, A) tuple | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/filters.py#L10-L22 | null | class Filter(object):
@property
def basename(self):
return self.__class__.__name__
def process(self, image):
return image
@classmethod
|
makinacorpus/landez | landez/tiles.py | TilesManager.tileslist | python | def tileslist(self, bbox, zoomlevels):
proj = GoogleProjection(self.tile_size, zoomlevels, self.tile_scheme)
return proj.tileslist(bbox) | Build the tiles list within the bottom-left/top-right bounding
box (minx, miny, maxx, maxy) at the specified zoom levels.
Return a list of tuples (z,x,y) | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L137-L144 | [
"def tileslist(self, bbox):\n if len(bbox) != 4:\n raise InvalidCoverageError(_(\"Wrong format of bounding box.\"))\n xmin, ymin, xmax, ymax = bbox\n if abs(xmin) > 180 or abs(xmax) > 180 or \\\n abs(ymin) > 90 or abs(ymax) > 90:\n raise InvalidCoverageError(_(\"Some coordinates exceed [-180,+180], [-90, 90].\"))\n\n if xmin >= xmax or ymin >= ymax:\n raise InvalidCoverageError(_(\"Bounding box format is (xmin, ymin, xmax, ymax)\"))\n\n ll0 = (xmin, ymax) # left top\n ll1 = (xmax, ymin) # right bottom\n\n l = []\n for z in self.levels:\n px0 = self.project_pixels(ll0,z)\n px1 = self.project_pixels(ll1,z)\n\n for x in range(int(px0[0]/self.tilesize),\n int(ceil(px1[0]/self.tilesize))):\n if (x < 0) or (x >= 2**z):\n continue\n for y in range(int(px0[1]/self.tilesize),\n int(ceil(px1[1]/self.tilesize))):\n if (y < 0) or (y >= 2**z):\n continue\n if self.scheme == 'tms':\n y = ((2**z-1) - y)\n l.append((z, x, y))\n return l\n"
] | class TilesManager(object):
def __init__(self, **kwargs):
"""
Manipulates tiles in general. Gives ability to list required tiles on a
bounding box, download them, render them, extract them from other mbtiles...
Keyword arguments:
cache -- use a local cache to share tiles between runs (default True)
tiles_dir -- Local folder containing existing tiles if cache is
True, or where temporary tiles will be written otherwise
(default DEFAULT_TMP_DIR)
tiles_url -- remote URL to download tiles (*default DEFAULT_TILES_URL*)
tiles_headers -- HTTP headers to send (*default empty*)
stylefile -- mapnik stylesheet file (*to render tiles locally*)
mbtiles_file -- A MBTiles file providing tiles (*to extract its tiles*)
wms_server -- A WMS server url (*to request tiles*)
wms_layers -- The list of layers to be requested
wms_options -- WMS parameters to be requested (see ``landez.reader.WMSReader``)
tile_size -- default tile size (default DEFAULT_TILE_SIZE)
tile_format -- default tile format (default DEFAULT_TILE_FORMAT)
tile_scheme -- default tile format (default DEFAULT_TILE_SCHEME)
"""
self.tile_size = kwargs.get('tile_size', DEFAULT_TILE_SIZE)
self.tile_format = kwargs.get('tile_format', DEFAULT_TILE_FORMAT)
self.tile_scheme = kwargs.get('tile_scheme', DEFAULT_TILE_SCHEME)
# Tiles Download
self.tiles_url = kwargs.get('tiles_url', DEFAULT_TILES_URL)
self.tiles_subdomains = kwargs.get('tiles_subdomains', DEFAULT_TILES_SUBDOMAINS)
self.tiles_headers = kwargs.get('tiles_headers')
# Tiles rendering
self.stylefile = kwargs.get('stylefile')
# Grids rendering
self.grid_fields = kwargs.get('grid_fields', [])
self.grid_layer = kwargs.get('grid_layer', 0)
# MBTiles reading
self.mbtiles_file = kwargs.get('mbtiles_file')
# WMS requesting
self.wms_server = kwargs.get('wms_server')
self.wms_layers = kwargs.get('wms_layers', [])
self.wms_options = kwargs.get('wms_options', {})
if self.mbtiles_file:
self.reader = MBTilesReader(self.mbtiles_file, self.tile_size)
elif self.wms_server:
assert self.wms_layers, _("Requires at least one layer (see ``wms_layers`` parameter)")
self.reader = WMSReader(self.wms_server, self.wms_layers, self.tiles_headers,
self.tile_size, **self.wms_options)
if 'format' in self.wms_options:
self.tile_format = self.wms_options['format']
logger.info(_("Tile format set to %s") % self.tile_format)
elif self.stylefile:
self.reader = MapnikRenderer(self.stylefile, self.tile_size)
else:
mimetype, encoding = mimetypes.guess_type(self.tiles_url)
if mimetype and mimetype != self.tile_format:
self.tile_format = mimetype
logger.info(_("Tile format set to %s") % self.tile_format)
self.reader = TileDownloader(self.tiles_url, headers=self.tiles_headers,
subdomains=self.tiles_subdomains, tilesize=self.tile_size)
# Tile files extensions
self._tile_extension = mimetypes.guess_extension(self.tile_format, strict=False)
assert self._tile_extension, _("Unknown format %s") % self.tile_format
if self._tile_extension in ('.jpe', '.jpg'):
self._tile_extension = '.jpeg'
# Cache
tiles_dir = kwargs.get('tiles_dir', DEFAULT_TMP_DIR)
if kwargs.get('cache', True):
self.cache = Disk(self.reader.basename, tiles_dir, extension=self._tile_extension)
if kwargs.get('cache_scheme'):
self.cache.scheme = kwargs.get('cache_scheme')
else:
self.cache = Dummy(extension=self._tile_extension)
# Overlays
self._layers = []
# Filters
self._filters = []
# Number of tiles rendered/downloaded here
self.rendered = 0
def add_layer(self, tilemanager, opacity=1.0):
"""
Add a layer to be blended (alpha-composite) on top of the tile.
tilemanager -- a `TileManager` instance
opacity -- transparency factor for compositing
"""
assert has_pil, _("Cannot blend layers without python PIL")
assert self.tile_size == tilemanager.tile_size, _("Cannot blend layers whose tile size differs")
assert 0 <= opacity <= 1, _("Opacity should be between 0.0 (transparent) and 1.0 (opaque)")
self.cache.basename += '%s%.1f' % (tilemanager.cache.basename, opacity)
self._layers.append((tilemanager, opacity))
def add_filter(self, filter_):
""" Add an image filter for post-processing """
assert has_pil, _("Cannot add filters without python PIL")
self.cache.basename += filter_.basename
self._filters.append(filter_)
def tile(self, z_x_y):
"""
Return the tile (binary) content of the tile and seed the cache.
"""
(z, x, y) = z_x_y
logger.debug(_("tile method called with %s") % ([z, x, y]))
output = self.cache.read((z, x, y))
if output is None:
output = self.reader.tile(z, x, y)
# Blend layers
if len(self._layers) > 0:
logger.debug(_("Will blend %s layer(s)") % len(self._layers))
output = self._blend_layers(output, (z, x, y))
# Apply filters
for f in self._filters:
image = f.process(self._tile_image(output))
output = self._image_tile(image)
# Save result to cache
self.cache.save(output, (z, x, y))
self.rendered += 1
return output
def grid(self, z_x_y):
""" Return the UTFGrid content """
# sources.py -> MapnikRenderer -> grid
(z, x, y) = z_x_y
content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer)
return content
def _blend_layers(self, imagecontent, z_x_y):
"""
Merge tiles of all layers into the specified tile path
"""
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
# Paste each layer
for (layer, opacity) in self._layers:
try:
# Prepare tile of overlay, if available
overlay = self._tile_image(layer.tile((z, x, y)))
except (IOError, DownloadError, ExtractionError)as e:
logger.warn(e)
continue
# Extract alpha mask
overlay = overlay.convert("RGBA")
r, g, b, a = overlay.split()
overlay = Image.merge("RGB", (r, g, b))
a = ImageEnhance.Brightness(a).enhance(opacity)
overlay.putalpha(a)
mask = Image.merge("L", (a,))
result.paste(overlay, (0, 0), mask)
# Read result
return self._image_tile(result)
def _tile_image(self, data):
"""
Tile binary content as PIL Image.
"""
image = Image.open(BytesIO(data))
return image.convert('RGBA')
def _image_tile(self, image):
out = StringIO()
image.save(out, self._tile_extension[1:])
return out.getvalue()
|
makinacorpus/landez | landez/tiles.py | TilesManager.add_layer | python | def add_layer(self, tilemanager, opacity=1.0):
assert has_pil, _("Cannot blend layers without python PIL")
assert self.tile_size == tilemanager.tile_size, _("Cannot blend layers whose tile size differs")
assert 0 <= opacity <= 1, _("Opacity should be between 0.0 (transparent) and 1.0 (opaque)")
self.cache.basename += '%s%.1f' % (tilemanager.cache.basename, opacity)
self._layers.append((tilemanager, opacity)) | Add a layer to be blended (alpha-composite) on top of the tile.
tilemanager -- a `TileManager` instance
opacity -- transparency factor for compositing | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L146-L156 | null | class TilesManager(object):
def __init__(self, **kwargs):
"""
Manipulates tiles in general. Gives ability to list required tiles on a
bounding box, download them, render them, extract them from other mbtiles...
Keyword arguments:
cache -- use a local cache to share tiles between runs (default True)
tiles_dir -- Local folder containing existing tiles if cache is
True, or where temporary tiles will be written otherwise
(default DEFAULT_TMP_DIR)
tiles_url -- remote URL to download tiles (*default DEFAULT_TILES_URL*)
tiles_headers -- HTTP headers to send (*default empty*)
stylefile -- mapnik stylesheet file (*to render tiles locally*)
mbtiles_file -- A MBTiles file providing tiles (*to extract its tiles*)
wms_server -- A WMS server url (*to request tiles*)
wms_layers -- The list of layers to be requested
wms_options -- WMS parameters to be requested (see ``landez.reader.WMSReader``)
tile_size -- default tile size (default DEFAULT_TILE_SIZE)
tile_format -- default tile format (default DEFAULT_TILE_FORMAT)
tile_scheme -- default tile format (default DEFAULT_TILE_SCHEME)
"""
self.tile_size = kwargs.get('tile_size', DEFAULT_TILE_SIZE)
self.tile_format = kwargs.get('tile_format', DEFAULT_TILE_FORMAT)
self.tile_scheme = kwargs.get('tile_scheme', DEFAULT_TILE_SCHEME)
# Tiles Download
self.tiles_url = kwargs.get('tiles_url', DEFAULT_TILES_URL)
self.tiles_subdomains = kwargs.get('tiles_subdomains', DEFAULT_TILES_SUBDOMAINS)
self.tiles_headers = kwargs.get('tiles_headers')
# Tiles rendering
self.stylefile = kwargs.get('stylefile')
# Grids rendering
self.grid_fields = kwargs.get('grid_fields', [])
self.grid_layer = kwargs.get('grid_layer', 0)
# MBTiles reading
self.mbtiles_file = kwargs.get('mbtiles_file')
# WMS requesting
self.wms_server = kwargs.get('wms_server')
self.wms_layers = kwargs.get('wms_layers', [])
self.wms_options = kwargs.get('wms_options', {})
if self.mbtiles_file:
self.reader = MBTilesReader(self.mbtiles_file, self.tile_size)
elif self.wms_server:
assert self.wms_layers, _("Requires at least one layer (see ``wms_layers`` parameter)")
self.reader = WMSReader(self.wms_server, self.wms_layers, self.tiles_headers,
self.tile_size, **self.wms_options)
if 'format' in self.wms_options:
self.tile_format = self.wms_options['format']
logger.info(_("Tile format set to %s") % self.tile_format)
elif self.stylefile:
self.reader = MapnikRenderer(self.stylefile, self.tile_size)
else:
mimetype, encoding = mimetypes.guess_type(self.tiles_url)
if mimetype and mimetype != self.tile_format:
self.tile_format = mimetype
logger.info(_("Tile format set to %s") % self.tile_format)
self.reader = TileDownloader(self.tiles_url, headers=self.tiles_headers,
subdomains=self.tiles_subdomains, tilesize=self.tile_size)
# Tile files extensions
self._tile_extension = mimetypes.guess_extension(self.tile_format, strict=False)
assert self._tile_extension, _("Unknown format %s") % self.tile_format
if self._tile_extension in ('.jpe', '.jpg'):
self._tile_extension = '.jpeg'
# Cache
tiles_dir = kwargs.get('tiles_dir', DEFAULT_TMP_DIR)
if kwargs.get('cache', True):
self.cache = Disk(self.reader.basename, tiles_dir, extension=self._tile_extension)
if kwargs.get('cache_scheme'):
self.cache.scheme = kwargs.get('cache_scheme')
else:
self.cache = Dummy(extension=self._tile_extension)
# Overlays
self._layers = []
# Filters
self._filters = []
# Number of tiles rendered/downloaded here
self.rendered = 0
def tileslist(self, bbox, zoomlevels):
"""
Build the tiles list within the bottom-left/top-right bounding
box (minx, miny, maxx, maxy) at the specified zoom levels.
Return a list of tuples (z,x,y)
"""
proj = GoogleProjection(self.tile_size, zoomlevels, self.tile_scheme)
return proj.tileslist(bbox)
def add_filter(self, filter_):
""" Add an image filter for post-processing """
assert has_pil, _("Cannot add filters without python PIL")
self.cache.basename += filter_.basename
self._filters.append(filter_)
def tile(self, z_x_y):
"""
Return the tile (binary) content of the tile and seed the cache.
"""
(z, x, y) = z_x_y
logger.debug(_("tile method called with %s") % ([z, x, y]))
output = self.cache.read((z, x, y))
if output is None:
output = self.reader.tile(z, x, y)
# Blend layers
if len(self._layers) > 0:
logger.debug(_("Will blend %s layer(s)") % len(self._layers))
output = self._blend_layers(output, (z, x, y))
# Apply filters
for f in self._filters:
image = f.process(self._tile_image(output))
output = self._image_tile(image)
# Save result to cache
self.cache.save(output, (z, x, y))
self.rendered += 1
return output
def grid(self, z_x_y):
""" Return the UTFGrid content """
# sources.py -> MapnikRenderer -> grid
(z, x, y) = z_x_y
content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer)
return content
def _blend_layers(self, imagecontent, z_x_y):
"""
Merge tiles of all layers into the specified tile path
"""
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
# Paste each layer
for (layer, opacity) in self._layers:
try:
# Prepare tile of overlay, if available
overlay = self._tile_image(layer.tile((z, x, y)))
except (IOError, DownloadError, ExtractionError)as e:
logger.warn(e)
continue
# Extract alpha mask
overlay = overlay.convert("RGBA")
r, g, b, a = overlay.split()
overlay = Image.merge("RGB", (r, g, b))
a = ImageEnhance.Brightness(a).enhance(opacity)
overlay.putalpha(a)
mask = Image.merge("L", (a,))
result.paste(overlay, (0, 0), mask)
# Read result
return self._image_tile(result)
def _tile_image(self, data):
"""
Tile binary content as PIL Image.
"""
image = Image.open(BytesIO(data))
return image.convert('RGBA')
def _image_tile(self, image):
out = StringIO()
image.save(out, self._tile_extension[1:])
return out.getvalue()
|
makinacorpus/landez | landez/tiles.py | TilesManager.add_filter | python | def add_filter(self, filter_):
assert has_pil, _("Cannot add filters without python PIL")
self.cache.basename += filter_.basename
self._filters.append(filter_) | Add an image filter for post-processing | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L158-L162 | null | class TilesManager(object):
def __init__(self, **kwargs):
"""
Manipulates tiles in general. Gives ability to list required tiles on a
bounding box, download them, render them, extract them from other mbtiles...
Keyword arguments:
cache -- use a local cache to share tiles between runs (default True)
tiles_dir -- Local folder containing existing tiles if cache is
True, or where temporary tiles will be written otherwise
(default DEFAULT_TMP_DIR)
tiles_url -- remote URL to download tiles (*default DEFAULT_TILES_URL*)
tiles_headers -- HTTP headers to send (*default empty*)
stylefile -- mapnik stylesheet file (*to render tiles locally*)
mbtiles_file -- A MBTiles file providing tiles (*to extract its tiles*)
wms_server -- A WMS server url (*to request tiles*)
wms_layers -- The list of layers to be requested
wms_options -- WMS parameters to be requested (see ``landez.reader.WMSReader``)
tile_size -- default tile size (default DEFAULT_TILE_SIZE)
tile_format -- default tile format (default DEFAULT_TILE_FORMAT)
tile_scheme -- default tile format (default DEFAULT_TILE_SCHEME)
"""
self.tile_size = kwargs.get('tile_size', DEFAULT_TILE_SIZE)
self.tile_format = kwargs.get('tile_format', DEFAULT_TILE_FORMAT)
self.tile_scheme = kwargs.get('tile_scheme', DEFAULT_TILE_SCHEME)
# Tiles Download
self.tiles_url = kwargs.get('tiles_url', DEFAULT_TILES_URL)
self.tiles_subdomains = kwargs.get('tiles_subdomains', DEFAULT_TILES_SUBDOMAINS)
self.tiles_headers = kwargs.get('tiles_headers')
# Tiles rendering
self.stylefile = kwargs.get('stylefile')
# Grids rendering
self.grid_fields = kwargs.get('grid_fields', [])
self.grid_layer = kwargs.get('grid_layer', 0)
# MBTiles reading
self.mbtiles_file = kwargs.get('mbtiles_file')
# WMS requesting
self.wms_server = kwargs.get('wms_server')
self.wms_layers = kwargs.get('wms_layers', [])
self.wms_options = kwargs.get('wms_options', {})
if self.mbtiles_file:
self.reader = MBTilesReader(self.mbtiles_file, self.tile_size)
elif self.wms_server:
assert self.wms_layers, _("Requires at least one layer (see ``wms_layers`` parameter)")
self.reader = WMSReader(self.wms_server, self.wms_layers, self.tiles_headers,
self.tile_size, **self.wms_options)
if 'format' in self.wms_options:
self.tile_format = self.wms_options['format']
logger.info(_("Tile format set to %s") % self.tile_format)
elif self.stylefile:
self.reader = MapnikRenderer(self.stylefile, self.tile_size)
else:
mimetype, encoding = mimetypes.guess_type(self.tiles_url)
if mimetype and mimetype != self.tile_format:
self.tile_format = mimetype
logger.info(_("Tile format set to %s") % self.tile_format)
self.reader = TileDownloader(self.tiles_url, headers=self.tiles_headers,
subdomains=self.tiles_subdomains, tilesize=self.tile_size)
# Tile files extensions
self._tile_extension = mimetypes.guess_extension(self.tile_format, strict=False)
assert self._tile_extension, _("Unknown format %s") % self.tile_format
if self._tile_extension in ('.jpe', '.jpg'):
self._tile_extension = '.jpeg'
# Cache
tiles_dir = kwargs.get('tiles_dir', DEFAULT_TMP_DIR)
if kwargs.get('cache', True):
self.cache = Disk(self.reader.basename, tiles_dir, extension=self._tile_extension)
if kwargs.get('cache_scheme'):
self.cache.scheme = kwargs.get('cache_scheme')
else:
self.cache = Dummy(extension=self._tile_extension)
# Overlays
self._layers = []
# Filters
self._filters = []
# Number of tiles rendered/downloaded here
self.rendered = 0
def tileslist(self, bbox, zoomlevels):
"""
Build the tiles list within the bottom-left/top-right bounding
box (minx, miny, maxx, maxy) at the specified zoom levels.
Return a list of tuples (z,x,y)
"""
proj = GoogleProjection(self.tile_size, zoomlevels, self.tile_scheme)
return proj.tileslist(bbox)
def add_layer(self, tilemanager, opacity=1.0):
"""
Add a layer to be blended (alpha-composite) on top of the tile.
tilemanager -- a `TileManager` instance
opacity -- transparency factor for compositing
"""
assert has_pil, _("Cannot blend layers without python PIL")
assert self.tile_size == tilemanager.tile_size, _("Cannot blend layers whose tile size differs")
assert 0 <= opacity <= 1, _("Opacity should be between 0.0 (transparent) and 1.0 (opaque)")
self.cache.basename += '%s%.1f' % (tilemanager.cache.basename, opacity)
self._layers.append((tilemanager, opacity))
def tile(self, z_x_y):
"""
Return the tile (binary) content of the tile and seed the cache.
"""
(z, x, y) = z_x_y
logger.debug(_("tile method called with %s") % ([z, x, y]))
output = self.cache.read((z, x, y))
if output is None:
output = self.reader.tile(z, x, y)
# Blend layers
if len(self._layers) > 0:
logger.debug(_("Will blend %s layer(s)") % len(self._layers))
output = self._blend_layers(output, (z, x, y))
# Apply filters
for f in self._filters:
image = f.process(self._tile_image(output))
output = self._image_tile(image)
# Save result to cache
self.cache.save(output, (z, x, y))
self.rendered += 1
return output
def grid(self, z_x_y):
""" Return the UTFGrid content """
# sources.py -> MapnikRenderer -> grid
(z, x, y) = z_x_y
content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer)
return content
def _blend_layers(self, imagecontent, z_x_y):
"""
Merge tiles of all layers into the specified tile path
"""
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
# Paste each layer
for (layer, opacity) in self._layers:
try:
# Prepare tile of overlay, if available
overlay = self._tile_image(layer.tile((z, x, y)))
except (IOError, DownloadError, ExtractionError)as e:
logger.warn(e)
continue
# Extract alpha mask
overlay = overlay.convert("RGBA")
r, g, b, a = overlay.split()
overlay = Image.merge("RGB", (r, g, b))
a = ImageEnhance.Brightness(a).enhance(opacity)
overlay.putalpha(a)
mask = Image.merge("L", (a,))
result.paste(overlay, (0, 0), mask)
# Read result
return self._image_tile(result)
def _tile_image(self, data):
"""
Tile binary content as PIL Image.
"""
image = Image.open(BytesIO(data))
return image.convert('RGBA')
def _image_tile(self, image):
out = StringIO()
image.save(out, self._tile_extension[1:])
return out.getvalue()
|
makinacorpus/landez | landez/tiles.py | TilesManager.tile | python | def tile(self, z_x_y):
(z, x, y) = z_x_y
logger.debug(_("tile method called with %s") % ([z, x, y]))
output = self.cache.read((z, x, y))
if output is None:
output = self.reader.tile(z, x, y)
# Blend layers
if len(self._layers) > 0:
logger.debug(_("Will blend %s layer(s)") % len(self._layers))
output = self._blend_layers(output, (z, x, y))
# Apply filters
for f in self._filters:
image = f.process(self._tile_image(output))
output = self._image_tile(image)
# Save result to cache
self.cache.save(output, (z, x, y))
self.rendered += 1
return output | Return the tile (binary) content of the tile and seed the cache. | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L164-L186 | [
"def _blend_layers(self, imagecontent, z_x_y):\n \"\"\"\n Merge tiles of all layers into the specified tile path\n \"\"\"\n (z, x, y) = z_x_y\n result = self._tile_image(imagecontent)\n # Paste each layer\n for (layer, opacity) in self._layers:\n try:\n # Prepare tile of overlay, if available\n overlay = self._tile_image(layer.tile((z, x, y)))\n except (IOError, DownloadError, ExtractionError)as e:\n logger.warn(e)\n continue\n # Extract alpha mask\n overlay = overlay.convert(\"RGBA\")\n r, g, b, a = overlay.split()\n overlay = Image.merge(\"RGB\", (r, g, b))\n a = ImageEnhance.Brightness(a).enhance(opacity)\n overlay.putalpha(a)\n mask = Image.merge(\"L\", (a,))\n result.paste(overlay, (0, 0), mask)\n # Read result\n return self._image_tile(result)\n",
"def _tile_image(self, data):\n \"\"\"\n Tile binary content as PIL Image.\n \"\"\"\n image = Image.open(BytesIO(data))\n return image.convert('RGBA')\n",
"def _image_tile(self, image):\n out = StringIO()\n image.save(out, self._tile_extension[1:])\n return out.getvalue()\n"
] | class TilesManager(object):
def __init__(self, **kwargs):
"""
Manipulates tiles in general. Gives ability to list required tiles on a
bounding box, download them, render them, extract them from other mbtiles...
Keyword arguments:
cache -- use a local cache to share tiles between runs (default True)
tiles_dir -- Local folder containing existing tiles if cache is
True, or where temporary tiles will be written otherwise
(default DEFAULT_TMP_DIR)
tiles_url -- remote URL to download tiles (*default DEFAULT_TILES_URL*)
tiles_headers -- HTTP headers to send (*default empty*)
stylefile -- mapnik stylesheet file (*to render tiles locally*)
mbtiles_file -- A MBTiles file providing tiles (*to extract its tiles*)
wms_server -- A WMS server url (*to request tiles*)
wms_layers -- The list of layers to be requested
wms_options -- WMS parameters to be requested (see ``landez.reader.WMSReader``)
tile_size -- default tile size (default DEFAULT_TILE_SIZE)
tile_format -- default tile format (default DEFAULT_TILE_FORMAT)
tile_scheme -- default tile format (default DEFAULT_TILE_SCHEME)
"""
self.tile_size = kwargs.get('tile_size', DEFAULT_TILE_SIZE)
self.tile_format = kwargs.get('tile_format', DEFAULT_TILE_FORMAT)
self.tile_scheme = kwargs.get('tile_scheme', DEFAULT_TILE_SCHEME)
# Tiles Download
self.tiles_url = kwargs.get('tiles_url', DEFAULT_TILES_URL)
self.tiles_subdomains = kwargs.get('tiles_subdomains', DEFAULT_TILES_SUBDOMAINS)
self.tiles_headers = kwargs.get('tiles_headers')
# Tiles rendering
self.stylefile = kwargs.get('stylefile')
# Grids rendering
self.grid_fields = kwargs.get('grid_fields', [])
self.grid_layer = kwargs.get('grid_layer', 0)
# MBTiles reading
self.mbtiles_file = kwargs.get('mbtiles_file')
# WMS requesting
self.wms_server = kwargs.get('wms_server')
self.wms_layers = kwargs.get('wms_layers', [])
self.wms_options = kwargs.get('wms_options', {})
if self.mbtiles_file:
self.reader = MBTilesReader(self.mbtiles_file, self.tile_size)
elif self.wms_server:
assert self.wms_layers, _("Requires at least one layer (see ``wms_layers`` parameter)")
self.reader = WMSReader(self.wms_server, self.wms_layers, self.tiles_headers,
self.tile_size, **self.wms_options)
if 'format' in self.wms_options:
self.tile_format = self.wms_options['format']
logger.info(_("Tile format set to %s") % self.tile_format)
elif self.stylefile:
self.reader = MapnikRenderer(self.stylefile, self.tile_size)
else:
mimetype, encoding = mimetypes.guess_type(self.tiles_url)
if mimetype and mimetype != self.tile_format:
self.tile_format = mimetype
logger.info(_("Tile format set to %s") % self.tile_format)
self.reader = TileDownloader(self.tiles_url, headers=self.tiles_headers,
subdomains=self.tiles_subdomains, tilesize=self.tile_size)
# Tile files extensions
self._tile_extension = mimetypes.guess_extension(self.tile_format, strict=False)
assert self._tile_extension, _("Unknown format %s") % self.tile_format
if self._tile_extension in ('.jpe', '.jpg'):
self._tile_extension = '.jpeg'
# Cache
tiles_dir = kwargs.get('tiles_dir', DEFAULT_TMP_DIR)
if kwargs.get('cache', True):
self.cache = Disk(self.reader.basename, tiles_dir, extension=self._tile_extension)
if kwargs.get('cache_scheme'):
self.cache.scheme = kwargs.get('cache_scheme')
else:
self.cache = Dummy(extension=self._tile_extension)
# Overlays
self._layers = []
# Filters
self._filters = []
# Number of tiles rendered/downloaded here
self.rendered = 0
def tileslist(self, bbox, zoomlevels):
"""
Build the tiles list within the bottom-left/top-right bounding
box (minx, miny, maxx, maxy) at the specified zoom levels.
Return a list of tuples (z,x,y)
"""
proj = GoogleProjection(self.tile_size, zoomlevels, self.tile_scheme)
return proj.tileslist(bbox)
def add_layer(self, tilemanager, opacity=1.0):
"""
Add a layer to be blended (alpha-composite) on top of the tile.
tilemanager -- a `TileManager` instance
opacity -- transparency factor for compositing
"""
assert has_pil, _("Cannot blend layers without python PIL")
assert self.tile_size == tilemanager.tile_size, _("Cannot blend layers whose tile size differs")
assert 0 <= opacity <= 1, _("Opacity should be between 0.0 (transparent) and 1.0 (opaque)")
self.cache.basename += '%s%.1f' % (tilemanager.cache.basename, opacity)
self._layers.append((tilemanager, opacity))
def add_filter(self, filter_):
""" Add an image filter for post-processing """
assert has_pil, _("Cannot add filters without python PIL")
self.cache.basename += filter_.basename
self._filters.append(filter_)
def grid(self, z_x_y):
""" Return the UTFGrid content """
# sources.py -> MapnikRenderer -> grid
(z, x, y) = z_x_y
content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer)
return content
def _blend_layers(self, imagecontent, z_x_y):
"""
Merge tiles of all layers into the specified tile path
"""
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
# Paste each layer
for (layer, opacity) in self._layers:
try:
# Prepare tile of overlay, if available
overlay = self._tile_image(layer.tile((z, x, y)))
except (IOError, DownloadError, ExtractionError)as e:
logger.warn(e)
continue
# Extract alpha mask
overlay = overlay.convert("RGBA")
r, g, b, a = overlay.split()
overlay = Image.merge("RGB", (r, g, b))
a = ImageEnhance.Brightness(a).enhance(opacity)
overlay.putalpha(a)
mask = Image.merge("L", (a,))
result.paste(overlay, (0, 0), mask)
# Read result
return self._image_tile(result)
def _tile_image(self, data):
"""
Tile binary content as PIL Image.
"""
image = Image.open(BytesIO(data))
return image.convert('RGBA')
def _image_tile(self, image):
out = StringIO()
image.save(out, self._tile_extension[1:])
return out.getvalue()
|
makinacorpus/landez | landez/tiles.py | TilesManager.grid | python | def grid(self, z_x_y):
# sources.py -> MapnikRenderer -> grid
(z, x, y) = z_x_y
content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer)
return content | Return the UTFGrid content | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L188-L193 | null | class TilesManager(object):
def __init__(self, **kwargs):
"""
Manipulates tiles in general. Gives ability to list required tiles on a
bounding box, download them, render them, extract them from other mbtiles...
Keyword arguments:
cache -- use a local cache to share tiles between runs (default True)
tiles_dir -- Local folder containing existing tiles if cache is
True, or where temporary tiles will be written otherwise
(default DEFAULT_TMP_DIR)
tiles_url -- remote URL to download tiles (*default DEFAULT_TILES_URL*)
tiles_headers -- HTTP headers to send (*default empty*)
stylefile -- mapnik stylesheet file (*to render tiles locally*)
mbtiles_file -- A MBTiles file providing tiles (*to extract its tiles*)
wms_server -- A WMS server url (*to request tiles*)
wms_layers -- The list of layers to be requested
wms_options -- WMS parameters to be requested (see ``landez.reader.WMSReader``)
tile_size -- default tile size (default DEFAULT_TILE_SIZE)
tile_format -- default tile format (default DEFAULT_TILE_FORMAT)
tile_scheme -- default tile format (default DEFAULT_TILE_SCHEME)
"""
self.tile_size = kwargs.get('tile_size', DEFAULT_TILE_SIZE)
self.tile_format = kwargs.get('tile_format', DEFAULT_TILE_FORMAT)
self.tile_scheme = kwargs.get('tile_scheme', DEFAULT_TILE_SCHEME)
# Tiles Download
self.tiles_url = kwargs.get('tiles_url', DEFAULT_TILES_URL)
self.tiles_subdomains = kwargs.get('tiles_subdomains', DEFAULT_TILES_SUBDOMAINS)
self.tiles_headers = kwargs.get('tiles_headers')
# Tiles rendering
self.stylefile = kwargs.get('stylefile')
# Grids rendering
self.grid_fields = kwargs.get('grid_fields', [])
self.grid_layer = kwargs.get('grid_layer', 0)
# MBTiles reading
self.mbtiles_file = kwargs.get('mbtiles_file')
# WMS requesting
self.wms_server = kwargs.get('wms_server')
self.wms_layers = kwargs.get('wms_layers', [])
self.wms_options = kwargs.get('wms_options', {})
if self.mbtiles_file:
self.reader = MBTilesReader(self.mbtiles_file, self.tile_size)
elif self.wms_server:
assert self.wms_layers, _("Requires at least one layer (see ``wms_layers`` parameter)")
self.reader = WMSReader(self.wms_server, self.wms_layers, self.tiles_headers,
self.tile_size, **self.wms_options)
if 'format' in self.wms_options:
self.tile_format = self.wms_options['format']
logger.info(_("Tile format set to %s") % self.tile_format)
elif self.stylefile:
self.reader = MapnikRenderer(self.stylefile, self.tile_size)
else:
mimetype, encoding = mimetypes.guess_type(self.tiles_url)
if mimetype and mimetype != self.tile_format:
self.tile_format = mimetype
logger.info(_("Tile format set to %s") % self.tile_format)
self.reader = TileDownloader(self.tiles_url, headers=self.tiles_headers,
subdomains=self.tiles_subdomains, tilesize=self.tile_size)
# Tile files extensions
self._tile_extension = mimetypes.guess_extension(self.tile_format, strict=False)
assert self._tile_extension, _("Unknown format %s") % self.tile_format
if self._tile_extension in ('.jpe', '.jpg'):
self._tile_extension = '.jpeg'
# Cache
tiles_dir = kwargs.get('tiles_dir', DEFAULT_TMP_DIR)
if kwargs.get('cache', True):
self.cache = Disk(self.reader.basename, tiles_dir, extension=self._tile_extension)
if kwargs.get('cache_scheme'):
self.cache.scheme = kwargs.get('cache_scheme')
else:
self.cache = Dummy(extension=self._tile_extension)
# Overlays
self._layers = []
# Filters
self._filters = []
# Number of tiles rendered/downloaded here
self.rendered = 0
def tileslist(self, bbox, zoomlevels):
"""
Build the tiles list within the bottom-left/top-right bounding
box (minx, miny, maxx, maxy) at the specified zoom levels.
Return a list of tuples (z,x,y)
"""
proj = GoogleProjection(self.tile_size, zoomlevels, self.tile_scheme)
return proj.tileslist(bbox)
def add_layer(self, tilemanager, opacity=1.0):
"""
Add a layer to be blended (alpha-composite) on top of the tile.
tilemanager -- a `TileManager` instance
opacity -- transparency factor for compositing
"""
assert has_pil, _("Cannot blend layers without python PIL")
assert self.tile_size == tilemanager.tile_size, _("Cannot blend layers whose tile size differs")
assert 0 <= opacity <= 1, _("Opacity should be between 0.0 (transparent) and 1.0 (opaque)")
self.cache.basename += '%s%.1f' % (tilemanager.cache.basename, opacity)
self._layers.append((tilemanager, opacity))
def add_filter(self, filter_):
""" Add an image filter for post-processing """
assert has_pil, _("Cannot add filters without python PIL")
self.cache.basename += filter_.basename
self._filters.append(filter_)
def tile(self, z_x_y):
"""
Return the tile (binary) content of the tile and seed the cache.
"""
(z, x, y) = z_x_y
logger.debug(_("tile method called with %s") % ([z, x, y]))
output = self.cache.read((z, x, y))
if output is None:
output = self.reader.tile(z, x, y)
# Blend layers
if len(self._layers) > 0:
logger.debug(_("Will blend %s layer(s)") % len(self._layers))
output = self._blend_layers(output, (z, x, y))
# Apply filters
for f in self._filters:
image = f.process(self._tile_image(output))
output = self._image_tile(image)
# Save result to cache
self.cache.save(output, (z, x, y))
self.rendered += 1
return output
def _blend_layers(self, imagecontent, z_x_y):
"""
Merge tiles of all layers into the specified tile path
"""
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
# Paste each layer
for (layer, opacity) in self._layers:
try:
# Prepare tile of overlay, if available
overlay = self._tile_image(layer.tile((z, x, y)))
except (IOError, DownloadError, ExtractionError)as e:
logger.warn(e)
continue
# Extract alpha mask
overlay = overlay.convert("RGBA")
r, g, b, a = overlay.split()
overlay = Image.merge("RGB", (r, g, b))
a = ImageEnhance.Brightness(a).enhance(opacity)
overlay.putalpha(a)
mask = Image.merge("L", (a,))
result.paste(overlay, (0, 0), mask)
# Read result
return self._image_tile(result)
def _tile_image(self, data):
"""
Tile binary content as PIL Image.
"""
image = Image.open(BytesIO(data))
return image.convert('RGBA')
def _image_tile(self, image):
out = StringIO()
image.save(out, self._tile_extension[1:])
return out.getvalue()
|
makinacorpus/landez | landez/tiles.py | TilesManager._blend_layers | python | def _blend_layers(self, imagecontent, z_x_y):
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
# Paste each layer
for (layer, opacity) in self._layers:
try:
# Prepare tile of overlay, if available
overlay = self._tile_image(layer.tile((z, x, y)))
except (IOError, DownloadError, ExtractionError)as e:
logger.warn(e)
continue
# Extract alpha mask
overlay = overlay.convert("RGBA")
r, g, b, a = overlay.split()
overlay = Image.merge("RGB", (r, g, b))
a = ImageEnhance.Brightness(a).enhance(opacity)
overlay.putalpha(a)
mask = Image.merge("L", (a,))
result.paste(overlay, (0, 0), mask)
# Read result
return self._image_tile(result) | Merge tiles of all layers into the specified tile path | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L196-L219 | [
"def _tile_image(self, data):\n \"\"\"\n Tile binary content as PIL Image.\n \"\"\"\n image = Image.open(BytesIO(data))\n return image.convert('RGBA')\n",
"def _image_tile(self, image):\n out = StringIO()\n image.save(out, self._tile_extension[1:])\n return out.getvalue()\n"
] | class TilesManager(object):
def __init__(self, **kwargs):
"""
Manipulates tiles in general. Gives ability to list required tiles on a
bounding box, download them, render them, extract them from other mbtiles...
Keyword arguments:
cache -- use a local cache to share tiles between runs (default True)
tiles_dir -- Local folder containing existing tiles if cache is
True, or where temporary tiles will be written otherwise
(default DEFAULT_TMP_DIR)
tiles_url -- remote URL to download tiles (*default DEFAULT_TILES_URL*)
tiles_headers -- HTTP headers to send (*default empty*)
stylefile -- mapnik stylesheet file (*to render tiles locally*)
mbtiles_file -- A MBTiles file providing tiles (*to extract its tiles*)
wms_server -- A WMS server url (*to request tiles*)
wms_layers -- The list of layers to be requested
wms_options -- WMS parameters to be requested (see ``landez.reader.WMSReader``)
tile_size -- default tile size (default DEFAULT_TILE_SIZE)
tile_format -- default tile format (default DEFAULT_TILE_FORMAT)
tile_scheme -- default tile format (default DEFAULT_TILE_SCHEME)
"""
self.tile_size = kwargs.get('tile_size', DEFAULT_TILE_SIZE)
self.tile_format = kwargs.get('tile_format', DEFAULT_TILE_FORMAT)
self.tile_scheme = kwargs.get('tile_scheme', DEFAULT_TILE_SCHEME)
# Tiles Download
self.tiles_url = kwargs.get('tiles_url', DEFAULT_TILES_URL)
self.tiles_subdomains = kwargs.get('tiles_subdomains', DEFAULT_TILES_SUBDOMAINS)
self.tiles_headers = kwargs.get('tiles_headers')
# Tiles rendering
self.stylefile = kwargs.get('stylefile')
# Grids rendering
self.grid_fields = kwargs.get('grid_fields', [])
self.grid_layer = kwargs.get('grid_layer', 0)
# MBTiles reading
self.mbtiles_file = kwargs.get('mbtiles_file')
# WMS requesting
self.wms_server = kwargs.get('wms_server')
self.wms_layers = kwargs.get('wms_layers', [])
self.wms_options = kwargs.get('wms_options', {})
if self.mbtiles_file:
self.reader = MBTilesReader(self.mbtiles_file, self.tile_size)
elif self.wms_server:
assert self.wms_layers, _("Requires at least one layer (see ``wms_layers`` parameter)")
self.reader = WMSReader(self.wms_server, self.wms_layers, self.tiles_headers,
self.tile_size, **self.wms_options)
if 'format' in self.wms_options:
self.tile_format = self.wms_options['format']
logger.info(_("Tile format set to %s") % self.tile_format)
elif self.stylefile:
self.reader = MapnikRenderer(self.stylefile, self.tile_size)
else:
mimetype, encoding = mimetypes.guess_type(self.tiles_url)
if mimetype and mimetype != self.tile_format:
self.tile_format = mimetype
logger.info(_("Tile format set to %s") % self.tile_format)
self.reader = TileDownloader(self.tiles_url, headers=self.tiles_headers,
subdomains=self.tiles_subdomains, tilesize=self.tile_size)
# Tile files extensions
self._tile_extension = mimetypes.guess_extension(self.tile_format, strict=False)
assert self._tile_extension, _("Unknown format %s") % self.tile_format
if self._tile_extension in ('.jpe', '.jpg'):
self._tile_extension = '.jpeg'
# Cache
tiles_dir = kwargs.get('tiles_dir', DEFAULT_TMP_DIR)
if kwargs.get('cache', True):
self.cache = Disk(self.reader.basename, tiles_dir, extension=self._tile_extension)
if kwargs.get('cache_scheme'):
self.cache.scheme = kwargs.get('cache_scheme')
else:
self.cache = Dummy(extension=self._tile_extension)
# Overlays
self._layers = []
# Filters
self._filters = []
# Number of tiles rendered/downloaded here
self.rendered = 0
def tileslist(self, bbox, zoomlevels):
"""
Build the tiles list within the bottom-left/top-right bounding
box (minx, miny, maxx, maxy) at the specified zoom levels.
Return a list of tuples (z,x,y)
"""
proj = GoogleProjection(self.tile_size, zoomlevels, self.tile_scheme)
return proj.tileslist(bbox)
def add_layer(self, tilemanager, opacity=1.0):
"""
Add a layer to be blended (alpha-composite) on top of the tile.
tilemanager -- a `TileManager` instance
opacity -- transparency factor for compositing
"""
assert has_pil, _("Cannot blend layers without python PIL")
assert self.tile_size == tilemanager.tile_size, _("Cannot blend layers whose tile size differs")
assert 0 <= opacity <= 1, _("Opacity should be between 0.0 (transparent) and 1.0 (opaque)")
self.cache.basename += '%s%.1f' % (tilemanager.cache.basename, opacity)
self._layers.append((tilemanager, opacity))
def add_filter(self, filter_):
""" Add an image filter for post-processing """
assert has_pil, _("Cannot add filters without python PIL")
self.cache.basename += filter_.basename
self._filters.append(filter_)
def tile(self, z_x_y):
"""
Return the tile (binary) content of the tile and seed the cache.
"""
(z, x, y) = z_x_y
logger.debug(_("tile method called with %s") % ([z, x, y]))
output = self.cache.read((z, x, y))
if output is None:
output = self.reader.tile(z, x, y)
# Blend layers
if len(self._layers) > 0:
logger.debug(_("Will blend %s layer(s)") % len(self._layers))
output = self._blend_layers(output, (z, x, y))
# Apply filters
for f in self._filters:
image = f.process(self._tile_image(output))
output = self._image_tile(image)
# Save result to cache
self.cache.save(output, (z, x, y))
self.rendered += 1
return output
def grid(self, z_x_y):
""" Return the UTFGrid content """
# sources.py -> MapnikRenderer -> grid
(z, x, y) = z_x_y
content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer)
return content
def _tile_image(self, data):
"""
Tile binary content as PIL Image.
"""
image = Image.open(BytesIO(data))
return image.convert('RGBA')
def _image_tile(self, image):
out = StringIO()
image.save(out, self._tile_extension[1:])
return out.getvalue()
|
makinacorpus/landez | landez/tiles.py | TilesManager._tile_image | python | def _tile_image(self, data):
image = Image.open(BytesIO(data))
return image.convert('RGBA') | Tile binary content as PIL Image. | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L221-L226 | null | class TilesManager(object):
def __init__(self, **kwargs):
"""
Manipulates tiles in general. Gives ability to list required tiles on a
bounding box, download them, render them, extract them from other mbtiles...
Keyword arguments:
cache -- use a local cache to share tiles between runs (default True)
tiles_dir -- Local folder containing existing tiles if cache is
True, or where temporary tiles will be written otherwise
(default DEFAULT_TMP_DIR)
tiles_url -- remote URL to download tiles (*default DEFAULT_TILES_URL*)
tiles_headers -- HTTP headers to send (*default empty*)
stylefile -- mapnik stylesheet file (*to render tiles locally*)
mbtiles_file -- A MBTiles file providing tiles (*to extract its tiles*)
wms_server -- A WMS server url (*to request tiles*)
wms_layers -- The list of layers to be requested
wms_options -- WMS parameters to be requested (see ``landez.reader.WMSReader``)
tile_size -- default tile size (default DEFAULT_TILE_SIZE)
tile_format -- default tile format (default DEFAULT_TILE_FORMAT)
tile_scheme -- default tile format (default DEFAULT_TILE_SCHEME)
"""
self.tile_size = kwargs.get('tile_size', DEFAULT_TILE_SIZE)
self.tile_format = kwargs.get('tile_format', DEFAULT_TILE_FORMAT)
self.tile_scheme = kwargs.get('tile_scheme', DEFAULT_TILE_SCHEME)
# Tiles Download
self.tiles_url = kwargs.get('tiles_url', DEFAULT_TILES_URL)
self.tiles_subdomains = kwargs.get('tiles_subdomains', DEFAULT_TILES_SUBDOMAINS)
self.tiles_headers = kwargs.get('tiles_headers')
# Tiles rendering
self.stylefile = kwargs.get('stylefile')
# Grids rendering
self.grid_fields = kwargs.get('grid_fields', [])
self.grid_layer = kwargs.get('grid_layer', 0)
# MBTiles reading
self.mbtiles_file = kwargs.get('mbtiles_file')
# WMS requesting
self.wms_server = kwargs.get('wms_server')
self.wms_layers = kwargs.get('wms_layers', [])
self.wms_options = kwargs.get('wms_options', {})
if self.mbtiles_file:
self.reader = MBTilesReader(self.mbtiles_file, self.tile_size)
elif self.wms_server:
assert self.wms_layers, _("Requires at least one layer (see ``wms_layers`` parameter)")
self.reader = WMSReader(self.wms_server, self.wms_layers, self.tiles_headers,
self.tile_size, **self.wms_options)
if 'format' in self.wms_options:
self.tile_format = self.wms_options['format']
logger.info(_("Tile format set to %s") % self.tile_format)
elif self.stylefile:
self.reader = MapnikRenderer(self.stylefile, self.tile_size)
else:
mimetype, encoding = mimetypes.guess_type(self.tiles_url)
if mimetype and mimetype != self.tile_format:
self.tile_format = mimetype
logger.info(_("Tile format set to %s") % self.tile_format)
self.reader = TileDownloader(self.tiles_url, headers=self.tiles_headers,
subdomains=self.tiles_subdomains, tilesize=self.tile_size)
# Tile files extensions
self._tile_extension = mimetypes.guess_extension(self.tile_format, strict=False)
assert self._tile_extension, _("Unknown format %s") % self.tile_format
if self._tile_extension in ('.jpe', '.jpg'):
self._tile_extension = '.jpeg'
# Cache
tiles_dir = kwargs.get('tiles_dir', DEFAULT_TMP_DIR)
if kwargs.get('cache', True):
self.cache = Disk(self.reader.basename, tiles_dir, extension=self._tile_extension)
if kwargs.get('cache_scheme'):
self.cache.scheme = kwargs.get('cache_scheme')
else:
self.cache = Dummy(extension=self._tile_extension)
# Overlays
self._layers = []
# Filters
self._filters = []
# Number of tiles rendered/downloaded here
self.rendered = 0
def tileslist(self, bbox, zoomlevels):
"""
Build the tiles list within the bottom-left/top-right bounding
box (minx, miny, maxx, maxy) at the specified zoom levels.
Return a list of tuples (z,x,y)
"""
proj = GoogleProjection(self.tile_size, zoomlevels, self.tile_scheme)
return proj.tileslist(bbox)
def add_layer(self, tilemanager, opacity=1.0):
"""
Add a layer to be blended (alpha-composite) on top of the tile.
tilemanager -- a `TileManager` instance
opacity -- transparency factor for compositing
"""
assert has_pil, _("Cannot blend layers without python PIL")
assert self.tile_size == tilemanager.tile_size, _("Cannot blend layers whose tile size differs")
assert 0 <= opacity <= 1, _("Opacity should be between 0.0 (transparent) and 1.0 (opaque)")
self.cache.basename += '%s%.1f' % (tilemanager.cache.basename, opacity)
self._layers.append((tilemanager, opacity))
def add_filter(self, filter_):
""" Add an image filter for post-processing """
assert has_pil, _("Cannot add filters without python PIL")
self.cache.basename += filter_.basename
self._filters.append(filter_)
def tile(self, z_x_y):
"""
Return the tile (binary) content of the tile and seed the cache.
"""
(z, x, y) = z_x_y
logger.debug(_("tile method called with %s") % ([z, x, y]))
output = self.cache.read((z, x, y))
if output is None:
output = self.reader.tile(z, x, y)
# Blend layers
if len(self._layers) > 0:
logger.debug(_("Will blend %s layer(s)") % len(self._layers))
output = self._blend_layers(output, (z, x, y))
# Apply filters
for f in self._filters:
image = f.process(self._tile_image(output))
output = self._image_tile(image)
# Save result to cache
self.cache.save(output, (z, x, y))
self.rendered += 1
return output
def grid(self, z_x_y):
""" Return the UTFGrid content """
# sources.py -> MapnikRenderer -> grid
(z, x, y) = z_x_y
content = self.reader.grid(z, x, y, self.grid_fields, self.grid_layer)
return content
def _blend_layers(self, imagecontent, z_x_y):
"""
Merge tiles of all layers into the specified tile path
"""
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
# Paste each layer
for (layer, opacity) in self._layers:
try:
# Prepare tile of overlay, if available
overlay = self._tile_image(layer.tile((z, x, y)))
except (IOError, DownloadError, ExtractionError)as e:
logger.warn(e)
continue
# Extract alpha mask
overlay = overlay.convert("RGBA")
r, g, b, a = overlay.split()
overlay = Image.merge("RGB", (r, g, b))
a = ImageEnhance.Brightness(a).enhance(opacity)
overlay.putalpha(a)
mask = Image.merge("L", (a,))
result.paste(overlay, (0, 0), mask)
# Read result
return self._image_tile(result)
def _image_tile(self, image):
out = StringIO()
image.save(out, self._tile_extension[1:])
return out.getvalue()
|
makinacorpus/landez | landez/tiles.py | MBTilesBuilder.zoomlevels | python | def zoomlevels(self):
zooms = set()
for coverage in self._bboxes:
for zoom in coverage[1]:
zooms.add(zoom)
return sorted(zooms) | Return the list of covered zoom levels, in ascending order | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L263-L271 | null | class MBTilesBuilder(TilesManager):
def __init__(self, **kwargs):
"""
A MBTiles builder for a list of bounding boxes and zoom levels.
filepath -- output MBTiles file (default DEFAULT_FILEPATH)
tmp_dir -- temporary folder for gathering tiles (default DEFAULT_TMP_DIR/filepath)
ignore_errors -- ignore errors during MBTiles creation (e.g. download errors)
"""
super(MBTilesBuilder, self).__init__(**kwargs)
self.filepath = kwargs.get('filepath', DEFAULT_FILEPATH)
self.ignore_errors = kwargs.get('ignore_errors', False)
# Gather tiles for mbutil
basename, ext = os.path.splitext(os.path.basename(self.filepath))
self.tmp_dir = kwargs.get('tmp_dir', DEFAULT_TMP_DIR)
self.tmp_dir = os.path.join(self.tmp_dir, basename)
self.tile_format = kwargs.get('tile_format', DEFAULT_TILE_FORMAT)
# Number of tiles in total
self.nbtiles = 0
self._bboxes = []
def add_coverage(self, bbox, zoomlevels):
"""
Add a coverage to be included in the resulting mbtiles file.
"""
self._bboxes.append((bbox, zoomlevels))
@property
@property
def bounds(self):
"""
Return the bounding box of covered areas
"""
return self._bboxes[0][0] #TODO: merge all coverages
def run(self, force=False):
"""
Build a MBTile file.
force -- overwrite if MBTiles file already exists.
"""
if os.path.exists(self.filepath):
if force:
logger.warn(_("%s already exists. Overwrite.") % self.filepath)
os.remove(self.filepath)
else:
# Already built, do not do anything.
logger.info(_("%s already exists. Nothing to do.") % self.filepath)
return
# Clean previous runs
self._clean_gather()
# If no coverage added, use bottom layer metadata
if len(self._bboxes) == 0 and len(self._layers) > 0:
bottomlayer = self._layers[0]
metadata = bottomlayer.reader.metadata()
if 'bounds' in metadata:
logger.debug(_("Use bounds of bottom layer %s") % bottomlayer)
bbox = map(float, metadata.get('bounds', '').split(','))
zoomlevels = range(int(metadata.get('minzoom', 0)), int(metadata.get('maxzoom', 0)))
self.add_coverage(bbox=bbox, zoomlevels=zoomlevels)
# Compute list of tiles
tileslist = set()
for bbox, levels in self._bboxes:
logger.debug(_("Compute list of tiles for bbox %s on zooms %s.") % (bbox, levels))
bboxlist = self.tileslist(bbox, levels)
logger.debug(_("Add %s tiles.") % len(bboxlist))
tileslist = tileslist.union(bboxlist)
logger.debug(_("%s tiles in total.") % len(tileslist))
self.nbtiles = len(tileslist)
if not self.nbtiles:
raise EmptyCoverageError(_("No tiles are covered by bounding boxes : %s") % self._bboxes)
logger.debug(_("%s tiles to be packaged.") % self.nbtiles)
# Go through whole list of tiles and gather them in tmp_dir
self.rendered = 0
for (z, x, y) in tileslist:
try:
self._gather((z, x, y))
except Exception as e:
logger.warn(e)
if not self.ignore_errors:
raise
logger.debug(_("%s tiles were missing.") % self.rendered)
# Some metadata
middlezoom = self.zoomlevels[len(self.zoomlevels) // 2]
lat = self.bounds[1] + (self.bounds[3] - self.bounds[1])/2
lon = self.bounds[0] + (self.bounds[2] - self.bounds[0])/2
metadata = {}
metadata['name'] = str(uuid.uuid4())
metadata['format'] = self._tile_extension[1:]
metadata['minzoom'] = self.zoomlevels[0]
metadata['maxzoom'] = self.zoomlevels[-1]
metadata['bounds'] = '%s,%s,%s,%s' % tuple(self.bounds)
metadata['center'] = '%s,%s,%s' % (lon, lat, middlezoom)
#display informations from the grids on hover
content_to_display = ''
for field_name in self.grid_fields:
content_to_display += "{{{ %s }}}<br>" % field_name
metadata['template'] = '{{#__location__}}{{/__location__}} {{#__teaser__}} \
%s {{/__teaser__}}{{#__full__}}{{/__full__}}' % content_to_display
metadatafile = os.path.join(self.tmp_dir, 'metadata.json')
with open(metadatafile, 'w') as output:
json.dump(metadata, output)
# TODO: add UTF-Grid of last layer, if any
# Package it!
logger.info(_("Build MBTiles file '%s'.") % self.filepath)
extension = self.tile_format.split("image/")[-1]
disk_to_mbtiles(
self.tmp_dir,
self.filepath,
format=extension,
scheme=self.cache.scheme
)
try:
os.remove("%s-journal" % self.filepath) # created by mbutil
except OSError as e:
pass
self._clean_gather()
def _gather(self, z_x_y):
(z, x, y) = z_x_y
files_dir, tile_name = self.cache.tile_file((z, x, y))
tmp_dir = os.path.join(self.tmp_dir, files_dir)
if not os.path.isdir(tmp_dir):
os.makedirs(tmp_dir)
tilecontent = self.tile((z, x, y))
tilepath = os.path.join(tmp_dir, tile_name)
with open(tilepath, 'wb') as f:
f.write(tilecontent)
if len(self.grid_fields) > 0:
gridcontent = self.grid((z, x, y))
gridpath = "%s.%s" % (os.path.splitext(tilepath)[0], 'grid.json')
with open(gridpath, 'w') as f:
f.write(gridcontent)
def _clean_gather(self):
logger.debug(_("Clean-up %s") % self.tmp_dir)
try:
shutil.rmtree(self.tmp_dir)
#Delete parent folder only if empty
try:
parent = os.path.dirname(self.tmp_dir)
os.rmdir(parent)
logger.debug(_("Clean-up parent %s") % parent)
except OSError:
pass
except OSError:
pass
|
makinacorpus/landez | landez/tiles.py | MBTilesBuilder.run | python | def run(self, force=False):
if os.path.exists(self.filepath):
if force:
logger.warn(_("%s already exists. Overwrite.") % self.filepath)
os.remove(self.filepath)
else:
# Already built, do not do anything.
logger.info(_("%s already exists. Nothing to do.") % self.filepath)
return
# Clean previous runs
self._clean_gather()
# If no coverage added, use bottom layer metadata
if len(self._bboxes) == 0 and len(self._layers) > 0:
bottomlayer = self._layers[0]
metadata = bottomlayer.reader.metadata()
if 'bounds' in metadata:
logger.debug(_("Use bounds of bottom layer %s") % bottomlayer)
bbox = map(float, metadata.get('bounds', '').split(','))
zoomlevels = range(int(metadata.get('minzoom', 0)), int(metadata.get('maxzoom', 0)))
self.add_coverage(bbox=bbox, zoomlevels=zoomlevels)
# Compute list of tiles
tileslist = set()
for bbox, levels in self._bboxes:
logger.debug(_("Compute list of tiles for bbox %s on zooms %s.") % (bbox, levels))
bboxlist = self.tileslist(bbox, levels)
logger.debug(_("Add %s tiles.") % len(bboxlist))
tileslist = tileslist.union(bboxlist)
logger.debug(_("%s tiles in total.") % len(tileslist))
self.nbtiles = len(tileslist)
if not self.nbtiles:
raise EmptyCoverageError(_("No tiles are covered by bounding boxes : %s") % self._bboxes)
logger.debug(_("%s tiles to be packaged.") % self.nbtiles)
# Go through whole list of tiles and gather them in tmp_dir
self.rendered = 0
for (z, x, y) in tileslist:
try:
self._gather((z, x, y))
except Exception as e:
logger.warn(e)
if not self.ignore_errors:
raise
logger.debug(_("%s tiles were missing.") % self.rendered)
# Some metadata
middlezoom = self.zoomlevels[len(self.zoomlevels) // 2]
lat = self.bounds[1] + (self.bounds[3] - self.bounds[1])/2
lon = self.bounds[0] + (self.bounds[2] - self.bounds[0])/2
metadata = {}
metadata['name'] = str(uuid.uuid4())
metadata['format'] = self._tile_extension[1:]
metadata['minzoom'] = self.zoomlevels[0]
metadata['maxzoom'] = self.zoomlevels[-1]
metadata['bounds'] = '%s,%s,%s,%s' % tuple(self.bounds)
metadata['center'] = '%s,%s,%s' % (lon, lat, middlezoom)
#display informations from the grids on hover
content_to_display = ''
for field_name in self.grid_fields:
content_to_display += "{{{ %s }}}<br>" % field_name
metadata['template'] = '{{#__location__}}{{/__location__}} {{#__teaser__}} \
%s {{/__teaser__}}{{#__full__}}{{/__full__}}' % content_to_display
metadatafile = os.path.join(self.tmp_dir, 'metadata.json')
with open(metadatafile, 'w') as output:
json.dump(metadata, output)
# TODO: add UTF-Grid of last layer, if any
# Package it!
logger.info(_("Build MBTiles file '%s'.") % self.filepath)
extension = self.tile_format.split("image/")[-1]
disk_to_mbtiles(
self.tmp_dir,
self.filepath,
format=extension,
scheme=self.cache.scheme
)
try:
os.remove("%s-journal" % self.filepath) # created by mbutil
except OSError as e:
pass
self._clean_gather() | Build a MBTile file.
force -- overwrite if MBTiles file already exists. | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L280-L370 | [
"def tileslist(self, bbox, zoomlevels):\n \"\"\"\n Build the tiles list within the bottom-left/top-right bounding\n box (minx, miny, maxx, maxy) at the specified zoom levels.\n Return a list of tuples (z,x,y)\n \"\"\"\n proj = GoogleProjection(self.tile_size, zoomlevels, self.tile_scheme)\n return proj.tileslist(bbox)\n",
"def add_coverage(self, bbox, zoomlevels):\n \"\"\"\n Add a coverage to be included in the resulting mbtiles file.\n \"\"\"\n self._bboxes.append((bbox, zoomlevels))\n",
"def _gather(self, z_x_y):\n (z, x, y) = z_x_y\n files_dir, tile_name = self.cache.tile_file((z, x, y))\n tmp_dir = os.path.join(self.tmp_dir, files_dir)\n if not os.path.isdir(tmp_dir):\n os.makedirs(tmp_dir)\n tilecontent = self.tile((z, x, y))\n tilepath = os.path.join(tmp_dir, tile_name)\n with open(tilepath, 'wb') as f:\n f.write(tilecontent)\n if len(self.grid_fields) > 0:\n gridcontent = self.grid((z, x, y))\n gridpath = \"%s.%s\" % (os.path.splitext(tilepath)[0], 'grid.json')\n with open(gridpath, 'w') as f:\n f.write(gridcontent)\n",
"def _clean_gather(self):\n logger.debug(_(\"Clean-up %s\") % self.tmp_dir)\n try:\n shutil.rmtree(self.tmp_dir)\n #Delete parent folder only if empty\n try:\n parent = os.path.dirname(self.tmp_dir)\n os.rmdir(parent)\n logger.debug(_(\"Clean-up parent %s\") % parent)\n except OSError:\n pass\n except OSError:\n pass\n"
] | class MBTilesBuilder(TilesManager):
def __init__(self, **kwargs):
"""
A MBTiles builder for a list of bounding boxes and zoom levels.
filepath -- output MBTiles file (default DEFAULT_FILEPATH)
tmp_dir -- temporary folder for gathering tiles (default DEFAULT_TMP_DIR/filepath)
ignore_errors -- ignore errors during MBTiles creation (e.g. download errors)
"""
super(MBTilesBuilder, self).__init__(**kwargs)
self.filepath = kwargs.get('filepath', DEFAULT_FILEPATH)
self.ignore_errors = kwargs.get('ignore_errors', False)
# Gather tiles for mbutil
basename, ext = os.path.splitext(os.path.basename(self.filepath))
self.tmp_dir = kwargs.get('tmp_dir', DEFAULT_TMP_DIR)
self.tmp_dir = os.path.join(self.tmp_dir, basename)
self.tile_format = kwargs.get('tile_format', DEFAULT_TILE_FORMAT)
# Number of tiles in total
self.nbtiles = 0
self._bboxes = []
def add_coverage(self, bbox, zoomlevels):
"""
Add a coverage to be included in the resulting mbtiles file.
"""
self._bboxes.append((bbox, zoomlevels))
@property
def zoomlevels(self):
"""
Return the list of covered zoom levels, in ascending order
"""
zooms = set()
for coverage in self._bboxes:
for zoom in coverage[1]:
zooms.add(zoom)
return sorted(zooms)
@property
def bounds(self):
"""
Return the bounding box of covered areas
"""
return self._bboxes[0][0] #TODO: merge all coverages
def _gather(self, z_x_y):
(z, x, y) = z_x_y
files_dir, tile_name = self.cache.tile_file((z, x, y))
tmp_dir = os.path.join(self.tmp_dir, files_dir)
if not os.path.isdir(tmp_dir):
os.makedirs(tmp_dir)
tilecontent = self.tile((z, x, y))
tilepath = os.path.join(tmp_dir, tile_name)
with open(tilepath, 'wb') as f:
f.write(tilecontent)
if len(self.grid_fields) > 0:
gridcontent = self.grid((z, x, y))
gridpath = "%s.%s" % (os.path.splitext(tilepath)[0], 'grid.json')
with open(gridpath, 'w') as f:
f.write(gridcontent)
def _clean_gather(self):
logger.debug(_("Clean-up %s") % self.tmp_dir)
try:
shutil.rmtree(self.tmp_dir)
#Delete parent folder only if empty
try:
parent = os.path.dirname(self.tmp_dir)
os.rmdir(parent)
logger.debug(_("Clean-up parent %s") % parent)
except OSError:
pass
except OSError:
pass
|
makinacorpus/landez | landez/tiles.py | ImageExporter.grid_tiles | python | def grid_tiles(self, bbox, zoomlevel):
tiles = self.tileslist(bbox, [zoomlevel])
grid = {}
for (z, x, y) in tiles:
if not grid.get(y):
grid[y] = []
grid[y].append(x)
sortedgrid = []
for y in sorted(grid.keys(), reverse=self.tile_scheme == 'tms'):
sortedgrid.append([(x, y) for x in sorted(grid[y])])
return sortedgrid | Return a grid of (x, y) tuples representing the juxtaposition
of tiles on the specified ``bbox`` at the specified ``zoomlevel``. | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L410-L424 | [
"def tileslist(self, bbox, zoomlevels):\n \"\"\"\n Build the tiles list within the bottom-left/top-right bounding\n box (minx, miny, maxx, maxy) at the specified zoom levels.\n Return a list of tuples (z,x,y)\n \"\"\"\n proj = GoogleProjection(self.tile_size, zoomlevels, self.tile_scheme)\n return proj.tileslist(bbox)\n"
] | class ImageExporter(TilesManager):
def __init__(self, **kwargs):
"""
Arrange the tiles and join them together to build a single big image.
"""
super(ImageExporter, self).__init__(**kwargs)
def export_image(self, bbox, zoomlevel, imagepath):
"""
Writes to ``imagepath`` the tiles for the specified bounding box and zoomlevel.
"""
assert has_pil, _("Cannot export image without python PIL")
grid = self.grid_tiles(bbox, zoomlevel)
width = len(grid[0])
height = len(grid)
widthpix = width * self.tile_size
heightpix = height * self.tile_size
result = Image.new("RGBA", (widthpix, heightpix))
offset = (0, 0)
for i, row in enumerate(grid):
for j, (x, y) in enumerate(row):
offset = (j * self.tile_size, i * self.tile_size)
img = self._tile_image(self.tile((zoomlevel, x, y)))
result.paste(img, offset)
logger.info(_("Save resulting image to '%s'") % imagepath)
result.save(imagepath)
|
makinacorpus/landez | landez/tiles.py | ImageExporter.export_image | python | def export_image(self, bbox, zoomlevel, imagepath):
assert has_pil, _("Cannot export image without python PIL")
grid = self.grid_tiles(bbox, zoomlevel)
width = len(grid[0])
height = len(grid)
widthpix = width * self.tile_size
heightpix = height * self.tile_size
result = Image.new("RGBA", (widthpix, heightpix))
offset = (0, 0)
for i, row in enumerate(grid):
for j, (x, y) in enumerate(row):
offset = (j * self.tile_size, i * self.tile_size)
img = self._tile_image(self.tile((zoomlevel, x, y)))
result.paste(img, offset)
logger.info(_("Save resulting image to '%s'") % imagepath)
result.save(imagepath) | Writes to ``imagepath`` the tiles for the specified bounding box and zoomlevel. | train | https://github.com/makinacorpus/landez/blob/6e5c71ded6071158e7943df204cd7bd1ed623a30/landez/tiles.py#L426-L445 | [
"def tile(self, z_x_y):\n \"\"\"\n Return the tile (binary) content of the tile and seed the cache.\n \"\"\"\n (z, x, y) = z_x_y\n logger.debug(_(\"tile method called with %s\") % ([z, x, y]))\n\n output = self.cache.read((z, x, y))\n if output is None:\n output = self.reader.tile(z, x, y)\n # Blend layers\n if len(self._layers) > 0:\n logger.debug(_(\"Will blend %s layer(s)\") % len(self._layers))\n output = self._blend_layers(output, (z, x, y))\n # Apply filters\n for f in self._filters:\n image = f.process(self._tile_image(output))\n output = self._image_tile(image)\n # Save result to cache\n self.cache.save(output, (z, x, y))\n\n self.rendered += 1\n return output\n",
"def _tile_image(self, data):\n \"\"\"\n Tile binary content as PIL Image.\n \"\"\"\n image = Image.open(BytesIO(data))\n return image.convert('RGBA')\n",
"def grid_tiles(self, bbox, zoomlevel):\n \"\"\"\n Return a grid of (x, y) tuples representing the juxtaposition\n of tiles on the specified ``bbox`` at the specified ``zoomlevel``.\n \"\"\"\n tiles = self.tileslist(bbox, [zoomlevel])\n grid = {}\n for (z, x, y) in tiles:\n if not grid.get(y):\n grid[y] = []\n grid[y].append(x)\n sortedgrid = []\n for y in sorted(grid.keys(), reverse=self.tile_scheme == 'tms'):\n sortedgrid.append([(x, y) for x in sorted(grid[y])])\n return sortedgrid\n"
] | class ImageExporter(TilesManager):
def __init__(self, **kwargs):
"""
Arrange the tiles and join them together to build a single big image.
"""
super(ImageExporter, self).__init__(**kwargs)
def grid_tiles(self, bbox, zoomlevel):
"""
Return a grid of (x, y) tuples representing the juxtaposition
of tiles on the specified ``bbox`` at the specified ``zoomlevel``.
"""
tiles = self.tileslist(bbox, [zoomlevel])
grid = {}
for (z, x, y) in tiles:
if not grid.get(y):
grid[y] = []
grid[y].append(x)
sortedgrid = []
for y in sorted(grid.keys(), reverse=self.tile_scheme == 'tms'):
sortedgrid.append([(x, y) for x in sorted(grid[y])])
return sortedgrid
|
frnmst/md-toc | md_toc/__main__.py | main | python | def main(args=None):
retcode = 0
try:
ci = CliInterface()
args = ci.parser.parse_args()
result = args.func(args)
if result is not None:
print(result)
retcode = 0
except Exception:
retcode = 1
traceback.print_exc()
sys.exit(retcode) | Call the CLI interface and wait for the result. | train | https://github.com/frnmst/md-toc/blob/86d2002ecf52fa9e1e5316a31f7eb7d549cb0830/md_toc/__main__.py#L28-L41 | null | #
# __main__.py
#
# Copyright (C) 2017-2019 frnmst (Franco Masotti) <franco.masotti@live.com>
#
# This file is part of md-toc.
#
# md-toc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# md-toc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with md-toc. If not, see <http://www.gnu.org/licenses/>.
#
"""Call the CLI parser."""
import sys
import traceback
from .cli import CliInterface
if __name__ == '__main__':
main()
|
frnmst/md-toc | md_toc/cli.py | CliToApi.write_toc | python | def write_toc(self, args):
# FIXME: Can this logic be moved into the create_parser function?
ordered = False
if args.ordered_list_marker is not None:
list_marker = args.ordered_list_marker
ordered = True
elif args.unordered_list_marker is not None:
list_marker = args.unordered_list_marker
else:
list_marker = md_parser[
args.parser]['list']['unordered']['default_marker']
toc_struct = build_multiple_tocs(
filenames=args.filename,
ordered=ordered,
no_links=args.no_links,
no_indentation=args.no_indentation,
no_list_coherence=args.no_list_coherence,
keep_header_levels=int(args.header_levels),
parser=args.parser,
list_marker=list_marker)
if args.in_place:
write_strings_on_files_between_markers(
filenames=args.filename,
strings=toc_struct,
marker=args.toc_marker)
else:
for toc in toc_struct:
print(toc, end='') | Write the table of contents. | train | https://github.com/frnmst/md-toc/blob/86d2002ecf52fa9e1e5316a31f7eb7d549cb0830/md_toc/cli.py#L46-L75 | [
"def build_multiple_tocs(filenames: list,\n ordered: bool = False,\n no_links: bool = False,\n no_indentation: bool = False,\n no_list_coherence: bool = False,\n keep_header_levels: int = 3,\n parser: str = 'github',\n list_marker: str = '-') -> list:\n r\"\"\"Parse files by line and build the table of contents of each file.\n\n :parameter filenames: the files that needs to be read.\n :parameter ordered: decides whether to build an ordered list or not.\n Defaults to ``False``.\n :parameter no_links: disables the use of links.\n Defaults to ``False``.\n :parameter no_indentation: disables indentation in the list.\n Defaults to ``False``.\n :parameter keep_header_levels: the maximum level of headers to be\n considered as such when building the table of contents.\n Defaults to ``3``.\n :parameter parser: decides rules on how to generate anchor links.\n Defaults to ``github``.\n :type filenames: list\n :type ordered: bool\n :type no_links: bool\n :type no_indentation: bool\n :type keep_header_levels: int\n :type parser: str\n :returns: toc_struct, the corresponding table of contents for each input\n file.\n :rtype: list\n :raises: a built-in exception.\n \"\"\"\n if len(filenames) > 0:\n for f in filenames:\n assert isinstance(f, str)\n\n if len(filenames) == 0:\n filenames.append('-')\n file_id = 0\n toc_struct = list()\n while file_id < len(filenames):\n toc_struct.append(\n build_toc(filenames[file_id], ordered, no_links, no_indentation,\n no_list_coherence, keep_header_levels, parser,\n list_marker))\n file_id += 1\n\n return toc_struct\n",
"def write_strings_on_files_between_markers(filenames: list, strings: list,\n marker: str):\n r\"\"\"Write the table of contents on multiple files.\n\n :parameter filenames: the files that needs to be read or modified.\n :parameter strings: the strings that will be written on the file. Each\n string is associated with one file.\n :parameter marker: a marker that will identify the start\n and the end of the string.\n :type filenames: list\n :type string: list\n :type marker: str\n :returns: None\n :rtype: None\n :raises: an fpyutils exception or a built-in exception.\n \"\"\"\n assert len(filenames) == len(strings)\n if len(filenames) > 0:\n for f in filenames:\n assert isinstance(f, str)\n if len(strings) > 0:\n for s in strings:\n assert isinstance(s, str)\n\n file_id = 0\n for f in filenames:\n write_string_on_file_between_markers(f, strings[file_id], marker)\n file_id += 1\n"
] | class CliToApi():
"""An interface between the CLI and API functions."""
|
frnmst/md-toc | md_toc/cli.py | CliInterface.create_parser | python | def create_parser(self):
parser = argparse.ArgumentParser(
description=PROGRAM_DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent(PROGRAM_EPILOG))
parser.add_argument(
'filename',
metavar='FILE_NAME',
nargs='*',
help='the I/O file name')
subparsers = parser.add_subparsers(
dest='parser', title='markdown parser')
subparsers.required = True
# github + cmark + gitlab + commonmarker.
github = subparsers.add_parser(
'github',
aliases=['cmark', 'gitlab', 'commonmarker'],
description='Use Commonmark rules to generate an output. If no \
option is selected, the default output will be an \
unordered list with the respective default values \
as listed below')
megroup = github.add_mutually_exclusive_group()
megroup.add_argument(
'-u',
'--unordered-list-marker',
choices=md_parser['github']['list']['unordered']['bullet_markers'],
nargs='?',
const=md_parser['github']['list']['unordered']['default_marker'],
help='set the marker and enables unordered list. Defaults to ' +
md_parser['github']['list']['unordered']['default_marker'])
megroup.add_argument(
'-o',
'--ordered-list-marker',
choices=md_parser['github']['list']['ordered']['closing_markers'],
nargs='?',
const=md_parser['github']['list']['ordered']
['default_closing_marker'],
help='set the marker and enables ordered lists. Defaults to ' +
md_parser['github']['list']['ordered']['default_closing_marker'])
github.add_argument(
'-l',
'--header-levels',
choices=[
str(i)
for i in range(1, md_parser['github']['header']['max_levels'] +
1)
],
nargs='?',
const=str(md_parser['github']['header']['default_keep_levels']),
help='set the maximum level of headers to be considered as part \
of the TOC. Defaults to ' + str(
md_parser['github']['header']['default_keep_levels']))
github.set_defaults(
header_levels=md_parser['github']['header']['default_keep_levels'])
# Redcarpet.
redcarpet = subparsers.add_parser(
'redcarpet',
description='Use Redcarpet rules to generate an output. If no \
option is selected, the default output will be an \
unordered list with the respective default values \
as listed below. Gitlab rules are the same as \
Redcarpet except that conflicts are avoided with \
duplicate headers.')
megroup = redcarpet.add_mutually_exclusive_group()
megroup.add_argument(
'-u',
'--unordered-list-marker',
choices=md_parser['redcarpet']['list']['unordered']
['bullet_markers'],
nargs='?',
const=md_parser['redcarpet']['list']['unordered']
['default_marker'],
help='set the marker and enables unordered list. Defaults to ' +
md_parser['redcarpet']['list']['unordered']['default_marker'])
megroup.add_argument(
'-o',
'--ordered-list-marker',
choices=md_parser['redcarpet']['list']['ordered']
['closing_markers'],
nargs='?',
const=md_parser['redcarpet']['list']['ordered']
['default_closing_marker'],
help='set the marker and enables ordered lists. Defaults to ' +
md_parser['redcarpet']['list']['ordered']['default_closing_marker']
)
redcarpet.add_argument(
'-l',
'--header-levels',
choices=[
str(i) for i in range(
1, md_parser['redcarpet']['header']['max_levels'] + 1)
],
nargs='?',
const=str(md_parser['redcarpet']['header']['default_keep_levels']),
help='set the maximum level of headers to be considered as part \
of the TOC. Defaults to ' + str(
md_parser['redcarpet']['header']['default_keep_levels']))
redcarpet.set_defaults(header_levels=md_parser['redcarpet']['header']
['default_keep_levels'])
c_or_i = parser.add_mutually_exclusive_group()
c_or_i.add_argument(
'-c',
'--no-list-coherence',
action='store_true',
help='avoids checking for TOC list coherence')
c_or_i.add_argument(
'-i',
'--no-indentation',
action='store_true',
help='avoids adding indentations to the TOC')
parser.add_argument(
'-l',
'--no-links',
action='store_true',
help='avoids adding links to the TOC')
parser.add_argument(
'-m',
'--toc-marker',
metavar='TOC_MARKER',
help='set the string to be used as the marker for positioning the \
table of contents. Defaults to ' +
common_defaults['toc_marker'])
parser.add_argument(
'-p',
'--in-place',
action='store_true',
help='overwrite the input file')
parser.add_argument(
'-v',
'--version',
action='version',
version=VERSION_NAME + ' ' + VERSION_NUMBER)
parser.set_defaults(toc_marker=common_defaults['toc_marker'])
parser.set_defaults(func=CliToApi().write_toc)
return parser | Create the CLI parser. | train | https://github.com/frnmst/md-toc/blob/86d2002ecf52fa9e1e5316a31f7eb7d549cb0830/md_toc/cli.py#L85-L229 | null | class CliInterface():
"""The interface exposed to the final user."""
def __init__(self):
"""Set the parser variable that will be used instead of using create_parser."""
self.parser = self.create_parser()
|
frnmst/md-toc | md_toc/api.py | write_string_on_file_between_markers | python | def write_string_on_file_between_markers(filename: str, string: str,
marker: str):
r"""Write the table of contents on a single file.
:parameter filename: the file that needs to be read or modified.
:parameter string: the string that will be written on the file.
:parameter marker: a marker that will identify the start
and the end of the string.
:type filenames: str
:type string: str
:type marker: str
:returns: None
:rtype: None
:raises: StdinIsNotAFileToBeWritten or an fpyutils exception
or a built-in exception.
"""
if filename == '-':
raise StdinIsNotAFileToBeWritten
final_string = marker + '\n\n' + string.rstrip() + '\n\n' + marker + '\n'
marker_line_positions = fpyutils.get_line_matches(
filename, marker, 2, loose_matching=True)
if 1 in marker_line_positions:
if 2 in marker_line_positions:
fpyutils.remove_line_interval(filename, marker_line_positions[1],
marker_line_positions[2], filename)
else:
fpyutils.remove_line_interval(filename, marker_line_positions[1],
marker_line_positions[1], filename)
fpyutils.insert_string_at_line(
filename,
final_string,
marker_line_positions[1],
filename,
append=False) | r"""Write the table of contents on a single file.
:parameter filename: the file that needs to be read or modified.
:parameter string: the string that will be written on the file.
:parameter marker: a marker that will identify the start
and the end of the string.
:type filenames: str
:type string: str
:type marker: str
:returns: None
:rtype: None
:raises: StdinIsNotAFileToBeWritten or an fpyutils exception
or a built-in exception. | train | https://github.com/frnmst/md-toc/blob/86d2002ecf52fa9e1e5316a31f7eb7d549cb0830/md_toc/api.py#L35-L70 | null | #
# api.py
#
# Copyright (C) 2017-2019 frnmst (Franco Masotti) <franco.masotti@live.com>
#
# This file is part of md-toc.
#
# md-toc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# md-toc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with md-toc. If not, see <http://www.gnu.org/licenses/>.
#
"""The main file."""
import fpyutils
import re
import curses.ascii
import sys
from .exceptions import (GithubOverflowCharsLinkLabel, GithubEmptyLinkLabel,
GithubOverflowOrderedListMarker,
StdinIsNotAFileToBeWritten,
TocDoesNotRenderAsCoherentList)
from .constants import common_defaults
from .constants import parser as md_parser
def write_strings_on_files_between_markers(filenames: list, strings: list,
marker: str):
r"""Write the table of contents on multiple files.
:parameter filenames: the files that needs to be read or modified.
:parameter strings: the strings that will be written on the file. Each
string is associated with one file.
:parameter marker: a marker that will identify the start
and the end of the string.
:type filenames: list
:type string: list
:type marker: str
:returns: None
:rtype: None
:raises: an fpyutils exception or a built-in exception.
"""
assert len(filenames) == len(strings)
if len(filenames) > 0:
for f in filenames:
assert isinstance(f, str)
if len(strings) > 0:
for s in strings:
assert isinstance(s, str)
file_id = 0
for f in filenames:
write_string_on_file_between_markers(f, strings[file_id], marker)
file_id += 1
def build_toc(filename: str,
ordered: bool = False,
no_links: bool = False,
no_indentation: bool = False,
no_list_coherence: bool = False,
keep_header_levels: int = 3,
parser: str = 'github',
list_marker: str = '-') -> str:
r"""Build the table of contents of a single file.
:parameter filename: the file that needs to be read.
:parameter ordered: decides whether to build an ordered list or not.
Defaults to ``False``.
:parameter no_links: disables the use of links.
Defaults to ``False``.
:parameter no_indentation: disables indentation in the list.
Defaults to ``False``.
:parameter keep_header_levels: the maximum level of headers to be
considered as such when building the table of contents.
Defaults to ``3``.
:parameter parser: decides rules on how to generate anchor links.
Defaults to ``github``.
:type filename: str
:type ordered: bool
:type no_links: bool
:type no_indentation: bool
:type keep_header_levels: int
:type parser: str
:returns: toc, the corresponding table of contents of the file.
:rtype: str
:raises: a built-in exception.
"""
toc = str()
header_type_counter = dict()
header_type_curr = 0
header_type_prev = 0
header_duplicate_counter = dict()
no_of_indentation_spaces_prev = 0
if ordered:
list_marker_log = build_list_marker_log(parser, list_marker)
if filename == '-':
f = sys.stdin
else:
f = open(filename, 'r')
line = f.readline()
if ordered:
list_marker_log = build_list_marker_log(parser, list_marker)
else:
list_marker_log = list()
is_within_code_fence = False
code_fence = None
is_document_end = False
if not no_indentation and not no_list_coherence:
# if indentation and list coherence.
indentation_list = build_indentation_list(parser)
while line:
# Document ending detection.
#
# This changes the state of is_within_code_fence if the
# file has no closing fence markers. This serves no practial
# purpose since the code would run correctly anyway. It is
# however more sematically correct.
#
# See the unit tests (examples 95 and 96 of the github parser)
# and the is_closing_code_fence function.
if filename != '-':
# stdin is not seekable.
file_pointer_pos = f.tell()
if f.readline() == str():
is_document_end = True
f.seek(file_pointer_pos)
# Code fence detection.
if is_within_code_fence:
is_within_code_fence = not is_closing_code_fence(
line, code_fence, is_document_end, parser)
line = f.readline()
else:
code_fence = is_opening_code_fence(line, parser)
if code_fence is not None:
# Update the status of the next line.
is_within_code_fence = True
line = f.readline()
if not is_within_code_fence or code_fence is None:
# Header detection and gathering.
header = get_md_header(line, header_duplicate_counter,
keep_header_levels, parser, no_links)
if header is not None:
header_type_curr = header['type']
# Take care of the ordered TOC.
if ordered:
increase_index_ordered_list(header_type_counter,
header_type_prev,
header_type_curr, parser)
index = header_type_counter[header_type_curr]
else:
index = 1
# Take care of list indentations.
if no_indentation:
no_of_indentation_spaces_curr = 0
# TOC list coherence checks are not necessary
# without indentation.
else:
if not no_list_coherence:
if not toc_renders_as_coherent_list(
header_type_curr, indentation_list, parser):
raise TocDoesNotRenderAsCoherentList
no_of_indentation_spaces_curr = compute_toc_line_indentation_spaces(
header_type_curr, header_type_prev,
no_of_indentation_spaces_prev, parser, ordered,
list_marker, list_marker_log, index)
# Build a single TOC line.
toc_line_no_indent = build_toc_line_without_indentation(
header, ordered, no_links, index, parser, list_marker)
# Save the TOC line with the indentation.
toc += build_toc_line(toc_line_no_indent,
no_of_indentation_spaces_curr) + '\n'
header_type_prev = header_type_curr
no_of_indentation_spaces_prev = no_of_indentation_spaces_curr
# endif
# endif
line = f.readline()
# endwhile
f.close()
return toc
def build_multiple_tocs(filenames: list,
ordered: bool = False,
no_links: bool = False,
no_indentation: bool = False,
no_list_coherence: bool = False,
keep_header_levels: int = 3,
parser: str = 'github',
list_marker: str = '-') -> list:
r"""Parse files by line and build the table of contents of each file.
:parameter filenames: the files that needs to be read.
:parameter ordered: decides whether to build an ordered list or not.
Defaults to ``False``.
:parameter no_links: disables the use of links.
Defaults to ``False``.
:parameter no_indentation: disables indentation in the list.
Defaults to ``False``.
:parameter keep_header_levels: the maximum level of headers to be
considered as such when building the table of contents.
Defaults to ``3``.
:parameter parser: decides rules on how to generate anchor links.
Defaults to ``github``.
:type filenames: list
:type ordered: bool
:type no_links: bool
:type no_indentation: bool
:type keep_header_levels: int
:type parser: str
:returns: toc_struct, the corresponding table of contents for each input
file.
:rtype: list
:raises: a built-in exception.
"""
if len(filenames) > 0:
for f in filenames:
assert isinstance(f, str)
if len(filenames) == 0:
filenames.append('-')
file_id = 0
toc_struct = list()
while file_id < len(filenames):
toc_struct.append(
build_toc(filenames[file_id], ordered, no_links, no_indentation,
no_list_coherence, keep_header_levels, parser,
list_marker))
file_id += 1
return toc_struct
def increase_index_ordered_list(header_type_count: dict,
header_type_prev: int,
header_type_curr: int,
parser: str = 'github'):
r"""Compute the current index for ordered list table of contents.
:parameter header_type_count: the count of each header type.
:parameter header_type_prev: the previous type of header (h[1-Inf]).
:parameter header_type_curr: the current type of header (h[1-Inf]).
:parameter parser: decides rules on how to generate ordered list markers.
Defaults to ``github``.
:type header_type_count: dict
:type header_type_prev: int
:type header_type_curr: int
:type parser: str
:returns: None
:rtype: None
:raises: GithubOverflowOrderedListMarker or a built-in exception.
"""
# header_type_prev might be 0 while header_type_curr can't.
assert header_type_prev >= 0
assert header_type_curr >= 1
# Base cases for a new table of contents or a new index type.
if header_type_prev == 0:
header_type_prev = header_type_curr
if (header_type_curr not in header_type_count
or header_type_prev < header_type_curr):
header_type_count[header_type_curr] = 0
header_type_count[header_type_curr] += 1
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
if header_type_count[header_type_curr] > md_parser['github']['list'][
'ordered']['max_marker_number']:
raise GithubOverflowOrderedListMarker
def build_list_marker_log(parser: str = 'github',
list_marker: str = '.') -> list:
r"""Create a data structure that holds list marker information.
:parameter parser: decides rules on how compute indentations.
Defaults to ``github``.
:parameter list_marker: a string that contains some of the first
characters of the list element. Defaults to ``-``.
:type parser: str
:type list_marker: str
:returns: list_marker_log, the data structure.
:rtype: list
:raises: a built-in exception.
.. note::
This function makes sense for ordered lists only.
"""
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
assert list_marker in md_parser[parser]['list']['ordered'][
'closing_markers']
list_marker_log = list()
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
list_marker_log = [
str(md_parser['github']['list']['ordered']['min_marker_number']) +
list_marker
for i in range(0, md_parser['github']['header']['max_levels'])
]
elif parser == 'redcarpet':
pass
return list_marker_log
def compute_toc_line_indentation_spaces(
header_type_curr: int = 1,
header_type_prev: int = 0,
no_of_indentation_spaces_prev: int = 0,
parser: str = 'github',
ordered: bool = False,
list_marker: str = '-',
list_marker_log: list = build_list_marker_log('github', '.'),
index: int = 1) -> int:
r"""Compute the number of indentation spaces for the TOC list element.
:parameter header_type_curr: the current type of header (h[1-Inf]).
Defaults to ``1``.
:parameter header_type_prev: the previous type of header (h[1-Inf]).
Defaults to ``0``.
:parameter no_of_indentation_spaces_prev: the number of previous indentation spaces.
Defaults to ``0``.
:parameter parser: decides rules on how compute indentations.
Defaults to ``github``.
:parameter ordered: if set to ``True``, numbers will be used
as list ids or otherwise a dash character, otherwise.
Defaults to ``False``.
:parameter list_marker: a string that contains some of the first
characters of the list element.
Defaults to ``-``.
:parameter list_marker_log: a data structure that holds list marker
information for ordered lists.
Defaults to ``build_list_marker_log('github', '.')``.
:parameter index: a number that will be used as list id in case of an
ordered table of contents. Defaults to ``1``.
:type header_type_curr: int
:type header_type_prev: int
:type no_of_indentation_spaces_prev: int
:type parser: str
:type ordered: bool
:type list_marker: str
:type list_marker_log: list
:type index: int
:returns: no_of_indentation_spaces_curr, the number of indentation spaces
for the list element.
:rtype: int
:raises: a built-in exception.
.. note::
Please note that this function
assumes that no_of_indentation_spaces_prev contains the correct
number of spaces.
"""
assert header_type_curr >= 1
assert header_type_prev >= 0
assert no_of_indentation_spaces_prev >= 0
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
if ordered:
assert list_marker in md_parser[parser]['list']['ordered'][
'closing_markers']
else:
assert list_marker in md_parser[parser]['list']['unordered'][
'bullet_markers']
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
if ordered:
assert len(
list_marker_log) == md_parser['github']['header']['max_levels']
for e in list_marker_log:
assert isinstance(e, str)
assert index >= 1
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
if header_type_prev == 0:
# Base case for the first toc line.
no_of_indentation_spaces_curr = 0
elif header_type_curr == header_type_prev:
# Base case for same indentation.
no_of_indentation_spaces_curr = no_of_indentation_spaces_prev
else:
if ordered:
list_marker_prev = str(list_marker_log[header_type_curr - 1])
else:
# list_marker for unordered lists will always be 1 character.
list_marker_prev = list_marker
# Generic cases.
if header_type_curr > header_type_prev:
# More indentation.
no_of_indentation_spaces_curr = (
no_of_indentation_spaces_prev + len(list_marker_prev) +
len(' '))
elif header_type_curr < header_type_prev:
# Less indentation.
no_of_indentation_spaces_curr = (
no_of_indentation_spaces_prev -
(len(list_marker_prev) + len(' ')))
# Reset older nested list indices. If this is not performed then
# future nested ordered lists will rely on incorrect data to
# compute indentations.
if ordered:
for i in range((header_type_curr - 1) + 1,
md_parser['github']['header']['max_levels']):
list_marker_log[i] = str(
md_parser['github']['list']['ordered']
['min_marker_number']) + list_marker
# Update the data structure.
if ordered:
list_marker_log[header_type_curr - 1] = str(index) + list_marker
elif parser == 'redcarpet':
no_of_indentation_spaces_curr = 4 * (header_type_curr - 1)
return no_of_indentation_spaces_curr
def build_toc_line_without_indentation(header: dict,
ordered: bool = False,
no_links: bool = False,
index: int = 1,
parser: str = 'github',
list_marker: str = '-') -> str:
r"""Return a list element of the table of contents.
:parameter header: a data structure that contains the original
text, the trimmed text and the type of header.
:parameter ordered: if set to ``True``, numbers will be used
as list ids, otherwise a dash character. Defaults
to ``False``.
:parameter no_links: disables the use of links. Defaults to ``False``.
:parameter index: a number that will be used as list id in case of an
ordered table of contents. Defaults to ``1``.
:parameter parser: decides rules on how compute indentations.
Defaults to ``github``.
:parameter list_marker: a string that contains some of the first
characters of the list element. Defaults to ``-``.
:type header: dict
:type ordered: bool
:type no_links: bool
:type index: int
:type parser: str
:type list_marker: str
:returns: toc_line_no_indent, a single line of the table of contents
without indentation.
:rtype: str
:raises: a built-in exception.
"""
assert 'type' in header
assert 'text_original' in header
assert 'text_anchor_link' in header
assert isinstance(header['type'], int)
assert isinstance(header['text_original'], str)
assert isinstance(header['text_anchor_link'], str)
assert header['type'] >= 1
assert index >= 1
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
if ordered:
assert list_marker in md_parser[parser]['list']['ordered'][
'closing_markers']
else:
assert list_marker in md_parser[parser]['list']['unordered'][
'bullet_markers']
toc_line_no_indent = str()
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
if ordered:
list_marker = str(index) + list_marker
# FIXME: is this always correct?
if no_links:
line = header['text_original']
else:
line = '[' + header['text_original'] + ']' + '(#' + header[
'text_anchor_link'] + ')'
toc_line_no_indent = list_marker + ' ' + line
return toc_line_no_indent
def build_toc_line(toc_line_no_indent: str,
no_of_indentation_spaces: int = 0) -> str:
r"""Build the TOC line.
:parameter toc_line_no_indent: the TOC line without indentation.
:parameter no_of_indentation_spaces: the number of indentation spaces.
Defaults to ``0``.
:type toc_line_no_indent: str
:type no_of_indentation_spaces: int
:returns: toc_line, a single line of the table of contents.
:rtype: str
:raises: a built-in exception.
"""
assert no_of_indentation_spaces >= 0
indentation = no_of_indentation_spaces * ' '
toc_line = indentation + toc_line_no_indent
return toc_line
def build_anchor_link(header_text_trimmed: str,
header_duplicate_counter: str,
parser: str = 'github') -> str:
r"""Apply the specified slug rule to build the anchor link.
:parameter header_text_trimmed: the text that needs to be transformed
in a link.
:parameter header_duplicate_counter: a data structure that keeps track of
possible duplicate header links in order to avoid them. This is
meaningful only for certain values of parser.
:parameter parser: decides rules on how to generate anchor links.
Defaults to ``github``.
:type header_text_trimmed: str
:type header_duplicate_counter: dict
:type parser: str
:returns: None if the specified parser is not recognized, or the anchor
link, otherwise.
:rtype: str
:raises: a built-in exception.
.. note::
The licenses of each markdown parser algorithm are reported on
the 'Markdown spec' documentation page.
"""
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
header_text_trimmed = header_text_trimmed.lower()
# Remove punctuation: Keep spaces, hypens and "word characters"
# only.
header_text_trimmed = re.sub(r'[^\w\s\- ]', '', header_text_trimmed)
header_text_trimmed = header_text_trimmed.replace(' ', '-')
# Check for duplicates.
ht = header_text_trimmed
# Set the initial value if we are examining the first occurrency.
# The state of header_duplicate_counter is available to the caller
# functions.
if header_text_trimmed not in header_duplicate_counter:
header_duplicate_counter[header_text_trimmed] = 0
if header_duplicate_counter[header_text_trimmed] > 0:
header_text_trimmed = header_text_trimmed + '-' + str(
header_duplicate_counter[header_text_trimmed])
header_duplicate_counter[ht] += 1
return header_text_trimmed
elif parser == 'redcarpet':
# To ensure full compatibility what follows is a direct translation
# of the rndr_header_anchor C function used in redcarpet.
STRIPPED = " -&+$,/:;=?@\"#{}|^~[]`\\*()%.!'"
header_text_trimmed_len = len(header_text_trimmed)
inserted = 0
stripped = 0
header_text_trimmed_middle_stage = ''
for i in range(0, header_text_trimmed_len):
if header_text_trimmed[i] == '<':
while i < header_text_trimmed_len and header_text_trimmed[
i] != '>':
i += 1
elif header_text_trimmed[i] == '&':
while i < header_text_trimmed_len and header_text_trimmed[
i] != ';':
i += 1
# str.find() == -1 if character is not found in str.
# https://docs.python.org/3.6/library/stdtypes.html?highlight=find#str.find
elif not curses.ascii.isascii(
header_text_trimmed[i]) or STRIPPED.find(
header_text_trimmed[i]) != -1:
if inserted and not stripped:
header_text_trimmed_middle_stage += '-'
stripped = 1
else:
header_text_trimmed_middle_stage += header_text_trimmed[
i].lower()
stripped = 0
inserted += 1
if stripped > 0 and inserted > 0:
header_text_trimmed_middle_stage = header_text_trimmed_middle_stage[
0:-1]
if inserted == 0 and header_text_trimmed_len > 0:
hash = 5381
for i in range(0, header_text_trimmed_len):
# Get the unicode representation with ord.
# Unicode should be equal to ASCII in ASCII's range of
# characters.
hash = ((hash << 5) + hash) + ord(header_text_trimmed[i])
# This is equivalent to %x in C. In Python we don't have
# the length problem so %x is equal to %lx in this case.
# Apparently there is no %l in Python...
header_text_trimmed_middle_stage = 'part-' + '{0:x}'.format(hash)
return header_text_trimmed_middle_stage
def get_atx_heading(line: str,
keep_header_levels: int = 3,
parser: str = 'github',
no_links: bool = False):
r"""Given a line extract the link label and its type.
:parameter line: the line to be examined.
:parameter keep_header_levels: the maximum level of headers to be
considered as such when building the table of contents.
Defaults to ``3``.
:parameter parser: decides rules on how to generate the anchor text.
Defaults to ``github``.
:parameter no_links: disables the use of links.
:type line: str
:type keep_header_levels: int
:type parser: str
:type np_links: bool
:returns: None if the line does not contain header elements according to
the rules of the selected markdown parser, or a tuple containing the
header type and the trimmed header text, according to the selected
parser rules, otherwise.
:rtype: typing.Optional[tuple]
:raises: GithubEmptyLinkLabel or GithubOverflowCharsLinkLabel or a
built-in exception.
"""
assert keep_header_levels >= 1
if len(line) == 0:
return None
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
if line[0] == '\u005c':
return None
i = 0
while i < len(line) and line[i] == ' ' and i <= md_parser['github'][
'header']['max_space_indentation']:
i += 1
if i > md_parser['github']['header']['max_space_indentation']:
return None
offset = i
while i < len(line) and line[i] == '#' and i <= md_parser['github'][
'header']['max_levels'] + offset:
i += 1
if i - offset > md_parser['github']['header'][
'max_levels'] or i - offset > keep_header_levels or i - offset == 0:
return None
current_headers = i - offset
# Include special cases for line endings which should not be
# discarded as non-ATX headers.
if i < len(line) and (line[i] != ' ' and line[i] != '\u000a'
and line[i] != '\u000d'):
return None
i += 1
# Exclude leading whitespaces after the ATX header identifier.
while i < len(line) and line[i] == ' ':
i += 1
# An algorithm to find the start and the end of the closing sequence.
# The closing sequence includes all the significant part of the
# string. This algorithm has a complexity of O(n) with n being the
# length of the line.
cs_start = i
cs_end = cs_start
line_prime = line[::-1]
hash_char_rounds = 0
go_on = True
i = 0
i_prev = i
while i < len(line) - cs_start - 1 and go_on:
if ((line_prime[i] != ' ' and line_prime[i] != '#')
or hash_char_rounds > 1):
if i > i_prev:
cs_end = len(line_prime) - i_prev
else:
cs_end = len(line_prime) - i
go_on = False
while go_on and line_prime[i] == ' ':
i += 1
i_prev = i
while go_on and line_prime[i] == '#':
i += 1
if i > i_prev:
hash_char_rounds += 1
# Instead of changing the whole algorithm to check for line
# endings, this seems cleaner.
find_newline = line.find('\u000a')
find_carriage_return = line.find('\u000d')
if find_newline != -1:
cs_end = min(cs_end, find_newline)
if find_carriage_return != -1:
cs_end = min(cs_end, find_carriage_return)
final_line = line[cs_start:cs_end]
if not no_links:
if len(final_line) > 0 and final_line[-1] == '\u005c':
final_line += ' '
if len(
final_line.strip('\u0020').strip('\u0009').strip('\u000a').
strip('\u000b').strip('\u000c').strip('\u000d')) == 0:
raise GithubEmptyLinkLabel
if len(final_line
) > md_parser['github']['link']['max_chars_label']:
raise GithubOverflowCharsLinkLabel
# Escape square brackets if not already escaped.
i = 0
while i < len(final_line):
if (final_line[i] == '[' or final_line[i] == ']'):
j = i - 1
consecutive_escape_characters = 0
while j >= 0 and final_line[j] == '\u005c':
consecutive_escape_characters += 1
j -= 1
if ((consecutive_escape_characters > 0
and consecutive_escape_characters % 2 == 0)
or consecutive_escape_characters == 0):
tmp = '\u005c'
else:
tmp = str()
final_line = final_line[0:i] + tmp + final_line[i:len(
final_line)]
i += 1 + len(tmp)
else:
i += 1
elif parser == 'redcarpet':
if line[0] != '#':
return None
i = 0
while (i < len(line)
and i < md_parser['redcarpet']['header']['max_levels']
and line[i] == '#'):
i += 1
current_headers = i
if i < len(line) and line[i] != ' ':
return None
while i < len(line) and line[i] == ' ':
i += 1
end = i
while end < len(line) and line[end] != '\n':
end += 1
while end > 0 and line[end - 1] == '#':
end -= 1
while end > 0 and line[end - 1] == ' ':
end -= 1
if end > i:
final_line = line
if not no_links and len(final_line) > 0 and final_line[-1] == '\\':
final_line += ' '
end += 1
final_line = final_line[i:end]
else:
return None
# TODO: escape or remove '[', ']', '(', ')' in inline links for redcarpet,
# TODO: check link label rules for redcarpet.
return current_headers, final_line
def get_md_header(header_text_line: str,
header_duplicate_counter: dict,
keep_header_levels: int = 3,
parser: str = 'github',
no_links: bool = False) -> dict:
r"""Build a data structure with the elements needed to create a TOC line.
:parameter header_text_line: a single markdown line that needs to be
transformed into a TOC line.
:parameter header_duplicate_counter: a data structure that contains the
number of occurrencies of each header anchor link. This is used to
avoid duplicate anchor links and it is meaningful only for certain
values of parser.
:parameter keep_header_levels: the maximum level of headers to be
considered as such when building the table of contents.
Defaults to ``3``.
:parameter parser: decides rules on how to generate anchor links.
Defaults to ``github``.
:type header_text_line: str
:type header_duplicate_counter: dict
:type keep_header_levels: int
:type parser: str
:returns: None if the input line does not correspond to one of the
designated cases or a data structure containing the necessary
components to create a table of contents line, otherwise.
:rtype: dict
:raises: a built-in exception.
.. note::
This works like a wrapper to other functions.
"""
result = get_atx_heading(header_text_line, keep_header_levels, parser,
no_links)
if result is None:
return result
else:
header_type, header_text_trimmed = result
header = {
'type':
header_type,
'text_original':
header_text_trimmed,
'text_anchor_link':
build_anchor_link(header_text_trimmed, header_duplicate_counter,
parser)
}
return header
def is_valid_code_fence_indent(line: str, parser: str = 'github') -> bool:
r"""Determine if the given line has valid indentation for a code block fence.
:parameter line: a single markdown line to evaluate.
:parameter parser: decides rules on how to generate the anchor text.
Defaults to ``github``.
:type line: str
:type parser: str
:returns: True if the given line has valid indentation or False
otherwise.
:rtype: bool
:raises: a built-in exception.
"""
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
return len(line) - len(line.lstrip(
' ')) <= md_parser['github']['code fence']['min_marker_characters']
elif parser == 'redcarpet':
# TODO.
return False
def is_opening_code_fence(line: str, parser: str = 'github'):
r"""Determine if the given line is possibly the opening of a fenced code block.
:parameter line: a single markdown line to evaluate.
:parameter parser: decides rules on how to generate the anchor text.
Defaults to ``github``.
:type line: str
:type parser: str
:returns: None if the input line is not an opening code fence. Otherwise,
returns the string which will identify the closing code fence
according to the input parsers' rules.
:rtype: typing.Optional[str]
:raises: a built-in exception.
"""
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
markers = md_parser['github']['code fence']['marker']
marker_min_length = md_parser['github']['code fence'][
'min_marker_characters']
if not is_valid_code_fence_indent(line):
return None
line = line.lstrip(' ').rstrip('\n')
if not line.startswith(
(markers[0] * marker_min_length, markers[1] * marker_min_length)):
return None
if line == len(line) * line[0]:
info_string = str()
else:
info_string = line.lstrip(line[0])
# Backticks or tildes in info string are explicitly forbidden.
if markers[0] in info_string or markers[1] in info_string:
return None
# Solves example 107. See:
# https://github.github.com/gfm/#example-107
if line.rstrip(markers[0]) != line and line.rstrip(markers[1]) != line:
return None
return line.rstrip(info_string)
elif parser == 'redcarpet':
# TODO.
return None
def is_closing_code_fence(line: str,
fence: str,
is_document_end: bool = False,
parser: str = 'github') -> bool:
r"""Determine if the given line is the end of a fenced code block.
:parameter line: a single markdown line to evaluate.
:paramter fence: a sequence of backticks or tildes marking the start of
the current code block. This is usually the return value of the
is_opening_code_fence function.
:parameter is_document_end: This variable tells the function that the
end of the file is reached.
Defaults to ``False``.
:parameter parser: decides rules on how to generate the anchor text.
Defaults to ``github``.
:type line: str
:type fence: str
:type is_document_end: bool
:type parser: str
:returns: True if the line ends the current code block. False otherwise.
:rtype: bool
:raises: a built-in exception.
"""
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
markers = md_parser['github']['code fence']['marker']
marker_min_length = md_parser['github']['code fence'][
'min_marker_characters']
if not is_valid_code_fence_indent(line):
return False
# Remove opening fence indentation after it is known to be valid.
fence = fence.lstrip(' ')
# Check if fence uses valid characters.
if not fence.startswith((markers[0], markers[1])):
return False
if len(fence) < marker_min_length:
return False
# Additional security.
fence = fence.rstrip('\n').rstrip(' ')
# Check that all fence characters are equal.
if fence != len(fence) * fence[0]:
return False
# We might be inside a code block if this is not closed
# by the end of the document, according to example 95 and 96.
# This means that the end of the document corresponds to
# a closing code fence.
# Of course we first have to check that fence is a valid opening
# code fence marker.
# See:
# https://github.github.com/gfm/#example-95
# https://github.github.com/gfm/#example-96
if is_document_end:
return True
# Check if line uses the same character as fence.
line = line.lstrip(' ')
if not line.startswith(fence):
return False
line = line.rstrip('\n').rstrip(' ')
# Solves example 93 and 94. See:
# https://github.github.com/gfm/#example-93
# https://github.github.com/gfm/#example-94
if len(line) < len(fence):
return False
# Closing fence must not have alien characters.
if line != len(line) * line[0]:
return False
return True
elif parser == 'redcarpet':
# TODO.
return False
def build_indentation_list(parser: str = 'github'):
r"""Create a data structure that holds the state of indentations.
:parameter parser: decides the length of the list.
Defaults to ``github``.
:type parser: str
:returns: indentation_list, a list that contains the state of
indentations given a header type.
:rtype: list
:raises: a built-in exception.
"""
indentation_list = list()
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
for i in range(0, md_parser[parser]['header']['max_levels']):
indentation_list.append(False)
return indentation_list
def toc_renders_as_coherent_list(
header_type_curr: int = 1,
indentation_list: list = build_indentation_list('github'),
parser: str = 'github') -> bool:
r"""Check if the TOC will render as a working list.
:parameter header_type_curr: the current type of header (h[1-Inf]).
:parameter parser: decides rules on how to generate ordered list markers
:type header_type_curr: int
:type indentation_list: list
:type parser: str
:returns: renders_as_list
:rtype: bool
:raises: a built-in exception.
"""
assert header_type_curr >= 1
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
assert len(
indentation_list) == md_parser[parser]['header']['max_levels']
for e in indentation_list:
assert isinstance(e, bool)
renders_as_list = True
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
# Update with current information.
indentation_list[header_type_curr - 1] = True
# Reset next cells to False, as a detection mechanism.
for i in range(header_type_curr,
md_parser['github']['header']['max_levels']):
indentation_list[i] = False
# Check for previous False cells. If there is a "hole" in the list
# it means that the TOC will have "wrong" indentation spaces, thus
# either not rendering as an HTML list or not as the user intended.
i = header_type_curr - 1
while i >= 0 and indentation_list[i]:
i -= 1
if i >= 0:
renders_as_list = False
return renders_as_list
if __name__ == '__main__':
pass
|
frnmst/md-toc | md_toc/api.py | write_strings_on_files_between_markers | python | def write_strings_on_files_between_markers(filenames: list, strings: list,
marker: str):
r"""Write the table of contents on multiple files.
:parameter filenames: the files that needs to be read or modified.
:parameter strings: the strings that will be written on the file. Each
string is associated with one file.
:parameter marker: a marker that will identify the start
and the end of the string.
:type filenames: list
:type string: list
:type marker: str
:returns: None
:rtype: None
:raises: an fpyutils exception or a built-in exception.
"""
assert len(filenames) == len(strings)
if len(filenames) > 0:
for f in filenames:
assert isinstance(f, str)
if len(strings) > 0:
for s in strings:
assert isinstance(s, str)
file_id = 0
for f in filenames:
write_string_on_file_between_markers(f, strings[file_id], marker)
file_id += 1 | r"""Write the table of contents on multiple files.
:parameter filenames: the files that needs to be read or modified.
:parameter strings: the strings that will be written on the file. Each
string is associated with one file.
:parameter marker: a marker that will identify the start
and the end of the string.
:type filenames: list
:type string: list
:type marker: str
:returns: None
:rtype: None
:raises: an fpyutils exception or a built-in exception. | train | https://github.com/frnmst/md-toc/blob/86d2002ecf52fa9e1e5316a31f7eb7d549cb0830/md_toc/api.py#L73-L100 | [
"def write_string_on_file_between_markers(filename: str, string: str,\n marker: str):\n r\"\"\"Write the table of contents on a single file.\n\n :parameter filename: the file that needs to be read or modified.\n :parameter string: the string that will be written on the file.\n :parameter marker: a marker that will identify the start\n and the end of the string.\n :type filenames: str\n :type string: str\n :type marker: str\n :returns: None\n :rtype: None\n :raises: StdinIsNotAFileToBeWritten or an fpyutils exception\n or a built-in exception.\n \"\"\"\n if filename == '-':\n raise StdinIsNotAFileToBeWritten\n\n final_string = marker + '\\n\\n' + string.rstrip() + '\\n\\n' + marker + '\\n'\n marker_line_positions = fpyutils.get_line_matches(\n filename, marker, 2, loose_matching=True)\n\n if 1 in marker_line_positions:\n if 2 in marker_line_positions:\n fpyutils.remove_line_interval(filename, marker_line_positions[1],\n marker_line_positions[2], filename)\n else:\n fpyutils.remove_line_interval(filename, marker_line_positions[1],\n marker_line_positions[1], filename)\n fpyutils.insert_string_at_line(\n filename,\n final_string,\n marker_line_positions[1],\n filename,\n append=False)\n"
] | #
# api.py
#
# Copyright (C) 2017-2019 frnmst (Franco Masotti) <franco.masotti@live.com>
#
# This file is part of md-toc.
#
# md-toc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# md-toc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with md-toc. If not, see <http://www.gnu.org/licenses/>.
#
"""The main file."""
import fpyutils
import re
import curses.ascii
import sys
from .exceptions import (GithubOverflowCharsLinkLabel, GithubEmptyLinkLabel,
GithubOverflowOrderedListMarker,
StdinIsNotAFileToBeWritten,
TocDoesNotRenderAsCoherentList)
from .constants import common_defaults
from .constants import parser as md_parser
def write_string_on_file_between_markers(filename: str, string: str,
marker: str):
r"""Write the table of contents on a single file.
:parameter filename: the file that needs to be read or modified.
:parameter string: the string that will be written on the file.
:parameter marker: a marker that will identify the start
and the end of the string.
:type filenames: str
:type string: str
:type marker: str
:returns: None
:rtype: None
:raises: StdinIsNotAFileToBeWritten or an fpyutils exception
or a built-in exception.
"""
if filename == '-':
raise StdinIsNotAFileToBeWritten
final_string = marker + '\n\n' + string.rstrip() + '\n\n' + marker + '\n'
marker_line_positions = fpyutils.get_line_matches(
filename, marker, 2, loose_matching=True)
if 1 in marker_line_positions:
if 2 in marker_line_positions:
fpyutils.remove_line_interval(filename, marker_line_positions[1],
marker_line_positions[2], filename)
else:
fpyutils.remove_line_interval(filename, marker_line_positions[1],
marker_line_positions[1], filename)
fpyutils.insert_string_at_line(
filename,
final_string,
marker_line_positions[1],
filename,
append=False)
def build_toc(filename: str,
ordered: bool = False,
no_links: bool = False,
no_indentation: bool = False,
no_list_coherence: bool = False,
keep_header_levels: int = 3,
parser: str = 'github',
list_marker: str = '-') -> str:
r"""Build the table of contents of a single file.
:parameter filename: the file that needs to be read.
:parameter ordered: decides whether to build an ordered list or not.
Defaults to ``False``.
:parameter no_links: disables the use of links.
Defaults to ``False``.
:parameter no_indentation: disables indentation in the list.
Defaults to ``False``.
:parameter keep_header_levels: the maximum level of headers to be
considered as such when building the table of contents.
Defaults to ``3``.
:parameter parser: decides rules on how to generate anchor links.
Defaults to ``github``.
:type filename: str
:type ordered: bool
:type no_links: bool
:type no_indentation: bool
:type keep_header_levels: int
:type parser: str
:returns: toc, the corresponding table of contents of the file.
:rtype: str
:raises: a built-in exception.
"""
toc = str()
header_type_counter = dict()
header_type_curr = 0
header_type_prev = 0
header_duplicate_counter = dict()
no_of_indentation_spaces_prev = 0
if ordered:
list_marker_log = build_list_marker_log(parser, list_marker)
if filename == '-':
f = sys.stdin
else:
f = open(filename, 'r')
line = f.readline()
if ordered:
list_marker_log = build_list_marker_log(parser, list_marker)
else:
list_marker_log = list()
is_within_code_fence = False
code_fence = None
is_document_end = False
if not no_indentation and not no_list_coherence:
# if indentation and list coherence.
indentation_list = build_indentation_list(parser)
while line:
# Document ending detection.
#
# This changes the state of is_within_code_fence if the
# file has no closing fence markers. This serves no practial
# purpose since the code would run correctly anyway. It is
# however more sematically correct.
#
# See the unit tests (examples 95 and 96 of the github parser)
# and the is_closing_code_fence function.
if filename != '-':
# stdin is not seekable.
file_pointer_pos = f.tell()
if f.readline() == str():
is_document_end = True
f.seek(file_pointer_pos)
# Code fence detection.
if is_within_code_fence:
is_within_code_fence = not is_closing_code_fence(
line, code_fence, is_document_end, parser)
line = f.readline()
else:
code_fence = is_opening_code_fence(line, parser)
if code_fence is not None:
# Update the status of the next line.
is_within_code_fence = True
line = f.readline()
if not is_within_code_fence or code_fence is None:
# Header detection and gathering.
header = get_md_header(line, header_duplicate_counter,
keep_header_levels, parser, no_links)
if header is not None:
header_type_curr = header['type']
# Take care of the ordered TOC.
if ordered:
increase_index_ordered_list(header_type_counter,
header_type_prev,
header_type_curr, parser)
index = header_type_counter[header_type_curr]
else:
index = 1
# Take care of list indentations.
if no_indentation:
no_of_indentation_spaces_curr = 0
# TOC list coherence checks are not necessary
# without indentation.
else:
if not no_list_coherence:
if not toc_renders_as_coherent_list(
header_type_curr, indentation_list, parser):
raise TocDoesNotRenderAsCoherentList
no_of_indentation_spaces_curr = compute_toc_line_indentation_spaces(
header_type_curr, header_type_prev,
no_of_indentation_spaces_prev, parser, ordered,
list_marker, list_marker_log, index)
# Build a single TOC line.
toc_line_no_indent = build_toc_line_without_indentation(
header, ordered, no_links, index, parser, list_marker)
# Save the TOC line with the indentation.
toc += build_toc_line(toc_line_no_indent,
no_of_indentation_spaces_curr) + '\n'
header_type_prev = header_type_curr
no_of_indentation_spaces_prev = no_of_indentation_spaces_curr
# endif
# endif
line = f.readline()
# endwhile
f.close()
return toc
def build_multiple_tocs(filenames: list,
ordered: bool = False,
no_links: bool = False,
no_indentation: bool = False,
no_list_coherence: bool = False,
keep_header_levels: int = 3,
parser: str = 'github',
list_marker: str = '-') -> list:
r"""Parse files by line and build the table of contents of each file.
:parameter filenames: the files that needs to be read.
:parameter ordered: decides whether to build an ordered list or not.
Defaults to ``False``.
:parameter no_links: disables the use of links.
Defaults to ``False``.
:parameter no_indentation: disables indentation in the list.
Defaults to ``False``.
:parameter keep_header_levels: the maximum level of headers to be
considered as such when building the table of contents.
Defaults to ``3``.
:parameter parser: decides rules on how to generate anchor links.
Defaults to ``github``.
:type filenames: list
:type ordered: bool
:type no_links: bool
:type no_indentation: bool
:type keep_header_levels: int
:type parser: str
:returns: toc_struct, the corresponding table of contents for each input
file.
:rtype: list
:raises: a built-in exception.
"""
if len(filenames) > 0:
for f in filenames:
assert isinstance(f, str)
if len(filenames) == 0:
filenames.append('-')
file_id = 0
toc_struct = list()
while file_id < len(filenames):
toc_struct.append(
build_toc(filenames[file_id], ordered, no_links, no_indentation,
no_list_coherence, keep_header_levels, parser,
list_marker))
file_id += 1
return toc_struct
def increase_index_ordered_list(header_type_count: dict,
header_type_prev: int,
header_type_curr: int,
parser: str = 'github'):
r"""Compute the current index for ordered list table of contents.
:parameter header_type_count: the count of each header type.
:parameter header_type_prev: the previous type of header (h[1-Inf]).
:parameter header_type_curr: the current type of header (h[1-Inf]).
:parameter parser: decides rules on how to generate ordered list markers.
Defaults to ``github``.
:type header_type_count: dict
:type header_type_prev: int
:type header_type_curr: int
:type parser: str
:returns: None
:rtype: None
:raises: GithubOverflowOrderedListMarker or a built-in exception.
"""
# header_type_prev might be 0 while header_type_curr can't.
assert header_type_prev >= 0
assert header_type_curr >= 1
# Base cases for a new table of contents or a new index type.
if header_type_prev == 0:
header_type_prev = header_type_curr
if (header_type_curr not in header_type_count
or header_type_prev < header_type_curr):
header_type_count[header_type_curr] = 0
header_type_count[header_type_curr] += 1
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
if header_type_count[header_type_curr] > md_parser['github']['list'][
'ordered']['max_marker_number']:
raise GithubOverflowOrderedListMarker
def build_list_marker_log(parser: str = 'github',
list_marker: str = '.') -> list:
r"""Create a data structure that holds list marker information.
:parameter parser: decides rules on how compute indentations.
Defaults to ``github``.
:parameter list_marker: a string that contains some of the first
characters of the list element. Defaults to ``-``.
:type parser: str
:type list_marker: str
:returns: list_marker_log, the data structure.
:rtype: list
:raises: a built-in exception.
.. note::
This function makes sense for ordered lists only.
"""
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
assert list_marker in md_parser[parser]['list']['ordered'][
'closing_markers']
list_marker_log = list()
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
list_marker_log = [
str(md_parser['github']['list']['ordered']['min_marker_number']) +
list_marker
for i in range(0, md_parser['github']['header']['max_levels'])
]
elif parser == 'redcarpet':
pass
return list_marker_log
def compute_toc_line_indentation_spaces(
header_type_curr: int = 1,
header_type_prev: int = 0,
no_of_indentation_spaces_prev: int = 0,
parser: str = 'github',
ordered: bool = False,
list_marker: str = '-',
list_marker_log: list = build_list_marker_log('github', '.'),
index: int = 1) -> int:
r"""Compute the number of indentation spaces for the TOC list element.
:parameter header_type_curr: the current type of header (h[1-Inf]).
Defaults to ``1``.
:parameter header_type_prev: the previous type of header (h[1-Inf]).
Defaults to ``0``.
:parameter no_of_indentation_spaces_prev: the number of previous indentation spaces.
Defaults to ``0``.
:parameter parser: decides rules on how compute indentations.
Defaults to ``github``.
:parameter ordered: if set to ``True``, numbers will be used
as list ids or otherwise a dash character, otherwise.
Defaults to ``False``.
:parameter list_marker: a string that contains some of the first
characters of the list element.
Defaults to ``-``.
:parameter list_marker_log: a data structure that holds list marker
information for ordered lists.
Defaults to ``build_list_marker_log('github', '.')``.
:parameter index: a number that will be used as list id in case of an
ordered table of contents. Defaults to ``1``.
:type header_type_curr: int
:type header_type_prev: int
:type no_of_indentation_spaces_prev: int
:type parser: str
:type ordered: bool
:type list_marker: str
:type list_marker_log: list
:type index: int
:returns: no_of_indentation_spaces_curr, the number of indentation spaces
for the list element.
:rtype: int
:raises: a built-in exception.
.. note::
Please note that this function
assumes that no_of_indentation_spaces_prev contains the correct
number of spaces.
"""
assert header_type_curr >= 1
assert header_type_prev >= 0
assert no_of_indentation_spaces_prev >= 0
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
if ordered:
assert list_marker in md_parser[parser]['list']['ordered'][
'closing_markers']
else:
assert list_marker in md_parser[parser]['list']['unordered'][
'bullet_markers']
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
if ordered:
assert len(
list_marker_log) == md_parser['github']['header']['max_levels']
for e in list_marker_log:
assert isinstance(e, str)
assert index >= 1
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
if header_type_prev == 0:
# Base case for the first toc line.
no_of_indentation_spaces_curr = 0
elif header_type_curr == header_type_prev:
# Base case for same indentation.
no_of_indentation_spaces_curr = no_of_indentation_spaces_prev
else:
if ordered:
list_marker_prev = str(list_marker_log[header_type_curr - 1])
else:
# list_marker for unordered lists will always be 1 character.
list_marker_prev = list_marker
# Generic cases.
if header_type_curr > header_type_prev:
# More indentation.
no_of_indentation_spaces_curr = (
no_of_indentation_spaces_prev + len(list_marker_prev) +
len(' '))
elif header_type_curr < header_type_prev:
# Less indentation.
no_of_indentation_spaces_curr = (
no_of_indentation_spaces_prev -
(len(list_marker_prev) + len(' ')))
# Reset older nested list indices. If this is not performed then
# future nested ordered lists will rely on incorrect data to
# compute indentations.
if ordered:
for i in range((header_type_curr - 1) + 1,
md_parser['github']['header']['max_levels']):
list_marker_log[i] = str(
md_parser['github']['list']['ordered']
['min_marker_number']) + list_marker
# Update the data structure.
if ordered:
list_marker_log[header_type_curr - 1] = str(index) + list_marker
elif parser == 'redcarpet':
no_of_indentation_spaces_curr = 4 * (header_type_curr - 1)
return no_of_indentation_spaces_curr
def build_toc_line_without_indentation(header: dict,
ordered: bool = False,
no_links: bool = False,
index: int = 1,
parser: str = 'github',
list_marker: str = '-') -> str:
r"""Return a list element of the table of contents.
:parameter header: a data structure that contains the original
text, the trimmed text and the type of header.
:parameter ordered: if set to ``True``, numbers will be used
as list ids, otherwise a dash character. Defaults
to ``False``.
:parameter no_links: disables the use of links. Defaults to ``False``.
:parameter index: a number that will be used as list id in case of an
ordered table of contents. Defaults to ``1``.
:parameter parser: decides rules on how compute indentations.
Defaults to ``github``.
:parameter list_marker: a string that contains some of the first
characters of the list element. Defaults to ``-``.
:type header: dict
:type ordered: bool
:type no_links: bool
:type index: int
:type parser: str
:type list_marker: str
:returns: toc_line_no_indent, a single line of the table of contents
without indentation.
:rtype: str
:raises: a built-in exception.
"""
assert 'type' in header
assert 'text_original' in header
assert 'text_anchor_link' in header
assert isinstance(header['type'], int)
assert isinstance(header['text_original'], str)
assert isinstance(header['text_anchor_link'], str)
assert header['type'] >= 1
assert index >= 1
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
if ordered:
assert list_marker in md_parser[parser]['list']['ordered'][
'closing_markers']
else:
assert list_marker in md_parser[parser]['list']['unordered'][
'bullet_markers']
toc_line_no_indent = str()
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
if ordered:
list_marker = str(index) + list_marker
# FIXME: is this always correct?
if no_links:
line = header['text_original']
else:
line = '[' + header['text_original'] + ']' + '(#' + header[
'text_anchor_link'] + ')'
toc_line_no_indent = list_marker + ' ' + line
return toc_line_no_indent
def build_toc_line(toc_line_no_indent: str,
no_of_indentation_spaces: int = 0) -> str:
r"""Build the TOC line.
:parameter toc_line_no_indent: the TOC line without indentation.
:parameter no_of_indentation_spaces: the number of indentation spaces.
Defaults to ``0``.
:type toc_line_no_indent: str
:type no_of_indentation_spaces: int
:returns: toc_line, a single line of the table of contents.
:rtype: str
:raises: a built-in exception.
"""
assert no_of_indentation_spaces >= 0
indentation = no_of_indentation_spaces * ' '
toc_line = indentation + toc_line_no_indent
return toc_line
def build_anchor_link(header_text_trimmed: str,
header_duplicate_counter: str,
parser: str = 'github') -> str:
r"""Apply the specified slug rule to build the anchor link.
:parameter header_text_trimmed: the text that needs to be transformed
in a link.
:parameter header_duplicate_counter: a data structure that keeps track of
possible duplicate header links in order to avoid them. This is
meaningful only for certain values of parser.
:parameter parser: decides rules on how to generate anchor links.
Defaults to ``github``.
:type header_text_trimmed: str
:type header_duplicate_counter: dict
:type parser: str
:returns: None if the specified parser is not recognized, or the anchor
link, otherwise.
:rtype: str
:raises: a built-in exception.
.. note::
The licenses of each markdown parser algorithm are reported on
the 'Markdown spec' documentation page.
"""
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
header_text_trimmed = header_text_trimmed.lower()
# Remove punctuation: Keep spaces, hypens and "word characters"
# only.
header_text_trimmed = re.sub(r'[^\w\s\- ]', '', header_text_trimmed)
header_text_trimmed = header_text_trimmed.replace(' ', '-')
# Check for duplicates.
ht = header_text_trimmed
# Set the initial value if we are examining the first occurrency.
# The state of header_duplicate_counter is available to the caller
# functions.
if header_text_trimmed not in header_duplicate_counter:
header_duplicate_counter[header_text_trimmed] = 0
if header_duplicate_counter[header_text_trimmed] > 0:
header_text_trimmed = header_text_trimmed + '-' + str(
header_duplicate_counter[header_text_trimmed])
header_duplicate_counter[ht] += 1
return header_text_trimmed
elif parser == 'redcarpet':
# To ensure full compatibility what follows is a direct translation
# of the rndr_header_anchor C function used in redcarpet.
STRIPPED = " -&+$,/:;=?@\"#{}|^~[]`\\*()%.!'"
header_text_trimmed_len = len(header_text_trimmed)
inserted = 0
stripped = 0
header_text_trimmed_middle_stage = ''
for i in range(0, header_text_trimmed_len):
if header_text_trimmed[i] == '<':
while i < header_text_trimmed_len and header_text_trimmed[
i] != '>':
i += 1
elif header_text_trimmed[i] == '&':
while i < header_text_trimmed_len and header_text_trimmed[
i] != ';':
i += 1
# str.find() == -1 if character is not found in str.
# https://docs.python.org/3.6/library/stdtypes.html?highlight=find#str.find
elif not curses.ascii.isascii(
header_text_trimmed[i]) or STRIPPED.find(
header_text_trimmed[i]) != -1:
if inserted and not stripped:
header_text_trimmed_middle_stage += '-'
stripped = 1
else:
header_text_trimmed_middle_stage += header_text_trimmed[
i].lower()
stripped = 0
inserted += 1
if stripped > 0 and inserted > 0:
header_text_trimmed_middle_stage = header_text_trimmed_middle_stage[
0:-1]
if inserted == 0 and header_text_trimmed_len > 0:
hash = 5381
for i in range(0, header_text_trimmed_len):
# Get the unicode representation with ord.
# Unicode should be equal to ASCII in ASCII's range of
# characters.
hash = ((hash << 5) + hash) + ord(header_text_trimmed[i])
# This is equivalent to %x in C. In Python we don't have
# the length problem so %x is equal to %lx in this case.
# Apparently there is no %l in Python...
header_text_trimmed_middle_stage = 'part-' + '{0:x}'.format(hash)
return header_text_trimmed_middle_stage
def get_atx_heading(line: str,
keep_header_levels: int = 3,
parser: str = 'github',
no_links: bool = False):
r"""Given a line extract the link label and its type.
:parameter line: the line to be examined.
:parameter keep_header_levels: the maximum level of headers to be
considered as such when building the table of contents.
Defaults to ``3``.
:parameter parser: decides rules on how to generate the anchor text.
Defaults to ``github``.
:parameter no_links: disables the use of links.
:type line: str
:type keep_header_levels: int
:type parser: str
:type np_links: bool
:returns: None if the line does not contain header elements according to
the rules of the selected markdown parser, or a tuple containing the
header type and the trimmed header text, according to the selected
parser rules, otherwise.
:rtype: typing.Optional[tuple]
:raises: GithubEmptyLinkLabel or GithubOverflowCharsLinkLabel or a
built-in exception.
"""
assert keep_header_levels >= 1
if len(line) == 0:
return None
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
if line[0] == '\u005c':
return None
i = 0
while i < len(line) and line[i] == ' ' and i <= md_parser['github'][
'header']['max_space_indentation']:
i += 1
if i > md_parser['github']['header']['max_space_indentation']:
return None
offset = i
while i < len(line) and line[i] == '#' and i <= md_parser['github'][
'header']['max_levels'] + offset:
i += 1
if i - offset > md_parser['github']['header'][
'max_levels'] or i - offset > keep_header_levels or i - offset == 0:
return None
current_headers = i - offset
# Include special cases for line endings which should not be
# discarded as non-ATX headers.
if i < len(line) and (line[i] != ' ' and line[i] != '\u000a'
and line[i] != '\u000d'):
return None
i += 1
# Exclude leading whitespaces after the ATX header identifier.
while i < len(line) and line[i] == ' ':
i += 1
# An algorithm to find the start and the end of the closing sequence.
# The closing sequence includes all the significant part of the
# string. This algorithm has a complexity of O(n) with n being the
# length of the line.
cs_start = i
cs_end = cs_start
line_prime = line[::-1]
hash_char_rounds = 0
go_on = True
i = 0
i_prev = i
while i < len(line) - cs_start - 1 and go_on:
if ((line_prime[i] != ' ' and line_prime[i] != '#')
or hash_char_rounds > 1):
if i > i_prev:
cs_end = len(line_prime) - i_prev
else:
cs_end = len(line_prime) - i
go_on = False
while go_on and line_prime[i] == ' ':
i += 1
i_prev = i
while go_on and line_prime[i] == '#':
i += 1
if i > i_prev:
hash_char_rounds += 1
# Instead of changing the whole algorithm to check for line
# endings, this seems cleaner.
find_newline = line.find('\u000a')
find_carriage_return = line.find('\u000d')
if find_newline != -1:
cs_end = min(cs_end, find_newline)
if find_carriage_return != -1:
cs_end = min(cs_end, find_carriage_return)
final_line = line[cs_start:cs_end]
if not no_links:
if len(final_line) > 0 and final_line[-1] == '\u005c':
final_line += ' '
if len(
final_line.strip('\u0020').strip('\u0009').strip('\u000a').
strip('\u000b').strip('\u000c').strip('\u000d')) == 0:
raise GithubEmptyLinkLabel
if len(final_line
) > md_parser['github']['link']['max_chars_label']:
raise GithubOverflowCharsLinkLabel
# Escape square brackets if not already escaped.
i = 0
while i < len(final_line):
if (final_line[i] == '[' or final_line[i] == ']'):
j = i - 1
consecutive_escape_characters = 0
while j >= 0 and final_line[j] == '\u005c':
consecutive_escape_characters += 1
j -= 1
if ((consecutive_escape_characters > 0
and consecutive_escape_characters % 2 == 0)
or consecutive_escape_characters == 0):
tmp = '\u005c'
else:
tmp = str()
final_line = final_line[0:i] + tmp + final_line[i:len(
final_line)]
i += 1 + len(tmp)
else:
i += 1
elif parser == 'redcarpet':
if line[0] != '#':
return None
i = 0
while (i < len(line)
and i < md_parser['redcarpet']['header']['max_levels']
and line[i] == '#'):
i += 1
current_headers = i
if i < len(line) and line[i] != ' ':
return None
while i < len(line) and line[i] == ' ':
i += 1
end = i
while end < len(line) and line[end] != '\n':
end += 1
while end > 0 and line[end - 1] == '#':
end -= 1
while end > 0 and line[end - 1] == ' ':
end -= 1
if end > i:
final_line = line
if not no_links and len(final_line) > 0 and final_line[-1] == '\\':
final_line += ' '
end += 1
final_line = final_line[i:end]
else:
return None
# TODO: escape or remove '[', ']', '(', ')' in inline links for redcarpet,
# TODO: check link label rules for redcarpet.
return current_headers, final_line
def get_md_header(header_text_line: str,
header_duplicate_counter: dict,
keep_header_levels: int = 3,
parser: str = 'github',
no_links: bool = False) -> dict:
r"""Build a data structure with the elements needed to create a TOC line.
:parameter header_text_line: a single markdown line that needs to be
transformed into a TOC line.
:parameter header_duplicate_counter: a data structure that contains the
number of occurrencies of each header anchor link. This is used to
avoid duplicate anchor links and it is meaningful only for certain
values of parser.
:parameter keep_header_levels: the maximum level of headers to be
considered as such when building the table of contents.
Defaults to ``3``.
:parameter parser: decides rules on how to generate anchor links.
Defaults to ``github``.
:type header_text_line: str
:type header_duplicate_counter: dict
:type keep_header_levels: int
:type parser: str
:returns: None if the input line does not correspond to one of the
designated cases or a data structure containing the necessary
components to create a table of contents line, otherwise.
:rtype: dict
:raises: a built-in exception.
.. note::
This works like a wrapper to other functions.
"""
result = get_atx_heading(header_text_line, keep_header_levels, parser,
no_links)
if result is None:
return result
else:
header_type, header_text_trimmed = result
header = {
'type':
header_type,
'text_original':
header_text_trimmed,
'text_anchor_link':
build_anchor_link(header_text_trimmed, header_duplicate_counter,
parser)
}
return header
def is_valid_code_fence_indent(line: str, parser: str = 'github') -> bool:
r"""Determine if the given line has valid indentation for a code block fence.
:parameter line: a single markdown line to evaluate.
:parameter parser: decides rules on how to generate the anchor text.
Defaults to ``github``.
:type line: str
:type parser: str
:returns: True if the given line has valid indentation or False
otherwise.
:rtype: bool
:raises: a built-in exception.
"""
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
return len(line) - len(line.lstrip(
' ')) <= md_parser['github']['code fence']['min_marker_characters']
elif parser == 'redcarpet':
# TODO.
return False
def is_opening_code_fence(line: str, parser: str = 'github'):
r"""Determine if the given line is possibly the opening of a fenced code block.
:parameter line: a single markdown line to evaluate.
:parameter parser: decides rules on how to generate the anchor text.
Defaults to ``github``.
:type line: str
:type parser: str
:returns: None if the input line is not an opening code fence. Otherwise,
returns the string which will identify the closing code fence
according to the input parsers' rules.
:rtype: typing.Optional[str]
:raises: a built-in exception.
"""
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
markers = md_parser['github']['code fence']['marker']
marker_min_length = md_parser['github']['code fence'][
'min_marker_characters']
if not is_valid_code_fence_indent(line):
return None
line = line.lstrip(' ').rstrip('\n')
if not line.startswith(
(markers[0] * marker_min_length, markers[1] * marker_min_length)):
return None
if line == len(line) * line[0]:
info_string = str()
else:
info_string = line.lstrip(line[0])
# Backticks or tildes in info string are explicitly forbidden.
if markers[0] in info_string or markers[1] in info_string:
return None
# Solves example 107. See:
# https://github.github.com/gfm/#example-107
if line.rstrip(markers[0]) != line and line.rstrip(markers[1]) != line:
return None
return line.rstrip(info_string)
elif parser == 'redcarpet':
# TODO.
return None
def is_closing_code_fence(line: str,
fence: str,
is_document_end: bool = False,
parser: str = 'github') -> bool:
r"""Determine if the given line is the end of a fenced code block.
:parameter line: a single markdown line to evaluate.
:paramter fence: a sequence of backticks or tildes marking the start of
the current code block. This is usually the return value of the
is_opening_code_fence function.
:parameter is_document_end: This variable tells the function that the
end of the file is reached.
Defaults to ``False``.
:parameter parser: decides rules on how to generate the anchor text.
Defaults to ``github``.
:type line: str
:type fence: str
:type is_document_end: bool
:type parser: str
:returns: True if the line ends the current code block. False otherwise.
:rtype: bool
:raises: a built-in exception.
"""
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
markers = md_parser['github']['code fence']['marker']
marker_min_length = md_parser['github']['code fence'][
'min_marker_characters']
if not is_valid_code_fence_indent(line):
return False
# Remove opening fence indentation after it is known to be valid.
fence = fence.lstrip(' ')
# Check if fence uses valid characters.
if not fence.startswith((markers[0], markers[1])):
return False
if len(fence) < marker_min_length:
return False
# Additional security.
fence = fence.rstrip('\n').rstrip(' ')
# Check that all fence characters are equal.
if fence != len(fence) * fence[0]:
return False
# We might be inside a code block if this is not closed
# by the end of the document, according to example 95 and 96.
# This means that the end of the document corresponds to
# a closing code fence.
# Of course we first have to check that fence is a valid opening
# code fence marker.
# See:
# https://github.github.com/gfm/#example-95
# https://github.github.com/gfm/#example-96
if is_document_end:
return True
# Check if line uses the same character as fence.
line = line.lstrip(' ')
if not line.startswith(fence):
return False
line = line.rstrip('\n').rstrip(' ')
# Solves example 93 and 94. See:
# https://github.github.com/gfm/#example-93
# https://github.github.com/gfm/#example-94
if len(line) < len(fence):
return False
# Closing fence must not have alien characters.
if line != len(line) * line[0]:
return False
return True
elif parser == 'redcarpet':
# TODO.
return False
def build_indentation_list(parser: str = 'github'):
r"""Create a data structure that holds the state of indentations.
:parameter parser: decides the length of the list.
Defaults to ``github``.
:type parser: str
:returns: indentation_list, a list that contains the state of
indentations given a header type.
:rtype: list
:raises: a built-in exception.
"""
indentation_list = list()
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
for i in range(0, md_parser[parser]['header']['max_levels']):
indentation_list.append(False)
return indentation_list
def toc_renders_as_coherent_list(
header_type_curr: int = 1,
indentation_list: list = build_indentation_list('github'),
parser: str = 'github') -> bool:
r"""Check if the TOC will render as a working list.
:parameter header_type_curr: the current type of header (h[1-Inf]).
:parameter parser: decides rules on how to generate ordered list markers
:type header_type_curr: int
:type indentation_list: list
:type parser: str
:returns: renders_as_list
:rtype: bool
:raises: a built-in exception.
"""
assert header_type_curr >= 1
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
assert len(
indentation_list) == md_parser[parser]['header']['max_levels']
for e in indentation_list:
assert isinstance(e, bool)
renders_as_list = True
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
# Update with current information.
indentation_list[header_type_curr - 1] = True
# Reset next cells to False, as a detection mechanism.
for i in range(header_type_curr,
md_parser['github']['header']['max_levels']):
indentation_list[i] = False
# Check for previous False cells. If there is a "hole" in the list
# it means that the TOC will have "wrong" indentation spaces, thus
# either not rendering as an HTML list or not as the user intended.
i = header_type_curr - 1
while i >= 0 and indentation_list[i]:
i -= 1
if i >= 0:
renders_as_list = False
return renders_as_list
if __name__ == '__main__':
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.