code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def color_xy(self):
color_x = self._last_reading.get('color_x')
color_y = self._last_reading.get('color_y')
if color_x is not None and color_y is not None:
return [float(color_x), float(color_y)]
return None | XY colour value: [float, float] or None
:rtype: list float |
def set_state(self, state, brightness=None,
color_kelvin=None, color_xy=None,
color_hue_saturation=None):
desired_state = {"powered": state}
color_state = self._format_color_data(color_hue_saturation, color_kelvin, color_xy)
if color_state is not Non... | :param state: a boolean of true (on) or false ('off')
:param brightness: a float from 0 to 1 to set the brightness of
this bulb
:param color_kelvin: an integer greater than 0 which is a color in
degrees Kelvin
:param color_xy: a pair of floats in a list which specify the desi... |
def set_tare(self, tare):
response = self.api_interface.set_device_state(self, {"tare": tare})
self._update_state_from_response(response) | :param tare: weight of tank as printed on can
:return: nothing
tare is not set in desired state, but on the main device. |
def set_alarm_sensitivity(self, mode):
values = {"desired_state": {"alarm_sensitivity": mode}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param mode: 1.0 for Very sensitive, 0.2 for not sensitive.
Steps in values of 0.2.
:return: nothing |
def set_alarm_mode(self, mode):
values = {"desired_state": {"alarm_mode": mode}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param mode: one of [None, "activity", "tamper", "forced_entry"]
:return: nothing |
def set_alarm_state(self, state):
values = {"desired_state": {"alarm_enabled": state}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param state: a boolean of ture (on) or false ('off')
:return: nothing |
def set_vacation_mode(self, state):
values = {"desired_state": {"vacation_mode_enabled": state}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param state: a boolean of ture (on) or false ('off')
:return: nothing |
def set_beeper_mode(self, state):
values = {"desired_state": {"beeper_enabled": state}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param state: a boolean of ture (on) or false ('off')
:return: nothing |
def set_state(self, state):
values = {"desired_state": {"locked": state}}
response = self.api_interface.local_set_state(self, values)
self._update_state_from_response(response) | :param state: a boolean of true (on) or false ('off')
:return: nothing |
def add_new_key(self, code, name):
device_json = {"code": code, "name": name}
return self.api_interface.create_lock_key(self, device_json) | Add a new user key code. |
def create_paired_device(self, dev_id, agent_path,
capability, cb_notify_device, cb_notify_error):
return self._interface.CreatePairedDevice(dev_id,
agent_path,
capability,
... | Creates a new object path for a remote device. This
method will connect to the remote device and retrieve
all SDP records and then initiate the pairing.
If a previously :py:meth:`create_device` was used
successfully, this method will only initiate the pairing.
Compared to :py:m... |
def _visit_body(self, node):
if (node.body and isinstance(node.body[0], ast.Expr) and
self.is_base_string(node.body[0].value)):
node.body[0].value.is_docstring = True
self.visit(node.body[0].value)
for sub_node in node.body:
self.visit(sub_no... | Traverse the body of the node manually.
If the first node is an expression which contains a string or bytes it
marks that as a docstring. |
def update_state(self):
response = self.api_interface.get_device_state(self, type_override="button")
return self._update_state_from_response(response) | Update state with latest info from Wink API. |
def lookup(self, domain, get_last_full_query=True):
last_full_builtwith_scan_date = None
if self.api_version == 7 and isinstance(domain, list):
domain = ','.join(domain)
if self.api_version in [2, 7]:
last_updates_resp = requests.get(ENDPOINTS_BY_API_VERSION[s... | Lookup BuiltWith results for the given domain. If API version 2 is used and the get_last_full_query flag
enabled, it also queries for the date of the last full BuiltWith scan. |
def set_schedule_enabled(self, state):
desired_state = {"schedule_enabled": state}
response = self.api_interface.set_device_state(self, {
"desired_state": desired_state
})
self._update_state_from_response(response) | :param state: a boolean True (on) or False (off)
:return: nothing |
def set_ac_fan_speed(self, speed):
desired_state = {"fan_speed": speed}
response = self.api_interface.set_device_state(self, {
"desired_state": desired_state
})
self._update_state_from_response(response) | :param speed: a float from 0.0 to 1.0 (0 - 100%)
:return: nothing |
def set_temperature(self, max_set_point=None):
desired_state = {}
if max_set_point:
desired_state['max_set_point'] = max_set_point
response = self.api_interface.set_device_state(self, {
"desired_state": desired_state
})
self._update_state_from_... | :param max_set_point: a float for the max set point value in celsius
:return: nothing |
def register(self, resource=None, **kwargs):
if resource is None:
def wrapper(resource):
return self.register(resource, **kwargs)
return wrapper
for key, value in kwargs.items():
setattr(resource.Meta, key, value)
if resource.Meta.na... | Register resource for currnet API.
:param resource: Resource to be registered
:type resource: jsonapi.resource.Resource or None
:return: resource
:rtype: jsonapi.resource.Resource
.. versionadded:: 0.4.1
:param kwargs: Extra meta parameters |
def urls(self):
from django.conf.urls import url
urls = [
url(r'^$', self.documentation),
url(r'^map$', self.map_view),
]
for resource_name in self.resource_map:
urls.extend([
url(r'(?P<resource_name>{})$'.format(
... | Get all of the api endpoints.
NOTE: only for django as of now.
NOTE: urlpatterns are deprecated since Django1.8
:return list: urls |
def update_urls(self, request, resource_name=None, ids=None):
http_host = request.META.get('HTTP_HOST', None)
if http_host is None:
http_host = request.META['SERVER_NAME']
if request.META['SERVER_PORT'] not in ('80', '443'):
http_host = "{}:{}".format(
... | Update url configuration.
:param request:
:param resource_name:
:type resource_name: str or None
:param ids:
:rtype: None |
def map_view(self, request):
self.update_urls(request)
resource_info = {
"resources": [{
"id": index + 1,
"href": "{}/{}".format(self.api_url, resource_name),
} for index, (resource_name, resource) in enumerate(
sorted(self... | Show information about available resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse |
def documentation(self, request):
self.update_urls(request)
context = {
"resources": sorted(self.resource_map.items())
}
return render(request, "jsonapi/index.html", context) | Resource documentation.
.. versionadded:: 0.7.2
Content-Type check
:return django.http.HttpResponse |
def handler_view(self, request, resource_name, ids=None):
signal_request.send(sender=self, request=request)
time_start = time.time()
self.update_urls(request, resource_name=resource_name, ids=ids)
resource = self.resource_map[resource_name]
allowed_http_methods = resour... | Handler for resources.
.. versionadded:: 0.5.7
Content-Type check
:return django.http.HttpResponse |
def away(self):
nest = self._last_reading.get('users_away', None)
ecobee = self.profile()
if nest is not None:
return nest
if ecobee is not None:
if ecobee == "home":
return False
return True
return None | This function handles both ecobee and nest thermostats
which use a different field for away/home status. |
def set_fan_mode(self, mode):
desired_state = {"fan_mode": mode}
response = self.api_interface.set_device_state(self, {
"desired_state": desired_state
})
self._update_state_from_response(response) | :param mode: a string one of ["on", "auto"]
:return: nothing |
def set_away(self, away=True):
if self.profile() is not None:
if away:
desired_state = {"profile": "away"}
else:
desired_state = {"profile": "home"}
else:
desired_state = {"users_away": away}
response = self.api_interf... | :param away: a boolean of true (away) or false ('home')
:return nothing
This function handles both ecobee and nest thermostats
which use a different field for away/home status. |
def _parse_ical_string(ical_string):
start_time = ical_string.splitlines()[0].replace(DTSTART, '')
if "RRULE" in ical_string:
days = ical_string.splitlines()[1].replace(REPEAT, '')
if days == "RRULE:FREQ=DAILY":
days = ['DAILY']
else:
days = days.spli... | SU,MO,TU,WE,TH,FR,SA
DTSTART;TZID=America/New_York:20180804T233251\nRRULE:FREQ=WEEKLY;BYDAY=SA
DTSTART;TZID=America/New_York:20180804T233251\nRRULE:FREQ=DAILY
DTSTART;TZID=America/New_York:20180804T233251\nRRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR,SA
DTSTART;TZID=America/New_York:20180718T174500 |
def set_dial(self, json_value, index, timezone=None):
values = self.json_state
values["nonce"] = str(random.randint(0, 1000000000))
if timezone is None:
json_value["channel_configuration"] = {"channel_id": "10"}
values["dials"][index] = json_value
... | :param json_value: The value to set
:param index: The dials index
:param timezone: The time zone to use for a time dial
:return: |
def update_state(self):
response = self.api_interface.get_device_state(self, id_override=self.parent.object_id(),
type_override=self.parent.object_type())
self._update_state_from_response(response) | Update state with latest info from Wink API. |
def _update_state_from_response(self, response_json):
if 'data' in response_json and response_json['data']['object_type'] == "cloud_clock":
cloud_clock = response_json.get('data')
if cloud_clock is None:
return False
alarms = cloud_clock.get('... | :param response_json: the json obj returned from query
:return: |
def set_recurrence(self, date, days=None):
if self.parent.get_time_dial() is None:
_LOGGER.error("Not setting alarm, no time dial.")
return False
timezone_string = self.parent.get_time_dial()["channel_configuration"]["timezone"]
ical_string = _create_ical_s... | :param date: Datetime object time to start/repeat
:param days: days to repeat (Defaults to one time alarm)
:return: |
def update_state(self):
response = self.api_interface.get_device_state(self, id_override=self.parent_id(),
type_override=self.parent_object_type())
self._update_state_from_response(response) | Update state with latest info from Wink API. |
def _update_state_from_response(self, response_json):
if response_json.get('data') is not None:
cloud_clock = response_json.get('data')
else:
cloud_clock = response_json
self.parent.json_state = cloud_clock
cloud_clock_last_reading = cloud_clock.... | :param response_json: the json obj returned from query
:return: |
def set_configuration(self, min_value, max_value, rotation="cw", scale="linear", ticks=12, min_position=0,
max_position=360):
_json = {"min_value": min_value, "max_value": max_value, "rotation": rotation, "scale_type": scale,
"num_ticks": ticks, "min_pos... | :param min_value: Any number
:param max_value: Any number above min_value
:param rotation: (String) cw or ccw
:param scale: (String) linear or log
:param ticks:(Int) number of ticks of the clock up to 360?
:param min_position: (Int) 0-360
:param max_position: (Int) ... |
def set_state(self, value, labels=None):
values = {"value": value}
json_labels = []
if labels:
for label in labels:
json_labels.append(str(label).upper())
values["labels"] = json_labels
self._update_state_from_response(self.par... | :param value: Any number
:param labels: A list of two Strings sending None won't change the current values.
:return: |
def make_time_dial(self, timezone_string):
self._update_state_from_response(self.parent.set_dial({}, self.index(), timezone_string)) | :param timezone_string:
:return: |
def fromtabix(filename, reference=None, start=None, stop=None, region=None,
header=None):
return TabixView(filename, reference, start, stop, region, header) | Extract rows from a tabix indexed file, e.g.::
>>> import petl as etl
>>> # activate bio extensions
... import petlx.bio
>>> table1 = etl.fromtabix('fixture/test.bed.gz',
... region='Pf3D7_02_v3')
>>> table1
+---------------+----------+----... |
def pair_new_device(self, pairing_mode, pairing_mode_duration=60, pairing_device_type_selector=None,
kidde_radio_code=None):
if pairing_mode == "lutron" and pairing_mode_duration < 120:
pairing_mode_duration = 120
elif pairing_mode == "zwave_network_redi... | :param pairing_mode: a string one of ["zigbee", "zwave", "zwave_exclusion",
"zwave_network_rediscovery", "lutron", "bluetooth", "kidde"]
:param pairing_mode_duration: an int in seconds defaults to 60
:param pairing_device_type_selector: a string I believe this is only for bluetooth device... |
def cipher(self):
# If no offset is selected, pick random one with sufficient distance
# from original.
if self.offset is False:
self.offset = randrange(5, 25)
logging.info("Random offset selected: {0}".format(self.offset))
logging.debug("Offset set: {0}"... | Applies the Caesar shift cipher.
Based on the attributes of the object, applies the Caesar shift cipher
to the message attribute. Accepts positive and negative integers as
offsets.
Required attributes:
message
offset
Returns:
String with cip... |
def calculate_entropy(self, entropy_string):
total = 0
for char in entropy_string:
if char.isalpha():
prob = self.frequency[char.lower()]
total += - math.log(prob) / math.log(2)
logging.debug("Entropy score: {0}".format(total))
return ... | Calculates the entropy of a string based on known frequency of
English letters.
Args:
entropy_string: A str representing the string to calculate.
Returns:
A negative float with the total entropy of the string (higher
is better). |
def cracked(self):
logging.info("Cracking message: {0}".format(self.message))
entropy_values = {}
attempt_cache = {}
message = self.message
for i in range(25):
self.message = message
self.offset = i * -1
logging.debug("Attempting crack... | Attempts to crack ciphertext using frequency of letters in English.
Returns:
String of most likely message. |
def decoded(self):
logging.info("Decoding message: {0}".format(self.message))
self.offset = self.offset * -1
return self.cipher() | Decodes message using Caesar shift cipher
Inverse operation of encoding, applies negative offset to Caesar shift
cipher.
Returns:
String decoded with cipher. |
def parse(cls, querydict):
for key in querydict.keys():
if not any((key in JSONAPIQueryDict._fields,
cls.RE_FIELDS.match(key))):
msg = "Query parameter {} is not known".format(key)
raise ValueError(msg)
result = JSONAPIQueryD... | Parse querydict data.
There are expected agruments:
distinct, fields, filter, include, page, sort
Parameters
----------
querydict : django.http.request.QueryDict
MultiValueDict with query arguments.
Returns
-------
result : dict
... |
def set_state(self, state):
desired_state = {"desired_state": {"powered": state}}
response = self.api_interface.set_device_state(self, desired_state)
self._update_state_from_response(response) | :param state: a boolean of true (on) or false ('off')
:return: nothing |
def _update_state_from_response(self, response_json):
power_strip = response_json.get('data')
power_strip_reading = power_strip.get('last_reading')
outlets = power_strip.get('outlets')
for outlet in outlets:
if outlet.get('outlet_id') == str(self.object_id())... | :param response_json: the json obj returned from query
:return: |
def set_state(self, state):
if self.index() == 0:
values = {"outlets": [{"desired_state": {"powered": state}}, {}]}
else:
values = {"outlets": [{}, {"desired_state": {"powered": state}}]}
response = self.api_interface.set_device_state(self, values, id_ove... | :param state: a boolean of true (on) or false ('off')
:return: nothing |
def set_state(self, state):
_field = self.binary_state_name()
values = {"desired_state": {_field: state}}
response = self.api_interface.local_set_state(self, values, type_override="binary_switche")
self._update_state_from_response(response) | :param state: a boolean of true (on) or false ('off')
:return: nothing |
def binary_state_name(self):
return_field = "powered"
_capabilities = self.json_state.get('capabilities')
if _capabilities is not None:
_fields = _capabilities.get('fields')
if _fields is not None:
for field in _fields:
... | Search all of the capabilities of the device and return the supported binary state field.
Default to returning powered. |
def update_state(self):
response = self.api_interface.local_get_state(self, type_override="binary_switche")
return self._update_state_from_response(response) | Update state with latest info from Wink API. |
def set_siren_volume(self, volume):
values = {
"desired_state": {
"siren_volume": volume
}
}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param volume: one of [low, medium, high] |
def set_chime_volume(self, volume):
values = {
"desired_state": {
"chime_volume": volume
}
}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param volume: one of [low, medium, high] |
def set_siren_strobe_enabled(self, enabled):
values = {
"desired_state": {
"strobe_enabled": enabled
}
}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param enabled: True or False
:return: nothing |
def set_chime_strobe_enabled(self, enabled):
values = {
"desired_state": {
"chime_strobe_enabled": enabled
}
}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param enabled: True or False
:return: nothing |
def set_siren_sound(self, sound):
values = {
"desired_state": {
"siren_sound": sound
}
}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param sound: a str, one of ["doorbell", "fur_elise", "doorbell_extended", "alert",
"william_tell", "rondo_alla_turca", "police_siren",
""evacuation", "beep_beep", "beep"]
:return: nothing |
def set_chime(self, sound, cycles=None):
desired_state = {"activate_chime": sound}
if cycles is not None:
desired_state.update({"chime_cycles": cycles})
response = self.api_interface.set_device_state(self,
{"desire... | :param sound: a str, one of ["doorbell", "fur_elise", "doorbell_extended", "alert",
"william_tell", "rondo_alla_turca", "police_siren",
""evacuation", "beep_beep", "beep", "inactive"]
:param cycles: Undocumented seems to have no effect... |
def set_auto_shutoff(self, timer):
values = {
"desired_state": {
"auto_shutoff": timer
}
}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param timer: an int, one of [None (never), -1, 30, 60, 120]
:return: nothing |
def set_state(self, state):
values = {"desired_state": {"powered": state}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param state: a boolean of true (on) or false ('off')
:return: nothing |
def flux_matrix(T, pi, qminus, qplus, netflux=True):
r
ind = np.diag_indices(T.shape[0])
flux = pi[:, np.newaxis] * qminus[:, np.newaxis] * T * qplus[np.newaxis, :]
"""Remove self fluxes f_ii"""
flux[ind] = 0.0
"""Return net or gross flux"""
if netflux:
return to_netflux(flux)
el... | r"""Compute the TPT flux network for the reaction A-->B.
Parameters
----------
T : (M, M) ndarray
transition matrix
pi : (M,) ndarray
Stationary distribution corresponding to T
qminus : (M,) ndarray
Backward comittor
qplus : (M,) ndarray
Forward committor
net... |
def to_netflux(flux):
r
netflux = flux - np.transpose(flux)
"""Set negative fluxes to zero"""
ind = (netflux < 0.0)
netflux[ind] = 0.0
return netflux | r"""Compute the netflux from the gross flux.
f_ij^{+}=max{0, f_ij-f_ji}
for all pairs i,j
Parameters
----------
flux : (M, M) ndarray
Matrix of flux values between pairs of states.
Returns
-------
netflux : (M, M) ndarray
Matrix of netflux values between pairs ... |
def flux_production(F):
r
influxes = np.array(np.sum(F, axis=0)).flatten() # all that flows in
outfluxes = np.array(np.sum(F, axis=1)).flatten() # all that flows out
prod = outfluxes - influxes # net flux into nodes
return prod | r"""Returns the net flux production for all states
Parameters
----------
F : (n, n) ndarray
Matrix of flux values between pairs of states.
Returns
-------
prod : (n) ndarray
array with flux production (positive) or consumption (negative) at each state |
def flux_producers(F, rtol=1e-05, atol=1e-12):
r
n = F.shape[0]
influxes = np.array(np.sum(F, axis=0)).flatten() # all that flows in
outfluxes = np.array(np.sum(F, axis=1)).flatten() # all that flows out
# net out flux absolute
prod_abs = np.maximum(outfluxes - influxes, np.zeros(n))
# net... | r"""Return indexes of states that are net flux producers.
Parameters
----------
F : (n, n) ndarray
Matrix of flux values between pairs of states.
rtol : float
relative tolerance. fulfilled if max(outflux-influx, 0) / max(outflux,influx) < rtol
atol : float
absolute tolerance... |
def flux_consumers(F, rtol=1e-05, atol=1e-12):
r
# can be used with sparse or dense
n = np.shape(F)[0]
influxes = np.array(np.sum(F, axis=0)).flatten() # all that flows in
outfluxes = np.array(np.sum(F, axis=1)).flatten() # all that flows out
# net in flux absolute
con_abs = np.maximum(inf... | r"""Return indexes of states that are net flux producers.
Parameters
----------
F : (n, n) ndarray
Matrix of flux values between pairs of states.
rtol : float
relative tolerance. fulfilled if max(outflux-influx, 0) / max(outflux,influx) < rtol
atol : float
absolute tolerance... |
def coarsegrain(F, sets):
r
nnew = len(sets)
Fc = np.zeros((nnew, nnew))
for i in range(0, nnew - 1):
for j in range(i + 1, nnew):
I = list(sets[i])
J = list(sets[j])
Fc[i, j] = np.sum(F[I, :][:, J])
Fc[j, i] = np.sum(F[J, :][:, I])
return Fc | r"""Coarse-grains the flux to the given sets
$fc_{i,j} = \sum_{i \in I,j \in J} f_{i,j}$
Note that if you coarse-grain a net flux, it does not necessarily have a net
flux property anymore. If want to make sure you get a netflux,
use to_netflux(coarsegrain(F,sets)).
Parameters
----------
F ... |
def total_flux(F, A=None):
r
if A is None:
prod = flux_production(F)
zeros = np.zeros(len(prod))
outflux = np.sum(np.maximum(prod, zeros))
return outflux
else:
X = set(np.arange(F.shape[0])) # total state space
A = set(A)
notA = X.difference(A)
... | r"""Compute the total flux, or turnover flux, that is produced by the
flux sources and consumed by the flux sinks
Parameters
----------
F : (n, n) ndarray
Matrix of flux values between pairs of states.
A : array_like (optional)
List of integer state labels for set A (reactant)
... |
def rate(totflux, pi, qminus):
r
kAB = totflux / (pi * qminus).sum()
return kAB | r"""Transition rate for reaction A to B.
Parameters
----------
totflux : float
The total flux between reactant and product
pi : (M,) ndarray
Stationary distribution
qminus : (M,) ndarray
Backward comittor
Returns
-------
kAB : float
The reaction rate (pe... |
def _init_journal(self, permissive=True):
nowstamp = datetime.now().strftime("%d-%b-%Y %H:%M:%S.%f")[:-3]
self._add_entry(templates.INIT
.format(time_stamp=nowstamp))
if permissive:
self._add_entry(templates.INIT_DEBUG) | Add the initialization lines to the journal.
By default adds JrnObj variable and timestamp to the journal contents.
Args:
permissive (bool): if True most errors in journal will not
cause Revit to stop journal execution.
Some sti... |
def _new_from_rft(self, base_template, rft_file):
self._add_entry(base_template)
self._add_entry(templates.NEW_FROM_RFT
.format(rft_file_path=rft_file,
rft_file_name=op.basename(rft_file))) | Append a new file from .rft entry to the journal.
This instructs Revit to create a new model based on
the provided .rft template.
Args:
base_template (str): new file journal template from rmj.templates
rft_file (str): full path to .rft template to be used |
def new_model(self, template_name='<None>'):
self._add_entry(templates.NEW_MODEL
.format(template_name=template_name)) | Append a new model from .rft entry to the journal.
This instructs Revit to create a new model based on the
provided .rft template.
Args:
template_name (str): optional full path to .rft template
to be used. default value is <None> |
def new_template(self, template_name='<None>'):
self._add_entry(templates.NEW_MODEL_TEMPLATE
.format(template_name=template_name)) | Append a new template from .rft entry to the journal.
This instructs Revit to create a new template model based on the
provided .rft template.
Args:
template_name (str): optional full path to .rft template
to be used. default value is <None> |
def open_model(self, model_path, audit=False):
if audit:
self._add_entry(templates.FILE_OPEN_AUDIT
.format(model_path=model_path))
else:
self._add_entry(templates.FILE_OPEN
.format(model_path=model... | Append a open non-workshared model entry to the journal.
This instructs Revit to open a non-workshared model.
Args:
model_path (str): full path to non-workshared model
audit (bool): if True audits the model when opening |
def execute_command(self, tab_name, panel_name,
command_module, command_class, command_data=None):
# make sure command_data is not empty
command_data = {} if command_data is None else command_data
# make the canonical name for the command
cmdclassname = '... | Append an execute external command entry to the journal.
This instructs Revit to execute the provided command from the
provided module, tab, and panel.
Args:
tab_name (str): name of ribbon tab that contains the command
panel_name (str): name of ribbon panel that contain... |
def execute_dynamo_definition(self, definition_path,
show_ui=False, shutdown=True,
automation=False, path_exec=True):
self._add_entry(templates.DYNAMO_COMMAND
.format(dynamo_def_path=definition_path,
... | Execute a dynamo definition.
Args:
definition_path (str): full path to dynamo definition file
show_ui (bool): show dynamo UI at execution
shutdown (bool): shutdown model after execution
automation (bool): activate dynamo automation
path_exec (bool): a... |
def import_family(self, rfa_file):
self._add_entry(templates.IMPORT_FAMILY
.format(family_file=rfa_file)) | Append a import family entry to the journal.
This instructs Revit to import a family into the opened model.
Args:
rfa_file (str): full path of the family file |
def export_warnings(self, export_file):
warn_filepath = op.dirname(export_file)
warn_filename = op.splitext(op.basename(export_file))[0]
self._add_entry(templates.EXPORT_WARNINGS
.format(warnings_export_path=warn_filepath,
... | Append an export warnings entry to the journal.
This instructs Revit to export warnings from the opened model.
Currently Revit will stop journal execution if the model does not
have any warnings and the export warnings UI button is disabled.
Args:
export_file (str): full pa... |
def purge_unused(self, pass_count=3):
for purge_count in range(0, pass_count):
self._add_entry(templates.PROJECT_PURGE) | Append an purge model entry to the journal.
This instructs Revit to purge the open model.
Args:
pass_count (int): number of times to execute the purge.
default is 3 |
def sync_model(self, comment='', compact_central=False,
release_borrowed=True, release_workset=True,
save_local=False):
self._add_entry(templates.FILE_SYNC_START)
if compact_central:
self._add_entry(templates.FILE_SYNC_COMPACT)
if relea... | Append a sync model entry to the journal.
This instructs Revit to sync the currently open workshared model.
Args:
comment (str): comment to be provided for the sync step
compact_central (bool): if True compacts the central file
release_borrowed (bool): if True relea... |
def write_journal(self, journal_file_path):
# TODO: assert the extension is txt and not other
with open(journal_file_path, "w") as jrn_file:
jrn_file.write(self._journal_contents) | Write the constructed journal in to the provided file.
Args:
journal_file_path (str): full path to output journal file |
def endswith(self, search_str):
for entry in reversed(list(open(self._jrnl_file, 'r'))[-5:]):
if search_str in entry:
return True
return False | Check whether the provided string exists in Journal file.
Only checks the last 5 lines of the journal file. This method is
usually used when tracking a journal from an active Revit session.
Args:
search_str (str): string to search for
Returns:
bool: if True the... |
def forward_committor(T, A, B):
r
X = set(range(T.shape[0]))
A = set(A)
B = set(B)
AB = A.intersection(B)
notAB = X.difference(A).difference(B)
if len(AB) > 0:
raise ValueError("Sets A and B have to be disjoint")
L = T - np.eye(T.shape[0]) # Generator matrix
"""Assemble lef... | r"""Forward committor between given sets.
The forward committor u(x) between sets A and B is the probability
for the chain starting in x to reach B before reaching A.
Parameters
----------
T : (M, M) ndarray
Transition matrix
A : array_like
List of integer state labels for set ... |
def prior_neighbor(C, alpha=0.001):
r
C_sym = C + C.transpose()
C_sym = C_sym.tocoo()
data = C_sym.data
row = C_sym.row
col = C_sym.col
data_B = alpha * np.ones_like(data)
B = coo_matrix((data_B, (row, col)))
return B | r"""Neighbor prior of strength alpha for the given count matrix.
Prior is defined by
b_ij = alpha if Z_ij+Z_ji > 0
b_ij = 0 else
Parameters
----------
C : (M, M) scipy.sparse matrix
Count matrix
alpha : float (optional)
Value of prior counts
Returns
-... |
def prior_const(C, alpha=0.001):
B = alpha * np.ones(C.shape)
return B | Constant prior of strength alpha.
Prior is defined via
b_ij=alpha for all i,j
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
alpha : float (optional)
Value of prior counts
Returns
-------
B : (M, M) ndarray
Prior count mat... |
def prior_rev(C, alpha=-1.0):
r
ind = np.triu_indices(C.shape[0])
B = np.zeros(C.shape)
B[ind] = alpha
return B | r"""Prior counts for sampling of reversible transition
matrices.
Prior is defined as
b_ij= alpha if i<=j
b_ij=0 else
The reversible prior adds -1 to the upper triagular part of
the given count matrix. This prior respects the fact that
for a reversible transition matrix the degrees... |
def sample_indexes_by_distribution(indexes, distributions, nsample):
# how many states in total?
n = len(indexes)
for dist in distributions:
if len(dist) != n:
raise ValueError('Size error: Distributions must all be of length n (number of states).')
# list of states
res = n... | Samples trajectory/time indexes according to the given probability distributions
Parameters
----------
indexes : list of ndarray( (N_i, 2) )
For each state, all trajectory and time indexes where this state occurs.
Each matrix has a number of rows equal to the number of occurrences of the co... |
def is_transition_matrix(T, tol=1e-10):
if T.ndim != 2:
return False
if T.shape[0] != T.shape[1]:
return False
dim = T.shape[0]
X = np.abs(T) - T
x = np.sum(T, axis=1)
return np.abs(x - np.ones(dim)).max() < dim * tol and X.max() < 2.0 * tol | Tests whether T is a transition matrix
Parameters
----------
T : ndarray shape=(n, n)
matrix to test
tol : float
tolerance to check with
Returns
-------
Truth value : bool
True, if all elements are in interval [0, 1]
and each row of T sums up to 1.
... |
def is_rate_matrix(K, tol=1e-10):
R = K - K.diagonal()
off_diagonal_positive = np.allclose(R, abs(R), 0.0, atol=tol)
row_sum = K.sum(axis=1)
row_sum_eq_0 = np.allclose(row_sum, 0.0, atol=tol)
return off_diagonal_positive and row_sum_eq_0 | True if K is a rate matrix
Parameters
----------
K : numpy.ndarray matrix
Matrix to check
tol : float
tolerance to check with
Returns
-------
Truth value : bool
True, if K negated diagonal is positive and row sums up to zero.
False, otherwise |
def is_reversible(T, mu=None, tol=1e-10):
r
if is_transition_matrix(T, tol):
if mu is None:
mu = stationary_distribution(T)
X = mu[:, np.newaxis] * T
return np.allclose(X, np.transpose(X), atol=tol)
else:
raise ValueError("given matrix is not a valid transition m... | r"""
checks whether T is reversible in terms of given stationary distribution.
If no distribution is given, it will be calculated out of T.
It performs following check:
:math:`\pi_i P_{ij} = \pi_j P_{ji}`
Parameters
----------
T : numpy.ndarray matrix
Transition matrix
mu : num... |
def count_matrix_coo2_mult(dtrajs, lag, sliding=True, sparse=True, nstates=None):
r
# Determine number of states
if nstates is None:
from msmtools.dtraj import number_of_states
nstates = number_of_states(dtrajs)
rows = []
cols = []
# collect transition index pairs
for dtraj i... | r"""Generate a count matrix from a given list discrete trajectories.
The generated count matrix is a sparse matrix in compressed
sparse row (CSR) or numpy ndarray format.
Parameters
----------
dtraj : list of ndarrays
discrete trajectories
lag : int
Lagtime in trajectory steps
... |
def is_transition_matrix(T, tol):
T = T.tocsr() # compressed sparse row for fast row slicing
values = T.data # non-zero entries of T
"""Check entry-wise positivity"""
is_positive = np.allclose(values, np.abs(values), rtol=tol)
"""Check row normalization"""
is_normed = np.allclose(T.sum(... | True if T is a transition matrix
Parameters
----------
T : scipy.sparse matrix
Matrix to check
tol : float
tolerance to check with
Returns
-------
Truth value: bool
True, if T is positive and normed
False, otherwise |
def is_rate_matrix(K, tol):
K = K.tocsr()
# check rows sum up to zero.
row_sum = K.sum(axis=1)
sum_eq_zero = np.allclose(row_sum, np.zeros(shape=row_sum.shape), atol=tol)
# store copy of original diagonal
org_diag = K.diagonal()
# substract diagonal
K = K - diags(org_diag, 0)
... | True if K is a rate matrix
Parameters
----------
K : scipy.sparse matrix
Matrix to check
tol : float
tolerance to check with
Returns
-------
Truth value : bool
True, if K negated diagonal is positive and row sums up to zero.
False, otherwise |
def is_reversible(T, mu=None, tol=1e-15):
r
if not is_transition_matrix(T, tol):
raise ValueError("given matrix is not a valid transition matrix.")
T = T.tocsr()
if mu is None:
from .decomposition import stationary_distribution
mu = stationary_distribution(T)
Mu = diags(mu... | r"""
checks whether T is reversible in terms of given stationary distribution.
If no distribution is given, it will be calculated out of T.
performs follwing check:
:math:`\pi_i P_{ij} = \pi_j P_{ji}
Parameters
----------
T : scipy.sparse matrix
Transition matrix
mu : numpy.ndar... |
def is_connected(T, directed=True):
r
nc = connected_components(T, directed=directed, connection='strong', \
return_labels=False)
return nc == 1 | r"""Check connectivity of the transition matrix.
Return true, if the input matrix is completely connected,
effectively checking if the number of connected components equals one.
Parameters
----------
T : scipy.sparse matrix
Transition matrix
directed : bool, optional
Whether to ... |
def is_ergodic(T, tol):
if isdense(T):
T = T.tocsr()
if not is_transition_matrix(T, tol):
raise ValueError("given matrix is not a valid transition matrix.")
num_components = connected_components(T, directed=True, \
connection='strong', \
... | checks if T is 'ergodic'
Parameters
----------
T : scipy.sparse matrix
Transition matrix
tol : float
tolerance
Returns
-------
Truth value : bool
True, if # strongly connected components = 1
False, otherwise |
def spawn(opts, conf):
if opts.config is not None:
os.environ["CALLSIGN_CONFIG_FILE"] = opts.config
sys.argv[1:] = [
"-noy", sibpath(__file__, "callsign.tac"),
"--pidfile", conf['pidfile'],
"--logfile", conf['logfile'],
]
twistd.run() | Acts like twistd |
def find_bottleneck(F, A, B):
r
if F.nnz == 0:
raise PathwayError('no more pathways left: Flux matrix does not contain any positive entries')
F = F.tocoo()
n = F.shape[0]
"""Get exdges and corresponding flux values"""
val = F.data
row = F.row
col = F.col
"""Sort edges accor... | r"""Find dynamic bottleneck of flux network.
Parameters
----------
F : scipy.sparse matrix
The flux network
A : array_like
The set of starting states
B : array_like
The set of end states
Returns
-------
e : tuple of int
The edge corresponding to the dynamic ... |
def has_connection(graph, A, B):
r
for istart in A:
nodes = csgraph.breadth_first_order(graph, istart, directed=True, return_predecessors=False)
if has_path(nodes, A, B):
return True
return False | r"""Check if the given graph contains a path connecting A and B.
Parameters
----------
graph : scipy.sparse matrix
Adjacency matrix of the graph
A : array_like
The set of starting states
B : array_like
The set of end states
Returns
-------
hc : bool
True ... |
def has_path(nodes, A, B):
r
x1 = np.intersect1d(nodes, A).size > 0
x2 = np.intersect1d(nodes, B).size > 0
return x1 and x2 | r"""Test if nodes from a breadth_first_order search lead from A to
B.
Parameters
----------
nodes : array_like
Nodes from breadth_first_oder_seatch
A : array_like
The set of educt states
B : array_like
The set of product states
Returns
-------
has_path : boo... |
def pathway(F, A, B):
r
if F.nnz == 0:
raise PathwayError('no more pathways left: Flux matrix does not contain any positive entries')
b1, b2, F = find_bottleneck(F, A, B)
if np.any(A == b1):
wL = [b1, ]
elif np.any(B == b1):
raise PathwayError(("Roles of vertices b1 and b2 ar... | r"""Compute the dominant reaction-pathway.
Parameters
----------
F : (M, M) scipy.sparse matrix
The flux network (matrix of netflux values)
A : array_like
The set of starting states
B : array_like
The set of end states
Returns
-------
w : list
The domina... |
def capacity(F, path):
r
F = F.todok()
L = len(path)
currents = np.zeros(L - 1)
for l in range(L - 1):
i = path[l]
j = path[l + 1]
currents[l] = F[i, j]
return currents.min() | r"""Compute capacity (min. current) of path.
Paramters
---------
F : (M, M) scipy.sparse matrix
The flux network (matrix of netflux values)
path : list
Reaction path
Returns
-------
c : float
Capacity (min. current of path) |
def remove_path(F, path):
r
c = capacity(F, path)
F = F.todok()
L = len(path)
for l in range(L - 1):
i = path[l]
j = path[l + 1]
F[i, j] -= c
return F | r"""Remove capacity along a path from flux network.
Parameters
----------
F : (M, M) scipy.sparse matrix
The flux network (matrix of netflux values)
path : list
Reaction path
Returns
-------
F : (M, M) scipy.sparse matrix
The updated flux network |
def add_endstates(F, A, B):
r
"""Outgoing currents from A"""
F = F.tocsr()
outA = (F[A, :].sum(axis=1)).getA()[:, 0]
"""Incoming currents into B"""
F = F.tocsc()
inB = (F[:, B].sum(axis=0)).getA()[0, :]
F = F.tocoo()
M = F.shape[0]
data_old = F.data
row_old = F.row
co... | r"""Adds artifical end states replacing source and sink sets.
Parameters
----------
F : (M, M) scipy.sparse matrix
The flux network (matrix of netflux values)
A : array_like
The set of starting states
B : array_like
The set of end states
Returns
-------
F_new : ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.